updated acknowledgments
[openemr.git] / phpmyadmin / libraries / Util.class.php
blob3468776a44ffe64d26dcf0c5fe31a5e2ba2d65d4
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 mixed $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 = false)
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 * Returns an HTML IMG tag for a particular icon from a theme,
91 * which may be an actual file or an icon from a sprite.
92 * This function takes into account the PropertiesIconic
93 * configuration setting and wraps the image tag in a span tag.
95 * @param string $icon name of icon file
96 * @param string $alternate alternate text
97 * @param boolean $force_text whether to force alternate text to be displayed
98 * @param boolean $menu_icon whether this icon is for the menu bar or not
100 * @return string an html snippet
102 public static function getIcon($icon, $alternate = '', $force_text = false,
103 $menu_icon = false
105 // $cfg['PropertiesIconic'] is true or both
106 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
107 // $cfg['PropertiesIconic'] is false or both
108 // OR we have no $include_icon
109 $include_text = ($force_text
110 || ($GLOBALS['cfg']['PropertiesIconic'] !== true));
112 // Sometimes use a span (we rely on this in js/sql.js). But for menu bar
113 // we don't need a span
114 $button = $menu_icon ? '' : '<span class="nowrap">';
115 if ($include_icon) {
116 $button .= self::getImage($icon, $alternate);
118 if ($include_icon && $include_text) {
119 $button .= ' ';
121 if ($include_text) {
122 $button .= $alternate;
124 $button .= $menu_icon ? '' : '</span>';
126 return $button;
130 * Returns an HTML IMG tag for a particular image from a theme,
131 * which may be an actual file or an icon from a sprite
133 * @param string $image The name of the file to get
134 * @param string $alternate Used to set 'alt' and 'title' attributes
135 * of the image
136 * @param array $attributes An associative array of other attributes
138 * @return string an html IMG tag
140 public static function getImage($image, $alternate = '', $attributes = array())
142 static $sprites; // cached list of available sprites (if any)
143 if (defined('TESTSUITE')) {
144 // prevent caching in testsuite
145 unset($sprites);
148 $url = '';
149 $is_sprite = false;
150 $alternate = htmlspecialchars($alternate);
152 // If it's the first time this function is called
153 if (! isset($sprites)) {
154 // Try to load the list of sprites
155 if (is_readable($_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php')) {
156 include_once $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
157 $sprites = PMA_sprites();
158 } else {
159 // No sprites are available for this theme
160 $sprites = array();
164 // Check if we have the requested image as a sprite
165 // and set $url accordingly
166 $class = str_replace(array('.gif','.png'), '', $image);
167 if (array_key_exists($class, $sprites)) {
168 $is_sprite = true;
169 $url = (defined('PMA_TEST_THEME') ? '../' : '') . 'themes/dot.gif';
170 } else {
171 $url = $GLOBALS['pmaThemeImage'] . $image;
174 // set class attribute
175 if ($is_sprite) {
176 if (isset($attributes['class'])) {
177 $attributes['class'] = "icon ic_$class " . $attributes['class'];
178 } else {
179 $attributes['class'] = "icon ic_$class";
183 // set all other attributes
184 $attr_str = '';
185 foreach ($attributes as $key => $value) {
186 if (! in_array($key, array('alt', 'title'))) {
187 $attr_str .= " $key=\"$value\"";
191 // override the alt attribute
192 if (isset($attributes['alt'])) {
193 $alt = $attributes['alt'];
194 } else {
195 $alt = $alternate;
198 // override the title attribute
199 if (isset($attributes['title'])) {
200 $title = $attributes['title'];
201 } else {
202 $title = $alternate;
205 // generate the IMG tag
206 $template = '<img src="%s" title="%s" alt="%s"%s />';
207 $retval = sprintf($template, $url, $title, $alt, $attr_str);
209 return $retval;
213 * Returns the formatted maximum size for an upload
215 * @param integer $max_upload_size the size
217 * @return string the message
219 * @access public
221 public static function getFormattedMaximumUploadSize($max_upload_size)
223 // I have to reduce the second parameter (sensitiveness) from 6 to 4
224 // to avoid weird results like 512 kKib
225 list($max_size, $max_unit) = self::formatByteDown($max_upload_size, 4);
226 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
230 * Generates a hidden field which should indicate to the browser
231 * the maximum size for upload
233 * @param integer $max_size the size
235 * @return string the INPUT field
237 * @access public
239 public static function generateHiddenMaxFileSize($max_size)
241 return '<input type="hidden" name="MAX_FILE_SIZE" value="'
242 . $max_size . '" />';
246 * Add slashes before "'" and "\" characters so a value containing them can
247 * be used in a sql comparison.
249 * @param string $a_string the string to slash
250 * @param bool $is_like whether the string will be used in a 'LIKE' clause
251 * (it then requires two more escaped sequences) or not
252 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
253 * (converts \n to \\n, \r to \\r)
254 * @param bool $php_code whether this function is used as part of the
255 * "Create PHP code" dialog
257 * @return string the slashed string
259 * @access public
261 public static function sqlAddSlashes(
262 $a_string = '', $is_like = false, $crlf = false, $php_code = false
264 if ($is_like) {
265 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
266 } else {
267 $a_string = str_replace('\\', '\\\\', $a_string);
270 if ($crlf) {
271 $a_string = strtr(
272 $a_string,
273 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
277 if ($php_code) {
278 $a_string = str_replace('\'', '\\\'', $a_string);
279 } else {
280 $a_string = str_replace('\'', '\'\'', $a_string);
283 return $a_string;
284 } // end of the 'sqlAddSlashes()' function
287 * Add slashes before "_" and "%" characters for using them in MySQL
288 * database, table and field names.
289 * Note: This function does not escape backslashes!
291 * @param string $name the string to escape
293 * @return string the escaped string
295 * @access public
297 public static function escapeMysqlWildcards($name)
299 return strtr($name, array('_' => '\\_', '%' => '\\%'));
300 } // end of the 'escapeMysqlWildcards()' function
303 * removes slashes before "_" and "%" characters
304 * Note: This function does not unescape backslashes!
306 * @param string $name the string to escape
308 * @return string the escaped string
310 * @access public
312 public static function unescapeMysqlWildcards($name)
314 return strtr($name, array('\\_' => '_', '\\%' => '%'));
315 } // end of the 'unescapeMysqlWildcards()' function
318 * removes quotes (',",`) from a quoted string
320 * checks if the string is quoted and removes this quotes
322 * @param string $quoted_string string to remove quotes from
323 * @param string $quote type of quote to remove
325 * @return string unqoted string
327 public static function unQuote($quoted_string, $quote = null)
329 $quotes = array();
331 if ($quote === null) {
332 $quotes[] = '`';
333 $quotes[] = '"';
334 $quotes[] = "'";
335 } else {
336 $quotes[] = $quote;
339 foreach ($quotes as $quote) {
340 if (substr($quoted_string, 0, 1) === $quote
341 && substr($quoted_string, -1, 1) === $quote
343 $unquoted_string = substr($quoted_string, 1, -1);
344 // replace escaped quotes
345 $unquoted_string = str_replace(
346 $quote . $quote,
347 $quote,
348 $unquoted_string
350 return $unquoted_string;
354 return $quoted_string;
358 * format sql strings
360 * @param mixed $parsed_sql pre-parsed SQL structure
361 * @param string $unparsed_sql raw SQL string
363 * @return string the formatted sql
365 * @global array the configuration array
366 * @global boolean whether the current statement is a multiple one or not
368 * @access public
369 * @todo move into PMA_Sql
371 public static function formatSql($parsed_sql, $unparsed_sql = '')
373 global $cfg;
375 // Check that we actually have a valid set of parsed data
376 // well, not quite
377 // first check for the SQL parser having hit an error
378 if (PMA_SQP_isError()) {
379 return htmlspecialchars($parsed_sql['raw']);
381 // then check for an array
382 if (! is_array($parsed_sql)) {
383 // We don't so just return the input directly
384 // This is intended to be used for when the SQL Parser is turned off
385 $formatted_sql = "<pre>\n";
386 if (($cfg['SQP']['fmtType'] == 'none') && ($unparsed_sql != '')) {
387 $formatted_sql .= $unparsed_sql;
388 } else {
389 $formatted_sql .= $parsed_sql;
391 $formatted_sql .= "\n</pre>";
392 return $formatted_sql;
395 $formatted_sql = '';
397 switch ($cfg['SQP']['fmtType']) {
398 case 'none':
399 if ($unparsed_sql != '') {
400 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
401 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
402 . '</pre></span>';
403 } else {
404 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
406 break;
407 case 'html':
408 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
409 break;
410 case 'text':
411 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
412 break;
413 default:
414 break;
415 } // end switch
417 return $formatted_sql;
418 } // end of the "formatSql()" function
421 * Displays a link to the documentation as an icon
423 * @param string $link documentation link
424 * @param string $target optional link target
426 * @return string the html link
428 * @access public
430 public static function showDocLink($link, $target = 'documentation')
432 return '<a href="' . $link . '" target="' . $target . '">'
433 . self::getImage('b_help.png', __('Documentation'))
434 . '</a>';
435 } // end of the 'showDocLink()' function
438 * Displays a link to the official MySQL documentation
440 * @param string $chapter chapter of "HTML, one page per chapter" documentation
441 * @param string $link contains name of page/anchor that is being linked
442 * @param bool $big_icon whether to use big icon (like in left frame)
443 * @param string $anchor anchor to page part
444 * @param bool $just_open whether only the opening <a> tag should be returned
446 * @return string the html link
448 * @access public
450 public static function showMySQLDocu(
451 $chapter, $link, $big_icon = false, $anchor = '', $just_open = false
453 global $cfg;
455 if (($cfg['MySQLManualType'] == 'none') || empty($cfg['MySQLManualBase'])) {
456 return '';
459 // Fixup for newly used names:
460 $chapter = str_replace('_', '-', strtolower($chapter));
461 $link = str_replace('_', '-', strtolower($link));
463 switch ($cfg['MySQLManualType']) {
464 case 'chapters':
465 if (empty($chapter)) {
466 $chapter = 'index';
468 if (empty($anchor)) {
469 $anchor = $link;
471 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
472 break;
473 case 'big':
474 if (empty($anchor)) {
475 $anchor = $link;
477 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
478 break;
479 case 'searchable':
480 if (empty($link)) {
481 $link = 'index';
483 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
484 if (! empty($anchor)) {
485 $url .= '#' . $anchor;
487 break;
488 case 'viewable':
489 default:
490 if (empty($link)) {
491 $link = 'index';
493 $mysql = '5.5';
494 $lang = 'en';
495 if (defined('PMA_MYSQL_INT_VERSION')) {
496 if (PMA_MYSQL_INT_VERSION >= 50600) {
497 $mysql = '5.6';
498 } else if (PMA_MYSQL_INT_VERSION >= 50500) {
499 $mysql = '5.5';
500 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
501 $mysql = '5.1';
502 } else {
503 $mysql = '5.0';
506 $url = $cfg['MySQLManualBase']
507 . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
508 if (! empty($anchor)) {
509 $url .= '#' . $anchor;
511 break;
514 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
515 if ($just_open) {
516 return $open_link;
517 } elseif ($big_icon) {
518 return $open_link
519 . self::getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
520 } else {
521 return self::showDocLink(PMA_linkURL($url), 'mysql_doc');
523 } // end of the 'showMySQLDocu()' function
526 * Returns link to documentation.
528 * @param string $page Page in documentation
529 * @param string $anchor Optional anchor in page
531 * @return string URL
533 public static function getDocuLink($page, $anchor = '')
535 /* Construct base URL */
536 $url = $page . '.html';
537 if (!empty($anchor)) {
538 $url .= '#' . $anchor;
541 /* Check if we have built local documentation */
542 if (defined('TESTSUITE')) {
543 /* Provide consistent URL for testsuite */
544 return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
545 } else if (file_exists('doc/html/index.html')) {
546 if (defined('PMA_SETUP')) {
547 return '../doc/html/' . $url;
548 } else {
549 return './doc/html/' . $url;
551 } else {
552 /* TODO: Should link to correct branch for released versions */
553 return PMA_linkURL('http://docs.phpmyadmin.net/en/latest/' . $url);
558 * Displays a link to the phpMyAdmin documentation
560 * @param string $page Page in documentation
561 * @param string $anchor Optional anchor in page
563 * @return string the html link
565 * @access public
567 public static function showDocu($page, $anchor = '')
569 return self::showDocLink(self::getDocuLink($page, $anchor));
570 } // end of the 'showDocu()' function
573 * Displays a link to the PHP documentation
575 * @param string $target anchor in documentation
577 * @return string the html link
579 * @access public
581 public static function showPHPDocu($target)
583 $url = PMA_getPHPDocLink($target);
585 return self::showDocLink($url);
586 } // end of the 'showPHPDocu()' function
589 * Returns HTML code for a tooltip
591 * @param string $message the message for the tooltip
593 * @return string
595 * @access public
597 public static function showHint($message)
599 if ($GLOBALS['cfg']['ShowHint']) {
600 $classClause = ' class="pma_hint"';
601 } else {
602 $classClause = '';
604 return '<span' . $classClause . '>'
605 . self::getImage('b_help.png')
606 . '<span class="hide">' . $message . '</span>'
607 . '</span>';
611 * Displays a MySQL error message in the main panel when $exit is true.
612 * Returns the error message otherwise.
614 * @param string $error_message the error message
615 * @param string $the_query the sql query that failed
616 * @param bool $is_modify_link whether to show a "modify" link or not
617 * @param string $back_url the "back" link url (full path is not required)
618 * @param bool $exit EXIT the page?
620 * @return mixed
622 * @global string the curent table
623 * @global string the current db
625 * @access public
627 public static function mysqlDie(
628 $error_message = '', $the_query = '',
629 $is_modify_link = true, $back_url = '', $exit = true
631 global $table, $db;
633 $error_msg = '';
635 if (! $error_message) {
636 $error_message = PMA_DBI_getError();
638 if (! $the_query && ! empty($GLOBALS['sql_query'])) {
639 $the_query = $GLOBALS['sql_query'];
642 // --- Added to solve bug #641765
643 if (! function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
644 $formatted_sql = htmlspecialchars($the_query);
645 } elseif (empty($the_query) || (trim($the_query) == '')) {
646 $formatted_sql = '';
647 } else {
648 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
649 $formatted_sql = htmlspecialchars(
650 substr(
651 $the_query, 0,
652 $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
655 . '[...]';
656 } else {
657 $formatted_sql = self::formatSql(
658 PMA_SQP_parse($the_query), $the_query
662 // ---
663 $error_msg .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
664 $error_msg .= ' <div class="error"><h1>' . __('Error')
665 . '</h1>' . "\n";
666 // if the config password is wrong, or the MySQL server does not
667 // respond, do not show the query that would reveal the
668 // username/password
669 if (! empty($the_query) && ! strstr($the_query, 'connect')) {
670 // --- Added to solve bug #641765
671 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
672 $error_msg .= PMA_SQP_getErrorString() . "\n";
673 $error_msg .= '<br />' . "\n";
675 // ---
676 // modified to show the help on sql errors
677 $error_msg .= '<p><strong>' . __('SQL query') . ':</strong>' . "\n";
678 if (strstr(strtolower($formatted_sql), 'select')) {
679 // please show me help to the error on select
680 $error_msg .= self::showMySQLDocu('SQL-Syntax', 'SELECT');
682 if ($is_modify_link) {
683 $_url_params = array(
684 'sql_query' => $the_query,
685 'show_query' => 1,
687 if (strlen($table)) {
688 $_url_params['db'] = $db;
689 $_url_params['table'] = $table;
690 $doedit_goto = '<a href="tbl_sql.php'
691 . PMA_generate_common_url($_url_params) . '">';
692 } elseif (strlen($db)) {
693 $_url_params['db'] = $db;
694 $doedit_goto = '<a href="db_sql.php'
695 . PMA_generate_common_url($_url_params) . '">';
696 } else {
697 $doedit_goto = '<a href="server_sql.php'
698 . PMA_generate_common_url($_url_params) . '">';
701 $error_msg .= $doedit_goto
702 . self::getIcon('b_edit.png', __('Edit'))
703 . '</a>';
704 } // end if
705 $error_msg .= ' </p>' . "\n"
706 .'<p>' . "\n"
707 . $formatted_sql . "\n"
708 . '</p>' . "\n";
709 } // end if
711 if (! empty($error_message)) {
712 $error_message = preg_replace(
713 "@((\015\012)|(\015)|(\012)){3,}@",
714 "\n\n",
715 $error_message
718 // modified to show the help on error-returns
719 // (now error-messages-server)
720 $error_msg .= '<p>' . "\n"
721 . ' <strong>' . __('MySQL said: ') . '</strong>'
722 . self::showMySQLDocu('Error-messages-server', 'Error-messages-server')
723 . "\n"
724 . '</p>' . "\n";
726 // The error message will be displayed within a CODE segment.
727 // To preserve original formatting, but allow wordwrapping,
728 // we do a couple of replacements
730 // Replace all non-single blanks with their HTML-counterpart
731 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
732 // Replace TAB-characters with their HTML-counterpart
733 $error_message = str_replace(
734 "\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message
736 // Replace linebreaks
737 $error_message = nl2br($error_message);
739 $error_msg .= '<code>' . "\n"
740 . $error_message . "\n"
741 . '</code><br />' . "\n";
742 $error_msg .= '</div>';
744 $_SESSION['Import_message']['message'] = $error_msg;
746 if ($exit) {
748 * If in an Ajax request
749 * - avoid displaying a Back link
750 * - use PMA_Response() to transmit the message and exit
752 if ($GLOBALS['is_ajax_request'] == true) {
753 $response = PMA_Response::getInstance();
754 $response->isSuccess(false);
755 $response->addJSON('message', $error_msg);
756 exit;
758 if (! empty($back_url)) {
759 if (strstr($back_url, '?')) {
760 $back_url .= '&amp;no_history=true';
761 } else {
762 $back_url .= '?no_history=true';
765 $_SESSION['Import_message']['go_back_url'] = $back_url;
767 $error_msg .= '<fieldset class="tblFooters">'
768 . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
769 . '</fieldset>' . "\n\n";
771 echo $error_msg;
772 exit;
773 } else {
774 return $error_msg;
776 } // end of the 'mysqlDie()' function
779 * returns array with tables of given db with extended information and grouped
781 * @param string $db name of db
782 * @param string $tables name of tables
783 * @param integer $limit_offset list offset
784 * @param int|bool $limit_count max tables to return
786 * @return array (recursive) grouped table list
788 public static function getTableList(
789 $db, $tables = null, $limit_offset = 0, $limit_count = false
791 $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
793 if ($tables === null) {
794 $tables = PMA_DBI_get_tables_full(
795 $db, false, false, null, $limit_offset, $limit_count
797 if ($GLOBALS['cfg']['NaturalOrder']) {
798 uksort($tables, 'strnatcasecmp');
802 if (count($tables) < 1) {
803 return $tables;
806 $default = array(
807 'Name' => '',
808 'Rows' => 0,
809 'Comment' => '',
810 'disp_name' => '',
813 $table_groups = array();
815 foreach ($tables as $table_name => $table) {
816 // check for correct row count
817 if ($table['Rows'] === null) {
818 // Do not check exact row count here,
819 // if row count is invalid possibly the table is defect
820 // and this would break left frame;
821 // but we can check row count if this is a view or the
822 // information_schema database
823 // since PMA_Table::countRecords() returns a limited row count
824 // in this case.
826 // set this because PMA_Table::countRecords() can use it
827 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
829 if ($tbl_is_view || PMA_is_system_schema($db)) {
830 $table['Rows'] = PMA_Table::countRecords(
831 $db,
832 $table['Name'],
833 false,
834 true
839 // in $group we save the reference to the place in $table_groups
840 // where to store the table info
841 if ($GLOBALS['cfg']['NavigationTreeEnableGrouping']
842 && $sep && strstr($table_name, $sep)
844 $parts = explode($sep, $table_name);
846 $group =& $table_groups;
847 $i = 0;
848 $group_name_full = '';
849 $parts_cnt = count($parts) - 1;
851 while (($i < $parts_cnt)
852 && ($i < $GLOBALS['cfg']['NavigationTreeTableLevel'])
854 $group_name = $parts[$i] . $sep;
855 $group_name_full .= $group_name;
857 if (! isset($group[$group_name])) {
858 $group[$group_name] = array();
859 $group[$group_name]['is' . $sep . 'group'] = true;
860 $group[$group_name]['tab' . $sep . 'count'] = 1;
861 $group[$group_name]['tab' . $sep . 'group']
862 = $group_name_full;
864 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
865 $table = $group[$group_name];
866 $group[$group_name] = array();
867 $group[$group_name][$group_name] = $table;
868 unset($table);
869 $group[$group_name]['is' . $sep . 'group'] = true;
870 $group[$group_name]['tab' . $sep . 'count'] = 1;
871 $group[$group_name]['tab' . $sep . 'group']
872 = $group_name_full;
874 } else {
875 $group[$group_name]['tab' . $sep . 'count']++;
878 $group =& $group[$group_name];
879 $i++;
882 } else {
883 if (! isset($table_groups[$table_name])) {
884 $table_groups[$table_name] = array();
886 $group =& $table_groups;
889 $table['disp_name'] = $table['Name'];
890 $group[$table_name] = array_merge($default, $table);
893 return $table_groups;
896 /* ----------------------- Set of misc functions ----------------------- */
899 * Adds backquotes on both sides of a database, table or field name.
900 * and escapes backquotes inside the name with another backquote
902 * example:
903 * <code>
904 * echo backquote('owner`s db'); // `owner``s db`
906 * </code>
908 * @param mixed $a_name the database, table or field name to "backquote"
909 * or array of it
910 * @param boolean $do_it a flag to bypass this function (used by dump
911 * functions)
913 * @return mixed the "backquoted" database, table or field name
915 * @access public
917 public static function backquote($a_name, $do_it = true)
919 if (is_array($a_name)) {
920 foreach ($a_name as &$data) {
921 $data = self::backquote($data, $do_it);
923 return $a_name;
926 if (! $do_it) {
927 global $PMA_SQPdata_forbidden_word;
928 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
929 return $a_name;
933 // '0' is also empty for php :-(
934 if (strlen($a_name) && $a_name !== '*') {
935 return '`' . str_replace('`', '``', $a_name) . '`';
936 } else {
937 return $a_name;
939 } // end of the 'backquote()' function
942 * Adds quotes on both sides of a database, table or field name.
943 * in compatibility mode
945 * example:
946 * <code>
947 * echo backquote('owner`s db'); // `owner``s db`
949 * </code>
951 * @param mixed $a_name the database, table or field name to
952 * "backquote" or array of it
953 * @param string $compatibility string compatibility mode (used by dump
954 * functions)
955 * @param boolean $do_it a flag to bypass this function (used by dump
956 * functions)
958 * @return mixed the "backquoted" database, table or field name
960 * @access public
962 public static function backquoteCompat(
963 $a_name, $compatibility = 'MSSQL', $do_it = true
965 if (is_array($a_name)) {
966 foreach ($a_name as &$data) {
967 $data = self::backquoteCompat($data, $compatibility, $do_it);
969 return $a_name;
972 if (! $do_it) {
973 global $PMA_SQPdata_forbidden_word;
974 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
975 return $a_name;
979 // @todo add more compatibility cases (ORACLE for example)
980 switch ($compatibility) {
981 case 'MSSQL':
982 $quote = '"';
983 break;
984 default:
985 (isset($GLOBALS['sql_backquotes'])) ? $quote = "`" : $quote = '';
986 break;
989 // '0' is also empty for php :-(
990 if (strlen($a_name) && $a_name !== '*') {
991 return $quote . $a_name . $quote;
992 } else {
993 return $a_name;
995 } // end of the 'backquoteCompat()' function
998 * Defines the <CR><LF> value depending on the user OS.
1000 * @return string the <CR><LF> value to use
1002 * @access public
1004 public static function whichCrlf()
1006 // The 'PMA_USR_OS' constant is defined in "libraries/Config.class.php"
1007 // Win case
1008 if (PMA_USR_OS == 'Win') {
1009 $the_crlf = "\r\n";
1010 } else {
1011 // Others
1012 $the_crlf = "\n";
1015 return $the_crlf;
1016 } // end of the 'whichCrlf()' function
1019 * Prepare the message and the query
1020 * usually the message is the result of the query executed
1022 * @param string $message the message to display
1023 * @param string $sql_query the query to display
1024 * @param string $type the type (level) of the message
1025 * @param boolean $is_view is this a message after a VIEW operation?
1027 * @return string
1029 * @access public
1031 public static function getMessage(
1032 $message, $sql_query = null, $type = 'notice', $is_view = false
1034 global $cfg;
1035 $retval = '';
1037 if (null === $sql_query) {
1038 if (! empty($GLOBALS['display_query'])) {
1039 $sql_query = $GLOBALS['display_query'];
1040 } elseif ($cfg['SQP']['fmtType'] == 'none'
1041 && ! empty($GLOBALS['unparsed_sql'])
1043 $sql_query = $GLOBALS['unparsed_sql'];
1044 } elseif (! empty($GLOBALS['sql_query'])) {
1045 $sql_query = $GLOBALS['sql_query'];
1046 } else {
1047 $sql_query = '';
1051 if (isset($GLOBALS['using_bookmark_message'])) {
1052 $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
1053 unset($GLOBALS['using_bookmark_message']);
1056 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1057 // check for it's presence before using it
1058 $retval .= '<div id="result_query"'
1059 . ( isset($GLOBALS['cell_align_left'])
1060 ? ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"'
1061 : '' )
1062 . '>' . "\n";
1064 if ($message instanceof PMA_Message) {
1065 if (isset($GLOBALS['special_message'])) {
1066 $message->addMessage($GLOBALS['special_message']);
1067 unset($GLOBALS['special_message']);
1069 $retval .= $message->getDisplay();
1070 } else {
1071 $retval .= '<div class="' . $type . '">';
1072 $retval .= PMA_sanitize($message);
1073 if (isset($GLOBALS['special_message'])) {
1074 $retval .= PMA_sanitize($GLOBALS['special_message']);
1075 unset($GLOBALS['special_message']);
1077 $retval .= '</div>';
1080 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1081 // Html format the query to be displayed
1082 // If we want to show some sql code it is easiest to create it here
1083 /* SQL-Parser-Analyzer */
1085 if (! empty($GLOBALS['show_as_php'])) {
1086 $new_line = '\\n"<br />' . "\n"
1087 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1088 $query_base = htmlspecialchars(addslashes($sql_query));
1089 $query_base = preg_replace(
1090 '/((\015\012)|(\015)|(\012))/', $new_line, $query_base
1092 } else {
1093 $query_base = $sql_query;
1096 $query_too_big = false;
1098 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1099 // when the query is large (for example an INSERT of binary
1100 // data), the parser chokes; so avoid parsing the query
1101 $query_too_big = true;
1102 $shortened_query_base = nl2br(
1103 htmlspecialchars(
1104 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL'])
1105 . '[...]'
1108 } elseif (! empty($GLOBALS['parsed_sql'])
1109 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1110 // (here, use "! empty" because when deleting a bookmark,
1111 // $GLOBALS['parsed_sql'] is set but empty
1112 $parsed_sql = $GLOBALS['parsed_sql'];
1113 } else {
1114 // Parse SQL if needed
1115 $parsed_sql = PMA_SQP_parse($query_base);
1118 // Analyze it
1119 if (isset($parsed_sql) && ! PMA_SQP_isError()) {
1120 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1122 // Same as below (append LIMIT), append the remembered ORDER BY
1123 if ($GLOBALS['cfg']['RememberSorting']
1124 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1125 && isset($GLOBALS['sql_order_to_append'])
1127 $query_base = $analyzed_display_query[0]['section_before_limit']
1128 . "\n" . $GLOBALS['sql_order_to_append']
1129 . $analyzed_display_query[0]['limit_clause'] . ' '
1130 . $analyzed_display_query[0]['section_after_limit'];
1132 // Need to reparse query
1133 $parsed_sql = PMA_SQP_parse($query_base);
1134 // update the $analyzed_display_query
1135 $analyzed_display_query[0]['section_before_limit']
1136 .= $GLOBALS['sql_order_to_append'];
1137 $analyzed_display_query[0]['order_by_clause']
1138 = $GLOBALS['sorted_col'];
1141 // Here we append the LIMIT added for navigation, to
1142 // enable its display. Adding it higher in the code
1143 // to $sql_query would create a problem when
1144 // using the Refresh or Edit links.
1146 // Only append it on SELECTs.
1149 * @todo what would be the best to do when someone hits Refresh:
1150 * use the current LIMITs ?
1153 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1154 && ! empty($GLOBALS['sql_limit_to_append'])
1156 $query_base = $analyzed_display_query[0]['section_before_limit']
1157 . "\n" . $GLOBALS['sql_limit_to_append']
1158 . $analyzed_display_query[0]['section_after_limit'];
1159 // Need to reparse query
1160 $parsed_sql = PMA_SQP_parse($query_base);
1164 if (! empty($GLOBALS['show_as_php'])) {
1165 $query_base = '$sql = "' . $query_base;
1166 } elseif (! empty($GLOBALS['validatequery'])) {
1167 try {
1168 $query_base = PMA_validateSQL($query_base);
1169 } catch (Exception $e) {
1170 $retval .= PMA_Message::error(
1171 __('Failed to connect to SQL validator!')
1172 )->getDisplay();
1174 } elseif (isset($parsed_sql)) {
1175 $query_base = self::formatSql($parsed_sql, $query_base);
1178 // Prepares links that may be displayed to edit/explain the query
1179 // (don't go to default pages, we must go to the page
1180 // where the query box is available)
1182 // Basic url query part
1183 $url_params = array();
1184 if (! isset($GLOBALS['db'])) {
1185 $GLOBALS['db'] = '';
1187 if (strlen($GLOBALS['db'])) {
1188 $url_params['db'] = $GLOBALS['db'];
1189 if (strlen($GLOBALS['table'])) {
1190 $url_params['table'] = $GLOBALS['table'];
1191 $edit_link = 'tbl_sql.php';
1192 } else {
1193 $edit_link = 'db_sql.php';
1195 } else {
1196 $edit_link = 'server_sql.php';
1199 // Want to have the query explained
1200 // but only explain a SELECT (that has not been explained)
1201 /* SQL-Parser-Analyzer */
1202 $explain_link = '';
1203 $is_select = false;
1204 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1205 $explain_params = $url_params;
1206 // Detect if we are validating as well
1207 // To preserve the validate uRL data
1208 if (! empty($GLOBALS['validatequery'])) {
1209 $explain_params['validatequery'] = 1;
1211 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1212 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1213 $_message = __('Explain SQL');
1214 $is_select = true;
1215 } elseif (
1216 preg_match(
1217 '@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query
1220 $explain_params['sql_query'] = substr($sql_query, 8);
1221 $_message = __('Skip Explain SQL');
1223 if (isset($explain_params['sql_query'])) {
1224 $explain_link = 'import.php'
1225 . PMA_generate_common_url($explain_params);
1226 $explain_link = ' ['
1227 . self::linkOrButton($explain_link, $_message) . ']';
1229 } //show explain
1231 $url_params['sql_query'] = $sql_query;
1232 $url_params['show_query'] = 1;
1234 // even if the query is big and was truncated, offer the chance
1235 // to edit it (unless it's enormous, see linkOrButton() )
1236 if (! empty($cfg['SQLQuery']['Edit'])) {
1237 if ($cfg['EditInWindow'] == true) {
1238 $onclick = 'PMA_querywindow.focus(\''
1239 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1240 } else {
1241 $onclick = '';
1244 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1245 $edit_link = ' ['
1246 . self::linkOrButton(
1247 $edit_link, __('Edit'),
1248 array('onclick' => $onclick, 'class' => 'disableAjax')
1250 . ']';
1251 } else {
1252 $edit_link = '';
1255 // Also we would like to get the SQL formed in some nice
1256 // php-code
1257 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1258 $php_params = $url_params;
1260 if (! empty($GLOBALS['show_as_php'])) {
1261 $_message = __('Without PHP Code');
1262 } else {
1263 $php_params['show_as_php'] = 1;
1264 $_message = __('Create PHP Code');
1267 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1268 $php_link = ' [' . self::linkOrButton($php_link, $_message) . ']';
1270 if (isset($GLOBALS['show_as_php'])) {
1272 $runquery_link = 'import.php'
1273 . PMA_generate_common_url($url_params);
1275 $php_link .= ' ['
1276 . self::linkOrButton($runquery_link, __('Submit Query'))
1277 . ']';
1279 } else {
1280 $php_link = '';
1281 } //show as php
1283 // Refresh query
1284 if (! empty($cfg['SQLQuery']['Refresh'])
1285 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1286 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1288 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1289 $refresh_link = ' ['
1290 . self::linkOrButton($refresh_link, __('Refresh')) . ']';
1291 } else {
1292 $refresh_link = '';
1293 } //refresh
1295 if (! empty($cfg['SQLValidator']['use'])
1296 && ! empty($cfg['SQLQuery']['Validate'])
1298 $validate_params = $url_params;
1299 if (! empty($GLOBALS['validatequery'])) {
1300 $validate_message = __('Skip Validate SQL');
1301 } else {
1302 $validate_params['validatequery'] = 1;
1303 $validate_message = __('Validate SQL');
1306 $validate_link = 'import.php'
1307 . PMA_generate_common_url($validate_params);
1308 $validate_link = ' ['
1309 . self::linkOrButton($validate_link, $validate_message) . ']';
1310 } else {
1311 $validate_link = '';
1312 } //validator
1314 if (! empty($GLOBALS['validatequery'])) {
1315 $retval .= '<div class="sqlvalidate">';
1316 } else {
1317 $retval .= '<code class="sql">';
1319 if ($query_too_big) {
1320 $retval .= $shortened_query_base;
1321 } else {
1322 $retval .= $query_base;
1325 //Clean up the end of the PHP
1326 if (! empty($GLOBALS['show_as_php'])) {
1327 $retval .= '";';
1329 if (! empty($GLOBALS['validatequery'])) {
1330 $retval .= '</div>';
1331 } else {
1332 $retval .= '</code>';
1335 $retval .= '<div class="tools">';
1336 // avoid displaying a Profiling checkbox that could
1337 // be checked, which would reexecute an INSERT, for example
1338 if (! empty($refresh_link)) {
1339 $retval .= self::getProfilingForm($sql_query);
1341 // if needed, generate an invisible form that contains controls for the
1342 // Inline link; this way, the behavior of the Inline link does not
1343 // depend on the profiling support or on the refresh link
1344 if (empty($refresh_link) || !self::profilingSupported()) {
1345 $retval .= '<form action="sql.php" method="post">';
1346 $retval .= PMA_generate_common_hidden_inputs(
1347 $GLOBALS['db'], $GLOBALS['table']
1349 $retval .= '<input type="hidden" name="sql_query" value="'
1350 . htmlspecialchars($sql_query) . '" />';
1351 $retval .= '</form>';
1354 // in the tools div, only display the Inline link when not in ajax
1355 // mode because 1) it currently does not work and 2) we would
1356 // have two similar mechanisms on the page for the same goal
1357 if ($is_select || ($GLOBALS['is_ajax_request'] === false)
1358 && ! $query_too_big
1360 // see in js/functions.js the jQuery code attached to id inline_edit
1361 // document.write conflicts with jQuery, hence used $().append()
1362 $retval .= "<script type=\"text/javascript\">\n" .
1363 "//<![CDATA[\n" .
1364 "$('.tools form').last().after('[ <a href=\"#\" title=\"" .
1365 PMA_escapeJsString(__('Inline edit of this query')) .
1366 "\" class=\"inline_edit_sql\">" .
1367 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1368 "</a> ]');\n" .
1369 "//]]>\n" .
1370 "</script>";
1372 $retval .= $edit_link . $explain_link . $php_link
1373 . $refresh_link . $validate_link;
1374 $retval .= '</div>';
1377 $retval .= '</div>';
1378 if ($GLOBALS['is_ajax_request'] === false) {
1379 $retval .= '<br class="clearfloat" />';
1382 return $retval;
1383 } // end of the 'getMessage()' function
1386 * Verifies if current MySQL server supports profiling
1388 * @access public
1390 * @return boolean whether profiling is supported
1392 public static function profilingSupported()
1394 if (!self::cacheExists('profiling_supported', true)) {
1395 // 5.0.37 has profiling but for example, 5.1.20 does not
1396 // (avoid a trip to the server for MySQL before 5.0.37)
1397 // and do not set a constant as we might be switching servers
1398 if (defined('PMA_MYSQL_INT_VERSION')
1399 && (PMA_MYSQL_INT_VERSION >= 50037)
1400 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1402 self::cacheSet('profiling_supported', true, true);
1403 } else {
1404 self::cacheSet('profiling_supported', false, true);
1408 return self::cacheGet('profiling_supported', true);
1412 * Returns HTML for the form with the Profiling checkbox
1414 * @param string $sql_query sql query
1416 * @return string HTML for the form with the Profiling checkbox
1418 * @access public
1420 public static function getProfilingForm($sql_query)
1422 $retval = '';
1423 if (self::profilingSupported()) {
1425 $retval .= '<form action="sql.php" method="post">' . "\n";
1426 $retval .= PMA_generate_common_hidden_inputs(
1427 $GLOBALS['db'], $GLOBALS['table']
1430 $retval .= '<input type="hidden" name="sql_query" value="'
1431 . htmlspecialchars($sql_query) . '" />' . "\n"
1432 . '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1434 $retval .= self::getCheckbox(
1435 'profiling', __('Profiling'), isset($_SESSION['profiling']), true
1437 $retval .= ' </form>' . "\n";
1440 return $retval;
1444 * Formats $value to byte view
1446 * @param double $value the value to format
1447 * @param int $limes the sensitiveness
1448 * @param int $comma the number of decimals to retain
1450 * @return array the formatted value and its unit
1452 * @access public
1454 public static function formatByteDown($value, $limes = 6, $comma = 0)
1456 if ($value === null) {
1457 return null;
1460 $byteUnits = array(
1461 /* l10n: shortcuts for Byte */
1462 __('B'),
1463 /* l10n: shortcuts for Kilobyte */
1464 __('KiB'),
1465 /* l10n: shortcuts for Megabyte */
1466 __('MiB'),
1467 /* l10n: shortcuts for Gigabyte */
1468 __('GiB'),
1469 /* l10n: shortcuts for Terabyte */
1470 __('TiB'),
1471 /* l10n: shortcuts for Petabyte */
1472 __('PiB'),
1473 /* l10n: shortcuts for Exabyte */
1474 __('EiB')
1477 $dh = self::pow(10, $comma);
1478 $li = self::pow(10, $limes);
1479 $unit = $byteUnits[0];
1481 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1482 if (isset($byteUnits[$d]) && ($value >= $li * self::pow(10, $ex))) {
1483 // use 1024.0 to avoid integer overflow on 64-bit machines
1484 $value = round($value / (self::pow(1024, $d) / $dh)) /$dh;
1485 $unit = $byteUnits[$d];
1486 break 1;
1487 } // end if
1488 } // end for
1490 if ($unit != $byteUnits[0]) {
1491 // if the unit is not bytes (as represented in current language)
1492 // reformat with max length of 5
1493 // 4th parameter=true means do not reformat if value < 1
1494 $return_value = self::formatNumber($value, 5, $comma, true);
1495 } else {
1496 // do not reformat, just handle the locale
1497 $return_value = self::formatNumber($value, 0);
1500 return array(trim($return_value), $unit);
1501 } // end of the 'formatByteDown' function
1504 * Changes thousands and decimal separators to locale specific values.
1506 * @param string $value the value
1508 * @return string
1510 public static function localizeNumber($value)
1512 return str_replace(
1513 array(',', '.'),
1514 array(
1515 /* l10n: Thousands separator */
1516 __(','),
1517 /* l10n: Decimal separator */
1518 __('.'),
1520 $value
1525 * Formats $value to the given length and appends SI prefixes
1526 * with a $length of 0 no truncation occurs, number is only formated
1527 * to the current locale
1529 * examples:
1530 * <code>
1531 * echo formatNumber(123456789, 6); // 123,457 k
1532 * echo formatNumber(-123456789, 4, 2); // -123.46 M
1533 * echo formatNumber(-0.003, 6); // -3 m
1534 * echo formatNumber(0.003, 3, 3); // 0.003
1535 * echo formatNumber(0.00003, 3, 2); // 0.03 m
1536 * echo formatNumber(0, 6); // 0
1537 * </code>
1539 * @param double $value the value to format
1540 * @param integer $digits_left number of digits left of the comma
1541 * @param integer $digits_right number of digits right of the comma
1542 * @param boolean $only_down do not reformat numbers below 1
1543 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1544 * (default: true)
1546 * @return string the formatted value and its unit
1548 * @access public
1550 public static function formatNumber(
1551 $value, $digits_left = 3, $digits_right = 0,
1552 $only_down = false, $noTrailingZero = true
1554 if ($value == 0) {
1555 return '0';
1558 $originalValue = $value;
1559 //number_format is not multibyte safe, str_replace is safe
1560 if ($digits_left === 0) {
1561 $value = number_format($value, $digits_right);
1562 if (($originalValue != 0) && (floatval($value) == 0)) {
1563 $value = ' <' . (1 / self::pow(10, $digits_right));
1565 return self::localizeNumber($value);
1568 // this units needs no translation, ISO
1569 $units = array(
1570 -8 => 'y',
1571 -7 => 'z',
1572 -6 => 'a',
1573 -5 => 'f',
1574 -4 => 'p',
1575 -3 => 'n',
1576 -2 => '&micro;',
1577 -1 => 'm',
1578 0 => ' ',
1579 1 => 'k',
1580 2 => 'M',
1581 3 => 'G',
1582 4 => 'T',
1583 5 => 'P',
1584 6 => 'E',
1585 7 => 'Z',
1586 8 => 'Y'
1589 // check for negative value to retain sign
1590 if ($value < 0) {
1591 $sign = '-';
1592 $value = abs($value);
1593 } else {
1594 $sign = '';
1597 $dh = self::pow(10, $digits_right);
1600 * This gives us the right SI prefix already,
1601 * but $digits_left parameter not incorporated
1603 $d = floor(log10($value) / 3);
1605 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1606 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1607 * to use, then lower the SI prefix
1609 $cur_digits = floor(log10($value / self::pow(1000, $d, 'pow'))+1);
1610 if ($digits_left > $cur_digits) {
1611 $d -= floor(($digits_left - $cur_digits)/3);
1614 if ($d < 0 && $only_down) {
1615 $d = 0;
1618 $value = round($value / (self::pow(1000, $d, 'pow') / $dh)) /$dh;
1619 $unit = $units[$d];
1621 // If we dont want any zeros after the comma just add the thousand separator
1622 if ($noTrailingZero) {
1623 $value = self::localizeNumber(
1624 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1626 } else {
1627 //number_format is not multibyte safe, str_replace is safe
1628 $value = self::localizeNumber(number_format($value, $digits_right));
1631 if ($originalValue != 0 && floatval($value) == 0) {
1632 return ' <' . (1 / self::pow(10, $digits_right)) . ' ' . $unit;
1635 return $sign . $value . ' ' . $unit;
1636 } // end of the 'formatNumber' function
1639 * Returns the number of bytes when a formatted size is given
1641 * @param string $formatted_size the size expression (for example 8MB)
1643 * @return integer The numerical part of the expression (for example 8)
1645 public static function extractValueFromFormattedSize($formatted_size)
1647 $return_value = -1;
1649 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1650 $return_value = substr($formatted_size, 0, -2) * self::pow(1024, 3);
1651 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1652 $return_value = substr($formatted_size, 0, -2) * self::pow(1024, 2);
1653 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1654 $return_value = substr($formatted_size, 0, -1) * self::pow(1024, 1);
1656 return $return_value;
1657 }// end of the 'extractValueFromFormattedSize' function
1660 * Writes localised date
1662 * @param string $timestamp the current timestamp
1663 * @param string $format format
1665 * @return string the formatted date
1667 * @access public
1669 public static function localisedDate($timestamp = -1, $format = '')
1671 $month = array(
1672 /* l10n: Short month name */
1673 __('Jan'),
1674 /* l10n: Short month name */
1675 __('Feb'),
1676 /* l10n: Short month name */
1677 __('Mar'),
1678 /* l10n: Short month name */
1679 __('Apr'),
1680 /* l10n: Short month name */
1681 _pgettext('Short month name', 'May'),
1682 /* l10n: Short month name */
1683 __('Jun'),
1684 /* l10n: Short month name */
1685 __('Jul'),
1686 /* l10n: Short month name */
1687 __('Aug'),
1688 /* l10n: Short month name */
1689 __('Sep'),
1690 /* l10n: Short month name */
1691 __('Oct'),
1692 /* l10n: Short month name */
1693 __('Nov'),
1694 /* l10n: Short month name */
1695 __('Dec'));
1696 $day_of_week = array(
1697 /* l10n: Short week day name */
1698 _pgettext('Short week day name', 'Sun'),
1699 /* l10n: Short week day name */
1700 __('Mon'),
1701 /* l10n: Short week day name */
1702 __('Tue'),
1703 /* l10n: Short week day name */
1704 __('Wed'),
1705 /* l10n: Short week day name */
1706 __('Thu'),
1707 /* l10n: Short week day name */
1708 __('Fri'),
1709 /* l10n: Short week day name */
1710 __('Sat'));
1712 if ($format == '') {
1713 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1714 $format = __('%B %d, %Y at %I:%M %p');
1717 if ($timestamp == -1) {
1718 $timestamp = time();
1721 $date = preg_replace(
1722 '@%[aA]@',
1723 $day_of_week[(int)strftime('%w', $timestamp)],
1724 $format
1726 $date = preg_replace(
1727 '@%[bB]@',
1728 $month[(int)strftime('%m', $timestamp)-1],
1729 $date
1732 return strftime($date, $timestamp);
1733 } // end of the 'localisedDate()' function
1736 * returns a tab for tabbed navigation.
1737 * If the variables $link and $args ar left empty, an inactive tab is created
1739 * @param array $tab array with all options
1740 * @param array $url_params tab specific URL parameters
1742 * @return string html code for one tab, a link if valid otherwise a span
1744 * @access public
1746 public static function getHtmlTab($tab, $url_params = array())
1748 // default values
1749 $defaults = array(
1750 'text' => '',
1751 'class' => '',
1752 'active' => null,
1753 'link' => '',
1754 'sep' => '?',
1755 'attr' => '',
1756 'args' => '',
1757 'warning' => '',
1758 'fragment' => '',
1759 'id' => '',
1762 $tab = array_merge($defaults, $tab);
1764 // determine additionnal style-class
1765 if (empty($tab['class'])) {
1766 if (! empty($tab['active'])
1767 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1769 $tab['class'] = 'active';
1770 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1771 && (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'])) {
1772 $tab['class'] = 'active';
1776 // If there are any tab specific URL parameters, merge those with
1777 // the general URL parameters
1778 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1779 $url_params = array_merge($url_params, $tab['url_params']);
1782 // build the link
1783 if (! empty($tab['link'])) {
1784 $tab['link'] = htmlentities($tab['link']);
1785 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1786 if (! empty($tab['args'])) {
1787 foreach ($tab['args'] as $param => $value) {
1788 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1789 . '=' . urlencode($value);
1794 if (! empty($tab['fragment'])) {
1795 $tab['link'] .= $tab['fragment'];
1798 // display icon
1799 if (isset($tab['icon'])) {
1800 // avoid generating an alt tag, because it only illustrates
1801 // the text that follows and if browser does not display
1802 // images, the text is duplicated
1803 $tab['text'] = self::getIcon($tab['icon'], $tab['text'], false, true);
1805 } elseif (empty($tab['text'])) {
1806 // check to not display an empty link-text
1807 $tab['text'] = '?';
1808 trigger_error(
1809 'empty linktext in function ' . __FUNCTION__ . '()',
1810 E_USER_NOTICE
1814 //Set the id for the tab, if set in the params
1815 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1816 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1818 if (! empty($tab['link'])) {
1819 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1820 .$id_string
1821 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1822 . $tab['text'] . '</a>';
1823 } else {
1824 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'
1825 . $id_string. '>' . $tab['text'] . '</span>';
1828 $out .= '</li>';
1829 return $out;
1830 } // end of the 'getHtmlTab()' function
1833 * returns html-code for a tab navigation
1835 * @param array $tabs one element per tab
1836 * @param string $url_params additional URL parameters
1837 * @param string $menu_id HTML id attribute for the menu container
1838 * @param bool $resizable whether to add a "resizable" class
1840 * @return string html-code for tab-navigation
1842 public static function getHtmlTabs($tabs, $url_params, $menu_id,
1843 $resizable = false
1845 $class = '';
1846 if ($resizable) {
1847 $class = ' class="resizable-menu"';
1850 $tab_navigation = '<div id="' . htmlentities($menu_id)
1851 . 'container" class="menucontainer">'
1852 .'<ul id="' . htmlentities($menu_id) . '" ' . $class . '>';
1854 foreach ($tabs as $tab) {
1855 $tab_navigation .= self::getHtmlTab($tab, $url_params);
1858 $tab_navigation .=
1859 '</ul>' . "\n"
1860 .'<div class="clearfloat"></div>'
1861 .'</div>' . "\n";
1863 return $tab_navigation;
1867 * Displays a link, or a button if the link's URL is too large, to
1868 * accommodate some browsers' limitations
1870 * @param string $url the URL
1871 * @param string $message the link message
1872 * @param mixed $tag_params string: js confirmation
1873 * array: additional tag params (f.e. style="")
1874 * @param boolean $new_form we set this to false when we are already in
1875 * a form, to avoid generating nested forms
1876 * @param boolean $strip_img whether to strip the image
1877 * @param string $target target
1879 * @return string the results to be echoed or saved in an array
1881 public static function linkOrButton(
1882 $url, $message, $tag_params = array(),
1883 $new_form = true, $strip_img = false, $target = ''
1885 $url_length = strlen($url);
1886 // with this we should be able to catch case of image upload
1887 // into a (MEDIUM) BLOB; not worth generating even a form for these
1888 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1889 return '';
1892 if (! is_array($tag_params)) {
1893 $tmp = $tag_params;
1894 $tag_params = array();
1895 if (! empty($tmp)) {
1896 $tag_params['onclick'] = 'return confirmLink(this, \''
1897 . PMA_escapeJsString($tmp) . '\')';
1899 unset($tmp);
1901 if (! empty($target)) {
1902 $tag_params['target'] = htmlentities($target);
1905 $tag_params_strings = array();
1906 foreach ($tag_params as $par_name => $par_value) {
1907 // htmlspecialchars() only on non javascript
1908 $par_value = substr($par_name, 0, 2) == 'on'
1909 ? $par_value
1910 : htmlspecialchars($par_value);
1911 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1914 $displayed_message = '';
1915 // Add text if not already added
1916 if (stristr($message, '<img')
1917 && (! $strip_img || ($GLOBALS['cfg']['PropertiesIconic'] === true))
1918 && (strip_tags($message) == $message)
1920 $displayed_message = '<span>'
1921 . htmlspecialchars(
1922 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1924 . '</span>';
1927 // Suhosin: Check that each query parameter is not above maximum
1928 $in_suhosin_limits = true;
1929 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1930 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1931 $query_parts = self::splitURLQuery($url);
1932 foreach ($query_parts as $query_pair) {
1933 list($eachvar, $eachval) = explode('=', $query_pair);
1934 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1935 $in_suhosin_limits = false;
1936 break;
1942 if (($url_length <= $GLOBALS['cfg']['LinkLengthLimit'])
1943 && $in_suhosin_limits
1945 // no whitespace within an <a> else Safari will make it part of the link
1946 $ret = "\n" . '<a href="' . $url . '" '
1947 . implode(' ', $tag_params_strings) . '>'
1948 . $message . $displayed_message . '</a>' . "\n";
1949 } else {
1950 // no spaces (linebreaks) at all
1951 // or after the hidden fields
1952 // IE will display them all
1954 // add class=link to submit button
1955 if (empty($tag_params['class'])) {
1956 $tag_params['class'] = 'link';
1959 if (! isset($query_parts)) {
1960 $query_parts = self::splitURLQuery($url);
1962 $url_parts = parse_url($url);
1964 if ($new_form) {
1965 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1966 . ' method="post"' . $target . ' style="display: inline;">';
1967 $subname_open = '';
1968 $subname_close = '';
1969 $submit_link = '#';
1970 } else {
1971 $query_parts[] = 'redirect=' . $url_parts['path'];
1972 if (empty($GLOBALS['subform_counter'])) {
1973 $GLOBALS['subform_counter'] = 0;
1975 $GLOBALS['subform_counter']++;
1976 $ret = '';
1977 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1978 $subname_close = ']';
1979 $submit_link = '#usesubform[' . $GLOBALS['subform_counter']
1980 . ']=1';
1983 foreach ($query_parts as $query_pair) {
1984 list($eachvar, $eachval) = explode('=', $query_pair);
1985 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1986 . $subname_close . '" value="'
1987 . htmlspecialchars(urldecode($eachval)) . '" />';
1988 } // end while
1990 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1991 . implode(' ', $tag_params_strings) . '>'
1992 . $message . ' ' . $displayed_message . '</a>' . "\n";
1994 if ($new_form) {
1995 $ret .= '</form>';
1997 } // end if... else...
1999 return $ret;
2000 } // end of the 'linkOrButton()' function
2003 * Splits a URL string by parameter
2005 * @param string $url the URL
2007 * @return array the parameter/value pairs, for example [0] db=sakila
2009 public static function splitURLQuery($url)
2011 // decode encoded url separators
2012 $separator = PMA_get_arg_separator();
2013 // on most places separator is still hard coded ...
2014 if ($separator !== '&') {
2015 // ... so always replace & with $separator
2016 $url = str_replace(htmlentities('&'), $separator, $url);
2017 $url = str_replace('&', $separator, $url);
2020 $url = str_replace(htmlentities($separator), $separator, $url);
2021 // end decode
2023 $url_parts = parse_url($url);
2025 return explode($separator, $url_parts['query']);
2029 * Returns a given timespan value in a readable format.
2031 * @param int $seconds the timespan
2033 * @return string the formatted value
2035 public static function timespanFormat($seconds)
2037 $days = floor($seconds / 86400);
2038 if ($days > 0) {
2039 $seconds -= $days * 86400;
2042 $hours = floor($seconds / 3600);
2043 if ($days > 0 || $hours > 0) {
2044 $seconds -= $hours * 3600;
2047 $minutes = floor($seconds / 60);
2048 if ($days > 0 || $hours > 0 || $minutes > 0) {
2049 $seconds -= $minutes * 60;
2052 return sprintf(
2053 __('%s days, %s hours, %s minutes and %s seconds'),
2054 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
2059 * Takes a string and outputs each character on a line for itself. Used
2060 * mainly for horizontalflipped display mode.
2061 * Takes care of special html-characters.
2062 * Fulfills https://sourceforge.net/p/phpmyadmin/feature-requests/164/
2064 * @param string $string The string
2065 * @param string $Separator The Separator (defaults to "<br />\n")
2067 * @access public
2068 * @todo add a multibyte safe function PMA_STR_split()
2070 * @return string The flipped string
2072 public static function flipstring($string, $Separator = "<br />\n")
2074 $format_string = '';
2075 $charbuff = false;
2077 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
2078 $char = $string{$i};
2079 $append = false;
2081 if ($char == '&') {
2082 $format_string .= $charbuff;
2083 $charbuff = $char;
2084 } elseif ($char == ';' && ! empty($charbuff)) {
2085 $format_string .= $charbuff . $char;
2086 $charbuff = false;
2087 $append = true;
2088 } elseif (! empty($charbuff)) {
2089 $charbuff .= $char;
2090 } else {
2091 $format_string .= $char;
2092 $append = true;
2095 // do not add separator after the last character
2096 if ($append && ($i != $str_len - 1)) {
2097 $format_string .= $Separator;
2101 return $format_string;
2105 * Function added to avoid path disclosures.
2106 * Called by each script that needs parameters, it displays
2107 * an error message and, by default, stops the execution.
2109 * Not sure we could use a strMissingParameter message here,
2110 * would have to check if the error message file is always available
2112 * @param array $params The names of the parameters needed by the calling script
2113 * @param bool $request Whether to include this list in checking for
2114 * special params
2116 * @return void
2118 * @global string path to current script
2119 * @global boolean flag whether any special variable was required
2121 * @access public
2123 public static function checkParameters($params, $request = true)
2125 global $checked_special;
2127 if (! isset($checked_special)) {
2128 $checked_special = false;
2131 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2132 $found_error = false;
2133 $error_message = '';
2135 foreach ($params as $param) {
2136 if ($request && ($param != 'db') && ($param != 'table')) {
2137 $checked_special = true;
2140 if (! isset($GLOBALS[$param])) {
2141 $error_message .= $reported_script_name
2142 . ': ' . __('Missing parameter:') . ' '
2143 . $param
2144 . self::showDocu('faq', 'faqmissingparameters')
2145 . '<br />';
2146 $found_error = true;
2149 if ($found_error) {
2150 PMA_fatalError($error_message, null, false);
2152 } // end function
2155 * Function to generate unique condition for specified row.
2157 * @param resource $handle current query result
2158 * @param integer $fields_cnt number of fields
2159 * @param array $fields_meta meta information about fields
2160 * @param array $row current row
2161 * @param boolean $force_unique generate condition only on pk or unique
2163 * @access public
2165 * @return array the calculated condition and whether condition is unique
2167 public static function getUniqueCondition(
2168 $handle, $fields_cnt, $fields_meta, $row, $force_unique = false
2170 $primary_key = '';
2171 $unique_key = '';
2172 $nonprimary_condition = '';
2173 $preferred_condition = '';
2174 $primary_key_array = array();
2175 $unique_key_array = array();
2176 $nonprimary_condition_array = array();
2177 $condition_array = array();
2179 for ($i = 0; $i < $fields_cnt; ++$i) {
2181 $condition = '';
2182 $con_key = '';
2183 $con_val = '';
2184 $field_flags = PMA_DBI_field_flags($handle, $i);
2185 $meta = $fields_meta[$i];
2187 // do not use a column alias in a condition
2188 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2189 $meta->orgname = $meta->name;
2191 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2192 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2194 foreach (
2195 $GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr
2197 // need (string) === (string)
2198 // '' !== 0 but '' == 0
2199 if ((string)$select_expr['alias'] === (string)$meta->name) {
2200 $meta->orgname = $select_expr['column'];
2201 break;
2202 } // end if
2203 } // end foreach
2207 // Do not use a table alias in a condition.
2208 // Test case is:
2209 // select * from galerie x WHERE
2210 //(select count(*) from galerie y where y.datum=x.datum)>1
2212 // But orgtable is present only with mysqli extension so the
2213 // fix is only for mysqli.
2214 // Also, do not use the original table name if we are dealing with
2215 // a view because this view might be updatable.
2216 // (The isView() verification should not be costly in most cases
2217 // because there is some caching in the function).
2218 if (isset($meta->orgtable)
2219 && ($meta->table != $meta->orgtable)
2220 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2222 $meta->table = $meta->orgtable;
2225 // to fix the bug where float fields (primary or not)
2226 // can't be matched because of the imprecision of
2227 // floating comparison, use CONCAT
2228 // (also, the syntax "CONCAT(field) IS NULL"
2229 // that we need on the next "if" will work)
2230 if ($meta->type == 'real') {
2231 $con_key = 'CONCAT(' . self::backquote($meta->table) . '.'
2232 . self::backquote($meta->orgname) . ')';
2233 } else {
2234 $con_key = self::backquote($meta->table) . '.'
2235 . self::backquote($meta->orgname);
2236 } // end if... else...
2237 $condition = ' ' . $con_key . ' ';
2239 if (! isset($row[$i]) || is_null($row[$i])) {
2240 $con_val = 'IS NULL';
2241 } else {
2242 // timestamp is numeric on some MySQL 4.1
2243 // for real we use CONCAT above and it should compare to string
2244 if ($meta->numeric
2245 && ($meta->type != 'timestamp')
2246 && ($meta->type != 'real')
2248 $con_val = '= ' . $row[$i];
2249 } elseif ((($meta->type == 'blob') || ($meta->type == 'string'))
2250 // hexify only if this is a true not empty BLOB or a BINARY
2251 && stristr($field_flags, 'BINARY')
2252 && ! empty($row[$i])
2254 // do not waste memory building a too big condition
2255 if (strlen($row[$i]) < 1000) {
2256 // use a CAST if possible, to avoid problems
2257 // if the field contains wildcard characters % or _
2258 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2259 } else if ($fields_cnt == 1) {
2260 // when this blob is the only field present
2261 // try settling with length comparison
2262 $condition = ' CHAR_LENGTH(' . $con_key . ') ';
2263 $con_val = ' = ' . strlen($row[$i]);
2264 } else {
2265 // this blob won't be part of the final condition
2266 $con_val = null;
2268 } elseif (in_array($meta->type, self::getGISDatatypes())
2269 && ! empty($row[$i])
2271 // do not build a too big condition
2272 if (strlen($row[$i]) < 5000) {
2273 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2274 } else {
2275 $condition = '';
2277 } elseif ($meta->type == 'bit') {
2278 $con_val = "= b'"
2279 . self::printableBitValue($row[$i], $meta->length) . "'";
2280 } else {
2281 $con_val = '= \''
2282 . self::sqlAddSlashes($row[$i], false, true) . '\'';
2286 if ($con_val != null) {
2288 $condition .= $con_val . ' AND';
2290 if ($meta->primary_key > 0) {
2291 $primary_key .= $condition;
2292 $primary_key_array[$con_key] = $con_val;
2293 } elseif ($meta->unique_key > 0) {
2294 $unique_key .= $condition;
2295 $unique_key_array[$con_key] = $con_val;
2298 $nonprimary_condition .= $condition;
2299 $nonprimary_condition_array[$con_key] = $con_val;
2301 } // end for
2303 // Correction University of Virginia 19991216:
2304 // prefer primary or unique keys for condition,
2305 // but use conjunction of all values if no primary key
2306 $clause_is_unique = true;
2308 if ($primary_key) {
2309 $preferred_condition = $primary_key;
2310 $condition_array = $primary_key_array;
2312 } elseif ($unique_key) {
2313 $preferred_condition = $unique_key;
2314 $condition_array = $unique_key_array;
2316 } elseif (! $force_unique) {
2317 $preferred_condition = $nonprimary_condition;
2318 $condition_array = $nonprimary_condition_array;
2319 $clause_is_unique = false;
2322 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2323 return(array($where_clause, $clause_is_unique, $condition_array));
2324 } // end function
2327 * Generate a button or image tag
2329 * @param string $button_name name of button element
2330 * @param string $button_class class of button or image element
2331 * @param string $image_name name of image element
2332 * @param string $text text to display
2333 * @param string $image image to display
2334 * @param string $value value
2336 * @return string html content
2338 * @access public
2340 public static function getButtonOrImage(
2341 $button_name, $button_class, $image_name, $text, $image, $value = ''
2343 if ($value == '') {
2344 $value = $text;
2347 if ($GLOBALS['cfg']['PropertiesIconic'] === false) {
2348 return ' <input type="submit" name="' . $button_name . '"'
2349 .' value="' . htmlspecialchars($value) . '"'
2350 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2353 /* Opera has trouble with <input type="image"> */
2354 /* IE (before version 9) has trouble with <button> */
2355 if (PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER < 9) {
2356 return '<input type="image" name="' . $image_name
2357 . '" class="' . $button_class
2358 . '" value="' . htmlspecialchars($value)
2359 . '" title="' . htmlspecialchars($text)
2360 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2361 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2362 ? '&nbsp;' . htmlspecialchars($text)
2363 : '') . "\n";
2364 } else {
2365 return '<button class="' . $button_class . '" type="submit"'
2366 .' name="' . $button_name . '" value="' . htmlspecialchars($value)
2367 . '" title="' . htmlspecialchars($text) . '">' . "\n"
2368 . self::getIcon($image, $text)
2369 .'</button>' . "\n";
2371 } // end function
2374 * Generate a pagination selector for browsing resultsets
2376 * @param string $name The name for the request parameter
2377 * @param int $rows Number of rows in the pagination set
2378 * @param int $pageNow current page number
2379 * @param int $nbTotalPage number of total pages
2380 * @param int $showAll If the number of pages is lower than this
2381 * variable, no pages will be omitted in pagination
2382 * @param int $sliceStart How many rows at the beginning should always
2383 * be shown?
2384 * @param int $sliceEnd How many rows at the end should always be shown?
2385 * @param int $percent Percentage of calculation page offsets to hop to a
2386 * next page
2387 * @param int $range Near the current page, how many pages should
2388 * be considered "nearby" and displayed as well?
2389 * @param string $prompt The prompt to display (sometimes empty)
2391 * @return string
2393 * @access public
2395 public static function pageselector(
2396 $name, $rows, $pageNow = 1, $nbTotalPage = 1, $showAll = 200,
2397 $sliceStart = 5,
2398 $sliceEnd = 5, $percent = 20, $range = 10, $prompt = ''
2400 $increment = floor($nbTotalPage / $percent);
2401 $pageNowMinusRange = ($pageNow - $range);
2402 $pageNowPlusRange = ($pageNow + $range);
2404 $gotopage = $prompt . ' <select class="pageselector ';
2405 $gotopage .= ' ajax';
2407 $gotopage .= '" name="' . $name . '" >';
2408 if ($nbTotalPage < $showAll) {
2409 $pages = range(1, $nbTotalPage);
2410 } else {
2411 $pages = array();
2413 // Always show first X pages
2414 for ($i = 1; $i <= $sliceStart; $i++) {
2415 $pages[] = $i;
2418 // Always show last X pages
2419 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2420 $pages[] = $i;
2423 // Based on the number of results we add the specified
2424 // $percent percentage to each page number,
2425 // so that we have a representing page number every now and then to
2426 // immediately jump to specific pages.
2427 // As soon as we get near our currently chosen page ($pageNow -
2428 // $range), every page number will be shown.
2429 $i = $sliceStart;
2430 $x = $nbTotalPage - $sliceEnd;
2431 $met_boundary = false;
2433 while ($i <= $x) {
2434 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2435 // If our pageselector comes near the current page, we use 1
2436 // counter increments
2437 $i++;
2438 $met_boundary = true;
2439 } else {
2440 // We add the percentage increment to our current page to
2441 // hop to the next one in range
2442 $i += $increment;
2444 // Make sure that we do not cross our boundaries.
2445 if ($i > $pageNowMinusRange && ! $met_boundary) {
2446 $i = $pageNowMinusRange;
2450 if ($i > 0 && $i <= $x) {
2451 $pages[] = $i;
2456 Add page numbers with "geometrically increasing" distances.
2458 This helps me a lot when navigating through giant tables.
2460 Test case: table with 2.28 million sets, 76190 pages. Page of interest
2461 is between 72376 and 76190.
2462 Selecting page 72376.
2463 Now, old version enumerated only +/- 10 pages around 72376 and the
2464 percentage increment produced steps of about 3000.
2466 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2467 around the current page.
2469 $i = $pageNow;
2470 $dist = 1;
2471 while ($i < $x) {
2472 $dist = 2 * $dist;
2473 $i = $pageNow + $dist;
2474 if ($i > 0 && $i <= $x) {
2475 $pages[] = $i;
2479 $i = $pageNow;
2480 $dist = 1;
2481 while ($i >0) {
2482 $dist = 2 * $dist;
2483 $i = $pageNow - $dist;
2484 if ($i > 0 && $i <= $x) {
2485 $pages[] = $i;
2489 // Since because of ellipsing of the current page some numbers may be
2490 // double, we unify our array:
2491 sort($pages);
2492 $pages = array_unique($pages);
2495 foreach ($pages as $i) {
2496 if ($i == $pageNow) {
2497 $selected = 'selected="selected" style="font-weight: bold"';
2498 } else {
2499 $selected = '';
2501 $gotopage .= ' <option ' . $selected
2502 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2505 $gotopage .= ' </select>';
2507 return $gotopage;
2508 } // end function
2511 * Prepare navigation for a list
2513 * @param int $count number of elements in the list
2514 * @param int $pos current position in the list
2515 * @param array $_url_params url parameters
2516 * @param string $script script name for form target
2517 * @param string $frame target frame
2518 * @param int $max_count maximum number of elements to display from the list
2519 * @param string $name the name for the request parameter
2520 * @param array $classes additional classes for the container
2522 * @return string $list_navigator_html the html content
2524 * @access public
2526 * @todo use $pos from $_url_params
2528 public static function getListNavigator(
2529 $count, $pos, $_url_params, $script, $frame, $max_count, $name = 'pos',
2530 $classes = array()
2533 $class = $frame == 'frame_navigation' ? ' class="ajax"' : '';
2535 $list_navigator_html = '';
2537 if ($max_count < $count) {
2539 $classes[] = 'pageselector';
2540 $list_navigator_html .= '<div class="' . implode(' ', $classes) . '">';
2542 if ($frame != 'frame_navigation') {
2543 $list_navigator_html .= __('Page number:');
2546 // Move to the beginning or to the previous page
2547 if ($pos > 0) {
2548 // patch #474210 - part 1
2549 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2550 $caption1 = '&lt;&lt;';
2551 $caption2 = ' &lt; ';
2552 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2553 $title2 = ' title="'
2554 . _pgettext('Previous page', 'Previous') . '"';
2555 } else {
2556 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2557 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2558 $title1 = '';
2559 $title2 = '';
2560 } // end if... else...
2562 $_url_params[$name] = 0;
2563 $list_navigator_html .= '<a' . $class . $title1 . ' href="' . $script
2564 . PMA_generate_common_url($_url_params) . '">' . $caption1
2565 . '</a>';
2567 $_url_params[$name] = $pos - $max_count;
2568 $list_navigator_html .= '<a' . $class . $title2 . ' href="' . $script
2569 . PMA_generate_common_url($_url_params) . '">' . $caption2
2570 . '</a>';
2573 $list_navigator_html .= '<form action="' . basename($script).
2574 '" method="post">';
2576 $list_navigator_html .= PMA_generate_common_hidden_inputs($_url_params);
2577 $list_navigator_html .= self::pageselector(
2578 $name,
2579 $max_count,
2580 floor(($pos + 1) / $max_count) + 1,
2581 ceil($count / $max_count)
2583 $list_navigator_html .= '</form>';
2585 if ($pos + $max_count < $count) {
2586 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2587 $caption3 = ' &gt; ';
2588 $caption4 = '&gt;&gt;';
2589 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2590 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2591 } else {
2592 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2593 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2594 $title3 = '';
2595 $title4 = '';
2596 } // end if... else...
2598 $_url_params[$name] = $pos + $max_count;
2599 $list_navigator_html .= '<a' . $class . $title3 . ' href="' . $script
2600 . PMA_generate_common_url($_url_params) . '" >' . $caption3
2601 . '</a>';
2603 $_url_params[$name] = floor($count / $max_count) * $max_count;
2604 if ($_url_params[$name] == $count) {
2605 $_url_params[$name] = $count - $max_count;
2608 $list_navigator_html .= '<a' . $class . $title4 . ' href="' . $script
2609 . PMA_generate_common_url($_url_params) . '" >' . $caption4
2610 . '</a>';
2612 $list_navigator_html .= '</div>' . "\n";
2615 return $list_navigator_html;
2619 * replaces %u in given path with current user name
2621 * example:
2622 * <code>
2623 * $user_dir = userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2625 * </code>
2627 * @param string $dir with wildcard for user
2629 * @return string per user directory
2631 public static function userDir($dir)
2633 // add trailing slash
2634 if (substr($dir, -1) != '/') {
2635 $dir .= '/';
2638 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2642 * returns html code for db link to default db page
2644 * @param string $database database
2646 * @return string html link to default db page
2648 public static function getDbLink($database = null)
2650 if (! strlen($database)) {
2651 if (! strlen($GLOBALS['db'])) {
2652 return '';
2654 $database = $GLOBALS['db'];
2655 } else {
2656 $database = self::unescapeMysqlWildcards($database);
2659 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2660 . PMA_generate_common_url($database) . '" title="'
2661 . sprintf(
2662 __('Jump to database &quot;%s&quot;.'),
2663 htmlspecialchars($database)
2665 . '">' . htmlspecialchars($database) . '</a>';
2669 * Prepare a lightbulb hint explaining a known external bug
2670 * that affects a functionality
2672 * @param string $functionality localized message explaining the func.
2673 * @param string $component 'mysql' (eventually, 'php')
2674 * @param string $minimum_version of this component
2675 * @param string $bugref bug reference for this component
2677 * @return void
2679 public static function getExternalBug(
2680 $functionality, $component, $minimum_version, $bugref
2682 $ext_but_html = '';
2683 if (($component == 'mysql') && (PMA_MYSQL_INT_VERSION < $minimum_version)) {
2684 $ext_but_html .= self::showHint(
2685 sprintf(
2686 __('The %s functionality is affected by a known bug, see %s'),
2687 $functionality,
2688 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2692 return $ext_but_html;
2696 * Returns a HTML checkbox
2698 * @param string $html_field_name the checkbox HTML field
2699 * @param string $label label for checkbox
2700 * @param boolean $checked is it initially checked?
2701 * @param boolean $onclick should it submit the form on click?
2703 * @return string HTML for the checkbox
2705 public static function getCheckbox($html_field_name, $label, $checked, $onclick)
2707 return '<input type="checkbox" name="' . $html_field_name . '" id="'
2708 . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
2709 . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
2710 . $html_field_name . '">' . $label . '</label>';
2714 * Generates a set of radio HTML fields
2716 * @param string $html_field_name the radio HTML field
2717 * @param array $choices the choices values and labels
2718 * @param string $checked_choice the choice to check by default
2719 * @param boolean $line_break whether to add HTML line break after a choice
2720 * @param boolean $escape_label whether to use htmlspecialchars() on label
2721 * @param string $class enclose each choice with a div of this class
2723 * @return string set of html radio fiels
2725 public static function getRadioFields(
2726 $html_field_name, $choices, $checked_choice = '',
2727 $line_break = true, $escape_label = true, $class = ''
2729 $radio_html = '';
2731 foreach ($choices as $choice_value => $choice_label) {
2733 if (! empty($class)) {
2734 $radio_html .= '<div class="' . $class . '">';
2737 $html_field_id = $html_field_name . '_' . $choice_value;
2738 $radio_html .= '<input type="radio" name="' . $html_field_name . '" id="'
2739 . $html_field_id . '" value="'
2740 . htmlspecialchars($choice_value) . '"';
2742 if ($choice_value == $checked_choice) {
2743 $radio_html .= ' checked="checked"';
2746 $radio_html .= ' />' . "\n"
2747 . '<label for="' . $html_field_id . '">'
2748 . ($escape_label
2749 ? htmlspecialchars($choice_label)
2750 : $choice_label)
2751 . '</label>';
2753 if ($line_break) {
2754 $radio_html .= '<br />';
2757 if (! empty($class)) {
2758 $radio_html .= '</div>';
2760 $radio_html .= "\n";
2763 return $radio_html;
2767 * Generates and returns an HTML dropdown
2769 * @param string $select_name name for the select element
2770 * @param array $choices choices values
2771 * @param string $active_choice the choice to select by default
2772 * @param string $id id of the select element; can be different in
2773 * case the dropdown is present more than once
2774 * on the page
2776 * @return string html content
2778 * @todo support titles
2780 public static function getDropdown($select_name, $choices, $active_choice, $id)
2782 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2783 . htmlspecialchars($id) . '">';
2785 foreach ($choices as $one_choice_value => $one_choice_label) {
2786 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2788 if ($one_choice_value == $active_choice) {
2789 $result .= ' selected="selected"';
2791 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2793 $result .= '</select>';
2795 return $result;
2799 * Generates a slider effect (jQjuery)
2800 * Takes care of generating the initial <div> and the link
2801 * controlling the slider; you have to generate the </div> yourself
2802 * after the sliding section.
2804 * @param string $id the id of the <div> on which to apply the effect
2805 * @param string $message the message to show as a link
2807 * @return string html div element
2810 public static function getDivForSliderEffect($id, $message)
2812 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2813 return '<div id="' . $id . '">';
2816 * Bad hack on the next line. document.write() conflicts with jQuery,
2817 * hence, opening the <div> with PHP itself instead of JavaScript.
2819 * @todo find a better solution that uses $.append(), the recommended
2820 * method maybe by using an additional param, the id of the div to
2821 * append to
2824 return '<div id="' . $id . '"'
2825 . (($GLOBALS['cfg']['InitialSlidersState'] == 'closed')
2826 ? ' style="display: none; overflow:auto;"'
2827 : '')
2828 . ' class="pma_auto_slider" title="' . htmlspecialchars($message) . '">';
2832 * Creates an AJAX sliding toggle button
2833 * (or and equivalent form when AJAX is disabled)
2835 * @param string $action The URL for the request to be executed
2836 * @param string $select_name The name for the dropdown box
2837 * @param array $options An array of options (see rte_footer.lib.php)
2838 * @param string $callback A JS snippet to execute when the request is
2839 * successfully processed
2841 * @return string HTML code for the toggle button
2843 public static function toggleButton($action, $select_name, $options, $callback)
2845 // Do the logic first
2846 $link = "$action&amp;" . urlencode($select_name) . "=";
2847 $link_on = $link . urlencode($options[1]['value']);
2848 $link_off = $link . urlencode($options[0]['value']);
2850 if ($options[1]['selected'] == true) {
2851 $state = 'on';
2852 } else if ($options[0]['selected'] == true) {
2853 $state = 'off';
2854 } else {
2855 $state = 'on';
2858 // Generate output
2859 return "<!-- TOGGLE START -->\n"
2860 . "<div class='wrapper toggleAjax hide'>\n"
2861 . " <div class='toggleButton'>\n"
2862 . " <div title='" . __('Click to toggle')
2863 . "' class='container $state'>\n"
2864 . " <img src='" . htmlspecialchars($GLOBALS['pmaThemeImage'])
2865 . "toggle-" . htmlspecialchars($GLOBALS['text_dir']) . ".png'\n"
2866 . " alt='' />\n"
2867 . " <table class='nospacing nopadding'>\n"
2868 . " <tbody>\n"
2869 . " <tr>\n"
2870 . " <td class='toggleOn'>\n"
2871 . " <span class='hide'>$link_on</span>\n"
2872 . " <div>"
2873 . str_replace(' ', '&nbsp;', htmlspecialchars($options[1]['label']))
2874 . "\n" . " </div>\n"
2875 . " </td>\n"
2876 . " <td><div>&nbsp;</div></td>\n"
2877 . " <td class='toggleOff'>\n"
2878 . " <span class='hide'>$link_off</span>\n"
2879 . " <div>"
2880 . str_replace(' ', '&nbsp;', htmlspecialchars($options[0]['label']))
2881 . "\n" . " </div>\n"
2882 . " </tr>\n"
2883 . " </tbody>\n"
2884 . " </table>\n"
2885 . " <span class='hide callback'>"
2886 . htmlspecialchars($callback) . "</span>\n"
2887 . " <span class='hide text_direction'>"
2888 . htmlspecialchars($GLOBALS['text_dir']) . "</span>\n"
2889 . " </div>\n"
2890 . " </div>\n"
2891 . "</div>\n"
2892 . "<!-- TOGGLE END -->";
2894 } // end toggleButton()
2897 * Clears cache content which needs to be refreshed on user change.
2899 * @return void
2901 public static function clearUserCache()
2903 self::cacheUnset('is_superuser', true);
2907 * Verifies if something is cached in the session
2909 * @param string $var variable name
2910 * @param int|true $server server
2912 * @return boolean
2914 public static function cacheExists($var, $server = 0)
2916 if ($server === true) {
2917 $server = $GLOBALS['server'];
2919 return isset($_SESSION['cache']['server_' . $server][$var]);
2923 * Gets cached information from the session
2925 * @param string $var varibale name
2926 * @param int|true $server server
2928 * @return mixed
2930 public static function cacheGet($var, $server = 0)
2932 if ($server === true) {
2933 $server = $GLOBALS['server'];
2935 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2936 return $_SESSION['cache']['server_' . $server][$var];
2937 } else {
2938 return null;
2943 * Caches information in the session
2945 * @param string $var variable name
2946 * @param mixed $val value
2947 * @param int|true $server server
2949 * @return mixed
2951 public static function cacheSet($var, $val = null, $server = 0)
2953 if ($server === true) {
2954 $server = $GLOBALS['server'];
2956 $_SESSION['cache']['server_' . $server][$var] = $val;
2960 * Removes cached information from the session
2962 * @param string $var variable name
2963 * @param int|true $server server
2965 * @return void
2967 public static function cacheUnset($var, $server = 0)
2969 if ($server === true) {
2970 $server = $GLOBALS['server'];
2972 unset($_SESSION['cache']['server_' . $server][$var]);
2976 * Converts a bit value to printable format;
2977 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2978 * function because in PHP, decbin() supports only 32 bits
2980 * @param numeric $value coming from a BIT field
2981 * @param integer $length length
2983 * @return string the printable value
2985 public static function printableBitValue($value, $length)
2987 $printable = '';
2988 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2989 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2991 $printable = substr($printable, -$length);
2992 return $printable;
2996 * Verifies whether the value contains a non-printable character
2998 * @param string $value value
3000 * @return boolean
3002 public static function containsNonPrintableAscii($value)
3004 return preg_match('@[^[:print:]]@', $value);
3008 * Converts a BIT type default value
3009 * for example, b'010' becomes 010
3011 * @param string $bit_default_value value
3013 * @return string the converted value
3015 public static function convertBitDefaultValue($bit_default_value)
3017 return strtr($bit_default_value, array("b" => "", "'" => ""));
3021 * Extracts the various parts from a column spec
3023 * @param string $columnspec Column specification
3025 * @return array associative array containing type, spec_in_brackets
3026 * and possibly enum_set_values (another array)
3028 public static function extractColumnSpec($columnspec)
3030 $first_bracket_pos = strpos($columnspec, '(');
3031 if ($first_bracket_pos) {
3032 $spec_in_brackets = chop(
3033 substr(
3034 $columnspec,
3035 $first_bracket_pos + 1,
3036 (strrpos($columnspec, ')') - $first_bracket_pos - 1)
3039 // convert to lowercase just to be sure
3040 $type = strtolower(chop(substr($columnspec, 0, $first_bracket_pos)));
3041 } else {
3042 $type = strtolower($columnspec);
3043 $spec_in_brackets = '';
3046 if ('enum' == $type || 'set' == $type) {
3047 // Define our working vars
3048 $enum_set_values = self::parseEnumSetValues($columnspec, false);
3049 $printtype = $type
3050 . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
3051 $binary = false;
3052 $unsigned = false;
3053 $zerofill = false;
3054 } else {
3055 $enum_set_values = array();
3057 /* Create printable type name */
3058 $printtype = strtolower($columnspec);
3060 // Strip the "BINARY" attribute, except if we find "BINARY(" because
3061 // this would be a BINARY or VARBINARY column type;
3062 // by the way, a BLOB should not show the BINARY attribute
3063 // because this is not accepted in MySQL syntax.
3064 if (preg_match('@binary@', $printtype)
3065 && ! preg_match('@binary[\(]@', $printtype)
3067 $printtype = preg_replace('@binary@', '', $printtype);
3068 $binary = true;
3069 } else {
3070 $binary = false;
3073 $printtype = preg_replace(
3074 '@zerofill@', '', $printtype, -1, $zerofill_cnt
3076 $zerofill = ($zerofill_cnt > 0);
3077 $printtype = preg_replace(
3078 '@unsigned@', '', $printtype, -1, $unsigned_cnt
3080 $unsigned = ($unsigned_cnt > 0);
3081 $printtype = trim($printtype);
3084 $attribute = ' ';
3085 if ($binary) {
3086 $attribute = 'BINARY';
3088 if ($unsigned) {
3089 $attribute = 'UNSIGNED';
3091 if ($zerofill) {
3092 $attribute = 'UNSIGNED ZEROFILL';
3095 $can_contain_collation = false;
3096 if (! $binary
3097 && preg_match(
3098 "@^(char|varchar|text|tinytext|mediumtext|longtext|set|enum)@", $type
3101 $can_contain_collation = true;
3104 // for the case ENUM('&#8211;','&ldquo;')
3105 $displayed_type = htmlspecialchars($printtype);
3106 if (strlen($printtype) > $GLOBALS['cfg']['LimitChars']) {
3107 $displayed_type = '<abbr title="' . $printtype . '">';
3108 $displayed_type .= substr($printtype, 0, $GLOBALS['cfg']['LimitChars']);
3109 $displayed_type .= '</abbr>';
3112 return array(
3113 'type' => $type,
3114 'spec_in_brackets' => $spec_in_brackets,
3115 'enum_set_values' => $enum_set_values,
3116 'print_type' => $printtype,
3117 'binary' => $binary,
3118 'unsigned' => $unsigned,
3119 'zerofill' => $zerofill,
3120 'attribute' => $attribute,
3121 'can_contain_collation' => $can_contain_collation,
3122 'displayed_type' => $displayed_type
3127 * Verifies if this table's engine supports foreign keys
3129 * @param string $engine engine
3131 * @return boolean
3133 public static function isForeignKeySupported($engine)
3135 $engine = strtoupper($engine);
3136 if (($engine == 'INNODB') || ($engine == 'PBXT')) {
3137 return true;
3138 } else {
3139 return false;
3144 * Replaces some characters by a displayable equivalent
3146 * @param string $content content
3148 * @return string the content with characters replaced
3150 public static function replaceBinaryContents($content)
3152 $result = str_replace("\x00", '\0', $content);
3153 $result = str_replace("\x08", '\b', $result);
3154 $result = str_replace("\x0a", '\n', $result);
3155 $result = str_replace("\x0d", '\r', $result);
3156 $result = str_replace("\x1a", '\Z', $result);
3157 return $result;
3161 * Converts GIS data to Well Known Text format
3163 * @param binary $data GIS data
3164 * @param bool $includeSRID Add SRID to the WKT
3166 * @return string GIS data in Well Know Text format
3168 public static function asWKT($data, $includeSRID = false)
3170 // Convert to WKT format
3171 $hex = bin2hex($data);
3172 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3173 if ($includeSRID) {
3174 $wktsql .= ", SRID(x'" . $hex . "')";
3177 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
3178 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
3179 $wktval = $wktarr[0];
3181 if ($includeSRID) {
3182 $srid = $wktarr[1];
3183 $wktval = "'" . $wktval . "'," . $srid;
3185 @PMA_DBI_free_result($wktresult);
3187 return $wktval;
3191 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3193 * @param string $string string
3195 * @return string with the chars replaced
3197 public static function duplicateFirstNewline($string)
3199 $first_occurence = strpos($string, "\r\n");
3200 if ($first_occurence === 0) {
3201 $string = "\n" . $string;
3203 return $string;
3207 * Get the action word corresponding to a script name
3208 * in order to display it as a title in navigation panel
3210 * @param string $target a valid value for $cfg['NavigationTreeDefaultTabTable'],
3211 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3213 * @return array
3215 public static function getTitleForTarget($target)
3217 $mapping = array(
3218 // Values for $cfg['DefaultTabTable']
3219 'tbl_structure.php' => __('Structure'),
3220 'tbl_sql.php' => __('SQL'),
3221 'tbl_select.php' =>__('Search'),
3222 'tbl_change.php' =>__('Insert'),
3223 'sql.php' => __('Browse'),
3225 // Values for $cfg['DefaultTabDatabase']
3226 'db_structure.php' => __('Structure'),
3227 'db_sql.php' => __('SQL'),
3228 'db_search.php' => __('Search'),
3229 'db_operations.php' => __('Operations'),
3231 return $mapping[$target];
3235 * Formats user string, expanding @VARIABLES@, accepting strftime format
3236 * string.
3238 * @param string $string Text where to do expansion.
3239 * @param function $escape Function to call for escaping variable values.
3240 * Can also be an array of:
3241 * - the escape method name
3242 * - the class that contains the method
3243 * - location of the class (for inclusion)
3244 * @param array $updates Array with overrides for default parameters
3245 * (obtained from GLOBALS).
3247 * @return string
3249 public static function expandUserString(
3250 $string, $escape = null, $updates = array()
3252 /* Content */
3253 $vars['http_host'] = PMA_getenv('HTTP_HOST');
3254 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3255 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3257 if (empty($GLOBALS['cfg']['Server']['verbose'])) {
3258 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host'];
3259 } else {
3260 $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose'];
3263 $vars['database'] = $GLOBALS['db'];
3264 $vars['table'] = $GLOBALS['table'];
3265 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3267 /* Update forced variables */
3268 foreach ($updates as $key => $val) {
3269 $vars[$key] = $val;
3272 /* Replacement mapping */
3274 * The __VAR__ ones are for backward compatibility, because user
3275 * might still have it in cookies.
3277 $replace = array(
3278 '@HTTP_HOST@' => $vars['http_host'],
3279 '@SERVER@' => $vars['server_name'],
3280 '__SERVER__' => $vars['server_name'],
3281 '@VERBOSE@' => $vars['server_verbose'],
3282 '@VSERVER@' => $vars['server_verbose_or_name'],
3283 '@DATABASE@' => $vars['database'],
3284 '__DB__' => $vars['database'],
3285 '@TABLE@' => $vars['table'],
3286 '__TABLE__' => $vars['table'],
3287 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3290 /* Optional escaping */
3291 if (! is_null($escape)) {
3292 if (is_array($escape)) {
3293 include_once $escape[2];
3294 $escape_class = new $escape[1];
3295 $escape_method = $escape[0];
3297 foreach ($replace as $key => $val) {
3298 if (is_array($escape)) {
3299 $replace[$key] = $escape_class->$escape_method($val);
3300 } else {
3301 $replace[$key] = ($escape == 'backquote')
3302 ? self::$escape($val)
3303 : $escape($val);
3308 /* Backward compatibility in 3.5.x */
3309 if (strpos($string, '@FIELDS@') !== false) {
3310 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3313 /* Fetch columns list if required */
3314 if (strpos($string, '@COLUMNS@') !== false) {
3315 $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3317 // sometimes the table no longer exists at this point
3318 if (! is_null($columns_list)) {
3319 $column_names = array();
3320 foreach ($columns_list as $column) {
3321 if (! is_null($escape)) {
3322 $column_names[] = self::$escape($column['Field']);
3323 } else {
3324 $column_names[] = $column['Field'];
3327 $replace['@COLUMNS@'] = implode(',', $column_names);
3328 } else {
3329 $replace['@COLUMNS@'] = '*';
3333 /* Do the replacement */
3334 return strtr(strftime($string), $replace);
3338 * Prepare the form used to browse anywhere on the local server for a file to
3339 * import
3341 * @param string $max_upload_size maximum upload size
3343 * @return void
3345 public static function getBrowseUploadFileBlock($max_upload_size)
3347 $block_html = '';
3349 if ($GLOBALS['is_upload'] && ! empty($GLOBALS['cfg']['UploadDir'])) {
3350 $block_html .= '<label for="radio_import_file">';
3351 } else {
3352 $block_html .= '<label for="input_import_file">';
3355 $block_html .= __("Browse your computer:") . '</label>'
3356 . '<div id="upload_form_status" style="display: none;"></div>'
3357 . '<div id="upload_form_status_info" style="display: none;"></div>'
3358 . '<input type="file" name="import_file" id="input_import_file" />'
3359 . self::getFormattedMaximumUploadSize($max_upload_size) . "\n"
3360 // some browsers should respect this :)
3361 . self::generateHiddenMaxFileSize($max_upload_size) . "\n";
3363 return $block_html;
3367 * Prepare the form used to select a file to import from the server upload
3368 * directory
3370 * @param array $import_list array of import plugins
3371 * @param string $uploaddir upload directory
3373 * @return void
3375 public static function getSelectUploadFileBlock($import_list, $uploaddir)
3377 $block_html = '';
3378 $block_html .= '<label for="radio_local_import_file">'
3379 . sprintf(
3380 __("Select from the web server upload directory <b>%s</b>:"),
3381 htmlspecialchars(self::userDir($uploaddir))
3383 . '</label>';
3385 $extensions = '';
3386 foreach ($import_list as $import_plugin) {
3387 if (! empty($extensions)) {
3388 $extensions .= '|';
3390 $extensions .= $import_plugin->getProperties()->getExtension();
3393 $matcher = '@\.(' . $extensions . ')(\.('
3394 . PMA_supportedDecompressions() . '))?$@';
3396 $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
3397 && isset($local_import_file))
3398 ? $local_import_file
3399 : '';
3401 $files = PMA_getFileSelectOptions(
3402 self::userDir($uploaddir),
3403 $matcher,
3404 $active
3407 if ($files === false) {
3408 PMA_Message::error(
3409 __('The directory you set for upload work cannot be reached')
3410 )->display();
3411 } elseif (! empty($files)) {
3412 $block_html .= "\n"
3413 . ' <select style="margin: 5px" size="1" '
3414 . 'name="local_import_file" '
3415 . 'id="select_local_import_file">' . "\n"
3416 . ' <option value="">&nbsp;</option>' . "\n"
3417 . $files
3418 . ' </select>' . "\n";
3419 } elseif (empty ($files)) {
3420 $block_html .= '<i>' . __('There are no files to upload') . '</i>';
3423 return $block_html;
3428 * Build titles and icons for action links
3430 * @return array the action titles
3432 public static function buildActionTitles()
3434 $titles = array();
3436 $titles['Browse'] = self::getIcon('b_browse.png', __('Browse'));
3437 $titles['NoBrowse'] = self::getIcon('bd_browse.png', __('Browse'));
3438 $titles['Search'] = self::getIcon('b_select.png', __('Search'));
3439 $titles['NoSearch'] = self::getIcon('bd_select.png', __('Search'));
3440 $titles['Insert'] = self::getIcon('b_insrow.png', __('Insert'));
3441 $titles['NoInsert'] = self::getIcon('bd_insrow.png', __('Insert'));
3442 $titles['Structure'] = self::getIcon('b_props.png', __('Structure'));
3443 $titles['Drop'] = self::getIcon('b_drop.png', __('Drop'));
3444 $titles['NoDrop'] = self::getIcon('bd_drop.png', __('Drop'));
3445 $titles['Empty'] = self::getIcon('b_empty.png', __('Empty'));
3446 $titles['NoEmpty'] = self::getIcon('bd_empty.png', __('Empty'));
3447 $titles['Edit'] = self::getIcon('b_edit.png', __('Edit'));
3448 $titles['NoEdit'] = self::getIcon('bd_edit.png', __('Edit'));
3449 $titles['Export'] = self::getIcon('b_export.png', __('Export'));
3450 $titles['NoExport'] = self::getIcon('bd_export.png', __('Export'));
3451 $titles['Execute'] = self::getIcon('b_nextpage.png', __('Execute'));
3452 $titles['NoExecute'] = self::getIcon('bd_nextpage.png', __('Execute'));
3454 return $titles;
3458 * This function processes the datatypes supported by the DB,
3459 * as specified in PMA_Types->getColumns() and either returns an array
3460 * (useful for quickly checking if a datatype is supported)
3461 * or an HTML snippet that creates a drop-down list.
3463 * @param bool $html Whether to generate an html snippet or an array
3464 * @param string $selected The value to mark as selected in HTML mode
3466 * @return mixed An HTML snippet or an array of datatypes.
3469 public static function getSupportedDatatypes($html = false, $selected = '')
3471 if ($html) {
3473 // NOTE: the SELECT tag in not included in this snippet.
3474 $retval = '';
3476 foreach ($GLOBALS['PMA_Types']->getColumns() as $key => $value) {
3477 if (is_array($value)) {
3478 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3479 foreach ($value as $subvalue) {
3480 if ($subvalue == $selected) {
3481 $retval .= sprintf(
3482 '<option selected="selected" title="%s">%s</option>',
3483 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3484 $subvalue
3486 } else if ($subvalue === '-') {
3487 $retval .= '<option disabled="disabled">';
3488 $retval .= $subvalue;
3489 $retval .= '</option>';
3490 } else {
3491 $retval .= sprintf(
3492 '<option title="%s">%s</option>',
3493 $GLOBALS['PMA_Types']->getTypeDescription($subvalue),
3494 $subvalue
3498 $retval .= '</optgroup>';
3499 } else {
3500 if ($selected == $value) {
3501 $retval .= sprintf(
3502 '<option selected="selected" title="%s">%s</option>',
3503 $GLOBALS['PMA_Types']->getTypeDescription($value),
3504 $value
3506 } else {
3507 $retval .= sprintf(
3508 '<option title="%s">%s</option>',
3509 $GLOBALS['PMA_Types']->getTypeDescription($value),
3510 $value
3515 } else {
3516 $retval = array();
3517 foreach ($GLOBALS['PMA_Types']->getColumns() as $value) {
3518 if (is_array($value)) {
3519 foreach ($value as $subvalue) {
3520 if ($subvalue !== '-') {
3521 $retval[] = $subvalue;
3524 } else {
3525 if ($value !== '-') {
3526 $retval[] = $value;
3532 return $retval;
3533 } // end getSupportedDatatypes()
3536 * Returns a list of datatypes that are not (yet) handled by PMA.
3537 * Used by: tbl_change.php and libraries/db_routines.inc.php
3539 * @return array list of datatypes
3541 public static function unsupportedDatatypes()
3543 $no_support_types = array();
3544 return $no_support_types;
3548 * Return GIS data types
3550 * @param bool $upper_case whether to return values in upper case
3552 * @return array GIS data types
3554 public static function getGISDatatypes($upper_case = false)
3556 $gis_data_types = array(
3557 'geometry',
3558 'point',
3559 'linestring',
3560 'polygon',
3561 'multipoint',
3562 'multilinestring',
3563 'multipolygon',
3564 'geometrycollection'
3566 if ($upper_case) {
3567 for ($i = 0; $i < count($gis_data_types); $i++) {
3568 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3571 return $gis_data_types;
3575 * Generates GIS data based on the string passed.
3577 * @param string $gis_string GIS string
3579 * @return string GIS data enclosed in 'GeomFromText' function
3581 public static function createGISData($gis_string)
3583 $gis_string = trim($gis_string);
3584 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3585 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3586 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3587 return 'GeomFromText(' . $gis_string . ')';
3588 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3589 return "GeomFromText('" . $gis_string . "')";
3590 } else {
3591 return $gis_string;
3596 * Returns the names and details of the functions
3597 * that can be applied on geometry data typess.
3599 * @param string $geom_type if provided the output is limited to the functions
3600 * that are applicable to the provided geometry type.
3601 * @param bool $binary if set to false functions that take two geometries
3602 * as arguments will not be included.
3603 * @param bool $display if set to true separators will be added to the
3604 * output array.
3606 * @return array names and details of the functions that can be applied on
3607 * geometry data typess.
3609 public static function getGISFunctions(
3610 $geom_type = null, $binary = true, $display = false
3612 $funcs = array();
3613 if ($display) {
3614 $funcs[] = array('display' => ' ');
3617 // Unary functions common to all geomety types
3618 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3619 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3620 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3621 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3622 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3623 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3625 $geom_type = trim(strtolower($geom_type));
3626 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3627 $funcs[] = array('display' => '--------');
3630 // Unary functions that are specific to each geomety type
3631 if ($geom_type == 'point') {
3632 $funcs['X'] = array('params' => 1, 'type' => 'float');
3633 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3635 } elseif ($geom_type == 'multipoint') {
3636 // no fucntions here
3637 } elseif ($geom_type == 'linestring') {
3638 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3639 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3640 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3641 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3642 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3644 } elseif ($geom_type == 'multilinestring') {
3645 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3646 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3648 } elseif ($geom_type == 'polygon') {
3649 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3650 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3651 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3653 } elseif ($geom_type == 'multipolygon') {
3654 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3655 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3656 // Not yet implemented in MySQL
3657 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3659 } elseif ($geom_type == 'geometrycollection') {
3660 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3663 // If we are asked for binary functions as well
3664 if ($binary) {
3665 // section separator
3666 if ($display) {
3667 $funcs[] = array('display' => '--------');
3670 if (PMA_MYSQL_INT_VERSION < 50601) {
3671 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3672 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3673 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3674 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3675 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3676 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3677 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3678 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3679 } else {
3680 // If MySQl version is greaeter than or equal 5.6.1,
3681 // use the ST_ prefix.
3682 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3683 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3684 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3685 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3686 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3687 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3688 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3689 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3692 if ($display) {
3693 $funcs[] = array('display' => '--------');
3695 // Minimum bounding rectangle functions
3696 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3697 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3698 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3699 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3700 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3701 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3702 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3704 return $funcs;
3708 * Returns default function for a particular column.
3710 * @param array $field Data about the column for which
3711 * to generate the dropdown
3712 * @param bool $insert_mode Whether the operation is 'insert'
3714 * @global array $cfg PMA configuration
3715 * @global array $analyzed_sql Analyzed SQL query
3716 * @global mixed $data data of currently edited row
3717 * (used to detect whether to choose defaults)
3719 * @return string An HTML snippet of a dropdown list with function
3720 * names appropriate for the requested column.
3722 public static function getDefaultFunctionForField($field, $insert_mode)
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 && ($analyzed_sql_field_array['default_value'] != 'NULL')
3752 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3755 // For primary keys of type char(36) or varchar(36) UUID if the default
3756 // function
3757 // Only applies to insert mode, as it would silently trash data on updates.
3758 if ($insert_mode
3759 && $field['Key'] == 'PRI'
3760 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3762 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3765 // this is set only when appropriate and is always true
3766 if (isset($field['display_binary_as_hex'])) {
3767 $default_function = 'UNHEX';
3770 return $default_function;
3774 * Creates a dropdown box with MySQL functions for a particular column.
3776 * @param array $field Data about the column for which
3777 * to generate the dropdown
3778 * @param bool $insert_mode Whether the operation is 'insert'
3780 * @return string An HTML snippet of a dropdown list with function
3781 * names appropriate for the requested column.
3783 public static function getFunctionsForField($field, $insert_mode)
3785 $default_function = self::getDefaultFunctionForField($field, $insert_mode);
3786 $dropdown_built = array();
3788 // Create the output
3789 $retval = '<option></option>' . "\n";
3790 // loop on the dropdown array and print all available options for that
3791 // field.
3792 $functions = $GLOBALS['PMA_Types']->getFunctions($field['True_Type']);
3793 foreach ($functions as $function) {
3794 $retval .= '<option';
3795 if ($default_function === $function) {
3796 $retval .= ' selected="selected"';
3798 $retval .= '>' . $function . '</option>' . "\n";
3799 $dropdown_built[$function] = true;
3802 // Create separator before all functions list
3803 if (count($functions) > 0) {
3804 $retval .= '<option value="" disabled="disabled">--------</option>'
3805 . "\n";
3808 // For compatibility's sake, do not let out all other functions. Instead
3809 // print a separator (blank) and then show ALL functions which weren't
3810 // shown yet.
3811 $functions = $GLOBALS['PMA_Types']->getAllFunctions();
3812 foreach ($functions as $function) {
3813 // Skip already included functions
3814 if (isset($dropdown_built[$function])) {
3815 continue;
3817 $retval .= '<option';
3818 if ($default_function === $function) {
3819 $retval .= ' selected="selected"';
3821 $retval .= '>' . $function . '</option>' . "\n";
3822 } // end for
3824 return $retval;
3825 } // end getFunctionsForField()
3828 * Checks if the current user has a specific privilege and returns true if the
3829 * user indeed has that privilege or false if (s)he doesn't. This function must
3830 * only be used for features that are available since MySQL 5, because it
3831 * relies on the INFORMATION_SCHEMA database to be present.
3833 * Example: currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3834 * // Checks if the currently logged in user has the global
3835 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3836 * // user has this privilege on database 'mydb'.
3838 * @param string $priv The privilege to check
3839 * @param mixed $db null, to only check global privileges
3840 * string, db name where to also check for privileges
3841 * @param mixed $tbl null, to only check global/db privileges
3842 * string, table name where to also check for privileges
3844 * @return bool
3846 public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
3848 // Get the username for the current user in the format
3849 // required to use in the information schema database.
3850 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3851 if ($user === false) {
3852 return false;
3855 $user = explode('@', $user);
3856 $username = "''";
3857 $username .= str_replace("'", "''", $user[0]);
3858 $username .= "''@''";
3859 $username .= str_replace("'", "''", $user[1]);
3860 $username .= "''";
3862 // Prepage the query
3863 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3864 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3866 // Check global privileges first.
3867 $user_privileges = PMA_DBI_fetch_value(
3868 sprintf(
3869 $query,
3870 'USER_PRIVILEGES',
3871 $username,
3872 $priv
3875 if ($user_privileges) {
3876 return true;
3878 // If a database name was provided and user does not have the
3879 // required global privilege, try database-wise permissions.
3880 if ($db !== null) {
3881 // need to escape wildcards in db and table names, see bug #3518484
3882 $db = str_replace(array('%', '_'), array('\%', '\_'), $db);
3883 $query .= " AND TABLE_SCHEMA='%s'";
3884 $schema_privileges = PMA_DBI_fetch_value(
3885 sprintf(
3886 $query,
3887 'SCHEMA_PRIVILEGES',
3888 $username,
3889 $priv,
3890 self::sqlAddSlashes($db)
3893 if ($schema_privileges) {
3894 return true;
3896 } else {
3897 // There was no database name provided and the user
3898 // does not have the correct global privilege.
3899 return false;
3901 // If a table name was also provided and we still didn't
3902 // find any valid privileges, try table-wise privileges.
3903 if ($tbl !== null) {
3904 // need to escape wildcards in db and table names, see bug #3518484
3905 $tbl = str_replace(array('%', '_'), array('\%', '\_'), $tbl);
3906 $query .= " AND TABLE_NAME='%s'";
3907 $table_privileges = PMA_DBI_fetch_value(
3908 sprintf(
3909 $query,
3910 'TABLE_PRIVILEGES',
3911 $username,
3912 $priv,
3913 self::sqlAddSlashes($db),
3914 self::sqlAddSlashes($tbl)
3917 if ($table_privileges) {
3918 return true;
3921 // If we reached this point, the user does not
3922 // have even valid table-wise privileges.
3923 return false;
3927 * Returns server type for current connection
3929 * Known types are: Drizzle, MariaDB and MySQL (default)
3931 * @return string
3933 public static function getServerType()
3935 $server_type = 'MySQL';
3936 if (PMA_DRIZZLE) {
3937 $server_type = 'Drizzle';
3938 } else if (stripos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3939 $server_type = 'MariaDB';
3940 } else if (stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3941 $server_type = 'Percona Server';
3943 return $server_type;
3947 * Analyzes the limit clause and return the start and length attributes of it.
3949 * @param string $limit_clause limit clause
3951 * @return array Start and length attributes of the limit clause
3953 public static function analyzeLimitClause($limit_clause)
3955 $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
3956 $size = count($start_and_length);
3957 if ($size == 1) {
3958 return array(
3959 'start' => '0',
3960 'length' => trim($start_and_length[0])
3962 } elseif ($size == 2) {
3963 return array(
3964 'start' => trim($start_and_length[0]),
3965 'length' => trim($start_and_length[1])
3971 * Prepare HTML code for display button.
3973 * @return void
3975 public static function getButton()
3977 return '<p class="print_ignore">'
3978 . '<input type="button" class="button" id="print" value="'
3979 . __('Print') . '" />'
3980 . '</p>';
3984 * Parses ENUM/SET values
3986 * @param string $definition The definition of the column
3987 * for which to parse the values
3988 * @param bool $escapeHtml Whether to escape html entitites
3990 * @return array
3992 public static function parseEnumSetValues($definition, $escapeHtml = true)
3994 $values_string = htmlentities($definition, ENT_COMPAT, "UTF-8");
3995 // There is a JS port of the below parser in functions.js
3996 // If you are fixing something here,
3997 // you need to also update the JS port.
3998 $values = array();
3999 $in_string = false;
4000 $buffer = '';
4002 for ($i=0; $i<strlen($values_string); $i++) {
4004 $curr = $values_string[$i];
4005 $next = ($i == strlen($values_string)-1) ? '' : $values_string[$i+1];
4007 if (! $in_string && $curr == "'") {
4008 $in_string = true;
4009 } else if (($in_string && $curr == "\\") && $next == "\\") {
4010 $buffer .= "&#92;";
4011 $i++;
4012 } else if (($in_string && $next == "'")
4013 && ($curr == "'" || $curr == "\\")
4015 $buffer .= "&#39;";
4016 $i++;
4017 } else if ($in_string && $curr == "'") {
4018 $in_string = false;
4019 $values[] = $buffer;
4020 $buffer = '';
4021 } else if ($in_string) {
4022 $buffer .= $curr;
4027 if (strlen($buffer) > 0) {
4028 // The leftovers in the buffer are the last value (if any)
4029 $values[] = $buffer;
4032 if (! $escapeHtml) {
4033 foreach ($values as $key => $value) {
4034 $values[$key] = html_entity_decode($value, ENT_QUOTES);
4038 return $values;
4042 * fills given tooltip arrays
4044 * @param array &$tooltip_truename tooltip data
4045 * @param array &$tooltip_aliasname tooltip data
4046 * @param array $table tabledata
4048 * @return void
4050 public static function fillTooltip(
4051 &$tooltip_truename, &$tooltip_aliasname, $table
4053 if (strstr($table['Comment'], '; InnoDB free') === false) {
4054 if (!strstr($table['Comment'], 'InnoDB free') === false) {
4055 // here we have just InnoDB generated part
4056 $table['Comment'] = '';
4058 } else {
4059 // remove InnoDB comment from end, just the minimal part
4060 // (*? is non greedy)
4061 $table['Comment'] = preg_replace(
4062 '@; InnoDB free:.*?$@', '', $table['Comment']
4065 // views have VIEW as comment so it's not a real comment put by a user
4066 if ('VIEW' == $table['Comment']) {
4067 $table['Comment'] = '';
4069 if (empty($table['Comment'])) {
4070 $table['Comment'] = $table['Name'];
4071 } else {
4072 // todo: why?
4073 $table['Comment'] .= ' ';
4076 $tooltip_truename[$table['Name']] = $table['Name'];
4077 $tooltip_aliasname[$table['Name']] = $table['Comment'];
4079 if (isset($table['Create_time']) && !empty($table['Create_time'])) {
4080 $tooltip_aliasname[$table['Name']] .= ', ' . __('Creation')
4081 . ': '
4082 . PMA_Util::localisedDate(strtotime($table['Create_time']));
4085 if (! empty($table['Update_time'])) {
4086 $tooltip_aliasname[$table['Name']] .= ', ' . __('Last update')
4087 . ': '
4088 . PMA_Util::localisedDate(strtotime($table['Update_time']));
4091 if (! empty($table['Check_time'])) {
4092 $tooltip_aliasname[$table['Name']] .= ', ' . __('Last check')
4093 . ': '
4094 . PMA_Util::localisedDate(strtotime($table['Check_time']));