1. Check existence of mb_string, mysql and xml extensions before installation.
[openemr.git] / phpmyadmin / libraries / Util.class.php
blobf19ec1260091e1258fbebea517ea04d4b4db117e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Hold the PMA_Util class
6 * @package PhpMyAdmin
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 require_once 'libraries/Template.class.php';
13 use PMA\Template;
15 /**
16 * Misc functions used all over the scripts.
18 * @package PhpMyAdmin
20 class PMA_Util
23 /**
24 * Detects which function to use for pow.
26 * @return string Function name.
28 public static function detectPow()
30 if (function_exists('bcpow')) {
31 // BCMath Arbitrary Precision Mathematics Function
32 return 'bcpow';
33 } elseif (function_exists('gmp_pow')) {
34 // GMP Function
35 return 'gmp_pow';
36 } else {
37 // PHP function
38 return 'pow';
42 /**
43 * Exponential expression / raise number into power
45 * @param string $base base to raise
46 * @param string $exp exponent to use
47 * @param string $use_function pow function to use, or false for auto-detect
49 * @return mixed string or float
51 public static function pow($base, $exp, $use_function = '')
53 static $pow_function = null;
55 if ($pow_function == null) {
56 $pow_function = self::detectPow();
59 if (! $use_function) {
60 if ($exp < 0) {
61 $use_function = 'pow';
62 } else {
63 $use_function = $pow_function;
67 if (($exp < 0) && ($use_function != 'pow')) {
68 return false;
71 switch ($use_function) {
72 case 'bcpow' :
73 // bcscale() needed for testing pow() with base values < 1
74 bcscale(10);
75 $pow = bcpow($base, $exp);
76 break;
77 case 'gmp_pow' :
78 $pow = gmp_strval(gmp_pow($base, $exp));
79 break;
80 case 'pow' :
81 $base = (float) $base;
82 $exp = (int) $exp;
83 $pow = pow($base, $exp);
84 break;
85 default:
86 $pow = $use_function($base, $exp);
89 return $pow;
92 /**
93 * Checks whether configuration value tells to show icons.
95 * @param string $value Configuration option name
97 * @return boolean Whether to show icons.
99 public static function showIcons($value)
101 return in_array($GLOBALS['cfg'][$value], array('icons', 'both'));
105 * Checks whether configuration value tells to show text.
107 * @param string $value Configuration option name
109 * @return boolean Whether to show text.
111 public static function showText($value)
113 return in_array($GLOBALS['cfg'][$value], array('text', 'both'));
117 * Returns an HTML IMG tag for a particular icon from a theme,
118 * which may be an actual file or an icon from a sprite.
119 * This function takes into account the ActionLinksMode
120 * configuration setting and wraps the image tag in a span tag.
122 * @param string $icon name of icon file
123 * @param string $alternate alternate text
124 * @param boolean $force_text whether to force alternate text to be displayed
125 * @param boolean $menu_icon whether this icon is for the menu bar or not
126 * @param string $control_param which directive controls the display
128 * @return string an html snippet
130 public static function getIcon(
131 $icon, $alternate = '', $force_text = false,
132 $menu_icon = false, $control_param = 'ActionLinksMode'
134 $include_icon = $include_text = false;
135 if (self::showIcons($control_param)) {
136 $include_icon = true;
138 if ($force_text
139 || self::showText($control_param)
141 $include_text = true;
143 // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
144 // we don't need a span
145 $button = $menu_icon ? '' : '<span class="nowrap">';
146 if ($include_icon) {
147 $button .= self::getImage($icon, $alternate);
149 if ($include_icon && $include_text) {
150 $button .= '&nbsp;';
152 if ($include_text) {
153 $button .= $alternate;
155 $button .= $menu_icon ? '' : '</span>';
157 return $button;
161 * Returns an HTML IMG tag for a particular image from a theme,
162 * which may be an actual file or an icon from a sprite
164 * @param string $image The name of the file to get
165 * @param string $alternate Used to set 'alt' and 'title' attributes
166 * of the image
167 * @param array $attributes An associative array of other attributes
169 * @return string an html IMG tag
171 public static function getImage($image, $alternate = '', $attributes = array())
173 static $sprites; // cached list of available sprites (if any)
174 if (defined('TESTSUITE')) {
175 // prevent caching in testsuite
176 unset($sprites);
179 $is_sprite = false;
180 $alternate = htmlspecialchars($alternate);
182 // If it's the first time this function is called
183 if (! isset($sprites)) {
184 // Try to load the list of sprites
185 $sprite_file = $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
186 if (is_readable($sprite_file)) {
187 include_once $sprite_file;
188 $sprites = PMA_sprites();
189 } else {
190 // No sprites are available for this theme
191 $sprites = array();
195 // Check if we have the requested image as a sprite
196 // and set $url accordingly
197 $class = str_replace(array('.gif','.png'), '', $image);
198 if (array_key_exists($class, $sprites)) {
199 $is_sprite = true;
200 $url = (defined('PMA_TEST_THEME') ? '../' : '') . 'themes/dot.gif';
201 } else {
202 $url = $GLOBALS['pmaThemeImage'] . $image;
205 // set class attribute
206 if ($is_sprite) {
207 if (isset($attributes['class'])) {
208 $attributes['class'] = "icon ic_$class " . $attributes['class'];
209 } else {
210 $attributes['class'] = "icon ic_$class";
214 // set all other attributes
215 $attr_str = '';
216 foreach ($attributes as $key => $value) {
217 if (! in_array($key, array('alt', 'title'))) {
218 $attr_str .= " $key=\"$value\"";
222 // override the alt attribute
223 if (isset($attributes['alt'])) {
224 $alt = $attributes['alt'];
225 } else {
226 $alt = $alternate;
229 // override the title attribute
230 if (isset($attributes['title'])) {
231 $title = $attributes['title'];
232 } else {
233 $title = $alternate;
236 // generate the IMG tag
237 $template = '<img src="%s" title="%s" alt="%s"%s />';
238 $retval = sprintf($template, $url, $title, $alt, $attr_str);
240 return $retval;
244 * Returns the formatted maximum size for an upload
246 * @param integer $max_upload_size the size
248 * @return string the message
250 * @access public
252 public static function getFormattedMaximumUploadSize($max_upload_size)
254 // I have to reduce the second parameter (sensitiveness) from 6 to 4
255 // to avoid weird results like 512 kKib
256 list($max_size, $max_unit) = self::formatByteDown($max_upload_size, 4);
257 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
261 * Generates a hidden field which should indicate to the browser
262 * the maximum size for upload
264 * @param integer $max_size the size
266 * @return string the INPUT field
268 * @access public
270 public static function generateHiddenMaxFileSize($max_size)
272 return '<input type="hidden" name="MAX_FILE_SIZE" value="'
273 . $max_size . '" />';
277 * Add slashes before "'" and "\" characters so a value containing them can
278 * be used in a sql comparison.
280 * @param string $a_string the string to slash
281 * @param bool $is_like whether the string will be used in a 'LIKE' clause
282 * (it then requires two more escaped sequences) or not
283 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
284 * (converts \n to \\n, \r to \\r)
285 * @param bool $php_code whether this function is used as part of the
286 * "Create PHP code" dialog
288 * @return string the slashed string
290 * @access public
292 public static function sqlAddSlashes(
293 $a_string = '', $is_like = false, $crlf = false, $php_code = false
295 if ($is_like) {
296 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
297 } else {
298 $a_string = str_replace('\\', '\\\\', $a_string);
301 if ($crlf) {
302 $a_string = strtr(
303 $a_string,
304 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
308 if ($php_code) {
309 $a_string = str_replace('\'', '\\\'', $a_string);
310 } else {
311 $a_string = str_replace('\'', '\\\'', $a_string);
314 return $a_string;
315 } // end of the 'sqlAddSlashes()' function
318 * Add slashes before "_" and "%" characters for using them in MySQL
319 * database, table and field names.
320 * Note: This function does not escape backslashes!
322 * @param string $name the string to escape
324 * @return string the escaped string
326 * @access public
328 public static function escapeMysqlWildcards($name)
330 return strtr($name, array('_' => '\\_', '%' => '\\%'));
331 } // end of the 'escapeMysqlWildcards()' function
334 * removes slashes before "_" and "%" characters
335 * Note: This function does not unescape backslashes!
337 * @param string $name the string to escape
339 * @return string the escaped string
341 * @access public
343 public static function unescapeMysqlWildcards($name)
345 return strtr($name, array('\\_' => '_', '\\%' => '%'));
346 } // end of the 'unescapeMysqlWildcards()' function
349 * removes quotes (',",`) from a quoted string
351 * checks if the string is quoted and removes this quotes
353 * @param string $quoted_string string to remove quotes from
354 * @param string $quote type of quote to remove
356 * @return string unqoted string
358 public static function unQuote($quoted_string, $quote = null)
360 $quotes = array();
362 if ($quote === null) {
363 $quotes[] = '`';
364 $quotes[] = '"';
365 $quotes[] = "'";
366 } else {
367 $quotes[] = $quote;
370 foreach ($quotes as $quote) {
371 if (/*overload*/mb_substr($quoted_string, 0, 1) === $quote
372 && /*overload*/mb_substr($quoted_string, -1, 1) === $quote
374 $unquoted_string = /*overload*/mb_substr($quoted_string, 1, -1);
375 // replace escaped quotes
376 $unquoted_string = str_replace(
377 $quote . $quote,
378 $quote,
379 $unquoted_string
381 return $unquoted_string;
385 return $quoted_string;
389 * format sql strings
391 * @param string $sqlQuery raw SQL string
392 * @param boolean $truncate truncate the query if it is too long
394 * @return string the formatted sql
396 * @global array $cfg the configuration array
398 * @access public
399 * @todo move into PMA_Sql
401 public static function formatSql($sqlQuery, $truncate = false)
403 global $cfg;
405 if ($truncate
406 && /*overload*/mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']
408 $sqlQuery = /*overload*/mb_substr(
409 $sqlQuery,
411 $cfg['MaxCharactersInDisplayedSQL']
412 ) . '[...]';
414 return '<code class="sql"><pre>' . "\n"
415 . htmlspecialchars($sqlQuery) . "\n"
416 . '</pre></code>';
417 } // end of the "formatSql()" function
420 * Displays a link to the documentation as an icon
422 * @param string $link documentation link
423 * @param string $target optional link target
425 * @return string the html link
427 * @access public
429 public static function showDocLink($link, $target = 'documentation')
431 return '<a href="' . $link . '" target="' . $target . '">'
432 . self::getImage('b_help.png', __('Documentation'))
433 . '</a>';
434 } // end of the 'showDocLink()' function
437 * Get a URL link to the official MySQL documentation
439 * @param string $link contains name of page/anchor that is being linked
440 * @param string $anchor anchor to page part
442 * @return string the URL link
444 * @access public
446 public static function getMySQLDocuURL($link, $anchor = '')
448 // Fixup for newly used names:
449 $link = str_replace('_', '-', /*overload*/mb_strtolower($link));
451 if (empty($link)) {
452 $link = 'index';
454 $mysql = '5.5';
455 $lang = 'en';
456 if (defined('PMA_MYSQL_INT_VERSION')) {
457 if (PMA_MYSQL_INT_VERSION >= 50700) {
458 $mysql = '5.7';
459 } else if (PMA_MYSQL_INT_VERSION >= 50600) {
460 $mysql = '5.6';
461 } else if (PMA_MYSQL_INT_VERSION >= 50500) {
462 $mysql = '5.5';
465 $url = 'http://dev.mysql.com/doc/refman/'
466 . $mysql . '/' . $lang . '/' . $link . '.html';
467 if (! empty($anchor)) {
468 $url .= '#' . $anchor;
471 return PMA_linkURL($url);
475 * Displays a link to the official MySQL documentation
477 * @param string $link contains name of page/anchor that is being linked
478 * @param bool $big_icon whether to use big icon (like in left frame)
479 * @param string $anchor anchor to page part
480 * @param bool $just_open whether only the opening <a> tag should be returned
482 * @return string the html link
484 * @access public
486 public static function showMySQLDocu(
487 $link, $big_icon = false, $anchor = '', $just_open = false
489 $url = self::getMySQLDocuURL($link, $anchor);
490 $open_link = '<a href="' . $url . '" target="mysql_doc">';
491 if ($just_open) {
492 return $open_link;
493 } elseif ($big_icon) {
494 return $open_link
495 . self::getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
496 } else {
497 return self::showDocLink($url, 'mysql_doc');
499 } // end of the 'showMySQLDocu()' function
502 * Returns link to documentation.
504 * @param string $page Page in documentation
505 * @param string $anchor Optional anchor in page
507 * @return string URL
509 public static function getDocuLink($page, $anchor = '')
511 /* Construct base URL */
512 $url = $page . '.html';
513 if (!empty($anchor)) {
514 $url .= '#' . $anchor;
517 /* Check if we have built local documentation */
518 if (defined('TESTSUITE')) {
519 /* Provide consistent URL for testsuite */
520 return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
521 } else if (file_exists('doc/html/index.html')) {
522 if (defined('PMA_SETUP')) {
523 return '../doc/html/' . $url;
524 } else {
525 return './doc/html/' . $url;
527 } else {
528 /* TODO: Should link to correct branch for released versions */
529 return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
534 * Displays a link to the phpMyAdmin documentation
536 * @param string $page Page in documentation
537 * @param string $anchor Optional anchor in page
539 * @return string the html link
541 * @access public
543 public static function showDocu($page, $anchor = '')
545 return self::showDocLink(self::getDocuLink($page, $anchor));
546 } // end of the 'showDocu()' function
549 * Displays a link to the PHP documentation
551 * @param string $target anchor in documentation
553 * @return string the html link
555 * @access public
557 public static function showPHPDocu($target)
559 $url = PMA_getPHPDocLink($target);
561 return self::showDocLink($url);
562 } // end of the 'showPHPDocu()' function
565 * Returns HTML code for a tooltip
567 * @param string $message the message for the tooltip
569 * @return string
571 * @access public
573 public static function showHint($message)
575 if ($GLOBALS['cfg']['ShowHint']) {
576 $classClause = ' class="pma_hint"';
577 } else {
578 $classClause = '';
580 return '<span' . $classClause . '>'
581 . self::getImage('b_help.png')
582 . '<span class="hide">' . $message . '</span>'
583 . '</span>';
587 * Displays a MySQL error message in the main panel when $exit is true.
588 * Returns the error message otherwise.
590 * @param string|bool $server_msg Server's error message.
591 * @param string $sql_query The SQL query that failed.
592 * @param bool $is_modify_link Whether to show a "modify" link or not.
593 * @param string $back_url URL for the "back" link (full path is
594 * not required).
595 * @param bool $exit Whether execution should be stopped or
596 * the error message should be returned.
598 * @return string
600 * @global string $table The current table.
601 * @global string $db The current database.
603 * @access public
605 public static function mysqlDie(
606 $server_msg = '', $sql_query = '',
607 $is_modify_link = true, $back_url = '', $exit = true
609 global $table, $db;
612 * Error message to be built.
613 * @var string $error_msg
615 $error_msg = '';
617 // Checking for any server errors.
618 if (empty($server_msg)) {
619 $server_msg = $GLOBALS['dbi']->getError();
622 // Finding the query that failed, if not specified.
623 if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
624 $sql_query = $GLOBALS['sql_query'];
626 $sql_query = trim($sql_query);
628 $errors = array();
629 if (! empty($sql_query)) {
631 * The lexer used for analysis.
632 * @var SqlParser\Lexer $lexer
634 $lexer = new SqlParser\Lexer($sql_query);
637 * The parser used for analysis.
638 * @var SqlParser\Parser $parser
640 $parser = new SqlParser\Parser($lexer->list);
643 * The errors found by the lexer and the parser.
644 * @var array $errors
646 $errors = SqlParser\Utils\Error::get(array($lexer, $parser));
649 if (empty($sql_query)) {
650 $formatted_sql = '';
651 } elseif (count($errors)) {
652 $formatted_sql = htmlspecialchars($sql_query);
653 } else {
654 $formatted_sql = self::formatSql($sql_query, true);
657 $error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';
659 // For security reasons, if the MySQL refuses the connection, the query
660 // is hidden so no details are revealed.
661 if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
663 // Static analysis errors.
664 if (!empty($errors)) {
665 $error_msg .= '<p><strong>' . __('Static analysis:')
666 . '</strong></p>';
667 $error_msg .= '<p>' . sprintf(
668 __('%d errors were found during analysis.'), count($errors)
669 ) . '</p>';
670 $error_msg .= '<p><ol>';
671 $error_msg .= implode(
672 SqlParser\Utils\Error::format(
673 $errors,
674 '<li>%2$s (near "%4$s" at position %5$d)</li>'
677 $error_msg .= '</ol></p>';
680 // Display the SQL query and link to MySQL documentation.
681 $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
682 $formattedSqlToLower = /*overload*/mb_strtolower($formatted_sql);
684 // TODO: Show documentation for all statement types.
685 if (/*overload*/mb_strstr($formattedSqlToLower, 'select')) {
686 // please show me help to the error on select
687 $error_msg .= self::showMySQLDocu('SELECT');
690 if ($is_modify_link) {
691 $_url_params = array(
692 'sql_query' => $sql_query,
693 'show_query' => 1,
695 if (/*overload*/mb_strlen($table)) {
696 $_url_params['db'] = $db;
697 $_url_params['table'] = $table;
698 $doedit_goto = '<a href="tbl_sql.php'
699 . PMA_URL_getCommon($_url_params) . '">';
700 } elseif (/*overload*/mb_strlen($db)) {
701 $_url_params['db'] = $db;
702 $doedit_goto = '<a href="db_sql.php'
703 . PMA_URL_getCommon($_url_params) . '">';
704 } else {
705 $doedit_goto = '<a href="server_sql.php'
706 . PMA_URL_getCommon($_url_params) . '">';
709 $error_msg .= $doedit_goto
710 . self::getIcon('b_edit.png', __('Edit'))
711 . '</a>';
714 $error_msg .= ' </p>' . "\n"
715 . '<p>' . "\n"
716 . $formatted_sql . "\n"
717 . '</p>' . "\n";
720 // Display server's error.
721 if (!empty($server_msg)) {
722 $server_msg = preg_replace(
723 "@((\015\012)|(\015)|(\012)){3,}@",
724 "\n\n",
725 $server_msg
728 // Adds a link to MySQL documentation.
729 $error_msg .= '<p>' . "\n"
730 . ' <strong>' . __('MySQL said: ') . '</strong>'
731 . self::showMySQLDocu('Error-messages-server')
732 . "\n"
733 . '</p>' . "\n";
735 // The error message will be displayed within a CODE segment.
736 // To preserve original formatting, but allow word-wrapping,
737 // a couple of replacements are done.
738 // All non-single blanks and TAB-characters are replaced with their
739 // HTML-counterpart
740 $server_msg = str_replace(
741 array(' ', "\t"),
742 array('&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'),
743 $server_msg
746 // Replace line breaks
747 $server_msg = nl2br($server_msg);
749 $error_msg .= '<code>' . $server_msg . '</code><br/>';
752 $error_msg .= '</div>';
753 $_SESSION['Import_message']['message'] = $error_msg;
755 if (!$exit) {
756 return $error_msg;
760 * If this is an AJAX request, there is no "Back" link and
761 * `PMA_Response()` is used to send the response.
763 if (!empty($GLOBALS['is_ajax_request'])) {
764 $response = PMA_Response::getInstance();
765 $response->isSuccess(false);
766 $response->addJSON('message', $error_msg);
767 exit;
770 if (!empty($back_url)) {
771 if (/*overload*/mb_strstr($back_url, '?')) {
772 $back_url .= '&amp;no_history=true';
773 } else {
774 $back_url .= '?no_history=true';
777 $_SESSION['Import_message']['go_back_url'] = $back_url;
779 $error_msg .= '<fieldset class="tblFooters">'
780 . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
781 . '</fieldset>' . "\n\n";
784 exit($error_msg);
788 * Check the correct row count
790 * @param string $db the db name
791 * @param array $table the table infos
793 * @return int $rowCount the possibly modified row count
796 private static function _checkRowCount($db, $table)
798 $rowCount = 0;
800 if ($table['Rows'] === null) {
801 // Do not check exact row count here,
802 // if row count is invalid possibly the table is defect
803 // and this would break the navigation panel;
804 // but we can check row count if this is a view or the
805 // information_schema database
806 // since PMA_Table::countRecords() returns a limited row count
807 // in this case.
809 // set this because PMA_Table::countRecords() can use it
810 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
812 if ($tbl_is_view || $GLOBALS['dbi']->isSystemSchema($db)) {
813 $rowCount = $GLOBALS['dbi']
814 ->getTable($db, $table['Name'])
815 ->countRecords();
818 return $rowCount;
822 * returns array with tables of given db with extended information and grouped
824 * @param string $db name of db
825 * @param string $tables name of tables
826 * @param integer $limit_offset list offset
827 * @param int|bool $limit_count max tables to return
829 * @return array (recursive) grouped table list
831 public static function getTableList(
832 $db, $tables = null, $limit_offset = 0, $limit_count = false
834 $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
836 if ($tables === null) {
837 $tables = $GLOBALS['dbi']->getTablesFull(
838 $db, '', false, null, $limit_offset, $limit_count
840 if ($GLOBALS['cfg']['NaturalOrder']) {
841 uksort($tables, 'strnatcasecmp');
845 if (count($tables) < 1) {
846 return $tables;
849 $default = array(
850 'Name' => '',
851 'Rows' => 0,
852 'Comment' => '',
853 'disp_name' => '',
856 $table_groups = array();
858 foreach ($tables as $table_name => $table) {
859 $table['Rows'] = self::_checkRowCount($db, $table);
861 // in $group we save the reference to the place in $table_groups
862 // where to store the table info
863 if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
864 && $sep && /*overload*/mb_strstr($table_name, $sep)
866 $parts = explode($sep, $table_name);
868 $group =& $table_groups;
869 $i = 0;
870 $group_name_full = '';
871 $parts_cnt = count($parts) - 1;
873 while (($i < $parts_cnt)
874 && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
876 $group_name = $parts[$i] . $sep;
877 $group_name_full .= $group_name;
879 if (! isset($group[$group_name])) {
880 $group[$group_name] = array();
881 $group[$group_name]['is' . $sep . 'group'] = true;
882 $group[$group_name]['tab' . $sep . 'count'] = 1;
883 $group[$group_name]['tab' . $sep . 'group']
884 = $group_name_full;
886 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
887 $table = $group[$group_name];
888 $group[$group_name] = array();
889 $group[$group_name][$group_name] = $table;
890 unset($table);
891 $group[$group_name]['is' . $sep . 'group'] = true;
892 $group[$group_name]['tab' . $sep . 'count'] = 1;
893 $group[$group_name]['tab' . $sep . 'group']
894 = $group_name_full;
896 } else {
897 $group[$group_name]['tab' . $sep . 'count']++;
900 $group =& $group[$group_name];
901 $i++;
904 } else {
905 if (! isset($table_groups[$table_name])) {
906 $table_groups[$table_name] = array();
908 $group =& $table_groups;
911 $table['disp_name'] = $table['Name'];
912 $group[$table_name] = array_merge($default, $table);
915 return $table_groups;
918 /* ----------------------- Set of misc functions ----------------------- */
921 * Adds backquotes on both sides of a database, table or field name.
922 * and escapes backquotes inside the name with another backquote
924 * example:
925 * <code>
926 * echo backquote('owner`s db'); // `owner``s db`
928 * </code>
930 * @param mixed $a_name the database, table or field name to "backquote"
931 * or array of it
932 * @param boolean $do_it a flag to bypass this function (used by dump
933 * functions)
935 * @return mixed the "backquoted" database, table or field name
937 * @access public
939 public static function backquote($a_name, $do_it = true)
941 if (is_array($a_name)) {
942 foreach ($a_name as &$data) {
943 $data = self::backquote($data, $do_it);
945 return $a_name;
948 if (! $do_it) {
949 if (!(SqlParser\Context::isKeyword($a_name) & SqlParser\Token::FLAG_KEYWORD_RESERVED)
951 return $a_name;
955 // '0' is also empty for php :-(
956 if (/*overload*/mb_strlen($a_name) && $a_name !== '*') {
957 return '`' . str_replace('`', '``', $a_name) . '`';
958 } else {
959 return $a_name;
961 } // end of the 'backquote()' function
964 * Adds backquotes on both sides of a database, table or field name.
965 * in compatibility mode
967 * example:
968 * <code>
969 * echo backquoteCompat('owner`s db'); // `owner``s db`
971 * </code>
973 * @param mixed $a_name the database, table or field name to
974 * "backquote" or array of it
975 * @param string $compatibility string compatibility mode (used by dump
976 * functions)
977 * @param boolean $do_it a flag to bypass this function (used by dump
978 * functions)
980 * @return mixed the "backquoted" database, table or field name
982 * @access public
984 public static function backquoteCompat(
985 $a_name, $compatibility = 'MSSQL', $do_it = true
987 if (is_array($a_name)) {
988 foreach ($a_name as &$data) {
989 $data = self::backquoteCompat($data, $compatibility, $do_it);
991 return $a_name;
994 if (! $do_it) {
995 if (!SqlParser\Context::isKeyword($a_name)) {
996 return $a_name;
1000 // @todo add more compatibility cases (ORACLE for example)
1001 switch ($compatibility) {
1002 case 'MSSQL':
1003 $quote = '"';
1004 break;
1005 default:
1006 $quote = "`";
1007 break;
1010 // '0' is also empty for php :-(
1011 if (/*overload*/mb_strlen($a_name) && $a_name !== '*') {
1012 return $quote . $a_name . $quote;
1013 } else {
1014 return $a_name;
1016 } // end of the 'backquoteCompat()' function
1019 * Defines the <CR><LF> value depending on the user OS.
1021 * @return string the <CR><LF> value to use
1023 * @access public
1025 public static function whichCrlf()
1027 // The 'PMA_USR_OS' constant is defined in "libraries/Config.class.php"
1028 // Win case
1029 if (PMA_USR_OS == 'Win') {
1030 $the_crlf = "\r\n";
1031 } else {
1032 // Others
1033 $the_crlf = "\n";
1036 return $the_crlf;
1037 } // end of the 'whichCrlf()' function
1040 * Prepare the message and the query
1041 * usually the message is the result of the query executed
1043 * @param PMA_Message|string $message the message to display
1044 * @param string $sql_query the query to display
1045 * @param string $type the type (level) of the message
1047 * @return string
1049 * @access public
1051 public static function getMessage(
1052 $message, $sql_query = null, $type = 'notice'
1054 global $cfg;
1055 $retval = '';
1057 if (null === $sql_query) {
1058 if (! empty($GLOBALS['display_query'])) {
1059 $sql_query = $GLOBALS['display_query'];
1060 } elseif (! empty($GLOBALS['unparsed_sql'])) {
1061 $sql_query = $GLOBALS['unparsed_sql'];
1062 } elseif (! empty($GLOBALS['sql_query'])) {
1063 $sql_query = $GLOBALS['sql_query'];
1064 } else {
1065 $sql_query = '';
1069 if (isset($GLOBALS['using_bookmark_message'])) {
1070 $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
1071 unset($GLOBALS['using_bookmark_message']);
1074 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1075 // check for it's presence before using it
1076 $retval .= '<div class="result_query"'
1077 . ( isset($GLOBALS['cell_align_left'])
1078 ? ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"'
1079 : '' )
1080 . '>' . "\n";
1082 if ($message instanceof PMA_Message) {
1083 if (isset($GLOBALS['special_message'])) {
1084 $message->addMessage($GLOBALS['special_message']);
1085 unset($GLOBALS['special_message']);
1087 $retval .= $message->getDisplay();
1088 } else {
1089 $retval .= '<div class="' . $type . '">';
1090 $retval .= PMA_sanitize($message);
1091 if (isset($GLOBALS['special_message'])) {
1092 $retval .= PMA_sanitize($GLOBALS['special_message']);
1093 unset($GLOBALS['special_message']);
1095 $retval .= '</div>';
1098 if ($cfg['ShowSQL'] == true && ! empty($sql_query) && $sql_query !== ';') {
1099 // Html format the query to be displayed
1100 // If we want to show some sql code it is easiest to create it here
1101 /* SQL-Parser-Analyzer */
1103 if (! empty($GLOBALS['show_as_php'])) {
1104 $new_line = '\\n"<br />' . "\n"
1105 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1106 $query_base = htmlspecialchars(addslashes($sql_query));
1107 $query_base = preg_replace(
1108 '/((\015\012)|(\015)|(\012))/', $new_line, $query_base
1110 } else {
1111 $query_base = $sql_query;
1114 $query_too_big = false;
1116 $queryLength = /*overload*/mb_strlen($query_base);
1117 if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) {
1118 // when the query is large (for example an INSERT of binary
1119 // data), the parser chokes; so avoid parsing the query
1120 $query_too_big = true;
1121 $shortened_query_base = nl2br(
1122 htmlspecialchars(
1123 /*overload*/mb_substr(
1124 $sql_query,
1126 $cfg['MaxCharactersInDisplayedSQL']
1127 ) . '[...]'
1132 if (! empty($GLOBALS['show_as_php'])) {
1133 $query_base = '$sql = "' . $query_base;
1134 } elseif (isset($query_base)) {
1135 $query_base = self::formatSql($query_base);
1138 // Prepares links that may be displayed to edit/explain the query
1139 // (don't go to default pages, we must go to the page
1140 // where the query box is available)
1142 // Basic url query part
1143 $url_params = array();
1144 if (! isset($GLOBALS['db'])) {
1145 $GLOBALS['db'] = '';
1147 if (/*overload*/mb_strlen($GLOBALS['db'])) {
1148 $url_params['db'] = $GLOBALS['db'];
1149 if (/*overload*/mb_strlen($GLOBALS['table'])) {
1150 $url_params['table'] = $GLOBALS['table'];
1151 $edit_link = 'tbl_sql.php';
1152 } else {
1153 $edit_link = 'db_sql.php';
1155 } else {
1156 $edit_link = 'server_sql.php';
1159 // Want to have the query explained
1160 // but only explain a SELECT (that has not been explained)
1161 /* SQL-Parser-Analyzer */
1162 $explain_link = '';
1163 $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
1164 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1165 $explain_params = $url_params;
1166 if ($is_select) {
1167 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1168 $explain_link = ' ['
1169 . self::linkOrButton(
1170 'import.php' . PMA_URL_getCommon($explain_params),
1171 __('Explain SQL')
1172 ) . ']';
1173 } elseif (preg_match(
1174 '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query
1175 )) {
1176 $explain_params['sql_query']
1177 = /*overload*/mb_substr($sql_query, 8);
1178 $explain_link = ' ['
1179 . self::linkOrButton(
1180 'import.php' . PMA_URL_getCommon($explain_params),
1181 __('Skip Explain SQL')
1182 ) . ']';
1183 $url = 'https://mariadb.org/explain_analyzer/analyze/'
1184 . '?client=phpMyAdmin&raw_explain='
1185 . urlencode(self::_generateRowQueryOutput($sql_query));
1186 $explain_link .= ' ['
1187 . self::linkOrButton(
1188 'url.php?url=' . urlencode($url),
1189 sprintf(__('Analyze Explain at %s'), 'mariadb.org'),
1190 array(),
1191 true,
1192 false,
1193 '_blank'
1194 ) . ']';
1196 } //show explain
1198 $url_params['sql_query'] = $sql_query;
1199 $url_params['show_query'] = 1;
1201 // even if the query is big and was truncated, offer the chance
1202 // to edit it (unless it's enormous, see linkOrButton() )
1203 if (! empty($cfg['SQLQuery']['Edit'])) {
1204 $edit_link .= PMA_URL_getCommon($url_params) . '#querybox';
1205 $edit_link = ' ['
1206 . self::linkOrButton(
1207 $edit_link, __('Edit')
1209 . ']';
1210 } else {
1211 $edit_link = '';
1214 // Also we would like to get the SQL formed in some nice
1215 // php-code
1216 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1217 $php_params = $url_params;
1219 if (! empty($GLOBALS['show_as_php'])) {
1220 $_message = __('Without PHP Code');
1221 } else {
1222 $php_params['show_as_php'] = 1;
1223 $_message = __('Create PHP code');
1226 $php_link = 'import.php' . PMA_URL_getCommon($php_params);
1227 $php_link = ' [' . self::linkOrButton($php_link, $_message) . ']';
1229 if (isset($GLOBALS['show_as_php'])) {
1231 $runquery_link = 'import.php'
1232 . PMA_URL_getCommon($url_params);
1234 $php_link .= ' ['
1235 . self::linkOrButton($runquery_link, __('Submit Query'))
1236 . ']';
1238 } else {
1239 $php_link = '';
1240 } //show as php
1242 // Refresh query
1243 if (! empty($cfg['SQLQuery']['Refresh'])
1244 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1245 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1247 $refresh_link = 'import.php' . PMA_URL_getCommon($url_params);
1248 $refresh_link = ' ['
1249 . self::linkOrButton($refresh_link, __('Refresh')) . ']';
1250 } else {
1251 $refresh_link = '';
1252 } //refresh
1254 $retval .= '<div class="sqlOuter">';
1255 if ($query_too_big) {
1256 $retval .= $shortened_query_base;
1257 } else {
1258 $retval .= $query_base;
1261 //Clean up the end of the PHP
1262 if (! empty($GLOBALS['show_as_php'])) {
1263 $retval .= '";';
1265 $retval .= '</div>';
1267 $retval .= '<div class="tools print_ignore">';
1268 $retval .= '<form action="sql.php" method="post">';
1269 $retval .= PMA_URL_getHiddenInputs(
1270 $GLOBALS['db'], $GLOBALS['table']
1272 $retval .= '<input type="hidden" name="sql_query" value="'
1273 . htmlspecialchars($sql_query) . '" />';
1275 // avoid displaying a Profiling checkbox that could
1276 // be checked, which would reexecute an INSERT, for example
1277 if (! empty($refresh_link) && self::profilingSupported()) {
1278 $retval .= '<input type="hidden" name="profiling_form" value="1" />';
1279 $retval .= self::getCheckbox(
1280 'profiling', __('Profiling'), isset($_SESSION['profiling']), true
1283 $retval .= '</form>';
1286 * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
1288 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1289 $inline_edit_link = ' ['
1290 . self::linkOrButton(
1291 '#',
1292 _pgettext('Inline edit query', 'Edit inline'),
1293 array('class' => 'inline_edit_sql')
1295 . ']';
1296 } else {
1297 $inline_edit_link = '';
1299 $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link
1300 . $refresh_link;
1301 $retval .= '</div>';
1304 $retval .= '</div>';
1305 if ($GLOBALS['is_ajax_request'] === false) {
1306 $retval .= '<br class="clearfloat" />';
1309 return $retval;
1310 } // end of the 'getMessage()' function
1313 * Execute an EXPLAIN query and formats results similar to MySQL command line
1314 * utility.
1316 * @param string $sqlQuery EXPLAIN query
1318 * @return string query resuls
1320 private static function _generateRowQueryOutput($sqlQuery)
1322 $ret = '';
1323 $result = $GLOBALS['dbi']->query($sqlQuery);
1324 if ($result) {
1325 $devider = '+';
1326 $columnNames = '|';
1327 $fieldsMeta = $GLOBALS['dbi']->getFieldsMeta($result);
1328 foreach ($fieldsMeta as $meta) {
1329 $devider .= '---+';
1330 $columnNames .= ' ' . $meta->name . ' |';
1332 $devider .= "\n";
1334 $ret .= $devider . $columnNames . "\n" . $devider;
1335 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
1336 $values = '|';
1337 foreach ($row as $value) {
1338 if (is_null($value)) {
1339 $value = 'NULL';
1341 $values .= ' ' . $value . ' |';
1343 $ret .= $values . "\n";
1345 $ret .= $devider;
1347 return $ret;
1351 * Verifies if current MySQL server supports profiling
1353 * @access public
1355 * @return boolean whether profiling is supported
1357 public static function profilingSupported()
1359 if (!self::cacheExists('profiling_supported')) {
1360 // 5.0.37 has profiling but for example, 5.1.20 does not
1361 // (avoid a trip to the server for MySQL before 5.0.37)
1362 // and do not set a constant as we might be switching servers
1363 if (defined('PMA_MYSQL_INT_VERSION')
1364 && $GLOBALS['dbi']->fetchValue("SELECT @@have_profiling")
1366 self::cacheSet('profiling_supported', true);
1367 } else {
1368 self::cacheSet('profiling_supported', false);
1372 return self::cacheGet('profiling_supported');
1376 * Formats $value to byte view
1378 * @param double|int $value the value to format
1379 * @param int $limes the sensitiveness
1380 * @param int $comma the number of decimals to retain
1382 * @return array the formatted value and its unit
1384 * @access public
1386 public static function formatByteDown($value, $limes = 6, $comma = 0)
1388 if ($value === null) {
1389 return null;
1392 $byteUnits = array(
1393 /* l10n: shortcuts for Byte */
1394 __('B'),
1395 /* l10n: shortcuts for Kilobyte */
1396 __('KiB'),
1397 /* l10n: shortcuts for Megabyte */
1398 __('MiB'),
1399 /* l10n: shortcuts for Gigabyte */
1400 __('GiB'),
1401 /* l10n: shortcuts for Terabyte */
1402 __('TiB'),
1403 /* l10n: shortcuts for Petabyte */
1404 __('PiB'),
1405 /* l10n: shortcuts for Exabyte */
1406 __('EiB')
1409 $dh = self::pow(10, $comma);
1410 $li = self::pow(10, $limes);
1411 $unit = $byteUnits[0];
1413 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1414 // cast to float to avoid overflow
1415 $unitSize = (float) $li * self::pow(10, $ex);
1416 if (isset($byteUnits[$d]) && $value >= $unitSize) {
1417 // use 1024.0 to avoid integer overflow on 64-bit machines
1418 $value = round($value / (self::pow(1024, $d) / $dh)) /$dh;
1419 $unit = $byteUnits[$d];
1420 break 1;
1421 } // end if
1422 } // end for
1424 if ($unit != $byteUnits[0]) {
1425 // if the unit is not bytes (as represented in current language)
1426 // reformat with max length of 5
1427 // 4th parameter=true means do not reformat if value < 1
1428 $return_value = self::formatNumber($value, 5, $comma, true);
1429 } else {
1430 // do not reformat, just handle the locale
1431 $return_value = self::formatNumber($value, 0);
1434 return array(trim($return_value), $unit);
1435 } // end of the 'formatByteDown' function
1438 * Changes thousands and decimal separators to locale specific values.
1440 * @param string $value the value
1442 * @return string
1444 public static function localizeNumber($value)
1446 return str_replace(
1447 array(',', '.'),
1448 array(
1449 /* l10n: Thousands separator */
1450 __(','),
1451 /* l10n: Decimal separator */
1452 __('.'),
1454 $value
1459 * Formats $value to the given length and appends SI prefixes
1460 * with a $length of 0 no truncation occurs, number is only formatted
1461 * to the current locale
1463 * examples:
1464 * <code>
1465 * echo formatNumber(123456789, 6); // 123,457 k
1466 * echo formatNumber(-123456789, 4, 2); // -123.46 M
1467 * echo formatNumber(-0.003, 6); // -3 m
1468 * echo formatNumber(0.003, 3, 3); // 0.003
1469 * echo formatNumber(0.00003, 3, 2); // 0.03 m
1470 * echo formatNumber(0, 6); // 0
1471 * </code>
1473 * @param double $value the value to format
1474 * @param integer $digits_left number of digits left of the comma
1475 * @param integer $digits_right number of digits right of the comma
1476 * @param boolean $only_down do not reformat numbers below 1
1477 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1478 * (default: true)
1480 * @return string the formatted value and its unit
1482 * @access public
1484 public static function formatNumber(
1485 $value, $digits_left = 3, $digits_right = 0,
1486 $only_down = false, $noTrailingZero = true
1488 if ($value == 0) {
1489 return '0';
1492 $originalValue = $value;
1493 //number_format is not multibyte safe, str_replace is safe
1494 if ($digits_left === 0) {
1495 $value = number_format($value, $digits_right);
1496 if (($originalValue != 0) && (floatval($value) == 0)) {
1497 $value = ' <' . (1 / self::pow(10, $digits_right));
1499 return self::localizeNumber($value);
1502 // this units needs no translation, ISO
1503 $units = array(
1504 -8 => 'y',
1505 -7 => 'z',
1506 -6 => 'a',
1507 -5 => 'f',
1508 -4 => 'p',
1509 -3 => 'n',
1510 -2 => '&micro;',
1511 -1 => 'm',
1512 0 => ' ',
1513 1 => 'k',
1514 2 => 'M',
1515 3 => 'G',
1516 4 => 'T',
1517 5 => 'P',
1518 6 => 'E',
1519 7 => 'Z',
1520 8 => 'Y'
1523 // check for negative value to retain sign
1524 if ($value < 0) {
1525 $sign = '-';
1526 $value = abs($value);
1527 } else {
1528 $sign = '';
1531 $dh = self::pow(10, $digits_right);
1534 * This gives us the right SI prefix already,
1535 * but $digits_left parameter not incorporated
1537 $d = floor(log10($value) / 3);
1539 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1540 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1541 * to use, then lower the SI prefix
1543 $cur_digits = floor(log10($value / self::pow(1000, $d, 'pow'))+1);
1544 if ($digits_left > $cur_digits) {
1545 $d -= floor(($digits_left - $cur_digits)/3);
1548 if ($d < 0 && $only_down) {
1549 $d = 0;
1552 $value = round($value / (self::pow(1000, $d, 'pow') / $dh)) /$dh;
1553 $unit = $units[$d];
1555 // If we don't want any zeros after the comma just add the thousand separator
1556 if ($noTrailingZero) {
1557 $localizedValue = self::localizeNumber(
1558 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1560 } else {
1561 //number_format is not multibyte safe, str_replace is safe
1562 $localizedValue = self::localizeNumber(
1563 number_format($value, $digits_right)
1567 if ($originalValue != 0 && floatval($value) == 0) {
1568 return ' <' . self::localizeNumber((1 / self::pow(10, $digits_right)))
1569 . ' ' . $unit;
1572 return $sign . $localizedValue . ' ' . $unit;
1573 } // end of the 'formatNumber' function
1576 * Returns the number of bytes when a formatted size is given
1578 * @param string $formatted_size the size expression (for example 8MB)
1580 * @return integer The numerical part of the expression (for example 8)
1582 public static function extractValueFromFormattedSize($formatted_size)
1584 $return_value = -1;
1586 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1587 $return_value = /*overload*/mb_substr($formatted_size, 0, -2)
1588 * self::pow(1024, 3);
1589 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1590 $return_value = /*overload*/mb_substr($formatted_size, 0, -2)
1591 * self::pow(1024, 2);
1592 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1593 $return_value = /*overload*/mb_substr($formatted_size, 0, -1)
1594 * self::pow(1024, 1);
1596 return $return_value;
1597 }// end of the 'extractValueFromFormattedSize' function
1600 * Writes localised date
1602 * @param integer $timestamp the current timestamp
1603 * @param string $format format
1605 * @return string the formatted date
1607 * @access public
1609 public static function localisedDate($timestamp = -1, $format = '')
1611 $month = array(
1612 /* l10n: Short month name */
1613 __('Jan'),
1614 /* l10n: Short month name */
1615 __('Feb'),
1616 /* l10n: Short month name */
1617 __('Mar'),
1618 /* l10n: Short month name */
1619 __('Apr'),
1620 /* l10n: Short month name */
1621 _pgettext('Short month name', 'May'),
1622 /* l10n: Short month name */
1623 __('Jun'),
1624 /* l10n: Short month name */
1625 __('Jul'),
1626 /* l10n: Short month name */
1627 __('Aug'),
1628 /* l10n: Short month name */
1629 __('Sep'),
1630 /* l10n: Short month name */
1631 __('Oct'),
1632 /* l10n: Short month name */
1633 __('Nov'),
1634 /* l10n: Short month name */
1635 __('Dec'));
1636 $day_of_week = array(
1637 /* l10n: Short week day name */
1638 _pgettext('Short week day name', 'Sun'),
1639 /* l10n: Short week day name */
1640 __('Mon'),
1641 /* l10n: Short week day name */
1642 __('Tue'),
1643 /* l10n: Short week day name */
1644 __('Wed'),
1645 /* l10n: Short week day name */
1646 __('Thu'),
1647 /* l10n: Short week day name */
1648 __('Fri'),
1649 /* l10n: Short week day name */
1650 __('Sat'));
1652 if ($format == '') {
1653 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1654 $format = __('%B %d, %Y at %I:%M %p');
1657 if ($timestamp == -1) {
1658 $timestamp = time();
1661 $date = preg_replace(
1662 '@%[aA]@',
1663 $day_of_week[(int)strftime('%w', $timestamp)],
1664 $format
1666 $date = preg_replace(
1667 '@%[bB]@',
1668 $month[(int)strftime('%m', $timestamp)-1],
1669 $date
1672 $ret = strftime($date, $timestamp);
1673 // Some OSes such as Win8.1 Traditional Chinese version did not produce UTF-8
1674 // output here. See https://sourceforge.net/p/phpmyadmin/bugs/4207/
1675 if (mb_detect_encoding($ret, 'UTF-8', true) != 'UTF-8') {
1676 $ret = date('Y-m-d H:i:s', $timestamp);
1679 return $ret;
1680 } // end of the 'localisedDate()' function
1683 * returns a tab for tabbed navigation.
1684 * If the variables $link and $args ar left empty, an inactive tab is created
1686 * @param array $tab array with all options
1687 * @param array $url_params tab specific URL parameters
1689 * @return string html code for one tab, a link if valid otherwise a span
1691 * @access public
1693 public static function getHtmlTab($tab, $url_params = array())
1695 // default values
1696 $defaults = array(
1697 'text' => '',
1698 'class' => '',
1699 'active' => null,
1700 'link' => '',
1701 'sep' => '?',
1702 'attr' => '',
1703 'args' => '',
1704 'warning' => '',
1705 'fragment' => '',
1706 'id' => '',
1709 $tab = array_merge($defaults, $tab);
1711 // determine additional style-class
1712 if (empty($tab['class'])) {
1713 if (! empty($tab['active'])
1714 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1716 $tab['class'] = 'active';
1717 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1718 && (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'])
1720 $tab['class'] = 'active';
1724 // If there are any tab specific URL parameters, merge those with
1725 // the general URL parameters
1726 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1727 $url_params = array_merge($url_params, $tab['url_params']);
1730 // build the link
1731 if (! empty($tab['link'])) {
1732 $tab['link'] = htmlentities($tab['link']);
1733 $tab['link'] = $tab['link'] . PMA_URL_getCommon($url_params);
1734 if (! empty($tab['args'])) {
1735 foreach ($tab['args'] as $param => $value) {
1736 $tab['link'] .= PMA_URL_getArgSeparator('html')
1737 . urlencode($param) . '=' . urlencode($value);
1742 if (! empty($tab['fragment'])) {
1743 $tab['link'] .= $tab['fragment'];
1746 // display icon
1747 if (isset($tab['icon'])) {
1748 // avoid generating an alt tag, because it only illustrates
1749 // the text that follows and if browser does not display
1750 // images, the text is duplicated
1751 $tab['text'] = self::getIcon(
1752 $tab['icon'],
1753 $tab['text'],
1754 false,
1755 true,
1756 'TabsMode'
1759 } elseif (empty($tab['text'])) {
1760 // check to not display an empty link-text
1761 $tab['text'] = '?';
1762 trigger_error(
1763 'empty linktext in function ' . __FUNCTION__ . '()',
1764 E_USER_NOTICE
1768 //Set the id for the tab, if set in the params
1769 $tabId = (empty($tab['id']) ? null : $tab['id']);
1771 $item = array();
1772 if (!empty($tab['link'])) {
1773 $item = array(
1774 'content' => $tab['text'],
1775 'url' => array(
1776 'href' => empty($tab['link']) ? null : $tab['link'],
1777 'id' => $tabId,
1778 'class' => 'tab' . htmlentities($tab['class']),
1781 } else {
1782 $item['content'] = '<span class="tab' . htmlentities($tab['class']) . '"'
1783 . $tabId . '>' . $tab['text'] . '</span>';
1786 $item['class'] = $tab['class'] == 'active' ? 'active' : '';
1788 return Template::get('list/item')
1789 ->render($item);
1790 } // end of the 'getHtmlTab()' function
1793 * returns html-code for a tab navigation
1795 * @param array $tabs one element per tab
1796 * @param array $url_params additional URL parameters
1797 * @param string $menu_id HTML id attribute for the menu container
1798 * @param bool $resizable whether to add a "resizable" class
1800 * @return string html-code for tab-navigation
1802 public static function getHtmlTabs($tabs, $url_params, $menu_id,
1803 $resizable = false
1805 $class = '';
1806 if ($resizable) {
1807 $class = ' class="resizable-menu"';
1810 $tab_navigation = '<div id="' . htmlentities($menu_id)
1811 . 'container" class="menucontainer">'
1812 . '<ul id="' . htmlentities($menu_id) . '" ' . $class . '>';
1814 foreach ($tabs as $tab) {
1815 $tab_navigation .= self::getHtmlTab($tab, $url_params);
1818 $tab_navigation .=
1819 '<div class="clearfloat"></div>'
1820 . '</ul>' . "\n"
1821 . '</div>' . "\n";
1823 return $tab_navigation;
1827 * Displays a link, or a button if the link's URL is too large, to
1828 * accommodate some browsers' limitations
1830 * @param string $url the URL
1831 * @param string $message the link message
1832 * @param mixed $tag_params string: js confirmation
1833 * array: additional tag params (f.e. style="")
1834 * @param boolean $new_form we set this to false when we are already in
1835 * a form, to avoid generating nested forms
1836 * @param boolean $strip_img whether to strip the image
1837 * @param string $target target
1839 * @return string the results to be echoed or saved in an array
1841 public static function linkOrButton(
1842 $url, $message, $tag_params = array(),
1843 $new_form = true, $strip_img = false, $target = ''
1845 $url_length = /*overload*/mb_strlen($url);
1846 // with this we should be able to catch case of image upload
1847 // into a (MEDIUM) BLOB; not worth generating even a form for these
1848 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1849 return '';
1852 if (! is_array($tag_params)) {
1853 $tmp = $tag_params;
1854 $tag_params = array();
1855 if (! empty($tmp)) {
1856 $tag_params['onclick'] = 'return confirmLink(this, \''
1857 . PMA_escapeJsString($tmp) . '\')';
1859 unset($tmp);
1861 if (! empty($target)) {
1862 $tag_params['target'] = htmlentities($target);
1865 $displayed_message = '';
1866 // Add text if not already added
1867 if (stristr($message, '<img')
1868 && (! $strip_img || ($GLOBALS['cfg']['ActionLinksMode'] == 'icons'))
1869 && (strip_tags($message) == $message)
1871 $displayed_message = '<span>'
1872 . htmlspecialchars(
1873 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1875 . '</span>';
1878 // Suhosin: Check that each query parameter is not above maximum
1879 $in_suhosin_limits = true;
1880 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1881 $suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length');
1882 if ($suhosin_get_MaxValueLength) {
1883 $query_parts = self::splitURLQuery($url);
1884 foreach ($query_parts as $query_pair) {
1885 if (strpos($query_pair, '=') === false) {
1886 continue;
1889 list(, $eachval) = explode('=', $query_pair);
1890 if (/*overload*/mb_strlen($eachval) > $suhosin_get_MaxValueLength
1892 $in_suhosin_limits = false;
1893 break;
1899 if (($url_length <= $GLOBALS['cfg']['LinkLengthLimit'])
1900 && $in_suhosin_limits
1902 $tag_params_strings = array();
1903 foreach ($tag_params as $par_name => $par_value) {
1904 // htmlspecialchars() only on non javascript
1905 $par_value = /*overload*/mb_substr($par_name, 0, 2) == 'on'
1906 ? $par_value
1907 : htmlspecialchars($par_value);
1908 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1911 // no whitespace within an <a> else Safari will make it part of the link
1912 $ret = "\n" . '<a href="' . $url . '" '
1913 . implode(' ', $tag_params_strings) . '>'
1914 . $message . $displayed_message . '</a>' . "\n";
1915 } else {
1916 // no spaces (line breaks) at all
1917 // or after the hidden fields
1918 // IE will display them all
1920 if (! isset($query_parts)) {
1921 $query_parts = self::splitURLQuery($url);
1923 $url_parts = parse_url($url);
1925 if ($new_form) {
1926 if ($target) {
1927 $target = ' target="' . $target . '"';
1929 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1930 . ' method="post"' . $target . ' style="display: inline;">';
1931 $subname_open = '';
1932 $subname_close = '';
1933 $submit_link = '#';
1934 } else {
1935 $query_parts[] = 'redirect=' . $url_parts['path'];
1936 if (empty($GLOBALS['subform_counter'])) {
1937 $GLOBALS['subform_counter'] = 0;
1939 $GLOBALS['subform_counter']++;
1940 $ret = '';
1941 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1942 $subname_close = ']';
1943 $submit_link = '#usesubform[' . $GLOBALS['subform_counter']
1944 . ']=1';
1947 foreach ($query_parts as $query_pair) {
1948 list($eachvar, $eachval) = explode('=', $query_pair);
1949 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1950 . $subname_close . '" value="'
1951 . htmlspecialchars(urldecode($eachval)) . '" />';
1952 } // end while
1954 if (empty($tag_params['class'])) {
1955 $tag_params['class'] = 'formLinkSubmit';
1956 } else {
1957 $tag_params['class'] .= ' formLinkSubmit';
1960 $tag_params_strings = array();
1961 foreach ($tag_params as $par_name => $par_value) {
1962 // htmlspecialchars() only on non javascript
1963 $par_value = /*overload*/mb_substr($par_name, 0, 2) == 'on'
1964 ? $par_value
1965 : htmlspecialchars($par_value);
1966 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1969 $ret .= "\n" . '<a href="' . $submit_link . '" '
1970 . implode(' ', $tag_params_strings) . '>'
1971 . $message . ' ' . $displayed_message . '</a>' . "\n";
1973 if ($new_form) {
1974 $ret .= '</form>';
1976 } // end if... else...
1978 return $ret;
1979 } // end of the 'linkOrButton()' function
1982 * Splits a URL string by parameter
1984 * @param string $url the URL
1986 * @return array the parameter/value pairs, for example [0] db=sakila
1988 public static function splitURLQuery($url)
1990 // decode encoded url separators
1991 $separator = PMA_URL_getArgSeparator();
1992 // on most places separator is still hard coded ...
1993 if ($separator !== '&') {
1994 // ... so always replace & with $separator
1995 $url = str_replace(htmlentities('&'), $separator, $url);
1996 $url = str_replace('&', $separator, $url);
1999 $url = str_replace(htmlentities($separator), $separator, $url);
2000 // end decode
2002 $url_parts = parse_url($url);
2004 if (! empty($url_parts['query'])) {
2005 return explode($separator, $url_parts['query']);
2006 } else {
2007 return array();
2012 * Returns a given timespan value in a readable format.
2014 * @param int $seconds the timespan
2016 * @return string the formatted value
2018 public static function timespanFormat($seconds)
2020 $days = floor($seconds / 86400);
2021 if ($days > 0) {
2022 $seconds -= $days * 86400;
2025 $hours = floor($seconds / 3600);
2026 if ($days > 0 || $hours > 0) {
2027 $seconds -= $hours * 3600;
2030 $minutes = floor($seconds / 60);
2031 if ($days > 0 || $hours > 0 || $minutes > 0) {
2032 $seconds -= $minutes * 60;
2035 return sprintf(
2036 __('%s days, %s hours, %s minutes and %s seconds'),
2037 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
2042 * Takes a string and outputs each character on a line for itself. Used
2043 * mainly for horizontalflipped display mode.
2044 * Takes care of special html-characters.
2045 * Fulfills https://sourceforge.net/p/phpmyadmin/feature-requests/164/
2047 * @param string $string The string
2048 * @param string $Separator The Separator (defaults to "<br />\n")
2050 * @access public
2051 * @todo add a multibyte safe function $GLOBALS['PMA_String']->split()
2053 * @return string The flipped string
2055 public static function flipstring($string, $Separator = "<br />\n")
2057 $format_string = '';
2058 $charbuff = false;
2060 for ($i = 0, $str_len = /*overload*/mb_strlen($string);
2061 $i < $str_len;
2062 $i++
2064 $char = $string{$i};
2065 $append = false;
2067 if ($char == '&') {
2068 $format_string .= $charbuff;
2069 $charbuff = $char;
2070 } elseif ($char == ';' && ! empty($charbuff)) {
2071 $format_string .= $charbuff . $char;
2072 $charbuff = false;
2073 $append = true;
2074 } elseif (! empty($charbuff)) {
2075 $charbuff .= $char;
2076 } else {
2077 $format_string .= $char;
2078 $append = true;
2081 // do not add separator after the last character
2082 if ($append && ($i != $str_len - 1)) {
2083 $format_string .= $Separator;
2087 return $format_string;
2091 * Function added to avoid path disclosures.
2092 * Called by each script that needs parameters, it displays
2093 * an error message and, by default, stops the execution.
2095 * Not sure we could use a strMissingParameter message here,
2096 * would have to check if the error message file is always available
2098 * @param string[] $params The names of the parameters needed by the calling
2099 * script
2100 * @param bool $request Whether to include this list in checking for
2101 * special params
2103 * @return void
2105 * @global boolean $checked_special flag whether any special variable
2106 * was required
2108 * @access public
2110 public static function checkParameters($params, $request = true)
2112 global $checked_special;
2114 if (! isset($checked_special)) {
2115 $checked_special = false;
2118 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2119 $found_error = false;
2120 $error_message = '';
2122 foreach ($params as $param) {
2123 if ($request && ($param != 'db') && ($param != 'table')) {
2124 $checked_special = true;
2127 if (! isset($GLOBALS[$param])) {
2128 $error_message .= $reported_script_name
2129 . ': ' . __('Missing parameter:') . ' '
2130 . $param
2131 . self::showDocu('faq', 'faqmissingparameters')
2132 . '<br />';
2133 $found_error = true;
2136 if ($found_error) {
2137 PMA_fatalError($error_message, null, false);
2139 } // end function
2142 * Function to generate unique condition for specified row.
2144 * @param resource $handle current query result
2145 * @param integer $fields_cnt number of fields
2146 * @param array $fields_meta meta information about fields
2147 * @param array $row current row
2148 * @param boolean $force_unique generate condition only on pk
2149 * or unique
2150 * @param string|boolean $restrict_to_table restrict the unique condition
2151 * to this table or false if
2152 * none
2153 * @param array $analyzed_sql_results the analyzed query
2155 * @access public
2157 * @return array the calculated condition and whether condition is unique
2159 public static function getUniqueCondition(
2160 $handle, $fields_cnt, $fields_meta, $row, $force_unique = false,
2161 $restrict_to_table = false, $analyzed_sql_results = null
2163 $primary_key = '';
2164 $unique_key = '';
2165 $nonprimary_condition = '';
2166 $preferred_condition = '';
2167 $primary_key_array = array();
2168 $unique_key_array = array();
2169 $nonprimary_condition_array = array();
2170 $condition_array = array();
2172 for ($i = 0; $i < $fields_cnt; ++$i) {
2174 $con_val = '';
2175 $field_flags = $GLOBALS['dbi']->fieldFlags($handle, $i);
2176 $meta = $fields_meta[$i];
2178 // do not use a column alias in a condition
2179 if (! isset($meta->orgname) || ! /*overload*/mb_strlen($meta->orgname)) {
2180 $meta->orgname = $meta->name;
2182 if (!empty($analyzed_sql_results['statement']->expr)) {
2183 foreach ($analyzed_sql_results['statement']->expr as $expr) {
2184 if ((empty($expr->alias)) || (empty($expr->column))) {
2185 continue;
2187 if (strcasecmp($meta->name, $expr->alias) == 0) {
2188 $meta->orgname = $expr->column;
2189 break;
2195 // Do not use a table alias in a condition.
2196 // Test case is:
2197 // select * from galerie x WHERE
2198 //(select count(*) from galerie y where y.datum=x.datum)>1
2200 // But orgtable is present only with mysqli extension so the
2201 // fix is only for mysqli.
2202 // Also, do not use the original table name if we are dealing with
2203 // a view because this view might be updatable.
2204 // (The isView() verification should not be costly in most cases
2205 // because there is some caching in the function).
2206 if (isset($meta->orgtable)
2207 && ($meta->table != $meta->orgtable)
2208 && ! $GLOBALS['dbi']->getTable($GLOBALS['db'], $meta->table)->isView()
2210 $meta->table = $meta->orgtable;
2213 // If this field is not from the table which the unique clause needs
2214 // to be restricted to.
2215 if ($restrict_to_table && $restrict_to_table != $meta->table) {
2216 continue;
2219 // to fix the bug where float fields (primary or not)
2220 // can't be matched because of the imprecision of
2221 // floating comparison, use CONCAT
2222 // (also, the syntax "CONCAT(field) IS NULL"
2223 // that we need on the next "if" will work)
2224 if ($meta->type == 'real') {
2225 $con_key = 'CONCAT(' . self::backquote($meta->table) . '.'
2226 . self::backquote($meta->orgname) . ')';
2227 } else {
2228 $con_key = self::backquote($meta->table) . '.'
2229 . self::backquote($meta->orgname);
2230 } // end if... else...
2231 $condition = ' ' . $con_key . ' ';
2233 if (! isset($row[$i]) || is_null($row[$i])) {
2234 $con_val = 'IS NULL';
2235 } else {
2236 // timestamp is numeric on some MySQL 4.1
2237 // for real we use CONCAT above and it should compare to string
2238 if ($meta->numeric
2239 && ($meta->type != 'timestamp')
2240 && ($meta->type != 'real')
2242 $con_val = '= ' . $row[$i];
2243 } elseif ((($meta->type == 'blob') || ($meta->type == 'string'))
2244 && stristr($field_flags, 'BINARY')
2245 && ! empty($row[$i])
2247 // hexify only if this is a true not empty BLOB or a BINARY
2249 // do not waste memory building a too big condition
2250 if (/*overload*/mb_strlen($row[$i]) < 1000) {
2251 // use a CAST if possible, to avoid problems
2252 // if the field contains wildcard characters % or _
2253 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2254 } else if ($fields_cnt == 1) {
2255 // when this blob is the only field present
2256 // try settling with length comparison
2257 $condition = ' CHAR_LENGTH(' . $con_key . ') ';
2258 $con_val = ' = ' . /*overload*/mb_strlen($row[$i]);
2259 } else {
2260 // this blob won't be part of the final condition
2261 $con_val = null;
2263 } elseif (in_array($meta->type, self::getGISDatatypes())
2264 && ! empty($row[$i])
2266 // do not build a too big condition
2267 if (/*overload*/mb_strlen($row[$i]) < 5000) {
2268 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2269 } else {
2270 $condition = '';
2272 } elseif ($meta->type == 'bit') {
2273 $con_val = "= b'"
2274 . self::printableBitValue($row[$i], $meta->length) . "'";
2275 } else {
2276 $con_val = '= \''
2277 . self::sqlAddSlashes($row[$i], false, true) . '\'';
2281 if ($con_val != null) {
2283 $condition .= $con_val . ' AND';
2285 if ($meta->primary_key > 0) {
2286 $primary_key .= $condition;
2287 $primary_key_array[$con_key] = $con_val;
2288 } elseif ($meta->unique_key > 0) {
2289 $unique_key .= $condition;
2290 $unique_key_array[$con_key] = $con_val;
2293 $nonprimary_condition .= $condition;
2294 $nonprimary_condition_array[$con_key] = $con_val;
2296 } // end for
2298 // Correction University of Virginia 19991216:
2299 // prefer primary or unique keys for condition,
2300 // but use conjunction of all values if no primary key
2301 $clause_is_unique = true;
2303 if ($primary_key) {
2304 $preferred_condition = $primary_key;
2305 $condition_array = $primary_key_array;
2307 } elseif ($unique_key) {
2308 $preferred_condition = $unique_key;
2309 $condition_array = $unique_key_array;
2311 } elseif (! $force_unique) {
2312 $preferred_condition = $nonprimary_condition;
2313 $condition_array = $nonprimary_condition_array;
2314 $clause_is_unique = false;
2317 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2318 return(array($where_clause, $clause_is_unique, $condition_array));
2319 } // end function
2322 * Generate a button or image tag
2324 * @param string $button_name name of button element
2325 * @param string $button_class class of button or image element
2326 * @param string $image_name name of image element
2327 * @param string $text text to display
2328 * @param string $image image to display
2329 * @param string $value value
2331 * @return string html content
2333 * @access public
2335 public static function getButtonOrImage(
2336 $button_name, $button_class, $image_name, $text, $image, $value = ''
2338 if ($value == '') {
2339 $value = $text;
2342 if ($GLOBALS['cfg']['ActionLinksMode'] == 'text') {
2343 return ' <input type="submit" name="' . $button_name . '"'
2344 . ' value="' . htmlspecialchars($value) . '"'
2345 . ' title="' . htmlspecialchars($text) . '" />' . "\n";
2348 /* Opera has trouble with <input type="image"> */
2349 /* IE (before version 9) has trouble with <button> */
2350 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
2351 return '<input type="image" name="' . $image_name
2352 . '" class="' . $button_class
2353 . '" value="' . htmlspecialchars($value)
2354 . '" title="' . htmlspecialchars($text)
2355 . '" src="' . $GLOBALS['pmaThemeImage'] . $image . '" />'
2356 . ($GLOBALS['cfg']['ActionLinksMode'] == 'both'
2357 ? '&nbsp;' . htmlspecialchars($text)
2358 : '') . "\n";
2359 } else {
2360 return '<button class="' . $button_class . '" type="submit"'
2361 . ' name="' . $button_name . '" value="' . htmlspecialchars($value)
2362 . '" title="' . htmlspecialchars($text) . '">' . "\n"
2363 . self::getIcon($image, $text)
2364 . '</button>' . "\n";
2366 } // end function
2369 * Generate a pagination selector for browsing resultsets
2371 * @param string $name The name for the request parameter
2372 * @param int $rows Number of rows in the pagination set
2373 * @param int $pageNow current page number
2374 * @param int $nbTotalPage number of total pages
2375 * @param int $showAll If the number of pages is lower than this
2376 * variable, no pages will be omitted in pagination
2377 * @param int $sliceStart How many rows at the beginning should always
2378 * be shown?
2379 * @param int $sliceEnd How many rows at the end should always be shown?
2380 * @param int $percent Percentage of calculation page offsets to hop to a
2381 * next page
2382 * @param int $range Near the current page, how many pages should
2383 * be considered "nearby" and displayed as well?
2384 * @param string $prompt The prompt to display (sometimes empty)
2386 * @return string
2388 * @access public
2390 public static function pageselector(
2391 $name, $rows, $pageNow = 1, $nbTotalPage = 1, $showAll = 200,
2392 $sliceStart = 5,
2393 $sliceEnd = 5, $percent = 20, $range = 10, $prompt = ''
2395 $increment = floor($nbTotalPage / $percent);
2396 $pageNowMinusRange = ($pageNow - $range);
2397 $pageNowPlusRange = ($pageNow + $range);
2399 $gotopage = $prompt . ' <select class="pageselector ajax"';
2401 $gotopage .= ' name="' . $name . '" >';
2402 if ($nbTotalPage < $showAll) {
2403 $pages = range(1, $nbTotalPage);
2404 } else {
2405 $pages = array();
2407 // Always show first X pages
2408 for ($i = 1; $i <= $sliceStart; $i++) {
2409 $pages[] = $i;
2412 // Always show last X pages
2413 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2414 $pages[] = $i;
2417 // Based on the number of results we add the specified
2418 // $percent percentage to each page number,
2419 // so that we have a representing page number every now and then to
2420 // immediately jump to specific pages.
2421 // As soon as we get near our currently chosen page ($pageNow -
2422 // $range), every page number will be shown.
2423 $i = $sliceStart;
2424 $x = $nbTotalPage - $sliceEnd;
2425 $met_boundary = false;
2427 while ($i <= $x) {
2428 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2429 // If our pageselector comes near the current page, we use 1
2430 // counter increments
2431 $i++;
2432 $met_boundary = true;
2433 } else {
2434 // We add the percentage increment to our current page to
2435 // hop to the next one in range
2436 $i += $increment;
2438 // Make sure that we do not cross our boundaries.
2439 if ($i > $pageNowMinusRange && ! $met_boundary) {
2440 $i = $pageNowMinusRange;
2444 if ($i > 0 && $i <= $x) {
2445 $pages[] = $i;
2450 Add page numbers with "geometrically increasing" distances.
2452 This helps me a lot when navigating through giant tables.
2454 Test case: table with 2.28 million sets, 76190 pages. Page of interest
2455 is between 72376 and 76190.
2456 Selecting page 72376.
2457 Now, old version enumerated only +/- 10 pages around 72376 and the
2458 percentage increment produced steps of about 3000.
2460 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2461 around the current page.
2463 $i = $pageNow;
2464 $dist = 1;
2465 while ($i < $x) {
2466 $dist = 2 * $dist;
2467 $i = $pageNow + $dist;
2468 if ($i > 0 && $i <= $x) {
2469 $pages[] = $i;
2473 $i = $pageNow;
2474 $dist = 1;
2475 while ($i > 0) {
2476 $dist = 2 * $dist;
2477 $i = $pageNow - $dist;
2478 if ($i > 0 && $i <= $x) {
2479 $pages[] = $i;
2483 // Since because of ellipsing of the current page some numbers may be
2484 // double, we unify our array:
2485 sort($pages);
2486 $pages = array_unique($pages);
2489 foreach ($pages as $i) {
2490 if ($i == $pageNow) {
2491 $selected = 'selected="selected" style="font-weight: bold"';
2492 } else {
2493 $selected = '';
2495 $gotopage .= ' <option ' . $selected
2496 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2499 $gotopage .= ' </select>';
2501 return $gotopage;
2502 } // end function
2505 * Prepare navigation for a list
2507 * @param int $count number of elements in the list
2508 * @param int $pos current position in the list
2509 * @param array $_url_params url parameters
2510 * @param string $script script name for form target
2511 * @param string $frame target frame
2512 * @param int $max_count maximum number of elements to display from
2513 * the list
2514 * @param string $name the name for the request parameter
2515 * @param string[] $classes additional classes for the container
2517 * @return string $list_navigator_html the html content
2519 * @access public
2521 * @todo use $pos from $_url_params
2523 public static function getListNavigator(
2524 $count, $pos, $_url_params, $script, $frame, $max_count, $name = 'pos',
2525 $classes = array()
2528 $class = $frame == 'frame_navigation' ? ' class="ajax"' : '';
2530 $list_navigator_html = '';
2532 if ($max_count < $count) {
2534 $classes[] = 'pageselector';
2535 $list_navigator_html .= '<div class="' . implode(' ', $classes) . '">';
2537 if ($frame != 'frame_navigation') {
2538 $list_navigator_html .= __('Page number:');
2541 // Move to the beginning or to the previous page
2542 if ($pos > 0) {
2543 $caption1 = ''; $caption2 = '';
2544 if (self::showIcons('TableNavigationLinksMode')) {
2545 $caption1 .= '&lt;&lt; ';
2546 $caption2 .= '&lt; ';
2548 if (self::showText('TableNavigationLinksMode')) {
2549 $caption1 .= _pgettext('First page', 'Begin');
2550 $caption2 .= _pgettext('Previous page', 'Previous');
2552 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2553 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2555 $_url_params[$name] = 0;
2556 $list_navigator_html .= '<a' . $class . $title1 . ' href="' . $script
2557 . PMA_URL_getCommon($_url_params) . '">' . $caption1
2558 . '</a>';
2560 $_url_params[$name] = $pos - $max_count;
2561 $list_navigator_html .= ' <a' . $class . $title2
2562 . ' href="' . $script . PMA_URL_getCommon($_url_params) . '">'
2563 . $caption2 . '</a>';
2566 $list_navigator_html .= '<form action="' . basename($script)
2567 . '" method="post">';
2569 $list_navigator_html .= PMA_URL_getHiddenInputs($_url_params);
2570 $list_navigator_html .= self::pageselector(
2571 $name,
2572 $max_count,
2573 floor(($pos + 1) / $max_count) + 1,
2574 ceil($count / $max_count)
2576 $list_navigator_html .= '</form>';
2578 if ($pos + $max_count < $count) {
2579 $caption3 = ''; $caption4 = '';
2580 if (self::showText('TableNavigationLinksMode')) {
2581 $caption3 .= _pgettext('Next page', 'Next');
2582 $caption4 .= _pgettext('Last page', 'End');
2584 if (self::showIcons('TableNavigationLinksMode')) {
2585 $caption3 .= ' &gt;';
2586 $caption4 .= ' &gt;&gt;';
2587 if (! self::showText('TableNavigationLinksMode')) {
2591 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2592 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2594 $_url_params[$name] = $pos + $max_count;
2595 $list_navigator_html .= '<a' . $class . $title3 . ' href="' . $script
2596 . PMA_URL_getCommon($_url_params) . '" >' . $caption3
2597 . '</a>';
2599 $_url_params[$name] = floor($count / $max_count) * $max_count;
2600 if ($_url_params[$name] == $count) {
2601 $_url_params[$name] = $count - $max_count;
2604 $list_navigator_html .= ' <a' . $class . $title4
2605 . ' href="' . $script . PMA_URL_getCommon($_url_params) . '" >'
2606 . $caption4 . '</a>';
2608 $list_navigator_html .= '</div>' . "\n";
2611 return $list_navigator_html;
2615 * replaces %u in given path with current user name
2617 * example:
2618 * <code>
2619 * $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2621 * </code>
2623 * @param string $dir with wildcard for user
2625 * @return string per user directory
2627 public static function userDir($dir)
2629 // add trailing slash
2630 if (/*overload*/mb_substr($dir, -1) != '/') {
2631 $dir .= '/';
2634 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2638 * returns html code for db link to default db page
2640 * @param string $database database
2642 * @return string html link to default db page
2644 public static function getDbLink($database = null)
2646 if (! /*overload*/mb_strlen($database)) {
2647 if (! /*overload*/mb_strlen($GLOBALS['db'])) {
2648 return '';
2650 $database = $GLOBALS['db'];
2651 } else {
2652 $database = self::unescapeMysqlWildcards($database);
2655 return '<a href="'
2656 . PMA_Util::getScriptNameForOption(
2657 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2659 . PMA_URL_getCommon(array('db' => $database)) . '" title="'
2660 . htmlspecialchars(
2661 sprintf(
2662 __('Jump to database "%s".'),
2663 $database
2666 . '">' . htmlspecialchars($database) . '</a>';
2670 * Prepare a lightbulb hint explaining a known external bug
2671 * that affects a functionality
2673 * @param string $functionality localized message explaining the func.
2674 * @param string $component 'mysql' (eventually, 'php')
2675 * @param string $minimum_version of this component
2676 * @param string $bugref bug reference for this component
2678 * @return String
2680 public static function getExternalBug(
2681 $functionality, $component, $minimum_version, $bugref
2683 $ext_but_html = '';
2684 if (($component == 'mysql') && (PMA_MYSQL_INT_VERSION < $minimum_version)) {
2685 $ext_but_html .= self::showHint(
2686 sprintf(
2687 __('The %s functionality is affected by a known bug, see %s'),
2688 $functionality,
2689 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2693 return $ext_but_html;
2697 * Returns a HTML checkbox
2699 * @param string $html_field_name the checkbox HTML field
2700 * @param string $label label for checkbox
2701 * @param boolean $checked is it initially checked?
2702 * @param boolean $onclick should it submit the form on click?
2703 * @param string $html_field_id id for the checkbox
2705 * @return string HTML for the checkbox
2707 public static function getCheckbox(
2708 $html_field_name, $label, $checked, $onclick, $html_field_id = ''
2710 return '<input type="checkbox" name="' . $html_field_name . '"'
2711 . ($html_field_id ? ' id="' . $html_field_id . '"' : '')
2712 . ($checked ? ' checked="checked"' : '')
2713 . ($onclick ? ' class="autosubmit"' : '') . ' />'
2714 . '<label' . ($html_field_id ? ' for="' . $html_field_id . '"' : '')
2715 . '>' . $label . '</label>';
2719 * Generates a set of radio HTML fields
2721 * @param string $html_field_name the radio HTML field
2722 * @param array $choices the choices values and labels
2723 * @param string $checked_choice the choice to check by default
2724 * @param boolean $line_break whether to add HTML line break after a choice
2725 * @param boolean $escape_label whether to use htmlspecialchars() on label
2726 * @param string $class enclose each choice with a div of this class
2727 * @param string $id_prefix prefix for the id attribute, name will be
2728 * used if this is not supplied
2730 * @return string set of html radio fiels
2732 public static function getRadioFields(
2733 $html_field_name, $choices, $checked_choice = '',
2734 $line_break = true, $escape_label = true, $class = '',
2735 $id_prefix = ''
2737 $radio_html = '';
2739 foreach ($choices as $choice_value => $choice_label) {
2741 if (! empty($class)) {
2742 $radio_html .= '<div class="' . $class . '">';
2745 if (! $id_prefix) {
2746 $id_prefix = $html_field_name;
2748 $html_field_id = $id_prefix . '_' . $choice_value;
2749 $radio_html .= '<input type="radio" name="' . $html_field_name . '" id="'
2750 . $html_field_id . '" value="'
2751 . htmlspecialchars($choice_value) . '"';
2753 if ($choice_value == $checked_choice) {
2754 $radio_html .= ' checked="checked"';
2757 $radio_html .= ' />' . "\n"
2758 . '<label for="' . $html_field_id . '">'
2759 . ($escape_label
2760 ? htmlspecialchars($choice_label)
2761 : $choice_label)
2762 . '</label>';
2764 if ($line_break) {
2765 $radio_html .= '<br />';
2768 if (! empty($class)) {
2769 $radio_html .= '</div>';
2771 $radio_html .= "\n";
2774 return $radio_html;
2778 * Generates and returns an HTML dropdown
2780 * @param string $select_name name for the select element
2781 * @param array $choices choices values
2782 * @param string $active_choice the choice to select by default
2783 * @param string $id id of the select element; can be different in
2784 * case the dropdown is present more than once
2785 * on the page
2786 * @param string $class class for the select element
2787 * @param string $placeholder Placeholder for dropdown if nothing else
2788 * is selected
2790 * @return string html content
2792 * @todo support titles
2794 public static function getDropdown(
2795 $select_name, $choices, $active_choice, $id, $class = '', $placeholder = null
2797 $result = '<select'
2798 . ' name="' . htmlspecialchars($select_name) . '"'
2799 . ' id="' . htmlspecialchars($id) . '"'
2800 . (! empty($class) ? ' class="' . htmlspecialchars($class) . '"' : '')
2801 . '>';
2803 $resultOptions = '';
2804 $selected = false;
2806 foreach ($choices as $one_choice_value => $one_choice_label) {
2807 $resultOptions .= '<option value="'
2808 . htmlspecialchars($one_choice_value) . '"';
2810 if ($one_choice_value == $active_choice) {
2811 $resultOptions .= ' selected="selected"';
2812 $selected = true;
2814 $resultOptions .= '>' . htmlspecialchars($one_choice_label)
2815 . '</option>';
2818 if (!empty($placeholder)) {
2819 $resultOptions = '<option value="" disabled="disabled"'
2820 . ( !$selected ? ' selected="selected"' : '' )
2821 . '>' . $placeholder . '</option>'
2822 . $resultOptions;
2825 $result .= $resultOptions
2826 . '</select>';
2828 return $result;
2832 * Generates a slider effect (jQjuery)
2833 * Takes care of generating the initial <div> and the link
2834 * controlling the slider; you have to generate the </div> yourself
2835 * after the sliding section.
2837 * @param string $id the id of the <div> on which to apply the effect
2838 * @param string $message the message to show as a link
2840 * @return string html div element
2843 public static function getDivForSliderEffect($id = '', $message = '')
2845 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2846 return '<div' . ($id ? ' id="' . $id . '"' : '') . '>';
2849 * Bad hack on the next line. document.write() conflicts with jQuery,
2850 * hence, opening the <div> with PHP itself instead of JavaScript.
2852 * @todo find a better solution that uses $.append(), the recommended
2853 * method maybe by using an additional param, the id of the div to
2854 * append to
2857 return '<div'
2858 . ($id ? ' id="' . $id . '"' : '')
2859 . (($GLOBALS['cfg']['InitialSlidersState'] == 'closed')
2860 ? ' style="display: none; overflow:auto;"'
2861 : '')
2862 . ' class="pma_auto_slider"'
2863 . ($message ? ' title="' . htmlspecialchars($message) . '"' : '')
2864 . '>';
2868 * Creates an AJAX sliding toggle button
2869 * (or and equivalent form when AJAX is disabled)
2871 * @param string $action The URL for the request to be executed
2872 * @param string $select_name The name for the dropdown box
2873 * @param array $options An array of options (see rte_footer.lib.php)
2874 * @param string $callback A JS snippet to execute when the request is
2875 * successfully processed
2877 * @return string HTML code for the toggle button
2879 public static function toggleButton($action, $select_name, $options, $callback)
2881 // Do the logic first
2882 $link = "$action&amp;" . urlencode($select_name) . "=";
2883 $link_on = $link . urlencode($options[1]['value']);
2884 $link_off = $link . urlencode($options[0]['value']);
2886 if ($options[1]['selected'] == true) {
2887 $state = 'on';
2888 } else if ($options[0]['selected'] == true) {
2889 $state = 'off';
2890 } else {
2891 $state = 'on';
2894 // Generate output
2895 return "<!-- TOGGLE START -->\n"
2896 . "<div class='wrapper toggleAjax hide'>\n"
2897 . " <div class='toggleButton'>\n"
2898 . " <div title='" . __('Click to toggle')
2899 . "' class='container $state'>\n"
2900 . " <img src='" . htmlspecialchars($GLOBALS['pmaThemeImage'])
2901 . "toggle-" . htmlspecialchars($GLOBALS['text_dir']) . ".png'\n"
2902 . " alt='' />\n"
2903 . " <table class='nospacing nopadding'>\n"
2904 . " <tbody>\n"
2905 . " <tr>\n"
2906 . " <td class='toggleOn'>\n"
2907 . " <span class='hide'>$link_on</span>\n"
2908 . " <div>"
2909 . str_replace(' ', '&nbsp;', htmlspecialchars($options[1]['label']))
2910 . "\n" . " </div>\n"
2911 . " </td>\n"
2912 . " <td><div>&nbsp;</div></td>\n"
2913 . " <td class='toggleOff'>\n"
2914 . " <span class='hide'>$link_off</span>\n"
2915 . " <div>"
2916 . str_replace(' ', '&nbsp;', htmlspecialchars($options[0]['label']))
2917 . "\n" . " </div>\n"
2918 . " </tr>\n"
2919 . " </tbody>\n"
2920 . " </table>\n"
2921 . " <span class='hide callback'>"
2922 . htmlspecialchars($callback) . "</span>\n"
2923 . " <span class='hide text_direction'>"
2924 . htmlspecialchars($GLOBALS['text_dir']) . "</span>\n"
2925 . " </div>\n"
2926 . " </div>\n"
2927 . "</div>\n"
2928 . "<!-- TOGGLE END -->";
2930 } // end toggleButton()
2933 * Clears cache content which needs to be refreshed on user change.
2935 * @return void
2937 public static function clearUserCache()
2939 self::cacheUnset('is_superuser');
2940 self::cacheUnset('is_createuser');
2941 self::cacheUnset('is_grantuser');
2945 * Verifies if something is cached in the session
2947 * @param string $var variable name
2949 * @return boolean
2951 public static function cacheExists($var)
2953 return isset($_SESSION['cache']['server_' . $GLOBALS['server']][$var]);
2957 * Gets cached information from the session
2959 * @param string $var variable name
2960 * @param Closure $callback callback to fetch the value
2962 * @return mixed
2964 public static function cacheGet($var, $callback = null)
2966 if (self::cacheExists($var)) {
2967 return $_SESSION['cache']['server_' . $GLOBALS['server']][$var];
2968 } else {
2969 if ($callback) {
2970 $val = $callback();
2971 self::cacheSet($var, $val);
2972 return $val;
2974 return null;
2979 * Caches information in the session
2981 * @param string $var variable name
2982 * @param mixed $val value
2984 * @return mixed
2986 public static function cacheSet($var, $val = null)
2988 $_SESSION['cache']['server_' . $GLOBALS['server']][$var] = $val;
2992 * Removes cached information from the session
2994 * @param string $var variable name
2996 * @return void
2998 public static function cacheUnset($var)
3000 unset($_SESSION['cache']['server_' . $GLOBALS['server']][$var]);
3004 * Converts a bit value to printable format;
3005 * in MySQL a BIT field can be from 1 to 64 bits so we need this
3006 * function because in PHP, decbin() supports only 32 bits
3007 * on 32-bit servers
3009 * @param number $value coming from a BIT field
3010 * @param integer $length length
3012 * @return string the printable value
3014 public static function printableBitValue($value, $length)
3016 // if running on a 64-bit server or the length is safe for decbin()
3017 if (PHP_INT_SIZE == 8 || $length < 33) {
3018 $printable = decbin($value);
3019 } else {
3020 // FIXME: does not work for the leftmost bit of a 64-bit value
3021 $i = 0;
3022 $printable = '';
3023 while ($value >= pow(2, $i)) {
3024 $i++;
3026 if ($i != 0) {
3027 $i = $i - 1;
3030 while ($i >= 0) {
3031 if ($value - pow(2, $i) < 0) {
3032 $printable = '0' . $printable;
3033 } else {
3034 $printable = '1' . $printable;
3035 $value = $value - pow(2, $i);
3037 $i--;
3039 $printable = strrev($printable);
3041 $printable = str_pad($printable, $length, '0', STR_PAD_LEFT);
3042 return $printable;
3046 * Verifies whether the value contains a non-printable character
3048 * @param string $value value
3050 * @return integer
3052 public static function containsNonPrintableAscii($value)
3054 return preg_match('@[^[:print:]]@', $value);
3058 * Converts a BIT type default value
3059 * for example, b'010' becomes 010
3061 * @param string $bit_default_value value
3063 * @return string the converted value
3065 public static function convertBitDefaultValue($bit_default_value)
3067 return rtrim(ltrim($bit_default_value, "b'"), "'");
3071 * Extracts the various parts from a column spec
3073 * @param string $columnspec Column specification
3075 * @return array associative array containing type, spec_in_brackets
3076 * and possibly enum_set_values (another array)
3078 public static function extractColumnSpec($columnspec)
3080 $first_bracket_pos = /*overload*/mb_strpos($columnspec, '(');
3081 if ($first_bracket_pos) {
3082 $spec_in_brackets = chop(
3083 /*overload*/mb_substr(
3084 $columnspec,
3085 $first_bracket_pos + 1,
3086 /*overload*/mb_strrpos($columnspec, ')') - $first_bracket_pos - 1
3089 // convert to lowercase just to be sure
3090 $type = /*overload*/mb_strtolower(
3091 chop(/*overload*/mb_substr($columnspec, 0, $first_bracket_pos))
3093 } else {
3094 // Split trailing attributes such as unsigned,
3095 // binary, zerofill and get data type name
3096 $type_parts = explode(' ', $columnspec);
3097 $type = /*overload*/mb_strtolower($type_parts[0]);
3098 $spec_in_brackets = '';
3101 if ('enum' == $type || 'set' == $type) {
3102 // Define our working vars
3103 $enum_set_values = self::parseEnumSetValues($columnspec, false);
3104 $printtype = $type
3105 . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
3106 $binary = false;
3107 $unsigned = false;
3108 $zerofill = false;
3109 } else {
3110 $enum_set_values = array();
3112 /* Create printable type name */
3113 $printtype = /*overload*/mb_strtolower($columnspec);
3115 // Strip the "BINARY" attribute, except if we find "BINARY(" because
3116 // this would be a BINARY or VARBINARY column type;
3117 // by the way, a BLOB should not show the BINARY attribute
3118 // because this is not accepted in MySQL syntax.
3119 if (preg_match('@binary@', $printtype)
3120 && ! preg_match('@binary[\(]@', $printtype)
3122 $printtype = preg_replace('@binary@', '', $printtype);
3123 $binary = true;
3124 } else {
3125 $binary = false;
3128 $printtype = preg_replace(
3129 '@zerofill@', '', $printtype, -1, $zerofill_cnt
3131 $zerofill = ($zerofill_cnt > 0);
3132 $printtype = preg_replace(
3133 '@unsigned@', '', $printtype, -1, $unsigned_cnt
3135 $unsigned = ($unsigned_cnt > 0);
3136 $printtype = trim($printtype);
3139 $attribute = ' ';
3140 if ($binary) {
3141 $attribute = 'BINARY';
3143 if ($unsigned) {
3144 $attribute = 'UNSIGNED';
3146 if ($zerofill) {
3147 $attribute = 'UNSIGNED ZEROFILL';
3150 $can_contain_collation = false;
3151 if (! $binary
3152 && preg_match(
3153 "@^(char|varchar|text|tinytext|mediumtext|longtext|set|enum)@", $type
3156 $can_contain_collation = true;
3159 // for the case ENUM('&#8211;','&ldquo;')
3160 $displayed_type = htmlspecialchars($printtype);
3161 if (/*overload*/mb_strlen($printtype) > $GLOBALS['cfg']['LimitChars']) {
3162 $displayed_type = '<abbr title="' . htmlspecialchars($printtype) . '">';
3163 $displayed_type .= htmlspecialchars(
3164 /*overload*/mb_substr(
3165 $printtype, 0, $GLOBALS['cfg']['LimitChars']
3166 ) . '...'
3168 $displayed_type .= '</abbr>';
3171 return array(
3172 'type' => $type,
3173 'spec_in_brackets' => $spec_in_brackets,
3174 'enum_set_values' => $enum_set_values,
3175 'print_type' => $printtype,
3176 'binary' => $binary,
3177 'unsigned' => $unsigned,
3178 'zerofill' => $zerofill,
3179 'attribute' => $attribute,
3180 'can_contain_collation' => $can_contain_collation,
3181 'displayed_type' => $displayed_type
3186 * Verifies if this table's engine supports foreign keys
3188 * @param string $engine engine
3190 * @return boolean
3192 public static function isForeignKeySupported($engine)
3194 $engine = strtoupper($engine);
3195 if (($engine == 'INNODB') || ($engine == 'PBXT')) {
3196 return true;
3197 } elseif ($engine == 'NDBCLUSTER' || $engine == 'NDB') {
3198 $ndbver = $GLOBALS['dbi']->fetchValue("SELECT @@ndb_version_string");
3199 return ($ndbver >= 7.3);
3200 } else {
3201 return false;
3206 * Is Foreign key check enabled?
3208 * @return bool
3210 public static function isForeignKeyCheck()
3212 if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'enable') {
3213 return true;
3214 } else if ($GLOBALS['cfg']['DefaultForeignKeyChecks'] === 'disable') {
3215 return false;
3217 return ($GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON');
3221 * Get HTML for Foreign key check checkbox
3223 * @return string HTML for checkbox
3225 public static function getFKCheckbox()
3227 $checked = self::isForeignKeyCheck();
3228 $html = '<input type="hidden" name="fk_checks" value="0" />';
3229 $html .= '<input type="checkbox" name="fk_checks"'
3230 . ' id="fk_checks" value="1"'
3231 . ($checked ? ' checked="checked"' : '') . '/>';
3232 $html .= '<label for="fk_checks">' . __('Enable foreign key checks')
3233 . '</label>';
3234 return $html;
3238 * Handle foreign key check request
3240 * @return bool Default foreign key checks value
3242 public static function handleDisableFKCheckInit()
3244 $default_fk_check_value
3245 = $GLOBALS['dbi']->getVariable('FOREIGN_KEY_CHECKS') == 'ON';
3246 if (isset($_REQUEST['fk_checks'])) {
3247 if (empty($_REQUEST['fk_checks'])) {
3248 // Disable foreign key checks
3249 $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'OFF');
3250 } else {
3251 // Enable foreign key checks
3252 $GLOBALS['dbi']->setVariable('FOREIGN_KEY_CHECKS', 'ON');
3254 } // else do nothing, go with default
3255 return $default_fk_check_value;
3259 * Cleanup changes done for foreign key check
3261 * @param bool $default_fk_check_value original value for 'FOREIGN_KEY_CHECKS'
3263 * @return void
3265 public static function handleDisableFKCheckCleanup($default_fk_check_value)
3267 $GLOBALS['dbi']->setVariable(
3268 'FOREIGN_KEY_CHECKS', $default_fk_check_value ? 'ON' : 'OFF'
3273 * Replaces some characters by a displayable equivalent
3275 * @param string $content content
3277 * @return string the content with characters replaced
3279 public static function replaceBinaryContents($content)
3281 $result = str_replace("\x00", '\0', $content);
3282 $result = str_replace("\x08", '\b', $result);
3283 $result = str_replace("\x0a", '\n', $result);
3284 $result = str_replace("\x0d", '\r', $result);
3285 $result = str_replace("\x1a", '\Z', $result);
3286 return $result;
3290 * Converts GIS data to Well Known Text format
3292 * @param string $data GIS data
3293 * @param bool $includeSRID Add SRID to the WKT
3295 * @return string GIS data in Well Know Text format
3297 public static function asWKT($data, $includeSRID = false)
3299 // Convert to WKT format
3300 $hex = bin2hex($data);
3301 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3302 if ($includeSRID) {
3303 $wktsql .= ", SRID(x'" . $hex . "')";
3306 $wktresult = $GLOBALS['dbi']->tryQuery(
3307 $wktsql, null, PMA_DatabaseInterface::QUERY_STORE
3309 $wktarr = $GLOBALS['dbi']->fetchRow($wktresult, 0);
3310 $wktval = $wktarr[0];
3312 if ($includeSRID) {
3313 $srid = $wktarr[1];
3314 $wktval = "'" . $wktval . "'," . $srid;
3316 @$GLOBALS['dbi']->freeResult($wktresult);
3318 return $wktval;
3322 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3324 * @param string $string string
3326 * @return string with the chars replaced
3328 public static function duplicateFirstNewline($string)
3330 $first_occurence = /*overload*/mb_strpos($string, "\r\n");
3331 if ($first_occurence === 0) {
3332 $string = "\n" . $string;
3334 return $string;
3338 * Get the action word corresponding to a script name
3339 * in order to display it as a title in navigation panel
3341 * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
3342 * $cfg['NavigationTreeDefaultTabTable2'],
3343 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3345 * @return string Title for the $cfg value
3347 public static function getTitleForTarget($target)
3349 $mapping = array(
3350 'structure' => __('Structure'),
3351 'sql' => __('SQL'),
3352 'search' =>__('Search'),
3353 'insert' =>__('Insert'),
3354 'browse' => __('Browse'),
3355 'operations' => __('Operations'),
3357 // For backward compatiblity
3359 // Values for $cfg['DefaultTabTable']
3360 'tbl_structure.php' => __('Structure'),
3361 'tbl_sql.php' => __('SQL'),
3362 'tbl_select.php' =>__('Search'),
3363 'tbl_change.php' =>__('Insert'),
3364 'sql.php' => __('Browse'),
3365 // Values for $cfg['DefaultTabDatabase']
3366 'db_structure.php' => __('Structure'),
3367 'db_sql.php' => __('SQL'),
3368 'db_search.php' => __('Search'),
3369 'db_operations.php' => __('Operations'),
3371 return isset($mapping[$target]) ? $mapping[$target] : false;
3375 * Get the script name corresponding to a plain English config word
3376 * in order to append in links on navigation and main panel
3378 * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
3379 * $cfg['NavigationTreeDefaultTabTable2'],
3380 * $cfg['DefaultTabTable'], $cfg['DefaultTabDatabase'] or
3381 * $cfg['DefaultTabServer']
3382 * @param string $location one out of 'server', 'table', 'database'
3384 * @return string script name corresponding to the config word
3386 public static function getScriptNameForOption($target, $location)
3388 if ($location == 'server') {
3389 // Values for $cfg['DefaultTabServer']
3390 switch ($target) {
3391 case 'welcome':
3392 return 'index.php';
3393 case 'databases':
3394 return 'server_databases.php';
3395 case 'status':
3396 return 'server_status.php';
3397 case 'variables':
3398 return 'server_variables.php';
3399 case 'privileges':
3400 return 'server_privileges.php';
3402 } elseif ($location == 'database') {
3403 // Values for $cfg['DefaultTabDatabase']
3404 switch ($target) {
3405 case 'structure':
3406 return 'db_structure.php';
3407 case 'sql':
3408 return 'db_sql.php';
3409 case 'search':
3410 return 'db_search.php';
3411 case 'operations':
3412 return 'db_operations.php';
3414 } elseif ($location == 'table') {
3415 // Values for $cfg['DefaultTabTable'],
3416 // $cfg['NavigationTreeDefaultTabTable'] and
3417 // $cfg['NavigationTreeDefaultTabTable2']
3418 switch ($target) {
3419 case 'structure':
3420 return 'tbl_structure.php';
3421 case 'sql':
3422 return 'tbl_sql.php';
3423 case 'search':
3424 return 'tbl_select.php';
3425 case 'insert':
3426 return 'tbl_change.php';
3427 case 'browse':
3428 return 'sql.php';
3432 return $target;
3436 * Formats user string, expanding @VARIABLES@, accepting strftime format
3437 * string.
3439 * @param string $string Text where to do expansion.
3440 * @param array|string $escape Function to call for escaping variable values.
3441 * Can also be an array of:
3442 * - the escape method name
3443 * - the class that contains the method
3444 * - location of the class (for inclusion)
3445 * @param array $updates Array with overrides for default parameters
3446 * (obtained from GLOBALS).
3448 * @return string
3450 public static function expandUserString(
3451 $string, $escape = null, $updates = array()
3453 /* Content */
3454 $vars = array();
3455 $vars['http_host'] = PMA_getenv('HTTP_HOST');
3456 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3457 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3459 if (empty($GLOBALS['cfg']['Server']['verbose'])) {
3460 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host'];
3461 } else {
3462 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose'];
3465 $vars['database'] = $GLOBALS['db'];
3466 $vars['table'] = $GLOBALS['table'];
3467 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3469 /* Update forced variables */
3470 foreach ($updates as $key => $val) {
3471 $vars[$key] = $val;
3474 /* Replacement mapping */
3476 * The __VAR__ ones are for backward compatibility, because user
3477 * might still have it in cookies.
3479 $replace = array(
3480 '@HTTP_HOST@' => $vars['http_host'],
3481 '@SERVER@' => $vars['server_name'],
3482 '__SERVER__' => $vars['server_name'],
3483 '@VERBOSE@' => $vars['server_verbose'],
3484 '@VSERVER@' => $vars['server_verbose_or_name'],
3485 '@DATABASE@' => $vars['database'],
3486 '__DB__' => $vars['database'],
3487 '@TABLE@' => $vars['table'],
3488 '__TABLE__' => $vars['table'],
3489 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3492 /* Optional escaping */
3493 if (! is_null($escape)) {
3494 if (is_array($escape)) {
3495 include_once $escape[2];
3496 $escape_class = new $escape[1];
3497 $escape_method = $escape[0];
3499 foreach ($replace as $key => $val) {
3500 if (is_array($escape)) {
3501 $replace[$key] = $escape_class->$escape_method($val);
3502 } else {
3503 $replace[$key] = ($escape == 'backquote')
3504 ? self::$escape($val)
3505 : $escape($val);
3510 /* Backward compatibility in 3.5.x */
3511 if (/*overload*/mb_strpos($string, '@FIELDS@') !== false) {
3512 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3515 /* Fetch columns list if required */
3516 if (/*overload*/mb_strpos($string, '@COLUMNS@') !== false) {
3517 $columns_list = $GLOBALS['dbi']->getColumns(
3518 $GLOBALS['db'], $GLOBALS['table']
3521 // sometimes the table no longer exists at this point
3522 if (! is_null($columns_list)) {
3523 $column_names = array();
3524 foreach ($columns_list as $column) {
3525 if (! is_null($escape)) {
3526 $column_names[] = self::$escape($column['Field']);
3527 } else {
3528 $column_names[] = $column['Field'];
3531 $replace['@COLUMNS@'] = implode(',', $column_names);
3532 } else {
3533 $replace['@COLUMNS@'] = '*';
3537 /* Do the replacement */
3538 return strtr(strftime($string), $replace);
3542 * Prepare the form used to browse anywhere on the local server for a file to
3543 * import
3545 * @param string $max_upload_size maximum upload size
3547 * @return String
3549 public static function getBrowseUploadFileBlock($max_upload_size)
3551 $block_html = '';
3553 if ($GLOBALS['is_upload'] && ! empty($GLOBALS['cfg']['UploadDir'])) {
3554 $block_html .= '<label for="radio_import_file">';
3555 } else {
3556 $block_html .= '<label for="input_import_file">';
3559 $block_html .= __("Browse your computer:") . '</label>'
3560 . '<div id="upload_form_status" style="display: none;"></div>'
3561 . '<div id="upload_form_status_info" style="display: none;"></div>'
3562 . '<input type="file" name="import_file" id="input_import_file" />'
3563 . self::getFormattedMaximumUploadSize($max_upload_size) . "\n"
3564 // some browsers should respect this :)
3565 . self::generateHiddenMaxFileSize($max_upload_size) . "\n";
3567 return $block_html;
3571 * Prepare the form used to select a file to import from the server upload
3572 * directory
3574 * @param ImportPlugin[] $import_list array of import plugins
3575 * @param string $uploaddir upload directory
3577 * @return String
3579 public static function getSelectUploadFileBlock($import_list, $uploaddir)
3581 $block_html = '';
3582 $block_html .= '<label for="radio_local_import_file">'
3583 . sprintf(
3584 __("Select from the web server upload directory <b>%s</b>:"),
3585 htmlspecialchars(self::userDir($uploaddir))
3587 . '</label>';
3589 $extensions = '';
3590 foreach ($import_list as $import_plugin) {
3591 if (! empty($extensions)) {
3592 $extensions .= '|';
3594 $extensions .= $import_plugin->getProperties()->getExtension();
3597 $matcher = '@\.(' . $extensions . ')(\.('
3598 . PMA_supportedDecompressions() . '))?$@';
3600 $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
3601 && isset($GLOBALS['local_import_file']))
3602 ? $GLOBALS['local_import_file']
3603 : '';
3605 $files = PMA_getFileSelectOptions(
3606 self::userDir($uploaddir),
3607 $matcher,
3608 $active
3611 if ($files === false) {
3612 PMA_Message::error(
3613 __('The directory you set for upload work cannot be reached.')
3614 )->display();
3615 } elseif (! empty($files)) {
3616 $block_html .= "\n"
3617 . ' <select style="margin: 5px" size="1" '
3618 . 'name="local_import_file" '
3619 . 'id="select_local_import_file">' . "\n"
3620 . ' <option value="">&nbsp;</option>' . "\n"
3621 . $files
3622 . ' </select>' . "\n";
3623 } elseif (empty($files)) {
3624 $block_html .= '<i>' . __('There are no files to upload!') . '</i>';
3627 return $block_html;
3632 * Build titles and icons for action links
3634 * @return array the action titles
3636 public static function buildActionTitles()
3638 $titles = array();
3640 $titles['Browse'] = self::getIcon('b_browse.png', __('Browse'));
3641 $titles['NoBrowse'] = self::getIcon('bd_browse.png', __('Browse'));
3642 $titles['Search'] = self::getIcon('b_select.png', __('Search'));
3643 $titles['NoSearch'] = self::getIcon('bd_select.png', __('Search'));
3644 $titles['Insert'] = self::getIcon('b_insrow.png', __('Insert'));
3645 $titles['NoInsert'] = self::getIcon('bd_insrow.png', __('Insert'));
3646 $titles['Structure'] = self::getIcon('b_props.png', __('Structure'));
3647 $titles['Drop'] = self::getIcon('b_drop.png', __('Drop'));
3648 $titles['NoDrop'] = self::getIcon('bd_drop.png', __('Drop'));
3649 $titles['Empty'] = self::getIcon('b_empty.png', __('Empty'));
3650 $titles['NoEmpty'] = self::getIcon('bd_empty.png', __('Empty'));
3651 $titles['Edit'] = self::getIcon('b_edit.png', __('Edit'));
3652 $titles['NoEdit'] = self::getIcon('bd_edit.png', __('Edit'));
3653 $titles['Export'] = self::getIcon('b_export.png', __('Export'));
3654 $titles['NoExport'] = self::getIcon('bd_export.png', __('Export'));
3655 $titles['Execute'] = self::getIcon('b_nextpage.png', __('Execute'));
3656 $titles['NoExecute'] = self::getIcon('bd_nextpage.png', __('Execute'));
3657 // For Favorite/NoFavorite, we need icon only.
3658 $titles['Favorite'] = self::getIcon('b_favorite.png', '');
3659 $titles['NoFavorite']= self::getIcon('b_no_favorite.png', '');
3661 return $titles;
3665 * This function processes the datatypes supported by the DB,
3666 * as specified in PMA_Types->getColumns() and either returns an array
3667 * (useful for quickly checking if a datatype is supported)
3668 * or an HTML snippet that creates a drop-down list.
3670 * @param bool $html Whether to generate an html snippet or an array
3671 * @param string $selected The value to mark as selected in HTML mode
3673 * @return mixed An HTML snippet or an array of datatypes.
3676 public static function getSupportedDatatypes($html = false, $selected = '')
3678 if ($html) {
3680 // NOTE: the SELECT tag in not included in this snippet.
3681 $retval = '';
3683 foreach ($GLOBALS['PMA_Types']->getColumns() as $key => $value) {
3684 if (is_array($value)) {
3685 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3686 foreach ($value as $subvalue) {
3687 if ($subvalue == $selected) {
3688 $retval .= sprintf(
3689 '<option selected="selected" title="%s">%s</option>',
3690 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3691 $subvalue
3693 } else if ($subvalue === '-') {
3694 $retval .= '<option disabled="disabled">';
3695 $retval .= $subvalue;
3696 $retval .= '</option>';
3697 } else {
3698 $retval .= sprintf(
3699 '<option title="%s">%s</option>',
3700 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3701 $subvalue
3705 $retval .= '</optgroup>';
3706 } else {
3707 if ($selected == $value) {
3708 $retval .= sprintf(
3709 '<option selected="selected" title="%s">%s</option>',
3710 $GLOBALS['PMA_Types']->getTypeDescription($value),
3711 $value
3713 } else {
3714 $retval .= sprintf(
3715 '<option title="%s">%s</option>',
3716 $GLOBALS['PMA_Types']->getTypeDescription($value),
3717 $value
3722 } else {
3723 $retval = array();
3724 foreach ($GLOBALS['PMA_Types']->getColumns() as $value) {
3725 if (is_array($value)) {
3726 foreach ($value as $subvalue) {
3727 if ($subvalue !== '-') {
3728 $retval[] = $subvalue;
3731 } else {
3732 if ($value !== '-') {
3733 $retval[] = $value;
3739 return $retval;
3740 } // end getSupportedDatatypes()
3743 * Returns a list of datatypes that are not (yet) handled by PMA.
3744 * Used by: tbl_change.php and libraries/db_routines.inc.php
3746 * @return array list of datatypes
3748 public static function unsupportedDatatypes()
3750 $no_support_types = array();
3751 return $no_support_types;
3755 * Return GIS data types
3757 * @param bool $upper_case whether to return values in upper case
3759 * @return string[] GIS data types
3761 public static function getGISDatatypes($upper_case = false)
3763 $gis_data_types = array(
3764 'geometry',
3765 'point',
3766 'linestring',
3767 'polygon',
3768 'multipoint',
3769 'multilinestring',
3770 'multipolygon',
3771 'geometrycollection'
3773 if ($upper_case) {
3774 for ($i = 0, $nb = count($gis_data_types); $i < $nb; $i++) {
3775 $gis_data_types[$i]
3776 = /*overload*/mb_strtoupper($gis_data_types[$i]);
3779 return $gis_data_types;
3783 * Generates GIS data based on the string passed.
3785 * @param string $gis_string GIS string
3787 * @return string GIS data enclosed in 'GeomFromText' function
3789 public static function createGISData($gis_string)
3791 $gis_string = trim($gis_string);
3792 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3793 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3794 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3795 return 'GeomFromText(' . $gis_string . ')';
3796 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3797 return "GeomFromText('" . $gis_string . "')";
3798 } else {
3799 return $gis_string;
3804 * Returns the names and details of the functions
3805 * that can be applied on geometry data types.
3807 * @param string $geom_type if provided the output is limited to the functions
3808 * that are applicable to the provided geometry type.
3809 * @param bool $binary if set to false functions that take two geometries
3810 * as arguments will not be included.
3811 * @param bool $display if set to true separators will be added to the
3812 * output array.
3814 * @return array names and details of the functions that can be applied on
3815 * geometry data types.
3817 public static function getGISFunctions(
3818 $geom_type = null, $binary = true, $display = false
3820 $funcs = array();
3821 if ($display) {
3822 $funcs[] = array('display' => ' ');
3825 // Unary functions common to all geometry types
3826 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3827 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3828 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3829 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3830 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3831 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3833 $geom_type = trim(/*overload*/mb_strtolower($geom_type));
3834 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3835 $funcs[] = array('display' => '--------');
3838 // Unary functions that are specific to each geometry type
3839 if ($geom_type == 'point') {
3840 $funcs['X'] = array('params' => 1, 'type' => 'float');
3841 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3843 } elseif ($geom_type == 'multipoint') {
3844 // no functions here
3845 } elseif ($geom_type == 'linestring') {
3846 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3847 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3848 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3849 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3850 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3852 } elseif ($geom_type == 'multilinestring') {
3853 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3854 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3856 } elseif ($geom_type == 'polygon') {
3857 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3858 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3859 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3861 } elseif ($geom_type == 'multipolygon') {
3862 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3863 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3864 // Not yet implemented in MySQL
3865 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3867 } elseif ($geom_type == 'geometrycollection') {
3868 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3871 // If we are asked for binary functions as well
3872 if ($binary) {
3873 // section separator
3874 if ($display) {
3875 $funcs[] = array('display' => '--------');
3878 if (PMA_MYSQL_INT_VERSION < 50601) {
3879 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3880 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3881 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3882 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3883 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3884 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3885 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3886 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3887 } else {
3888 // If MySQl version is greater than or equal 5.6.1,
3889 // use the ST_ prefix.
3890 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3891 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3892 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3893 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3894 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3895 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3896 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3897 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3900 if ($display) {
3901 $funcs[] = array('display' => '--------');
3903 // Minimum bounding rectangle functions
3904 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3905 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3906 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3907 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3908 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3909 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3910 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3912 return $funcs;
3916 * Returns default function for a particular column.
3918 * @param array $field Data about the column for which
3919 * to generate the dropdown
3920 * @param bool $insert_mode Whether the operation is 'insert'
3922 * @global array $cfg PMA configuration
3923 * @global mixed $data data of currently edited row
3924 * (used to detect whether to choose defaults)
3926 * @return string An HTML snippet of a dropdown list with function
3927 * names appropriate for the requested column.
3929 public static function getDefaultFunctionForField($field, $insert_mode)
3932 * @todo Except for $cfg, no longer use globals but pass as parameters
3933 * from higher levels
3935 global $cfg, $data;
3937 $default_function = '';
3939 // Can we get field class based values?
3940 $current_class = $GLOBALS['PMA_Types']->getTypeClass($field['True_Type']);
3941 if (! empty($current_class)) {
3942 if (isset($cfg['DefaultFunctions']['FUNC_' . $current_class])) {
3943 $default_function
3944 = $cfg['DefaultFunctions']['FUNC_' . $current_class];
3948 // what function defined as default?
3949 // for the first timestamp we don't set the default function
3950 // if there is a default value for the timestamp
3951 // (not including CURRENT_TIMESTAMP)
3952 // and the column does not have the
3953 // ON UPDATE DEFAULT TIMESTAMP attribute.
3954 if (($field['True_Type'] == 'timestamp')
3955 && $field['first_timestamp']
3956 && empty($field['Default'])
3957 && empty($data)
3958 && $field['Extra'] != 'on update CURRENT_TIMESTAMP'
3959 && $field['Null'] == 'NO'
3961 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3964 // For primary keys of type char(36) or varchar(36) UUID if the default
3965 // function
3966 // Only applies to insert mode, as it would silently trash data on updates.
3967 if ($insert_mode
3968 && $field['Key'] == 'PRI'
3969 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3971 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3974 return $default_function;
3978 * Creates a dropdown box with MySQL functions for a particular column.
3980 * @param array $field Data about the column for which
3981 * to generate the dropdown
3982 * @param bool $insert_mode Whether the operation is 'insert'
3984 * @return string An HTML snippet of a dropdown list with function
3985 * names appropriate for the requested column.
3987 public static function getFunctionsForField($field, $insert_mode)
3989 $default_function = self::getDefaultFunctionForField($field, $insert_mode);
3990 $dropdown_built = array();
3992 // Create the output
3993 $retval = '<option></option>' . "\n";
3994 // loop on the dropdown array and print all available options for that
3995 // field.
3996 $functions = $GLOBALS['PMA_Types']->getFunctions($field['True_Type']);
3997 foreach ($functions as $function) {
3998 $retval .= '<option';
3999 if ($default_function === $function) {
4000 $retval .= ' selected="selected"';
4002 $retval .= '>' . $function . '</option>' . "\n";
4003 $dropdown_built[$function] = true;
4006 // Create separator before all functions list
4007 if (count($functions) > 0) {
4008 $retval .= '<option value="" disabled="disabled">--------</option>'
4009 . "\n";
4012 // For compatibility's sake, do not let out all other functions. Instead
4013 // print a separator (blank) and then show ALL functions which weren't
4014 // shown yet.
4015 $functions = $GLOBALS['PMA_Types']->getAllFunctions();
4016 foreach ($functions as $function) {
4017 // Skip already included functions
4018 if (isset($dropdown_built[$function])) {
4019 continue;
4021 $retval .= '<option';
4022 if ($default_function === $function) {
4023 $retval .= ' selected="selected"';
4025 $retval .= '>' . $function . '</option>' . "\n";
4026 } // end for
4028 return $retval;
4029 } // end getFunctionsForField()
4032 * Checks if the current user has a specific privilege and returns true if the
4033 * user indeed has that privilege or false if (s)he doesn't. This function must
4034 * only be used for features that are available since MySQL 5, because it
4035 * relies on the INFORMATION_SCHEMA database to be present.
4037 * Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
4038 * // Checks if the currently logged in user has the global
4039 * // 'CREATE ROUTINE' privilege or, if not, checks if the
4040 * // user has this privilege on database 'mydb'.
4042 * @param string $priv The privilege to check
4043 * @param mixed $db null, to only check global privileges
4044 * string, db name where to also check for privileges
4045 * @param mixed $tbl null, to only check global/db privileges
4046 * string, table name where to also check for privileges
4048 * @return bool
4050 public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
4052 // Get the username for the current user in the format
4053 // required to use in the information schema database.
4054 $user = $GLOBALS['dbi']->fetchValue("SELECT CURRENT_USER();");
4055 if ($user === false) {
4056 return false;
4059 if ($user == '@') { // MySQL is started with --skip-grant-tables
4060 return true;
4063 $user = explode('@', $user);
4064 $username = "''";
4065 $username .= str_replace("'", "''", $user[0]);
4066 $username .= "''@''";
4067 $username .= str_replace("'", "''", $user[1]);
4068 $username .= "''";
4070 // Prepare the query
4071 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
4072 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
4074 // Check global privileges first.
4075 $user_privileges = $GLOBALS['dbi']->fetchValue(
4076 sprintf(
4077 $query,
4078 'USER_PRIVILEGES',
4079 $username,
4080 $priv
4083 if ($user_privileges) {
4084 return true;
4086 // If a database name was provided and user does not have the
4087 // required global privilege, try database-wise permissions.
4088 if ($db !== null) {
4089 $query .= " AND '%s' LIKE `TABLE_SCHEMA`";
4090 $schema_privileges = $GLOBALS['dbi']->fetchValue(
4091 sprintf(
4092 $query,
4093 'SCHEMA_PRIVILEGES',
4094 $username,
4095 $priv,
4096 self::sqlAddSlashes($db)
4099 if ($schema_privileges) {
4100 return true;
4102 } else {
4103 // There was no database name provided and the user
4104 // does not have the correct global privilege.
4105 return false;
4107 // If a table name was also provided and we still didn't
4108 // find any valid privileges, try table-wise privileges.
4109 if ($tbl !== null) {
4110 // need to escape wildcards in db and table names, see bug #3518484
4111 $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
4112 $query .= " AND TABLE_NAME='%s'";
4113 $table_privileges = $GLOBALS['dbi']->fetchValue(
4114 sprintf(
4115 $query,
4116 'TABLE_PRIVILEGES',
4117 $username,
4118 $priv,
4119 self::sqlAddSlashes($db),
4120 self::sqlAddSlashes($tbl)
4123 if ($table_privileges) {
4124 return true;
4127 // If we reached this point, the user does not
4128 // have even valid table-wise privileges.
4129 return false;
4133 * Returns server type for current connection
4135 * Known types are: Drizzle, MariaDB and MySQL (default)
4137 * @return string
4139 public static function getServerType()
4141 $server_type = 'MySQL';
4142 if (PMA_DRIZZLE) {
4143 $server_type = 'Drizzle';
4144 return $server_type;
4147 if (/*overload*/mb_stripos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
4148 $server_type = 'MariaDB';
4149 return $server_type;
4152 if (/*overload*/mb_stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
4153 $server_type = 'Percona Server';
4154 return $server_type;
4157 return $server_type;
4161 * Prepare HTML code for display button.
4163 * @return String
4165 public static function getButton()
4167 return '<p class="print_ignore">'
4168 . '<input type="button" class="button" id="print" value="'
4169 . __('Print') . '" />'
4170 . '</p>';
4174 * Parses ENUM/SET values
4176 * @param string $definition The definition of the column
4177 * for which to parse the values
4178 * @param bool $escapeHtml Whether to escape html entities
4180 * @return array
4182 public static function parseEnumSetValues($definition, $escapeHtml = true)
4184 $values_string = htmlentities($definition, ENT_COMPAT, "UTF-8");
4185 // There is a JS port of the below parser in functions.js
4186 // If you are fixing something here,
4187 // you need to also update the JS port.
4188 $values = array();
4189 $in_string = false;
4190 $buffer = '';
4192 for ($i = 0, $length = /*overload*/mb_strlen($values_string);
4193 $i < $length;
4194 $i++
4196 $curr = /*overload*/mb_substr($values_string, $i, 1);
4197 $next = ($i == /*overload*/mb_strlen($values_string) - 1)
4198 ? ''
4199 : /*overload*/mb_substr($values_string, $i + 1, 1);
4201 if (! $in_string && $curr == "'") {
4202 $in_string = true;
4203 } else if (($in_string && $curr == "\\") && $next == "\\") {
4204 $buffer .= "&#92;";
4205 $i++;
4206 } else if (($in_string && $next == "'")
4207 && ($curr == "'" || $curr == "\\")
4209 $buffer .= "&#39;";
4210 $i++;
4211 } else if ($in_string && $curr == "'") {
4212 $in_string = false;
4213 $values[] = $buffer;
4214 $buffer = '';
4215 } else if ($in_string) {
4216 $buffer .= $curr;
4221 if (/*overload*/mb_strlen($buffer) > 0) {
4222 // The leftovers in the buffer are the last value (if any)
4223 $values[] = $buffer;
4226 if (! $escapeHtml) {
4227 foreach ($values as $key => $value) {
4228 $values[$key] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
4232 return $values;
4236 * Get regular expression which occur first inside the given sql query.
4238 * @param Array $regex_array Comparing regular expressions.
4239 * @param String $query SQL query to be checked.
4241 * @return String Matching regular expression.
4243 public static function getFirstOccurringRegularExpression($regex_array, $query)
4245 $minimum_first_occurence_index = null;
4246 $regex = null;
4248 foreach ($regex_array as $test_regex) {
4249 if (preg_match($test_regex, $query, $matches, PREG_OFFSET_CAPTURE)) {
4250 if (is_null($minimum_first_occurence_index)
4251 || ($matches[0][1] < $minimum_first_occurence_index)
4253 $regex = $test_regex;
4254 $minimum_first_occurence_index = $matches[0][1];
4258 return $regex;
4262 * Return the list of tabs for the menu with corresponding names
4264 * @param string $level 'server', 'db' or 'table' level
4266 * @return array list of tabs for the menu
4268 public static function getMenuTabList($level = null)
4270 $tabList = array(
4271 'server' => array(
4272 'databases' => __('Databases'),
4273 'sql' => __('SQL'),
4274 'status' => __('Status'),
4275 'rights' => __('Users'),
4276 'export' => __('Export'),
4277 'import' => __('Import'),
4278 'settings' => __('Settings'),
4279 'binlog' => __('Binary log'),
4280 'replication' => __('Replication'),
4281 'vars' => __('Variables'),
4282 'charset' => __('Charsets'),
4283 'plugins' => __('Plugins'),
4284 'engine' => __('Engines')
4286 'db' => array(
4287 'structure' => __('Structure'),
4288 'sql' => __('SQL'),
4289 'search' => __('Search'),
4290 'qbe' => __('Query'),
4291 'export' => __('Export'),
4292 'import' => __('Import'),
4293 'operation' => __('Operations'),
4294 'privileges' => __('Privileges'),
4295 'routines' => __('Routines'),
4296 'events' => __('Events'),
4297 'triggers' => __('Triggers'),
4298 'tracking' => __('Tracking'),
4299 'designer' => __('Designer'),
4300 'central_columns' => __('Central columns')
4302 'table' => array(
4303 'browse' => __('Browse'),
4304 'structure' => __('Structure'),
4305 'sql' => __('SQL'),
4306 'search' => __('Search'),
4307 'insert' => __('Insert'),
4308 'export' => __('Export'),
4309 'import' => __('Import'),
4310 'privileges' => __('Privileges'),
4311 'operation' => __('Operations'),
4312 'tracking' => __('Tracking'),
4313 'triggers' => __('Triggers'),
4317 if ($level == null) {
4318 return $tabList;
4319 } else if (array_key_exists($level, $tabList)) {
4320 return $tabList[$level];
4321 } else {
4322 return null;
4327 * Returns information with regards to handling the http request
4329 * @param array $context Data about the context for which
4330 * to http request is sent
4332 * @return array of updated context information
4334 public static function handleContext(array $context)
4336 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUrl'])) {
4337 $context['http'] = array(
4338 'proxy' => $GLOBALS['cfg']['ProxyUrl'],
4339 'request_fulluri' => true
4341 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUser'])) {
4342 $auth = base64_encode(
4343 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4345 $context['http']['header'] .= 'Proxy-Authorization: Basic '
4346 . $auth . "\r\n";
4349 return $context;
4352 * Updates an existing curl as necessary
4354 * @param resource $curl_handle A curl_handle resource
4355 * created by curl_init which should
4356 * have several options set
4358 * @return resource curl_handle with updated options
4360 public static function configureCurl($curl_handle)
4362 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUrl'])) {
4363 curl_setopt($curl_handle, CURLOPT_PROXY, $GLOBALS['cfg']['ProxyUrl']);
4364 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUser'])) {
4365 curl_setopt(
4366 $curl_handle,
4367 CURLOPT_PROXYUSERPWD,
4368 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4372 curl_setopt($curl_handle, CURLOPT_USERAGENT, 'phpMyAdmin/' . PMA_VERSION);
4373 return $curl_handle;
4377 * Add fractional seconds to time, datetime and timestamp strings.
4378 * If the string contains fractional seconds,
4379 * pads it with 0s up to 6 decimal places.
4381 * @param string $value time, datetime or timestamp strings
4383 * @return string time, datetime or timestamp strings with fractional seconds
4385 public static function addMicroseconds($value)
4387 if (empty($value) || $value == 'CURRENT_TIMESTAMP') {
4388 return $value;
4391 if (/*overload*/mb_strpos($value, '.') === false) {
4392 return $value . '.000000';
4395 $value .= '000000';
4396 return /*overload*/mb_substr(
4397 $value,
4399 /*overload*/mb_strpos($value, '.') + 7
4404 * Reads the file, detects the compression MIME type, closes the file
4405 * and returns the MIME type
4407 * @param resource $file the file handle
4409 * @return string the MIME type for compression, or 'none'
4411 public static function getCompressionMimeType($file)
4413 $test = fread($file, 4);
4414 $len = strlen($test);
4415 fclose($file);
4416 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
4417 return 'application/gzip';
4419 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
4420 return 'application/bzip2';
4422 if ($len >= 4 && $test == "PK\003\004") {
4423 return 'application/zip';
4425 return 'none';
4429 * Renders a single link for the top of the navigation panel
4431 * @param string $link The url for the link
4432 * @param bool $showText Whether to show the text or to
4433 * only use it for title attributes
4434 * @param string $text The text to display and use for title attributes
4435 * @param bool $showIcon Whether to show the icon
4436 * @param string $icon The filename of the icon to show
4437 * @param string $linkId Value to use for the ID attribute
4438 * @param boolean $disableAjax Whether to disable ajax page loading for this link
4439 * @param string $linkTarget The name of the target frame for the link
4440 * @param array $classes HTML classes to apply
4442 * @return string HTML code for one link
4444 public static function getNavigationLink(
4445 $link,
4446 $showText,
4447 $text,
4448 $showIcon,
4449 $icon,
4450 $linkId = '',
4451 $disableAjax = false,
4452 $linkTarget = '',
4453 $classes = array()
4455 $retval = '<a href="' . $link . '"';
4456 if (! empty($linkId)) {
4457 $retval .= ' id="' . $linkId . '"';
4459 if (! empty($linkTarget)) {
4460 $retval .= ' target="' . $linkTarget . '"';
4462 if ($disableAjax) {
4463 $classes[] = 'disableAjax';
4465 if (!empty($classes)) {
4466 $retval .= ' class="' . join(" ", $classes) . '"';
4468 $retval .= ' title="' . $text . '">';
4469 if ($showIcon) {
4470 $retval .= PMA_Util::getImage(
4471 $icon,
4472 $text
4475 if ($showText) {
4476 $retval .= $text;
4478 $retval .= '</a>';
4479 if ($showText) {
4480 $retval .= '<br />';
4482 return $retval;
4486 * Provide COLLATE clause, if required, to perform case sensitive comparisons
4487 * for queries on information_schema.
4489 * @return string COLLATE clause if needed or empty string.
4491 public static function getCollateForIS()
4493 $lowerCaseTableNames = self::cacheGet(
4494 'lower_case_table_names',
4495 function () {
4496 return $GLOBALS['dbi']->fetchValue(
4497 "SELECT @@lower_case_table_names"
4502 if ($lowerCaseTableNames === '0' // issue #10961
4503 || $lowerCaseTableNames === '2' // issue #11461
4505 return "COLLATE utf8_bin";
4507 return "";
4511 * Process the index data.
4513 * @param array $indexes index data
4515 * @return array processes index data
4517 public static function processIndexData($indexes)
4519 $lastIndex = '';
4521 $primary = '';
4522 $pk_array = array(); // will be use to emphasis prim. keys in the table
4523 $indexes_info = array();
4524 $indexes_data = array();
4526 // view
4527 foreach ($indexes as $row) {
4528 // Backups the list of primary keys
4529 if ($row['Key_name'] == 'PRIMARY') {
4530 $primary .= $row['Column_name'] . ', ';
4531 $pk_array[$row['Column_name']] = 1;
4533 // Retains keys informations
4534 if ($row['Key_name'] != $lastIndex) {
4535 $indexes[] = $row['Key_name'];
4536 $lastIndex = $row['Key_name'];
4538 $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index'];
4539 $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique'];
4540 if (isset($row['Cardinality'])) {
4541 $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality'];
4543 // I don't know what does following column mean....
4544 // $indexes_info[$row['Key_name']]['Packed'] = $row['Packed'];
4546 $indexes_info[$row['Key_name']]['Comment'] = $row['Comment'];
4548 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name']
4549 = $row['Column_name'];
4550 if (isset($row['Sub_part'])) {
4551 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part']
4552 = $row['Sub_part'];
4555 } // end while
4557 return array($primary, $pk_array, $indexes_info, $indexes_data);
4561 * Returns the HTML for check all check box and with selected text
4562 * for multi submits
4564 * @param string $pmaThemeImage path to theme's image folder
4565 * @param string $text_dir text direction
4566 * @param string $formName name of the enclosing form
4568 * @return string HTML
4570 public static function getWithSelected($pmaThemeImage, $text_dir, $formName)
4572 $html = '<img class="selectallarrow" '
4573 . 'src="' . $pmaThemeImage . 'arrow_' . $text_dir . '.png" '
4574 . 'width="38" height="22" alt="' . __('With selected:') . '" />';
4575 $html .= '<input type="checkbox" id="' . $formName . '_checkall" '
4576 . 'class="checkall_box" title="' . __('Check all') . '" />'
4577 . '<label for="' . $formName . '_checkall">' . __('Check all')
4578 . '</label>';
4579 $html .= '<i style="margin-left: 2em">'
4580 . __('With selected:') . '</i>';
4582 return $html;
4586 * Function to get html for the start row and number of rows panel
4588 * @param string $sql_query sql query
4590 * @return string html
4592 public static function getStartAndNumberOfRowsPanel($sql_query)
4594 $pos = isset($_REQUEST['pos'])
4595 ? $_REQUEST['pos']
4596 : $_SESSION['tmpval']['pos'];
4597 if (isset($_REQUEST['session_max_rows'])) {
4598 $rows = $_REQUEST['session_max_rows'];
4599 } else {
4600 if ($_SESSION['tmpval']['max_rows'] != 'all') {
4601 $rows = $_SESSION['tmpval']['max_rows'];
4602 } else {
4603 $rows = $GLOBALS['cfg']['MaxRows'];
4607 return Template::get('startAndNumberOfRowsPanel')
4608 ->render(
4609 array(
4610 'pos' => $pos,
4611 'unlim_num_rows' => $_REQUEST['unlim_num_rows'],
4612 'rows' => $rows,
4613 'sql_query' => $sql_query,
4619 * Returns whether the database server supports virtual columns
4621 * @return bool
4623 public static function isVirtualColumnsSupported()
4625 $serverType = self::getServerType();
4626 return $serverType == 'MySQL' && PMA_MYSQL_INT_VERSION >= 50705
4627 || ($serverType == 'MariaDB' && PMA_MYSQL_INT_VERSION >= 50200);
4631 * Returns the proper class clause according to the column type
4633 * @param string $type the column type
4635 * @return string $class_clause the HTML class clause
4637 public static function getClassForType($type)
4639 if ('set' == $type
4640 || 'enum' == $type
4642 $class_clause = '';
4643 } else {
4644 $class_clause = ' class="nowrap"';
4646 return $class_clause;
4650 * Gets the list of tables in the current db and information about these
4651 * tables if possible
4653 * @param string $db database name
4654 * @param string $sub_part part of script name
4656 * @return array
4659 public static function getDbInfo($db, $sub_part)
4661 global $cfg;
4664 * limits for table list
4666 if (! isset($_SESSION['tmpval']['table_limit_offset'])
4667 || $_SESSION['tmpval']['table_limit_offset_db'] != $db
4669 $_SESSION['tmpval']['table_limit_offset'] = 0;
4670 $_SESSION['tmpval']['table_limit_offset_db'] = $db;
4672 if (isset($_REQUEST['pos'])) {
4673 $_SESSION['tmpval']['table_limit_offset'] = (int) $_REQUEST['pos'];
4675 $pos = $_SESSION['tmpval']['table_limit_offset'];
4678 * whether to display extended stats
4680 $is_show_stats = $cfg['ShowStats'];
4683 * whether selected db is information_schema
4685 $db_is_system_schema = false;
4687 if ($GLOBALS['dbi']->isSystemSchema($db)) {
4688 $is_show_stats = false;
4689 $db_is_system_schema = true;
4693 * information about tables in db
4695 $tables = array();
4697 $tooltip_truename = array();
4698 $tooltip_aliasname = array();
4700 // Special speedup for newer MySQL Versions (in 4.0 format changed)
4701 if (true === $cfg['SkipLockedTables'] && ! PMA_DRIZZLE) {
4702 $db_info_result = $GLOBALS['dbi']->query(
4703 'SHOW OPEN TABLES FROM ' . PMA_Util::backquote($db) . ';'
4706 // Blending out tables in use
4707 if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
4708 $tables = self::getTablesWhenOpen($db, $db_info_result);
4710 } elseif ($db_info_result) {
4711 $GLOBALS['dbi']->freeResult($db_info_result);
4715 if (empty($tables)) {
4716 // Set some sorting defaults
4717 $sort = 'Name';
4718 $sort_order = 'ASC';
4720 if (isset($_REQUEST['sort'])) {
4721 $sortable_name_mappings = array(
4722 'table' => 'Name',
4723 'records' => 'Rows',
4724 'type' => 'Engine',
4725 'collation' => 'Collation',
4726 'size' => 'Data_length',
4727 'overhead' => 'Data_free',
4728 'creation' => 'Create_time',
4729 'last_update' => 'Update_time',
4730 'last_check' => 'Check_time',
4731 'comment' => 'Comment',
4734 // Make sure the sort type is implemented
4735 if (isset($sortable_name_mappings[$_REQUEST['sort']])) {
4736 $sort = $sortable_name_mappings[$_REQUEST['sort']];
4737 if ($_REQUEST['sort_order'] == 'DESC') {
4738 $sort_order = 'DESC';
4743 $tbl_group = false;
4744 $groupWithSeparator = false;
4745 $tbl_type = null;
4746 $limit_offset = 0;
4747 $limit_count = false;
4748 $groupTable = array();
4750 if (! empty($_REQUEST['tbl_group']) || ! empty($_REQUEST['tbl_type'])) {
4751 if (! empty($_REQUEST['tbl_type'])) {
4752 // only tables for selected type
4753 $tbl_type = $_REQUEST['tbl_type'];
4755 if (! empty($_REQUEST['tbl_group'])) {
4756 // only tables for selected group
4757 $tbl_group = $_REQUEST['tbl_group'];
4758 // include the table with the exact name of the group if such exists
4759 $groupTable = $GLOBALS['dbi']->getTablesFull(
4760 $db, $tbl_group, false, null, $limit_offset,
4761 $limit_count, $sort, $sort_order, $tbl_type
4763 $groupWithSeparator = $tbl_group
4764 . $GLOBALS['cfg']['NavigationTreeTableSeparator'];
4766 } else {
4767 // all tables in db
4768 // - get the total number of tables
4769 // (needed for proper working of the MaxTableList feature)
4770 $tables = $GLOBALS['dbi']->getTables($db);
4771 $total_num_tables = count($tables);
4772 if (isset($sub_part) && $sub_part == '_export') {
4773 // (don't fetch only a subset if we are coming from db_export.php,
4774 // because I think it's too risky to display only a subset of the
4775 // table names when exporting a db)
4778 * @todo Page selector for table names?
4780 } else {
4781 // fetch the details for a possible limited subset
4782 $limit_offset = $pos;
4783 $limit_count = true;
4786 $tables = array_merge(
4787 $groupTable,
4788 $GLOBALS['dbi']->getTablesFull(
4789 $db, $groupWithSeparator, ($groupWithSeparator !== false), null,
4790 $limit_offset, $limit_count, $sort, $sort_order, $tbl_type
4795 $num_tables = count($tables);
4796 // (needed for proper working of the MaxTableList feature)
4797 if (! isset($total_num_tables)) {
4798 $total_num_tables = $num_tables;
4802 * If coming from a Show MySQL link on the home page,
4803 * put something in $sub_part
4805 if (empty($sub_part)) {
4806 $sub_part = '_structure';
4809 return array(
4810 $tables,
4811 $num_tables,
4812 $total_num_tables,
4813 $sub_part,
4814 $is_show_stats,
4815 $db_is_system_schema,
4816 $tooltip_truename,
4817 $tooltip_aliasname,
4818 $pos
4823 * Gets the list of tables in the current db, taking into account
4824 * that they might be "in use"
4826 * @param string $db database name
4827 * @param object $db_info_result result set
4829 * @return array $tables list of tables
4832 public static function getTablesWhenOpen($db, $db_info_result)
4834 $tables = array();
4836 while ($tmp = $GLOBALS['dbi']->fetchAssoc($db_info_result)) {
4837 // if in use, memorize table name
4838 if ($tmp['In_use'] > 0) {
4839 $sot_cache[$tmp['Table']] = true;
4842 $GLOBALS['dbi']->freeResult($db_info_result);
4844 // is there at least one "in use" table?
4845 if (isset($sot_cache)) {
4846 $db_info_result = false;
4848 $tblGroupSql = "";
4849 $whereAdded = false;
4850 if (PMA_isValid($_REQUEST['tbl_group'])) {
4851 $group = PMA_Util::escapeMysqlWildcards($_REQUEST['tbl_group']);
4852 $groupWithSeparator = PMA_Util::escapeMysqlWildcards(
4853 $_REQUEST['tbl_group']
4854 . $GLOBALS['cfg']['NavigationTreeTableSeparator']
4856 $tblGroupSql .= " WHERE ("
4857 . PMA_Util::backquote('Tables_in_' . $db)
4858 . " LIKE '" . $groupWithSeparator . "%'"
4859 . " OR "
4860 . PMA_Util::backquote('Tables_in_' . $db)
4861 . " LIKE '" . $group . "')";
4862 $whereAdded = true;
4864 if (PMA_isValid($_REQUEST['tbl_type'], array('table', 'view'))) {
4865 $tblGroupSql .= $whereAdded ? " AND" : " WHERE";
4866 if ($_REQUEST['tbl_type'] == 'view') {
4867 $tblGroupSql .= " `Table_type` != 'BASE TABLE'";
4868 } else {
4869 $tblGroupSql .= " `Table_type` = 'BASE TABLE'";
4872 $db_info_result = $GLOBALS['dbi']->query(
4873 'SHOW FULL TABLES FROM ' . PMA_Util::backquote($db) . $tblGroupSql,
4874 null, PMA_DatabaseInterface::QUERY_STORE
4876 unset($tblGroupSql, $whereAdded);
4878 if ($db_info_result && $GLOBALS['dbi']->numRows($db_info_result) > 0) {
4879 while ($tmp = $GLOBALS['dbi']->fetchRow($db_info_result)) {
4880 if (! isset($sot_cache[$tmp[0]])) {
4881 $sts_result = $GLOBALS['dbi']->query(
4882 "SHOW TABLE STATUS FROM " . PMA_Util::backquote($db)
4883 . " LIKE '" . PMA_Util::sqlAddSlashes($tmp[0], true)
4884 . "';"
4886 $sts_tmp = $GLOBALS['dbi']->fetchAssoc($sts_result);
4887 $GLOBALS['dbi']->freeResult($sts_result);
4888 unset($sts_result);
4890 $tableArray = $GLOBALS['dbi']->copyTableProperties(
4891 array($sts_tmp), $db
4893 $tables[$sts_tmp['Name']] = $tableArray[0];
4894 } else { // table in use
4895 $tables[$tmp[0]] = array(
4896 'TABLE_NAME' => $tmp[0],
4897 'ENGINE' => '',
4898 'TABLE_TYPE' => '',
4899 'TABLE_ROWS' => 0,
4902 } // end while
4903 if ($GLOBALS['cfg']['NaturalOrder']) {
4904 uksort($tables, 'strnatcasecmp');
4907 } elseif ($db_info_result) {
4908 $GLOBALS['dbi']->freeResult($db_info_result);
4910 unset($sot_cache);
4912 return $tables;