Translated using Weblate (Hindi)
[phpmyadmin.git] / libraries / Util.class.php
blobe8e4bc7d45518d69792d89419ca169f2aaf38f73
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 /**
13 * Misc functions used all over the scripts.
15 * @package PhpMyAdmin
17 class PMA_Util
20 /**
21 * Detects which function to use for pow.
23 * @return string Function name.
25 public static function detectPow()
27 if (function_exists('bcpow')) {
28 // BCMath Arbitrary Precision Mathematics Function
29 return 'bcpow';
30 } elseif (function_exists('gmp_pow')) {
31 // GMP Function
32 return 'gmp_pow';
33 } else {
34 // PHP function
35 return 'pow';
39 /**
40 * Exponential expression / raise number into power
42 * @param string $base base to raise
43 * @param string $exp exponent to use
44 * @param string $use_function pow function to use, or false for auto-detect
46 * @return mixed string or float
48 public static function pow($base, $exp, $use_function = '')
50 static $pow_function = null;
52 if ($pow_function == null) {
53 $pow_function = self::detectPow();
56 if (! $use_function) {
57 if ($exp < 0) {
58 $use_function = 'pow';
59 } else {
60 $use_function = $pow_function;
64 if (($exp < 0) && ($use_function != 'pow')) {
65 return false;
68 switch ($use_function) {
69 case 'bcpow' :
70 // bcscale() needed for testing pow() with base values < 1
71 bcscale(10);
72 $pow = bcpow($base, $exp);
73 break;
74 case 'gmp_pow' :
75 $pow = gmp_strval(gmp_pow($base, $exp));
76 break;
77 case 'pow' :
78 $base = (float) $base;
79 $exp = (int) $exp;
80 $pow = pow($base, $exp);
81 break;
82 default:
83 $pow = $use_function($base, $exp);
86 return $pow;
89 /**
90 * Checks whether configuration value tells to show icons.
92 * @param string $value Configuration option name
94 * @return boolean Whether to show icons.
96 public static function showIcons($value)
98 return in_array($GLOBALS['cfg'][$value], array('icons', 'both'));
102 * Checks whether configuration value tells to show text.
104 * @param string $value Configuration option name
106 * @return boolean Whether to show text.
108 public static function showText($value)
110 return in_array($GLOBALS['cfg'][$value], array('text', 'both'));
114 * Returns an HTML IMG tag for a particular icon from a theme,
115 * which may be an actual file or an icon from a sprite.
116 * This function takes into account the ActionLinksMode
117 * configuration setting and wraps the image tag in a span tag.
119 * @param string $icon name of icon file
120 * @param string $alternate alternate text
121 * @param boolean $force_text whether to force alternate text to be displayed
122 * @param boolean $menu_icon whether this icon is for the menu bar or not
123 * @param string $control_param which directive controls the display
125 * @return string an html snippet
127 public static function getIcon(
128 $icon, $alternate = '', $force_text = false,
129 $menu_icon = false, $control_param = 'ActionLinksMode'
131 $include_icon = $include_text = false;
132 if (self::showIcons($control_param)) {
133 $include_icon = true;
135 if ($force_text
136 || self::showText($control_param)
138 $include_text = true;
140 // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
141 // we don't need a span
142 $button = $menu_icon ? '' : '<span class="nowrap">';
143 if ($include_icon) {
144 $button .= self::getImage($icon, $alternate);
146 if ($include_icon && $include_text) {
147 $button .= ' ';
149 if ($include_text) {
150 $button .= $alternate;
152 $button .= $menu_icon ? '' : '</span>';
154 return $button;
158 * Returns an HTML IMG tag for a particular image from a theme,
159 * which may be an actual file or an icon from a sprite
161 * @param string $image The name of the file to get
162 * @param string $alternate Used to set 'alt' and 'title' attributes
163 * of the image
164 * @param array $attributes An associative array of other attributes
166 * @return string an html IMG tag
168 public static function getImage($image, $alternate = '', $attributes = array())
170 static $sprites; // cached list of available sprites (if any)
171 if (defined('TESTSUITE')) {
172 // prevent caching in testsuite
173 unset($sprites);
176 $is_sprite = false;
177 $alternate = htmlspecialchars($alternate);
179 // If it's the first time this function is called
180 if (! isset($sprites)) {
181 // Try to load the list of sprites
182 $sprite_file = $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
183 if (is_readable($sprite_file)) {
184 include_once $sprite_file;
185 $sprites = PMA_sprites();
186 } else {
187 // No sprites are available for this theme
188 $sprites = array();
192 // Check if we have the requested image as a sprite
193 // and set $url accordingly
194 $class = str_replace(array('.gif','.png'), '', $image);
195 if (array_key_exists($class, $sprites)) {
196 $is_sprite = true;
197 $url = (defined('PMA_TEST_THEME') ? '../' : '') . 'themes/dot.gif';
198 } else {
199 $url = $GLOBALS['pmaThemeImage'] . $image;
202 // set class attribute
203 if ($is_sprite) {
204 if (isset($attributes['class'])) {
205 $attributes['class'] = "icon ic_$class " . $attributes['class'];
206 } else {
207 $attributes['class'] = "icon ic_$class";
211 // set all other attributes
212 $attr_str = '';
213 foreach ($attributes as $key => $value) {
214 if (! in_array($key, array('alt', 'title'))) {
215 $attr_str .= " $key=\"$value\"";
219 // override the alt attribute
220 if (isset($attributes['alt'])) {
221 $alt = $attributes['alt'];
222 } else {
223 $alt = $alternate;
226 // override the title attribute
227 if (isset($attributes['title'])) {
228 $title = $attributes['title'];
229 } else {
230 $title = $alternate;
233 // generate the IMG tag
234 $template = '<img src="%s" title="%s" alt="%s"%s />';
235 $retval = sprintf($template, $url, $title, $alt, $attr_str);
237 return $retval;
241 * Returns the formatted maximum size for an upload
243 * @param integer $max_upload_size the size
245 * @return string the message
247 * @access public
249 public static function getFormattedMaximumUploadSize($max_upload_size)
251 // I have to reduce the second parameter (sensitiveness) from 6 to 4
252 // to avoid weird results like 512 kKib
253 list($max_size, $max_unit) = self::formatByteDown($max_upload_size, 4);
254 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
258 * Generates a hidden field which should indicate to the browser
259 * the maximum size for upload
261 * @param integer $max_size the size
263 * @return string the INPUT field
265 * @access public
267 public static function generateHiddenMaxFileSize($max_size)
269 return '<input type="hidden" name="MAX_FILE_SIZE" value="'
270 . $max_size . '" />';
274 * Add slashes before "'" and "\" characters so a value containing them can
275 * be used in a sql comparison.
277 * @param string $a_string the string to slash
278 * @param bool $is_like whether the string will be used in a 'LIKE' clause
279 * (it then requires two more escaped sequences) or not
280 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
281 * (converts \n to \\n, \r to \\r)
282 * @param bool $php_code whether this function is used as part of the
283 * "Create PHP code" dialog
285 * @return string the slashed string
287 * @access public
289 public static function sqlAddSlashes(
290 $a_string = '', $is_like = false, $crlf = false, $php_code = false
292 if ($is_like) {
293 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
294 } else {
295 $a_string = str_replace('\\', '\\\\', $a_string);
298 if ($crlf) {
299 $a_string = strtr(
300 $a_string,
301 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
305 if ($php_code) {
306 $a_string = str_replace('\'', '\\\'', $a_string);
307 } else {
308 $a_string = str_replace('\'', '\'\'', $a_string);
311 return $a_string;
312 } // end of the 'sqlAddSlashes()' function
315 * Add slashes before "_" and "%" characters for using them in MySQL
316 * database, table and field names.
317 * Note: This function does not escape backslashes!
319 * @param string $name the string to escape
321 * @return string the escaped string
323 * @access public
325 public static function escapeMysqlWildcards($name)
327 return strtr($name, array('_' => '\\_', '%' => '\\%'));
328 } // end of the 'escapeMysqlWildcards()' function
331 * removes slashes before "_" and "%" characters
332 * Note: This function does not unescape backslashes!
334 * @param string $name the string to escape
336 * @return string the escaped string
338 * @access public
340 public static function unescapeMysqlWildcards($name)
342 return strtr($name, array('\\_' => '_', '\\%' => '%'));
343 } // end of the 'unescapeMysqlWildcards()' function
346 * removes quotes (',",`) from a quoted string
348 * checks if the string is quoted and removes this quotes
350 * @param string $quoted_string string to remove quotes from
351 * @param string $quote type of quote to remove
353 * @return string unqoted string
355 public static function unQuote($quoted_string, $quote = null)
357 $quotes = array();
359 if ($quote === null) {
360 $quotes[] = '`';
361 $quotes[] = '"';
362 $quotes[] = "'";
363 } else {
364 $quotes[] = $quote;
367 foreach ($quotes as $quote) {
368 if (/*overload*/mb_substr($quoted_string, 0, 1) === $quote
369 && /*overload*/mb_substr($quoted_string, -1, 1) === $quote
371 $unquoted_string = /*overload*/mb_substr($quoted_string, 1, -1);
372 // replace escaped quotes
373 $unquoted_string = str_replace(
374 $quote . $quote,
375 $quote,
376 $unquoted_string
378 return $unquoted_string;
382 return $quoted_string;
386 * format sql strings
388 * @param string $sqlQuery raw SQL string
389 * @param boolean $truncate truncate the query if it is too long
391 * @return string the formatted sql
393 * @global array $cfg the configuration array
395 * @access public
396 * @todo move into PMA_Sql
398 public static function formatSql($sqlQuery, $truncate = false)
400 global $cfg;
402 if ($truncate
403 && /*overload*/mb_strlen($sqlQuery) > $cfg['MaxCharactersInDisplayedSQL']
405 $sqlQuery = /*overload*/mb_substr(
406 $sqlQuery,
408 $cfg['MaxCharactersInDisplayedSQL']
409 ) . '[...]';
411 return '<code class="sql"><pre>' . "\n"
412 . htmlspecialchars($sqlQuery) . "\n"
413 . '</pre></code>';
414 } // end of the "formatSql()" function
417 * Displays a link to the documentation as an icon
419 * @param string $link documentation link
420 * @param string $target optional link target
422 * @return string the html link
424 * @access public
426 public static function showDocLink($link, $target = 'documentation')
428 return '<a href="' . $link . '" target="' . $target . '">'
429 . self::getImage('b_help.png', __('Documentation'))
430 . '</a>';
431 } // end of the 'showDocLink()' function
434 * Get a URL link to the official MySQL documentation
436 * @param string $link contains name of page/anchor that is being linked
437 * @param string $anchor anchor to page part
439 * @return string the URL link
441 * @access public
443 public static function getMySQLDocuURL($link, $anchor = '')
445 // Fixup for newly used names:
446 $link = str_replace('_', '-', /*overload*/mb_strtolower($link));
448 if (empty($link)) {
449 $link = 'index';
451 $mysql = '5.5';
452 $lang = 'en';
453 if (defined('PMA_MYSQL_INT_VERSION')) {
454 if (PMA_MYSQL_INT_VERSION >= 50600) {
455 $mysql = '5.6';
456 } else if (PMA_MYSQL_INT_VERSION >= 50500) {
457 $mysql = '5.5';
460 $url = 'http://dev.mysql.com/doc/refman/'
461 . $mysql . '/' . $lang . '/' . $link . '.html';
462 if (! empty($anchor)) {
463 $url .= '#' . $anchor;
466 return PMA_linkURL($url);
470 * Displays a link to the official MySQL documentation
472 * @param string $link contains name of page/anchor that is being linked
473 * @param bool $big_icon whether to use big icon (like in left frame)
474 * @param string $anchor anchor to page part
475 * @param bool $just_open whether only the opening <a> tag should be returned
477 * @return string the html link
479 * @access public
481 public static function showMySQLDocu(
482 $link, $big_icon = false, $anchor = '', $just_open = false
484 $url = self::getMySQLDocuURL($link, $anchor);
485 $open_link = '<a href="' . $url . '" target="mysql_doc">';
486 if ($just_open) {
487 return $open_link;
488 } elseif ($big_icon) {
489 return $open_link
490 . self::getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
491 } else {
492 return self::showDocLink($url, 'mysql_doc');
494 } // end of the 'showMySQLDocu()' function
497 * Returns link to documentation.
499 * @param string $page Page in documentation
500 * @param string $anchor Optional anchor in page
502 * @return string URL
504 public static function getDocuLink($page, $anchor = '')
506 /* Construct base URL */
507 $url = $page . '.html';
508 if (!empty($anchor)) {
509 $url .= '#' . $anchor;
512 /* Check if we have built local documentation */
513 if (defined('TESTSUITE')) {
514 /* Provide consistent URL for testsuite */
515 return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
516 } else if (file_exists('doc/html/index.html')) {
517 if (defined('PMA_SETUP')) {
518 return '../doc/html/' . $url;
519 } else {
520 return './doc/html/' . $url;
522 } else {
523 /* TODO: Should link to correct branch for released versions */
524 return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
529 * Displays a link to the phpMyAdmin documentation
531 * @param string $page Page in documentation
532 * @param string $anchor Optional anchor in page
534 * @return string the html link
536 * @access public
538 public static function showDocu($page, $anchor = '')
540 return self::showDocLink(self::getDocuLink($page, $anchor));
541 } // end of the 'showDocu()' function
544 * Displays a link to the PHP documentation
546 * @param string $target anchor in documentation
548 * @return string the html link
550 * @access public
552 public static function showPHPDocu($target)
554 $url = PMA_getPHPDocLink($target);
556 return self::showDocLink($url);
557 } // end of the 'showPHPDocu()' function
560 * Returns HTML code for a tooltip
562 * @param string $message the message for the tooltip
564 * @return string
566 * @access public
568 public static function showHint($message)
570 if ($GLOBALS['cfg']['ShowHint']) {
571 $classClause = ' class="pma_hint"';
572 } else {
573 $classClause = '';
575 return '<span' . $classClause . '>'
576 . self::getImage('b_help.png')
577 . '<span class="hide">' . $message . '</span>'
578 . '</span>';
582 * Displays a MySQL error message in the main panel when $exit is true.
583 * Returns the error message otherwise.
585 * @param string|bool $error_message the error message
586 * @param string $the_query the sql query that failed
587 * @param bool $is_modify_link whether to show a "modify" link or not
588 * @param string $back_url the "back" link url (full path is not
589 * required)
590 * @param bool $exit EXIT the page?
592 * @return string
594 * @global string $table the curent table
595 * @global string $db the current db
597 * @access public
599 public static function mysqlDie(
600 $error_message = '', $the_query = '',
601 $is_modify_link = true, $back_url = '', $exit = true
603 global $table, $db;
605 $error_msg = '';
607 if (! $error_message) {
608 $error_message = $GLOBALS['dbi']->getError();
610 if (! $the_query && ! empty($GLOBALS['sql_query'])) {
611 $the_query = $GLOBALS['sql_query'];
614 // --- Added to solve bug #641765
615 if (! function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
616 $formatted_sql = htmlspecialchars($the_query);
617 } elseif (empty($the_query) || (trim($the_query) == '')) {
618 $formatted_sql = '';
619 } else {
620 $formatted_sql = self::formatSql($the_query, true);
622 // ---
623 $error_msg .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
624 $error_msg .= ' <div class="error"><h1>' . __('Error')
625 . '</h1>' . "\n";
627 // if the config password is wrong, or the MySQL server does not
628 // respond, do not show the query that would reveal the
629 // username/password
630 if (! empty($the_query) && ! /*overload*/mb_strstr($the_query, 'connect')) {
631 // --- Added to solve bug #641765
632 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
633 $error_msg .= PMA_SQP_getErrorString() . "\n";
634 $error_msg .= '<br />' . "\n";
636 // ---
637 // modified to show the help on sql errors
638 $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
639 $formattedSqlToLower = /*overload*/mb_strtolower($formatted_sql);
640 if (/*overload*/mb_strstr($formattedSqlToLower, 'select')) {
641 // please show me help to the error on select
642 $error_msg .= self::showMySQLDocu('SELECT');
644 if ($is_modify_link) {
645 $_url_params = array(
646 'sql_query' => $the_query,
647 'show_query' => 1,
649 if (/*overload*/mb_strlen($table)) {
650 $_url_params['db'] = $db;
651 $_url_params['table'] = $table;
652 $doedit_goto = '<a href="tbl_sql.php'
653 . PMA_URL_getCommon($_url_params) . '">';
654 } elseif (/*overload*/mb_strlen($db)) {
655 $_url_params['db'] = $db;
656 $doedit_goto = '<a href="db_sql.php'
657 . PMA_URL_getCommon($_url_params) . '">';
658 } else {
659 $doedit_goto = '<a href="server_sql.php'
660 . PMA_URL_getCommon($_url_params) . '">';
663 $error_msg .= $doedit_goto
664 . self::getIcon('b_edit.png', __('Edit'))
665 . '</a>';
666 } // end if
667 $error_msg .= ' </p>' . "\n"
668 . '<p>' . "\n"
669 . $formatted_sql . "\n"
670 . '</p>' . "\n";
671 } // end if
673 if (! empty($error_message)) {
674 $error_message = preg_replace(
675 "@((\015\012)|(\015)|(\012)){3,}@",
676 "\n\n",
677 $error_message
680 // modified to show the help on error-returns
681 // (now error-messages-server)
682 $error_msg .= '<p>' . "\n"
683 . ' <strong>' . __('MySQL said: ') . '</strong>'
684 . self::showMySQLDocu('Error-messages-server')
685 . "\n"
686 . '</p>' . "\n";
688 // The error message will be displayed within a CODE segment.
689 // To preserve original formatting, but allow wordwrapping,
690 // we do a couple of replacements
692 // Replace all non-single blanks with their HTML-counterpart
693 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
694 // Replace TAB-characters with their HTML-counterpart
695 $error_message = str_replace(
696 "\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message
698 // Replace line breaks
699 $error_message = nl2br($error_message);
701 $error_msg .= '<code>' . "\n"
702 . $error_message . "\n"
703 . '</code><br />' . "\n";
704 $error_msg .= '</div>';
706 $_SESSION['Import_message']['message'] = $error_msg;
708 if (!$exit) {
709 return $error_msg;
713 * If in an Ajax request
714 * - avoid displaying a Back link
715 * - use PMA_Response() to transmit the message and exit
717 if (isset($GLOBALS['is_ajax_request'])
718 && $GLOBALS['is_ajax_request'] == true
720 $response = PMA_Response::getInstance();
721 $response->isSuccess(false);
722 $response->addJSON('message', $error_msg);
723 exit;
725 if (! empty($back_url)) {
726 if (/*overload*/mb_strstr($back_url, '?')) {
727 $back_url .= '&amp;no_history=true';
728 } else {
729 $back_url .= '?no_history=true';
732 $_SESSION['Import_message']['go_back_url'] = $back_url;
734 $error_msg .= '<fieldset class="tblFooters">'
735 . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
736 . '</fieldset>' . "\n\n";
738 echo $error_msg;
739 exit;
740 } // end of the 'mysqlDie()' function
743 * returns array with tables of given db with extended information and grouped
745 * @param string $db name of db
746 * @param string $tables name of tables
747 * @param integer $limit_offset list offset
748 * @param int|bool $limit_count max tables to return
750 * @return array (recursive) grouped table list
752 public static function getTableList(
753 $db, $tables = null, $limit_offset = 0, $limit_count = false
755 $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
757 if ($tables === null) {
758 $tables = $GLOBALS['dbi']->getTablesFull(
759 $db, '', false, null, $limit_offset, $limit_count
761 if ($GLOBALS['cfg']['NaturalOrder']) {
762 uksort($tables, 'strnatcasecmp');
766 if (count($tables) < 1) {
767 return $tables;
770 $default = array(
771 'Name' => '',
772 'Rows' => 0,
773 'Comment' => '',
774 'disp_name' => '',
777 $table_groups = array();
779 foreach ($tables as $table_name => $table) {
780 // check for correct row count
781 if ($table['Rows'] === null) {
782 // Do not check exact row count here,
783 // if row count is invalid possibly the table is defect
784 // and this would break left frame;
785 // but we can check row count if this is a view or the
786 // information_schema database
787 // since PMA_Table::countRecords() returns a limited row count
788 // in this case.
790 // set this because PMA_Table::countRecords() can use it
791 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
793 if ($tbl_is_view || $GLOBALS['dbi']->isSystemSchema($db)) {
794 $table['Rows'] = PMA_Table::countRecords(
795 $db,
796 $table['Name'],
797 false,
798 true
803 // in $group we save the reference to the place in $table_groups
804 // where to store the table info
805 if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
806 && $sep && /*overload*/mb_strstr($table_name, $sep)
808 $parts = explode($sep, $table_name);
810 $group =& $table_groups;
811 $i = 0;
812 $group_name_full = '';
813 $parts_cnt = count($parts) - 1;
815 while (($i < $parts_cnt)
816 && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
818 $group_name = $parts[$i] . $sep;
819 $group_name_full .= $group_name;
821 if (! isset($group[$group_name])) {
822 $group[$group_name] = array();
823 $group[$group_name]['is' . $sep . 'group'] = true;
824 $group[$group_name]['tab' . $sep . 'count'] = 1;
825 $group[$group_name]['tab' . $sep . 'group']
826 = $group_name_full;
828 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
829 $table = $group[$group_name];
830 $group[$group_name] = array();
831 $group[$group_name][$group_name] = $table;
832 unset($table);
833 $group[$group_name]['is' . $sep . 'group'] = true;
834 $group[$group_name]['tab' . $sep . 'count'] = 1;
835 $group[$group_name]['tab' . $sep . 'group']
836 = $group_name_full;
838 } else {
839 $group[$group_name]['tab' . $sep . 'count']++;
842 $group =& $group[$group_name];
843 $i++;
846 } else {
847 if (! isset($table_groups[$table_name])) {
848 $table_groups[$table_name] = array();
850 $group =& $table_groups;
853 $table['disp_name'] = $table['Name'];
854 $group[$table_name] = array_merge($default, $table);
857 return $table_groups;
860 /* ----------------------- Set of misc functions ----------------------- */
863 * Adds backquotes on both sides of a database, table or field name.
864 * and escapes backquotes inside the name with another backquote
866 * example:
867 * <code>
868 * echo backquote('owner`s db'); // `owner``s db`
870 * </code>
872 * @param mixed $a_name the database, table or field name to "backquote"
873 * or array of it
874 * @param boolean $do_it a flag to bypass this function (used by dump
875 * functions)
877 * @return mixed the "backquoted" database, table or field name
879 * @access public
881 public static function backquote($a_name, $do_it = true)
883 if (is_array($a_name)) {
884 foreach ($a_name as &$data) {
885 $data = self::backquote($data, $do_it);
887 return $a_name;
890 if (! $do_it) {
891 global $PMA_SQPdata_forbidden_word;
892 $eltNameUpper = /*overload*/mb_strtoupper($a_name);
893 if (!in_array($eltNameUpper, $PMA_SQPdata_forbidden_word)) {
894 return $a_name;
898 // '0' is also empty for php :-(
899 if (/*overload*/mb_strlen($a_name) && $a_name !== '*') {
900 return '`' . str_replace('`', '``', $a_name) . '`';
901 } else {
902 return $a_name;
904 } // end of the 'backquote()' function
907 * Adds backquotes on both sides of a database, table or field name.
908 * in compatibility mode
910 * example:
911 * <code>
912 * echo backquoteCompat('owner`s db'); // `owner``s db`
914 * </code>
916 * @param mixed $a_name the database, table or field name to
917 * "backquote" or array of it
918 * @param string $compatibility string compatibility mode (used by dump
919 * functions)
920 * @param boolean $do_it a flag to bypass this function (used by dump
921 * functions)
923 * @return mixed the "backquoted" database, table or field name
925 * @access public
927 public static function backquoteCompat(
928 $a_name, $compatibility = 'MSSQL', $do_it = true
930 if (is_array($a_name)) {
931 foreach ($a_name as &$data) {
932 $data = self::backquoteCompat($data, $compatibility, $do_it);
934 return $a_name;
937 if (! $do_it) {
938 global $PMA_SQPdata_forbidden_word;
939 $eltNameUpper = /*overload*/mb_strtoupper($a_name);
940 if (!in_array($eltNameUpper, $PMA_SQPdata_forbidden_word)) {
941 return $a_name;
945 // @todo add more compatibility cases (ORACLE for example)
946 switch ($compatibility) {
947 case 'MSSQL':
948 $quote = '"';
949 break;
950 default:
951 $quote = "`";
952 break;
955 // '0' is also empty for php :-(
956 if (/*overload*/mb_strlen($a_name) && $a_name !== '*') {
957 return $quote . $a_name . $quote;
958 } else {
959 return $a_name;
961 } // end of the 'backquoteCompat()' function
964 * Defines the <CR><LF> value depending on the user OS.
966 * @return string the <CR><LF> value to use
968 * @access public
970 public static function whichCrlf()
972 // The 'PMA_USR_OS' constant is defined in "libraries/Config.class.php"
973 // Win case
974 if (PMA_USR_OS == 'Win') {
975 $the_crlf = "\r\n";
976 } else {
977 // Others
978 $the_crlf = "\n";
981 return $the_crlf;
982 } // end of the 'whichCrlf()' function
985 * Prepare the message and the query
986 * usually the message is the result of the query executed
988 * @param string $message the message to display
989 * @param string $sql_query the query to display
990 * @param string $type the type (level) of the message
992 * @return string
994 * @access public
996 public static function getMessage(
997 $message, $sql_query = null, $type = 'notice'
999 global $cfg;
1000 $retval = '';
1002 if (null === $sql_query) {
1003 if (! empty($GLOBALS['display_query'])) {
1004 $sql_query = $GLOBALS['display_query'];
1005 } elseif (! empty($GLOBALS['unparsed_sql'])) {
1006 $sql_query = $GLOBALS['unparsed_sql'];
1007 } elseif (! empty($GLOBALS['sql_query'])) {
1008 $sql_query = $GLOBALS['sql_query'];
1009 } else {
1010 $sql_query = '';
1014 if (isset($GLOBALS['using_bookmark_message'])) {
1015 $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
1016 unset($GLOBALS['using_bookmark_message']);
1019 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1020 // check for it's presence before using it
1021 $retval .= '<div class="result_query"'
1022 . ( isset($GLOBALS['cell_align_left'])
1023 ? ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"'
1024 : '' )
1025 . '>' . "\n";
1027 if ($message instanceof PMA_Message) {
1028 if (isset($GLOBALS['special_message'])) {
1029 $message->addMessage($GLOBALS['special_message']);
1030 unset($GLOBALS['special_message']);
1032 $retval .= $message->getDisplay();
1033 } else {
1034 $retval .= '<div class="' . $type . '">';
1035 $retval .= PMA_sanitize($message);
1036 if (isset($GLOBALS['special_message'])) {
1037 $retval .= PMA_sanitize($GLOBALS['special_message']);
1038 unset($GLOBALS['special_message']);
1040 $retval .= '</div>';
1043 if ($cfg['ShowSQL'] == true && ! empty($sql_query) && $sql_query !== ';') {
1044 // Html format the query to be displayed
1045 // If we want to show some sql code it is easiest to create it here
1046 /* SQL-Parser-Analyzer */
1048 if (! empty($GLOBALS['show_as_php'])) {
1049 $new_line = '\\n"<br />' . "\n"
1050 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1051 $query_base = htmlspecialchars(addslashes($sql_query));
1052 $query_base = preg_replace(
1053 '/((\015\012)|(\015)|(\012))/', $new_line, $query_base
1055 } else {
1056 $query_base = $sql_query;
1059 $query_too_big = false;
1061 $queryLength = /*overload*/mb_strlen($query_base);
1062 if ($queryLength > $cfg['MaxCharactersInDisplayedSQL']) {
1063 // when the query is large (for example an INSERT of binary
1064 // data), the parser chokes; so avoid parsing the query
1065 $query_too_big = true;
1066 $shortened_query_base = nl2br(
1067 htmlspecialchars(
1068 /*overload*/mb_substr(
1069 $sql_query,
1071 $cfg['MaxCharactersInDisplayedSQL']
1072 ) . '[...]'
1075 } elseif (! empty($GLOBALS['parsed_sql'])
1076 && $query_base == $GLOBALS['parsed_sql']['raw']
1078 // (here, use "! empty" because when deleting a bookmark,
1079 // $GLOBALS['parsed_sql'] is set but empty
1080 $parsed_sql = $GLOBALS['parsed_sql'];
1081 } else {
1082 // Parse SQL if needed
1083 $parsed_sql = PMA_SQP_parse($query_base);
1086 // Analyze it
1087 if (isset($parsed_sql) && ! PMA_SQP_isError()) {
1088 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1090 // Same as below (append LIMIT), append the remembered ORDER BY
1091 if ($GLOBALS['cfg']['RememberSorting']
1092 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1093 && isset($GLOBALS['sql_order_to_append'])
1095 $query_base = $analyzed_display_query[0]['section_before_limit']
1096 . "\n" . $GLOBALS['sql_order_to_append']
1097 . $analyzed_display_query[0]['limit_clause'] . ' '
1098 . $analyzed_display_query[0]['section_after_limit'];
1099 // update the $analyzed_display_query
1100 $analyzed_display_query[0]['section_before_limit']
1101 .= $GLOBALS['sql_order_to_append'];
1102 $analyzed_display_query[0]['order_by_clause']
1103 = $GLOBALS['sorted_col'];
1106 // Here we append the LIMIT added for navigation, to
1107 // enable its display. Adding it higher in the code
1108 // to $sql_query would create a problem when
1109 // using the Refresh or Edit links.
1111 // Only append it on SELECTs.
1114 * @todo what would be the best to do when someone hits Refresh:
1115 * use the current LIMITs ?
1118 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1119 && ! empty($GLOBALS['sql_limit_to_append'])
1121 $query_base = $analyzed_display_query[0]['section_before_limit']
1122 . "\n" . $GLOBALS['sql_limit_to_append']
1123 . $analyzed_display_query[0]['section_after_limit'];
1127 if (! empty($GLOBALS['show_as_php'])) {
1128 $query_base = '$sql = "' . $query_base;
1129 } elseif (isset($query_base)) {
1130 $query_base = self::formatSql($query_base);
1133 // Prepares links that may be displayed to edit/explain the query
1134 // (don't go to default pages, we must go to the page
1135 // where the query box is available)
1137 // Basic url query part
1138 $url_params = array();
1139 if (! isset($GLOBALS['db'])) {
1140 $GLOBALS['db'] = '';
1142 if (/*overload*/mb_strlen($GLOBALS['db'])) {
1143 $url_params['db'] = $GLOBALS['db'];
1144 if (/*overload*/mb_strlen($GLOBALS['table'])) {
1145 $url_params['table'] = $GLOBALS['table'];
1146 $edit_link = 'tbl_sql.php';
1147 } else {
1148 $edit_link = 'db_sql.php';
1150 } else {
1151 $edit_link = 'server_sql.php';
1154 // Want to have the query explained
1155 // but only explain a SELECT (that has not been explained)
1156 /* SQL-Parser-Analyzer */
1157 $explain_link = '';
1158 $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
1159 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1160 $explain_params = $url_params;
1161 if ($is_select) {
1162 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1163 $_message = __('Explain SQL');
1164 } elseif (preg_match(
1165 '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query
1166 )) {
1167 $explain_params['sql_query']
1168 = /*overload*/mb_substr($sql_query, 8);
1169 $_message = __('Skip Explain SQL');
1171 if (isset($explain_params['sql_query']) && isset($_message)) {
1172 $explain_link = ' ['
1173 . self::linkOrButton(
1174 'import.php' . PMA_URL_getCommon($explain_params),
1175 $_message
1176 ) . ']';
1178 } //show explain
1180 $url_params['sql_query'] = $sql_query;
1181 $url_params['show_query'] = 1;
1183 // even if the query is big and was truncated, offer the chance
1184 // to edit it (unless it's enormous, see linkOrButton() )
1185 if (! empty($cfg['SQLQuery']['Edit'])) {
1186 $edit_link .= PMA_URL_getCommon($url_params) . '#querybox';
1187 $edit_link = ' ['
1188 . self::linkOrButton(
1189 $edit_link, __('Edit')
1191 . ']';
1192 } else {
1193 $edit_link = '';
1196 // Also we would like to get the SQL formed in some nice
1197 // php-code
1198 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1199 $php_params = $url_params;
1201 if (! empty($GLOBALS['show_as_php'])) {
1202 $_message = __('Without PHP Code');
1203 } else {
1204 $php_params['show_as_php'] = 1;
1205 $_message = __('Create PHP Code');
1208 $php_link = 'import.php' . PMA_URL_getCommon($php_params);
1209 $php_link = ' [' . self::linkOrButton($php_link, $_message) . ']';
1211 if (isset($GLOBALS['show_as_php'])) {
1213 $runquery_link = 'import.php'
1214 . PMA_URL_getCommon($url_params);
1216 $php_link .= ' ['
1217 . self::linkOrButton($runquery_link, __('Submit Query'))
1218 . ']';
1220 } else {
1221 $php_link = '';
1222 } //show as php
1224 // Refresh query
1225 if (! empty($cfg['SQLQuery']['Refresh'])
1226 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1227 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1229 $refresh_link = 'import.php' . PMA_URL_getCommon($url_params);
1230 $refresh_link = ' ['
1231 . self::linkOrButton($refresh_link, __('Refresh')) . ']';
1232 } else {
1233 $refresh_link = '';
1234 } //refresh
1236 $retval .= '<div class="sqlOuter">';
1237 if ($query_too_big) {
1238 $retval .= $shortened_query_base;
1239 } else {
1240 $retval .= $query_base;
1243 //Clean up the end of the PHP
1244 if (! empty($GLOBALS['show_as_php'])) {
1245 $retval .= '";';
1247 $retval .= '</div>';
1249 $retval .= '<div class="tools">';
1250 $retval .= '<form action="sql.php" method="post">';
1251 $retval .= PMA_URL_getHiddenInputs(
1252 $GLOBALS['db'], $GLOBALS['table']
1254 $retval .= '<input type="hidden" name="sql_query" value="'
1255 . htmlspecialchars($sql_query) . '" />';
1257 // avoid displaying a Profiling checkbox that could
1258 // be checked, which would reexecute an INSERT, for example
1259 if (! empty($refresh_link) && self::profilingSupported()) {
1260 $retval .= '<input type="hidden" name="profiling_form" value="1" />';
1261 $retval .= self::getCheckbox(
1262 'profiling', __('Profiling'), isset($_SESSION['profiling']), true
1265 $retval .= '</form>';
1268 * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
1270 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1271 $inline_edit_link = ' ['
1272 . self::linkOrButton(
1273 '#',
1274 _pgettext('Inline edit query', 'Edit inline'),
1275 array('class' => 'inline_edit_sql')
1277 . ']';
1278 } else {
1279 $inline_edit_link = '';
1281 $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link
1282 . $refresh_link;
1283 $retval .= '</div>';
1286 $retval .= '</div>';
1287 if ($GLOBALS['is_ajax_request'] === false) {
1288 $retval .= '<br class="clearfloat" />';
1291 return $retval;
1292 } // end of the 'getMessage()' function
1295 * Verifies if current MySQL server supports profiling
1297 * @access public
1299 * @return boolean whether profiling is supported
1301 public static function profilingSupported()
1303 if (!self::cacheExists('profiling_supported')) {
1304 // 5.0.37 has profiling but for example, 5.1.20 does not
1305 // (avoid a trip to the server for MySQL before 5.0.37)
1306 // and do not set a constant as we might be switching servers
1307 if (defined('PMA_MYSQL_INT_VERSION')
1308 && $GLOBALS['dbi']->fetchValue("SHOW VARIABLES LIKE 'profiling'")
1310 self::cacheSet('profiling_supported', true);
1311 } else {
1312 self::cacheSet('profiling_supported', false);
1316 return self::cacheGet('profiling_supported');
1320 * Formats $value to byte view
1322 * @param double|int $value the value to format
1323 * @param int $limes the sensitiveness
1324 * @param int $comma the number of decimals to retain
1326 * @return array the formatted value and its unit
1328 * @access public
1330 public static function formatByteDown($value, $limes = 6, $comma = 0)
1332 if ($value === null) {
1333 return null;
1336 $byteUnits = array(
1337 /* l10n: shortcuts for Byte */
1338 __('B'),
1339 /* l10n: shortcuts for Kilobyte */
1340 __('KiB'),
1341 /* l10n: shortcuts for Megabyte */
1342 __('MiB'),
1343 /* l10n: shortcuts for Gigabyte */
1344 __('GiB'),
1345 /* l10n: shortcuts for Terabyte */
1346 __('TiB'),
1347 /* l10n: shortcuts for Petabyte */
1348 __('PiB'),
1349 /* l10n: shortcuts for Exabyte */
1350 __('EiB')
1353 $dh = self::pow(10, $comma);
1354 $li = self::pow(10, $limes);
1355 $unit = $byteUnits[0];
1357 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1358 // cast to float to avoid overflow
1359 $unitSize = (float) $li * self::pow(10, $ex);
1360 if (isset($byteUnits[$d]) && $value >= $unitSize) {
1361 // use 1024.0 to avoid integer overflow on 64-bit machines
1362 $value = round($value / (self::pow(1024, $d) / $dh)) /$dh;
1363 $unit = $byteUnits[$d];
1364 break 1;
1365 } // end if
1366 } // end for
1368 if ($unit != $byteUnits[0]) {
1369 // if the unit is not bytes (as represented in current language)
1370 // reformat with max length of 5
1371 // 4th parameter=true means do not reformat if value < 1
1372 $return_value = self::formatNumber($value, 5, $comma, true);
1373 } else {
1374 // do not reformat, just handle the locale
1375 $return_value = self::formatNumber($value, 0);
1378 return array(trim($return_value), $unit);
1379 } // end of the 'formatByteDown' function
1382 * Changes thousands and decimal separators to locale specific values.
1384 * @param string $value the value
1386 * @return string
1388 public static function localizeNumber($value)
1390 return str_replace(
1391 array(',', '.'),
1392 array(
1393 /* l10n: Thousands separator */
1394 __(','),
1395 /* l10n: Decimal separator */
1396 __('.'),
1398 $value
1403 * Formats $value to the given length and appends SI prefixes
1404 * with a $length of 0 no truncation occurs, number is only formatted
1405 * to the current locale
1407 * examples:
1408 * <code>
1409 * echo formatNumber(123456789, 6); // 123,457 k
1410 * echo formatNumber(-123456789, 4, 2); // -123.46 M
1411 * echo formatNumber(-0.003, 6); // -3 m
1412 * echo formatNumber(0.003, 3, 3); // 0.003
1413 * echo formatNumber(0.00003, 3, 2); // 0.03 m
1414 * echo formatNumber(0, 6); // 0
1415 * </code>
1417 * @param double $value the value to format
1418 * @param integer $digits_left number of digits left of the comma
1419 * @param integer $digits_right number of digits right of the comma
1420 * @param boolean $only_down do not reformat numbers below 1
1421 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1422 * (default: true)
1424 * @return string the formatted value and its unit
1426 * @access public
1428 public static function formatNumber(
1429 $value, $digits_left = 3, $digits_right = 0,
1430 $only_down = false, $noTrailingZero = true
1432 if ($value == 0) {
1433 return '0';
1436 $originalValue = $value;
1437 //number_format is not multibyte safe, str_replace is safe
1438 if ($digits_left === 0) {
1439 $value = number_format($value, $digits_right);
1440 if (($originalValue != 0) && (floatval($value) == 0)) {
1441 $value = ' <' . (1 / self::pow(10, $digits_right));
1443 return self::localizeNumber($value);
1446 // this units needs no translation, ISO
1447 $units = array(
1448 -8 => 'y',
1449 -7 => 'z',
1450 -6 => 'a',
1451 -5 => 'f',
1452 -4 => 'p',
1453 -3 => 'n',
1454 -2 => '&micro;',
1455 -1 => 'm',
1456 0 => ' ',
1457 1 => 'k',
1458 2 => 'M',
1459 3 => 'G',
1460 4 => 'T',
1461 5 => 'P',
1462 6 => 'E',
1463 7 => 'Z',
1464 8 => 'Y'
1467 // check for negative value to retain sign
1468 if ($value < 0) {
1469 $sign = '-';
1470 $value = abs($value);
1471 } else {
1472 $sign = '';
1475 $dh = self::pow(10, $digits_right);
1478 * This gives us the right SI prefix already,
1479 * but $digits_left parameter not incorporated
1481 $d = floor(log10($value) / 3);
1483 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1484 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1485 * to use, then lower the SI prefix
1487 $cur_digits = floor(log10($value / self::pow(1000, $d, 'pow'))+1);
1488 if ($digits_left > $cur_digits) {
1489 $d -= floor(($digits_left - $cur_digits)/3);
1492 if ($d < 0 && $only_down) {
1493 $d = 0;
1496 $value = round($value / (self::pow(1000, $d, 'pow') / $dh)) /$dh;
1497 $unit = $units[$d];
1499 // If we don't want any zeros after the comma just add the thousand separator
1500 if ($noTrailingZero) {
1501 $localizedValue = self::localizeNumber(
1502 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1504 } else {
1505 //number_format is not multibyte safe, str_replace is safe
1506 $localizedValue = self::localizeNumber(number_format($value, $digits_right));
1509 if ($originalValue != 0 && floatval($value) == 0) {
1510 return ' <' . self::localizeNumber((1 / self::pow(10, $digits_right))) . ' ' . $unit;
1513 return $sign . $localizedValue . ' ' . $unit;
1514 } // end of the 'formatNumber' function
1517 * Returns the number of bytes when a formatted size is given
1519 * @param string $formatted_size the size expression (for example 8MB)
1521 * @return integer The numerical part of the expression (for example 8)
1523 public static function extractValueFromFormattedSize($formatted_size)
1525 $return_value = -1;
1527 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1528 $return_value = /*overload*/mb_substr($formatted_size, 0, -2)
1529 * self::pow(1024, 3);
1530 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1531 $return_value = /*overload*/mb_substr($formatted_size, 0, -2)
1532 * self::pow(1024, 2);
1533 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1534 $return_value = /*overload*/mb_substr($formatted_size, 0, -1)
1535 * self::pow(1024, 1);
1537 return $return_value;
1538 }// end of the 'extractValueFromFormattedSize' function
1541 * Writes localised date
1543 * @param integer $timestamp the current timestamp
1544 * @param string $format format
1546 * @return string the formatted date
1548 * @access public
1550 public static function localisedDate($timestamp = -1, $format = '')
1552 $month = array(
1553 /* l10n: Short month name */
1554 __('Jan'),
1555 /* l10n: Short month name */
1556 __('Feb'),
1557 /* l10n: Short month name */
1558 __('Mar'),
1559 /* l10n: Short month name */
1560 __('Apr'),
1561 /* l10n: Short month name */
1562 _pgettext('Short month name', 'May'),
1563 /* l10n: Short month name */
1564 __('Jun'),
1565 /* l10n: Short month name */
1566 __('Jul'),
1567 /* l10n: Short month name */
1568 __('Aug'),
1569 /* l10n: Short month name */
1570 __('Sep'),
1571 /* l10n: Short month name */
1572 __('Oct'),
1573 /* l10n: Short month name */
1574 __('Nov'),
1575 /* l10n: Short month name */
1576 __('Dec'));
1577 $day_of_week = array(
1578 /* l10n: Short week day name */
1579 _pgettext('Short week day name', 'Sun'),
1580 /* l10n: Short week day name */
1581 __('Mon'),
1582 /* l10n: Short week day name */
1583 __('Tue'),
1584 /* l10n: Short week day name */
1585 __('Wed'),
1586 /* l10n: Short week day name */
1587 __('Thu'),
1588 /* l10n: Short week day name */
1589 __('Fri'),
1590 /* l10n: Short week day name */
1591 __('Sat'));
1593 if ($format == '') {
1594 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1595 $format = __('%B %d, %Y at %I:%M %p');
1598 if ($timestamp == -1) {
1599 $timestamp = time();
1602 $date = preg_replace(
1603 '@%[aA]@',
1604 $day_of_week[(int)strftime('%w', $timestamp)],
1605 $format
1607 $date = preg_replace(
1608 '@%[bB]@',
1609 $month[(int)strftime('%m', $timestamp)-1],
1610 $date
1613 $ret = strftime($date, $timestamp);
1614 // Some OSes such as Win8.1 Traditional Chinese version did not produce UTF-8
1615 // output here. See https://sourceforge.net/p/phpmyadmin/bugs/4207/
1616 if (mb_detect_encoding($ret, 'UTF-8', true) != 'UTF-8') {
1617 $ret = date('Y-m-d H:i:s', $timestamp);
1620 return $ret;
1621 } // end of the 'localisedDate()' function
1624 * returns a tab for tabbed navigation.
1625 * If the variables $link and $args ar left empty, an inactive tab is created
1627 * @param array $tab array with all options
1628 * @param array $url_params tab specific URL parameters
1630 * @return string html code for one tab, a link if valid otherwise a span
1632 * @access public
1634 public static function getHtmlTab($tab, $url_params = array())
1636 // default values
1637 $defaults = array(
1638 'text' => '',
1639 'class' => '',
1640 'active' => null,
1641 'link' => '',
1642 'sep' => '?',
1643 'attr' => '',
1644 'args' => '',
1645 'warning' => '',
1646 'fragment' => '',
1647 'id' => '',
1650 $tab = array_merge($defaults, $tab);
1652 // determine additional style-class
1653 if (empty($tab['class'])) {
1654 if (! empty($tab['active'])
1655 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1657 $tab['class'] = 'active';
1658 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1659 && (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'])
1661 $tab['class'] = 'active';
1665 // If there are any tab specific URL parameters, merge those with
1666 // the general URL parameters
1667 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1668 $url_params = array_merge($url_params, $tab['url_params']);
1671 // build the link
1672 if (! empty($tab['link'])) {
1673 $tab['link'] = htmlentities($tab['link']);
1674 $tab['link'] = $tab['link'] . PMA_URL_getCommon($url_params);
1675 if (! empty($tab['args'])) {
1676 foreach ($tab['args'] as $param => $value) {
1677 $tab['link'] .= PMA_URL_getArgSeparator('html')
1678 . urlencode($param) . '=' . urlencode($value);
1683 if (! empty($tab['fragment'])) {
1684 $tab['link'] .= $tab['fragment'];
1687 // display icon
1688 if (isset($tab['icon'])) {
1689 // avoid generating an alt tag, because it only illustrates
1690 // the text that follows and if browser does not display
1691 // images, the text is duplicated
1692 $tab['text'] = self::getIcon(
1693 $tab['icon'],
1694 $tab['text'],
1695 false,
1696 true,
1697 'TabsMode'
1700 } elseif (empty($tab['text'])) {
1701 // check to not display an empty link-text
1702 $tab['text'] = '?';
1703 trigger_error(
1704 'empty linktext in function ' . __FUNCTION__ . '()',
1705 E_USER_NOTICE
1709 //Set the id for the tab, if set in the params
1710 $id_string = ( empty($tab['id']) ? '' : ' id="' . $tab['id'] . '" ' );
1711 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1713 if (! empty($tab['link'])) {
1714 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1715 . $id_string
1716 . ' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1717 . $tab['text'] . '</a>';
1718 } else {
1719 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'
1720 . $id_string . '>' . $tab['text'] . '</span>';
1723 $out .= '</li>';
1724 return $out;
1725 } // end of the 'getHtmlTab()' function
1728 * returns html-code for a tab navigation
1730 * @param array $tabs one element per tab
1731 * @param array $url_params additional URL parameters
1732 * @param string $menu_id HTML id attribute for the menu container
1733 * @param bool $resizable whether to add a "resizable" class
1735 * @return string html-code for tab-navigation
1737 public static function getHtmlTabs($tabs, $url_params, $menu_id,
1738 $resizable = false
1740 $class = '';
1741 if ($resizable) {
1742 $class = ' class="resizable-menu"';
1745 $tab_navigation = '<div id="' . htmlentities($menu_id)
1746 . 'container" class="menucontainer">'
1747 . '<ul id="' . htmlentities($menu_id) . '" ' . $class . '>';
1749 foreach ($tabs as $tab) {
1750 $tab_navigation .= self::getHtmlTab($tab, $url_params);
1753 $tab_navigation .=
1754 '<div class="clearfloat"></div>'
1755 . '</ul>' . "\n"
1756 . '</div>' . "\n";
1758 return $tab_navigation;
1762 * Displays a link, or a button if the link's URL is too large, to
1763 * accommodate some browsers' limitations
1765 * @param string $url the URL
1766 * @param string $message the link message
1767 * @param mixed $tag_params string: js confirmation
1768 * array: additional tag params (f.e. style="")
1769 * @param boolean $new_form we set this to false when we are already in
1770 * a form, to avoid generating nested forms
1771 * @param boolean $strip_img whether to strip the image
1772 * @param string $target target
1774 * @return string the results to be echoed or saved in an array
1776 public static function linkOrButton(
1777 $url, $message, $tag_params = array(),
1778 $new_form = true, $strip_img = false, $target = ''
1780 $url_length = /*overload*/mb_strlen($url);
1781 // with this we should be able to catch case of image upload
1782 // into a (MEDIUM) BLOB; not worth generating even a form for these
1783 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1784 return '';
1787 if (! is_array($tag_params)) {
1788 $tmp = $tag_params;
1789 $tag_params = array();
1790 if (! empty($tmp)) {
1791 $tag_params['onclick'] = 'return confirmLink(this, \''
1792 . PMA_escapeJsString($tmp) . '\')';
1794 unset($tmp);
1796 if (! empty($target)) {
1797 $tag_params['target'] = htmlentities($target);
1800 $displayed_message = '';
1801 // Add text if not already added
1802 if (stristr($message, '<img')
1803 && (! $strip_img || ($GLOBALS['cfg']['ActionLinksMode'] == 'icons'))
1804 && (strip_tags($message) == $message)
1806 $displayed_message = '<span>'
1807 . htmlspecialchars(
1808 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1810 . '</span>';
1813 // Suhosin: Check that each query parameter is not above maximum
1814 $in_suhosin_limits = true;
1815 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1816 $suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length');
1817 if ($suhosin_get_MaxValueLength) {
1818 $query_parts = self::splitURLQuery($url);
1819 foreach ($query_parts as $query_pair) {
1820 if (strpos($query_pair, '=') !== false) {
1821 list(, $eachval) = explode('=', $query_pair);
1822 if (/*overload*/mb_strlen($eachval) > $suhosin_get_MaxValueLength
1824 $in_suhosin_limits = false;
1825 break;
1832 if (($url_length <= $GLOBALS['cfg']['LinkLengthLimit'])
1833 && $in_suhosin_limits
1835 $tag_params_strings = array();
1836 foreach ($tag_params as $par_name => $par_value) {
1837 // htmlspecialchars() only on non javascript
1838 $par_value = /*overload*/mb_substr($par_name, 0, 2) == 'on'
1839 ? $par_value
1840 : htmlspecialchars($par_value);
1841 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1844 // no whitespace within an <a> else Safari will make it part of the link
1845 $ret = "\n" . '<a href="' . $url . '" '
1846 . implode(' ', $tag_params_strings) . '>'
1847 . $message . $displayed_message . '</a>' . "\n";
1848 } else {
1849 // no spaces (line breaks) at all
1850 // or after the hidden fields
1851 // IE will display them all
1853 if (! isset($query_parts)) {
1854 $query_parts = self::splitURLQuery($url);
1856 $url_parts = parse_url($url);
1858 if ($new_form) {
1859 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1860 . ' method="post"' . $target . ' style="display: inline;">';
1861 $subname_open = '';
1862 $subname_close = '';
1863 $submit_link = '#';
1864 } else {
1865 $query_parts[] = 'redirect=' . $url_parts['path'];
1866 if (empty($GLOBALS['subform_counter'])) {
1867 $GLOBALS['subform_counter'] = 0;
1869 $GLOBALS['subform_counter']++;
1870 $ret = '';
1871 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1872 $subname_close = ']';
1873 $submit_link = '#usesubform[' . $GLOBALS['subform_counter']
1874 . ']=1';
1877 foreach ($query_parts as $query_pair) {
1878 list($eachvar, $eachval) = explode('=', $query_pair);
1879 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1880 . $subname_close . '" value="'
1881 . htmlspecialchars(urldecode($eachval)) . '" />';
1882 } // end while
1884 if (empty($tag_params['class'])) {
1885 $tag_params['class'] = 'formLinkSubmit';
1886 } else {
1887 $tag_params['class'] .= ' formLinkSubmit';
1890 $tag_params_strings = array();
1891 foreach ($tag_params as $par_name => $par_value) {
1892 // htmlspecialchars() only on non javascript
1893 $par_value = /*overload*/mb_substr($par_name, 0, 2) == 'on'
1894 ? $par_value
1895 : htmlspecialchars($par_value);
1896 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1899 $ret .= "\n" . '<a href="' . $submit_link . '" '
1900 . implode(' ', $tag_params_strings) . '>'
1901 . $message . ' ' . $displayed_message . '</a>' . "\n";
1903 if ($new_form) {
1904 $ret .= '</form>';
1906 } // end if... else...
1908 return $ret;
1909 } // end of the 'linkOrButton()' function
1912 * Splits a URL string by parameter
1914 * @param string $url the URL
1916 * @return array the parameter/value pairs, for example [0] db=sakila
1918 public static function splitURLQuery($url)
1920 // decode encoded url separators
1921 $separator = PMA_URL_getArgSeparator();
1922 // on most places separator is still hard coded ...
1923 if ($separator !== '&') {
1924 // ... so always replace & with $separator
1925 $url = str_replace(htmlentities('&'), $separator, $url);
1926 $url = str_replace('&', $separator, $url);
1929 $url = str_replace(htmlentities($separator), $separator, $url);
1930 // end decode
1932 $url_parts = parse_url($url);
1934 if (! empty($url_parts['query'])) {
1935 return explode($separator, $url_parts['query']);
1936 } else {
1937 return array();
1942 * Returns a given timespan value in a readable format.
1944 * @param int $seconds the timespan
1946 * @return string the formatted value
1948 public static function timespanFormat($seconds)
1950 $days = floor($seconds / 86400);
1951 if ($days > 0) {
1952 $seconds -= $days * 86400;
1955 $hours = floor($seconds / 3600);
1956 if ($days > 0 || $hours > 0) {
1957 $seconds -= $hours * 3600;
1960 $minutes = floor($seconds / 60);
1961 if ($days > 0 || $hours > 0 || $minutes > 0) {
1962 $seconds -= $minutes * 60;
1965 return sprintf(
1966 __('%s days, %s hours, %s minutes and %s seconds'),
1967 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1972 * Takes a string and outputs each character on a line for itself. Used
1973 * mainly for horizontalflipped display mode.
1974 * Takes care of special html-characters.
1975 * Fulfills https://sourceforge.net/p/phpmyadmin/feature-requests/164/
1977 * @param string $string The string
1978 * @param string $Separator The Separator (defaults to "<br />\n")
1980 * @access public
1981 * @todo add a multibyte safe function $GLOBALS['PMA_String']->split()
1983 * @return string The flipped string
1985 public static function flipstring($string, $Separator = "<br />\n")
1987 $format_string = '';
1988 $charbuff = false;
1990 for ($i = 0, $str_len = /*overload*/mb_strlen($string);
1991 $i < $str_len;
1992 $i++
1994 $char = $string{$i};
1995 $append = false;
1997 if ($char == '&') {
1998 $format_string .= $charbuff;
1999 $charbuff = $char;
2000 } elseif ($char == ';' && ! empty($charbuff)) {
2001 $format_string .= $charbuff . $char;
2002 $charbuff = false;
2003 $append = true;
2004 } elseif (! empty($charbuff)) {
2005 $charbuff .= $char;
2006 } else {
2007 $format_string .= $char;
2008 $append = true;
2011 // do not add separator after the last character
2012 if ($append && ($i != $str_len - 1)) {
2013 $format_string .= $Separator;
2017 return $format_string;
2021 * Function added to avoid path disclosures.
2022 * Called by each script that needs parameters, it displays
2023 * an error message and, by default, stops the execution.
2025 * Not sure we could use a strMissingParameter message here,
2026 * would have to check if the error message file is always available
2028 * @param string[] $params The names of the parameters needed by the calling
2029 * script
2030 * @param bool $request Whether to include this list in checking for
2031 * special params
2033 * @return void
2035 * @global boolean $checked_special flag whether any special variable
2036 * was required
2038 * @access public
2040 public static function checkParameters($params, $request = true)
2042 global $checked_special;
2044 if (! isset($checked_special)) {
2045 $checked_special = false;
2048 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2049 $found_error = false;
2050 $error_message = '';
2052 foreach ($params as $param) {
2053 if ($request && ($param != 'db') && ($param != 'table')) {
2054 $checked_special = true;
2057 if (! isset($GLOBALS[$param])) {
2058 $error_message .= $reported_script_name
2059 . ': ' . __('Missing parameter:') . ' '
2060 . $param
2061 . self::showDocu('faq', 'faqmissingparameters')
2062 . '<br />';
2063 $found_error = true;
2066 if ($found_error) {
2067 PMA_fatalError($error_message, null, false);
2069 } // end function
2072 * Function to generate unique condition for specified row.
2074 * @param resource $handle current query result
2075 * @param integer $fields_cnt number of fields
2076 * @param array $fields_meta meta information about fields
2077 * @param array $row current row
2078 * @param boolean $force_unique generate condition only on pk or
2079 * unique
2080 * @param string|boolean $restrict_to_table restrict the unique condition to
2081 * this table or false if none
2083 * @access public
2085 * @return array the calculated condition and whether condition is unique
2087 public static function getUniqueCondition(
2088 $handle, $fields_cnt, $fields_meta, $row, $force_unique = false,
2089 $restrict_to_table = false
2091 $primary_key = '';
2092 $unique_key = '';
2093 $nonprimary_condition = '';
2094 $preferred_condition = '';
2095 $primary_key_array = array();
2096 $unique_key_array = array();
2097 $nonprimary_condition_array = array();
2098 $condition_array = array();
2100 for ($i = 0; $i < $fields_cnt; ++$i) {
2102 $con_val = '';
2103 $field_flags = $GLOBALS['dbi']->fieldFlags($handle, $i);
2104 $meta = $fields_meta[$i];
2106 // do not use a column alias in a condition
2107 if (! isset($meta->orgname) || ! /*overload*/mb_strlen($meta->orgname)) {
2108 $meta->orgname = $meta->name;
2110 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2111 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2113 foreach (
2114 $GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr
2116 // need (string) === (string)
2117 // '' !== 0 but '' == 0
2118 if ((string)$select_expr['alias'] === (string)$meta->name) {
2119 $meta->orgname = $select_expr['column'];
2120 break;
2121 } // end if
2122 } // end foreach
2126 // Do not use a table alias in a condition.
2127 // Test case is:
2128 // select * from galerie x WHERE
2129 //(select count(*) from galerie y where y.datum=x.datum)>1
2131 // But orgtable is present only with mysqli extension so the
2132 // fix is only for mysqli.
2133 // Also, do not use the original table name if we are dealing with
2134 // a view because this view might be updatable.
2135 // (The isView() verification should not be costly in most cases
2136 // because there is some caching in the function).
2137 if (isset($meta->orgtable)
2138 && ($meta->table != $meta->orgtable)
2139 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2141 $meta->table = $meta->orgtable;
2144 // If this field is not from the table which the unique clause needs
2145 // to be restricted to.
2146 if ($restrict_to_table && $restrict_to_table != $meta->table) {
2147 continue;
2150 // to fix the bug where float fields (primary or not)
2151 // can't be matched because of the imprecision of
2152 // floating comparison, use CONCAT
2153 // (also, the syntax "CONCAT(field) IS NULL"
2154 // that we need on the next "if" will work)
2155 if ($meta->type == 'real') {
2156 $con_key = 'CONCAT(' . self::backquote($meta->table) . '.'
2157 . self::backquote($meta->orgname) . ')';
2158 } else {
2159 $con_key = self::backquote($meta->table) . '.'
2160 . self::backquote($meta->orgname);
2161 } // end if... else...
2162 $condition = ' ' . $con_key . ' ';
2164 if (! isset($row[$i]) || is_null($row[$i])) {
2165 $con_val = 'IS NULL';
2166 } else {
2167 // timestamp is numeric on some MySQL 4.1
2168 // for real we use CONCAT above and it should compare to string
2169 if ($meta->numeric
2170 && ($meta->type != 'timestamp')
2171 && ($meta->type != 'real')
2173 $con_val = '= ' . $row[$i];
2174 } elseif ((($meta->type == 'blob') || ($meta->type == 'string'))
2175 && stristr($field_flags, 'BINARY')
2176 && ! empty($row[$i])
2178 // hexify only if this is a true not empty BLOB or a BINARY
2180 // do not waste memory building a too big condition
2181 if (/*overload*/mb_strlen($row[$i]) < 1000) {
2182 // use a CAST if possible, to avoid problems
2183 // if the field contains wildcard characters % or _
2184 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2185 } else if ($fields_cnt == 1) {
2186 // when this blob is the only field present
2187 // try settling with length comparison
2188 $condition = ' CHAR_LENGTH(' . $con_key . ') ';
2189 $con_val = ' = ' . /*overload*/mb_strlen($row[$i]);
2190 } else {
2191 // this blob won't be part of the final condition
2192 $con_val = null;
2194 } elseif (in_array($meta->type, self::getGISDatatypes())
2195 && ! empty($row[$i])
2197 // do not build a too big condition
2198 if (/*overload*/mb_strlen($row[$i]) < 5000) {
2199 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2200 } else {
2201 $condition = '';
2203 } elseif ($meta->type == 'bit') {
2204 $con_val = "= b'"
2205 . self::printableBitValue($row[$i], $meta->length) . "'";
2206 } else {
2207 $con_val = '= \''
2208 . self::sqlAddSlashes($row[$i], false, true) . '\'';
2212 if ($con_val != null) {
2214 $condition .= $con_val . ' AND';
2216 if ($meta->primary_key > 0) {
2217 $primary_key .= $condition;
2218 $primary_key_array[$con_key] = $con_val;
2219 } elseif ($meta->unique_key > 0) {
2220 $unique_key .= $condition;
2221 $unique_key_array[$con_key] = $con_val;
2224 $nonprimary_condition .= $condition;
2225 $nonprimary_condition_array[$con_key] = $con_val;
2227 } // end for
2229 // Correction University of Virginia 19991216:
2230 // prefer primary or unique keys for condition,
2231 // but use conjunction of all values if no primary key
2232 $clause_is_unique = true;
2234 if ($primary_key) {
2235 $preferred_condition = $primary_key;
2236 $condition_array = $primary_key_array;
2238 } elseif ($unique_key) {
2239 $preferred_condition = $unique_key;
2240 $condition_array = $unique_key_array;
2242 } elseif (! $force_unique) {
2243 $preferred_condition = $nonprimary_condition;
2244 $condition_array = $nonprimary_condition_array;
2245 $clause_is_unique = false;
2248 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2249 return(array($where_clause, $clause_is_unique, $condition_array));
2250 } // end function
2253 * Generate a button or image tag
2255 * @param string $button_name name of button element
2256 * @param string $button_class class of button or image element
2257 * @param string $image_name name of image element
2258 * @param string $text text to display
2259 * @param string $image image to display
2260 * @param string $value value
2262 * @return string html content
2264 * @access public
2266 public static function getButtonOrImage(
2267 $button_name, $button_class, $image_name, $text, $image, $value = ''
2269 if ($value == '') {
2270 $value = $text;
2273 if ($GLOBALS['cfg']['ActionLinksMode'] == 'text') {
2274 return ' <input type="submit" name="' . $button_name . '"'
2275 . ' value="' . htmlspecialchars($value) . '"'
2276 . ' title="' . htmlspecialchars($text) . '" />' . "\n";
2279 /* Opera has trouble with <input type="image"> */
2280 /* IE (before version 9) has trouble with <button> */
2281 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
2282 return '<input type="image" name="' . $image_name
2283 . '" class="' . $button_class
2284 . '" value="' . htmlspecialchars($value)
2285 . '" title="' . htmlspecialchars($text)
2286 . '" src="' . $GLOBALS['pmaThemeImage'] . $image . '" />'
2287 . ($GLOBALS['cfg']['ActionLinksMode'] == 'both'
2288 ? '&nbsp;' . htmlspecialchars($text)
2289 : '') . "\n";
2290 } else {
2291 return '<button class="' . $button_class . '" type="submit"'
2292 . ' name="' . $button_name . '" value="' . htmlspecialchars($value)
2293 . '" title="' . htmlspecialchars($text) . '">' . "\n"
2294 . self::getIcon($image, $text)
2295 . '</button>' . "\n";
2297 } // end function
2300 * Generate a pagination selector for browsing resultsets
2302 * @param string $name The name for the request parameter
2303 * @param int $rows Number of rows in the pagination set
2304 * @param int $pageNow current page number
2305 * @param int $nbTotalPage number of total pages
2306 * @param int $showAll If the number of pages is lower than this
2307 * variable, no pages will be omitted in pagination
2308 * @param int $sliceStart How many rows at the beginning should always
2309 * be shown?
2310 * @param int $sliceEnd How many rows at the end should always be shown?
2311 * @param int $percent Percentage of calculation page offsets to hop to a
2312 * next page
2313 * @param int $range Near the current page, how many pages should
2314 * be considered "nearby" and displayed as well?
2315 * @param string $prompt The prompt to display (sometimes empty)
2317 * @return string
2319 * @access public
2321 public static function pageselector(
2322 $name, $rows, $pageNow = 1, $nbTotalPage = 1, $showAll = 200,
2323 $sliceStart = 5,
2324 $sliceEnd = 5, $percent = 20, $range = 10, $prompt = ''
2326 $increment = floor($nbTotalPage / $percent);
2327 $pageNowMinusRange = ($pageNow - $range);
2328 $pageNowPlusRange = ($pageNow + $range);
2330 $gotopage = $prompt . ' <select class="pageselector ajax"';
2332 $gotopage .= ' name="' . $name . '" >';
2333 if ($nbTotalPage < $showAll) {
2334 $pages = range(1, $nbTotalPage);
2335 } else {
2336 $pages = array();
2338 // Always show first X pages
2339 for ($i = 1; $i <= $sliceStart; $i++) {
2340 $pages[] = $i;
2343 // Always show last X pages
2344 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2345 $pages[] = $i;
2348 // Based on the number of results we add the specified
2349 // $percent percentage to each page number,
2350 // so that we have a representing page number every now and then to
2351 // immediately jump to specific pages.
2352 // As soon as we get near our currently chosen page ($pageNow -
2353 // $range), every page number will be shown.
2354 $i = $sliceStart;
2355 $x = $nbTotalPage - $sliceEnd;
2356 $met_boundary = false;
2358 while ($i <= $x) {
2359 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2360 // If our pageselector comes near the current page, we use 1
2361 // counter increments
2362 $i++;
2363 $met_boundary = true;
2364 } else {
2365 // We add the percentage increment to our current page to
2366 // hop to the next one in range
2367 $i += $increment;
2369 // Make sure that we do not cross our boundaries.
2370 if ($i > $pageNowMinusRange && ! $met_boundary) {
2371 $i = $pageNowMinusRange;
2375 if ($i > 0 && $i <= $x) {
2376 $pages[] = $i;
2381 Add page numbers with "geometrically increasing" distances.
2383 This helps me a lot when navigating through giant tables.
2385 Test case: table with 2.28 million sets, 76190 pages. Page of interest
2386 is between 72376 and 76190.
2387 Selecting page 72376.
2388 Now, old version enumerated only +/- 10 pages around 72376 and the
2389 percentage increment produced steps of about 3000.
2391 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2392 around the current page.
2394 $i = $pageNow;
2395 $dist = 1;
2396 while ($i < $x) {
2397 $dist = 2 * $dist;
2398 $i = $pageNow + $dist;
2399 if ($i > 0 && $i <= $x) {
2400 $pages[] = $i;
2404 $i = $pageNow;
2405 $dist = 1;
2406 while ($i > 0) {
2407 $dist = 2 * $dist;
2408 $i = $pageNow - $dist;
2409 if ($i > 0 && $i <= $x) {
2410 $pages[] = $i;
2414 // Since because of ellipsing of the current page some numbers may be
2415 // double, we unify our array:
2416 sort($pages);
2417 $pages = array_unique($pages);
2420 foreach ($pages as $i) {
2421 if ($i == $pageNow) {
2422 $selected = 'selected="selected" style="font-weight: bold"';
2423 } else {
2424 $selected = '';
2426 $gotopage .= ' <option ' . $selected
2427 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2430 $gotopage .= ' </select>';
2432 return $gotopage;
2433 } // end function
2436 * Prepare navigation for a list
2438 * @param int $count number of elements in the list
2439 * @param int $pos current position in the list
2440 * @param array $_url_params url parameters
2441 * @param string $script script name for form target
2442 * @param string $frame target frame
2443 * @param int $max_count maximum number of elements to display from
2444 * the list
2445 * @param string $name the name for the request parameter
2446 * @param string[] $classes additional classes for the container
2448 * @return string $list_navigator_html the html content
2450 * @access public
2452 * @todo use $pos from $_url_params
2454 public static function getListNavigator(
2455 $count, $pos, $_url_params, $script, $frame, $max_count, $name = 'pos',
2456 $classes = array()
2459 $class = $frame == 'frame_navigation' ? ' class="ajax"' : '';
2461 $list_navigator_html = '';
2463 if ($max_count < $count) {
2465 $classes[] = 'pageselector';
2466 $list_navigator_html .= '<div class="' . implode(' ', $classes) . '">';
2468 if ($frame != 'frame_navigation') {
2469 $list_navigator_html .= __('Page number:');
2472 // Move to the beginning or to the previous page
2473 if ($pos > 0) {
2474 $caption1 = ''; $caption2 = '';
2475 if (self::showIcons('TableNavigationLinksMode')) {
2476 $caption1 .= '&lt;&lt; ';
2477 $caption2 .= '&lt; ';
2479 if (self::showText('TableNavigationLinksMode')) {
2480 $caption1 .= _pgettext('First page', 'Begin');
2481 $caption2 .= _pgettext('Previous page', 'Previous');
2483 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2484 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2486 $_url_params[$name] = 0;
2487 $list_navigator_html .= '<a' . $class . $title1 . ' href="' . $script
2488 . PMA_URL_getCommon($_url_params) . '">' . $caption1
2489 . '</a>';
2491 $_url_params[$name] = $pos - $max_count;
2492 $list_navigator_html .= ' <a' . $class . $title2
2493 . ' href="' . $script . PMA_URL_getCommon($_url_params) . '">'
2494 . $caption2 . '</a>';
2497 $list_navigator_html .= '<form action="' . basename($script)
2498 . '" method="post">';
2500 $list_navigator_html .= PMA_URL_getHiddenInputs($_url_params);
2501 $list_navigator_html .= self::pageselector(
2502 $name,
2503 $max_count,
2504 floor(($pos + 1) / $max_count) + 1,
2505 ceil($count / $max_count)
2507 $list_navigator_html .= '</form>';
2509 if ($pos + $max_count < $count) {
2510 $caption3 = ''; $caption4 = '';
2511 if (self::showText('TableNavigationLinksMode')) {
2512 $caption3 .= _pgettext('Next page', 'Next');
2513 $caption4 .= _pgettext('Last page', 'End');
2515 if (self::showIcons('TableNavigationLinksMode')) {
2516 $caption3 .= ' &gt;';
2517 $caption4 .= ' &gt;&gt;';
2518 if (! self::showText('TableNavigationLinksMode')) {
2522 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2523 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2525 $_url_params[$name] = $pos + $max_count;
2526 $list_navigator_html .= '<a' . $class . $title3 . ' href="' . $script
2527 . PMA_URL_getCommon($_url_params) . '" >' . $caption3
2528 . '</a>';
2530 $_url_params[$name] = floor($count / $max_count) * $max_count;
2531 if ($_url_params[$name] == $count) {
2532 $_url_params[$name] = $count - $max_count;
2535 $list_navigator_html .= ' <a' . $class . $title4
2536 . ' href="' . $script . PMA_URL_getCommon($_url_params) . '" >'
2537 . $caption4 . '</a>';
2539 $list_navigator_html .= '</div>' . "\n";
2542 return $list_navigator_html;
2546 * replaces %u in given path with current user name
2548 * example:
2549 * <code>
2550 * $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2552 * </code>
2554 * @param string $dir with wildcard for user
2556 * @return string per user directory
2558 public static function userDir($dir)
2560 // add trailing slash
2561 if (/*overload*/mb_substr($dir, -1) != '/') {
2562 $dir .= '/';
2565 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2569 * returns html code for db link to default db page
2571 * @param string $database database
2573 * @return string html link to default db page
2575 public static function getDbLink($database = null)
2577 if (! /*overload*/mb_strlen($database)) {
2578 if (! /*overload*/mb_strlen($GLOBALS['db'])) {
2579 return '';
2581 $database = $GLOBALS['db'];
2582 } else {
2583 $database = self::unescapeMysqlWildcards($database);
2586 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase']
2587 . PMA_URL_getCommon(array('db' => $database)) . '" title="'
2588 . htmlspecialchars(
2589 sprintf(
2590 __('Jump to database "%s".'),
2591 $database
2594 . '">' . htmlspecialchars($database) . '</a>';
2598 * Prepare a lightbulb hint explaining a known external bug
2599 * that affects a functionality
2601 * @param string $functionality localized message explaining the func.
2602 * @param string $component 'mysql' (eventually, 'php')
2603 * @param string $minimum_version of this component
2604 * @param string $bugref bug reference for this component
2606 * @return String
2608 public static function getExternalBug(
2609 $functionality, $component, $minimum_version, $bugref
2611 $ext_but_html = '';
2612 if (($component == 'mysql') && (PMA_MYSQL_INT_VERSION < $minimum_version)) {
2613 $ext_but_html .= self::showHint(
2614 sprintf(
2615 __('The %s functionality is affected by a known bug, see %s'),
2616 $functionality,
2617 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2621 return $ext_but_html;
2625 * Returns a HTML checkbox
2627 * @param string $html_field_name the checkbox HTML field
2628 * @param string $label label for checkbox
2629 * @param boolean $checked is it initially checked?
2630 * @param boolean $onclick should it submit the form on click?
2631 * @param string $html_field_id id for the checkbox
2633 * @return string HTML for the checkbox
2635 public static function getCheckbox(
2636 $html_field_name, $label, $checked, $onclick, $html_field_id = ''
2638 return '<input type="checkbox" name="' . $html_field_name . '"'
2639 . ($html_field_id ? ' id="' . $html_field_id . '"' : '')
2640 . ($checked ? ' checked="checked"' : '')
2641 . ($onclick ? ' class="autosubmit"' : '') . ' />'
2642 . '<label' . ($html_field_id ? ' for="' . $html_field_id . '"' : '')
2643 . '>' . $label . '</label>';
2647 * Generates a set of radio HTML fields
2649 * @param string $html_field_name the radio HTML field
2650 * @param array $choices the choices values and labels
2651 * @param string $checked_choice the choice to check by default
2652 * @param boolean $line_break whether to add HTML line break after a choice
2653 * @param boolean $escape_label whether to use htmlspecialchars() on label
2654 * @param string $class enclose each choice with a div of this class
2655 * @param string $id_prefix prefix for the id attribute, name will be
2656 * used if this is not supplied
2658 * @return string set of html radio fiels
2660 public static function getRadioFields(
2661 $html_field_name, $choices, $checked_choice = '',
2662 $line_break = true, $escape_label = true, $class = '',
2663 $id_prefix = ''
2665 $radio_html = '';
2667 foreach ($choices as $choice_value => $choice_label) {
2669 if (! empty($class)) {
2670 $radio_html .= '<div class="' . $class . '">';
2673 if (! $id_prefix) {
2674 $id_prefix = $html_field_name;
2676 $html_field_id = $id_prefix . '_' . $choice_value;
2677 $radio_html .= '<input type="radio" name="' . $html_field_name . '" id="'
2678 . $html_field_id . '" value="'
2679 . htmlspecialchars($choice_value) . '"';
2681 if ($choice_value == $checked_choice) {
2682 $radio_html .= ' checked="checked"';
2685 $radio_html .= ' />' . "\n"
2686 . '<label for="' . $html_field_id . '">'
2687 . ($escape_label
2688 ? htmlspecialchars($choice_label)
2689 : $choice_label)
2690 . '</label>';
2692 if ($line_break) {
2693 $radio_html .= '<br />';
2696 if (! empty($class)) {
2697 $radio_html .= '</div>';
2699 $radio_html .= "\n";
2702 return $radio_html;
2706 * Generates and returns an HTML dropdown
2708 * @param string $select_name name for the select element
2709 * @param array $choices choices values
2710 * @param string $active_choice the choice to select by default
2711 * @param string $id id of the select element; can be different in
2712 * case the dropdown is present more than once
2713 * on the page
2714 * @param string $class class for the select element
2715 * @param string $placeholder Placeholder for dropdown if nothing else
2716 * is selected
2718 * @return string html content
2720 * @todo support titles
2722 public static function getDropdown(
2723 $select_name, $choices, $active_choice, $id, $class = '', $placeholder = null
2725 $result = '<select'
2726 . ' name="' . htmlspecialchars($select_name) . '"'
2727 . ' id="' . htmlspecialchars($id) . '"'
2728 . (! empty($class) ? ' class="' . htmlspecialchars($class) . '"' : '')
2729 . '>';
2731 $resultOptions = '';
2732 $selected = false;
2734 foreach ($choices as $one_choice_value => $one_choice_label) {
2735 $resultOptions .= '<option value="'
2736 . htmlspecialchars($one_choice_value) . '"';
2738 if ($one_choice_value == $active_choice) {
2739 $resultOptions .= ' selected="selected"';
2740 $selected = true;
2742 $resultOptions .= '>' . htmlspecialchars($one_choice_label)
2743 . '</option>';
2746 if (!empty($placeholder)) {
2747 $resultOptions = '<option value="" disabled="disabled"'
2748 . ( !$selected ? ' selected="selected"' : '' )
2749 . '>' . $placeholder . '</option>'
2750 . $resultOptions;
2753 $result .= $resultOptions
2754 . '</select>';
2756 return $result;
2760 * Generates a slider effect (jQjuery)
2761 * Takes care of generating the initial <div> and the link
2762 * controlling the slider; you have to generate the </div> yourself
2763 * after the sliding section.
2765 * @param string $id the id of the <div> on which to apply the effect
2766 * @param string $message the message to show as a link
2768 * @return string html div element
2771 public static function getDivForSliderEffect($id = '', $message = '')
2773 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2774 return '<div' . ($id ? ' id="' . $id . '"' : '') . '>';
2777 * Bad hack on the next line. document.write() conflicts with jQuery,
2778 * hence, opening the <div> with PHP itself instead of JavaScript.
2780 * @todo find a better solution that uses $.append(), the recommended
2781 * method maybe by using an additional param, the id of the div to
2782 * append to
2785 return '<div'
2786 . ($id ? ' id="' . $id . '"' : '')
2787 . (($GLOBALS['cfg']['InitialSlidersState'] == 'closed')
2788 ? ' style="display: none; overflow:auto;"'
2789 : '')
2790 . ' class="pma_auto_slider"'
2791 . ($message ? ' title="' . htmlspecialchars($message) . '"' : '')
2792 . '>';
2796 * Creates an AJAX sliding toggle button
2797 * (or and equivalent form when AJAX is disabled)
2799 * @param string $action The URL for the request to be executed
2800 * @param string $select_name The name for the dropdown box
2801 * @param array $options An array of options (see rte_footer.lib.php)
2802 * @param string $callback A JS snippet to execute when the request is
2803 * successfully processed
2805 * @return string HTML code for the toggle button
2807 public static function toggleButton($action, $select_name, $options, $callback)
2809 // Do the logic first
2810 $link = "$action&amp;" . urlencode($select_name) . "=";
2811 $link_on = $link . urlencode($options[1]['value']);
2812 $link_off = $link . urlencode($options[0]['value']);
2814 if ($options[1]['selected'] == true) {
2815 $state = 'on';
2816 } else if ($options[0]['selected'] == true) {
2817 $state = 'off';
2818 } else {
2819 $state = 'on';
2822 // Generate output
2823 return "<!-- TOGGLE START -->\n"
2824 . "<div class='wrapper toggleAjax hide'>\n"
2825 . " <div class='toggleButton'>\n"
2826 . " <div title='" . __('Click to toggle')
2827 . "' class='container $state'>\n"
2828 . " <img src='" . htmlspecialchars($GLOBALS['pmaThemeImage'])
2829 . "toggle-" . htmlspecialchars($GLOBALS['text_dir']) . ".png'\n"
2830 . " alt='' />\n"
2831 . " <table class='nospacing nopadding'>\n"
2832 . " <tbody>\n"
2833 . " <tr>\n"
2834 . " <td class='toggleOn'>\n"
2835 . " <span class='hide'>$link_on</span>\n"
2836 . " <div>"
2837 . str_replace(' ', '&nbsp;', htmlspecialchars($options[1]['label']))
2838 . "\n" . " </div>\n"
2839 . " </td>\n"
2840 . " <td><div>&nbsp;</div></td>\n"
2841 . " <td class='toggleOff'>\n"
2842 . " <span class='hide'>$link_off</span>\n"
2843 . " <div>"
2844 . str_replace(' ', '&nbsp;', htmlspecialchars($options[0]['label']))
2845 . "\n" . " </div>\n"
2846 . " </tr>\n"
2847 . " </tbody>\n"
2848 . " </table>\n"
2849 . " <span class='hide callback'>"
2850 . htmlspecialchars($callback) . "</span>\n"
2851 . " <span class='hide text_direction'>"
2852 . htmlspecialchars($GLOBALS['text_dir']) . "</span>\n"
2853 . " </div>\n"
2854 . " </div>\n"
2855 . "</div>\n"
2856 . "<!-- TOGGLE END -->";
2858 } // end toggleButton()
2861 * Clears cache content which needs to be refreshed on user change.
2863 * @return void
2865 public static function clearUserCache()
2867 self::cacheUnset('is_superuser');
2868 self::cacheUnset('is_createuser');
2869 self::cacheUnset('is_grantuser');
2873 * Verifies if something is cached in the session
2875 * @param string $var variable name
2877 * @return boolean
2879 public static function cacheExists($var)
2881 return isset($_SESSION['cache']['server_' . $GLOBALS['server']][$var]);
2885 * Gets cached information from the session
2887 * @param string $var variable name
2889 * @return mixed
2891 public static function cacheGet($var)
2893 if (isset($_SESSION['cache']['server_' . $GLOBALS['server']][$var])) {
2894 return $_SESSION['cache']['server_' . $GLOBALS['server']][$var];
2895 } else {
2896 return null;
2901 * Caches information in the session
2903 * @param string $var variable name
2904 * @param mixed $val value
2906 * @return mixed
2908 public static function cacheSet($var, $val = null)
2910 $_SESSION['cache']['server_' . $GLOBALS['server']][$var] = $val;
2914 * Removes cached information from the session
2916 * @param string $var variable name
2918 * @return void
2920 public static function cacheUnset($var)
2922 unset($_SESSION['cache']['server_' . $GLOBALS['server']][$var]);
2926 * Converts a bit value to printable format;
2927 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2928 * function because in PHP, decbin() supports only 32 bits
2929 * on 32-bit servers
2931 * @param number $value coming from a BIT field
2932 * @param integer $length length
2934 * @return string the printable value
2936 public static function printableBitValue($value, $length)
2938 // if running on a 64-bit server or the length is safe for decbin()
2939 if (PHP_INT_SIZE == 8 || $length < 33) {
2940 $printable = decbin($value);
2941 } else {
2942 // FIXME: does not work for the leftmost bit of a 64-bit value
2943 $i = 0;
2944 $printable = '';
2945 while ($value >= pow(2, $i)) {
2946 $i++;
2948 if ($i != 0) {
2949 $i = $i - 1;
2952 while ($i >= 0) {
2953 if ($value - pow(2, $i) < 0) {
2954 $printable = '0' . $printable;
2955 } else {
2956 $printable = '1' . $printable;
2957 $value = $value - pow(2, $i);
2959 $i--;
2961 $printable = strrev($printable);
2963 $printable = str_pad($printable, $length, '0', STR_PAD_LEFT);
2964 return $printable;
2968 * Verifies whether the value contains a non-printable character
2970 * @param string $value value
2972 * @return integer
2974 public static function containsNonPrintableAscii($value)
2976 return preg_match('@[^[:print:]]@', $value);
2980 * Converts a BIT type default value
2981 * for example, b'010' becomes 010
2983 * @param string $bit_default_value value
2985 * @return string the converted value
2987 public static function convertBitDefaultValue($bit_default_value)
2989 return rtrim(ltrim($bit_default_value, "b'"), "'");
2993 * Extracts the various parts from a column spec
2995 * @param string $columnspec Column specification
2997 * @return array associative array containing type, spec_in_brackets
2998 * and possibly enum_set_values (another array)
3000 public static function extractColumnSpec($columnspec)
3002 $first_bracket_pos = /*overload*/mb_strpos($columnspec, '(');
3003 if ($first_bracket_pos) {
3004 $spec_in_brackets = chop(
3005 /*overload*/mb_substr(
3006 $columnspec,
3007 $first_bracket_pos + 1,
3008 /*overload*/mb_strrpos($columnspec, ')') - $first_bracket_pos - 1
3011 // convert to lowercase just to be sure
3012 $type = /*overload*/mb_strtolower(
3013 chop(/*overload*/mb_substr($columnspec, 0, $first_bracket_pos))
3015 } else {
3016 // Split trailing attributes such as unsigned,
3017 // binary, zerofill and get data type name
3018 $type_parts = explode(' ', $columnspec);
3019 $type = /*overload*/mb_strtolower($type_parts[0]);
3020 $spec_in_brackets = '';
3023 if ('enum' == $type || 'set' == $type) {
3024 // Define our working vars
3025 $enum_set_values = self::parseEnumSetValues($columnspec, false);
3026 $printtype = $type
3027 . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
3028 $binary = false;
3029 $unsigned = false;
3030 $zerofill = false;
3031 } else {
3032 $enum_set_values = array();
3034 /* Create printable type name */
3035 $printtype = /*overload*/mb_strtolower($columnspec);
3037 // Strip the "BINARY" attribute, except if we find "BINARY(" because
3038 // this would be a BINARY or VARBINARY column type;
3039 // by the way, a BLOB should not show the BINARY attribute
3040 // because this is not accepted in MySQL syntax.
3041 if (preg_match('@binary@', $printtype)
3042 && ! preg_match('@binary[\(]@', $printtype)
3044 $printtype = preg_replace('@binary@', '', $printtype);
3045 $binary = true;
3046 } else {
3047 $binary = false;
3050 $printtype = preg_replace(
3051 '@zerofill@', '', $printtype, -1, $zerofill_cnt
3053 $zerofill = ($zerofill_cnt > 0);
3054 $printtype = preg_replace(
3055 '@unsigned@', '', $printtype, -1, $unsigned_cnt
3057 $unsigned = ($unsigned_cnt > 0);
3058 $printtype = trim($printtype);
3061 $attribute = ' ';
3062 if ($binary) {
3063 $attribute = 'BINARY';
3065 if ($unsigned) {
3066 $attribute = 'UNSIGNED';
3068 if ($zerofill) {
3069 $attribute = 'UNSIGNED ZEROFILL';
3072 $can_contain_collation = false;
3073 if (! $binary
3074 && preg_match(
3075 "@^(char|varchar|text|tinytext|mediumtext|longtext|set|enum)@", $type
3078 $can_contain_collation = true;
3081 // for the case ENUM('&#8211;','&ldquo;')
3082 $displayed_type = htmlspecialchars($printtype);
3083 if (/*overload*/mb_strlen($printtype) > $GLOBALS['cfg']['LimitChars']) {
3084 $displayed_type = '<abbr title="' . htmlspecialchars($printtype) . '">';
3085 $displayed_type .= htmlspecialchars(
3086 /*overload*/mb_substr(
3087 $printtype, 0, $GLOBALS['cfg']['LimitChars']
3090 $displayed_type .= '</abbr>';
3093 return array(
3094 'type' => $type,
3095 'spec_in_brackets' => $spec_in_brackets,
3096 'enum_set_values' => $enum_set_values,
3097 'print_type' => $printtype,
3098 'binary' => $binary,
3099 'unsigned' => $unsigned,
3100 'zerofill' => $zerofill,
3101 'attribute' => $attribute,
3102 'can_contain_collation' => $can_contain_collation,
3103 'displayed_type' => $displayed_type
3108 * Verifies if this table's engine supports foreign keys
3110 * @param string $engine engine
3112 * @return boolean
3114 public static function isForeignKeySupported($engine)
3116 $engine = strtoupper($engine);
3117 if (($engine == 'INNODB') || ($engine == 'PBXT')) {
3118 return true;
3119 } elseif ($engine == 'NDBCLUSTER' || $engine == 'NDB') {
3120 $ndbver = $GLOBALS['dbi']->fetchValue(
3121 "SHOW VARIABLES LIKE 'ndb_version_string'"
3123 return ($ndbver >= 7.3);
3124 } else {
3125 return false;
3130 * Replaces some characters by a displayable equivalent
3132 * @param string $content content
3134 * @return string the content with characters replaced
3136 public static function replaceBinaryContents($content)
3138 $result = str_replace("\x00", '\0', $content);
3139 $result = str_replace("\x08", '\b', $result);
3140 $result = str_replace("\x0a", '\n', $result);
3141 $result = str_replace("\x0d", '\r', $result);
3142 $result = str_replace("\x1a", '\Z', $result);
3143 return $result;
3147 * Converts GIS data to Well Known Text format
3149 * @param string $data GIS data
3150 * @param bool $includeSRID Add SRID to the WKT
3152 * @return string GIS data in Well Know Text format
3154 public static function asWKT($data, $includeSRID = false)
3156 // Convert to WKT format
3157 $hex = bin2hex($data);
3158 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3159 if ($includeSRID) {
3160 $wktsql .= ", SRID(x'" . $hex . "')";
3163 $wktresult = $GLOBALS['dbi']->tryQuery(
3164 $wktsql, null, PMA_DatabaseInterface::QUERY_STORE
3166 $wktarr = $GLOBALS['dbi']->fetchRow($wktresult, 0);
3167 $wktval = $wktarr[0];
3169 if ($includeSRID) {
3170 $srid = $wktarr[1];
3171 $wktval = "'" . $wktval . "'," . $srid;
3173 @$GLOBALS['dbi']->freeResult($wktresult);
3175 return $wktval;
3179 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3181 * @param string $string string
3183 * @return string with the chars replaced
3185 public static function duplicateFirstNewline($string)
3187 $first_occurence = /*overload*/mb_strpos($string, "\r\n");
3188 if ($first_occurence === 0) {
3189 $string = "\n" . $string;
3191 return $string;
3195 * Get the action word corresponding to a script name
3196 * in order to display it as a title in navigation panel
3198 * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
3199 * $cfg['NavigationTreeDefaultTabTable2'],
3200 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3202 * @return array
3204 public static function getTitleForTarget($target)
3206 $mapping = array(
3207 // Values for $cfg['DefaultTabTable']
3208 'tbl_structure.php' => __('Structure'),
3209 'tbl_sql.php' => __('SQL'),
3210 'tbl_select.php' =>__('Search'),
3211 'tbl_change.php' =>__('Insert'),
3212 'sql.php' => __('Browse'),
3214 // Values for $cfg['DefaultTabDatabase']
3215 'db_structure.php' => __('Structure'),
3216 'db_sql.php' => __('SQL'),
3217 'db_search.php' => __('Search'),
3218 'db_operations.php' => __('Operations'),
3220 return isset($mapping[$target]) ? $mapping[$target] : false;
3224 * Formats user string, expanding @VARIABLES@, accepting strftime format
3225 * string.
3227 * @param string $string Text where to do expansion.
3228 * @param array|string $escape Function to call for escaping variable values.
3229 * Can also be an array of:
3230 * - the escape method name
3231 * - the class that contains the method
3232 * - location of the class (for inclusion)
3233 * @param array $updates Array with overrides for default parameters
3234 * (obtained from GLOBALS).
3236 * @return string
3238 public static function expandUserString(
3239 $string, $escape = null, $updates = array()
3241 /* Content */
3242 $vars = array();
3243 $vars['http_host'] = PMA_getenv('HTTP_HOST');
3244 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3245 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3247 if (empty($GLOBALS['cfg']['Server']['verbose'])) {
3248 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host'];
3249 } else {
3250 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose'];
3253 $vars['database'] = $GLOBALS['db'];
3254 $vars['table'] = $GLOBALS['table'];
3255 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3257 /* Update forced variables */
3258 foreach ($updates as $key => $val) {
3259 $vars[$key] = $val;
3262 /* Replacement mapping */
3264 * The __VAR__ ones are for backward compatibility, because user
3265 * might still have it in cookies.
3267 $replace = array(
3268 '@HTTP_HOST@' => $vars['http_host'],
3269 '@SERVER@' => $vars['server_name'],
3270 '__SERVER__' => $vars['server_name'],
3271 '@VERBOSE@' => $vars['server_verbose'],
3272 '@VSERVER@' => $vars['server_verbose_or_name'],
3273 '@DATABASE@' => $vars['database'],
3274 '__DB__' => $vars['database'],
3275 '@TABLE@' => $vars['table'],
3276 '__TABLE__' => $vars['table'],
3277 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3280 /* Optional escaping */
3281 if (! is_null($escape)) {
3282 if (is_array($escape)) {
3283 include_once $escape[2];
3284 $escape_class = new $escape[1];
3285 $escape_method = $escape[0];
3287 foreach ($replace as $key => $val) {
3288 if (is_array($escape)) {
3289 $replace[$key] = $escape_class->$escape_method($val);
3290 } else {
3291 $replace[$key] = ($escape == 'backquote')
3292 ? self::$escape($val)
3293 : $escape($val);
3298 /* Backward compatibility in 3.5.x */
3299 if (/*overload*/mb_strpos($string, '@FIELDS@') !== false) {
3300 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3303 /* Fetch columns list if required */
3304 if (/*overload*/mb_strpos($string, '@COLUMNS@') !== false) {
3305 $columns_list = $GLOBALS['dbi']->getColumns(
3306 $GLOBALS['db'], $GLOBALS['table']
3309 // sometimes the table no longer exists at this point
3310 if (! is_null($columns_list)) {
3311 $column_names = array();
3312 foreach ($columns_list as $column) {
3313 if (! is_null($escape)) {
3314 $column_names[] = self::$escape($column['Field']);
3315 } else {
3316 $column_names[] = $column['Field'];
3319 $replace['@COLUMNS@'] = implode(',', $column_names);
3320 } else {
3321 $replace['@COLUMNS@'] = '*';
3325 /* Do the replacement */
3326 return strtr(strftime($string), $replace);
3330 * Prepare the form used to browse anywhere on the local server for a file to
3331 * import
3333 * @param string $max_upload_size maximum upload size
3335 * @return String
3337 public static function getBrowseUploadFileBlock($max_upload_size)
3339 $block_html = '';
3341 if ($GLOBALS['is_upload'] && ! empty($GLOBALS['cfg']['UploadDir'])) {
3342 $block_html .= '<label for="radio_import_file">';
3343 } else {
3344 $block_html .= '<label for="input_import_file">';
3347 $block_html .= __("Browse your computer:") . '</label>'
3348 . '<div id="upload_form_status" style="display: none;"></div>'
3349 . '<div id="upload_form_status_info" style="display: none;"></div>'
3350 . '<input type="file" name="import_file" id="input_import_file" />'
3351 . self::getFormattedMaximumUploadSize($max_upload_size) . "\n"
3352 // some browsers should respect this :)
3353 . self::generateHiddenMaxFileSize($max_upload_size) . "\n";
3355 return $block_html;
3359 * Prepare the form used to select a file to import from the server upload
3360 * directory
3362 * @param array $import_list array of import plugins
3363 * @param string $uploaddir upload directory
3365 * @return String
3367 public static function getSelectUploadFileBlock($import_list, $uploaddir)
3369 $block_html = '';
3370 $block_html .= '<label for="radio_local_import_file">'
3371 . sprintf(
3372 __("Select from the web server upload directory <b>%s</b>:"),
3373 htmlspecialchars(self::userDir($uploaddir))
3375 . '</label>';
3377 $extensions = '';
3378 foreach ($import_list as $import_plugin) {
3379 if (! empty($extensions)) {
3380 $extensions .= '|';
3382 $extensions .= $import_plugin->getProperties()->getExtension();
3385 $matcher = '@\.(' . $extensions . ')(\.('
3386 . PMA_supportedDecompressions() . '))?$@';
3388 $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
3389 && isset($GLOBALS['local_import_file']))
3390 ? $GLOBALS['local_import_file']
3391 : '';
3393 $files = PMA_getFileSelectOptions(
3394 self::userDir($uploaddir),
3395 $matcher,
3396 $active
3399 if ($files === false) {
3400 PMA_Message::error(
3401 __('The directory you set for upload work cannot be reached.')
3402 )->display();
3403 } elseif (! empty($files)) {
3404 $block_html .= "\n"
3405 . ' <select style="margin: 5px" size="1" '
3406 . 'name="local_import_file" '
3407 . 'id="select_local_import_file">' . "\n"
3408 . ' <option value="">&nbsp;</option>' . "\n"
3409 . $files
3410 . ' </select>' . "\n";
3411 } elseif (empty ($files)) {
3412 $block_html .= '<i>' . __('There are no files to upload!') . '</i>';
3415 return $block_html;
3420 * Build titles and icons for action links
3422 * @return array the action titles
3424 public static function buildActionTitles()
3426 $titles = array();
3428 $titles['Browse'] = self::getIcon('b_browse.png', __('Browse'));
3429 $titles['NoBrowse'] = self::getIcon('bd_browse.png', __('Browse'));
3430 $titles['Search'] = self::getIcon('b_select.png', __('Search'));
3431 $titles['NoSearch'] = self::getIcon('bd_select.png', __('Search'));
3432 $titles['Insert'] = self::getIcon('b_insrow.png', __('Insert'));
3433 $titles['NoInsert'] = self::getIcon('bd_insrow.png', __('Insert'));
3434 $titles['Structure'] = self::getIcon('b_props.png', __('Structure'));
3435 $titles['Drop'] = self::getIcon('b_drop.png', __('Drop'));
3436 $titles['NoDrop'] = self::getIcon('bd_drop.png', __('Drop'));
3437 $titles['Empty'] = self::getIcon('b_empty.png', __('Empty'));
3438 $titles['NoEmpty'] = self::getIcon('bd_empty.png', __('Empty'));
3439 $titles['Edit'] = self::getIcon('b_edit.png', __('Edit'));
3440 $titles['NoEdit'] = self::getIcon('bd_edit.png', __('Edit'));
3441 $titles['Export'] = self::getIcon('b_export.png', __('Export'));
3442 $titles['NoExport'] = self::getIcon('bd_export.png', __('Export'));
3443 $titles['Execute'] = self::getIcon('b_nextpage.png', __('Execute'));
3444 $titles['NoExecute'] = self::getIcon('bd_nextpage.png', __('Execute'));
3445 // For Favorite/NoFavorite, we need icon only.
3446 $titles['Favorite'] = self::getIcon('b_favorite.png', '');
3447 $titles['NoFavorite']= self::getIcon('b_no_favorite.png', '');
3449 return $titles;
3453 * This function processes the datatypes supported by the DB,
3454 * as specified in PMA_Types->getColumns() and either returns an array
3455 * (useful for quickly checking if a datatype is supported)
3456 * or an HTML snippet that creates a drop-down list.
3458 * @param bool $html Whether to generate an html snippet or an array
3459 * @param string $selected The value to mark as selected in HTML mode
3461 * @return mixed An HTML snippet or an array of datatypes.
3464 public static function getSupportedDatatypes($html = false, $selected = '')
3466 if ($html) {
3468 // NOTE: the SELECT tag in not included in this snippet.
3469 $retval = '';
3471 foreach ($GLOBALS['PMA_Types']->getColumns() as $key => $value) {
3472 if (is_array($value)) {
3473 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3474 foreach ($value as $subvalue) {
3475 if ($subvalue == $selected) {
3476 $retval .= sprintf(
3477 '<option selected="selected" title="%s">%s</option>',
3478 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3479 $subvalue
3481 } else if ($subvalue === '-') {
3482 $retval .= '<option disabled="disabled">';
3483 $retval .= $subvalue;
3484 $retval .= '</option>';
3485 } else {
3486 $retval .= sprintf(
3487 '<option title="%s">%s</option>',
3488 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3489 $subvalue
3493 $retval .= '</optgroup>';
3494 } else {
3495 if ($selected == $value) {
3496 $retval .= sprintf(
3497 '<option selected="selected" title="%s">%s</option>',
3498 $GLOBALS['PMA_Types']->getTypeDescription($value),
3499 $value
3501 } else {
3502 $retval .= sprintf(
3503 '<option title="%s">%s</option>',
3504 $GLOBALS['PMA_Types']->getTypeDescription($value),
3505 $value
3510 } else {
3511 $retval = array();
3512 foreach ($GLOBALS['PMA_Types']->getColumns() as $value) {
3513 if (is_array($value)) {
3514 foreach ($value as $subvalue) {
3515 if ($subvalue !== '-') {
3516 $retval[] = $subvalue;
3519 } else {
3520 if ($value !== '-') {
3521 $retval[] = $value;
3527 return $retval;
3528 } // end getSupportedDatatypes()
3531 * Returns a list of datatypes that are not (yet) handled by PMA.
3532 * Used by: tbl_change.php and libraries/db_routines.inc.php
3534 * @return array list of datatypes
3536 public static function unsupportedDatatypes()
3538 $no_support_types = array();
3539 return $no_support_types;
3543 * Return GIS data types
3545 * @param bool $upper_case whether to return values in upper case
3547 * @return string[] GIS data types
3549 public static function getGISDatatypes($upper_case = false)
3551 $gis_data_types = array(
3552 'geometry',
3553 'point',
3554 'linestring',
3555 'polygon',
3556 'multipoint',
3557 'multilinestring',
3558 'multipolygon',
3559 'geometrycollection'
3561 if ($upper_case) {
3562 for ($i = 0, $nb = count($gis_data_types); $i < $nb; $i++) {
3563 $gis_data_types[$i]
3564 = /*overload*/mb_strtoupper($gis_data_types[$i]);
3567 return $gis_data_types;
3571 * Generates GIS data based on the string passed.
3573 * @param string $gis_string GIS string
3575 * @return string GIS data enclosed in 'GeomFromText' function
3577 public static function createGISData($gis_string)
3579 $gis_string = trim($gis_string);
3580 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3581 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3582 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3583 return 'GeomFromText(' . $gis_string . ')';
3584 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3585 return "GeomFromText('" . $gis_string . "')";
3586 } else {
3587 return $gis_string;
3592 * Returns the names and details of the functions
3593 * that can be applied on geometry data types.
3595 * @param string $geom_type if provided the output is limited to the functions
3596 * that are applicable to the provided geometry type.
3597 * @param bool $binary if set to false functions that take two geometries
3598 * as arguments will not be included.
3599 * @param bool $display if set to true separators will be added to the
3600 * output array.
3602 * @return array names and details of the functions that can be applied on
3603 * geometry data types.
3605 public static function getGISFunctions(
3606 $geom_type = null, $binary = true, $display = false
3608 $funcs = array();
3609 if ($display) {
3610 $funcs[] = array('display' => ' ');
3613 // Unary functions common to all geometry types
3614 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3615 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3616 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3617 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3618 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3619 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3621 $geom_type = trim(/*overload*/mb_strtolower($geom_type));
3622 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3623 $funcs[] = array('display' => '--------');
3626 // Unary functions that are specific to each geometry type
3627 if ($geom_type == 'point') {
3628 $funcs['X'] = array('params' => 1, 'type' => 'float');
3629 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3631 } elseif ($geom_type == 'multipoint') {
3632 // no functions here
3633 } elseif ($geom_type == 'linestring') {
3634 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3635 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3636 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3637 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3638 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3640 } elseif ($geom_type == 'multilinestring') {
3641 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3642 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3644 } elseif ($geom_type == 'polygon') {
3645 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3646 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3647 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3649 } elseif ($geom_type == 'multipolygon') {
3650 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3651 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3652 // Not yet implemented in MySQL
3653 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3655 } elseif ($geom_type == 'geometrycollection') {
3656 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3659 // If we are asked for binary functions as well
3660 if ($binary) {
3661 // section separator
3662 if ($display) {
3663 $funcs[] = array('display' => '--------');
3666 if (PMA_MYSQL_INT_VERSION < 50601) {
3667 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3668 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3669 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3670 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3671 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3672 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3673 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3674 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3675 } else {
3676 // If MySQl version is greater than or equal 5.6.1,
3677 // use the ST_ prefix.
3678 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3679 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3680 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3681 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3682 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3683 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3684 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3685 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3688 if ($display) {
3689 $funcs[] = array('display' => '--------');
3691 // Minimum bounding rectangle functions
3692 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3693 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3694 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3695 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3696 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3697 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3698 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3700 return $funcs;
3704 * Returns default function for a particular column.
3706 * @param array $field Data about the column for which
3707 * to generate the dropdown
3708 * @param bool $insert_mode Whether the operation is 'insert'
3710 * @global array $cfg PMA configuration
3711 * @global array $analyzed_sql Analyzed SQL query
3712 * @global mixed $data data of currently edited row
3713 * (used to detect whether to choose defaults)
3715 * @return string An HTML snippet of a dropdown list with function
3716 * names appropriate for the requested column.
3718 public static function getDefaultFunctionForField($field, $insert_mode)
3721 * @todo Except for $cfg, no longer use globals but pass as parameters
3722 * from higher levels
3724 global $cfg, $analyzed_sql, $data;
3726 $default_function = '';
3728 // Can we get field class based values?
3729 $current_class = $GLOBALS['PMA_Types']->getTypeClass($field['True_Type']);
3730 if (! empty($current_class)) {
3731 if (isset($cfg['DefaultFunctions']['FUNC_' . $current_class])) {
3732 $default_function
3733 = $cfg['DefaultFunctions']['FUNC_' . $current_class];
3737 $analyzed_sql_field_array = $analyzed_sql[0]['create_table_fields']
3738 [$field['Field']];
3739 // what function defined as default?
3740 // for the first timestamp we don't set the default function
3741 // if there is a default value for the timestamp
3742 // (not including CURRENT_TIMESTAMP)
3743 // and the column does not have the
3744 // ON UPDATE DEFAULT TIMESTAMP attribute.
3745 if (($field['True_Type'] == 'timestamp')
3746 && $field['first_timestamp']
3747 && empty($field['Default'])
3748 && empty($data)
3749 && ! isset($analyzed_sql_field_array['on_update_current_timestamp'])
3750 && ! (isset($analyzed_sql_field_array['default_value'])
3751 && $analyzed_sql_field_array['default_value'] == 'NULL')
3753 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3756 // For primary keys of type char(36) or varchar(36) UUID if the default
3757 // function
3758 // Only applies to insert mode, as it would silently trash data on updates.
3759 if ($insert_mode
3760 && $field['Key'] == 'PRI'
3761 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3763 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3766 return $default_function;
3770 * Creates a dropdown box with MySQL functions for a particular column.
3772 * @param array $field Data about the column for which
3773 * to generate the dropdown
3774 * @param bool $insert_mode Whether the operation is 'insert'
3776 * @return string An HTML snippet of a dropdown list with function
3777 * names appropriate for the requested column.
3779 public static function getFunctionsForField($field, $insert_mode)
3781 $default_function = self::getDefaultFunctionForField($field, $insert_mode);
3782 $dropdown_built = array();
3784 // Create the output
3785 $retval = '<option></option>' . "\n";
3786 // loop on the dropdown array and print all available options for that
3787 // field.
3788 $functions = $GLOBALS['PMA_Types']->getFunctions($field['True_Type']);
3789 foreach ($functions as $function) {
3790 $retval .= '<option';
3791 if ($default_function === $function) {
3792 $retval .= ' selected="selected"';
3794 $retval .= '>' . $function . '</option>' . "\n";
3795 $dropdown_built[$function] = true;
3798 // Create separator before all functions list
3799 if (count($functions) > 0) {
3800 $retval .= '<option value="" disabled="disabled">--------</option>'
3801 . "\n";
3804 // For compatibility's sake, do not let out all other functions. Instead
3805 // print a separator (blank) and then show ALL functions which weren't
3806 // shown yet.
3807 $functions = $GLOBALS['PMA_Types']->getAllFunctions();
3808 foreach ($functions as $function) {
3809 // Skip already included functions
3810 if (isset($dropdown_built[$function])) {
3811 continue;
3813 $retval .= '<option';
3814 if ($default_function === $function) {
3815 $retval .= ' selected="selected"';
3817 $retval .= '>' . $function . '</option>' . "\n";
3818 } // end for
3820 return $retval;
3821 } // end getFunctionsForField()
3824 * Checks if the current user has a specific privilege and returns true if the
3825 * user indeed has that privilege or false if (s)he doesn't. This function must
3826 * only be used for features that are available since MySQL 5, because it
3827 * relies on the INFORMATION_SCHEMA database to be present.
3829 * Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3830 * // Checks if the currently logged in user has the global
3831 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3832 * // user has this privilege on database 'mydb'.
3834 * @param string $priv The privilege to check
3835 * @param mixed $db null, to only check global privileges
3836 * string, db name where to also check for privileges
3837 * @param mixed $tbl null, to only check global/db privileges
3838 * string, table name where to also check for privileges
3840 * @return bool
3842 public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
3844 // Get the username for the current user in the format
3845 // required to use in the information schema database.
3846 $user = $GLOBALS['dbi']->fetchValue("SELECT CURRENT_USER();");
3847 if ($user === false) {
3848 return false;
3851 $user = explode('@', $user);
3852 $username = "''";
3853 $username .= str_replace("'", "''", $user[0]);
3854 $username .= "''@''";
3855 $username .= str_replace("'", "''", $user[1]);
3856 $username .= "''";
3858 // Prepare the query
3859 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3860 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3862 // Check global privileges first.
3863 $user_privileges = $GLOBALS['dbi']->fetchValue(
3864 sprintf(
3865 $query,
3866 'USER_PRIVILEGES',
3867 $username,
3868 $priv
3871 if ($user_privileges) {
3872 return true;
3874 // If a database name was provided and user does not have the
3875 // required global privilege, try database-wise permissions.
3876 if ($db !== null) {
3877 $query .= " AND '%s' LIKE `TABLE_SCHEMA`";
3878 $schema_privileges = $GLOBALS['dbi']->fetchValue(
3879 sprintf(
3880 $query,
3881 'SCHEMA_PRIVILEGES',
3882 $username,
3883 $priv,
3884 self::sqlAddSlashes($db)
3887 if ($schema_privileges) {
3888 return true;
3890 } else {
3891 // There was no database name provided and the user
3892 // does not have the correct global privilege.
3893 return false;
3895 // If a table name was also provided and we still didn't
3896 // find any valid privileges, try table-wise privileges.
3897 if ($tbl !== null) {
3898 // need to escape wildcards in db and table names, see bug #3518484
3899 $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
3900 $query .= " AND TABLE_NAME='%s'";
3901 $table_privileges = $GLOBALS['dbi']->fetchValue(
3902 sprintf(
3903 $query,
3904 'TABLE_PRIVILEGES',
3905 $username,
3906 $priv,
3907 self::sqlAddSlashes($db),
3908 self::sqlAddSlashes($tbl)
3911 if ($table_privileges) {
3912 return true;
3915 // If we reached this point, the user does not
3916 // have even valid table-wise privileges.
3917 return false;
3921 * Returns server type for current connection
3923 * Known types are: Drizzle, MariaDB and MySQL (default)
3925 * @return string
3927 public static function getServerType()
3929 $server_type = 'MySQL';
3930 if (PMA_DRIZZLE) {
3931 $server_type = 'Drizzle';
3932 return $server_type;
3935 if (/*overload*/mb_stripos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3936 $server_type = 'MariaDB';
3937 return $server_type;
3940 if (/*overload*/mb_stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3941 $server_type = 'Percona Server';
3942 return $server_type;
3945 return $server_type;
3949 * Analyzes the limit clause and return the start and length attributes of it.
3951 * @param string $limit_clause limit clause
3953 * @return array|bool Start and length attributes of the limit clause or false
3954 * on failure
3956 public static function analyzeLimitClause($limit_clause)
3958 $limitParams = trim(str_ireplace('LIMIT', '', $limit_clause));
3959 if ('' == $limitParams) {
3960 return false;
3963 $start_and_length = explode(',', $limitParams);
3964 $size = count($start_and_length);
3965 if ($size == 1) {
3966 return array(
3967 'start' => '0',
3968 'length' => trim($start_and_length[0])
3970 } elseif ($size == 2) {
3971 return array(
3972 'start' => trim($start_and_length[0]),
3973 'length' => trim($start_and_length[1])
3977 return false;
3981 * Prepare HTML code for display button.
3983 * @return String
3985 public static function getButton()
3987 return '<p class="print_ignore">'
3988 . '<input type="button" class="button" id="print" value="'
3989 . __('Print') . '" />'
3990 . '</p>';
3994 * Parses ENUM/SET values
3996 * @param string $definition The definition of the column
3997 * for which to parse the values
3998 * @param bool $escapeHtml Whether to escape html entities
4000 * @return array
4002 public static function parseEnumSetValues($definition, $escapeHtml = true)
4004 $values_string = htmlentities($definition, ENT_COMPAT, "UTF-8");
4005 // There is a JS port of the below parser in functions.js
4006 // If you are fixing something here,
4007 // you need to also update the JS port.
4008 $values = array();
4009 $in_string = false;
4010 $buffer = '';
4012 for ($i=0, $length = /*overload*/mb_strlen($values_string);
4013 $i < $length;
4014 $i++
4016 $curr = /*overload*/mb_substr($values_string, $i, 1);
4017 $next = ($i == /*overload*/mb_strlen($values_string)-1)
4018 ? ''
4019 : /*overload*/mb_substr($values_string, $i + 1, 1);
4021 if (! $in_string && $curr == "'") {
4022 $in_string = true;
4023 } else if (($in_string && $curr == "\\") && $next == "\\") {
4024 $buffer .= "&#92;";
4025 $i++;
4026 } else if (($in_string && $next == "'")
4027 && ($curr == "'" || $curr == "\\")
4029 $buffer .= "&#39;";
4030 $i++;
4031 } else if ($in_string && $curr == "'") {
4032 $in_string = false;
4033 $values[] = $buffer;
4034 $buffer = '';
4035 } else if ($in_string) {
4036 $buffer .= $curr;
4041 if (/*overload*/mb_strlen($buffer) > 0) {
4042 // The leftovers in the buffer are the last value (if any)
4043 $values[] = $buffer;
4046 if (! $escapeHtml) {
4047 foreach ($values as $key => $value) {
4048 $values[$key] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
4052 return $values;
4056 * fills given tooltip arrays
4058 * @param array &$tooltip_truename tooltip data
4059 * @param array &$tooltip_aliasname tooltip data
4060 * @param array $table tabledata
4062 * @return void
4064 public static function fillTooltip(
4065 &$tooltip_truename, &$tooltip_aliasname, $table
4067 if (/*overload*/mb_strstr($table['Comment'], '; InnoDB free') === false) {
4068 if (!/*overload*/mb_strstr($table['Comment'], 'InnoDB free') === false) {
4069 // here we have just InnoDB generated part
4070 $table['Comment'] = '';
4072 } else {
4073 // remove InnoDB comment from end, just the minimal part
4074 // (*? is non greedy)
4075 $table['Comment'] = preg_replace(
4076 '@; InnoDB free:.*?$@', '', $table['Comment']
4079 // views have VIEW as comment so it's not a real comment put by a user
4080 if ('VIEW' == $table['Comment']) {
4081 $table['Comment'] = '';
4083 if (empty($table['Comment'])) {
4084 $table['Comment'] = $table['Name'];
4085 } else {
4086 // todo: why?
4087 $table['Comment'] .= ' ';
4090 $tooltip_truename[$table['Name']] = $table['Name'];
4091 $tooltip_aliasname[$table['Name']] = $table['Comment'];
4093 if (isset($table['Create_time']) && !empty($table['Create_time'])) {
4094 $tooltip_aliasname[$table['Name']] .= ', ' . __('Creation')
4095 . ': '
4096 . PMA_Util::localisedDate(strtotime($table['Create_time']));
4099 if (! empty($table['Update_time'])) {
4100 $tooltip_aliasname[$table['Name']] .= ', ' . __('Last update')
4101 . ': '
4102 . PMA_Util::localisedDate(strtotime($table['Update_time']));
4105 if (! empty($table['Check_time'])) {
4106 $tooltip_aliasname[$table['Name']] .= ', ' . __('Last check')
4107 . ': '
4108 . PMA_Util::localisedDate(strtotime($table['Check_time']));
4113 * Get regular expression which occur first inside the given sql query.
4115 * @param Array $regex_array Comparing regular expressions.
4116 * @param String $query SQL query to be checked.
4118 * @return String Matching regular expression.
4120 public static function getFirstOccurringRegularExpression($regex_array, $query)
4122 $minimum_first_occurence_index = null;
4123 $regex = null;
4125 foreach ($regex_array as $test_regex) {
4126 if (preg_match($test_regex, $query, $matches, PREG_OFFSET_CAPTURE)) {
4127 if (is_null($minimum_first_occurence_index)
4128 || ($matches[0][1] < $minimum_first_occurence_index)
4130 $regex = $test_regex;
4131 $minimum_first_occurence_index = $matches[0][1];
4135 return $regex;
4139 * Return the list of tabs for the menu with corresponding names
4141 * @param string $level 'server', 'db' or 'table' level
4143 * @return array list of tabs for the menu
4145 public static function getMenuTabList($level = null)
4147 $tabList = array(
4148 'server' => array(
4149 'databases' => __('Databases'),
4150 'sql' => __('SQL'),
4151 'status' => __('Status'),
4152 'rights' => __('Users'),
4153 'export' => __('Export'),
4154 'import' => __('Import'),
4155 'settings' => __('Settings'),
4156 'binlog' => __('Binary log'),
4157 'replication' => __('Replication'),
4158 'vars' => __('Variables'),
4159 'charset' => __('Charsets'),
4160 'plugins' => __('Plugins'),
4161 'engine' => __('Engines')
4163 'db' => array(
4164 'structure' => __('Structure'),
4165 'sql' => __('SQL'),
4166 'search' => __('Search'),
4167 'qbe' => __('Query'),
4168 'export' => __('Export'),
4169 'import' => __('Import'),
4170 'operation' => __('Operations'),
4171 'privileges' => __('Privileges'),
4172 'routines' => __('Routines'),
4173 'events' => __('Events'),
4174 'triggers' => __('Triggers'),
4175 'tracking' => __('Tracking'),
4176 'designer' => __('Designer'),
4177 'central_columns' => __('Central columns')
4179 'table' => array(
4180 'browse' => __('Browse'),
4181 'structure' => __('Structure'),
4182 'sql' => __('SQL'),
4183 'search' => __('Search'),
4184 'insert' => __('Insert'),
4185 'export' => __('Export'),
4186 'import' => __('Import'),
4187 'privileges' => __('Privileges'),
4188 'operation' => __('Operations'),
4189 'tracking' => __('Tracking'),
4190 'triggers' => __('Triggers'),
4194 if ($level == null) {
4195 return $tabList;
4196 } else if (array_key_exists($level, $tabList)) {
4197 return $tabList[$level];
4198 } else {
4199 return null;
4204 * Returns information with regards to handling the http request
4206 * @param array $context Data about the context for which
4207 * to http request is sent
4209 * @return array of updated context information
4211 public static function handleContext(array $context)
4213 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUrl'])) {
4214 $context['http'] = array(
4215 'proxy' => $GLOBALS['cfg']['ProxyUrl'],
4216 'request_fulluri' => true
4218 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUser'])) {
4219 $auth = base64_encode(
4220 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4222 $context['http']['header'] .= 'Proxy-Authorization: Basic '
4223 . $auth . "\r\n";
4226 return $context;
4229 * Updates an existing curl as necessary
4231 * @param resource $curl_handle A curl_handle resource
4232 * created by curl_init which should
4233 * have several options set
4235 * @return resource curl_handle with updated options
4237 public static function configureCurl($curl_handle)
4239 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUrl'])) {
4240 curl_setopt($curl_handle, CURLOPT_PROXY, $GLOBALS['cfg']['ProxyUrl']);
4241 if (/*overload*/mb_strlen($GLOBALS['cfg']['ProxyUser'])) {
4242 curl_setopt(
4243 $curl_handle,
4244 CURLOPT_PROXYUSERPWD,
4245 $GLOBALS['cfg']['ProxyUser'] . ':' . $GLOBALS['cfg']['ProxyPass']
4249 curl_setopt($curl_handle, CURLOPT_USERAGENT, 'phpMyAdmin/' . PMA_VERSION);
4250 return $curl_handle;
4253 * Returns information with latest version from phpmyadmin.net
4255 * @return object JSON decoded object with the data
4257 public static function getLatestVersion()
4259 // wait 3s at most for server response, it's enough to get information
4260 // from a working server
4261 $connection_timeout = 3;
4263 $response = '{}';
4264 // Get response text from phpmyadmin.net or from the session
4265 // Update cache every 6 hours
4266 if (isset($_SESSION['cache']['version_check'])
4267 && time() < $_SESSION['cache']['version_check']['timestamp'] + 3600 * 6
4269 $save = false;
4270 $response = $_SESSION['cache']['version_check']['response'];
4271 } else {
4272 $save = true;
4273 $file = 'https://www.phpmyadmin.net/home_page/version.json';
4274 if (ini_get('allow_url_fopen')) {
4275 $context = array(
4276 'http' => array(
4277 'request_fulluri' => true,
4278 'timeout' => $connection_timeout,
4281 $context = PMA_Util::handleContext($context);
4282 if (! defined('TESTSUITE')) {
4283 session_write_close();
4285 $response = file_get_contents(
4286 $file,
4287 false,
4288 stream_context_create($context)
4290 } else if (function_exists('curl_init')) {
4291 $curl_handle = curl_init($file);
4292 if ($curl_handle === false) {
4293 return null;
4295 $curl_handle = PMA_Util::configureCurl($curl_handle);
4296 curl_setopt(
4297 $curl_handle,
4298 CURLOPT_HEADER,
4299 false
4301 curl_setopt(
4302 $curl_handle,
4303 CURLOPT_RETURNTRANSFER,
4304 true
4306 curl_setopt(
4307 $curl_handle,
4308 CURLOPT_TIMEOUT,
4309 $connection_timeout
4311 if (! defined('TESTSUITE')) {
4312 session_write_close();
4314 $response = curl_exec($curl_handle);
4318 $data = json_decode($response);
4319 if (is_object($data)
4320 && ! empty($data->version)
4321 && ! empty($data->date)
4322 && $save
4324 if (! isset($_SESSION) && ! defined('TESTSUITE')) {
4325 ini_set('session.use_only_cookies', 'false');
4326 ini_set('session.use_cookies', 'false');
4327 ini_set('session.use_trans_sid', 'false');
4328 ini_set('session.cache_limiter', 'nocache');
4329 session_start();
4331 $_SESSION['cache']['version_check'] = array(
4332 'response' => $response,
4333 'timestamp' => time()
4336 return $data;
4340 * Calculates numerical equivalent of phpMyAdmin version string
4342 * @param string $version version
4344 * @return mixed false on failure, integer on success
4346 public static function versionToInt($version)
4348 $parts = explode('-', $version);
4349 if (count($parts) > 1) {
4350 $suffix = $parts[1];
4351 } else {
4352 $suffix = '';
4354 $parts = explode('.', $parts[0]);
4356 $result = 0;
4358 if (count($parts) >= 1 && is_numeric($parts[0])) {
4359 $result += 1000000 * $parts[0];
4362 if (count($parts) >= 2 && is_numeric($parts[1])) {
4363 $result += 10000 * $parts[1];
4366 if (count($parts) >= 3 && is_numeric($parts[2])) {
4367 $result += 100 * $parts[2];
4370 if (count($parts) >= 4 && is_numeric($parts[3])) {
4371 $result += 1 * $parts[3];
4374 if (!empty($suffix)) {
4375 $matches = array();
4376 if (preg_match('/^(\D+)(\d+)$/', $suffix, $matches)) {
4377 $suffix = $matches[1];
4378 $result += intval($matches[2]);
4380 switch ($suffix) {
4381 case 'pl':
4382 $result += 60;
4383 break;
4384 case 'rc':
4385 $result += 30;
4386 break;
4387 case 'beta':
4388 $result += 20;
4389 break;
4390 case 'alpha':
4391 $result += 10;
4392 break;
4393 case 'dev':
4394 $result += 0;
4395 break;
4397 } else {
4398 $result += 50; // for final
4401 return $result;
4405 * Add fractional seconds to time, datetime and timestamp strings.
4406 * If the string contains fractional seconds,
4407 * pads it with 0s up to 6 decimal places.
4409 * @param string $value time, datetime or timestamp strings
4411 * @return string time, datetime or timestamp strings with fractional seconds
4413 public static function addMicroseconds($value)
4415 if (empty($value) || $value == 'CURRENT_TIMESTAMP') {
4416 return $value;
4419 if (/*overload*/mb_strpos($value, '.') === false) {
4420 return $value . '.000000';
4423 $value .= '000000';
4424 return /*overload*/mb_substr(
4425 $value,
4427 /*overload*/mb_strpos($value, '.') + 7
4432 * Reads the file, detects the compression MIME type, closes the file
4433 * and returns the MIME type
4435 * @param resource $file the file handle
4437 * @return string the MIME type for compression, or 'none'
4439 public static function getCompressionMimeType($file)
4441 $test = fread($file, 4);
4442 $len = strlen($test);
4443 fclose($file);
4444 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
4445 return 'application/gzip';
4447 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
4448 return 'application/bzip2';
4450 if ($len >= 4 && $test == "PK\003\004") {
4451 return 'application/zip';
4453 return 'none';
4457 * Renders a single link for the top of the navigation panel
4459 * @param string $link The url for the link
4460 * @param bool $showText Whether to show the text or to
4461 * only use it for title attributes
4462 * @param string $text The text to display and use for title attributes
4463 * @param bool $showIcon Whether to show the icon
4464 * @param string $icon The filename of the icon to show
4465 * @param string $linkId Value to use for the ID attribute
4466 * @param boolean $disableAjax Whether to disable ajax page loading for this link
4467 * @param string $linkTarget The name of the target frame for the link
4469 * @return string HTML code for one link
4471 public static function getNavigationLink(
4472 $link,
4473 $showText,
4474 $text,
4475 $showIcon,
4476 $icon,
4477 $linkId = '',
4478 $disableAjax = false,
4479 $linkTarget = ''
4481 $retval = '<a href="' . $link . '"';
4482 if (! empty($linkId)) {
4483 $retval .= ' id="' . $linkId . '"';
4485 if (! empty($linkTarget)) {
4486 $retval .= ' target="' . $linkTarget . '"';
4488 if ($disableAjax) {
4489 $retval .= ' class="disableAjax"';
4491 $retval .= ' title="' . $text . '">';
4492 if ($showIcon) {
4493 $retval .= PMA_Util::getImage(
4494 $icon,
4495 $text
4498 if ($showText) {
4499 $retval .= $text;
4501 $retval .= '</a>';
4502 if ($showText) {
4503 $retval .= '<br />';
4505 return $retval;
4509 * Provide COLLATE clause, if required, to perform case sensitive comparisons
4510 * for queries on information_schema.
4512 * @return string COLLATE clause if needed or empty string.
4514 public static function getCollateForIS()
4516 $lowerCaseTableNames = $GLOBALS['dbi']->fetchValue(
4517 "SHOW VARIABLES LIKE 'lower_case_table_names'", 0, 1
4520 if ($lowerCaseTableNames === '0') {
4521 return "COLLATE utf8_bin";
4523 return "";
4527 * Process the index data.
4529 * @param array $indexes index data
4531 * @return array processes index data
4533 public static function processIndexData($indexes)
4535 $lastIndex = '';
4537 $primary = '';
4538 $pk_array = array(); // will be use to emphasis prim. keys in the table
4539 $indexes_info = array();
4540 $indexes_data = array();
4542 // view
4543 foreach ($indexes as $row) {
4544 // Backups the list of primary keys
4545 if ($row['Key_name'] == 'PRIMARY') {
4546 $primary .= $row['Column_name'] . ', ';
4547 $pk_array[$row['Column_name']] = 1;
4549 // Retains keys informations
4550 if ($row['Key_name'] != $lastIndex) {
4551 $indexes[] = $row['Key_name'];
4552 $lastIndex = $row['Key_name'];
4554 $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index'];
4555 $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique'];
4556 if (isset($row['Cardinality'])) {
4557 $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality'];
4559 // I don't know what does following column mean....
4560 // $indexes_info[$row['Key_name']]['Packed'] = $row['Packed'];
4562 $indexes_info[$row['Key_name']]['Comment'] = $row['Comment'];
4564 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name']
4565 = $row['Column_name'];
4566 if (isset($row['Sub_part'])) {
4567 $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part']
4568 = $row['Sub_part'];
4571 } // end while
4573 return array($primary, $pk_array, $indexes_info, $indexes_data);
4577 * Returns the HTML for check all check box and with selected text
4578 * for multi submits
4580 * @param string $pmaThemeImage path to theme's image folder
4581 * @param string $text_dir text direction
4582 * @param string $formName name of the enclosing form
4584 * @return string HTML
4586 public static function getWithSelected($pmaThemeImage, $text_dir, $formName)
4588 $html = '<img class="selectallarrow" '
4589 . 'src="' . $pmaThemeImage . 'arrow_' . $text_dir . '.png" '
4590 . 'width="38" height="22" alt="' . __('With selected:') . '" />';
4591 $html .= '<input type="checkbox" id="' . $formName . '_checkall" '
4592 . 'class="checkall_box" title="' . __('Check All') . '" />'
4593 . '<label for="' . $formName . '_checkall">' . __('Check All')
4594 . '</label>';
4595 $html .= '<i style="margin-left: 2em">'
4596 . __('With selected:') . '</i>';
4598 return $html;