Translated using Weblate.
[phpmyadmin.git] / libraries / common.lib.php
blob4e2b8d0ec01f4010aa4542879e4f61a45df151d0
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Misc functions used all over the scripts.
6 * @package PhpMyAdmin
7 */
9 /**
10 * Detects which function to use for PMA_pow.
12 * @return string Function name.
14 function PMA_detect_pow()
16 if (function_exists('bcpow')) {
17 // BCMath Arbitrary Precision Mathematics Function
18 return 'bcpow';
19 } elseif (function_exists('gmp_pow')) {
20 // GMP Function
21 return 'gmp_pow';
22 } else {
23 // PHP function
24 return 'pow';
28 /**
29 * Exponential expression / raise number into power
31 * @param string $base base to raise
32 * @param string $exp exponent to use
33 * @param mixed $use_function pow function to use, or false for auto-detect
35 * @return mixed string or float
37 function PMA_pow($base, $exp, $use_function = false)
39 static $pow_function = null;
41 if (null == $pow_function) {
42 $pow_function = PMA_detect_pow();
45 if (! $use_function) {
46 $use_function = $pow_function;
49 if ($exp < 0 && 'pow' != $use_function) {
50 return false;
52 switch ($use_function) {
53 case 'bcpow' :
54 // bcscale() needed for testing PMA_pow() with base values < 1
55 bcscale(10);
56 $pow = bcpow($base, $exp);
57 break;
58 case 'gmp_pow' :
59 $pow = gmp_strval(gmp_pow($base, $exp));
60 break;
61 case 'pow' :
62 $base = (float) $base;
63 $exp = (int) $exp;
64 $pow = pow($base, $exp);
65 break;
66 default:
67 $pow = $use_function($base, $exp);
70 return $pow;
73 /**
74 * Returns an HTML IMG tag for a particular icon from a theme,
75 * which may be an actual file or an icon from a sprite.
76 * This function takes into account the PropertiesIconic
77 * configuration setting and wraps the image tag in a span tag.
79 * @param string $icon name of icon file
80 * @param string $alternate alternate text
81 * @param boolean $force_text whether to force alternate text to be displayed
83 * @return string an html snippet
85 function PMA_getIcon($icon, $alternate = '', $force_text = false)
87 // $cfg['PropertiesIconic'] is true or both
88 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
89 // $cfg['PropertiesIconic'] is false or both
90 // OR we have no $include_icon
91 $include_text = ($force_text || true !== $GLOBALS['cfg']['PropertiesIconic']);
93 // Always use a span (we rely on this in js/sql.js)
94 $button = '<span class="nowrap">';
95 if ($include_icon) {
96 $button .= PMA_getImage($icon, $alternate);
98 if ($include_icon && $include_text) {
99 $button .= ' ';
101 if ($include_text) {
102 $button .= $alternate;
104 $button .= '</span>';
106 return $button;
110 * Returns an HTML IMG tag for a particular image from a theme,
111 * which may be an actual file or an icon from a sprite
113 * @param string $image The name of the file to get
114 * @param string $alternate Used to set 'alt' and 'title' attributes of the image
115 * @param array $attributes An associative array of other attributes
117 * @return string an html IMG tag
119 function PMA_getImage($image, $alternate = '', $attributes = array())
121 static $sprites; // cached list of available sprites (if any)
123 $url = '';
124 $is_sprite = false;
125 $alternate = htmlspecialchars($alternate);
127 // If it's the first time this function is called
128 if (! isset($sprites)) {
129 // Try to load the list of sprites
130 if (is_readable($_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php')) {
131 include_once $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
132 $sprites = PMA_sprites();
133 } else {
134 // No sprites are available for this theme
135 $sprites = array();
138 // Check if we have the requested image as a sprite
139 // and set $url accordingly
140 $class = str_replace(array('.gif','.png'), '', $image);
141 if (array_key_exists($class, $sprites)) {
142 $is_sprite = true;
143 $url = 'themes/dot.gif';
144 } else {
145 $url = $GLOBALS['pmaThemeImage'] . $image;
147 // set class attribute
148 if ($is_sprite) {
149 if (isset($attributes['class'])) {
150 $attributes['class'] = "icon ic_$class " . $attributes['class'];
151 } else {
152 $attributes['class'] = "icon ic_$class";
155 // set all other attributes
156 $attr_str = '';
157 foreach ($attributes as $key => $value) {
158 if (! in_array($key, array('alt', 'title'))) {
159 $attr_str .= " $key=\"$value\"";
162 // override the alt attribute
163 if (isset($attributes['alt'])) {
164 $alt = $attributes['alt'];
165 } else {
166 $alt = $alternate;
168 // override the title attribute
169 if (isset($attributes['title'])) {
170 $title = $attributes['title'];
171 } else {
172 $title = $alternate;
174 // generate the IMG tag
175 $template = '<img src="%s" title="%s" alt="%s"%s />';
176 $retval = sprintf($template, $url, $title, $alt, $attr_str);
178 return $retval;
182 * Displays the maximum size for an upload
184 * @param integer $max_upload_size the size
186 * @return string the message
188 * @access public
190 function PMA_displayMaximumUploadSize($max_upload_size)
192 // I have to reduce the second parameter (sensitiveness) from 6 to 4
193 // to avoid weird results like 512 kKib
194 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
195 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
199 * Generates a hidden field which should indicate to the browser
200 * the maximum size for upload
202 * @param integer $max_size the size
204 * @return string the INPUT field
206 * @access public
208 function PMA_generateHiddenMaxFileSize($max_size)
210 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
214 * Add slashes before "'" and "\" characters so a value containing them can
215 * be used in a sql comparison.
217 * @param string $a_string the string to slash
218 * @param bool $is_like whether the string will be used in a 'LIKE' clause
219 * (it then requires two more escaped sequences) or not
220 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
221 * (converts \n to \\n, \r to \\r)
222 * @param bool $php_code whether this function is used as part of the
223 * "Create PHP code" dialog
225 * @return string the slashed string
227 * @access public
229 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
231 if ($is_like) {
232 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
233 } else {
234 $a_string = str_replace('\\', '\\\\', $a_string);
237 if ($crlf) {
238 $a_string = strtr(
239 $a_string,
240 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
244 if ($php_code) {
245 $a_string = str_replace('\'', '\\\'', $a_string);
246 } else {
247 $a_string = str_replace('\'', '\'\'', $a_string);
250 return $a_string;
251 } // end of the 'PMA_sqlAddSlashes()' function
255 * Add slashes before "_" and "%" characters for using them in MySQL
256 * database, table and field names.
257 * Note: This function does not escape backslashes!
259 * @param string $name the string to escape
261 * @return string the escaped string
263 * @access public
265 function PMA_escape_mysql_wildcards($name)
267 return strtr($name, array('_' => '\\_', '%' => '\\%'));
268 } // end of the 'PMA_escape_mysql_wildcards()' function
271 * removes slashes before "_" and "%" characters
272 * Note: This function does not unescape backslashes!
274 * @param string $name the string to escape
276 * @return string the escaped string
278 * @access public
280 function PMA_unescape_mysql_wildcards($name)
282 return strtr($name, array('\\_' => '_', '\\%' => '%'));
283 } // end of the 'PMA_unescape_mysql_wildcards()' function
286 * removes quotes (',",`) from a quoted string
288 * checks if the sting is quoted and removes this quotes
290 * @param string $quoted_string string to remove quotes from
291 * @param string $quote type of quote to remove
293 * @return string unqoted string
295 function PMA_unQuote($quoted_string, $quote = null)
297 $quotes = array();
299 if (null === $quote) {
300 $quotes[] = '`';
301 $quotes[] = '"';
302 $quotes[] = "'";
303 } else {
304 $quotes[] = $quote;
307 foreach ($quotes as $quote) {
308 if (substr($quoted_string, 0, 1) === $quote
309 && substr($quoted_string, -1, 1) === $quote
311 $unquoted_string = substr($quoted_string, 1, -1);
312 // replace escaped quotes
313 $unquoted_string = str_replace(
314 $quote . $quote,
315 $quote,
316 $unquoted_string
318 return $unquoted_string;
322 return $quoted_string;
326 * format sql strings
328 * @param mixed $parsed_sql pre-parsed SQL structure
329 * @param string $unparsed_sql raw SQL string
331 * @return string the formatted sql
333 * @global array the configuration array
334 * @global boolean whether the current statement is a multiple one or not
336 * @access public
337 * @todo move into PMA_Sql
339 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
341 global $cfg;
343 // Check that we actually have a valid set of parsed data
344 // well, not quite
345 // first check for the SQL parser having hit an error
346 if (PMA_SQP_isError()) {
347 return htmlspecialchars($parsed_sql['raw']);
349 // then check for an array
350 if (! is_array($parsed_sql)) {
351 // We don't so just return the input directly
352 // This is intended to be used for when the SQL Parser is turned off
353 $formatted_sql = "<pre>\n";
354 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
355 $formatted_sql .= $unparsed_sql;
356 } else {
357 $formatted_sql .= $parsed_sql;
359 $formatted_sql .= "\n</pre>";
360 return $formatted_sql;
363 $formatted_sql = '';
365 switch ($cfg['SQP']['fmtType']) {
366 case 'none':
367 if ($unparsed_sql != '') {
368 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
369 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
370 . '</pre></span>';
371 } else {
372 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
374 break;
375 case 'html':
376 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
377 break;
378 case 'text':
379 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
380 break;
381 default:
382 break;
383 } // end switch
385 return $formatted_sql;
386 } // end of the "PMA_formatSql()" function
390 * Displays a link to the official MySQL documentation
392 * @param string $chapter chapter of "HTML, one page per chapter" documentation
393 * @param string $link contains name of page/anchor that is being linked
394 * @param bool $big_icon whether to use big icon (like in left frame)
395 * @param string $anchor anchor to page part
396 * @param bool $just_open whether only the opening <a> tag should be returned
398 * @return string the html link
400 * @access public
402 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
404 global $cfg;
406 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
407 return '';
410 // Fixup for newly used names:
411 $chapter = str_replace('_', '-', strtolower($chapter));
412 $link = str_replace('_', '-', strtolower($link));
414 switch ($cfg['MySQLManualType']) {
415 case 'chapters':
416 if (empty($chapter)) {
417 $chapter = 'index';
419 if (empty($anchor)) {
420 $anchor = $link;
422 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
423 break;
424 case 'big':
425 if (empty($anchor)) {
426 $anchor = $link;
428 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
429 break;
430 case 'searchable':
431 if (empty($link)) {
432 $link = 'index';
434 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
435 if (!empty($anchor)) {
436 $url .= '#' . $anchor;
438 break;
439 case 'viewable':
440 default:
441 if (empty($link)) {
442 $link = 'index';
444 $mysql = '5.0';
445 $lang = 'en';
446 if (defined('PMA_MYSQL_INT_VERSION')) {
447 if (PMA_MYSQL_INT_VERSION >= 50500) {
448 $mysql = '5.5';
449 /* l10n: Please check that translation actually exists. */
450 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
451 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
452 $mysql = '5.1';
453 /* l10n: Please check that translation actually exists. */
454 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
455 } else {
456 $mysql = '5.0';
457 /* l10n: Please check that translation actually exists. */
458 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
461 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
462 if (!empty($anchor)) {
463 $url .= '#' . $anchor;
465 break;
468 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
469 if ($just_open) {
470 return $open_link;
471 } elseif ($big_icon) {
472 return $open_link . PMA_getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
473 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
474 return $open_link . PMA_getImage('b_help.png', __('Documentation')) . '</a>';
475 } else {
476 return '[' . $open_link . __('Documentation') . '</a>]';
478 } // end of the 'PMA_showMySQLDocu()' function
482 * Displays a link to the phpMyAdmin documentation
484 * @param string $anchor anchor in documentation
486 * @return string the html link
488 * @access public
490 function PMA_showDocu($anchor)
492 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
493 return '<a href="Documentation.html#' . $anchor . '" target="documentation">'
494 . PMA_getImage('b_help.png', __('Documentation'))
495 . '</a>';
496 } else {
497 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">'
498 . __('Documentation') . '</a>]';
500 } // end of the 'PMA_showDocu()' function
503 * Displays a link to the PHP documentation
505 * @param string $target anchor in documentation
507 * @return string the html link
509 * @access public
511 function PMA_showPHPDocu($target)
513 $url = PMA_getPHPDocLink($target);
515 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
516 return '<a href="' . $url . '" target="documentation">'
517 . PMA_getImage('b_help.png', __('Documentation'))
518 . '</a>';
519 } else {
520 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
522 } // end of the 'PMA_showPHPDocu()' function
525 * returns HTML for a footnote marker and add the messsage to the footnotes
527 * @param string $message the error message
528 * @param bool $bbcode
529 * @param string $type message types
531 * @return string html code for a footnote marker
533 * @access public
535 function PMA_showHint($message, $bbcode = false, $type = 'notice')
537 if ($message instanceof PMA_Message) {
538 $key = $message->getHash();
539 $type = $message->getLevel();
540 } else {
541 $key = md5($message);
544 if (! isset($GLOBALS['footnotes'][$key])) {
545 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
546 $GLOBALS['footnotes'] = array();
548 $nr = count($GLOBALS['footnotes']) + 1;
549 $GLOBALS['footnotes'][$key] = array(
550 'note' => $message,
551 'type' => $type,
552 'nr' => $nr,
554 } else {
555 $nr = $GLOBALS['footnotes'][$key]['nr'];
558 if ($bbcode) {
559 return '[sup]' . $nr . '[/sup]';
562 // footnotemarker used in js/tooltip.js
563 return '<sup class="footnotemarker">' . $nr . '</sup>' .
564 PMA_getImage('b_help.png', '', array('class' => 'footnotemarker footnote_' . $nr));
568 * Displays a MySQL error message in the right frame.
570 * @param string $error_message the error message
571 * @param string $the_query the sql query that failed
572 * @param bool $is_modify_link whether to show a "modify" link or not
573 * @param string $back_url the "back" link url (full path is not required)
574 * @param bool $exit EXIT the page?
576 * @global string the curent table
577 * @global string the current db
579 * @access public
581 function PMA_mysqlDie($error_message = '', $the_query = '',
582 $is_modify_link = true, $back_url = '', $exit = true)
584 global $table, $db;
587 * start http output, display html headers
589 include_once './libraries/header.inc.php';
591 $error_msg_output = '';
593 if (!$error_message) {
594 $error_message = PMA_DBI_getError();
596 if (!$the_query && !empty($GLOBALS['sql_query'])) {
597 $the_query = $GLOBALS['sql_query'];
600 // --- Added to solve bug #641765
601 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
602 $formatted_sql = htmlspecialchars($the_query);
603 } elseif (empty($the_query) || trim($the_query) == '') {
604 $formatted_sql = '';
605 } else {
606 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
607 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
608 } else {
609 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
612 // ---
613 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
614 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
615 // if the config password is wrong, or the MySQL server does not
616 // respond, do not show the query that would reveal the
617 // username/password
618 if (!empty($the_query) && !strstr($the_query, 'connect')) {
619 // --- Added to solve bug #641765
620 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
621 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
622 $error_msg_output .= '<br />' . "\n";
624 // ---
625 // modified to show the help on sql errors
626 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
627 if (strstr(strtolower($formatted_sql), 'select')) {
628 // please show me help to the error on select
629 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
631 if ($is_modify_link) {
632 $_url_params = array(
633 'sql_query' => $the_query,
634 'show_query' => 1,
636 if (strlen($table)) {
637 $_url_params['db'] = $db;
638 $_url_params['table'] = $table;
639 $doedit_goto = '<a href="tbl_sql.php' . PMA_generate_common_url($_url_params) . '">';
640 } elseif (strlen($db)) {
641 $_url_params['db'] = $db;
642 $doedit_goto = '<a href="db_sql.php' . PMA_generate_common_url($_url_params) . '">';
643 } else {
644 $doedit_goto = '<a href="server_sql.php' . PMA_generate_common_url($_url_params) . '">';
647 $error_msg_output .= $doedit_goto
648 . PMA_getIcon('b_edit.png', __('Edit'))
649 . '</a>';
650 } // end if
651 $error_msg_output .= ' </p>' . "\n"
652 .' <p>' . "\n"
653 .' ' . $formatted_sql . "\n"
654 .' </p>' . "\n";
655 } // end if
657 if (! empty($error_message)) {
658 $error_message = preg_replace(
659 "@((\015\012)|(\015)|(\012)){3,}@",
660 "\n\n",
661 $error_message
664 // modified to show the help on error-returns
665 // (now error-messages-server)
666 $error_msg_output .= '<p>' . "\n"
667 . ' <strong>' . __('MySQL said: ') . '</strong>'
668 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
669 . "\n"
670 . '</p>' . "\n";
672 // The error message will be displayed within a CODE segment.
673 // To preserve original formatting, but allow wordwrapping,
674 // we do a couple of replacements
676 // Replace all non-single blanks with their HTML-counterpart
677 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
678 // Replace TAB-characters with their HTML-counterpart
679 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
680 // Replace linebreaks
681 $error_message = nl2br($error_message);
683 $error_msg_output .= '<code>' . "\n"
684 . $error_message . "\n"
685 . '</code><br />' . "\n";
686 $error_msg_output .= '</div>';
688 $_SESSION['Import_message']['message'] = $error_msg_output;
690 if ($exit) {
692 * If in an Ajax request
693 * - avoid displaying a Back link
694 * - use PMA_ajaxResponse() to transmit the message and exit
696 if ($GLOBALS['is_ajax_request'] == true) {
697 PMA_ajaxResponse($error_msg_output, false);
699 if (! empty($back_url)) {
700 if (strstr($back_url, '?')) {
701 $back_url .= '&amp;no_history=true';
702 } else {
703 $back_url .= '?no_history=true';
706 $_SESSION['Import_message']['go_back_url'] = $back_url;
708 $error_msg_output .= '<fieldset class="tblFooters">';
709 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
710 $error_msg_output .= '</fieldset>' . "\n\n";
713 echo $error_msg_output;
715 * display footer and exit
717 include './libraries/footer.inc.php';
718 } else {
719 echo $error_msg_output;
721 } // end of the 'PMA_mysqlDie()' function
724 * returns array with tables of given db with extended information and grouped
726 * @param string $db name of db
727 * @param string $tables name of tables
728 * @param integer $limit_offset list offset
729 * @param int|bool $limit_count max tables to return
731 * @return array (recursive) grouped table list
733 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
735 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
737 if (null === $tables) {
738 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
739 if ($GLOBALS['cfg']['NaturalOrder']) {
740 uksort($tables, 'strnatcasecmp');
744 if (count($tables) < 1) {
745 return $tables;
748 $default = array(
749 'Name' => '',
750 'Rows' => 0,
751 'Comment' => '',
752 'disp_name' => '',
755 $table_groups = array();
757 // for blobstreaming - list of blobstreaming tables
759 // load PMA configuration
760 $PMA_Config = $GLOBALS['PMA_Config'];
762 foreach ($tables as $table_name => $table) {
763 // if BS tables exist
764 if (PMA_BS_IsHiddenTable($table_name)) {
765 continue;
768 // check for correct row count
769 if (null === $table['Rows']) {
770 // Do not check exact row count here,
771 // if row count is invalid possibly the table is defect
772 // and this would break left frame;
773 // but we can check row count if this is a view or the
774 // information_schema database
775 // since PMA_Table::countRecords() returns a limited row count
776 // in this case.
778 // set this because PMA_Table::countRecords() can use it
779 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
781 if ($tbl_is_view || PMA_is_system_schema($db)) {
782 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'], false, true);
786 // in $group we save the reference to the place in $table_groups
787 // where to store the table info
788 if ($GLOBALS['cfg']['LeftFrameDBTree']
789 && $sep && strstr($table_name, $sep)
791 $parts = explode($sep, $table_name);
793 $group =& $table_groups;
794 $i = 0;
795 $group_name_full = '';
796 $parts_cnt = count($parts) - 1;
797 while ($i < $parts_cnt
798 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
799 $group_name = $parts[$i] . $sep;
800 $group_name_full .= $group_name;
802 if (! isset($group[$group_name])) {
803 $group[$group_name] = array();
804 $group[$group_name]['is' . $sep . 'group'] = true;
805 $group[$group_name]['tab' . $sep . 'count'] = 1;
806 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
807 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
808 $table = $group[$group_name];
809 $group[$group_name] = array();
810 $group[$group_name][$group_name] = $table;
811 unset($table);
812 $group[$group_name]['is' . $sep . 'group'] = true;
813 $group[$group_name]['tab' . $sep . 'count'] = 1;
814 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
815 } else {
816 $group[$group_name]['tab' . $sep . 'count']++;
818 $group =& $group[$group_name];
819 $i++;
821 } else {
822 if (! isset($table_groups[$table_name])) {
823 $table_groups[$table_name] = array();
825 $group =& $table_groups;
829 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
830 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
831 && $table['Comment'] // do not switch if the comment is empty
833 // switch tooltip and name
834 $table['disp_name'] = $table['Comment'];
835 $table['Comment'] = $table['Name'];
836 } else {
837 $table['disp_name'] = $table['Name'];
840 $group[$table_name] = array_merge($default, $table);
843 return $table_groups;
846 /* ----------------------- Set of misc functions ----------------------- */
850 * Adds backquotes on both sides of a database, table or field name.
851 * and escapes backquotes inside the name with another backquote
853 * example:
854 * <code>
855 * echo PMA_backquote('owner`s db'); // `owner``s db`
857 * </code>
859 * @param mixed $a_name the database, table or field name to "backquote"
860 * or array of it
861 * @param boolean $do_it a flag to bypass this function (used by dump
862 * functions)
864 * @return mixed the "backquoted" database, table or field name
866 * @access public
868 function PMA_backquote($a_name, $do_it = true)
870 if (is_array($a_name)) {
871 foreach ($a_name as &$data) {
872 $data = PMA_backquote($data, $do_it);
874 return $a_name;
877 if (! $do_it) {
878 global $PMA_SQPdata_forbidden_word;
880 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
881 return $a_name;
885 // '0' is also empty for php :-(
886 if (strlen($a_name) && $a_name !== '*') {
887 return '`' . str_replace('`', '``', $a_name) . '`';
888 } else {
889 return $a_name;
891 } // end of the 'PMA_backquote()' function
894 * Defines the <CR><LF> value depending on the user OS.
896 * @return string the <CR><LF> value to use
898 * @access public
900 function PMA_whichCrlf()
902 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
903 // Win case
904 if (PMA_USR_OS == 'Win') {
905 $the_crlf = "\r\n";
906 } else {
907 // Others
908 $the_crlf = "\n";
911 return $the_crlf;
912 } // end of the 'PMA_whichCrlf()' function
915 * Reloads navigation if needed.
917 * @param bool $jsonly prints out pure JavaScript
919 * @access public
921 function PMA_reloadNavigation($jsonly=false)
923 // Reloads the navigation frame via JavaScript if required
924 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
925 // one of the reasons for a reload is when a table is dropped
926 // in this case, get rid of the table limit offset, otherwise
927 // we have a problem when dropping a table on the last page
928 // and the offset becomes greater than the total number of tables
929 unset($_SESSION['tmp_user_values']['table_limit_offset']);
930 echo "\n";
931 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
932 if (!$jsonly) {
933 echo '<script type="text/javascript">' . PHP_EOL;
936 //<![CDATA[
937 if (typeof(window.parent) != 'undefined'
938 && typeof(window.parent.frame_navigation) != 'undefined'
939 && window.parent.goTo) {
940 window.parent.goTo('<?php echo $reload_url; ?>');
942 //]]>
943 <?php
944 if (!$jsonly) {
945 echo '</script>' . PHP_EOL;
948 unset($GLOBALS['reload']);
953 * displays the message and the query
954 * usually the message is the result of the query executed
956 * @param string $message the message to display
957 * @param string $sql_query the query to display
958 * @param string $type the type (level) of the message
959 * @param boolean $is_view is this a message after a VIEW operation?
961 * @return string
963 * @access public
965 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
968 * PMA_ajaxResponse uses this function to collect the string of HTML generated
969 * for showing the message. Use output buffering to collect it and return it
970 * in a string. In some special cases on sql.php, buffering has to be disabled
971 * and hence we check with $GLOBALS['buffer_message']
973 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
974 ob_start();
976 global $cfg;
978 if (null === $sql_query) {
979 if (! empty($GLOBALS['display_query'])) {
980 $sql_query = $GLOBALS['display_query'];
981 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
982 $sql_query = $GLOBALS['unparsed_sql'];
983 } elseif (! empty($GLOBALS['sql_query'])) {
984 $sql_query = $GLOBALS['sql_query'];
985 } else {
986 $sql_query = '';
990 if (isset($GLOBALS['using_bookmark_message'])) {
991 $GLOBALS['using_bookmark_message']->display();
992 unset($GLOBALS['using_bookmark_message']);
995 // Corrects the tooltip text via JS if required
996 // @todo this is REALLY the wrong place to do this - very unexpected here
997 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
998 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
999 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1000 echo "\n";
1001 echo '<script type="text/javascript">' . "\n";
1002 echo '//<![CDATA[' . "\n";
1003 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
1004 . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1005 echo '//]]>' . "\n";
1006 echo '</script>' . "\n";
1007 } // end if ... elseif
1009 // Checks if the table needs to be repaired after a TRUNCATE query.
1010 // @todo what about $GLOBALS['display_query']???
1011 // @todo this is REALLY the wrong place to do this - very unexpected here
1012 if (strlen($GLOBALS['table'])
1013 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
1015 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
1016 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1019 unset($tbl_status);
1021 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1022 // check for it's presence before using it
1023 echo '<div id="result_query" align="'
1024 . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' )
1025 . '">' . "\n";
1027 if ($message instanceof PMA_Message) {
1028 if (isset($GLOBALS['special_message'])) {
1029 $message->addMessage($GLOBALS['special_message']);
1030 unset($GLOBALS['special_message']);
1032 $message->display();
1033 $type = $message->getLevel();
1034 } else {
1035 echo '<div class="' . $type . '">';
1036 echo PMA_sanitize($message);
1037 if (isset($GLOBALS['special_message'])) {
1038 echo PMA_sanitize($GLOBALS['special_message']);
1039 unset($GLOBALS['special_message']);
1041 echo '</div>';
1044 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1045 // Html format the query to be displayed
1046 // If we want to show some sql code it is easiest to create it here
1047 /* SQL-Parser-Analyzer */
1049 if (! empty($GLOBALS['show_as_php'])) {
1050 $new_line = '\\n"<br />' . "\n"
1051 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1052 $query_base = htmlspecialchars(addslashes($sql_query));
1053 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1054 } else {
1055 $query_base = $sql_query;
1058 $query_too_big = false;
1060 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1061 // when the query is large (for example an INSERT of binary
1062 // data), the parser chokes; so avoid parsing the query
1063 $query_too_big = true;
1064 $shortened_query_base = nl2br(
1065 htmlspecialchars(
1066 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
1069 } elseif (! empty($GLOBALS['parsed_sql'])
1070 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1071 // (here, use "! empty" because when deleting a bookmark,
1072 // $GLOBALS['parsed_sql'] is set but empty
1073 $parsed_sql = $GLOBALS['parsed_sql'];
1074 } else {
1075 // Parse SQL if needed
1076 $parsed_sql = PMA_SQP_parse($query_base);
1079 // Analyze it
1080 if (isset($parsed_sql) && ! PMA_SQP_isError()) {
1081 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1083 // Same as below (append LIMIT), append the remembered ORDER BY
1084 if ($GLOBALS['cfg']['RememberSorting']
1085 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1086 && isset($GLOBALS['sql_order_to_append'])
1088 $query_base = $analyzed_display_query[0]['section_before_limit']
1089 . "\n" . $GLOBALS['sql_order_to_append']
1090 . $analyzed_display_query[0]['section_after_limit'];
1092 // Need to reparse query
1093 $parsed_sql = PMA_SQP_parse($query_base);
1094 // update the $analyzed_display_query
1095 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1096 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1099 // Here we append the LIMIT added for navigation, to
1100 // enable its display. Adding it higher in the code
1101 // to $sql_query would create a problem when
1102 // using the Refresh or Edit links.
1104 // Only append it on SELECTs.
1107 * @todo what would be the best to do when someone hits Refresh:
1108 * use the current LIMITs ?
1111 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1112 && isset($GLOBALS['sql_limit_to_append'])
1114 $query_base = $analyzed_display_query[0]['section_before_limit']
1115 . "\n" . $GLOBALS['sql_limit_to_append']
1116 . $analyzed_display_query[0]['section_after_limit'];
1117 // Need to reparse query
1118 $parsed_sql = PMA_SQP_parse($query_base);
1122 if (! empty($GLOBALS['show_as_php'])) {
1123 $query_base = '$sql = "' . $query_base;
1124 } elseif (! empty($GLOBALS['validatequery'])) {
1125 try {
1126 $query_base = PMA_validateSQL($query_base);
1127 } catch (Exception $e) {
1128 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1130 } elseif (isset($parsed_sql)) {
1131 $query_base = PMA_formatSql($parsed_sql, $query_base);
1134 // Prepares links that may be displayed to edit/explain the query
1135 // (don't go to default pages, we must go to the page
1136 // where the query box is available)
1138 // Basic url query part
1139 $url_params = array();
1140 if (! isset($GLOBALS['db'])) {
1141 $GLOBALS['db'] = '';
1143 if (strlen($GLOBALS['db'])) {
1144 $url_params['db'] = $GLOBALS['db'];
1145 if (strlen($GLOBALS['table'])) {
1146 $url_params['table'] = $GLOBALS['table'];
1147 $edit_link = 'tbl_sql.php';
1148 } else {
1149 $edit_link = 'db_sql.php';
1151 } else {
1152 $edit_link = 'server_sql.php';
1155 // Want to have the query explained
1156 // but only explain a SELECT (that has not been explained)
1157 /* SQL-Parser-Analyzer */
1158 $explain_link = '';
1159 $is_select = false;
1160 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1161 $explain_params = $url_params;
1162 // Detect if we are validating as well
1163 // To preserve the validate uRL data
1164 if (! empty($GLOBALS['validatequery'])) {
1165 $explain_params['validatequery'] = 1;
1167 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1168 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1169 $_message = __('Explain SQL');
1170 $is_select = true;
1171 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1172 $explain_params['sql_query'] = substr($sql_query, 8);
1173 $_message = __('Skip Explain SQL');
1175 if (isset($explain_params['sql_query'])) {
1176 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1177 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1179 } //show explain
1181 $url_params['sql_query'] = $sql_query;
1182 $url_params['show_query'] = 1;
1184 // even if the query is big and was truncated, offer the chance
1185 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1186 if (! empty($cfg['SQLQuery']['Edit'])) {
1187 if ($cfg['EditInWindow'] == true) {
1188 $onclick = 'window.parent.focus_querywindow(\''
1189 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1190 } else {
1191 $onclick = '';
1194 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1195 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1196 } else {
1197 $edit_link = '';
1200 $url_qpart = PMA_generate_common_url($url_params);
1202 // Also we would like to get the SQL formed in some nice
1203 // php-code
1204 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1205 $php_params = $url_params;
1207 if (! empty($GLOBALS['show_as_php'])) {
1208 $_message = __('Without PHP Code');
1209 } else {
1210 $php_params['show_as_php'] = 1;
1211 $_message = __('Create PHP Code');
1214 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1215 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1217 if (isset($GLOBALS['show_as_php'])) {
1218 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1219 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1221 } else {
1222 $php_link = '';
1223 } //show as php
1225 // Refresh query
1226 if (! empty($cfg['SQLQuery']['Refresh'])
1227 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1228 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1230 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1231 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1232 } else {
1233 $refresh_link = '';
1234 } //refresh
1236 if (! empty($cfg['SQLValidator']['use'])
1237 && ! empty($cfg['SQLQuery']['Validate'])
1239 $validate_params = $url_params;
1240 if (!empty($GLOBALS['validatequery'])) {
1241 $validate_message = __('Skip Validate SQL');
1242 } else {
1243 $validate_params['validatequery'] = 1;
1244 $validate_message = __('Validate SQL');
1247 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1248 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1249 } else {
1250 $validate_link = '';
1251 } //validator
1253 if (!empty($GLOBALS['validatequery'])) {
1254 echo '<div class="sqlvalidate">';
1255 } else {
1256 echo '<code class="sql">';
1258 if ($query_too_big) {
1259 echo $shortened_query_base;
1260 } else {
1261 echo $query_base;
1264 //Clean up the end of the PHP
1265 if (! empty($GLOBALS['show_as_php'])) {
1266 echo '";';
1268 if (!empty($GLOBALS['validatequery'])) {
1269 echo '</div>';
1270 } else {
1271 echo '</code>';
1274 echo '<div class="tools">';
1275 // avoid displaying a Profiling checkbox that could
1276 // be checked, which would reexecute an INSERT, for example
1277 if (! empty($refresh_link)) {
1278 PMA_profilingCheckbox($sql_query);
1280 // if needed, generate an invisible form that contains controls for the
1281 // Inline link; this way, the behavior of the Inline link does not
1282 // depend on the profiling support or on the refresh link
1283 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1284 echo '<form action="sql.php" method="post">';
1285 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1286 echo '<input type="hidden" name="sql_query" value="'
1287 . htmlspecialchars($sql_query) . '" />';
1288 echo '</form>';
1291 // in the tools div, only display the Inline link when not in ajax
1292 // mode because 1) it currently does not work and 2) we would
1293 // have two similar mechanisms on the page for the same goal
1294 if ($is_select
1295 || $GLOBALS['is_ajax_request'] === false
1296 && ! $query_too_big
1298 // see in js/functions.js the jQuery code attached to id inline_edit
1299 // document.write conflicts with jQuery, hence used $().append()
1300 echo "<script type=\"text/javascript\">\n" .
1301 "//<![CDATA[\n" .
1302 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1303 PMA_escapeJsString(__('Inline edit of this query')) .
1304 "\" class=\"inline_edit_sql\">" .
1305 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1306 "</a>]');\n" .
1307 "//]]>\n" .
1308 "</script>";
1310 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1311 echo '</div>';
1313 echo '</div>';
1314 if ($GLOBALS['is_ajax_request'] === false) {
1315 echo '<br class="clearfloat" />';
1318 // If we are in an Ajax request, we have most probably been called in
1319 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1320 // to PMA_ajaxResponse(), which will encode it for JSON.
1321 if ($GLOBALS['is_ajax_request'] == true
1322 && ! isset($GLOBALS['buffer_message'])
1324 $buffer_contents = ob_get_contents();
1325 ob_end_clean();
1326 return $buffer_contents;
1328 return null;
1329 } // end of the 'PMA_showMessage()' function
1332 * Verifies if current MySQL server supports profiling
1334 * @access public
1336 * @return boolean whether profiling is supported
1338 function PMA_profilingSupported()
1340 if (! PMA_cacheExists('profiling_supported', true)) {
1341 // 5.0.37 has profiling but for example, 5.1.20 does not
1342 // (avoid a trip to the server for MySQL before 5.0.37)
1343 // and do not set a constant as we might be switching servers
1344 if (defined('PMA_MYSQL_INT_VERSION')
1345 && PMA_MYSQL_INT_VERSION >= 50037
1346 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1348 PMA_cacheSet('profiling_supported', true, true);
1349 } else {
1350 PMA_cacheSet('profiling_supported', false, true);
1354 return PMA_cacheGet('profiling_supported', true);
1358 * Displays a form with the Profiling checkbox
1360 * @param string $sql_query sql query
1362 * @access public
1364 function PMA_profilingCheckbox($sql_query)
1366 if (PMA_profilingSupported()) {
1367 echo '<form action="sql.php" method="post">' . "\n";
1368 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1369 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1370 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1371 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1372 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1373 echo '</form>' . "\n";
1378 * Formats $value to byte view
1380 * @param double $value the value to format
1381 * @param int $limes the sensitiveness
1382 * @param int $comma the number of decimals to retain
1384 * @return array the formatted value and its unit
1386 * @access public
1388 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1390 if ($value === null) {
1391 return null;
1394 $byteUnits = array(
1395 /* l10n: shortcuts for Byte */
1396 __('B'),
1397 /* l10n: shortcuts for Kilobyte */
1398 __('KiB'),
1399 /* l10n: shortcuts for Megabyte */
1400 __('MiB'),
1401 /* l10n: shortcuts for Gigabyte */
1402 __('GiB'),
1403 /* l10n: shortcuts for Terabyte */
1404 __('TiB'),
1405 /* l10n: shortcuts for Petabyte */
1406 __('PiB'),
1407 /* l10n: shortcuts for Exabyte */
1408 __('EiB')
1411 $dh = PMA_pow(10, $comma);
1412 $li = PMA_pow(10, $limes);
1413 $unit = $byteUnits[0];
1415 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1416 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1417 // use 1024.0 to avoid integer overflow on 64-bit machines
1418 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1419 $unit = $byteUnits[$d];
1420 break 1;
1421 } // end if
1422 } // end for
1424 if ($unit != $byteUnits[0]) {
1425 // if the unit is not bytes (as represented in current language)
1426 // reformat with max length of 5
1427 // 4th parameter=true means do not reformat if value < 1
1428 $return_value = PMA_formatNumber($value, 5, $comma, true);
1429 } else {
1430 // do not reformat, just handle the locale
1431 $return_value = PMA_formatNumber($value, 0);
1434 return array(trim($return_value), $unit);
1435 } // end of the 'PMA_formatByteDown' function
1438 * Changes thousands and decimal separators to locale specific values.
1440 * @param string $value the value
1442 * @return string
1444 function PMA_localizeNumber($value)
1446 return str_replace(
1447 array(',', '.'),
1448 array(
1449 /* l10n: Thousands separator */
1450 __(','),
1451 /* l10n: Decimal separator */
1452 __('.'),
1454 $value
1459 * Formats $value to the given length and appends SI prefixes
1460 * with a $length of 0 no truncation occurs, number is only formated
1461 * to the current locale
1463 * examples:
1464 * <code>
1465 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1466 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1467 * echo PMA_formatNumber(-0.003, 6); // -3 m
1468 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1469 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1470 * echo PMA_formatNumber(0, 6); // 0
1471 * </code>
1473 * @param double $value the value to format
1474 * @param integer $digits_left number of digits left of the comma
1475 * @param integer $digits_right number of digits right of the comma
1476 * @param boolean $only_down do not reformat numbers below 1
1477 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1478 * (default: true)
1480 * @return string the formatted value and its unit
1482 * @access public
1484 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1485 $only_down = false, $noTrailingZero = true)
1487 if ($value==0) {
1488 return '0';
1491 $originalValue = $value;
1492 //number_format is not multibyte safe, str_replace is safe
1493 if ($digits_left === 0) {
1494 $value = number_format($value, $digits_right);
1495 if ($originalValue != 0 && floatval($value) == 0) {
1496 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1499 return PMA_localizeNumber($value);
1502 // this units needs no translation, ISO
1503 $units = array(
1504 -8 => 'y',
1505 -7 => 'z',
1506 -6 => 'a',
1507 -5 => 'f',
1508 -4 => 'p',
1509 -3 => 'n',
1510 -2 => '&micro;',
1511 -1 => 'm',
1512 0 => ' ',
1513 1 => 'k',
1514 2 => 'M',
1515 3 => 'G',
1516 4 => 'T',
1517 5 => 'P',
1518 6 => 'E',
1519 7 => 'Z',
1520 8 => 'Y'
1523 // check for negative value to retain sign
1524 if ($value < 0) {
1525 $sign = '-';
1526 $value = abs($value);
1527 } else {
1528 $sign = '';
1531 $dh = PMA_pow(10, $digits_right);
1534 * This gives us the right SI prefix already,
1535 * but $digits_left parameter not incorporated
1537 $d = floor(log10($value) / 3);
1539 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1540 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1541 * to use, then lower the SI prefix
1543 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1544 if ($digits_left > $cur_digits) {
1545 $d-= floor(($digits_left - $cur_digits)/3);
1548 if ($d<0 && $only_down) {
1549 $d=0;
1552 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1553 $unit = $units[$d];
1555 // If we dont want any zeros after the comma just add the thousand seperator
1556 if ($noTrailingZero) {
1557 $value = PMA_localizeNumber(
1558 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1560 } else {
1561 //number_format is not multibyte safe, str_replace is safe
1562 $value = PMA_localizeNumber(number_format($value, $digits_right));
1565 if ($originalValue!=0 && floatval($value) == 0) {
1566 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1569 return $sign . $value . ' ' . $unit;
1570 } // end of the 'PMA_formatNumber' function
1573 * Returns the number of bytes when a formatted size is given
1575 * @param string $formatted_size the size expression (for example 8MB)
1577 * @return integer The numerical part of the expression (for example 8)
1579 function PMA_extractValueFromFormattedSize($formatted_size)
1581 $return_value = -1;
1583 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1584 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1585 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1586 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1587 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1588 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1590 return $return_value;
1591 }// end of the 'PMA_extractValueFromFormattedSize' function
1594 * Writes localised date
1596 * @param string $timestamp the current timestamp
1597 * @param string $format format
1599 * @return string the formatted date
1601 * @access public
1603 function PMA_localisedDate($timestamp = -1, $format = '')
1605 $month = array(
1606 /* l10n: Short month name */
1607 __('Jan'),
1608 /* l10n: Short month name */
1609 __('Feb'),
1610 /* l10n: Short month name */
1611 __('Mar'),
1612 /* l10n: Short month name */
1613 __('Apr'),
1614 /* l10n: Short month name */
1615 _pgettext('Short month name', 'May'),
1616 /* l10n: Short month name */
1617 __('Jun'),
1618 /* l10n: Short month name */
1619 __('Jul'),
1620 /* l10n: Short month name */
1621 __('Aug'),
1622 /* l10n: Short month name */
1623 __('Sep'),
1624 /* l10n: Short month name */
1625 __('Oct'),
1626 /* l10n: Short month name */
1627 __('Nov'),
1628 /* l10n: Short month name */
1629 __('Dec'));
1630 $day_of_week = array(
1631 /* l10n: Short week day name */
1632 _pgettext('Short week day name', 'Sun'),
1633 /* l10n: Short week day name */
1634 __('Mon'),
1635 /* l10n: Short week day name */
1636 __('Tue'),
1637 /* l10n: Short week day name */
1638 __('Wed'),
1639 /* l10n: Short week day name */
1640 __('Thu'),
1641 /* l10n: Short week day name */
1642 __('Fri'),
1643 /* l10n: Short week day name */
1644 __('Sat'));
1646 if ($format == '') {
1647 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1648 $format = __('%B %d, %Y at %I:%M %p');
1651 if ($timestamp == -1) {
1652 $timestamp = time();
1655 $date = preg_replace(
1656 '@%[aA]@',
1657 $day_of_week[(int)strftime('%w', $timestamp)],
1658 $format
1660 $date = preg_replace(
1661 '@%[bB]@',
1662 $month[(int)strftime('%m', $timestamp)-1],
1663 $date
1666 return strftime($date, $timestamp);
1667 } // end of the 'PMA_localisedDate()' function
1671 * returns a tab for tabbed navigation.
1672 * If the variables $link and $args ar left empty, an inactive tab is created
1674 * @param array $tab array with all options
1675 * @param array $url_params
1677 * @return string html code for one tab, a link if valid otherwise a span
1679 * @access public
1681 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1683 // default values
1684 $defaults = array(
1685 'text' => '',
1686 'class' => '',
1687 'active' => null,
1688 'link' => '',
1689 'sep' => '?',
1690 'attr' => '',
1691 'args' => '',
1692 'warning' => '',
1693 'fragment' => '',
1694 'id' => '',
1697 $tab = array_merge($defaults, $tab);
1699 // determine additionnal style-class
1700 if (empty($tab['class'])) {
1701 if (! empty($tab['active'])
1702 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1704 $tab['class'] = 'active';
1705 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1706 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1707 && empty($tab['warning'])) {
1708 $tab['class'] = 'active';
1712 if (!empty($tab['warning'])) {
1713 $tab['class'] .= ' error';
1714 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1717 // If there are any tab specific URL parameters, merge those with
1718 // the general URL parameters
1719 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1720 $url_params = array_merge($url_params, $tab['url_params']);
1723 // build the link
1724 if (!empty($tab['link'])) {
1725 $tab['link'] = htmlentities($tab['link']);
1726 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1727 if (! empty($tab['args'])) {
1728 foreach ($tab['args'] as $param => $value) {
1729 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1730 . '=' . urlencode($value);
1735 if (! empty($tab['fragment'])) {
1736 $tab['link'] .= $tab['fragment'];
1739 // display icon, even if iconic is disabled but the link-text is missing
1740 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1741 && isset($tab['icon'])
1743 // avoid generating an alt tag, because it only illustrates
1744 // the text that follows and if browser does not display
1745 // images, the text is duplicated
1746 $tab['text'] = PMA_getImage(htmlentities($tab['icon'])) . $tab['text'];
1748 } elseif (empty($tab['text'])) {
1749 // check to not display an empty link-text
1750 $tab['text'] = '?';
1751 trigger_error(
1752 'empty linktext in function ' . __FUNCTION__ . '()',
1753 E_USER_NOTICE
1757 //Set the id for the tab, if set in the params
1758 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1759 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1761 if (!empty($tab['link'])) {
1762 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1763 .$id_string
1764 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1765 . $tab['text'] . '</a>';
1766 } else {
1767 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1768 . $tab['text'] . '</span>';
1771 $out .= '</li>';
1772 return $out;
1773 } // end of the 'PMA_generate_html_tab()' function
1776 * returns html-code for a tab navigation
1778 * @param array $tabs one element per tab
1779 * @param string $url_params
1780 * @param string $base_dir
1781 * @param string $menu_id
1783 * @return string html-code for tab-navigation
1785 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='', $menu_id='topmenu')
1787 $tab_navigation = '<div id="' . htmlentities($menu_id) . 'container" class="menucontainer">'
1788 .'<ul id="' . htmlentities($menu_id) . '">';
1790 foreach ($tabs as $tab) {
1791 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1794 $tab_navigation .=
1795 '</ul>' . "\n"
1796 .'<div class="clearfloat"></div>'
1797 .'</div>' . "\n";
1799 return $tab_navigation;
1804 * Displays a link, or a button if the link's URL is too large, to
1805 * accommodate some browsers' limitations
1807 * @param string $url the URL
1808 * @param string $message the link message
1809 * @param mixed $tag_params string: js confirmation
1810 * array: additional tag params (f.e. style="")
1811 * @param boolean $new_form we set this to false when we are already in
1812 * a form, to avoid generating nested forms
1813 * @param boolean $strip_img whether to strip the image
1814 * @param string $target target
1816 * @return string the results to be echoed or saved in an array
1818 function PMA_linkOrButton($url, $message, $tag_params = array(),
1819 $new_form = true, $strip_img = false, $target = '')
1821 $url_length = strlen($url);
1822 // with this we should be able to catch case of image upload
1823 // into a (MEDIUM) BLOB; not worth generating even a form for these
1824 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1825 return '';
1829 if (! is_array($tag_params)) {
1830 $tmp = $tag_params;
1831 $tag_params = array();
1832 if (!empty($tmp)) {
1833 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1835 unset($tmp);
1837 if (! empty($target)) {
1838 $tag_params['target'] = htmlentities($target);
1841 $tag_params_strings = array();
1842 foreach ($tag_params as $par_name => $par_value) {
1843 // htmlspecialchars() only on non javascript
1844 $par_value = substr($par_name, 0, 2) == 'on'
1845 ? $par_value
1846 : htmlspecialchars($par_value);
1847 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1850 $displayed_message = '';
1851 // Add text if not already added
1852 if (stristr($message, '<img')
1853 && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
1854 && strip_tags($message)==$message
1856 $displayed_message = '<span>'
1857 . htmlspecialchars(
1858 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1860 . '</span>';
1863 // Suhosin: Check that each query parameter is not above maximum
1864 $in_suhosin_limits = true;
1865 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1866 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1867 $query_parts = PMA_splitURLQuery($url);
1868 foreach ($query_parts as $query_pair) {
1869 list($eachvar, $eachval) = explode('=', $query_pair);
1870 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1871 $in_suhosin_limits = false;
1872 break;
1878 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1879 // no whitespace within an <a> else Safari will make it part of the link
1880 $ret = "\n" . '<a href="' . $url . '" '
1881 . implode(' ', $tag_params_strings) . '>'
1882 . $message . $displayed_message . '</a>' . "\n";
1883 } else {
1884 // no spaces (linebreaks) at all
1885 // or after the hidden fields
1886 // IE will display them all
1888 // add class=link to submit button
1889 if (empty($tag_params['class'])) {
1890 $tag_params['class'] = 'link';
1893 if (! isset($query_parts)) {
1894 $query_parts = PMA_splitURLQuery($url);
1896 $url_parts = parse_url($url);
1898 if ($new_form) {
1899 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1900 . ' method="post"' . $target . ' style="display: inline;">';
1901 $subname_open = '';
1902 $subname_close = '';
1903 $submit_link = '#';
1904 } else {
1905 $query_parts[] = 'redirect=' . $url_parts['path'];
1906 if (empty($GLOBALS['subform_counter'])) {
1907 $GLOBALS['subform_counter'] = 0;
1909 $GLOBALS['subform_counter']++;
1910 $ret = '';
1911 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1912 $subname_close = ']';
1913 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1915 foreach ($query_parts as $query_pair) {
1916 list($eachvar, $eachval) = explode('=', $query_pair);
1917 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1918 . $subname_close . '" value="'
1919 . htmlspecialchars(urldecode($eachval)) . '" />';
1920 } // end while
1922 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1923 . implode(' ', $tag_params_strings) . '>'
1924 . $message . ' ' . $displayed_message . '</a>' . "\n";
1926 if ($new_form) {
1927 $ret .= '</form>';
1929 } // end if... else...
1931 return $ret;
1932 } // end of the 'PMA_linkOrButton()' function
1936 * Splits a URL string by parameter
1938 * @param string $url the URL
1940 * @return array the parameter/value pairs, for example [0] db=sakila
1942 function PMA_splitURLQuery($url)
1944 // decode encoded url separators
1945 $separator = PMA_get_arg_separator();
1946 // on most places separator is still hard coded ...
1947 if ($separator !== '&') {
1948 // ... so always replace & with $separator
1949 $url = str_replace(htmlentities('&'), $separator, $url);
1950 $url = str_replace('&', $separator, $url);
1952 $url = str_replace(htmlentities($separator), $separator, $url);
1953 // end decode
1955 $url_parts = parse_url($url);
1956 return explode($separator, $url_parts['query']);
1960 * Returns a given timespan value in a readable format.
1962 * @param int $seconds the timespan
1964 * @return string the formatted value
1966 function PMA_timespanFormat($seconds)
1968 $days = floor($seconds / 86400);
1969 if ($days > 0) {
1970 $seconds -= $days * 86400;
1972 $hours = floor($seconds / 3600);
1973 if ($days > 0 || $hours > 0) {
1974 $seconds -= $hours * 3600;
1976 $minutes = floor($seconds / 60);
1977 if ($days > 0 || $hours > 0 || $minutes > 0) {
1978 $seconds -= $minutes * 60;
1980 return sprintf(
1981 __('%s days, %s hours, %s minutes and %s seconds'),
1982 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1987 * Takes a string and outputs each character on a line for itself. Used
1988 * mainly for horizontalflipped display mode.
1989 * Takes care of special html-characters.
1990 * Fulfills todo-item
1991 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1993 * @param string $string The string
1994 * @param string $Separator The Separator (defaults to "<br />\n")
1996 * @access public
1997 * @todo add a multibyte safe function PMA_STR_split()
1999 * @return string The flipped string
2001 function PMA_flipstring($string, $Separator = "<br />\n")
2003 $format_string = '';
2004 $charbuff = false;
2006 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
2007 $char = $string{$i};
2008 $append = false;
2010 if ($char == '&') {
2011 $format_string .= $charbuff;
2012 $charbuff = $char;
2013 } elseif ($char == ';' && !empty($charbuff)) {
2014 $format_string .= $charbuff . $char;
2015 $charbuff = false;
2016 $append = true;
2017 } elseif (! empty($charbuff)) {
2018 $charbuff .= $char;
2019 } else {
2020 $format_string .= $char;
2021 $append = true;
2024 // do not add separator after the last character
2025 if ($append && ($i != $str_len - 1)) {
2026 $format_string .= $Separator;
2030 return $format_string;
2034 * Function added to avoid path disclosures.
2035 * Called by each script that needs parameters, it displays
2036 * an error message and, by default, stops the execution.
2038 * Not sure we could use a strMissingParameter message here,
2039 * would have to check if the error message file is always available
2041 * @param array $params The names of the parameters needed by the calling script.
2042 * @param bool $die Stop the execution?
2043 * (Set this manually to false in the calling script
2044 * until you know all needed parameters to check).
2045 * @param bool $request Whether to include this list in checking for special params.
2047 * @global string path to current script
2048 * @global boolean flag whether any special variable was required
2050 * @access public
2051 * @todo use PMA_fatalError() if $die === true?
2053 function PMA_checkParameters($params, $die = true, $request = true)
2055 global $checked_special;
2057 if (! isset($checked_special)) {
2058 $checked_special = false;
2061 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2062 $found_error = false;
2063 $error_message = '';
2065 foreach ($params as $param) {
2066 if ($request && $param != 'db' && $param != 'table') {
2067 $checked_special = true;
2070 if (! isset($GLOBALS[$param])) {
2071 $error_message .= $reported_script_name
2072 . ': ' . __('Missing parameter:') . ' '
2073 . $param
2074 . PMA_showDocu('faqmissingparameters')
2075 . '<br />';
2076 $found_error = true;
2079 if ($found_error) {
2081 * display html meta tags
2083 include_once './libraries/header_meta_style.inc.php';
2084 echo '</head><body><p>' . $error_message . '</p></body></html>';
2085 if ($die) {
2086 exit();
2089 } // end function
2092 * Function to generate unique condition for specified row.
2094 * @param resource $handle current query result
2095 * @param integer $fields_cnt number of fields
2096 * @param array $fields_meta meta information about fields
2097 * @param array $row current row
2098 * @param boolean $force_unique generate condition only on pk or unique
2100 * @access public
2102 * @return array the calculated condition and whether condition is unique
2104 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2106 $primary_key = '';
2107 $unique_key = '';
2108 $nonprimary_condition = '';
2109 $preferred_condition = '';
2110 $primary_key_array = array();
2111 $unique_key_array = array();
2112 $nonprimary_condition_array = array();
2113 $condition_array = array();
2115 for ($i = 0; $i < $fields_cnt; ++$i) {
2116 $condition = '';
2117 $con_key = '';
2118 $con_val = '';
2119 $field_flags = PMA_DBI_field_flags($handle, $i);
2120 $meta = $fields_meta[$i];
2122 // do not use a column alias in a condition
2123 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2124 $meta->orgname = $meta->name;
2126 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2127 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2129 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2130 // need (string) === (string)
2131 // '' !== 0 but '' == 0
2132 if ((string) $select_expr['alias'] === (string) $meta->name) {
2133 $meta->orgname = $select_expr['column'];
2134 break;
2135 } // end if
2136 } // end foreach
2140 // Do not use a table alias in a condition.
2141 // Test case is:
2142 // select * from galerie x WHERE
2143 //(select count(*) from galerie y where y.datum=x.datum)>1
2145 // But orgtable is present only with mysqli extension so the
2146 // fix is only for mysqli.
2147 // Also, do not use the original table name if we are dealing with
2148 // a view because this view might be updatable.
2149 // (The isView() verification should not be costly in most cases
2150 // because there is some caching in the function).
2151 if (isset($meta->orgtable)
2152 && $meta->table != $meta->orgtable
2153 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2155 $meta->table = $meta->orgtable;
2158 // to fix the bug where float fields (primary or not)
2159 // can't be matched because of the imprecision of
2160 // floating comparison, use CONCAT
2161 // (also, the syntax "CONCAT(field) IS NULL"
2162 // that we need on the next "if" will work)
2163 if ($meta->type == 'real') {
2164 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2165 . PMA_backquote($meta->orgname) . ')';
2166 } else {
2167 $con_key = PMA_backquote($meta->table) . '.'
2168 . PMA_backquote($meta->orgname);
2169 } // end if... else...
2170 $condition = ' ' . $con_key . ' ';
2172 if (! isset($row[$i]) || is_null($row[$i])) {
2173 $con_val = 'IS NULL';
2174 } else {
2175 // timestamp is numeric on some MySQL 4.1
2176 // for real we use CONCAT above and it should compare to string
2177 if ($meta->numeric
2178 && $meta->type != 'timestamp'
2179 && $meta->type != 'real'
2181 $con_val = '= ' . $row[$i];
2182 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2183 // hexify only if this is a true not empty BLOB or a BINARY
2184 && stristr($field_flags, 'BINARY')
2185 && !empty($row[$i])) {
2186 // do not waste memory building a too big condition
2187 if (strlen($row[$i]) < 1000) {
2188 // use a CAST if possible, to avoid problems
2189 // if the field contains wildcard characters % or _
2190 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2191 } else {
2192 // this blob won't be part of the final condition
2193 $con_val = null;
2195 } elseif (in_array($meta->type, PMA_getGISDatatypes())
2196 && ! empty($row[$i])
2198 // do not build a too big condition
2199 if (strlen($row[$i]) < 5000) {
2200 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2201 } else {
2202 $condition = '';
2204 } elseif ($meta->type == 'bit') {
2205 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2206 } else {
2207 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2210 if ($con_val != null) {
2211 $condition .= $con_val . ' AND';
2212 if ($meta->primary_key > 0) {
2213 $primary_key .= $condition;
2214 $primary_key_array[$con_key] = $con_val;
2215 } elseif ($meta->unique_key > 0) {
2216 $unique_key .= $condition;
2217 $unique_key_array[$con_key] = $con_val;
2219 $nonprimary_condition .= $condition;
2220 $nonprimary_condition_array[$con_key] = $con_val;
2222 } // end for
2224 // Correction University of Virginia 19991216:
2225 // prefer primary or unique keys for condition,
2226 // but use conjunction of all values if no primary key
2227 $clause_is_unique = true;
2228 if ($primary_key) {
2229 $preferred_condition = $primary_key;
2230 $condition_array = $primary_key_array;
2231 } elseif ($unique_key) {
2232 $preferred_condition = $unique_key;
2233 $condition_array = $unique_key_array;
2234 } elseif (! $force_unique) {
2235 $preferred_condition = $nonprimary_condition;
2236 $condition_array = $nonprimary_condition_array;
2237 $clause_is_unique = false;
2240 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2241 return(array($where_clause, $clause_is_unique, $condition_array));
2242 } // end function
2245 * Generate a button or image tag
2247 * @param string $button_name name of button element
2248 * @param string $button_class class of button element
2249 * @param string $image_name name of image element
2250 * @param string $text text to display
2251 * @param string $image image to display
2252 * @param string $value value
2254 * @access public
2256 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2257 $image, $value = '')
2259 if ($value == '') {
2260 $value = $text;
2262 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2263 echo ' <input type="submit" name="' . $button_name . '"'
2264 .' value="' . htmlspecialchars($value) . '"'
2265 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2266 return;
2269 /* Opera has trouble with <input type="image"> */
2270 /* IE has trouble with <button> */
2271 if (PMA_USR_BROWSER_AGENT != 'IE') {
2272 echo '<button class="' . $button_class . '" type="submit"'
2273 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2274 .' title="' . htmlspecialchars($text) . '">' . "\n"
2275 . PMA_getIcon($image, $text)
2276 .'</button>' . "\n";
2277 } else {
2278 echo '<input type="image" name="' . $image_name
2279 . '" value="' . htmlspecialchars($value)
2280 . '" title="' . htmlspecialchars($text)
2281 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2282 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2283 ? '&nbsp;' . htmlspecialchars($text)
2284 : '') . "\n";
2286 } // end function
2289 * Generate a pagination selector for browsing resultsets
2291 * @param int $rows Number of rows in the pagination set
2292 * @param int $pageNow current page number
2293 * @param int $nbTotalPage number of total pages
2294 * @param int $showAll If the number of pages is lower than this
2295 * variable, no pages will be omitted in pagination
2296 * @param int $sliceStart How many rows at the beginning should always be shown?
2297 * @param int $sliceEnd How many rows at the end should always be shown?
2298 * @param int $percent Percentage of calculation page offsets to hop to a
2299 * next page
2300 * @param int $range Near the current page, how many pages should
2301 * be considered "nearby" and displayed as well?
2302 * @param string $prompt The prompt to display (sometimes empty)
2304 * @return string
2306 * @access public
2308 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2309 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2310 $range = 10, $prompt = '')
2312 $increment = floor($nbTotalPage / $percent);
2313 $pageNowMinusRange = ($pageNow - $range);
2314 $pageNowPlusRange = ($pageNow + $range);
2316 $gotopage = $prompt . ' <select id="pageselector" ';
2317 if ($GLOBALS['cfg']['AjaxEnable']) {
2318 $gotopage .= ' class="ajax"';
2320 $gotopage .= ' name="pos" >' . "\n";
2321 if ($nbTotalPage < $showAll) {
2322 $pages = range(1, $nbTotalPage);
2323 } else {
2324 $pages = array();
2326 // Always show first X pages
2327 for ($i = 1; $i <= $sliceStart; $i++) {
2328 $pages[] = $i;
2331 // Always show last X pages
2332 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2333 $pages[] = $i;
2336 // Based on the number of results we add the specified
2337 // $percent percentage to each page number,
2338 // so that we have a representing page number every now and then to
2339 // immediately jump to specific pages.
2340 // As soon as we get near our currently chosen page ($pageNow -
2341 // $range), every page number will be shown.
2342 $i = $sliceStart;
2343 $x = $nbTotalPage - $sliceEnd;
2344 $met_boundary = false;
2345 while ($i <= $x) {
2346 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2347 // If our pageselector comes near the current page, we use 1
2348 // counter increments
2349 $i++;
2350 $met_boundary = true;
2351 } else {
2352 // We add the percentage increment to our current page to
2353 // hop to the next one in range
2354 $i += $increment;
2356 // Make sure that we do not cross our boundaries.
2357 if ($i > $pageNowMinusRange && ! $met_boundary) {
2358 $i = $pageNowMinusRange;
2362 if ($i > 0 && $i <= $x) {
2363 $pages[] = $i;
2368 Add page numbers with "geometrically increasing" distances.
2370 This helps me a lot when navigating through giant tables.
2372 Test case: table with 2.28 million sets, 76190 pages. Page of interest is
2373 between 72376 and 76190.
2374 Selecting page 72376.
2375 Now, old version enumerated only +/- 10 pages around 72376 and the
2376 percentage increment produced steps of about 3000.
2378 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2379 around the current page.
2382 $i = $pageNow;
2383 $dist = 1;
2384 while ($i < $x) {
2385 $dist = 2 * $dist;
2386 $i = $pageNow + $dist;
2387 if ($i > 0 && $i <= $x) {
2388 $pages[] = $i;
2392 $i = $pageNow;
2393 $dist = 1;
2394 while ($i >0) {
2395 $dist = 2 * $dist;
2396 $i = $pageNow - $dist;
2397 if ($i > 0 && $i <= $x) {
2398 $pages[] = $i;
2402 // Since because of ellipsing of the current page some numbers may be double,
2403 // we unify our array:
2404 sort($pages);
2405 $pages = array_unique($pages);
2408 foreach ($pages as $i) {
2409 if ($i == $pageNow) {
2410 $selected = 'selected="selected" style="font-weight: bold"';
2411 } else {
2412 $selected = '';
2414 $gotopage .= ' <option ' . $selected
2415 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2418 $gotopage .= ' </select><noscript><input type="submit" value="'
2419 . __('Go') . '" /></noscript>';
2421 return $gotopage;
2422 } // end function
2426 * Generate navigation for a list
2428 * @param int $count number of elements in the list
2429 * @param int $pos current position in the list
2430 * @param array $_url_params url parameters
2431 * @param string $script script name for form target
2432 * @param string $frame target frame
2433 * @param int $max_count maximum number of elements to display from the list
2435 * @access public
2437 * @todo use $pos from $_url_params
2439 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2442 if ($max_count < $count) {
2443 echo 'frame_navigation' == $frame
2444 ? '<div id="navidbpageselector">' . "\n"
2445 : '';
2446 echo __('Page number:');
2447 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2449 // Move to the beginning or to the previous page
2450 if ($pos > 0) {
2451 // patch #474210 - part 1
2452 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2453 $caption1 = '&lt;&lt;';
2454 $caption2 = ' &lt; ';
2455 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2456 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2457 } else {
2458 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2459 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2460 $title1 = '';
2461 $title2 = '';
2462 } // end if... else...
2463 $_url_params['pos'] = 0;
2464 echo '<a' . $title1 . ' href="' . $script
2465 . PMA_generate_common_url($_url_params) . '" target="'
2466 . $frame . '">' . $caption1 . '</a>';
2467 $_url_params['pos'] = $pos - $max_count;
2468 echo '<a' . $title2 . ' href="' . $script
2469 . PMA_generate_common_url($_url_params) . '" target="'
2470 . $frame . '">' . $caption2 . '</a>';
2473 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2474 echo PMA_generate_common_hidden_inputs($_url_params);
2475 echo PMA_pageselector(
2476 $max_count,
2477 floor(($pos + 1) / $max_count) + 1,
2478 ceil($count / $max_count)
2480 echo '</form>';
2482 if ($pos + $max_count < $count) {
2483 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2484 $caption3 = ' &gt; ';
2485 $caption4 = '&gt;&gt;';
2486 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2487 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2488 } else {
2489 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2490 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2491 $title3 = '';
2492 $title4 = '';
2493 } // end if... else...
2494 $_url_params['pos'] = $pos + $max_count;
2495 echo '<a' . $title3 . ' href="' . $script
2496 . PMA_generate_common_url($_url_params) . '" target="'
2497 . $frame . '">' . $caption3 . '</a>';
2498 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2499 if ($_url_params['pos'] == $count) {
2500 $_url_params['pos'] = $count - $max_count;
2502 echo '<a' . $title4 . ' href="' . $script
2503 . PMA_generate_common_url($_url_params) . '" target="'
2504 . $frame . '">' . $caption4 . '</a>';
2506 echo "\n";
2507 if ('frame_navigation' == $frame) {
2508 echo '</div>' . "\n";
2514 * replaces %u in given path with current user name
2516 * example:
2517 * <code>
2518 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2520 * </code>
2522 * @param string $dir with wildcard for user
2524 * @return string per user directory
2526 function PMA_userDir($dir)
2528 // add trailing slash
2529 if (substr($dir, -1) != '/') {
2530 $dir .= '/';
2533 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2537 * returns html code for db link to default db page
2539 * @param string $database database
2541 * @return string html link to default db page
2543 function PMA_getDbLink($database = null)
2545 if (! strlen($database)) {
2546 if (! strlen($GLOBALS['db'])) {
2547 return '';
2549 $database = $GLOBALS['db'];
2550 } else {
2551 $database = PMA_unescape_mysql_wildcards($database);
2554 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2555 . PMA_generate_common_url($database) . '" title="'
2556 . sprintf(
2557 __('Jump to database &quot;%s&quot;.'),
2558 htmlspecialchars($database)
2560 . '">' . htmlspecialchars($database) . '</a>';
2564 * Displays a lightbulb hint explaining a known external bug
2565 * that affects a functionality
2567 * @param string $functionality localized message explaining the func.
2568 * @param string $component 'mysql' (eventually, 'php')
2569 * @param string $minimum_version of this component
2570 * @param string $bugref bug reference for this component
2572 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2574 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2575 echo PMA_showHint(
2576 sprintf(
2577 __('The %s functionality is affected by a known bug, see %s'),
2578 $functionality,
2579 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2586 * Generates and echoes an HTML checkbox
2588 * @param string $html_field_name the checkbox HTML field
2589 * @param string $label label for checkbox
2590 * @param boolean $checked is it initially checked?
2591 * @param boolean $onclick should it submit the form on click?
2593 * @return the HTML for the checkbox
2595 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2598 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2599 . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
2600 . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
2601 . $html_field_name . '">' . $label . '</label>';
2605 * Generates and echoes a set of radio HTML fields
2607 * @param string $html_field_name the radio HTML field
2608 * @param array $choices the choices values and labels
2609 * @param string $checked_choice the choice to check by default
2610 * @param boolean $line_break whether to add an HTML line break after a choice
2611 * @param boolean $escape_label whether to use htmlspecialchars() on label
2612 * @param string $class enclose each choice with a div of this class
2614 * @return the HTML for the tadio buttons
2616 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2617 $line_break = true, $escape_label = true, $class='')
2619 foreach ($choices as $choice_value => $choice_label) {
2620 if (! empty($class)) {
2621 echo '<div class="' . $class . '">';
2623 $html_field_id = $html_field_name . '_' . $choice_value;
2624 echo '<input type="radio" name="' . $html_field_name . '" id="'
2625 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2626 if ($choice_value == $checked_choice) {
2627 echo ' checked="checked"';
2629 echo ' />' . "\n";
2630 echo '<label for="' . $html_field_id . '">'
2631 . ($escape_label ? htmlspecialchars($choice_label) : $choice_label)
2632 . '</label>';
2633 if ($line_break) {
2634 echo '<br />';
2636 if (! empty($class)) {
2637 echo '</div>';
2639 echo "\n";
2644 * Generates and returns an HTML dropdown
2646 * @param string $select_name name for the select element
2647 * @param array $choices choices values
2648 * @param string $active_choice the choice to select by default
2649 * @param string $id id of the select element; can be different in case
2650 * the dropdown is present more than once on the page
2652 * @return string
2654 * @todo support titles
2656 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2658 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2659 . htmlspecialchars($id) . '">';
2660 foreach ($choices as $one_choice_value => $one_choice_label) {
2661 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2662 if ($one_choice_value == $active_choice) {
2663 $result .= ' selected="selected"';
2665 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2667 $result .= '</select>';
2668 return $result;
2672 * Generates a slider effect (jQjuery)
2673 * Takes care of generating the initial <div> and the link
2674 * controlling the slider; you have to generate the </div> yourself
2675 * after the sliding section.
2677 * @param string $id the id of the <div> on which to apply the effect
2678 * @param string $message the message to show as a link
2680 function PMA_generate_slider_effect($id, $message)
2682 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2683 echo '<div id="' . $id . '">';
2684 return;
2687 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2688 * opening the <div> with PHP itself instead of JavaScript.
2690 * @todo find a better solution that uses $.append(), the recommended method
2691 * maybe by using an additional param, the id of the div to append to
2694 <div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none; overflow:auto;"' : ''; ?> class="pma_auto_slider" title="<?php echo htmlspecialchars($message); ?>">
2695 <?php
2699 * Creates an AJAX sliding toggle button
2700 * (or and equivalent form when AJAX is disabled)
2702 * @param string $action The URL for the request to be executed
2703 * @param string $select_name The name for the dropdown box
2704 * @param array $options An array of options (see rte_footer.lib.php)
2705 * @param string $callback A JS snippet to execute when the request is
2706 * successfully processed
2708 * @return string HTML code for the toggle button
2710 function PMA_toggleButton($action, $select_name, $options, $callback)
2712 // Do the logic first
2713 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2714 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2715 if ($options[1]['selected'] == true) {
2716 $state = 'on';
2717 } else if ($options[0]['selected'] == true) {
2718 $state = 'off';
2719 } else {
2720 $state = 'on';
2722 $selected1 = '';
2723 $selected0 = '';
2724 if ($options[1]['selected'] == true) {
2725 $selected1 = " selected='selected'";
2726 } else if ($options[0]['selected'] == true) {
2727 $selected0 = " selected='selected'";
2729 // Generate output
2730 $retval = "<!-- TOGGLE START -->\n";
2731 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2732 $retval .= "<noscript>\n";
2734 $retval .= "<div class='wrapper'>\n";
2735 $retval .= " <form action='$action' method='post'>\n";
2736 $retval .= " <select name='$select_name'>\n";
2737 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2738 $retval .= " {$options[1]['label']}\n";
2739 $retval .= " </option>\n";
2740 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2741 $retval .= " {$options[0]['label']}\n";
2742 $retval .= " </option>\n";
2743 $retval .= " </select>\n";
2744 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2745 $retval .= " </form>\n";
2746 $retval .= "</div>\n";
2747 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2748 $retval .= "</noscript>\n";
2749 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2750 $retval .= " <div class='toggleButton'>\n";
2751 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2752 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2753 $retval .= " alt='' />\n";
2754 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2755 $retval .= " <tbody>\n";
2756 $retval .= " <td class='toggleOn'>\n";
2757 $retval .= " <span class='hide'>$link_on</span>\n";
2758 $retval .= " <div>";
2759 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2760 $retval .= " </td>\n";
2761 $retval .= " <td><div>&nbsp;</div></td>\n";
2762 $retval .= " <td class='toggleOff'>\n";
2763 $retval .= " <span class='hide'>$link_off</span>\n";
2764 $retval .= " <div>";
2765 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2766 $retval .= " </div>\n";
2767 $retval .= " </tbody>\n";
2768 $retval .= " </tr></table>\n";
2769 $retval .= " <span class='hide callback'>$callback</span>\n";
2770 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2771 $retval .= " </div>\n";
2772 $retval .= " </div>\n";
2773 $retval .= "</div>\n";
2775 $retval .= "<!-- TOGGLE END -->";
2777 return $retval;
2778 } // end PMA_toggleButton()
2781 * Clears cache content which needs to be refreshed on user change.
2783 * @return nothing
2785 function PMA_clearUserCache()
2787 PMA_cacheUnset('is_superuser', true);
2791 * Verifies if something is cached in the session
2793 * @param string $var variable name
2794 * @param int|true $server server
2796 * @return boolean
2798 function PMA_cacheExists($var, $server = 0)
2800 if (true === $server) {
2801 $server = $GLOBALS['server'];
2803 return isset($_SESSION['cache']['server_' . $server][$var]);
2807 * Gets cached information from the session
2809 * @param string $var varibale name
2810 * @param int|true $server server
2812 * @return mixed
2814 function PMA_cacheGet($var, $server = 0)
2816 if (true === $server) {
2817 $server = $GLOBALS['server'];
2819 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2820 return $_SESSION['cache']['server_' . $server][$var];
2821 } else {
2822 return null;
2827 * Caches information in the session
2829 * @param string $var variable name
2830 * @param mixed $val value
2831 * @param int|true $server server
2833 * @return mixed
2835 function PMA_cacheSet($var, $val = null, $server = 0)
2837 if (true === $server) {
2838 $server = $GLOBALS['server'];
2840 $_SESSION['cache']['server_' . $server][$var] = $val;
2844 * Removes cached information from the session
2846 * @param string $var variable name
2847 * @param int|true $server server
2849 * @return nothing
2851 function PMA_cacheUnset($var, $server = 0)
2853 if (true === $server) {
2854 $server = $GLOBALS['server'];
2856 unset($_SESSION['cache']['server_' . $server][$var]);
2860 * Converts a bit value to printable format;
2861 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2862 * function because in PHP, decbin() supports only 32 bits
2864 * @param numeric $value coming from a BIT field
2865 * @param integer $length length
2867 * @return string the printable value
2869 function PMA_printable_bit_value($value, $length)
2871 $printable = '';
2872 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2873 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2875 $printable = substr($printable, -$length);
2876 return $printable;
2880 * Verifies whether the value contains a non-printable character
2882 * @param string $value value
2884 * @return boolean
2886 function PMA_contains_nonprintable_ascii($value)
2888 return preg_match('@[^[:print:]]@', $value);
2892 * Converts a BIT type default value
2893 * for example, b'010' becomes 010
2895 * @param string $bit_default_value value
2897 * @return string the converted value
2899 function PMA_convert_bit_default_value($bit_default_value)
2901 return strtr($bit_default_value, array("b" => "", "'" => ""));
2905 * Extracts the various parts from a field type spec
2907 * @param string $fieldspec Field specification
2909 * @return array associative array containing type, spec_in_brackets
2910 * and possibly enum_set_values (another array)
2912 function PMA_extractFieldSpec($fieldspec)
2914 $first_bracket_pos = strpos($fieldspec, '(');
2915 if ($first_bracket_pos) {
2916 $spec_in_brackets = chop(
2917 substr(
2918 $fieldspec,
2919 $first_bracket_pos + 1,
2920 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2923 // convert to lowercase just to be sure
2924 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2925 } else {
2926 $type = strtolower($fieldspec);
2927 $spec_in_brackets = '';
2930 if ('enum' == $type || 'set' == $type) {
2931 // Define our working vars
2932 $enum_set_values = array();
2933 $working = "";
2934 $in_string = false;
2935 $index = 0;
2937 // While there is another character to process
2938 while (isset($fieldspec[$index])) {
2939 // Grab the char to look at
2940 $char = $fieldspec[$index];
2942 // If it is a single quote, needs to be handled specially
2943 if ($char == "'") {
2944 // If we are not currently in a string, begin one
2945 if (! $in_string) {
2946 $in_string = true;
2947 $working = "";
2948 } else {
2949 // Otherwise, it may be either an end of a string,
2950 // or a 'double quote' which can be handled as-is
2951 // Check out the next character (if possible)
2952 $has_next = isset($fieldspec[$index + 1]);
2953 $next = $has_next ? $fieldspec[$index + 1] : null;
2955 //If we have reached the end of our 'working' string (because
2956 //there are no more chars,or the next char is not another quote)
2957 if (! $has_next || $next != "'") {
2958 $enum_set_values[] = $working;
2959 $in_string = false;
2961 } elseif ($next == "'") {
2962 // Otherwise, this is a 'double quote',
2963 // and can be added to the working string
2964 $working .= "'";
2965 // Skip the next char; we already know what it is
2966 $index++;
2969 } elseif ('\\' == $char
2970 && isset($fieldspec[$index + 1])
2971 && "'" == $fieldspec[$index + 1]
2973 // escaping of a quote?
2974 $working .= "'";
2975 $index++;
2976 } else {
2977 // Otherwise, add it to our working string like normal
2978 $working .= $char;
2980 // Increment character index
2981 $index++;
2982 } // end while
2983 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2984 $binary = false;
2985 $unsigned = false;
2986 $zerofill = false;
2987 } else {
2988 $enum_set_values = array();
2990 /* Create printable type name */
2991 $printtype = strtolower($fieldspec);
2993 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2994 // this would be a BINARY or VARBINARY field type;
2995 // by the way, a BLOB should not show the BINARY attribute
2996 // because this is not accepted in MySQL syntax.
2997 if (preg_match('@binary@', $printtype) && ! preg_match('@binary[\(]@', $printtype)) {
2998 $printtype = preg_replace('@binary@', '', $printtype);
2999 $binary = true;
3000 } else {
3001 $binary = false;
3003 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
3004 $zerofill = ($zerofill_cnt > 0);
3005 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
3006 $unsigned = ($unsigned_cnt > 0);
3007 $printtype = trim($printtype);
3011 $attribute = ' ';
3012 if ($binary) {
3013 $attribute = 'BINARY';
3015 if ($unsigned) {
3016 $attribute = 'UNSIGNED';
3018 if ($zerofill) {
3019 $attribute = 'UNSIGNED ZEROFILL';
3022 return array(
3023 'type' => $type,
3024 'spec_in_brackets' => $spec_in_brackets,
3025 'enum_set_values' => $enum_set_values,
3026 'print_type' => $printtype,
3027 'binary' => $binary,
3028 'unsigned' => $unsigned,
3029 'zerofill' => $zerofill,
3030 'attribute' => $attribute,
3035 * Verifies if this table's engine supports foreign keys
3037 * @param string $engine engine
3039 * @return boolean
3041 function PMA_foreignkey_supported($engine)
3043 $engine = strtoupper($engine);
3044 if ('INNODB' == $engine || 'PBXT' == $engine) {
3045 return true;
3046 } else {
3047 return false;
3052 * Replaces some characters by a displayable equivalent
3054 * @param string $content content
3056 * @return string the content with characters replaced
3058 function PMA_replace_binary_contents($content)
3060 $result = str_replace("\x00", '\0', $content);
3061 $result = str_replace("\x08", '\b', $result);
3062 $result = str_replace("\x0a", '\n', $result);
3063 $result = str_replace("\x0d", '\r', $result);
3064 $result = str_replace("\x1a", '\Z', $result);
3065 return $result;
3069 * Converts GIS data to Well Known Text format
3071 * @param binary $data GIS data
3072 * @param bool $includeSRID Add SRID to the WKT
3074 * @return GIS data in Well Know Text format
3076 function PMA_asWKT($data, $includeSRID = false)
3078 // Convert to WKT format
3079 $hex = bin2hex($data);
3080 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3081 if ($includeSRID) {
3082 $wktsql .= ", SRID(x'" . $hex . "')";
3084 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
3085 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
3086 $wktval = $wktarr[0];
3087 if ($includeSRID) {
3088 $srid = $wktarr[1];
3089 $wktval = "'" . $wktval . "'," . $srid;
3091 @PMA_DBI_free_result($wktresult);
3092 return $wktval;
3096 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3098 * @param string $string string
3100 * @return string with the chars replaced
3103 function PMA_duplicateFirstNewline($string)
3105 $first_occurence = strpos($string, "\r\n");
3106 if ($first_occurence === 0) {
3107 $string = "\n".$string;
3109 return $string;
3113 * Get the action word corresponding to a script name
3114 * in order to display it as a title in navigation panel
3116 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3117 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3119 * @return array
3121 function PMA_getTitleForTarget($target)
3123 $mapping = array(
3124 // Values for $cfg['DefaultTabTable']
3125 'tbl_structure.php' => __('Structure'),
3126 'tbl_sql.php' => __('SQL'),
3127 'tbl_select.php' =>__('Search'),
3128 'tbl_change.php' =>__('Insert'),
3129 'sql.php' => __('Browse'),
3131 // Values for $cfg['DefaultTabDatabase']
3132 'db_structure.php' => __('Structure'),
3133 'db_sql.php' => __('SQL'),
3134 'db_search.php' => __('Search'),
3135 'db_operations.php' => __('Operations'),
3137 return $mapping[$target];
3141 * Formats user string, expanding @VARIABLES@, accepting strftime format string.
3143 * @param string $string Text where to do expansion.
3144 * @param function $escape Function to call for escaping variable values.
3145 * @param array $updates Array with overrides for default parameters
3146 * (obtained from GLOBALS).
3148 * @return string
3150 function PMA_expandUserString($string, $escape = null, $updates = array())
3152 /* Content */
3153 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
3154 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3155 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3156 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3157 ? $GLOBALS['cfg']['Server']['verbose']
3158 : $GLOBALS['cfg']['Server']['host'];
3159 $vars['database'] = $GLOBALS['db'];
3160 $vars['table'] = $GLOBALS['table'];
3161 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3163 /* Update forced variables */
3164 foreach ($updates as $key => $val) {
3165 $vars[$key] = $val;
3168 /* Replacement mapping */
3170 * The __VAR__ ones are for backward compatibility, because user
3171 * might still have it in cookies.
3173 $replace = array(
3174 '@HTTP_HOST@' => $vars['http_host'],
3175 '@SERVER@' => $vars['server_name'],
3176 '__SERVER__' => $vars['server_name'],
3177 '@VERBOSE@' => $vars['server_verbose'],
3178 '@VSERVER@' => $vars['server_verbose_or_name'],
3179 '@DATABASE@' => $vars['database'],
3180 '__DB__' => $vars['database'],
3181 '@TABLE@' => $vars['table'],
3182 '__TABLE__' => $vars['table'],
3183 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3186 /* Optional escaping */
3187 if (!is_null($escape)) {
3188 foreach ($replace as $key => $val) {
3189 $replace[$key] = $escape($val);
3193 /* Backward compatibility in 3.5.x */
3194 if (strpos($string, '@FIELDS@') !== false) {
3195 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3198 /* Fetch columns list if required */
3199 if (strpos($string, '@COLUMNS@') !== false) {
3200 $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3202 $column_names = array();
3203 foreach ($columns_list as $column) {
3204 if (! is_null($escape)) {
3205 $column_names[] = $escape($column['Field']);
3206 } else {
3207 $column_names[] = $field['Field'];
3211 $replace['@COLUMNS@'] = implode(',', $column_names);
3214 /* Do the replacement */
3215 return strtr(strftime($string), $replace);
3219 * function that generates a json output for an ajax request and ends script
3220 * execution
3222 * @param PMA_Message|string $message message string containing the
3223 * html of the message
3224 * @param bool $success success whether the ajax request
3225 * was successfull
3226 * @param array $extra_data extra data optional -
3227 * any other data as part of the json request
3229 * @return nothing
3231 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3233 $response = array();
3234 if ( $success == true ) {
3235 $response['success'] = true;
3236 if ($message instanceof PMA_Message) {
3237 $response['message'] = $message->getDisplay();
3238 } else {
3239 $response['message'] = $message;
3241 } else {
3242 $response['success'] = false;
3243 if ($message instanceof PMA_Message) {
3244 $response['error'] = $message->getDisplay();
3245 } else {
3246 $response['error'] = $message;
3250 // If extra_data has been provided, append it to the response array
3251 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3252 $response = array_merge($response, $extra_data);
3255 // Set the Content-Type header to JSON so that jQuery parses the
3256 // response correctly.
3258 // At this point, other headers might have been sent;
3259 // even if $GLOBALS['is_header_sent'] is true,
3260 // we have to send these additional headers.
3261 header('Cache-Control: no-cache');
3262 header("Content-Type: application/json");
3264 echo json_encode($response);
3266 if (!defined('TESTSUITE'))
3267 exit;
3271 * Display the form used to browse anywhere on the local server for a file to import
3273 * @param string $max_upload_size maximum upload size
3275 * @return nothing
3277 function PMA_browseUploadFile($max_upload_size)
3279 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3280 echo '<div id="upload_form_status" style="display: none;"></div>';
3281 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3282 echo '<input type="file" name="import_file" id="input_import_file" />';
3283 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3284 // some browsers should respect this :)
3285 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3289 * Display the form used to select a file to import from the server upload directory
3291 * @param array $import_list array of import types
3292 * @param string $uploaddir upload directory
3294 * @return nothing
3296 function PMA_selectUploadFile($import_list, $uploaddir)
3298 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3299 $extensions = '';
3300 foreach ($import_list as $key => $val) {
3301 if (!empty($extensions)) {
3302 $extensions .= '|';
3304 $extensions .= $val['extension'];
3306 $matcher = '@\.(' . $extensions . ')(\.('
3307 . PMA_supportedDecompressions() . '))?$@';
3309 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3310 ? $local_import_file
3311 : '';
3312 $files = PMA_getFileSelectOptions(
3313 PMA_userDir($uploaddir),
3314 $matcher,
3315 $active
3317 if ($files === false) {
3318 PMA_Message::error(
3319 __('The directory you set for upload work cannot be reached')
3320 )->display();
3321 } elseif (!empty($files)) {
3322 echo "\n";
3323 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3324 echo ' <option value="">&nbsp;</option>' . "\n";
3325 echo $files;
3326 echo ' </select>' . "\n";
3327 } elseif (empty ($files)) {
3328 echo '<i>' . __('There are no files to upload') . '</i>';
3333 * Build titles and icons for action links
3335 * @return array the action titles
3337 function PMA_buildActionTitles()
3339 $titles = array();
3341 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3342 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3343 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3344 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3345 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3346 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3347 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3348 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3349 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3350 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3351 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3352 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3353 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3354 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3355 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3356 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3357 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3358 return $titles;
3362 * This function processes the datatypes supported by the DB, as specified in
3363 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3364 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3366 * @param bool $html Whether to generate an html snippet or an array
3367 * @param string $selected The value to mark as selected in HTML mode
3369 * @return mixed An HTML snippet or an array of datatypes.
3372 function PMA_getSupportedDatatypes($html = false, $selected = '')
3374 global $cfg;
3376 if ($html) {
3377 // NOTE: the SELECT tag in not included in this snippet.
3378 $retval = '';
3379 foreach ($cfg['ColumnTypes'] as $key => $value) {
3380 if (is_array($value)) {
3381 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3382 foreach ($value as $subvalue) {
3383 if ($subvalue == $selected) {
3384 $retval .= "<option selected='selected'>";
3385 $retval .= $subvalue;
3386 $retval .= "</option>";
3387 } else if ($subvalue === '-') {
3388 $retval .= "<option disabled='disabled'>";
3389 $retval .= $subvalue;
3390 $retval .= "</option>";
3391 } else {
3392 $retval .= "<option>$subvalue</option>";
3395 $retval .= '</optgroup>';
3396 } else {
3397 if ($selected == $value) {
3398 $retval .= "<option selected='selected'>$value</option>";
3399 } else {
3400 $retval .= "<option>$value</option>";
3404 } else {
3405 $retval = array();
3406 foreach ($cfg['ColumnTypes'] as $value) {
3407 if (is_array($value)) {
3408 foreach ($value as $subvalue) {
3409 if ($subvalue !== '-') {
3410 $retval[] = $subvalue;
3413 } else {
3414 if ($value !== '-') {
3415 $retval[] = $value;
3421 return $retval;
3422 } // end PMA_getSupportedDatatypes()
3425 * Returns a list of datatypes that are not (yet) handled by PMA.
3426 * Used by: tbl_change.php and libraries/db_routines.inc.php
3428 * @return array list of datatypes
3430 function PMA_unsupportedDatatypes()
3432 $no_support_types = array();
3433 return $no_support_types;
3437 * Return GIS data types
3439 * @param bool $upper_case whether to return values in upper case
3441 * @return array GIS data types
3443 function PMA_getGISDatatypes($upper_case = false)
3445 $gis_data_types = array(
3446 'geometry',
3447 'point',
3448 'linestring',
3449 'polygon',
3450 'multipoint',
3451 'multilinestring',
3452 'multipolygon',
3453 'geometrycollection'
3455 if ($upper_case) {
3456 for ($i = 0; $i < count($gis_data_types); $i++) {
3457 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3461 return $gis_data_types;
3465 * Generates GIS data based on the string passed.
3467 * @param string $gis_string GIS string
3469 * @return GIS data enclosed in 'GeomFromText' function
3471 function PMA_createGISData($gis_string)
3473 $gis_string = trim($gis_string);
3474 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3475 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3476 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3477 return 'GeomFromText(' . $gis_string . ')';
3478 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3479 return "GeomFromText('" . $gis_string . "')";
3480 } else {
3481 return $gis_string;
3486 * Returns the names and details of the functions
3487 * that can be applied on geometry data typess.
3489 * @param string $geom_type if provided the output is limited to the functions
3490 * that are applicable to the provided geometry type.
3491 * @param bool $binary if set to false functions that take two geometries
3492 * as arguments will not be included.
3493 * @param bool $display if set to true seperators will be added to the
3494 * output array.
3496 * @return array names and details of the functions that can be applied on
3497 * geometry data typess.
3499 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3501 $funcs = array();
3502 if ($display) {
3503 $funcs[] = array('display' => ' ');
3506 // Unary functions common to all geomety types
3507 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3508 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3509 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3510 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3511 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3512 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3514 $geom_type = trim(strtolower($geom_type));
3515 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3516 $funcs[] = array('display' => '--------');
3519 // Unary functions that are specific to each geomety type
3520 if ($geom_type == 'point') {
3521 $funcs['X'] = array('params' => 1, 'type' => 'float');
3522 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3524 } elseif ($geom_type == 'multipoint') {
3525 // no fucntions here
3526 } elseif ($geom_type == 'linestring') {
3527 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3528 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3529 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3530 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3531 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3533 } elseif ($geom_type == 'multilinestring') {
3534 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3535 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3537 } elseif ($geom_type == 'polygon') {
3538 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3539 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3540 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3542 } elseif ($geom_type == 'multipolygon') {
3543 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3544 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3545 // Not yet implemented in MySQL
3546 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3548 } elseif ($geom_type == 'geometrycollection') {
3549 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3552 // If we are asked for binary functions as well
3553 if ($binary) {
3554 // section seperator
3555 if ($display) {
3556 $funcs[] = array('display' => '--------');
3558 if (PMA_MYSQL_INT_VERSION < 50601) {
3559 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3560 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3561 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3562 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3563 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3564 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3565 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3566 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3567 } else {
3568 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3569 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3570 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3571 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3572 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3573 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3574 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3575 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3576 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3580 if ($display) {
3581 $funcs[] = array('display' => '--------');
3583 // Minimum bounding rectangle functions
3584 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3585 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3586 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3587 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3588 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3589 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3590 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3592 return $funcs;
3596 * Creates a dropdown box with MySQL functions for a particular column.
3598 * @param array $field Data about the column for which
3599 * to generate the dropdown
3600 * @param bool $insert_mode Whether the operation is 'insert'
3602 * @global array $cfg PMA configuration
3603 * @global array $analyzed_sql Analyzed SQL query
3604 * @global mixed $data (null/string) FIXME: what is this for?
3606 * @return string An HTML snippet of a dropdown list with function
3607 * names appropriate for the requested column.
3609 function PMA_getFunctionsForField($field, $insert_mode)
3611 global $cfg, $analyzed_sql, $data;
3613 $selected = '';
3614 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3615 // or something similar. Then directly look up the entry in the
3616 // RestrictFunctions array, which'll then reveal the available dropdown options
3617 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3618 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3620 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3621 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3622 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3623 } else {
3624 $dropdown = array();
3625 $default_function = '';
3627 $dropdown_built = array();
3628 $op_spacing_needed = false;
3629 // what function defined as default?
3630 // for the first timestamp we don't set the default function
3631 // if there is a default value for the timestamp
3632 // (not including CURRENT_TIMESTAMP)
3633 // and the column does not have the
3634 // ON UPDATE DEFAULT TIMESTAMP attribute.
3635 if ($field['True_Type'] == 'timestamp'
3636 && empty($field['Default'])
3637 && empty($data)
3638 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3640 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3642 // For primary keys of type char(36) or varchar(36) UUID if the default function
3643 // Only applies to insert mode, as it would silently trash data on updates.
3644 if ($insert_mode
3645 && $field['Key'] == 'PRI'
3646 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3648 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3650 // this is set only when appropriate and is always true
3651 if (isset($field['display_binary_as_hex'])) {
3652 $default_function = 'UNHEX';
3655 // Create the output
3656 $retval = ' <option></option>' . "\n";
3657 // loop on the dropdown array and print all available options for that field.
3658 foreach ($dropdown as $each_dropdown) {
3659 $retval .= ' ';
3660 $retval .= '<option';
3661 if ($default_function === $each_dropdown) {
3662 $retval .= ' selected="selected"';
3664 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3665 $dropdown_built[$each_dropdown] = 'true';
3666 $op_spacing_needed = true;
3668 // For compatibility's sake, do not let out all other functions. Instead
3669 // print a separator (blank) and then show ALL functions which weren't shown
3670 // yet.
3671 $cnt_functions = count($cfg['Functions']);
3672 for ($j = 0; $j < $cnt_functions; $j++) {
3673 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3674 || $dropdown_built[$cfg['Functions'][$j]] != 'true'
3676 // Is current function defined as default?
3677 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3678 || (! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3679 ? ' selected="selected"'
3680 : '';
3681 if ($op_spacing_needed == true) {
3682 $retval .= ' ';
3683 $retval .= '<option value="">--------</option>' . "\n";
3684 $op_spacing_needed = false;
3687 $retval .= ' ';
3688 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3689 . '</option>' . "\n";
3691 } // end for
3693 return $retval;
3694 } // end PMA_getFunctionsForField()
3697 * Checks if the current user has a specific privilege and returns true if the
3698 * user indeed has that privilege or false if (s)he doesn't. This function must
3699 * only be used for features that are available since MySQL 5, because it
3700 * relies on the INFORMATION_SCHEMA database to be present.
3702 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3703 * // Checks if the currently logged in user has the global
3704 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3705 * // user has this privilege on database 'mydb'.
3707 * @param string $priv The privilege to check
3708 * @param mixed $db null, to only check global privileges
3709 * string, db name where to also check for privileges
3710 * @param mixed $tbl null, to only check global privileges
3711 * string, db name where to also check for privileges
3713 * @return bool
3715 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3717 // Get the username for the current user in the format
3718 // required to use in the information schema database.
3719 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3720 if ($user === false) {
3721 return false;
3723 $user = explode('@', $user);
3724 $username = "''";
3725 $username .= str_replace("'", "''", $user[0]);
3726 $username .= "''@''";
3727 $username .= str_replace("'", "''", $user[1]);
3728 $username .= "''";
3729 // Prepage the query
3730 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3731 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3732 // Check global privileges first.
3733 if (PMA_DBI_fetch_value(
3734 sprintf(
3735 $query,
3736 'USER_PRIVILEGES',
3737 $username,
3738 $priv
3742 return true;
3744 // If a database name was provided and user does not have the
3745 // required global privilege, try database-wise permissions.
3746 if ($db !== null) {
3747 $query .= " AND TABLE_SCHEMA='%s'";
3748 if (PMA_DBI_fetch_value(
3749 sprintf(
3750 $query,
3751 'SCHEMA_PRIVILEGES',
3752 $username,
3753 $priv,
3754 PMA_sqlAddSlashes($db)
3758 return true;
3760 } else {
3761 // There was no database name provided and the user
3762 // does not have the correct global privilege.
3763 return false;
3765 // If a table name was also provided and we still didn't
3766 // find any valid privileges, try table-wise privileges.
3767 if ($tbl !== null) {
3768 $query .= " AND TABLE_NAME='%s'";
3769 if ($retval = PMA_DBI_fetch_value(
3770 sprintf(
3771 $query,
3772 'TABLE_PRIVILEGES',
3773 $username,
3774 $priv,
3775 PMA_sqlAddSlashes($db),
3776 PMA_sqlAddSlashes($tbl)
3780 return true;
3783 // If we reached this point, the user does not
3784 // have even valid table-wise privileges.
3785 return false;
3789 * Returns server type for current connection
3791 * Known types are: Drizzle, MariaDB and MySQL (default)
3793 * @return string
3795 function PMA_getServerType()
3797 $server_type = 'MySQL';
3798 if (PMA_DRIZZLE) {
3799 $server_type = 'Drizzle';
3800 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3801 $server_type = 'MariaDB';
3802 } else if (stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3803 $server_type = 'Percona Server';
3805 return $server_type;
3809 * Analyzes the limit clause and return the start and length attributes of it.
3811 * @param string $limit_clause limit clause
3813 * @return array Start and length attributes of the limit clause
3815 function PMA_analyzeLimitClause($limit_clause)
3817 $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
3818 return array(
3819 'start' => trim($start_and_length[0]),
3820 'length' => trim($start_and_length[1])
3825 * Outputs HTML code for print button.
3827 * @return nothing
3829 function PMA_printButton()
3831 echo '<p class="print_ignore">';
3832 echo '<input type="button" id="print" value="' . __('Print') . '" />';
3833 echo '</p>';