Merge branch 'master' of ssh://repo.or.cz/srv/git/phpmyadmin/madhuracj into OpenGIS
[phpmyadmin/madhuracj.git] / libraries / common.lib.php
blobfb1c307c2bfb77190dae6e41f38b92428f71938a
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 $url = '';
122 $is_sprite = false;
123 $alternate = htmlspecialchars($alternate);
125 // Check if we have the requested image as a sprite
126 // and set $url accordingly
127 if (is_readable($_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php')) {
128 include_once $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
129 $sprites = PMA_sprites();
130 $class = str_replace(array('.gif','.png'), '', $image);
131 if (array_key_exists($class, $sprites)) {
132 $is_sprite = true;
133 $url = 'themes/dot.gif';
134 } else {
135 $url = $GLOBALS['pmaThemeImage'] . $image;
137 } else {
138 $url = $GLOBALS['pmaThemeImage'] . $image;
140 // set class attribute
141 if ($is_sprite) {
142 if (isset($attributes['class'])) {
143 $attributes['class'] = "icon ic_$class " . $attributes['class'];
144 } else {
145 $attributes['class'] = "icon ic_$class";
148 // set all other attributes
149 $attr_str = '';
150 foreach ($attributes as $key => $value) {
151 if (! in_array($key, array('alt', 'title'))) {
152 $attr_str .= " $key=\"$value\"";
155 // override the alt attribute
156 if (isset($attributes['alt'])) {
157 $alt = $attributes['alt'];
158 } else {
159 $alt = $alternate;
161 // override the title attribute
162 if (isset($attributes['title'])) {
163 $title = $attributes['title'];
164 } else {
165 $title = $alternate;
167 // generate the IMG tag
168 $template = '<img src="%s" title="%s" alt="%s"%s />';
169 $retval = sprintf($template, $url, $title, $alt, $attr_str);
171 return $retval;
175 * Displays the maximum size for an upload
177 * @param integer $max_upload_size the size
179 * @return string the message
181 * @access public
183 function PMA_displayMaximumUploadSize($max_upload_size)
185 // I have to reduce the second parameter (sensitiveness) from 6 to 4
186 // to avoid weird results like 512 kKib
187 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
188 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
192 * Generates a hidden field which should indicate to the browser
193 * the maximum size for upload
195 * @param integer $max_size the size
197 * @return string the INPUT field
199 * @access public
201 function PMA_generateHiddenMaxFileSize($max_size)
203 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
207 * Add slashes before "'" and "\" characters so a value containing them can
208 * be used in a sql comparison.
210 * @param string $a_string the string to slash
211 * @param bool $is_like whether the string will be used in a 'LIKE' clause
212 * (it then requires two more escaped sequences) or not
213 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
214 * (converts \n to \\n, \r to \\r)
215 * @param bool $php_code whether this function is used as part of the
216 * "Create PHP code" dialog
218 * @return string the slashed string
220 * @access public
222 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
224 if ($is_like) {
225 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
226 } else {
227 $a_string = str_replace('\\', '\\\\', $a_string);
230 if ($crlf) {
231 $a_string = strtr(
232 $a_string,
233 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
237 if ($php_code) {
238 $a_string = str_replace('\'', '\\\'', $a_string);
239 } else {
240 $a_string = str_replace('\'', '\'\'', $a_string);
243 return $a_string;
244 } // end of the 'PMA_sqlAddSlashes()' function
248 * Add slashes before "_" and "%" characters for using them in MySQL
249 * database, table and field names.
250 * Note: This function does not escape backslashes!
252 * @param string $name the string to escape
254 * @return string the escaped string
256 * @access public
258 function PMA_escape_mysql_wildcards($name)
260 return strtr($name, array('_' => '\\_', '%' => '\\%'));
261 } // end of the 'PMA_escape_mysql_wildcards()' function
264 * removes slashes before "_" and "%" characters
265 * Note: This function does not unescape backslashes!
267 * @param string $name the string to escape
269 * @return string the escaped string
271 * @access public
273 function PMA_unescape_mysql_wildcards($name)
275 return strtr($name, array('\\_' => '_', '\\%' => '%'));
276 } // end of the 'PMA_unescape_mysql_wildcards()' function
279 * removes quotes (',",`) from a quoted string
281 * checks if the sting is quoted and removes this quotes
283 * @param string $quoted_string string to remove quotes from
284 * @param string $quote type of quote to remove
286 * @return string unqoted string
288 function PMA_unQuote($quoted_string, $quote = null)
290 $quotes = array();
292 if (null === $quote) {
293 $quotes[] = '`';
294 $quotes[] = '"';
295 $quotes[] = "'";
296 } else {
297 $quotes[] = $quote;
300 foreach ($quotes as $quote) {
301 if (substr($quoted_string, 0, 1) === $quote
302 && substr($quoted_string, -1, 1) === $quote
304 $unquoted_string = substr($quoted_string, 1, -1);
305 // replace escaped quotes
306 $unquoted_string = str_replace(
307 $quote . $quote,
308 $quote,
309 $unquoted_string
311 return $unquoted_string;
315 return $quoted_string;
319 * format sql strings
321 * @param mixed $parsed_sql pre-parsed SQL structure
322 * @param string $unparsed_sql raw SQL string
324 * @return string the formatted sql
326 * @global array the configuration array
327 * @global boolean whether the current statement is a multiple one or not
329 * @access public
330 * @todo move into PMA_Sql
332 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
334 global $cfg;
336 // Check that we actually have a valid set of parsed data
337 // well, not quite
338 // first check for the SQL parser having hit an error
339 if (PMA_SQP_isError()) {
340 return htmlspecialchars($parsed_sql['raw']);
342 // then check for an array
343 if (! is_array($parsed_sql)) {
344 // We don't so just return the input directly
345 // This is intended to be used for when the SQL Parser is turned off
346 $formatted_sql = "<pre>\n";
347 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
348 $formatted_sql .= $unparsed_sql;
349 } else {
350 $formatted_sql .= $parsed_sql;
352 $formatted_sql .= "\n</pre>";
353 return $formatted_sql;
356 $formatted_sql = '';
358 switch ($cfg['SQP']['fmtType']) {
359 case 'none':
360 if ($unparsed_sql != '') {
361 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
362 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
363 . '</pre></span>';
364 } else {
365 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
367 break;
368 case 'html':
369 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
370 break;
371 case 'text':
372 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
373 break;
374 default:
375 break;
376 } // end switch
378 return $formatted_sql;
379 } // end of the "PMA_formatSql()" function
383 * Displays a link to the official MySQL documentation
385 * @param string $chapter chapter of "HTML, one page per chapter" documentation
386 * @param string $link contains name of page/anchor that is being linked
387 * @param bool $big_icon whether to use big icon (like in left frame)
388 * @param string $anchor anchor to page part
389 * @param bool $just_open whether only the opening <a> tag should be returned
391 * @return string the html link
393 * @access public
395 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
397 global $cfg;
399 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
400 return '';
403 // Fixup for newly used names:
404 $chapter = str_replace('_', '-', strtolower($chapter));
405 $link = str_replace('_', '-', strtolower($link));
407 switch ($cfg['MySQLManualType']) {
408 case 'chapters':
409 if (empty($chapter)) {
410 $chapter = 'index';
412 if (empty($anchor)) {
413 $anchor = $link;
415 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
416 break;
417 case 'big':
418 if (empty($anchor)) {
419 $anchor = $link;
421 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
422 break;
423 case 'searchable':
424 if (empty($link)) {
425 $link = 'index';
427 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
428 if (!empty($anchor)) {
429 $url .= '#' . $anchor;
431 break;
432 case 'viewable':
433 default:
434 if (empty($link)) {
435 $link = 'index';
437 $mysql = '5.0';
438 $lang = 'en';
439 if (defined('PMA_MYSQL_INT_VERSION')) {
440 if (PMA_MYSQL_INT_VERSION >= 50500) {
441 $mysql = '5.5';
442 /* l10n: Please check that translation actually exists. */
443 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
444 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
445 $mysql = '5.1';
446 /* l10n: Please check that translation actually exists. */
447 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
448 } else {
449 $mysql = '5.0';
450 /* l10n: Please check that translation actually exists. */
451 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
454 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
455 if (!empty($anchor)) {
456 $url .= '#' . $anchor;
458 break;
461 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
462 if ($just_open) {
463 return $open_link;
464 } elseif ($big_icon) {
465 return $open_link . PMA_getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
466 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
467 return $open_link . PMA_getImage('b_help.png', __('Documentation')) . '</a>';
468 } else {
469 return '[' . $open_link . __('Documentation') . '</a>]';
471 } // end of the 'PMA_showMySQLDocu()' function
475 * Displays a link to the phpMyAdmin documentation
477 * @param string $anchor anchor in documentation
479 * @return string the html link
481 * @access public
483 function PMA_showDocu($anchor)
485 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
486 return '<a href="Documentation.html#' . $anchor . '" target="documentation">'
487 . PMA_getImage('b_help.png', __('Documentation'))
488 . '</a>';
489 } else {
490 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">'
491 . __('Documentation') . '</a>]';
493 } // end of the 'PMA_showDocu()' function
496 * Displays a link to the PHP documentation
498 * @param string $target anchor in documentation
500 * @return string the html link
502 * @access public
504 function PMA_showPHPDocu($target)
506 $url = PMA_getPHPDocLink($target);
508 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
509 return '<a href="' . $url . '" target="documentation">'
510 . PMA_getImage('b_help.png', __('Documentation'))
511 . '</a>';
512 } else {
513 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
515 } // end of the 'PMA_showPHPDocu()' function
518 * returns HTML for a footnote marker and add the messsage to the footnotes
520 * @param string $message the error message
521 * @param bool $bbcode
522 * @param string $type message types
524 * @return string html code for a footnote marker
526 * @access public
528 function PMA_showHint($message, $bbcode = false, $type = 'notice')
530 if ($message instanceof PMA_Message) {
531 $key = $message->getHash();
532 $type = $message->getLevel();
533 } else {
534 $key = md5($message);
537 if (! isset($GLOBALS['footnotes'][$key])) {
538 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
539 $GLOBALS['footnotes'] = array();
541 $nr = count($GLOBALS['footnotes']) + 1;
542 $GLOBALS['footnotes'][$key] = array(
543 'note' => $message,
544 'type' => $type,
545 'nr' => $nr,
547 } else {
548 $nr = $GLOBALS['footnotes'][$key]['nr'];
551 if ($bbcode) {
552 return '[sup]' . $nr . '[/sup]';
555 // footnotemarker used in js/tooltip.js
556 return '<sup class="footnotemarker">' . $nr . '</sup>' .
557 PMA_getImage('b_help.png', '', array('class' => 'footnotemarker footnote_' . $nr));
561 * Displays a MySQL error message in the right frame.
563 * @param string $error_message the error message
564 * @param string $the_query the sql query that failed
565 * @param bool $is_modify_link whether to show a "modify" link or not
566 * @param string $back_url the "back" link url (full path is not required)
567 * @param bool $exit EXIT the page?
569 * @global string the curent table
570 * @global string the current db
572 * @access public
574 function PMA_mysqlDie($error_message = '', $the_query = '',
575 $is_modify_link = true, $back_url = '', $exit = true)
577 global $table, $db;
580 * start http output, display html headers
582 include_once './libraries/header.inc.php';
584 $error_msg_output = '';
586 if (!$error_message) {
587 $error_message = PMA_DBI_getError();
589 if (!$the_query && !empty($GLOBALS['sql_query'])) {
590 $the_query = $GLOBALS['sql_query'];
593 // --- Added to solve bug #641765
594 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
595 $formatted_sql = htmlspecialchars($the_query);
596 } elseif (empty($the_query) || trim($the_query) == '') {
597 $formatted_sql = '';
598 } else {
599 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
600 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
601 } else {
602 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
605 // ---
606 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
607 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
608 // if the config password is wrong, or the MySQL server does not
609 // respond, do not show the query that would reveal the
610 // username/password
611 if (!empty($the_query) && !strstr($the_query, 'connect')) {
612 // --- Added to solve bug #641765
613 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
614 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
615 $error_msg_output .= '<br />' . "\n";
617 // ---
618 // modified to show the help on sql errors
619 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
620 if (strstr(strtolower($formatted_sql), 'select')) {
621 // please show me help to the error on select
622 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
624 if ($is_modify_link) {
625 $_url_params = array(
626 'sql_query' => $the_query,
627 'show_query' => 1,
629 if (strlen($table)) {
630 $_url_params['db'] = $db;
631 $_url_params['table'] = $table;
632 $doedit_goto = '<a href="tbl_sql.php' . PMA_generate_common_url($_url_params) . '">';
633 } elseif (strlen($db)) {
634 $_url_params['db'] = $db;
635 $doedit_goto = '<a href="db_sql.php' . PMA_generate_common_url($_url_params) . '">';
636 } else {
637 $doedit_goto = '<a href="server_sql.php' . PMA_generate_common_url($_url_params) . '">';
640 $error_msg_output .= $doedit_goto
641 . PMA_getIcon('b_edit.png', __('Edit'))
642 . '</a>';
643 } // end if
644 $error_msg_output .= ' </p>' . "\n"
645 .' <p>' . "\n"
646 .' ' . $formatted_sql . "\n"
647 .' </p>' . "\n";
648 } // end if
650 if (! empty($error_message)) {
651 $error_message = preg_replace(
652 "@((\015\012)|(\015)|(\012)){3,}@",
653 "\n\n",
654 $error_message
657 // modified to show the help on error-returns
658 // (now error-messages-server)
659 $error_msg_output .= '<p>' . "\n"
660 . ' <strong>' . __('MySQL said: ') . '</strong>'
661 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
662 . "\n"
663 . '</p>' . "\n";
665 // The error message will be displayed within a CODE segment.
666 // To preserve original formatting, but allow wordwrapping,
667 // we do a couple of replacements
669 // Replace all non-single blanks with their HTML-counterpart
670 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
671 // Replace TAB-characters with their HTML-counterpart
672 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
673 // Replace linebreaks
674 $error_message = nl2br($error_message);
676 $error_msg_output .= '<code>' . "\n"
677 . $error_message . "\n"
678 . '</code><br />' . "\n";
679 $error_msg_output .= '</div>';
681 $_SESSION['Import_message']['message'] = $error_msg_output;
683 if ($exit) {
685 * If in an Ajax request
686 * - avoid displaying a Back link
687 * - use PMA_ajaxResponse() to transmit the message and exit
689 if ($GLOBALS['is_ajax_request'] == true) {
690 PMA_ajaxResponse($error_msg_output, false);
692 if (! empty($back_url)) {
693 if (strstr($back_url, '?')) {
694 $back_url .= '&amp;no_history=true';
695 } else {
696 $back_url .= '?no_history=true';
699 $_SESSION['Import_message']['go_back_url'] = $back_url;
701 $error_msg_output .= '<fieldset class="tblFooters">';
702 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
703 $error_msg_output .= '</fieldset>' . "\n\n";
706 echo $error_msg_output;
708 * display footer and exit
710 include './libraries/footer.inc.php';
711 } else {
712 echo $error_msg_output;
714 } // end of the 'PMA_mysqlDie()' function
717 * returns array with tables of given db with extended information and grouped
719 * @param string $db name of db
720 * @param string $tables name of tables
721 * @param integer $limit_offset list offset
722 * @param int|bool $limit_count max tables to return
724 * @return array (recursive) grouped table list
726 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
728 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
730 if (null === $tables) {
731 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
732 if ($GLOBALS['cfg']['NaturalOrder']) {
733 uksort($tables, 'strnatcasecmp');
737 if (count($tables) < 1) {
738 return $tables;
741 $default = array(
742 'Name' => '',
743 'Rows' => 0,
744 'Comment' => '',
745 'disp_name' => '',
748 $table_groups = array();
750 // for blobstreaming - list of blobstreaming tables
752 // load PMA configuration
753 $PMA_Config = $GLOBALS['PMA_Config'];
755 foreach ($tables as $table_name => $table) {
756 // if BS tables exist
757 if (PMA_BS_IsHiddenTable($table_name)) {
758 continue;
761 // check for correct row count
762 if (null === $table['Rows']) {
763 // Do not check exact row count here,
764 // if row count is invalid possibly the table is defect
765 // and this would break left frame;
766 // but we can check row count if this is a view or the
767 // information_schema database
768 // since PMA_Table::countRecords() returns a limited row count
769 // in this case.
771 // set this because PMA_Table::countRecords() can use it
772 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
774 if ($tbl_is_view || PMA_is_system_schema($db)) {
775 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'], false, true);
779 // in $group we save the reference to the place in $table_groups
780 // where to store the table info
781 if ($GLOBALS['cfg']['LeftFrameDBTree']
782 && $sep && strstr($table_name, $sep)
784 $parts = explode($sep, $table_name);
786 $group =& $table_groups;
787 $i = 0;
788 $group_name_full = '';
789 $parts_cnt = count($parts) - 1;
790 while ($i < $parts_cnt
791 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
792 $group_name = $parts[$i] . $sep;
793 $group_name_full .= $group_name;
795 if (! isset($group[$group_name])) {
796 $group[$group_name] = array();
797 $group[$group_name]['is' . $sep . 'group'] = true;
798 $group[$group_name]['tab' . $sep . 'count'] = 1;
799 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
800 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
801 $table = $group[$group_name];
802 $group[$group_name] = array();
803 $group[$group_name][$group_name] = $table;
804 unset($table);
805 $group[$group_name]['is' . $sep . 'group'] = true;
806 $group[$group_name]['tab' . $sep . 'count'] = 1;
807 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
808 } else {
809 $group[$group_name]['tab' . $sep . 'count']++;
811 $group =& $group[$group_name];
812 $i++;
814 } else {
815 if (! isset($table_groups[$table_name])) {
816 $table_groups[$table_name] = array();
818 $group =& $table_groups;
822 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
823 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
825 // switch tooltip and name
826 $table['disp_name'] = $table['Comment'];
827 $table['Comment'] = $table['Name'];
828 } else {
829 $table['disp_name'] = $table['Name'];
832 $group[$table_name] = array_merge($default, $table);
835 return $table_groups;
838 /* ----------------------- Set of misc functions ----------------------- */
842 * Adds backquotes on both sides of a database, table or field name.
843 * and escapes backquotes inside the name with another backquote
845 * example:
846 * <code>
847 * echo PMA_backquote('owner`s db'); // `owner``s db`
849 * </code>
851 * @param mixed $a_name the database, table or field name to "backquote"
852 * or array of it
853 * @param boolean $do_it a flag to bypass this function (used by dump
854 * functions)
856 * @return mixed the "backquoted" database, table or field name
858 * @access public
860 function PMA_backquote($a_name, $do_it = true)
862 if (is_array($a_name)) {
863 foreach ($a_name as &$data) {
864 $data = PMA_backquote($data, $do_it);
866 return $a_name;
869 if (! $do_it) {
870 global $PMA_SQPdata_forbidden_word;
872 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
873 return $a_name;
877 // '0' is also empty for php :-(
878 if (strlen($a_name) && $a_name !== '*') {
879 return '`' . str_replace('`', '``', $a_name) . '`';
880 } else {
881 return $a_name;
883 } // end of the 'PMA_backquote()' function
886 * Defines the <CR><LF> value depending on the user OS.
888 * @return string the <CR><LF> value to use
890 * @access public
892 function PMA_whichCrlf()
894 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
895 // Win case
896 if (PMA_USR_OS == 'Win') {
897 $the_crlf = "\r\n";
898 } else {
899 // Others
900 $the_crlf = "\n";
903 return $the_crlf;
904 } // end of the 'PMA_whichCrlf()' function
907 * Reloads navigation if needed.
909 * @param bool $jsonly prints out pure JavaScript
911 * @access public
913 function PMA_reloadNavigation($jsonly=false)
915 // Reloads the navigation frame via JavaScript if required
916 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
917 // one of the reasons for a reload is when a table is dropped
918 // in this case, get rid of the table limit offset, otherwise
919 // we have a problem when dropping a table on the last page
920 // and the offset becomes greater than the total number of tables
921 unset($_SESSION['tmp_user_values']['table_limit_offset']);
922 echo "\n";
923 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
924 if (!$jsonly) {
925 echo '<script type="text/javascript">' . PHP_EOL;
928 //<![CDATA[
929 if (typeof(window.parent) != 'undefined'
930 && typeof(window.parent.frame_navigation) != 'undefined'
931 && window.parent.goTo) {
932 window.parent.goTo('<?php echo $reload_url; ?>');
934 //]]>
935 <?php
936 if (!$jsonly) {
937 echo '</script>' . PHP_EOL;
940 unset($GLOBALS['reload']);
945 * displays the message and the query
946 * usually the message is the result of the query executed
948 * @param string $message the message to display
949 * @param string $sql_query the query to display
950 * @param string $type the type (level) of the message
951 * @param boolean $is_view is this a message after a VIEW operation?
953 * @return string
955 * @access public
957 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
960 * PMA_ajaxResponse uses this function to collect the string of HTML generated
961 * for showing the message. Use output buffering to collect it and return it
962 * in a string. In some special cases on sql.php, buffering has to be disabled
963 * and hence we check with $GLOBALS['buffer_message']
965 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
966 ob_start();
968 global $cfg;
970 if (null === $sql_query) {
971 if (! empty($GLOBALS['display_query'])) {
972 $sql_query = $GLOBALS['display_query'];
973 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
974 $sql_query = $GLOBALS['unparsed_sql'];
975 } elseif (! empty($GLOBALS['sql_query'])) {
976 $sql_query = $GLOBALS['sql_query'];
977 } else {
978 $sql_query = '';
982 if (isset($GLOBALS['using_bookmark_message'])) {
983 $GLOBALS['using_bookmark_message']->display();
984 unset($GLOBALS['using_bookmark_message']);
987 // Corrects the tooltip text via JS if required
988 // @todo this is REALLY the wrong place to do this - very unexpected here
989 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
990 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
991 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
992 echo "\n";
993 echo '<script type="text/javascript">' . "\n";
994 echo '//<![CDATA[' . "\n";
995 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
996 . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
997 echo '//]]>' . "\n";
998 echo '</script>' . "\n";
999 } // end if ... elseif
1001 // Checks if the table needs to be repaired after a TRUNCATE query.
1002 // @todo what about $GLOBALS['display_query']???
1003 // @todo this is REALLY the wrong place to do this - very unexpected here
1004 if (strlen($GLOBALS['table'])
1005 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
1007 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
1008 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1011 unset($tbl_status);
1013 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1014 // check for it's presence before using it
1015 echo '<div id="result_query" align="'
1016 . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' )
1017 . '">' . "\n";
1019 if ($message instanceof PMA_Message) {
1020 if (isset($GLOBALS['special_message'])) {
1021 $message->addMessage($GLOBALS['special_message']);
1022 unset($GLOBALS['special_message']);
1024 $message->display();
1025 $type = $message->getLevel();
1026 } else {
1027 echo '<div class="' . $type . '">';
1028 echo PMA_sanitize($message);
1029 if (isset($GLOBALS['special_message'])) {
1030 echo PMA_sanitize($GLOBALS['special_message']);
1031 unset($GLOBALS['special_message']);
1033 echo '</div>';
1036 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1037 // Html format the query to be displayed
1038 // If we want to show some sql code it is easiest to create it here
1039 /* SQL-Parser-Analyzer */
1041 if (! empty($GLOBALS['show_as_php'])) {
1042 $new_line = '\\n"<br />' . "\n"
1043 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1044 $query_base = htmlspecialchars(addslashes($sql_query));
1045 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1046 } else {
1047 $query_base = $sql_query;
1050 $query_too_big = false;
1052 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1053 // when the query is large (for example an INSERT of binary
1054 // data), the parser chokes; so avoid parsing the query
1055 $query_too_big = true;
1056 $shortened_query_base = nl2br(
1057 htmlspecialchars(
1058 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
1061 } elseif (! empty($GLOBALS['parsed_sql'])
1062 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1063 // (here, use "! empty" because when deleting a bookmark,
1064 // $GLOBALS['parsed_sql'] is set but empty
1065 $parsed_sql = $GLOBALS['parsed_sql'];
1066 } else {
1067 // Parse SQL if needed
1068 $parsed_sql = PMA_SQP_parse($query_base);
1071 // Analyze it
1072 if (isset($parsed_sql) && ! PMA_SQP_isError()) {
1073 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1075 // Same as below (append LIMIT), append the remembered ORDER BY
1076 if ($GLOBALS['cfg']['RememberSorting']
1077 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1078 && isset($GLOBALS['sql_order_to_append'])
1080 $query_base = $analyzed_display_query[0]['section_before_limit']
1081 . "\n" . $GLOBALS['sql_order_to_append']
1082 . $analyzed_display_query[0]['section_after_limit'];
1084 // Need to reparse query
1085 $parsed_sql = PMA_SQP_parse($query_base);
1086 // update the $analyzed_display_query
1087 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1088 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1091 // Here we append the LIMIT added for navigation, to
1092 // enable its display. Adding it higher in the code
1093 // to $sql_query would create a problem when
1094 // using the Refresh or Edit links.
1096 // Only append it on SELECTs.
1099 * @todo what would be the best to do when someone hits Refresh:
1100 * use the current LIMITs ?
1103 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1104 && isset($GLOBALS['sql_limit_to_append'])
1106 $query_base = $analyzed_display_query[0]['section_before_limit']
1107 . "\n" . $GLOBALS['sql_limit_to_append']
1108 . $analyzed_display_query[0]['section_after_limit'];
1109 // Need to reparse query
1110 $parsed_sql = PMA_SQP_parse($query_base);
1114 if (! empty($GLOBALS['show_as_php'])) {
1115 $query_base = '$sql = "' . $query_base;
1116 } elseif (! empty($GLOBALS['validatequery'])) {
1117 try {
1118 $query_base = PMA_validateSQL($query_base);
1119 } catch (Exception $e) {
1120 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1122 } elseif (isset($parsed_sql)) {
1123 $query_base = PMA_formatSql($parsed_sql, $query_base);
1126 // Prepares links that may be displayed to edit/explain the query
1127 // (don't go to default pages, we must go to the page
1128 // where the query box is available)
1130 // Basic url query part
1131 $url_params = array();
1132 if (! isset($GLOBALS['db'])) {
1133 $GLOBALS['db'] = '';
1135 if (strlen($GLOBALS['db'])) {
1136 $url_params['db'] = $GLOBALS['db'];
1137 if (strlen($GLOBALS['table'])) {
1138 $url_params['table'] = $GLOBALS['table'];
1139 $edit_link = 'tbl_sql.php';
1140 } else {
1141 $edit_link = 'db_sql.php';
1143 } else {
1144 $edit_link = 'server_sql.php';
1147 // Want to have the query explained
1148 // but only explain a SELECT (that has not been explained)
1149 /* SQL-Parser-Analyzer */
1150 $explain_link = '';
1151 $is_select = false;
1152 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1153 $explain_params = $url_params;
1154 // Detect if we are validating as well
1155 // To preserve the validate uRL data
1156 if (! empty($GLOBALS['validatequery'])) {
1157 $explain_params['validatequery'] = 1;
1159 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1160 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1161 $_message = __('Explain SQL');
1162 $is_select = true;
1163 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1164 $explain_params['sql_query'] = substr($sql_query, 8);
1165 $_message = __('Skip Explain SQL');
1167 if (isset($explain_params['sql_query'])) {
1168 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1169 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1171 } //show explain
1173 $url_params['sql_query'] = $sql_query;
1174 $url_params['show_query'] = 1;
1176 // even if the query is big and was truncated, offer the chance
1177 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1178 if (! empty($cfg['SQLQuery']['Edit'])) {
1179 if ($cfg['EditInWindow'] == true) {
1180 $onclick = 'window.parent.focus_querywindow(\''
1181 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1182 } else {
1183 $onclick = '';
1186 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1187 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1188 } else {
1189 $edit_link = '';
1192 $url_qpart = PMA_generate_common_url($url_params);
1194 // Also we would like to get the SQL formed in some nice
1195 // php-code
1196 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1197 $php_params = $url_params;
1199 if (! empty($GLOBALS['show_as_php'])) {
1200 $_message = __('Without PHP Code');
1201 } else {
1202 $php_params['show_as_php'] = 1;
1203 $_message = __('Create PHP Code');
1206 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1207 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1209 if (isset($GLOBALS['show_as_php'])) {
1210 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1211 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1213 } else {
1214 $php_link = '';
1215 } //show as php
1217 // Refresh query
1218 if (! empty($cfg['SQLQuery']['Refresh'])
1219 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1220 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1222 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1223 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1224 } else {
1225 $refresh_link = '';
1226 } //refresh
1228 if (! empty($cfg['SQLValidator']['use'])
1229 && ! empty($cfg['SQLQuery']['Validate'])
1231 $validate_params = $url_params;
1232 if (!empty($GLOBALS['validatequery'])) {
1233 $validate_message = __('Skip Validate SQL');
1234 } else {
1235 $validate_params['validatequery'] = 1;
1236 $validate_message = __('Validate SQL');
1239 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1240 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1241 } else {
1242 $validate_link = '';
1243 } //validator
1245 if (!empty($GLOBALS['validatequery'])) {
1246 echo '<div class="sqlvalidate">';
1247 } else {
1248 echo '<code class="sql">';
1250 if ($query_too_big) {
1251 echo $shortened_query_base;
1252 } else {
1253 echo $query_base;
1256 //Clean up the end of the PHP
1257 if (! empty($GLOBALS['show_as_php'])) {
1258 echo '";';
1260 if (!empty($GLOBALS['validatequery'])) {
1261 echo '</div>';
1262 } else {
1263 echo '</code>';
1266 echo '<div class="tools">';
1267 // avoid displaying a Profiling checkbox that could
1268 // be checked, which would reexecute an INSERT, for example
1269 if (! empty($refresh_link)) {
1270 PMA_profilingCheckbox($sql_query);
1272 // if needed, generate an invisible form that contains controls for the
1273 // Inline link; this way, the behavior of the Inline link does not
1274 // depend on the profiling support or on the refresh link
1275 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1276 echo '<form action="sql.php" method="post">';
1277 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1278 echo '<input type="hidden" name="sql_query" value="'
1279 . htmlspecialchars($sql_query) . '" />';
1280 echo '</form>';
1283 // in the tools div, only display the Inline link when not in ajax
1284 // mode because 1) it currently does not work and 2) we would
1285 // have two similar mechanisms on the page for the same goal
1286 if ($is_select
1287 || $GLOBALS['is_ajax_request'] === false
1288 && ! $query_too_big
1290 // see in js/functions.js the jQuery code attached to id inline_edit
1291 // document.write conflicts with jQuery, hence used $().append()
1292 echo "<script type=\"text/javascript\">\n" .
1293 "//<![CDATA[\n" .
1294 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1295 PMA_escapeJsString(__('Inline edit of this query')) .
1296 "\" class=\"inline_edit_sql\">" .
1297 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1298 "</a>]');\n" .
1299 "//]]>\n" .
1300 "</script>";
1302 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1303 echo '</div>';
1305 echo '</div>';
1306 if ($GLOBALS['is_ajax_request'] === false) {
1307 echo '<br class="clearfloat" />';
1310 // If we are in an Ajax request, we have most probably been called in
1311 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1312 // to PMA_ajaxResponse(), which will encode it for JSON.
1313 if ($GLOBALS['is_ajax_request'] == true
1314 && ! isset($GLOBALS['buffer_message'])
1316 $buffer_contents = ob_get_contents();
1317 ob_end_clean();
1318 return $buffer_contents;
1320 return null;
1321 } // end of the 'PMA_showMessage()' function
1324 * Verifies if current MySQL server supports profiling
1326 * @access public
1328 * @return boolean whether profiling is supported
1330 function PMA_profilingSupported()
1332 if (! PMA_cacheExists('profiling_supported', true)) {
1333 // 5.0.37 has profiling but for example, 5.1.20 does not
1334 // (avoid a trip to the server for MySQL before 5.0.37)
1335 // and do not set a constant as we might be switching servers
1336 if (defined('PMA_MYSQL_INT_VERSION')
1337 && PMA_MYSQL_INT_VERSION >= 50037
1338 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1340 PMA_cacheSet('profiling_supported', true, true);
1341 } else {
1342 PMA_cacheSet('profiling_supported', false, true);
1346 return PMA_cacheGet('profiling_supported', true);
1350 * Displays a form with the Profiling checkbox
1352 * @param string $sql_query sql query
1354 * @access public
1356 function PMA_profilingCheckbox($sql_query)
1358 if (PMA_profilingSupported()) {
1359 echo '<form action="sql.php" method="post">' . "\n";
1360 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1361 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1362 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1363 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1364 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1365 echo '</form>' . "\n";
1370 * Formats $value to byte view
1372 * @param double $value the value to format
1373 * @param int $limes the sensitiveness
1374 * @param int $comma the number of decimals to retain
1376 * @return array the formatted value and its unit
1378 * @access public
1380 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1382 if ($value === null) {
1383 return null;
1386 $byteUnits = array(
1387 /* l10n: shortcuts for Byte */
1388 __('B'),
1389 /* l10n: shortcuts for Kilobyte */
1390 __('KiB'),
1391 /* l10n: shortcuts for Megabyte */
1392 __('MiB'),
1393 /* l10n: shortcuts for Gigabyte */
1394 __('GiB'),
1395 /* l10n: shortcuts for Terabyte */
1396 __('TiB'),
1397 /* l10n: shortcuts for Petabyte */
1398 __('PiB'),
1399 /* l10n: shortcuts for Exabyte */
1400 __('EiB')
1403 $dh = PMA_pow(10, $comma);
1404 $li = PMA_pow(10, $limes);
1405 $unit = $byteUnits[0];
1407 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1408 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1409 // use 1024.0 to avoid integer overflow on 64-bit machines
1410 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1411 $unit = $byteUnits[$d];
1412 break 1;
1413 } // end if
1414 } // end for
1416 if ($unit != $byteUnits[0]) {
1417 // if the unit is not bytes (as represented in current language)
1418 // reformat with max length of 5
1419 // 4th parameter=true means do not reformat if value < 1
1420 $return_value = PMA_formatNumber($value, 5, $comma, true);
1421 } else {
1422 // do not reformat, just handle the locale
1423 $return_value = PMA_formatNumber($value, 0);
1426 return array(trim($return_value), $unit);
1427 } // end of the 'PMA_formatByteDown' function
1430 * Changes thousands and decimal separators to locale specific values.
1432 * @param string $value the value
1434 * @return string
1436 function PMA_localizeNumber($value)
1438 return str_replace(
1439 array(',', '.'),
1440 array(
1441 /* l10n: Thousands separator */
1442 __(','),
1443 /* l10n: Decimal separator */
1444 __('.'),
1446 $value
1451 * Formats $value to the given length and appends SI prefixes
1452 * with a $length of 0 no truncation occurs, number is only formated
1453 * to the current locale
1455 * examples:
1456 * <code>
1457 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1458 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1459 * echo PMA_formatNumber(-0.003, 6); // -3 m
1460 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1461 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1462 * echo PMA_formatNumber(0, 6); // 0
1463 * </code>
1465 * @param double $value the value to format
1466 * @param integer $digits_left number of digits left of the comma
1467 * @param integer $digits_right number of digits right of the comma
1468 * @param boolean $only_down do not reformat numbers below 1
1469 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1470 * (default: true)
1472 * @return string the formatted value and its unit
1474 * @access public
1476 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1477 $only_down = false, $noTrailingZero = true)
1479 if ($value==0) {
1480 return '0';
1483 $originalValue = $value;
1484 //number_format is not multibyte safe, str_replace is safe
1485 if ($digits_left === 0) {
1486 $value = number_format($value, $digits_right);
1487 if ($originalValue != 0 && floatval($value) == 0) {
1488 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1491 return PMA_localizeNumber($value);
1494 // this units needs no translation, ISO
1495 $units = array(
1496 -8 => 'y',
1497 -7 => 'z',
1498 -6 => 'a',
1499 -5 => 'f',
1500 -4 => 'p',
1501 -3 => 'n',
1502 -2 => '&micro;',
1503 -1 => 'm',
1504 0 => ' ',
1505 1 => 'k',
1506 2 => 'M',
1507 3 => 'G',
1508 4 => 'T',
1509 5 => 'P',
1510 6 => 'E',
1511 7 => 'Z',
1512 8 => 'Y'
1515 // check for negative value to retain sign
1516 if ($value < 0) {
1517 $sign = '-';
1518 $value = abs($value);
1519 } else {
1520 $sign = '';
1523 $dh = PMA_pow(10, $digits_right);
1526 * This gives us the right SI prefix already,
1527 * but $digits_left parameter not incorporated
1529 $d = floor(log10($value) / 3);
1531 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1532 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1533 * to use, then lower the SI prefix
1535 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1536 if ($digits_left > $cur_digits) {
1537 $d-= floor(($digits_left - $cur_digits)/3);
1540 if ($d<0 && $only_down) {
1541 $d=0;
1544 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1545 $unit = $units[$d];
1547 // If we dont want any zeros after the comma just add the thousand seperator
1548 if ($noTrailingZero) {
1549 $value = PMA_localizeNumber(
1550 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1552 } else {
1553 //number_format is not multibyte safe, str_replace is safe
1554 $value = PMA_localizeNumber(number_format($value, $digits_right));
1557 if ($originalValue!=0 && floatval($value) == 0) {
1558 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1561 return $sign . $value . ' ' . $unit;
1562 } // end of the 'PMA_formatNumber' function
1565 * Returns the number of bytes when a formatted size is given
1567 * @param string $formatted_size the size expression (for example 8MB)
1569 * @return integer The numerical part of the expression (for example 8)
1571 function PMA_extractValueFromFormattedSize($formatted_size)
1573 $return_value = -1;
1575 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1576 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1577 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1578 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1579 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1580 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1582 return $return_value;
1583 }// end of the 'PMA_extractValueFromFormattedSize' function
1586 * Writes localised date
1588 * @param string $timestamp the current timestamp
1589 * @param string $format format
1591 * @return string the formatted date
1593 * @access public
1595 function PMA_localisedDate($timestamp = -1, $format = '')
1597 $month = array(
1598 /* l10n: Short month name */
1599 __('Jan'),
1600 /* l10n: Short month name */
1601 __('Feb'),
1602 /* l10n: Short month name */
1603 __('Mar'),
1604 /* l10n: Short month name */
1605 __('Apr'),
1606 /* l10n: Short month name */
1607 _pgettext('Short month name', 'May'),
1608 /* l10n: Short month name */
1609 __('Jun'),
1610 /* l10n: Short month name */
1611 __('Jul'),
1612 /* l10n: Short month name */
1613 __('Aug'),
1614 /* l10n: Short month name */
1615 __('Sep'),
1616 /* l10n: Short month name */
1617 __('Oct'),
1618 /* l10n: Short month name */
1619 __('Nov'),
1620 /* l10n: Short month name */
1621 __('Dec'));
1622 $day_of_week = array(
1623 /* l10n: Short week day name */
1624 _pgettext('Short week day name', 'Sun'),
1625 /* l10n: Short week day name */
1626 __('Mon'),
1627 /* l10n: Short week day name */
1628 __('Tue'),
1629 /* l10n: Short week day name */
1630 __('Wed'),
1631 /* l10n: Short week day name */
1632 __('Thu'),
1633 /* l10n: Short week day name */
1634 __('Fri'),
1635 /* l10n: Short week day name */
1636 __('Sat'));
1638 if ($format == '') {
1639 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1640 $format = __('%B %d, %Y at %I:%M %p');
1643 if ($timestamp == -1) {
1644 $timestamp = time();
1647 $date = preg_replace(
1648 '@%[aA]@',
1649 $day_of_week[(int)strftime('%w', $timestamp)],
1650 $format
1652 $date = preg_replace(
1653 '@%[bB]@',
1654 $month[(int)strftime('%m', $timestamp)-1],
1655 $date
1658 return strftime($date, $timestamp);
1659 } // end of the 'PMA_localisedDate()' function
1663 * returns a tab for tabbed navigation.
1664 * If the variables $link and $args ar left empty, an inactive tab is created
1666 * @param array $tab array with all options
1667 * @param array $url_params
1669 * @return string html code for one tab, a link if valid otherwise a span
1671 * @access public
1673 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1675 // default values
1676 $defaults = array(
1677 'text' => '',
1678 'class' => '',
1679 'active' => null,
1680 'link' => '',
1681 'sep' => '?',
1682 'attr' => '',
1683 'args' => '',
1684 'warning' => '',
1685 'fragment' => '',
1686 'id' => '',
1689 $tab = array_merge($defaults, $tab);
1691 // determine additionnal style-class
1692 if (empty($tab['class'])) {
1693 if (! empty($tab['active'])
1694 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1696 $tab['class'] = 'active';
1697 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1698 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1699 && empty($tab['warning'])) {
1700 $tab['class'] = 'active';
1704 if (!empty($tab['warning'])) {
1705 $tab['class'] .= ' error';
1706 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1709 // If there are any tab specific URL parameters, merge those with
1710 // the general URL parameters
1711 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1712 $url_params = array_merge($url_params, $tab['url_params']);
1715 // build the link
1716 if (!empty($tab['link'])) {
1717 $tab['link'] = htmlentities($tab['link']);
1718 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1719 if (! empty($tab['args'])) {
1720 foreach ($tab['args'] as $param => $value) {
1721 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1722 . '=' . urlencode($value);
1727 if (! empty($tab['fragment'])) {
1728 $tab['link'] .= $tab['fragment'];
1731 // display icon, even if iconic is disabled but the link-text is missing
1732 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1733 && isset($tab['icon'])
1735 // avoid generating an alt tag, because it only illustrates
1736 // the text that follows and if browser does not display
1737 // images, the text is duplicated
1738 $tab['text'] = PMA_getImage(htmlentities($tab['icon'])) . $tab['text'];
1740 } elseif (empty($tab['text'])) {
1741 // check to not display an empty link-text
1742 $tab['text'] = '?';
1743 trigger_error(
1744 'empty linktext in function ' . __FUNCTION__ . '()',
1745 E_USER_NOTICE
1749 //Set the id for the tab, if set in the params
1750 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1751 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1753 if (!empty($tab['link'])) {
1754 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1755 .$id_string
1756 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1757 . $tab['text'] . '</a>';
1758 } else {
1759 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1760 . $tab['text'] . '</span>';
1763 $out .= '</li>';
1764 return $out;
1765 } // end of the 'PMA_generate_html_tab()' function
1768 * returns html-code for a tab navigation
1770 * @param array $tabs one element per tab
1771 * @param string $url_params
1772 * @param string $base_dir
1773 * @param string $menu_id
1775 * @return string html-code for tab-navigation
1777 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='', $menu_id='topmenu')
1779 $tab_navigation = '<div id="' . htmlentities($menu_id) . 'container" class="menucontainer">'
1780 .'<ul id="' . htmlentities($menu_id) . '">';
1782 foreach ($tabs as $tab) {
1783 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1786 $tab_navigation .=
1787 '</ul>' . "\n"
1788 .'<div class="clearfloat"></div>'
1789 .'</div>' . "\n";
1791 return $tab_navigation;
1796 * Displays a link, or a button if the link's URL is too large, to
1797 * accommodate some browsers' limitations
1799 * @param string $url the URL
1800 * @param string $message the link message
1801 * @param mixed $tag_params string: js confirmation
1802 * array: additional tag params (f.e. style="")
1803 * @param boolean $new_form we set this to false when we are already in
1804 * a form, to avoid generating nested forms
1805 * @param boolean $strip_img whether to strip the image
1806 * @param string $target target
1808 * @return string the results to be echoed or saved in an array
1810 function PMA_linkOrButton($url, $message, $tag_params = array(),
1811 $new_form = true, $strip_img = false, $target = '')
1813 $url_length = strlen($url);
1814 // with this we should be able to catch case of image upload
1815 // into a (MEDIUM) BLOB; not worth generating even a form for these
1816 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1817 return '';
1821 if (! is_array($tag_params)) {
1822 $tmp = $tag_params;
1823 $tag_params = array();
1824 if (!empty($tmp)) {
1825 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1827 unset($tmp);
1829 if (! empty($target)) {
1830 $tag_params['target'] = htmlentities($target);
1833 $tag_params_strings = array();
1834 foreach ($tag_params as $par_name => $par_value) {
1835 // htmlspecialchars() only on non javascript
1836 $par_value = substr($par_name, 0, 2) == 'on'
1837 ? $par_value
1838 : htmlspecialchars($par_value);
1839 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1842 $displayed_message = '';
1843 // Add text if not already added
1844 if (stristr($message, '<img')
1845 && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
1846 && strip_tags($message)==$message
1848 $displayed_message = '<span>'
1849 . htmlspecialchars(
1850 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1852 . '</span>';
1855 // Suhosin: Check that each query parameter is not above maximum
1856 $in_suhosin_limits = true;
1857 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1858 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1859 $query_parts = PMA_splitURLQuery($url);
1860 foreach ($query_parts as $query_pair) {
1861 list($eachvar, $eachval) = explode('=', $query_pair);
1862 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1863 $in_suhosin_limits = false;
1864 break;
1870 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1871 // no whitespace within an <a> else Safari will make it part of the link
1872 $ret = "\n" . '<a href="' . $url . '" '
1873 . implode(' ', $tag_params_strings) . '>'
1874 . $message . $displayed_message . '</a>' . "\n";
1875 } else {
1876 // no spaces (linebreaks) at all
1877 // or after the hidden fields
1878 // IE will display them all
1880 // add class=link to submit button
1881 if (empty($tag_params['class'])) {
1882 $tag_params['class'] = 'link';
1885 if (! isset($query_parts)) {
1886 $query_parts = PMA_splitURLQuery($url);
1888 $url_parts = parse_url($url);
1890 if ($new_form) {
1891 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1892 . ' method="post"' . $target . ' style="display: inline;">';
1893 $subname_open = '';
1894 $subname_close = '';
1895 $submit_link = '#';
1896 } else {
1897 $query_parts[] = 'redirect=' . $url_parts['path'];
1898 if (empty($GLOBALS['subform_counter'])) {
1899 $GLOBALS['subform_counter'] = 0;
1901 $GLOBALS['subform_counter']++;
1902 $ret = '';
1903 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1904 $subname_close = ']';
1905 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1907 foreach ($query_parts as $query_pair) {
1908 list($eachvar, $eachval) = explode('=', $query_pair);
1909 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1910 . $subname_close . '" value="'
1911 . htmlspecialchars(urldecode($eachval)) . '" />';
1912 } // end while
1914 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1915 . implode(' ', $tag_params_strings) . '>'
1916 . $message . ' ' . $displayed_message . '</a>' . "\n";
1918 if ($new_form) {
1919 $ret .= '</form>';
1921 } // end if... else...
1923 return $ret;
1924 } // end of the 'PMA_linkOrButton()' function
1928 * Splits a URL string by parameter
1930 * @param string $url the URL
1932 * @return array the parameter/value pairs, for example [0] db=sakila
1934 function PMA_splitURLQuery($url)
1936 // decode encoded url separators
1937 $separator = PMA_get_arg_separator();
1938 // on most places separator is still hard coded ...
1939 if ($separator !== '&') {
1940 // ... so always replace & with $separator
1941 $url = str_replace(htmlentities('&'), $separator, $url);
1942 $url = str_replace('&', $separator, $url);
1944 $url = str_replace(htmlentities($separator), $separator, $url);
1945 // end decode
1947 $url_parts = parse_url($url);
1948 return explode($separator, $url_parts['query']);
1952 * Returns a given timespan value in a readable format.
1954 * @param int $seconds the timespan
1956 * @return string the formatted value
1958 function PMA_timespanFormat($seconds)
1960 $days = floor($seconds / 86400);
1961 if ($days > 0) {
1962 $seconds -= $days * 86400;
1964 $hours = floor($seconds / 3600);
1965 if ($days > 0 || $hours > 0) {
1966 $seconds -= $hours * 3600;
1968 $minutes = floor($seconds / 60);
1969 if ($days > 0 || $hours > 0 || $minutes > 0) {
1970 $seconds -= $minutes * 60;
1972 return sprintf(
1973 __('%s days, %s hours, %s minutes and %s seconds'),
1974 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1979 * Takes a string and outputs each character on a line for itself. Used
1980 * mainly for horizontalflipped display mode.
1981 * Takes care of special html-characters.
1982 * Fulfills todo-item
1983 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1985 * @param string $string The string
1986 * @param string $Separator The Separator (defaults to "<br />\n")
1988 * @access public
1989 * @todo add a multibyte safe function PMA_STR_split()
1991 * @return string The flipped string
1993 function PMA_flipstring($string, $Separator = "<br />\n")
1995 $format_string = '';
1996 $charbuff = false;
1998 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1999 $char = $string{$i};
2000 $append = false;
2002 if ($char == '&') {
2003 $format_string .= $charbuff;
2004 $charbuff = $char;
2005 } elseif ($char == ';' && !empty($charbuff)) {
2006 $format_string .= $charbuff . $char;
2007 $charbuff = false;
2008 $append = true;
2009 } elseif (! empty($charbuff)) {
2010 $charbuff .= $char;
2011 } else {
2012 $format_string .= $char;
2013 $append = true;
2016 // do not add separator after the last character
2017 if ($append && ($i != $str_len - 1)) {
2018 $format_string .= $Separator;
2022 return $format_string;
2026 * Function added to avoid path disclosures.
2027 * Called by each script that needs parameters, it displays
2028 * an error message and, by default, stops the execution.
2030 * Not sure we could use a strMissingParameter message here,
2031 * would have to check if the error message file is always available
2033 * @param array $params The names of the parameters needed by the calling script.
2034 * @param bool $die Stop the execution?
2035 * (Set this manually to false in the calling script
2036 * until you know all needed parameters to check).
2037 * @param bool $request Whether to include this list in checking for special params.
2039 * @global string path to current script
2040 * @global boolean flag whether any special variable was required
2042 * @access public
2043 * @todo use PMA_fatalError() if $die === true?
2045 function PMA_checkParameters($params, $die = true, $request = true)
2047 global $checked_special;
2049 if (! isset($checked_special)) {
2050 $checked_special = false;
2053 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2054 $found_error = false;
2055 $error_message = '';
2057 foreach ($params as $param) {
2058 if ($request && $param != 'db' && $param != 'table') {
2059 $checked_special = true;
2062 if (! isset($GLOBALS[$param])) {
2063 $error_message .= $reported_script_name
2064 . ': ' . __('Missing parameter:') . ' '
2065 . $param
2066 . PMA_showDocu('faqmissingparameters')
2067 . '<br />';
2068 $found_error = true;
2071 if ($found_error) {
2073 * display html meta tags
2075 include_once './libraries/header_meta_style.inc.php';
2076 echo '</head><body><p>' . $error_message . '</p></body></html>';
2077 if ($die) {
2078 exit();
2081 } // end function
2084 * Function to generate unique condition for specified row.
2086 * @param resource $handle current query result
2087 * @param integer $fields_cnt number of fields
2088 * @param array $fields_meta meta information about fields
2089 * @param array $row current row
2090 * @param boolean $force_unique generate condition only on pk or unique
2092 * @access public
2094 * @return array the calculated condition and whether condition is unique
2096 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2098 $primary_key = '';
2099 $unique_key = '';
2100 $nonprimary_condition = '';
2101 $preferred_condition = '';
2102 $primary_key_array = array();
2103 $unique_key_array = array();
2104 $nonprimary_condition_array = array();
2105 $condition_array = array();
2107 for ($i = 0; $i < $fields_cnt; ++$i) {
2108 $condition = '';
2109 $con_key = '';
2110 $con_val = '';
2111 $field_flags = PMA_DBI_field_flags($handle, $i);
2112 $meta = $fields_meta[$i];
2114 // do not use a column alias in a condition
2115 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2116 $meta->orgname = $meta->name;
2118 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2119 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2121 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2122 // need (string) === (string)
2123 // '' !== 0 but '' == 0
2124 if ((string) $select_expr['alias'] === (string) $meta->name) {
2125 $meta->orgname = $select_expr['column'];
2126 break;
2127 } // end if
2128 } // end foreach
2132 // Do not use a table alias in a condition.
2133 // Test case is:
2134 // select * from galerie x WHERE
2135 //(select count(*) from galerie y where y.datum=x.datum)>1
2137 // But orgtable is present only with mysqli extension so the
2138 // fix is only for mysqli.
2139 // Also, do not use the original table name if we are dealing with
2140 // a view because this view might be updatable.
2141 // (The isView() verification should not be costly in most cases
2142 // because there is some caching in the function).
2143 if (isset($meta->orgtable)
2144 && $meta->table != $meta->orgtable
2145 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2147 $meta->table = $meta->orgtable;
2150 // to fix the bug where float fields (primary or not)
2151 // can't be matched because of the imprecision of
2152 // floating comparison, use CONCAT
2153 // (also, the syntax "CONCAT(field) IS NULL"
2154 // that we need on the next "if" will work)
2155 if ($meta->type == 'real') {
2156 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2157 . PMA_backquote($meta->orgname) . ')';
2158 } else {
2159 $con_key = PMA_backquote($meta->table) . '.'
2160 . PMA_backquote($meta->orgname);
2161 } // end if... else...
2162 $condition = ' ' . $con_key . ' ';
2164 if (! isset($row[$i]) || is_null($row[$i])) {
2165 $con_val = 'IS NULL';
2166 } else {
2167 // timestamp is numeric on some MySQL 4.1
2168 // for real we use CONCAT above and it should compare to string
2169 if ($meta->numeric
2170 && $meta->type != 'timestamp'
2171 && $meta->type != 'real'
2173 $con_val = '= ' . $row[$i];
2174 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2175 // hexify only if this is a true not empty BLOB or a BINARY
2176 && stristr($field_flags, 'BINARY')
2177 && !empty($row[$i])) {
2178 // do not waste memory building a too big condition
2179 if (strlen($row[$i]) < 1000) {
2180 // use a CAST if possible, to avoid problems
2181 // if the field contains wildcard characters % or _
2182 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2183 } else {
2184 // this blob won't be part of the final condition
2185 $con_val = null;
2187 } elseif (in_array($meta->type, PMA_getGISDatatypes())
2188 && ! empty($row[$i])
2190 // do not build a too big condition
2191 if (strlen($row[$i]) < 5000) {
2192 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2193 } else {
2194 $condition = '';
2196 } elseif ($meta->type == 'bit') {
2197 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2198 } else {
2199 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2202 if ($con_val != null) {
2203 $condition .= $con_val . ' AND';
2204 if ($meta->primary_key > 0) {
2205 $primary_key .= $condition;
2206 $primary_key_array[$con_key] = $con_val;
2207 } elseif ($meta->unique_key > 0) {
2208 $unique_key .= $condition;
2209 $unique_key_array[$con_key] = $con_val;
2211 $nonprimary_condition .= $condition;
2212 $nonprimary_condition_array[$con_key] = $con_val;
2214 } // end for
2216 // Correction University of Virginia 19991216:
2217 // prefer primary or unique keys for condition,
2218 // but use conjunction of all values if no primary key
2219 $clause_is_unique = true;
2220 if ($primary_key) {
2221 $preferred_condition = $primary_key;
2222 $condition_array = $primary_key_array;
2223 } elseif ($unique_key) {
2224 $preferred_condition = $unique_key;
2225 $condition_array = $unique_key_array;
2226 } elseif (! $force_unique) {
2227 $preferred_condition = $nonprimary_condition;
2228 $condition_array = $nonprimary_condition_array;
2229 $clause_is_unique = false;
2232 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2233 return(array($where_clause, $clause_is_unique, $condition_array));
2234 } // end function
2237 * Generate a button or image tag
2239 * @param string $button_name name of button element
2240 * @param string $button_class class of button element
2241 * @param string $image_name name of image element
2242 * @param string $text text to display
2243 * @param string $image image to display
2244 * @param string $value value
2246 * @access public
2248 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2249 $image, $value = '')
2251 if ($value == '') {
2252 $value = $text;
2254 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2255 echo ' <input type="submit" name="' . $button_name . '"'
2256 .' value="' . htmlspecialchars($value) . '"'
2257 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2258 return;
2261 /* Opera has trouble with <input type="image"> */
2262 /* IE has trouble with <button> */
2263 if (PMA_USR_BROWSER_AGENT != 'IE') {
2264 echo '<button class="' . $button_class . '" type="submit"'
2265 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2266 .' title="' . htmlspecialchars($text) . '">' . "\n"
2267 . PMA_getIcon($image, $text)
2268 .'</button>' . "\n";
2269 } else {
2270 echo '<input type="image" name="' . $image_name
2271 . '" value="' . htmlspecialchars($value)
2272 . '" title="' . htmlspecialchars($text)
2273 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2274 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2275 ? '&nbsp;' . htmlspecialchars($text)
2276 : '') . "\n";
2278 } // end function
2281 * Generate a pagination selector for browsing resultsets
2283 * @param int $rows Number of rows in the pagination set
2284 * @param int $pageNow current page number
2285 * @param int $nbTotalPage number of total pages
2286 * @param int $showAll If the number of pages is lower than this
2287 * variable, no pages will be omitted in pagination
2288 * @param int $sliceStart How many rows at the beginning should always be shown?
2289 * @param int $sliceEnd How many rows at the end should always be shown?
2290 * @param int $percent Percentage of calculation page offsets to hop to a
2291 * next page
2292 * @param int $range Near the current page, how many pages should
2293 * be considered "nearby" and displayed as well?
2294 * @param string $prompt The prompt to display (sometimes empty)
2296 * @return string
2298 * @access public
2300 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2301 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2302 $range = 10, $prompt = '')
2304 $increment = floor($nbTotalPage / $percent);
2305 $pageNowMinusRange = ($pageNow - $range);
2306 $pageNowPlusRange = ($pageNow + $range);
2308 $gotopage = $prompt . ' <select id="pageselector" ';
2309 if ($GLOBALS['cfg']['AjaxEnable']) {
2310 $gotopage .= ' class="ajax"';
2312 $gotopage .= ' name="pos" >' . "\n";
2313 if ($nbTotalPage < $showAll) {
2314 $pages = range(1, $nbTotalPage);
2315 } else {
2316 $pages = array();
2318 // Always show first X pages
2319 for ($i = 1; $i <= $sliceStart; $i++) {
2320 $pages[] = $i;
2323 // Always show last X pages
2324 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2325 $pages[] = $i;
2328 // Based on the number of results we add the specified
2329 // $percent percentage to each page number,
2330 // so that we have a representing page number every now and then to
2331 // immediately jump to specific pages.
2332 // As soon as we get near our currently chosen page ($pageNow -
2333 // $range), every page number will be shown.
2334 $i = $sliceStart;
2335 $x = $nbTotalPage - $sliceEnd;
2336 $met_boundary = false;
2337 while ($i <= $x) {
2338 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2339 // If our pageselector comes near the current page, we use 1
2340 // counter increments
2341 $i++;
2342 $met_boundary = true;
2343 } else {
2344 // We add the percentage increment to our current page to
2345 // hop to the next one in range
2346 $i += $increment;
2348 // Make sure that we do not cross our boundaries.
2349 if ($i > $pageNowMinusRange && ! $met_boundary) {
2350 $i = $pageNowMinusRange;
2354 if ($i > 0 && $i <= $x) {
2355 $pages[] = $i;
2360 Add page numbers with "geometrically increasing" distances.
2362 This helps me a lot when navigating through giant tables.
2364 Test case: table with 2.28 million sets, 76190 pages. Page of interest is
2365 between 72376 and 76190.
2366 Selecting page 72376.
2367 Now, old version enumerated only +/- 10 pages around 72376 and the
2368 percentage increment produced steps of about 3000.
2370 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2371 around the current page.
2374 $i = $pageNow;
2375 $dist = 1;
2376 while ($i < $x) {
2377 $dist = 2 * $dist;
2378 $i = $pageNow + $dist;
2379 if ($i > 0 && $i <= $x) {
2380 $pages[] = $i;
2384 $i = $pageNow;
2385 $dist = 1;
2386 while ($i >0) {
2387 $dist = 2 * $dist;
2388 $i = $pageNow - $dist;
2389 if ($i > 0 && $i <= $x) {
2390 $pages[] = $i;
2394 // Since because of ellipsing of the current page some numbers may be double,
2395 // we unify our array:
2396 sort($pages);
2397 $pages = array_unique($pages);
2400 foreach ($pages as $i) {
2401 if ($i == $pageNow) {
2402 $selected = 'selected="selected" style="font-weight: bold"';
2403 } else {
2404 $selected = '';
2406 $gotopage .= ' <option ' . $selected
2407 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2410 $gotopage .= ' </select><noscript><input type="submit" value="'
2411 . __('Go') . '" /></noscript>';
2413 return $gotopage;
2414 } // end function
2418 * Generate navigation for a list
2420 * @param int $count number of elements in the list
2421 * @param int $pos current position in the list
2422 * @param array $_url_params url parameters
2423 * @param string $script script name for form target
2424 * @param string $frame target frame
2425 * @param int $max_count maximum number of elements to display from the list
2427 * @access public
2429 * @todo use $pos from $_url_params
2431 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2434 if ($max_count < $count) {
2435 echo 'frame_navigation' == $frame
2436 ? '<div id="navidbpageselector">' . "\n"
2437 : '';
2438 echo __('Page number:');
2439 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2441 // Move to the beginning or to the previous page
2442 if ($pos > 0) {
2443 // patch #474210 - part 1
2444 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2445 $caption1 = '&lt;&lt;';
2446 $caption2 = ' &lt; ';
2447 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2448 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2449 } else {
2450 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2451 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2452 $title1 = '';
2453 $title2 = '';
2454 } // end if... else...
2455 $_url_params['pos'] = 0;
2456 echo '<a' . $title1 . ' href="' . $script
2457 . PMA_generate_common_url($_url_params) . '" target="'
2458 . $frame . '">' . $caption1 . '</a>';
2459 $_url_params['pos'] = $pos - $max_count;
2460 echo '<a' . $title2 . ' href="' . $script
2461 . PMA_generate_common_url($_url_params) . '" target="'
2462 . $frame . '">' . $caption2 . '</a>';
2465 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2466 echo PMA_generate_common_hidden_inputs($_url_params);
2467 echo PMA_pageselector(
2468 $max_count,
2469 floor(($pos + 1) / $max_count) + 1,
2470 ceil($count / $max_count)
2472 echo '</form>';
2474 if ($pos + $max_count < $count) {
2475 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2476 $caption3 = ' &gt; ';
2477 $caption4 = '&gt;&gt;';
2478 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2479 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2480 } else {
2481 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2482 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2483 $title3 = '';
2484 $title4 = '';
2485 } // end if... else...
2486 $_url_params['pos'] = $pos + $max_count;
2487 echo '<a' . $title3 . ' href="' . $script
2488 . PMA_generate_common_url($_url_params) . '" target="'
2489 . $frame . '">' . $caption3 . '</a>';
2490 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2491 if ($_url_params['pos'] == $count) {
2492 $_url_params['pos'] = $count - $max_count;
2494 echo '<a' . $title4 . ' href="' . $script
2495 . PMA_generate_common_url($_url_params) . '" target="'
2496 . $frame . '">' . $caption4 . '</a>';
2498 echo "\n";
2499 if ('frame_navigation' == $frame) {
2500 echo '</div>' . "\n";
2506 * replaces %u in given path with current user name
2508 * example:
2509 * <code>
2510 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2512 * </code>
2514 * @param string $dir with wildcard for user
2516 * @return string per user directory
2518 function PMA_userDir($dir)
2520 // add trailing slash
2521 if (substr($dir, -1) != '/') {
2522 $dir .= '/';
2525 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2529 * returns html code for db link to default db page
2531 * @param string $database database
2533 * @return string html link to default db page
2535 function PMA_getDbLink($database = null)
2537 if (! strlen($database)) {
2538 if (! strlen($GLOBALS['db'])) {
2539 return '';
2541 $database = $GLOBALS['db'];
2542 } else {
2543 $database = PMA_unescape_mysql_wildcards($database);
2546 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2547 . PMA_generate_common_url($database) . '" title="'
2548 . sprintf(
2549 __('Jump to database &quot;%s&quot;.'),
2550 htmlspecialchars($database)
2552 . '">' . htmlspecialchars($database) . '</a>';
2556 * Displays a lightbulb hint explaining a known external bug
2557 * that affects a functionality
2559 * @param string $functionality localized message explaining the func.
2560 * @param string $component 'mysql' (eventually, 'php')
2561 * @param string $minimum_version of this component
2562 * @param string $bugref bug reference for this component
2564 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2566 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2567 echo PMA_showHint(
2568 sprintf(
2569 __('The %s functionality is affected by a known bug, see %s'),
2570 $functionality,
2571 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2578 * Generates and echoes an HTML checkbox
2580 * @param string $html_field_name the checkbox HTML field
2581 * @param string $label label for checkbox
2582 * @param boolean $checked is it initially checked?
2583 * @param boolean $onclick should it submit the form on click?
2585 * @return the HTML for the checkbox
2587 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2590 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2591 . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
2592 . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
2593 . $html_field_name . '">' . $label . '</label>';
2597 * Generates and echoes a set of radio HTML fields
2599 * @param string $html_field_name the radio HTML field
2600 * @param array $choices the choices values and labels
2601 * @param string $checked_choice the choice to check by default
2602 * @param boolean $line_break whether to add an HTML line break after a choice
2603 * @param boolean $escape_label whether to use htmlspecialchars() on label
2604 * @param string $class enclose each choice with a div of this class
2606 * @return the HTML for the tadio buttons
2608 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2609 $line_break = true, $escape_label = true, $class='')
2611 foreach ($choices as $choice_value => $choice_label) {
2612 if (! empty($class)) {
2613 echo '<div class="' . $class . '">';
2615 $html_field_id = $html_field_name . '_' . $choice_value;
2616 echo '<input type="radio" name="' . $html_field_name . '" id="'
2617 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2618 if ($choice_value == $checked_choice) {
2619 echo ' checked="checked"';
2621 echo ' />' . "\n";
2622 echo '<label for="' . $html_field_id . '">'
2623 . ($escape_label ? htmlspecialchars($choice_label) : $choice_label)
2624 . '</label>';
2625 if ($line_break) {
2626 echo '<br />';
2628 if (! empty($class)) {
2629 echo '</div>';
2631 echo "\n";
2636 * Generates and returns an HTML dropdown
2638 * @param string $select_name name for the select element
2639 * @param array $choices choices values
2640 * @param string $active_choice the choice to select by default
2641 * @param string $id id of the select element; can be different in case
2642 * the dropdown is present more than once on the page
2644 * @return string
2646 * @todo support titles
2648 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2650 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2651 . htmlspecialchars($id) . '">';
2652 foreach ($choices as $one_choice_value => $one_choice_label) {
2653 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2654 if ($one_choice_value == $active_choice) {
2655 $result .= ' selected="selected"';
2657 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2659 $result .= '</select>';
2660 return $result;
2664 * Generates a slider effect (jQjuery)
2665 * Takes care of generating the initial <div> and the link
2666 * controlling the slider; you have to generate the </div> yourself
2667 * after the sliding section.
2669 * @param string $id the id of the <div> on which to apply the effect
2670 * @param string $message the message to show as a link
2672 function PMA_generate_slider_effect($id, $message)
2674 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2675 echo '<div id="' . $id . '">';
2676 return;
2679 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2680 * opening the <div> with PHP itself instead of JavaScript.
2682 * @todo find a better solution that uses $.append(), the recommended method
2683 * maybe by using an additional param, the id of the div to append to
2686 <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); ?>">
2687 <?php
2691 * Creates an AJAX sliding toggle button
2692 * (or and equivalent form when AJAX is disabled)
2694 * @param string $action The URL for the request to be executed
2695 * @param string $select_name The name for the dropdown box
2696 * @param array $options An array of options (see rte_footer.lib.php)
2697 * @param string $callback A JS snippet to execute when the request is
2698 * successfully processed
2700 * @return string HTML code for the toggle button
2702 function PMA_toggleButton($action, $select_name, $options, $callback)
2704 // Do the logic first
2705 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2706 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2707 if ($options[1]['selected'] == true) {
2708 $state = 'on';
2709 } else if ($options[0]['selected'] == true) {
2710 $state = 'off';
2711 } else {
2712 $state = 'on';
2714 $selected1 = '';
2715 $selected0 = '';
2716 if ($options[1]['selected'] == true) {
2717 $selected1 = " selected='selected'";
2718 } else if ($options[0]['selected'] == true) {
2719 $selected0 = " selected='selected'";
2721 // Generate output
2722 $retval = "<!-- TOGGLE START -->\n";
2723 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2724 $retval .= "<noscript>\n";
2726 $retval .= "<div class='wrapper'>\n";
2727 $retval .= " <form action='$action' method='post'>\n";
2728 $retval .= " <select name='$select_name'>\n";
2729 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2730 $retval .= " {$options[1]['label']}\n";
2731 $retval .= " </option>\n";
2732 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2733 $retval .= " {$options[0]['label']}\n";
2734 $retval .= " </option>\n";
2735 $retval .= " </select>\n";
2736 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2737 $retval .= " </form>\n";
2738 $retval .= "</div>\n";
2739 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2740 $retval .= "</noscript>\n";
2741 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2742 $retval .= " <div class='toggleButton'>\n";
2743 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2744 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2745 $retval .= " alt='' />\n";
2746 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2747 $retval .= " <tbody>\n";
2748 $retval .= " <td class='toggleOn'>\n";
2749 $retval .= " <span class='hide'>$link_on</span>\n";
2750 $retval .= " <div>";
2751 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2752 $retval .= " </td>\n";
2753 $retval .= " <td><div>&nbsp;</div></td>\n";
2754 $retval .= " <td class='toggleOff'>\n";
2755 $retval .= " <span class='hide'>$link_off</span>\n";
2756 $retval .= " <div>";
2757 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2758 $retval .= " </div>\n";
2759 $retval .= " </tbody>\n";
2760 $retval .= " </tr></table>\n";
2761 $retval .= " <span class='hide callback'>$callback</span>\n";
2762 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2763 $retval .= " </div>\n";
2764 $retval .= " </div>\n";
2765 $retval .= "</div>\n";
2767 $retval .= "<!-- TOGGLE END -->";
2769 return $retval;
2770 } // end PMA_toggleButton()
2773 * Clears cache content which needs to be refreshed on user change.
2775 * @return nothing
2777 function PMA_clearUserCache()
2779 PMA_cacheUnset('is_superuser', true);
2783 * Verifies if something is cached in the session
2785 * @param string $var variable name
2786 * @param int|true $server server
2788 * @return boolean
2790 function PMA_cacheExists($var, $server = 0)
2792 if (true === $server) {
2793 $server = $GLOBALS['server'];
2795 return isset($_SESSION['cache']['server_' . $server][$var]);
2799 * Gets cached information from the session
2801 * @param string $var varibale name
2802 * @param int|true $server server
2804 * @return mixed
2806 function PMA_cacheGet($var, $server = 0)
2808 if (true === $server) {
2809 $server = $GLOBALS['server'];
2811 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2812 return $_SESSION['cache']['server_' . $server][$var];
2813 } else {
2814 return null;
2819 * Caches information in the session
2821 * @param string $var variable name
2822 * @param mixed $val value
2823 * @param int|true $server server
2825 * @return mixed
2827 function PMA_cacheSet($var, $val = null, $server = 0)
2829 if (true === $server) {
2830 $server = $GLOBALS['server'];
2832 $_SESSION['cache']['server_' . $server][$var] = $val;
2836 * Removes cached information from the session
2838 * @param string $var variable name
2839 * @param int|true $server server
2841 * @return nothing
2843 function PMA_cacheUnset($var, $server = 0)
2845 if (true === $server) {
2846 $server = $GLOBALS['server'];
2848 unset($_SESSION['cache']['server_' . $server][$var]);
2852 * Converts a bit value to printable format;
2853 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2854 * function because in PHP, decbin() supports only 32 bits
2856 * @param numeric $value coming from a BIT field
2857 * @param integer $length length
2859 * @return string the printable value
2861 function PMA_printable_bit_value($value, $length)
2863 $printable = '';
2864 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2865 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2867 $printable = substr($printable, -$length);
2868 return $printable;
2872 * Verifies whether the value contains a non-printable character
2874 * @param string $value value
2876 * @return boolean
2878 function PMA_contains_nonprintable_ascii($value)
2880 return preg_match('@[^[:print:]]@', $value);
2884 * Converts a BIT type default value
2885 * for example, b'010' becomes 010
2887 * @param string $bit_default_value value
2889 * @return string the converted value
2891 function PMA_convert_bit_default_value($bit_default_value)
2893 return strtr($bit_default_value, array("b" => "", "'" => ""));
2897 * Extracts the various parts from a field type spec
2899 * @param string $fieldspec Field specification
2901 * @return array associative array containing type, spec_in_brackets
2902 * and possibly enum_set_values (another array)
2904 function PMA_extractFieldSpec($fieldspec)
2906 $first_bracket_pos = strpos($fieldspec, '(');
2907 if ($first_bracket_pos) {
2908 $spec_in_brackets = chop(
2909 substr(
2910 $fieldspec,
2911 $first_bracket_pos + 1,
2912 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2915 // convert to lowercase just to be sure
2916 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2917 } else {
2918 $type = strtolower($fieldspec);
2919 $spec_in_brackets = '';
2922 if ('enum' == $type || 'set' == $type) {
2923 // Define our working vars
2924 $enum_set_values = array();
2925 $working = "";
2926 $in_string = false;
2927 $index = 0;
2929 // While there is another character to process
2930 while (isset($fieldspec[$index])) {
2931 // Grab the char to look at
2932 $char = $fieldspec[$index];
2934 // If it is a single quote, needs to be handled specially
2935 if ($char == "'") {
2936 // If we are not currently in a string, begin one
2937 if (! $in_string) {
2938 $in_string = true;
2939 $working = "";
2940 } else {
2941 // Otherwise, it may be either an end of a string,
2942 // or a 'double quote' which can be handled as-is
2943 // Check out the next character (if possible)
2944 $has_next = isset($fieldspec[$index + 1]);
2945 $next = $has_next ? $fieldspec[$index + 1] : null;
2947 //If we have reached the end of our 'working' string (because
2948 //there are no more chars,or the next char is not another quote)
2949 if (! $has_next || $next != "'") {
2950 $enum_set_values[] = $working;
2951 $in_string = false;
2953 } elseif ($next == "'") {
2954 // Otherwise, this is a 'double quote',
2955 // and can be added to the working string
2956 $working .= "'";
2957 // Skip the next char; we already know what it is
2958 $index++;
2961 } elseif ('\\' == $char
2962 && isset($fieldspec[$index + 1])
2963 && "'" == $fieldspec[$index + 1]
2965 // escaping of a quote?
2966 $working .= "'";
2967 $index++;
2968 } else {
2969 // Otherwise, add it to our working string like normal
2970 $working .= $char;
2972 // Increment character index
2973 $index++;
2974 } // end while
2975 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2976 $binary = false;
2977 $unsigned = false;
2978 $zerofill = false;
2979 } else {
2980 $enum_set_values = array();
2982 /* Create printable type name */
2983 $printtype = strtolower($fieldspec);
2985 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2986 // this would be a BINARY or VARBINARY field type;
2987 // by the way, a BLOB should not show the BINARY attribute
2988 // because this is not accepted in MySQL syntax.
2989 if (preg_match('@binary@', $printtype) && ! preg_match('@binary[\(]@', $printtype)) {
2990 $printtype = preg_replace('@binary@', '', $printtype);
2991 $binary = true;
2992 } else {
2993 $binary = false;
2995 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2996 $zerofill = ($zerofill_cnt > 0);
2997 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
2998 $unsigned = ($unsigned_cnt > 0);
2999 $printtype = trim($printtype);
3003 $attribute = ' ';
3004 if ($binary) {
3005 $attribute = 'BINARY';
3007 if ($unsigned) {
3008 $attribute = 'UNSIGNED';
3010 if ($zerofill) {
3011 $attribute = 'UNSIGNED ZEROFILL';
3014 return array(
3015 'type' => $type,
3016 'spec_in_brackets' => $spec_in_brackets,
3017 'enum_set_values' => $enum_set_values,
3018 'print_type' => $printtype,
3019 'binary' => $binary,
3020 'unsigned' => $unsigned,
3021 'zerofill' => $zerofill,
3022 'attribute' => $attribute,
3027 * Verifies if this table's engine supports foreign keys
3029 * @param string $engine engine
3031 * @return boolean
3033 function PMA_foreignkey_supported($engine)
3035 $engine = strtoupper($engine);
3036 if ('INNODB' == $engine || 'PBXT' == $engine) {
3037 return true;
3038 } else {
3039 return false;
3044 * Replaces some characters by a displayable equivalent
3046 * @param string $content content
3048 * @return string the content with characters replaced
3050 function PMA_replace_binary_contents($content)
3052 $result = str_replace("\x00", '\0', $content);
3053 $result = str_replace("\x08", '\b', $result);
3054 $result = str_replace("\x0a", '\n', $result);
3055 $result = str_replace("\x0d", '\r', $result);
3056 $result = str_replace("\x1a", '\Z', $result);
3057 return $result;
3061 * Converts GIS data to Well Known Text format
3063 * @param binary $data GIS data
3064 * @param bool $includeSRID Add SRID to the WKT
3066 * @return GIS data in Well Know Text format
3068 function PMA_asWKT($data, $includeSRID = false)
3070 // Convert to WKT format
3071 $hex = bin2hex($data);
3072 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3073 if ($includeSRID) {
3074 $wktsql .= ", SRID(x'" . $hex . "')";
3076 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
3077 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
3078 $wktval = $wktarr[0];
3079 if ($includeSRID) {
3080 $srid = $wktarr[1];
3081 $wktval = "'" . $wktval . "'," . $srid;
3083 @PMA_DBI_free_result($wktresult);
3084 return $wktval;
3088 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3090 * @param string $string string
3092 * @return string with the chars replaced
3095 function PMA_duplicateFirstNewline($string)
3097 $first_occurence = strpos($string, "\r\n");
3098 if ($first_occurence === 0) {
3099 $string = "\n".$string;
3101 return $string;
3105 * Get the action word corresponding to a script name
3106 * in order to display it as a title in navigation panel
3108 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3109 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3111 * @return array
3113 function PMA_getTitleForTarget($target)
3115 $mapping = array(
3116 // Values for $cfg['DefaultTabTable']
3117 'tbl_structure.php' => __('Structure'),
3118 'tbl_sql.php' => __('SQL'),
3119 'tbl_select.php' =>__('Search'),
3120 'tbl_change.php' =>__('Insert'),
3121 'sql.php' => __('Browse'),
3123 // Values for $cfg['DefaultTabDatabase']
3124 'db_structure.php' => __('Structure'),
3125 'db_sql.php' => __('SQL'),
3126 'db_search.php' => __('Search'),
3127 'db_operations.php' => __('Operations'),
3129 return $mapping[$target];
3133 * Formats user string, expanding @VARIABLES@, accepting strftime format string.
3135 * @param string $string Text where to do expansion.
3136 * @param function $escape Function to call for escaping variable values.
3137 * @param array $updates Array with overrides for default parameters
3138 * (obtained from GLOBALS).
3140 * @return string
3142 function PMA_expandUserString($string, $escape = null, $updates = array())
3144 /* Content */
3145 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
3146 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3147 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3148 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3149 ? $GLOBALS['cfg']['Server']['verbose']
3150 : $GLOBALS['cfg']['Server']['host'];
3151 $vars['database'] = $GLOBALS['db'];
3152 $vars['table'] = $GLOBALS['table'];
3153 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3155 /* Update forced variables */
3156 foreach ($updates as $key => $val) {
3157 $vars[$key] = $val;
3160 /* Replacement mapping */
3162 * The __VAR__ ones are for backward compatibility, because user
3163 * might still have it in cookies.
3165 $replace = array(
3166 '@HTTP_HOST@' => $vars['http_host'],
3167 '@SERVER@' => $vars['server_name'],
3168 '__SERVER__' => $vars['server_name'],
3169 '@VERBOSE@' => $vars['server_verbose'],
3170 '@VSERVER@' => $vars['server_verbose_or_name'],
3171 '@DATABASE@' => $vars['database'],
3172 '__DB__' => $vars['database'],
3173 '@TABLE@' => $vars['table'],
3174 '__TABLE__' => $vars['table'],
3175 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3178 /* Optional escaping */
3179 if (!is_null($escape)) {
3180 foreach ($replace as $key => $val) {
3181 $replace[$key] = $escape($val);
3185 /* Backward compatibility in 3.5.x */
3186 if (strpos($string, '@FIELDS@') !== false) {
3187 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3190 /* Fetch columns list if required */
3191 if (strpos($string, '@COLUMNS@') !== false) {
3192 $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3194 $column_names = array();
3195 foreach ($columns_list as $column) {
3196 if (! is_null($escape)) {
3197 $column_names[] = $escape($column['Field']);
3198 } else {
3199 $column_names[] = $field['Field'];
3203 $replace['@COLUMNS@'] = implode(',', $column_names);
3206 /* Do the replacement */
3207 return strtr(strftime($string), $replace);
3211 * function that generates a json output for an ajax request and ends script
3212 * execution
3214 * @param PMA_Message|string $message message string containing the
3215 * html of the message
3216 * @param bool $success success whether the ajax request
3217 * was successfull
3218 * @param array $extra_data extra data optional -
3219 * any other data as part of the json request
3221 * @return nothing
3223 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3225 $response = array();
3226 if ( $success == true ) {
3227 $response['success'] = true;
3228 if ($message instanceof PMA_Message) {
3229 $response['message'] = $message->getDisplay();
3230 } else {
3231 $response['message'] = $message;
3233 } else {
3234 $response['success'] = false;
3235 if ($message instanceof PMA_Message) {
3236 $response['error'] = $message->getDisplay();
3237 } else {
3238 $response['error'] = $message;
3242 // If extra_data has been provided, append it to the response array
3243 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3244 $response = array_merge($response, $extra_data);
3247 // Set the Content-Type header to JSON so that jQuery parses the
3248 // response correctly.
3250 // At this point, other headers might have been sent;
3251 // even if $GLOBALS['is_header_sent'] is true,
3252 // we have to send these additional headers.
3253 header('Cache-Control: no-cache');
3254 header("Content-Type: application/json");
3256 echo json_encode($response);
3258 if (!defined('TESTSUITE'))
3259 exit;
3263 * Display the form used to browse anywhere on the local server for a file to import
3265 * @param string $max_upload_size maximum upload size
3267 * @return nothing
3269 function PMA_browseUploadFile($max_upload_size)
3271 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3272 echo '<div id="upload_form_status" style="display: none;"></div>';
3273 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3274 echo '<input type="file" name="import_file" id="input_import_file" />';
3275 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3276 // some browsers should respect this :)
3277 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3281 * Display the form used to select a file to import from the server upload directory
3283 * @param array $import_list array of import types
3284 * @param string $uploaddir upload directory
3286 * @return nothing
3288 function PMA_selectUploadFile($import_list, $uploaddir)
3290 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3291 $extensions = '';
3292 foreach ($import_list as $key => $val) {
3293 if (!empty($extensions)) {
3294 $extensions .= '|';
3296 $extensions .= $val['extension'];
3298 $matcher = '@\.(' . $extensions . ')(\.('
3299 . PMA_supportedDecompressions() . '))?$@';
3301 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3302 ? $local_import_file
3303 : '';
3304 $files = PMA_getFileSelectOptions(
3305 PMA_userDir($uploaddir),
3306 $matcher,
3307 $active
3309 if ($files === false) {
3310 PMA_Message::error(
3311 __('The directory you set for upload work cannot be reached')
3312 )->display();
3313 } elseif (!empty($files)) {
3314 echo "\n";
3315 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3316 echo ' <option value="">&nbsp;</option>' . "\n";
3317 echo $files;
3318 echo ' </select>' . "\n";
3319 } elseif (empty ($files)) {
3320 echo '<i>' . __('There are no files to upload') . '</i>';
3325 * Build titles and icons for action links
3327 * @return array the action titles
3329 function PMA_buildActionTitles()
3331 $titles = array();
3333 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3334 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3335 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3336 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3337 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3338 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3339 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3340 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3341 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3342 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3343 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3344 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3345 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3346 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3347 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3348 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3349 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3350 return $titles;
3354 * This function processes the datatypes supported by the DB, as specified in
3355 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3356 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3358 * @param bool $html Whether to generate an html snippet or an array
3359 * @param string $selected The value to mark as selected in HTML mode
3361 * @return mixed An HTML snippet or an array of datatypes.
3364 function PMA_getSupportedDatatypes($html = false, $selected = '')
3366 global $cfg;
3368 if ($html) {
3369 // NOTE: the SELECT tag in not included in this snippet.
3370 $retval = '';
3371 foreach ($cfg['ColumnTypes'] as $key => $value) {
3372 if (is_array($value)) {
3373 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3374 foreach ($value as $subvalue) {
3375 if ($subvalue == $selected) {
3376 $retval .= "<option selected='selected'>";
3377 $retval .= $subvalue;
3378 $retval .= "</option>";
3379 } else if ($subvalue === '-') {
3380 $retval .= "<option disabled='disabled'>";
3381 $retval .= $subvalue;
3382 $retval .= "</option>";
3383 } else {
3384 $retval .= "<option>$subvalue</option>";
3387 $retval .= '</optgroup>';
3388 } else {
3389 if ($selected == $value) {
3390 $retval .= "<option selected='selected'>$value</option>";
3391 } else {
3392 $retval .= "<option>$value</option>";
3396 } else {
3397 $retval = array();
3398 foreach ($cfg['ColumnTypes'] as $value) {
3399 if (is_array($value)) {
3400 foreach ($value as $subvalue) {
3401 if ($subvalue !== '-') {
3402 $retval[] = $subvalue;
3405 } else {
3406 if ($value !== '-') {
3407 $retval[] = $value;
3413 return $retval;
3414 } // end PMA_getSupportedDatatypes()
3417 * Returns a list of datatypes that are not (yet) handled by PMA.
3418 * Used by: tbl_change.php and libraries/db_routines.inc.php
3420 * @return array list of datatypes
3422 function PMA_unsupportedDatatypes()
3424 $no_support_types = array();
3425 return $no_support_types;
3429 * Return GIS data types
3431 * @param bool $upper_case whether to return values in upper case
3433 * @return array GIS data types
3435 function PMA_getGISDatatypes($upper_case = false)
3437 $gis_data_types = array(
3438 'geometry',
3439 'point',
3440 'linestring',
3441 'polygon',
3442 'multipoint',
3443 'multilinestring',
3444 'multipolygon',
3445 'geometrycollection'
3447 if ($upper_case) {
3448 for ($i = 0; $i < count($gis_data_types); $i++) {
3449 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3453 return $gis_data_types;
3457 * Generates GIS data based on the string passed.
3459 * @param string $gis_string GIS string
3461 * @return GIS data enclosed in 'GeomFromText' function
3463 function PMA_createGISData($gis_string)
3465 $gis_string = trim($gis_string);
3466 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3467 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3468 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3469 return 'GeomFromText(' . $gis_string . ')';
3470 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3471 return "GeomFromText('" . $gis_string . "')";
3472 } else {
3473 return $gis_string;
3478 * Returns the names and details of the functions
3479 * that can be applied on geometry data typess.
3481 * @param string $geom_type if provided the output is limited to the functions
3482 * that are applicable to the provided geometry type.
3483 * @param bool $binary if set to false functions that take two geometries
3484 * as arguments will not be included.
3485 * @param bool $display if set to true seperators will be added to the
3486 * output array.
3488 * @return array names and details of the functions that can be applied on
3489 * geometry data typess.
3491 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3493 $funcs = array();
3494 if ($display) {
3495 $funcs[] = array('display' => ' ');
3498 // Unary functions common to all geomety types
3499 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3500 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3501 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3502 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3503 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3504 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3506 $geom_type = trim(strtolower($geom_type));
3507 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3508 $funcs[] = array('display' => '--------');
3511 // Unary functions that are specific to each geomety type
3512 if ($geom_type == 'point') {
3513 $funcs['X'] = array('params' => 1, 'type' => 'float');
3514 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3516 } elseif ($geom_type == 'multipoint') {
3517 // no fucntions here
3518 } elseif ($geom_type == 'linestring') {
3519 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3520 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3521 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3522 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3523 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3525 } elseif ($geom_type == 'multilinestring') {
3526 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3527 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3529 } elseif ($geom_type == 'polygon') {
3530 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3531 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3532 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3534 } elseif ($geom_type == 'multipolygon') {
3535 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3536 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3537 // Not yet implemented in MySQL
3538 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3540 } elseif ($geom_type == 'geometrycollection') {
3541 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3544 // If we are asked for binary functions as well
3545 if ($binary) {
3546 // section seperator
3547 if ($display) {
3548 $funcs[] = array('display' => '--------');
3550 if (PMA_MYSQL_INT_VERSION < 50601) {
3551 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3552 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3553 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3554 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3555 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3556 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3557 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3558 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3559 } else {
3560 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3561 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3562 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3563 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3564 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3565 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3566 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3567 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3568 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3572 if ($display) {
3573 $funcs[] = array('display' => '--------');
3575 // Minimum bounding rectangle functions
3576 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3577 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3578 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3579 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3580 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3581 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3582 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3584 return $funcs;
3588 * Creates a dropdown box with MySQL functions for a particular column.
3590 * @param array $field Data about the column for which
3591 * to generate the dropdown
3592 * @param bool $insert_mode Whether the operation is 'insert'
3594 * @global array $cfg PMA configuration
3595 * @global array $analyzed_sql Analyzed SQL query
3596 * @global mixed $data (null/string) FIXME: what is this for?
3598 * @return string An HTML snippet of a dropdown list with function
3599 * names appropriate for the requested column.
3601 function PMA_getFunctionsForField($field, $insert_mode)
3603 global $cfg, $analyzed_sql, $data;
3605 $selected = '';
3606 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3607 // or something similar. Then directly look up the entry in the
3608 // RestrictFunctions array, which'll then reveal the available dropdown options
3609 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3610 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3612 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3613 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3614 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3615 } else {
3616 $dropdown = array();
3617 $default_function = '';
3619 $dropdown_built = array();
3620 $op_spacing_needed = false;
3621 // what function defined as default?
3622 // for the first timestamp we don't set the default function
3623 // if there is a default value for the timestamp
3624 // (not including CURRENT_TIMESTAMP)
3625 // and the column does not have the
3626 // ON UPDATE DEFAULT TIMESTAMP attribute.
3627 if ($field['True_Type'] == 'timestamp'
3628 && empty($field['Default'])
3629 && empty($data)
3630 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3632 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3634 // For primary keys of type char(36) or varchar(36) UUID if the default function
3635 // Only applies to insert mode, as it would silently trash data on updates.
3636 if ($insert_mode
3637 && $field['Key'] == 'PRI'
3638 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3640 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3642 // this is set only when appropriate and is always true
3643 if (isset($field['display_binary_as_hex'])) {
3644 $default_function = 'UNHEX';
3647 // Create the output
3648 $retval = ' <option></option>' . "\n";
3649 // loop on the dropdown array and print all available options for that field.
3650 foreach ($dropdown as $each_dropdown) {
3651 $retval .= ' ';
3652 $retval .= '<option';
3653 if ($default_function === $each_dropdown) {
3654 $retval .= ' selected="selected"';
3656 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3657 $dropdown_built[$each_dropdown] = 'true';
3658 $op_spacing_needed = true;
3660 // For compatibility's sake, do not let out all other functions. Instead
3661 // print a separator (blank) and then show ALL functions which weren't shown
3662 // yet.
3663 $cnt_functions = count($cfg['Functions']);
3664 for ($j = 0; $j < $cnt_functions; $j++) {
3665 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3666 || $dropdown_built[$cfg['Functions'][$j]] != 'true'
3668 // Is current function defined as default?
3669 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3670 || (! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3671 ? ' selected="selected"'
3672 : '';
3673 if ($op_spacing_needed == true) {
3674 $retval .= ' ';
3675 $retval .= '<option value="">--------</option>' . "\n";
3676 $op_spacing_needed = false;
3679 $retval .= ' ';
3680 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3681 . '</option>' . "\n";
3683 } // end for
3685 return $retval;
3686 } // end PMA_getFunctionsForField()
3689 * Checks if the current user has a specific privilege and returns true if the
3690 * user indeed has that privilege or false if (s)he doesn't. This function must
3691 * only be used for features that are available since MySQL 5, because it
3692 * relies on the INFORMATION_SCHEMA database to be present.
3694 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3695 * // Checks if the currently logged in user has the global
3696 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3697 * // user has this privilege on database 'mydb'.
3699 * @param string $priv The privilege to check
3700 * @param mixed $db null, to only check global privileges
3701 * string, db name where to also check for privileges
3702 * @param mixed $tbl null, to only check global privileges
3703 * string, db name where to also check for privileges
3705 * @return bool
3707 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3709 // Get the username for the current user in the format
3710 // required to use in the information schema database.
3711 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3712 if ($user === false) {
3713 return false;
3715 $user = explode('@', $user);
3716 $username = "''";
3717 $username .= str_replace("'", "''", $user[0]);
3718 $username .= "''@''";
3719 $username .= str_replace("'", "''", $user[1]);
3720 $username .= "''";
3721 // Prepage the query
3722 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3723 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3724 // Check global privileges first.
3725 if (PMA_DBI_fetch_value(
3726 sprintf(
3727 $query,
3728 'USER_PRIVILEGES',
3729 $username,
3730 $priv
3734 return true;
3736 // If a database name was provided and user does not have the
3737 // required global privilege, try database-wise permissions.
3738 if ($db !== null) {
3739 $query .= " AND TABLE_SCHEMA='%s'";
3740 if (PMA_DBI_fetch_value(
3741 sprintf(
3742 $query,
3743 'SCHEMA_PRIVILEGES',
3744 $username,
3745 $priv,
3746 PMA_sqlAddSlashes($db)
3750 return true;
3752 } else {
3753 // There was no database name provided and the user
3754 // does not have the correct global privilege.
3755 return false;
3757 // If a table name was also provided and we still didn't
3758 // find any valid privileges, try table-wise privileges.
3759 if ($tbl !== null) {
3760 $query .= " AND TABLE_NAME='%s'";
3761 if ($retval = PMA_DBI_fetch_value(
3762 sprintf(
3763 $query,
3764 'TABLE_PRIVILEGES',
3765 $username,
3766 $priv,
3767 PMA_sqlAddSlashes($db),
3768 PMA_sqlAddSlashes($tbl)
3772 return true;
3775 // If we reached this point, the user does not
3776 // have even valid table-wise privileges.
3777 return false;
3781 * Returns server type for current connection
3783 * Known types are: Drizzle, MariaDB and MySQL (default)
3785 * @return string
3787 function PMA_getServerType()
3789 $server_type = 'MySQL';
3790 if (PMA_DRIZZLE) {
3791 $server_type = 'Drizzle';
3792 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3793 $server_type = 'MariaDB';
3794 } else if (stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3795 $server_type = 'Percona Server';
3797 return $server_type;
3801 * Analyzes the limit clause and return the start and length attributes of it.
3803 * @param string $limit_clause limit clause
3805 * @return array Start and length attributes of the limit clause
3807 function PMA_analyzeLimitClause($limit_clause)
3809 $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
3810 return array(
3811 'start' => trim($start_and_length[0]),
3812 'length' => trim($start_and_length[1])
3817 * Outputs HTML code for print button.
3819 * @return nothing
3821 function PMA_printButton()
3823 echo '<p class="print_ignore">';
3824 echo '<input type="button" id="print" value="' . __('Print') . '" />';
3825 echo '</p>';