Update .po files
[phpmyadmin.git] / libraries / common.lib.php
blobcd56d03f492ad3f9d83483ebda4d6b5eec9d94a9
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'
832 // switch tooltip and name
833 $table['disp_name'] = $table['Comment'];
834 $table['Comment'] = $table['Name'];
835 } else {
836 $table['disp_name'] = $table['Name'];
839 $group[$table_name] = array_merge($default, $table);
842 return $table_groups;
845 /* ----------------------- Set of misc functions ----------------------- */
849 * Adds backquotes on both sides of a database, table or field name.
850 * and escapes backquotes inside the name with another backquote
852 * example:
853 * <code>
854 * echo PMA_backquote('owner`s db'); // `owner``s db`
856 * </code>
858 * @param mixed $a_name the database, table or field name to "backquote"
859 * or array of it
860 * @param boolean $do_it a flag to bypass this function (used by dump
861 * functions)
863 * @return mixed the "backquoted" database, table or field name
865 * @access public
867 function PMA_backquote($a_name, $do_it = true)
869 if (is_array($a_name)) {
870 foreach ($a_name as &$data) {
871 $data = PMA_backquote($data, $do_it);
873 return $a_name;
876 if (! $do_it) {
877 global $PMA_SQPdata_forbidden_word;
879 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
880 return $a_name;
884 // '0' is also empty for php :-(
885 if (strlen($a_name) && $a_name !== '*') {
886 return '`' . str_replace('`', '``', $a_name) . '`';
887 } else {
888 return $a_name;
890 } // end of the 'PMA_backquote()' function
893 * Defines the <CR><LF> value depending on the user OS.
895 * @return string the <CR><LF> value to use
897 * @access public
899 function PMA_whichCrlf()
901 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
902 // Win case
903 if (PMA_USR_OS == 'Win') {
904 $the_crlf = "\r\n";
905 } else {
906 // Others
907 $the_crlf = "\n";
910 return $the_crlf;
911 } // end of the 'PMA_whichCrlf()' function
914 * Reloads navigation if needed.
916 * @param bool $jsonly prints out pure JavaScript
918 * @access public
920 function PMA_reloadNavigation($jsonly=false)
922 // Reloads the navigation frame via JavaScript if required
923 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
924 // one of the reasons for a reload is when a table is dropped
925 // in this case, get rid of the table limit offset, otherwise
926 // we have a problem when dropping a table on the last page
927 // and the offset becomes greater than the total number of tables
928 unset($_SESSION['tmp_user_values']['table_limit_offset']);
929 echo "\n";
930 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
931 if (!$jsonly) {
932 echo '<script type="text/javascript">' . PHP_EOL;
935 //<![CDATA[
936 if (typeof(window.parent) != 'undefined'
937 && typeof(window.parent.frame_navigation) != 'undefined'
938 && window.parent.goTo) {
939 window.parent.goTo('<?php echo $reload_url; ?>');
941 //]]>
942 <?php
943 if (!$jsonly) {
944 echo '</script>' . PHP_EOL;
947 unset($GLOBALS['reload']);
952 * displays the message and the query
953 * usually the message is the result of the query executed
955 * @param string $message the message to display
956 * @param string $sql_query the query to display
957 * @param string $type the type (level) of the message
958 * @param boolean $is_view is this a message after a VIEW operation?
960 * @return string
962 * @access public
964 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
967 * PMA_ajaxResponse uses this function to collect the string of HTML generated
968 * for showing the message. Use output buffering to collect it and return it
969 * in a string. In some special cases on sql.php, buffering has to be disabled
970 * and hence we check with $GLOBALS['buffer_message']
972 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
973 ob_start();
975 global $cfg;
977 if (null === $sql_query) {
978 if (! empty($GLOBALS['display_query'])) {
979 $sql_query = $GLOBALS['display_query'];
980 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
981 $sql_query = $GLOBALS['unparsed_sql'];
982 } elseif (! empty($GLOBALS['sql_query'])) {
983 $sql_query = $GLOBALS['sql_query'];
984 } else {
985 $sql_query = '';
989 if (isset($GLOBALS['using_bookmark_message'])) {
990 $GLOBALS['using_bookmark_message']->display();
991 unset($GLOBALS['using_bookmark_message']);
994 // Corrects the tooltip text via JS if required
995 // @todo this is REALLY the wrong place to do this - very unexpected here
996 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
997 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
998 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
999 echo "\n";
1000 echo '<script type="text/javascript">' . "\n";
1001 echo '//<![CDATA[' . "\n";
1002 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
1003 . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1004 echo '//]]>' . "\n";
1005 echo '</script>' . "\n";
1006 } // end if ... elseif
1008 // Checks if the table needs to be repaired after a TRUNCATE query.
1009 // @todo what about $GLOBALS['display_query']???
1010 // @todo this is REALLY the wrong place to do this - very unexpected here
1011 if (strlen($GLOBALS['table'])
1012 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
1014 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
1015 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1018 unset($tbl_status);
1020 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1021 // check for it's presence before using it
1022 echo '<div id="result_query" align="'
1023 . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' )
1024 . '">' . "\n";
1026 if ($message instanceof PMA_Message) {
1027 if (isset($GLOBALS['special_message'])) {
1028 $message->addMessage($GLOBALS['special_message']);
1029 unset($GLOBALS['special_message']);
1031 $message->display();
1032 $type = $message->getLevel();
1033 } else {
1034 echo '<div class="' . $type . '">';
1035 echo PMA_sanitize($message);
1036 if (isset($GLOBALS['special_message'])) {
1037 echo PMA_sanitize($GLOBALS['special_message']);
1038 unset($GLOBALS['special_message']);
1040 echo '</div>';
1043 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1044 // Html format the query to be displayed
1045 // If we want to show some sql code it is easiest to create it here
1046 /* SQL-Parser-Analyzer */
1048 if (! empty($GLOBALS['show_as_php'])) {
1049 $new_line = '\\n"<br />' . "\n"
1050 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1051 $query_base = htmlspecialchars(addslashes($sql_query));
1052 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1053 } else {
1054 $query_base = $sql_query;
1057 $query_too_big = false;
1059 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1060 // when the query is large (for example an INSERT of binary
1061 // data), the parser chokes; so avoid parsing the query
1062 $query_too_big = true;
1063 $shortened_query_base = nl2br(
1064 htmlspecialchars(
1065 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
1068 } elseif (! empty($GLOBALS['parsed_sql'])
1069 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1070 // (here, use "! empty" because when deleting a bookmark,
1071 // $GLOBALS['parsed_sql'] is set but empty
1072 $parsed_sql = $GLOBALS['parsed_sql'];
1073 } else {
1074 // Parse SQL if needed
1075 $parsed_sql = PMA_SQP_parse($query_base);
1078 // Analyze it
1079 if (isset($parsed_sql) && ! PMA_SQP_isError()) {
1080 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1082 // Same as below (append LIMIT), append the remembered ORDER BY
1083 if ($GLOBALS['cfg']['RememberSorting']
1084 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1085 && isset($GLOBALS['sql_order_to_append'])
1087 $query_base = $analyzed_display_query[0]['section_before_limit']
1088 . "\n" . $GLOBALS['sql_order_to_append']
1089 . $analyzed_display_query[0]['section_after_limit'];
1091 // Need to reparse query
1092 $parsed_sql = PMA_SQP_parse($query_base);
1093 // update the $analyzed_display_query
1094 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1095 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1098 // Here we append the LIMIT added for navigation, to
1099 // enable its display. Adding it higher in the code
1100 // to $sql_query would create a problem when
1101 // using the Refresh or Edit links.
1103 // Only append it on SELECTs.
1106 * @todo what would be the best to do when someone hits Refresh:
1107 * use the current LIMITs ?
1110 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1111 && isset($GLOBALS['sql_limit_to_append'])
1113 $query_base = $analyzed_display_query[0]['section_before_limit']
1114 . "\n" . $GLOBALS['sql_limit_to_append']
1115 . $analyzed_display_query[0]['section_after_limit'];
1116 // Need to reparse query
1117 $parsed_sql = PMA_SQP_parse($query_base);
1121 if (! empty($GLOBALS['show_as_php'])) {
1122 $query_base = '$sql = "' . $query_base;
1123 } elseif (! empty($GLOBALS['validatequery'])) {
1124 try {
1125 $query_base = PMA_validateSQL($query_base);
1126 } catch (Exception $e) {
1127 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1129 } elseif (isset($parsed_sql)) {
1130 $query_base = PMA_formatSql($parsed_sql, $query_base);
1133 // Prepares links that may be displayed to edit/explain the query
1134 // (don't go to default pages, we must go to the page
1135 // where the query box is available)
1137 // Basic url query part
1138 $url_params = array();
1139 if (! isset($GLOBALS['db'])) {
1140 $GLOBALS['db'] = '';
1142 if (strlen($GLOBALS['db'])) {
1143 $url_params['db'] = $GLOBALS['db'];
1144 if (strlen($GLOBALS['table'])) {
1145 $url_params['table'] = $GLOBALS['table'];
1146 $edit_link = 'tbl_sql.php';
1147 } else {
1148 $edit_link = 'db_sql.php';
1150 } else {
1151 $edit_link = 'server_sql.php';
1154 // Want to have the query explained
1155 // but only explain a SELECT (that has not been explained)
1156 /* SQL-Parser-Analyzer */
1157 $explain_link = '';
1158 $is_select = false;
1159 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1160 $explain_params = $url_params;
1161 // Detect if we are validating as well
1162 // To preserve the validate uRL data
1163 if (! empty($GLOBALS['validatequery'])) {
1164 $explain_params['validatequery'] = 1;
1166 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1167 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1168 $_message = __('Explain SQL');
1169 $is_select = true;
1170 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1171 $explain_params['sql_query'] = substr($sql_query, 8);
1172 $_message = __('Skip Explain SQL');
1174 if (isset($explain_params['sql_query'])) {
1175 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1176 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1178 } //show explain
1180 $url_params['sql_query'] = $sql_query;
1181 $url_params['show_query'] = 1;
1183 // even if the query is big and was truncated, offer the chance
1184 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1185 if (! empty($cfg['SQLQuery']['Edit'])) {
1186 if ($cfg['EditInWindow'] == true) {
1187 $onclick = 'window.parent.focus_querywindow(\''
1188 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1189 } else {
1190 $onclick = '';
1193 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1194 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1195 } else {
1196 $edit_link = '';
1199 $url_qpart = PMA_generate_common_url($url_params);
1201 // Also we would like to get the SQL formed in some nice
1202 // php-code
1203 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1204 $php_params = $url_params;
1206 if (! empty($GLOBALS['show_as_php'])) {
1207 $_message = __('Without PHP Code');
1208 } else {
1209 $php_params['show_as_php'] = 1;
1210 $_message = __('Create PHP Code');
1213 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1214 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1216 if (isset($GLOBALS['show_as_php'])) {
1217 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1218 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1220 } else {
1221 $php_link = '';
1222 } //show as php
1224 // Refresh query
1225 if (! empty($cfg['SQLQuery']['Refresh'])
1226 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1227 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1229 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1230 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1231 } else {
1232 $refresh_link = '';
1233 } //refresh
1235 if (! empty($cfg['SQLValidator']['use'])
1236 && ! empty($cfg['SQLQuery']['Validate'])
1238 $validate_params = $url_params;
1239 if (!empty($GLOBALS['validatequery'])) {
1240 $validate_message = __('Skip Validate SQL');
1241 } else {
1242 $validate_params['validatequery'] = 1;
1243 $validate_message = __('Validate SQL');
1246 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1247 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1248 } else {
1249 $validate_link = '';
1250 } //validator
1252 if (!empty($GLOBALS['validatequery'])) {
1253 echo '<div class="sqlvalidate">';
1254 } else {
1255 echo '<code class="sql">';
1257 if ($query_too_big) {
1258 echo $shortened_query_base;
1259 } else {
1260 echo $query_base;
1263 //Clean up the end of the PHP
1264 if (! empty($GLOBALS['show_as_php'])) {
1265 echo '";';
1267 if (!empty($GLOBALS['validatequery'])) {
1268 echo '</div>';
1269 } else {
1270 echo '</code>';
1273 echo '<div class="tools">';
1274 // avoid displaying a Profiling checkbox that could
1275 // be checked, which would reexecute an INSERT, for example
1276 if (! empty($refresh_link)) {
1277 PMA_profilingCheckbox($sql_query);
1279 // if needed, generate an invisible form that contains controls for the
1280 // Inline link; this way, the behavior of the Inline link does not
1281 // depend on the profiling support or on the refresh link
1282 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1283 echo '<form action="sql.php" method="post">';
1284 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1285 echo '<input type="hidden" name="sql_query" value="'
1286 . htmlspecialchars($sql_query) . '" />';
1287 echo '</form>';
1290 // in the tools div, only display the Inline link when not in ajax
1291 // mode because 1) it currently does not work and 2) we would
1292 // have two similar mechanisms on the page for the same goal
1293 if ($is_select
1294 || $GLOBALS['is_ajax_request'] === false
1295 && ! $query_too_big
1297 // see in js/functions.js the jQuery code attached to id inline_edit
1298 // document.write conflicts with jQuery, hence used $().append()
1299 echo "<script type=\"text/javascript\">\n" .
1300 "//<![CDATA[\n" .
1301 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1302 PMA_escapeJsString(__('Inline edit of this query')) .
1303 "\" class=\"inline_edit_sql\">" .
1304 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1305 "</a>]');\n" .
1306 "//]]>\n" .
1307 "</script>";
1309 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1310 echo '</div>';
1312 echo '</div>';
1313 if ($GLOBALS['is_ajax_request'] === false) {
1314 echo '<br class="clearfloat" />';
1317 // If we are in an Ajax request, we have most probably been called in
1318 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1319 // to PMA_ajaxResponse(), which will encode it for JSON.
1320 if ($GLOBALS['is_ajax_request'] == true
1321 && ! isset($GLOBALS['buffer_message'])
1323 $buffer_contents = ob_get_contents();
1324 ob_end_clean();
1325 return $buffer_contents;
1327 return null;
1328 } // end of the 'PMA_showMessage()' function
1331 * Verifies if current MySQL server supports profiling
1333 * @access public
1335 * @return boolean whether profiling is supported
1337 function PMA_profilingSupported()
1339 if (! PMA_cacheExists('profiling_supported', true)) {
1340 // 5.0.37 has profiling but for example, 5.1.20 does not
1341 // (avoid a trip to the server for MySQL before 5.0.37)
1342 // and do not set a constant as we might be switching servers
1343 if (defined('PMA_MYSQL_INT_VERSION')
1344 && PMA_MYSQL_INT_VERSION >= 50037
1345 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1347 PMA_cacheSet('profiling_supported', true, true);
1348 } else {
1349 PMA_cacheSet('profiling_supported', false, true);
1353 return PMA_cacheGet('profiling_supported', true);
1357 * Displays a form with the Profiling checkbox
1359 * @param string $sql_query sql query
1361 * @access public
1363 function PMA_profilingCheckbox($sql_query)
1365 if (PMA_profilingSupported()) {
1366 echo '<form action="sql.php" method="post">' . "\n";
1367 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1368 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1369 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1370 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1371 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1372 echo '</form>' . "\n";
1377 * Formats $value to byte view
1379 * @param double $value the value to format
1380 * @param int $limes the sensitiveness
1381 * @param int $comma the number of decimals to retain
1383 * @return array the formatted value and its unit
1385 * @access public
1387 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1389 if ($value === null) {
1390 return null;
1393 $byteUnits = array(
1394 /* l10n: shortcuts for Byte */
1395 __('B'),
1396 /* l10n: shortcuts for Kilobyte */
1397 __('KiB'),
1398 /* l10n: shortcuts for Megabyte */
1399 __('MiB'),
1400 /* l10n: shortcuts for Gigabyte */
1401 __('GiB'),
1402 /* l10n: shortcuts for Terabyte */
1403 __('TiB'),
1404 /* l10n: shortcuts for Petabyte */
1405 __('PiB'),
1406 /* l10n: shortcuts for Exabyte */
1407 __('EiB')
1410 $dh = PMA_pow(10, $comma);
1411 $li = PMA_pow(10, $limes);
1412 $unit = $byteUnits[0];
1414 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1415 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1416 // use 1024.0 to avoid integer overflow on 64-bit machines
1417 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1418 $unit = $byteUnits[$d];
1419 break 1;
1420 } // end if
1421 } // end for
1423 if ($unit != $byteUnits[0]) {
1424 // if the unit is not bytes (as represented in current language)
1425 // reformat with max length of 5
1426 // 4th parameter=true means do not reformat if value < 1
1427 $return_value = PMA_formatNumber($value, 5, $comma, true);
1428 } else {
1429 // do not reformat, just handle the locale
1430 $return_value = PMA_formatNumber($value, 0);
1433 return array(trim($return_value), $unit);
1434 } // end of the 'PMA_formatByteDown' function
1437 * Changes thousands and decimal separators to locale specific values.
1439 * @param string $value the value
1441 * @return string
1443 function PMA_localizeNumber($value)
1445 return str_replace(
1446 array(',', '.'),
1447 array(
1448 /* l10n: Thousands separator */
1449 __(','),
1450 /* l10n: Decimal separator */
1451 __('.'),
1453 $value
1458 * Formats $value to the given length and appends SI prefixes
1459 * with a $length of 0 no truncation occurs, number is only formated
1460 * to the current locale
1462 * examples:
1463 * <code>
1464 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1465 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1466 * echo PMA_formatNumber(-0.003, 6); // -3 m
1467 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1468 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1469 * echo PMA_formatNumber(0, 6); // 0
1470 * </code>
1472 * @param double $value the value to format
1473 * @param integer $digits_left number of digits left of the comma
1474 * @param integer $digits_right number of digits right of the comma
1475 * @param boolean $only_down do not reformat numbers below 1
1476 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1477 * (default: true)
1479 * @return string the formatted value and its unit
1481 * @access public
1483 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1484 $only_down = false, $noTrailingZero = true)
1486 if ($value==0) {
1487 return '0';
1490 $originalValue = $value;
1491 //number_format is not multibyte safe, str_replace is safe
1492 if ($digits_left === 0) {
1493 $value = number_format($value, $digits_right);
1494 if ($originalValue != 0 && floatval($value) == 0) {
1495 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1498 return PMA_localizeNumber($value);
1501 // this units needs no translation, ISO
1502 $units = array(
1503 -8 => 'y',
1504 -7 => 'z',
1505 -6 => 'a',
1506 -5 => 'f',
1507 -4 => 'p',
1508 -3 => 'n',
1509 -2 => '&micro;',
1510 -1 => 'm',
1511 0 => ' ',
1512 1 => 'k',
1513 2 => 'M',
1514 3 => 'G',
1515 4 => 'T',
1516 5 => 'P',
1517 6 => 'E',
1518 7 => 'Z',
1519 8 => 'Y'
1522 // check for negative value to retain sign
1523 if ($value < 0) {
1524 $sign = '-';
1525 $value = abs($value);
1526 } else {
1527 $sign = '';
1530 $dh = PMA_pow(10, $digits_right);
1533 * This gives us the right SI prefix already,
1534 * but $digits_left parameter not incorporated
1536 $d = floor(log10($value) / 3);
1538 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1539 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1540 * to use, then lower the SI prefix
1542 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1543 if ($digits_left > $cur_digits) {
1544 $d-= floor(($digits_left - $cur_digits)/3);
1547 if ($d<0 && $only_down) {
1548 $d=0;
1551 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1552 $unit = $units[$d];
1554 // If we dont want any zeros after the comma just add the thousand seperator
1555 if ($noTrailingZero) {
1556 $value = PMA_localizeNumber(
1557 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1559 } else {
1560 //number_format is not multibyte safe, str_replace is safe
1561 $value = PMA_localizeNumber(number_format($value, $digits_right));
1564 if ($originalValue!=0 && floatval($value) == 0) {
1565 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1568 return $sign . $value . ' ' . $unit;
1569 } // end of the 'PMA_formatNumber' function
1572 * Returns the number of bytes when a formatted size is given
1574 * @param string $formatted_size the size expression (for example 8MB)
1576 * @return integer The numerical part of the expression (for example 8)
1578 function PMA_extractValueFromFormattedSize($formatted_size)
1580 $return_value = -1;
1582 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1583 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1584 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1585 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1586 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1587 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1589 return $return_value;
1590 }// end of the 'PMA_extractValueFromFormattedSize' function
1593 * Writes localised date
1595 * @param string $timestamp the current timestamp
1596 * @param string $format format
1598 * @return string the formatted date
1600 * @access public
1602 function PMA_localisedDate($timestamp = -1, $format = '')
1604 $month = array(
1605 /* l10n: Short month name */
1606 __('Jan'),
1607 /* l10n: Short month name */
1608 __('Feb'),
1609 /* l10n: Short month name */
1610 __('Mar'),
1611 /* l10n: Short month name */
1612 __('Apr'),
1613 /* l10n: Short month name */
1614 _pgettext('Short month name', 'May'),
1615 /* l10n: Short month name */
1616 __('Jun'),
1617 /* l10n: Short month name */
1618 __('Jul'),
1619 /* l10n: Short month name */
1620 __('Aug'),
1621 /* l10n: Short month name */
1622 __('Sep'),
1623 /* l10n: Short month name */
1624 __('Oct'),
1625 /* l10n: Short month name */
1626 __('Nov'),
1627 /* l10n: Short month name */
1628 __('Dec'));
1629 $day_of_week = array(
1630 /* l10n: Short week day name */
1631 _pgettext('Short week day name', 'Sun'),
1632 /* l10n: Short week day name */
1633 __('Mon'),
1634 /* l10n: Short week day name */
1635 __('Tue'),
1636 /* l10n: Short week day name */
1637 __('Wed'),
1638 /* l10n: Short week day name */
1639 __('Thu'),
1640 /* l10n: Short week day name */
1641 __('Fri'),
1642 /* l10n: Short week day name */
1643 __('Sat'));
1645 if ($format == '') {
1646 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1647 $format = __('%B %d, %Y at %I:%M %p');
1650 if ($timestamp == -1) {
1651 $timestamp = time();
1654 $date = preg_replace(
1655 '@%[aA]@',
1656 $day_of_week[(int)strftime('%w', $timestamp)],
1657 $format
1659 $date = preg_replace(
1660 '@%[bB]@',
1661 $month[(int)strftime('%m', $timestamp)-1],
1662 $date
1665 return strftime($date, $timestamp);
1666 } // end of the 'PMA_localisedDate()' function
1670 * returns a tab for tabbed navigation.
1671 * If the variables $link and $args ar left empty, an inactive tab is created
1673 * @param array $tab array with all options
1674 * @param array $url_params
1676 * @return string html code for one tab, a link if valid otherwise a span
1678 * @access public
1680 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1682 // default values
1683 $defaults = array(
1684 'text' => '',
1685 'class' => '',
1686 'active' => null,
1687 'link' => '',
1688 'sep' => '?',
1689 'attr' => '',
1690 'args' => '',
1691 'warning' => '',
1692 'fragment' => '',
1693 'id' => '',
1696 $tab = array_merge($defaults, $tab);
1698 // determine additionnal style-class
1699 if (empty($tab['class'])) {
1700 if (! empty($tab['active'])
1701 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1703 $tab['class'] = 'active';
1704 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1705 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1706 && empty($tab['warning'])) {
1707 $tab['class'] = 'active';
1711 if (!empty($tab['warning'])) {
1712 $tab['class'] .= ' error';
1713 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1716 // If there are any tab specific URL parameters, merge those with
1717 // the general URL parameters
1718 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1719 $url_params = array_merge($url_params, $tab['url_params']);
1722 // build the link
1723 if (!empty($tab['link'])) {
1724 $tab['link'] = htmlentities($tab['link']);
1725 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1726 if (! empty($tab['args'])) {
1727 foreach ($tab['args'] as $param => $value) {
1728 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1729 . '=' . urlencode($value);
1734 if (! empty($tab['fragment'])) {
1735 $tab['link'] .= $tab['fragment'];
1738 // display icon, even if iconic is disabled but the link-text is missing
1739 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1740 && isset($tab['icon'])
1742 // avoid generating an alt tag, because it only illustrates
1743 // the text that follows and if browser does not display
1744 // images, the text is duplicated
1745 $tab['text'] = PMA_getImage(htmlentities($tab['icon'])) . $tab['text'];
1747 } elseif (empty($tab['text'])) {
1748 // check to not display an empty link-text
1749 $tab['text'] = '?';
1750 trigger_error(
1751 'empty linktext in function ' . __FUNCTION__ . '()',
1752 E_USER_NOTICE
1756 //Set the id for the tab, if set in the params
1757 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1758 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1760 if (!empty($tab['link'])) {
1761 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1762 .$id_string
1763 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1764 . $tab['text'] . '</a>';
1765 } else {
1766 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1767 . $tab['text'] . '</span>';
1770 $out .= '</li>';
1771 return $out;
1772 } // end of the 'PMA_generate_html_tab()' function
1775 * returns html-code for a tab navigation
1777 * @param array $tabs one element per tab
1778 * @param string $url_params
1779 * @param string $base_dir
1780 * @param string $menu_id
1782 * @return string html-code for tab-navigation
1784 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='', $menu_id='topmenu')
1786 $tab_navigation = '<div id="' . htmlentities($menu_id) . 'container" class="menucontainer">'
1787 .'<ul id="' . htmlentities($menu_id) . '">';
1789 foreach ($tabs as $tab) {
1790 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1793 $tab_navigation .=
1794 '</ul>' . "\n"
1795 .'<div class="clearfloat"></div>'
1796 .'</div>' . "\n";
1798 return $tab_navigation;
1803 * Displays a link, or a button if the link's URL is too large, to
1804 * accommodate some browsers' limitations
1806 * @param string $url the URL
1807 * @param string $message the link message
1808 * @param mixed $tag_params string: js confirmation
1809 * array: additional tag params (f.e. style="")
1810 * @param boolean $new_form we set this to false when we are already in
1811 * a form, to avoid generating nested forms
1812 * @param boolean $strip_img whether to strip the image
1813 * @param string $target target
1815 * @return string the results to be echoed or saved in an array
1817 function PMA_linkOrButton($url, $message, $tag_params = array(),
1818 $new_form = true, $strip_img = false, $target = '')
1820 $url_length = strlen($url);
1821 // with this we should be able to catch case of image upload
1822 // into a (MEDIUM) BLOB; not worth generating even a form for these
1823 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1824 return '';
1828 if (! is_array($tag_params)) {
1829 $tmp = $tag_params;
1830 $tag_params = array();
1831 if (!empty($tmp)) {
1832 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1834 unset($tmp);
1836 if (! empty($target)) {
1837 $tag_params['target'] = htmlentities($target);
1840 $tag_params_strings = array();
1841 foreach ($tag_params as $par_name => $par_value) {
1842 // htmlspecialchars() only on non javascript
1843 $par_value = substr($par_name, 0, 2) == 'on'
1844 ? $par_value
1845 : htmlspecialchars($par_value);
1846 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1849 $displayed_message = '';
1850 // Add text if not already added
1851 if (stristr($message, '<img')
1852 && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
1853 && strip_tags($message)==$message
1855 $displayed_message = '<span>'
1856 . htmlspecialchars(
1857 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1859 . '</span>';
1862 // Suhosin: Check that each query parameter is not above maximum
1863 $in_suhosin_limits = true;
1864 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1865 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1866 $query_parts = PMA_splitURLQuery($url);
1867 foreach ($query_parts as $query_pair) {
1868 list($eachvar, $eachval) = explode('=', $query_pair);
1869 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1870 $in_suhosin_limits = false;
1871 break;
1877 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1878 // no whitespace within an <a> else Safari will make it part of the link
1879 $ret = "\n" . '<a href="' . $url . '" '
1880 . implode(' ', $tag_params_strings) . '>'
1881 . $message . $displayed_message . '</a>' . "\n";
1882 } else {
1883 // no spaces (linebreaks) at all
1884 // or after the hidden fields
1885 // IE will display them all
1887 // add class=link to submit button
1888 if (empty($tag_params['class'])) {
1889 $tag_params['class'] = 'link';
1892 if (! isset($query_parts)) {
1893 $query_parts = PMA_splitURLQuery($url);
1895 $url_parts = parse_url($url);
1897 if ($new_form) {
1898 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1899 . ' method="post"' . $target . ' style="display: inline;">';
1900 $subname_open = '';
1901 $subname_close = '';
1902 $submit_link = '#';
1903 } else {
1904 $query_parts[] = 'redirect=' . $url_parts['path'];
1905 if (empty($GLOBALS['subform_counter'])) {
1906 $GLOBALS['subform_counter'] = 0;
1908 $GLOBALS['subform_counter']++;
1909 $ret = '';
1910 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1911 $subname_close = ']';
1912 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1914 foreach ($query_parts as $query_pair) {
1915 list($eachvar, $eachval) = explode('=', $query_pair);
1916 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1917 . $subname_close . '" value="'
1918 . htmlspecialchars(urldecode($eachval)) . '" />';
1919 } // end while
1921 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1922 . implode(' ', $tag_params_strings) . '>'
1923 . $message . ' ' . $displayed_message . '</a>' . "\n";
1925 if ($new_form) {
1926 $ret .= '</form>';
1928 } // end if... else...
1930 return $ret;
1931 } // end of the 'PMA_linkOrButton()' function
1935 * Splits a URL string by parameter
1937 * @param string $url the URL
1939 * @return array the parameter/value pairs, for example [0] db=sakila
1941 function PMA_splitURLQuery($url)
1943 // decode encoded url separators
1944 $separator = PMA_get_arg_separator();
1945 // on most places separator is still hard coded ...
1946 if ($separator !== '&') {
1947 // ... so always replace & with $separator
1948 $url = str_replace(htmlentities('&'), $separator, $url);
1949 $url = str_replace('&', $separator, $url);
1951 $url = str_replace(htmlentities($separator), $separator, $url);
1952 // end decode
1954 $url_parts = parse_url($url);
1955 return explode($separator, $url_parts['query']);
1959 * Returns a given timespan value in a readable format.
1961 * @param int $seconds the timespan
1963 * @return string the formatted value
1965 function PMA_timespanFormat($seconds)
1967 $days = floor($seconds / 86400);
1968 if ($days > 0) {
1969 $seconds -= $days * 86400;
1971 $hours = floor($seconds / 3600);
1972 if ($days > 0 || $hours > 0) {
1973 $seconds -= $hours * 3600;
1975 $minutes = floor($seconds / 60);
1976 if ($days > 0 || $hours > 0 || $minutes > 0) {
1977 $seconds -= $minutes * 60;
1979 return sprintf(
1980 __('%s days, %s hours, %s minutes and %s seconds'),
1981 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1986 * Takes a string and outputs each character on a line for itself. Used
1987 * mainly for horizontalflipped display mode.
1988 * Takes care of special html-characters.
1989 * Fulfills todo-item
1990 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1992 * @param string $string The string
1993 * @param string $Separator The Separator (defaults to "<br />\n")
1995 * @access public
1996 * @todo add a multibyte safe function PMA_STR_split()
1998 * @return string The flipped string
2000 function PMA_flipstring($string, $Separator = "<br />\n")
2002 $format_string = '';
2003 $charbuff = false;
2005 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
2006 $char = $string{$i};
2007 $append = false;
2009 if ($char == '&') {
2010 $format_string .= $charbuff;
2011 $charbuff = $char;
2012 } elseif ($char == ';' && !empty($charbuff)) {
2013 $format_string .= $charbuff . $char;
2014 $charbuff = false;
2015 $append = true;
2016 } elseif (! empty($charbuff)) {
2017 $charbuff .= $char;
2018 } else {
2019 $format_string .= $char;
2020 $append = true;
2023 // do not add separator after the last character
2024 if ($append && ($i != $str_len - 1)) {
2025 $format_string .= $Separator;
2029 return $format_string;
2033 * Function added to avoid path disclosures.
2034 * Called by each script that needs parameters, it displays
2035 * an error message and, by default, stops the execution.
2037 * Not sure we could use a strMissingParameter message here,
2038 * would have to check if the error message file is always available
2040 * @param array $params The names of the parameters needed by the calling script.
2041 * @param bool $die Stop the execution?
2042 * (Set this manually to false in the calling script
2043 * until you know all needed parameters to check).
2044 * @param bool $request Whether to include this list in checking for special params.
2046 * @global string path to current script
2047 * @global boolean flag whether any special variable was required
2049 * @access public
2050 * @todo use PMA_fatalError() if $die === true?
2052 function PMA_checkParameters($params, $die = true, $request = true)
2054 global $checked_special;
2056 if (! isset($checked_special)) {
2057 $checked_special = false;
2060 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2061 $found_error = false;
2062 $error_message = '';
2064 foreach ($params as $param) {
2065 if ($request && $param != 'db' && $param != 'table') {
2066 $checked_special = true;
2069 if (! isset($GLOBALS[$param])) {
2070 $error_message .= $reported_script_name
2071 . ': ' . __('Missing parameter:') . ' '
2072 . $param
2073 . PMA_showDocu('faqmissingparameters')
2074 . '<br />';
2075 $found_error = true;
2078 if ($found_error) {
2080 * display html meta tags
2082 include_once './libraries/header_meta_style.inc.php';
2083 echo '</head><body><p>' . $error_message . '</p></body></html>';
2084 if ($die) {
2085 exit();
2088 } // end function
2091 * Function to generate unique condition for specified row.
2093 * @param resource $handle current query result
2094 * @param integer $fields_cnt number of fields
2095 * @param array $fields_meta meta information about fields
2096 * @param array $row current row
2097 * @param boolean $force_unique generate condition only on pk or unique
2099 * @access public
2101 * @return array the calculated condition and whether condition is unique
2103 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2105 $primary_key = '';
2106 $unique_key = '';
2107 $nonprimary_condition = '';
2108 $preferred_condition = '';
2109 $primary_key_array = array();
2110 $unique_key_array = array();
2111 $nonprimary_condition_array = array();
2112 $condition_array = array();
2114 for ($i = 0; $i < $fields_cnt; ++$i) {
2115 $condition = '';
2116 $con_key = '';
2117 $con_val = '';
2118 $field_flags = PMA_DBI_field_flags($handle, $i);
2119 $meta = $fields_meta[$i];
2121 // do not use a column alias in a condition
2122 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2123 $meta->orgname = $meta->name;
2125 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2126 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2128 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2129 // need (string) === (string)
2130 // '' !== 0 but '' == 0
2131 if ((string) $select_expr['alias'] === (string) $meta->name) {
2132 $meta->orgname = $select_expr['column'];
2133 break;
2134 } // end if
2135 } // end foreach
2139 // Do not use a table alias in a condition.
2140 // Test case is:
2141 // select * from galerie x WHERE
2142 //(select count(*) from galerie y where y.datum=x.datum)>1
2144 // But orgtable is present only with mysqli extension so the
2145 // fix is only for mysqli.
2146 // Also, do not use the original table name if we are dealing with
2147 // a view because this view might be updatable.
2148 // (The isView() verification should not be costly in most cases
2149 // because there is some caching in the function).
2150 if (isset($meta->orgtable)
2151 && $meta->table != $meta->orgtable
2152 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2154 $meta->table = $meta->orgtable;
2157 // to fix the bug where float fields (primary or not)
2158 // can't be matched because of the imprecision of
2159 // floating comparison, use CONCAT
2160 // (also, the syntax "CONCAT(field) IS NULL"
2161 // that we need on the next "if" will work)
2162 if ($meta->type == 'real') {
2163 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2164 . PMA_backquote($meta->orgname) . ')';
2165 } else {
2166 $con_key = PMA_backquote($meta->table) . '.'
2167 . PMA_backquote($meta->orgname);
2168 } // end if... else...
2169 $condition = ' ' . $con_key . ' ';
2171 if (! isset($row[$i]) || is_null($row[$i])) {
2172 $con_val = 'IS NULL';
2173 } else {
2174 // timestamp is numeric on some MySQL 4.1
2175 // for real we use CONCAT above and it should compare to string
2176 if ($meta->numeric
2177 && $meta->type != 'timestamp'
2178 && $meta->type != 'real'
2180 $con_val = '= ' . $row[$i];
2181 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2182 // hexify only if this is a true not empty BLOB or a BINARY
2183 && stristr($field_flags, 'BINARY')
2184 && !empty($row[$i])) {
2185 // do not waste memory building a too big condition
2186 if (strlen($row[$i]) < 1000) {
2187 // use a CAST if possible, to avoid problems
2188 // if the field contains wildcard characters % or _
2189 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2190 } else {
2191 // this blob won't be part of the final condition
2192 $con_val = null;
2194 } elseif (in_array($meta->type, PMA_getGISDatatypes())
2195 && ! empty($row[$i])
2197 // do not build a too big condition
2198 if (strlen($row[$i]) < 5000) {
2199 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2200 } else {
2201 $condition = '';
2203 } elseif ($meta->type == 'bit') {
2204 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2205 } else {
2206 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2209 if ($con_val != null) {
2210 $condition .= $con_val . ' AND';
2211 if ($meta->primary_key > 0) {
2212 $primary_key .= $condition;
2213 $primary_key_array[$con_key] = $con_val;
2214 } elseif ($meta->unique_key > 0) {
2215 $unique_key .= $condition;
2216 $unique_key_array[$con_key] = $con_val;
2218 $nonprimary_condition .= $condition;
2219 $nonprimary_condition_array[$con_key] = $con_val;
2221 } // end for
2223 // Correction University of Virginia 19991216:
2224 // prefer primary or unique keys for condition,
2225 // but use conjunction of all values if no primary key
2226 $clause_is_unique = true;
2227 if ($primary_key) {
2228 $preferred_condition = $primary_key;
2229 $condition_array = $primary_key_array;
2230 } elseif ($unique_key) {
2231 $preferred_condition = $unique_key;
2232 $condition_array = $unique_key_array;
2233 } elseif (! $force_unique) {
2234 $preferred_condition = $nonprimary_condition;
2235 $condition_array = $nonprimary_condition_array;
2236 $clause_is_unique = false;
2239 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2240 return(array($where_clause, $clause_is_unique, $condition_array));
2241 } // end function
2244 * Generate a button or image tag
2246 * @param string $button_name name of button element
2247 * @param string $button_class class of button element
2248 * @param string $image_name name of image element
2249 * @param string $text text to display
2250 * @param string $image image to display
2251 * @param string $value value
2253 * @access public
2255 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2256 $image, $value = '')
2258 if ($value == '') {
2259 $value = $text;
2261 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2262 echo ' <input type="submit" name="' . $button_name . '"'
2263 .' value="' . htmlspecialchars($value) . '"'
2264 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2265 return;
2268 /* Opera has trouble with <input type="image"> */
2269 /* IE has trouble with <button> */
2270 if (PMA_USR_BROWSER_AGENT != 'IE') {
2271 echo '<button class="' . $button_class . '" type="submit"'
2272 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2273 .' title="' . htmlspecialchars($text) . '">' . "\n"
2274 . PMA_getIcon($image, $text)
2275 .'</button>' . "\n";
2276 } else {
2277 echo '<input type="image" name="' . $image_name
2278 . '" value="' . htmlspecialchars($value)
2279 . '" title="' . htmlspecialchars($text)
2280 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2281 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2282 ? '&nbsp;' . htmlspecialchars($text)
2283 : '') . "\n";
2285 } // end function
2288 * Generate a pagination selector for browsing resultsets
2290 * @param int $rows Number of rows in the pagination set
2291 * @param int $pageNow current page number
2292 * @param int $nbTotalPage number of total pages
2293 * @param int $showAll If the number of pages is lower than this
2294 * variable, no pages will be omitted in pagination
2295 * @param int $sliceStart How many rows at the beginning should always be shown?
2296 * @param int $sliceEnd How many rows at the end should always be shown?
2297 * @param int $percent Percentage of calculation page offsets to hop to a
2298 * next page
2299 * @param int $range Near the current page, how many pages should
2300 * be considered "nearby" and displayed as well?
2301 * @param string $prompt The prompt to display (sometimes empty)
2303 * @return string
2305 * @access public
2307 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2308 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2309 $range = 10, $prompt = '')
2311 $increment = floor($nbTotalPage / $percent);
2312 $pageNowMinusRange = ($pageNow - $range);
2313 $pageNowPlusRange = ($pageNow + $range);
2315 $gotopage = $prompt . ' <select id="pageselector" ';
2316 if ($GLOBALS['cfg']['AjaxEnable']) {
2317 $gotopage .= ' class="ajax"';
2319 $gotopage .= ' name="pos" >' . "\n";
2320 if ($nbTotalPage < $showAll) {
2321 $pages = range(1, $nbTotalPage);
2322 } else {
2323 $pages = array();
2325 // Always show first X pages
2326 for ($i = 1; $i <= $sliceStart; $i++) {
2327 $pages[] = $i;
2330 // Always show last X pages
2331 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2332 $pages[] = $i;
2335 // Based on the number of results we add the specified
2336 // $percent percentage to each page number,
2337 // so that we have a representing page number every now and then to
2338 // immediately jump to specific pages.
2339 // As soon as we get near our currently chosen page ($pageNow -
2340 // $range), every page number will be shown.
2341 $i = $sliceStart;
2342 $x = $nbTotalPage - $sliceEnd;
2343 $met_boundary = false;
2344 while ($i <= $x) {
2345 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2346 // If our pageselector comes near the current page, we use 1
2347 // counter increments
2348 $i++;
2349 $met_boundary = true;
2350 } else {
2351 // We add the percentage increment to our current page to
2352 // hop to the next one in range
2353 $i += $increment;
2355 // Make sure that we do not cross our boundaries.
2356 if ($i > $pageNowMinusRange && ! $met_boundary) {
2357 $i = $pageNowMinusRange;
2361 if ($i > 0 && $i <= $x) {
2362 $pages[] = $i;
2367 Add page numbers with "geometrically increasing" distances.
2369 This helps me a lot when navigating through giant tables.
2371 Test case: table with 2.28 million sets, 76190 pages. Page of interest is
2372 between 72376 and 76190.
2373 Selecting page 72376.
2374 Now, old version enumerated only +/- 10 pages around 72376 and the
2375 percentage increment produced steps of about 3000.
2377 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2378 around the current page.
2381 $i = $pageNow;
2382 $dist = 1;
2383 while ($i < $x) {
2384 $dist = 2 * $dist;
2385 $i = $pageNow + $dist;
2386 if ($i > 0 && $i <= $x) {
2387 $pages[] = $i;
2391 $i = $pageNow;
2392 $dist = 1;
2393 while ($i >0) {
2394 $dist = 2 * $dist;
2395 $i = $pageNow - $dist;
2396 if ($i > 0 && $i <= $x) {
2397 $pages[] = $i;
2401 // Since because of ellipsing of the current page some numbers may be double,
2402 // we unify our array:
2403 sort($pages);
2404 $pages = array_unique($pages);
2407 foreach ($pages as $i) {
2408 if ($i == $pageNow) {
2409 $selected = 'selected="selected" style="font-weight: bold"';
2410 } else {
2411 $selected = '';
2413 $gotopage .= ' <option ' . $selected
2414 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2417 $gotopage .= ' </select><noscript><input type="submit" value="'
2418 . __('Go') . '" /></noscript>';
2420 return $gotopage;
2421 } // end function
2425 * Generate navigation for a list
2427 * @param int $count number of elements in the list
2428 * @param int $pos current position in the list
2429 * @param array $_url_params url parameters
2430 * @param string $script script name for form target
2431 * @param string $frame target frame
2432 * @param int $max_count maximum number of elements to display from the list
2434 * @access public
2436 * @todo use $pos from $_url_params
2438 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2441 if ($max_count < $count) {
2442 echo 'frame_navigation' == $frame
2443 ? '<div id="navidbpageselector">' . "\n"
2444 : '';
2445 echo __('Page number:');
2446 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2448 // Move to the beginning or to the previous page
2449 if ($pos > 0) {
2450 // patch #474210 - part 1
2451 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2452 $caption1 = '&lt;&lt;';
2453 $caption2 = ' &lt; ';
2454 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2455 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2456 } else {
2457 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2458 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2459 $title1 = '';
2460 $title2 = '';
2461 } // end if... else...
2462 $_url_params['pos'] = 0;
2463 echo '<a' . $title1 . ' href="' . $script
2464 . PMA_generate_common_url($_url_params) . '" target="'
2465 . $frame . '">' . $caption1 . '</a>';
2466 $_url_params['pos'] = $pos - $max_count;
2467 echo '<a' . $title2 . ' href="' . $script
2468 . PMA_generate_common_url($_url_params) . '" target="'
2469 . $frame . '">' . $caption2 . '</a>';
2472 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2473 echo PMA_generate_common_hidden_inputs($_url_params);
2474 echo PMA_pageselector(
2475 $max_count,
2476 floor(($pos + 1) / $max_count) + 1,
2477 ceil($count / $max_count)
2479 echo '</form>';
2481 if ($pos + $max_count < $count) {
2482 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2483 $caption3 = ' &gt; ';
2484 $caption4 = '&gt;&gt;';
2485 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2486 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2487 } else {
2488 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2489 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2490 $title3 = '';
2491 $title4 = '';
2492 } // end if... else...
2493 $_url_params['pos'] = $pos + $max_count;
2494 echo '<a' . $title3 . ' href="' . $script
2495 . PMA_generate_common_url($_url_params) . '" target="'
2496 . $frame . '">' . $caption3 . '</a>';
2497 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2498 if ($_url_params['pos'] == $count) {
2499 $_url_params['pos'] = $count - $max_count;
2501 echo '<a' . $title4 . ' href="' . $script
2502 . PMA_generate_common_url($_url_params) . '" target="'
2503 . $frame . '">' . $caption4 . '</a>';
2505 echo "\n";
2506 if ('frame_navigation' == $frame) {
2507 echo '</div>' . "\n";
2513 * replaces %u in given path with current user name
2515 * example:
2516 * <code>
2517 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2519 * </code>
2521 * @param string $dir with wildcard for user
2523 * @return string per user directory
2525 function PMA_userDir($dir)
2527 // add trailing slash
2528 if (substr($dir, -1) != '/') {
2529 $dir .= '/';
2532 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2536 * returns html code for db link to default db page
2538 * @param string $database database
2540 * @return string html link to default db page
2542 function PMA_getDbLink($database = null)
2544 if (! strlen($database)) {
2545 if (! strlen($GLOBALS['db'])) {
2546 return '';
2548 $database = $GLOBALS['db'];
2549 } else {
2550 $database = PMA_unescape_mysql_wildcards($database);
2553 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2554 . PMA_generate_common_url($database) . '" title="'
2555 . sprintf(
2556 __('Jump to database &quot;%s&quot;.'),
2557 htmlspecialchars($database)
2559 . '">' . htmlspecialchars($database) . '</a>';
2563 * Displays a lightbulb hint explaining a known external bug
2564 * that affects a functionality
2566 * @param string $functionality localized message explaining the func.
2567 * @param string $component 'mysql' (eventually, 'php')
2568 * @param string $minimum_version of this component
2569 * @param string $bugref bug reference for this component
2571 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2573 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2574 echo PMA_showHint(
2575 sprintf(
2576 __('The %s functionality is affected by a known bug, see %s'),
2577 $functionality,
2578 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2585 * Generates and echoes an HTML checkbox
2587 * @param string $html_field_name the checkbox HTML field
2588 * @param string $label label for checkbox
2589 * @param boolean $checked is it initially checked?
2590 * @param boolean $onclick should it submit the form on click?
2592 * @return the HTML for the checkbox
2594 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2597 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2598 . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
2599 . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
2600 . $html_field_name . '">' . $label . '</label>';
2604 * Generates and echoes a set of radio HTML fields
2606 * @param string $html_field_name the radio HTML field
2607 * @param array $choices the choices values and labels
2608 * @param string $checked_choice the choice to check by default
2609 * @param boolean $line_break whether to add an HTML line break after a choice
2610 * @param boolean $escape_label whether to use htmlspecialchars() on label
2611 * @param string $class enclose each choice with a div of this class
2613 * @return the HTML for the tadio buttons
2615 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2616 $line_break = true, $escape_label = true, $class='')
2618 foreach ($choices as $choice_value => $choice_label) {
2619 if (! empty($class)) {
2620 echo '<div class="' . $class . '">';
2622 $html_field_id = $html_field_name . '_' . $choice_value;
2623 echo '<input type="radio" name="' . $html_field_name . '" id="'
2624 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2625 if ($choice_value == $checked_choice) {
2626 echo ' checked="checked"';
2628 echo ' />' . "\n";
2629 echo '<label for="' . $html_field_id . '">'
2630 . ($escape_label ? htmlspecialchars($choice_label) : $choice_label)
2631 . '</label>';
2632 if ($line_break) {
2633 echo '<br />';
2635 if (! empty($class)) {
2636 echo '</div>';
2638 echo "\n";
2643 * Generates and returns an HTML dropdown
2645 * @param string $select_name name for the select element
2646 * @param array $choices choices values
2647 * @param string $active_choice the choice to select by default
2648 * @param string $id id of the select element; can be different in case
2649 * the dropdown is present more than once on the page
2651 * @return string
2653 * @todo support titles
2655 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2657 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2658 . htmlspecialchars($id) . '">';
2659 foreach ($choices as $one_choice_value => $one_choice_label) {
2660 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2661 if ($one_choice_value == $active_choice) {
2662 $result .= ' selected="selected"';
2664 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2666 $result .= '</select>';
2667 return $result;
2671 * Generates a slider effect (jQjuery)
2672 * Takes care of generating the initial <div> and the link
2673 * controlling the slider; you have to generate the </div> yourself
2674 * after the sliding section.
2676 * @param string $id the id of the <div> on which to apply the effect
2677 * @param string $message the message to show as a link
2679 function PMA_generate_slider_effect($id, $message)
2681 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2682 echo '<div id="' . $id . '">';
2683 return;
2686 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2687 * opening the <div> with PHP itself instead of JavaScript.
2689 * @todo find a better solution that uses $.append(), the recommended method
2690 * maybe by using an additional param, the id of the div to append to
2693 <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); ?>">
2694 <?php
2698 * Creates an AJAX sliding toggle button
2699 * (or and equivalent form when AJAX is disabled)
2701 * @param string $action The URL for the request to be executed
2702 * @param string $select_name The name for the dropdown box
2703 * @param array $options An array of options (see rte_footer.lib.php)
2704 * @param string $callback A JS snippet to execute when the request is
2705 * successfully processed
2707 * @return string HTML code for the toggle button
2709 function PMA_toggleButton($action, $select_name, $options, $callback)
2711 // Do the logic first
2712 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2713 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2714 if ($options[1]['selected'] == true) {
2715 $state = 'on';
2716 } else if ($options[0]['selected'] == true) {
2717 $state = 'off';
2718 } else {
2719 $state = 'on';
2721 $selected1 = '';
2722 $selected0 = '';
2723 if ($options[1]['selected'] == true) {
2724 $selected1 = " selected='selected'";
2725 } else if ($options[0]['selected'] == true) {
2726 $selected0 = " selected='selected'";
2728 // Generate output
2729 $retval = "<!-- TOGGLE START -->\n";
2730 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2731 $retval .= "<noscript>\n";
2733 $retval .= "<div class='wrapper'>\n";
2734 $retval .= " <form action='$action' method='post'>\n";
2735 $retval .= " <select name='$select_name'>\n";
2736 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2737 $retval .= " {$options[1]['label']}\n";
2738 $retval .= " </option>\n";
2739 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2740 $retval .= " {$options[0]['label']}\n";
2741 $retval .= " </option>\n";
2742 $retval .= " </select>\n";
2743 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2744 $retval .= " </form>\n";
2745 $retval .= "</div>\n";
2746 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2747 $retval .= "</noscript>\n";
2748 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2749 $retval .= " <div class='toggleButton'>\n";
2750 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2751 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2752 $retval .= " alt='' />\n";
2753 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2754 $retval .= " <tbody>\n";
2755 $retval .= " <td class='toggleOn'>\n";
2756 $retval .= " <span class='hide'>$link_on</span>\n";
2757 $retval .= " <div>";
2758 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2759 $retval .= " </td>\n";
2760 $retval .= " <td><div>&nbsp;</div></td>\n";
2761 $retval .= " <td class='toggleOff'>\n";
2762 $retval .= " <span class='hide'>$link_off</span>\n";
2763 $retval .= " <div>";
2764 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2765 $retval .= " </div>\n";
2766 $retval .= " </tbody>\n";
2767 $retval .= " </tr></table>\n";
2768 $retval .= " <span class='hide callback'>$callback</span>\n";
2769 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2770 $retval .= " </div>\n";
2771 $retval .= " </div>\n";
2772 $retval .= "</div>\n";
2774 $retval .= "<!-- TOGGLE END -->";
2776 return $retval;
2777 } // end PMA_toggleButton()
2780 * Clears cache content which needs to be refreshed on user change.
2782 * @return nothing
2784 function PMA_clearUserCache()
2786 PMA_cacheUnset('is_superuser', true);
2790 * Verifies if something is cached in the session
2792 * @param string $var variable name
2793 * @param int|true $server server
2795 * @return boolean
2797 function PMA_cacheExists($var, $server = 0)
2799 if (true === $server) {
2800 $server = $GLOBALS['server'];
2802 return isset($_SESSION['cache']['server_' . $server][$var]);
2806 * Gets cached information from the session
2808 * @param string $var varibale name
2809 * @param int|true $server server
2811 * @return mixed
2813 function PMA_cacheGet($var, $server = 0)
2815 if (true === $server) {
2816 $server = $GLOBALS['server'];
2818 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2819 return $_SESSION['cache']['server_' . $server][$var];
2820 } else {
2821 return null;
2826 * Caches information in the session
2828 * @param string $var variable name
2829 * @param mixed $val value
2830 * @param int|true $server server
2832 * @return mixed
2834 function PMA_cacheSet($var, $val = null, $server = 0)
2836 if (true === $server) {
2837 $server = $GLOBALS['server'];
2839 $_SESSION['cache']['server_' . $server][$var] = $val;
2843 * Removes cached information from the session
2845 * @param string $var variable name
2846 * @param int|true $server server
2848 * @return nothing
2850 function PMA_cacheUnset($var, $server = 0)
2852 if (true === $server) {
2853 $server = $GLOBALS['server'];
2855 unset($_SESSION['cache']['server_' . $server][$var]);
2859 * Converts a bit value to printable format;
2860 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2861 * function because in PHP, decbin() supports only 32 bits
2863 * @param numeric $value coming from a BIT field
2864 * @param integer $length length
2866 * @return string the printable value
2868 function PMA_printable_bit_value($value, $length)
2870 $printable = '';
2871 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2872 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2874 $printable = substr($printable, -$length);
2875 return $printable;
2879 * Verifies whether the value contains a non-printable character
2881 * @param string $value value
2883 * @return boolean
2885 function PMA_contains_nonprintable_ascii($value)
2887 return preg_match('@[^[:print:]]@', $value);
2891 * Converts a BIT type default value
2892 * for example, b'010' becomes 010
2894 * @param string $bit_default_value value
2896 * @return string the converted value
2898 function PMA_convert_bit_default_value($bit_default_value)
2900 return strtr($bit_default_value, array("b" => "", "'" => ""));
2904 * Extracts the various parts from a field type spec
2906 * @param string $fieldspec Field specification
2908 * @return array associative array containing type, spec_in_brackets
2909 * and possibly enum_set_values (another array)
2911 function PMA_extractFieldSpec($fieldspec)
2913 $first_bracket_pos = strpos($fieldspec, '(');
2914 if ($first_bracket_pos) {
2915 $spec_in_brackets = chop(
2916 substr(
2917 $fieldspec,
2918 $first_bracket_pos + 1,
2919 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2922 // convert to lowercase just to be sure
2923 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2924 } else {
2925 $type = strtolower($fieldspec);
2926 $spec_in_brackets = '';
2929 if ('enum' == $type || 'set' == $type) {
2930 // Define our working vars
2931 $enum_set_values = array();
2932 $working = "";
2933 $in_string = false;
2934 $index = 0;
2936 // While there is another character to process
2937 while (isset($fieldspec[$index])) {
2938 // Grab the char to look at
2939 $char = $fieldspec[$index];
2941 // If it is a single quote, needs to be handled specially
2942 if ($char == "'") {
2943 // If we are not currently in a string, begin one
2944 if (! $in_string) {
2945 $in_string = true;
2946 $working = "";
2947 } else {
2948 // Otherwise, it may be either an end of a string,
2949 // or a 'double quote' which can be handled as-is
2950 // Check out the next character (if possible)
2951 $has_next = isset($fieldspec[$index + 1]);
2952 $next = $has_next ? $fieldspec[$index + 1] : null;
2954 //If we have reached the end of our 'working' string (because
2955 //there are no more chars,or the next char is not another quote)
2956 if (! $has_next || $next != "'") {
2957 $enum_set_values[] = $working;
2958 $in_string = false;
2960 } elseif ($next == "'") {
2961 // Otherwise, this is a 'double quote',
2962 // and can be added to the working string
2963 $working .= "'";
2964 // Skip the next char; we already know what it is
2965 $index++;
2968 } elseif ('\\' == $char
2969 && isset($fieldspec[$index + 1])
2970 && "'" == $fieldspec[$index + 1]
2972 // escaping of a quote?
2973 $working .= "'";
2974 $index++;
2975 } else {
2976 // Otherwise, add it to our working string like normal
2977 $working .= $char;
2979 // Increment character index
2980 $index++;
2981 } // end while
2982 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2983 $binary = false;
2984 $unsigned = false;
2985 $zerofill = false;
2986 } else {
2987 $enum_set_values = array();
2989 /* Create printable type name */
2990 $printtype = strtolower($fieldspec);
2992 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2993 // this would be a BINARY or VARBINARY field type;
2994 // by the way, a BLOB should not show the BINARY attribute
2995 // because this is not accepted in MySQL syntax.
2996 if (preg_match('@binary@', $printtype) && ! preg_match('@binary[\(]@', $printtype)) {
2997 $printtype = preg_replace('@binary@', '', $printtype);
2998 $binary = true;
2999 } else {
3000 $binary = false;
3002 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
3003 $zerofill = ($zerofill_cnt > 0);
3004 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
3005 $unsigned = ($unsigned_cnt > 0);
3006 $printtype = trim($printtype);
3010 $attribute = ' ';
3011 if ($binary) {
3012 $attribute = 'BINARY';
3014 if ($unsigned) {
3015 $attribute = 'UNSIGNED';
3017 if ($zerofill) {
3018 $attribute = 'UNSIGNED ZEROFILL';
3021 return array(
3022 'type' => $type,
3023 'spec_in_brackets' => $spec_in_brackets,
3024 'enum_set_values' => $enum_set_values,
3025 'print_type' => $printtype,
3026 'binary' => $binary,
3027 'unsigned' => $unsigned,
3028 'zerofill' => $zerofill,
3029 'attribute' => $attribute,
3034 * Verifies if this table's engine supports foreign keys
3036 * @param string $engine engine
3038 * @return boolean
3040 function PMA_foreignkey_supported($engine)
3042 $engine = strtoupper($engine);
3043 if ('INNODB' == $engine || 'PBXT' == $engine) {
3044 return true;
3045 } else {
3046 return false;
3051 * Replaces some characters by a displayable equivalent
3053 * @param string $content content
3055 * @return string the content with characters replaced
3057 function PMA_replace_binary_contents($content)
3059 $result = str_replace("\x00", '\0', $content);
3060 $result = str_replace("\x08", '\b', $result);
3061 $result = str_replace("\x0a", '\n', $result);
3062 $result = str_replace("\x0d", '\r', $result);
3063 $result = str_replace("\x1a", '\Z', $result);
3064 return $result;
3068 * Converts GIS data to Well Known Text format
3070 * @param binary $data GIS data
3071 * @param bool $includeSRID Add SRID to the WKT
3073 * @return GIS data in Well Know Text format
3075 function PMA_asWKT($data, $includeSRID = false)
3077 // Convert to WKT format
3078 $hex = bin2hex($data);
3079 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3080 if ($includeSRID) {
3081 $wktsql .= ", SRID(x'" . $hex . "')";
3083 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
3084 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
3085 $wktval = $wktarr[0];
3086 if ($includeSRID) {
3087 $srid = $wktarr[1];
3088 $wktval = "'" . $wktval . "'," . $srid;
3090 @PMA_DBI_free_result($wktresult);
3091 return $wktval;
3095 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3097 * @param string $string string
3099 * @return string with the chars replaced
3102 function PMA_duplicateFirstNewline($string)
3104 $first_occurence = strpos($string, "\r\n");
3105 if ($first_occurence === 0) {
3106 $string = "\n".$string;
3108 return $string;
3112 * Get the action word corresponding to a script name
3113 * in order to display it as a title in navigation panel
3115 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3116 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3118 * @return array
3120 function PMA_getTitleForTarget($target)
3122 $mapping = array(
3123 // Values for $cfg['DefaultTabTable']
3124 'tbl_structure.php' => __('Structure'),
3125 'tbl_sql.php' => __('SQL'),
3126 'tbl_select.php' =>__('Search'),
3127 'tbl_change.php' =>__('Insert'),
3128 'sql.php' => __('Browse'),
3130 // Values for $cfg['DefaultTabDatabase']
3131 'db_structure.php' => __('Structure'),
3132 'db_sql.php' => __('SQL'),
3133 'db_search.php' => __('Search'),
3134 'db_operations.php' => __('Operations'),
3136 return $mapping[$target];
3140 * Formats user string, expanding @VARIABLES@, accepting strftime format string.
3142 * @param string $string Text where to do expansion.
3143 * @param function $escape Function to call for escaping variable values.
3144 * @param array $updates Array with overrides for default parameters
3145 * (obtained from GLOBALS).
3147 * @return string
3149 function PMA_expandUserString($string, $escape = null, $updates = array())
3151 /* Content */
3152 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
3153 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3154 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3155 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3156 ? $GLOBALS['cfg']['Server']['verbose']
3157 : $GLOBALS['cfg']['Server']['host'];
3158 $vars['database'] = $GLOBALS['db'];
3159 $vars['table'] = $GLOBALS['table'];
3160 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3162 /* Update forced variables */
3163 foreach ($updates as $key => $val) {
3164 $vars[$key] = $val;
3167 /* Replacement mapping */
3169 * The __VAR__ ones are for backward compatibility, because user
3170 * might still have it in cookies.
3172 $replace = array(
3173 '@HTTP_HOST@' => $vars['http_host'],
3174 '@SERVER@' => $vars['server_name'],
3175 '__SERVER__' => $vars['server_name'],
3176 '@VERBOSE@' => $vars['server_verbose'],
3177 '@VSERVER@' => $vars['server_verbose_or_name'],
3178 '@DATABASE@' => $vars['database'],
3179 '__DB__' => $vars['database'],
3180 '@TABLE@' => $vars['table'],
3181 '__TABLE__' => $vars['table'],
3182 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3185 /* Optional escaping */
3186 if (!is_null($escape)) {
3187 foreach ($replace as $key => $val) {
3188 $replace[$key] = $escape($val);
3192 /* Backward compatibility in 3.5.x */
3193 if (strpos($string, '@FIELDS@') !== false) {
3194 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3197 /* Fetch columns list if required */
3198 if (strpos($string, '@COLUMNS@') !== false) {
3199 $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3201 $column_names = array();
3202 foreach ($columns_list as $column) {
3203 if (! is_null($escape)) {
3204 $column_names[] = $escape($column['Field']);
3205 } else {
3206 $column_names[] = $field['Field'];
3210 $replace['@COLUMNS@'] = implode(',', $column_names);
3213 /* Do the replacement */
3214 return strtr(strftime($string), $replace);
3218 * function that generates a json output for an ajax request and ends script
3219 * execution
3221 * @param PMA_Message|string $message message string containing the
3222 * html of the message
3223 * @param bool $success success whether the ajax request
3224 * was successfull
3225 * @param array $extra_data extra data optional -
3226 * any other data as part of the json request
3228 * @return nothing
3230 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3232 $response = array();
3233 if ( $success == true ) {
3234 $response['success'] = true;
3235 if ($message instanceof PMA_Message) {
3236 $response['message'] = $message->getDisplay();
3237 } else {
3238 $response['message'] = $message;
3240 } else {
3241 $response['success'] = false;
3242 if ($message instanceof PMA_Message) {
3243 $response['error'] = $message->getDisplay();
3244 } else {
3245 $response['error'] = $message;
3249 // If extra_data has been provided, append it to the response array
3250 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3251 $response = array_merge($response, $extra_data);
3254 // Set the Content-Type header to JSON so that jQuery parses the
3255 // response correctly.
3257 // At this point, other headers might have been sent;
3258 // even if $GLOBALS['is_header_sent'] is true,
3259 // we have to send these additional headers.
3260 header('Cache-Control: no-cache');
3261 header("Content-Type: application/json");
3263 echo json_encode($response);
3265 if (!defined('TESTSUITE'))
3266 exit;
3270 * Display the form used to browse anywhere on the local server for a file to import
3272 * @param string $max_upload_size maximum upload size
3274 * @return nothing
3276 function PMA_browseUploadFile($max_upload_size)
3278 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3279 echo '<div id="upload_form_status" style="display: none;"></div>';
3280 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3281 echo '<input type="file" name="import_file" id="input_import_file" />';
3282 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3283 // some browsers should respect this :)
3284 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3288 * Display the form used to select a file to import from the server upload directory
3290 * @param array $import_list array of import types
3291 * @param string $uploaddir upload directory
3293 * @return nothing
3295 function PMA_selectUploadFile($import_list, $uploaddir)
3297 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3298 $extensions = '';
3299 foreach ($import_list as $key => $val) {
3300 if (!empty($extensions)) {
3301 $extensions .= '|';
3303 $extensions .= $val['extension'];
3305 $matcher = '@\.(' . $extensions . ')(\.('
3306 . PMA_supportedDecompressions() . '))?$@';
3308 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3309 ? $local_import_file
3310 : '';
3311 $files = PMA_getFileSelectOptions(
3312 PMA_userDir($uploaddir),
3313 $matcher,
3314 $active
3316 if ($files === false) {
3317 PMA_Message::error(
3318 __('The directory you set for upload work cannot be reached')
3319 )->display();
3320 } elseif (!empty($files)) {
3321 echo "\n";
3322 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3323 echo ' <option value="">&nbsp;</option>' . "\n";
3324 echo $files;
3325 echo ' </select>' . "\n";
3326 } elseif (empty ($files)) {
3327 echo '<i>' . __('There are no files to upload') . '</i>';
3332 * Build titles and icons for action links
3334 * @return array the action titles
3336 function PMA_buildActionTitles()
3338 $titles = array();
3340 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3341 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3342 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3343 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3344 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3345 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3346 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3347 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3348 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3349 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3350 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3351 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3352 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3353 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3354 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3355 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3356 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3357 return $titles;
3361 * This function processes the datatypes supported by the DB, as specified in
3362 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3363 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3365 * @param bool $html Whether to generate an html snippet or an array
3366 * @param string $selected The value to mark as selected in HTML mode
3368 * @return mixed An HTML snippet or an array of datatypes.
3371 function PMA_getSupportedDatatypes($html = false, $selected = '')
3373 global $cfg;
3375 if ($html) {
3376 // NOTE: the SELECT tag in not included in this snippet.
3377 $retval = '';
3378 foreach ($cfg['ColumnTypes'] as $key => $value) {
3379 if (is_array($value)) {
3380 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3381 foreach ($value as $subvalue) {
3382 if ($subvalue == $selected) {
3383 $retval .= "<option selected='selected'>";
3384 $retval .= $subvalue;
3385 $retval .= "</option>";
3386 } else if ($subvalue === '-') {
3387 $retval .= "<option disabled='disabled'>";
3388 $retval .= $subvalue;
3389 $retval .= "</option>";
3390 } else {
3391 $retval .= "<option>$subvalue</option>";
3394 $retval .= '</optgroup>';
3395 } else {
3396 if ($selected == $value) {
3397 $retval .= "<option selected='selected'>$value</option>";
3398 } else {
3399 $retval .= "<option>$value</option>";
3403 } else {
3404 $retval = array();
3405 foreach ($cfg['ColumnTypes'] as $value) {
3406 if (is_array($value)) {
3407 foreach ($value as $subvalue) {
3408 if ($subvalue !== '-') {
3409 $retval[] = $subvalue;
3412 } else {
3413 if ($value !== '-') {
3414 $retval[] = $value;
3420 return $retval;
3421 } // end PMA_getSupportedDatatypes()
3424 * Returns a list of datatypes that are not (yet) handled by PMA.
3425 * Used by: tbl_change.php and libraries/db_routines.inc.php
3427 * @return array list of datatypes
3429 function PMA_unsupportedDatatypes()
3431 $no_support_types = array();
3432 return $no_support_types;
3436 * Return GIS data types
3438 * @param bool $upper_case whether to return values in upper case
3440 * @return array GIS data types
3442 function PMA_getGISDatatypes($upper_case = false)
3444 $gis_data_types = array(
3445 'geometry',
3446 'point',
3447 'linestring',
3448 'polygon',
3449 'multipoint',
3450 'multilinestring',
3451 'multipolygon',
3452 'geometrycollection'
3454 if ($upper_case) {
3455 for ($i = 0; $i < count($gis_data_types); $i++) {
3456 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3460 return $gis_data_types;
3464 * Generates GIS data based on the string passed.
3466 * @param string $gis_string GIS string
3468 * @return GIS data enclosed in 'GeomFromText' function
3470 function PMA_createGISData($gis_string)
3472 $gis_string = trim($gis_string);
3473 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3474 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3475 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3476 return 'GeomFromText(' . $gis_string . ')';
3477 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3478 return "GeomFromText('" . $gis_string . "')";
3479 } else {
3480 return $gis_string;
3485 * Returns the names and details of the functions
3486 * that can be applied on geometry data typess.
3488 * @param string $geom_type if provided the output is limited to the functions
3489 * that are applicable to the provided geometry type.
3490 * @param bool $binary if set to false functions that take two geometries
3491 * as arguments will not be included.
3492 * @param bool $display if set to true seperators will be added to the
3493 * output array.
3495 * @return array names and details of the functions that can be applied on
3496 * geometry data typess.
3498 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3500 $funcs = array();
3501 if ($display) {
3502 $funcs[] = array('display' => ' ');
3505 // Unary functions common to all geomety types
3506 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3507 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3508 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3509 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3510 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3511 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3513 $geom_type = trim(strtolower($geom_type));
3514 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3515 $funcs[] = array('display' => '--------');
3518 // Unary functions that are specific to each geomety type
3519 if ($geom_type == 'point') {
3520 $funcs['X'] = array('params' => 1, 'type' => 'float');
3521 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3523 } elseif ($geom_type == 'multipoint') {
3524 // no fucntions here
3525 } elseif ($geom_type == 'linestring') {
3526 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3527 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3528 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3529 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3530 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3532 } elseif ($geom_type == 'multilinestring') {
3533 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3534 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3536 } elseif ($geom_type == 'polygon') {
3537 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3538 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3539 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3541 } elseif ($geom_type == 'multipolygon') {
3542 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3543 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3544 // Not yet implemented in MySQL
3545 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3547 } elseif ($geom_type == 'geometrycollection') {
3548 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3551 // If we are asked for binary functions as well
3552 if ($binary) {
3553 // section seperator
3554 if ($display) {
3555 $funcs[] = array('display' => '--------');
3557 if (PMA_MYSQL_INT_VERSION < 50601) {
3558 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3559 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3560 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3561 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3562 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3563 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3564 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3565 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3566 } else {
3567 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3568 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3569 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3570 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3571 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3572 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3573 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3574 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3575 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3579 if ($display) {
3580 $funcs[] = array('display' => '--------');
3582 // Minimum bounding rectangle functions
3583 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3584 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3585 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3586 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3587 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3588 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3589 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3591 return $funcs;
3595 * Creates a dropdown box with MySQL functions for a particular column.
3597 * @param array $field Data about the column for which
3598 * to generate the dropdown
3599 * @param bool $insert_mode Whether the operation is 'insert'
3601 * @global array $cfg PMA configuration
3602 * @global array $analyzed_sql Analyzed SQL query
3603 * @global mixed $data (null/string) FIXME: what is this for?
3605 * @return string An HTML snippet of a dropdown list with function
3606 * names appropriate for the requested column.
3608 function PMA_getFunctionsForField($field, $insert_mode)
3610 global $cfg, $analyzed_sql, $data;
3612 $selected = '';
3613 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3614 // or something similar. Then directly look up the entry in the
3615 // RestrictFunctions array, which'll then reveal the available dropdown options
3616 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3617 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3619 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3620 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3621 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3622 } else {
3623 $dropdown = array();
3624 $default_function = '';
3626 $dropdown_built = array();
3627 $op_spacing_needed = false;
3628 // what function defined as default?
3629 // for the first timestamp we don't set the default function
3630 // if there is a default value for the timestamp
3631 // (not including CURRENT_TIMESTAMP)
3632 // and the column does not have the
3633 // ON UPDATE DEFAULT TIMESTAMP attribute.
3634 if ($field['True_Type'] == 'timestamp'
3635 && empty($field['Default'])
3636 && empty($data)
3637 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3639 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3641 // For primary keys of type char(36) or varchar(36) UUID if the default function
3642 // Only applies to insert mode, as it would silently trash data on updates.
3643 if ($insert_mode
3644 && $field['Key'] == 'PRI'
3645 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3647 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3649 // this is set only when appropriate and is always true
3650 if (isset($field['display_binary_as_hex'])) {
3651 $default_function = 'UNHEX';
3654 // Create the output
3655 $retval = ' <option></option>' . "\n";
3656 // loop on the dropdown array and print all available options for that field.
3657 foreach ($dropdown as $each_dropdown) {
3658 $retval .= ' ';
3659 $retval .= '<option';
3660 if ($default_function === $each_dropdown) {
3661 $retval .= ' selected="selected"';
3663 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3664 $dropdown_built[$each_dropdown] = 'true';
3665 $op_spacing_needed = true;
3667 // For compatibility's sake, do not let out all other functions. Instead
3668 // print a separator (blank) and then show ALL functions which weren't shown
3669 // yet.
3670 $cnt_functions = count($cfg['Functions']);
3671 for ($j = 0; $j < $cnt_functions; $j++) {
3672 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3673 || $dropdown_built[$cfg['Functions'][$j]] != 'true'
3675 // Is current function defined as default?
3676 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3677 || (! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3678 ? ' selected="selected"'
3679 : '';
3680 if ($op_spacing_needed == true) {
3681 $retval .= ' ';
3682 $retval .= '<option value="">--------</option>' . "\n";
3683 $op_spacing_needed = false;
3686 $retval .= ' ';
3687 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3688 . '</option>' . "\n";
3690 } // end for
3692 return $retval;
3693 } // end PMA_getFunctionsForField()
3696 * Checks if the current user has a specific privilege and returns true if the
3697 * user indeed has that privilege or false if (s)he doesn't. This function must
3698 * only be used for features that are available since MySQL 5, because it
3699 * relies on the INFORMATION_SCHEMA database to be present.
3701 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3702 * // Checks if the currently logged in user has the global
3703 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3704 * // user has this privilege on database 'mydb'.
3706 * @param string $priv The privilege to check
3707 * @param mixed $db null, to only check global privileges
3708 * string, db name where to also check for privileges
3709 * @param mixed $tbl null, to only check global privileges
3710 * string, db name where to also check for privileges
3712 * @return bool
3714 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3716 // Get the username for the current user in the format
3717 // required to use in the information schema database.
3718 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3719 if ($user === false) {
3720 return false;
3722 $user = explode('@', $user);
3723 $username = "''";
3724 $username .= str_replace("'", "''", $user[0]);
3725 $username .= "''@''";
3726 $username .= str_replace("'", "''", $user[1]);
3727 $username .= "''";
3728 // Prepage the query
3729 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3730 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3731 // Check global privileges first.
3732 if (PMA_DBI_fetch_value(
3733 sprintf(
3734 $query,
3735 'USER_PRIVILEGES',
3736 $username,
3737 $priv
3741 return true;
3743 // If a database name was provided and user does not have the
3744 // required global privilege, try database-wise permissions.
3745 if ($db !== null) {
3746 $query .= " AND TABLE_SCHEMA='%s'";
3747 if (PMA_DBI_fetch_value(
3748 sprintf(
3749 $query,
3750 'SCHEMA_PRIVILEGES',
3751 $username,
3752 $priv,
3753 PMA_sqlAddSlashes($db)
3757 return true;
3759 } else {
3760 // There was no database name provided and the user
3761 // does not have the correct global privilege.
3762 return false;
3764 // If a table name was also provided and we still didn't
3765 // find any valid privileges, try table-wise privileges.
3766 if ($tbl !== null) {
3767 $query .= " AND TABLE_NAME='%s'";
3768 if ($retval = PMA_DBI_fetch_value(
3769 sprintf(
3770 $query,
3771 'TABLE_PRIVILEGES',
3772 $username,
3773 $priv,
3774 PMA_sqlAddSlashes($db),
3775 PMA_sqlAddSlashes($tbl)
3779 return true;
3782 // If we reached this point, the user does not
3783 // have even valid table-wise privileges.
3784 return false;
3788 * Returns server type for current connection
3790 * Known types are: Drizzle, MariaDB and MySQL (default)
3792 * @return string
3794 function PMA_getServerType()
3796 $server_type = 'MySQL';
3797 if (PMA_DRIZZLE) {
3798 $server_type = 'Drizzle';
3799 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3800 $server_type = 'MariaDB';
3801 } else if (stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3802 $server_type = 'Percona Server';
3804 return $server_type;
3808 * Analyzes the limit clause and return the start and length attributes of it.
3810 * @param string $limit_clause limit clause
3812 * @return array Start and length attributes of the limit clause
3814 function PMA_analyzeLimitClause($limit_clause)
3816 $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
3817 return array(
3818 'start' => trim($start_and_length[0]),
3819 'length' => trim($start_and_length[1])
3824 * Outputs HTML code for print button.
3826 * @return nothing
3828 function PMA_printButton()
3830 echo '<p class="print_ignore">';
3831 echo '<input type="button" id="print" value="' . __('Print') . '" />';
3832 echo '</p>';