Translation update done using Pootle.
[phpmyadmin.git] / libraries / common.lib.php
blobc1463bb7c2daaff5a372d707fe19f9fa9b379422
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['Comment'] = $table['Name'];
827 $table['disp_name'] = $table['Comment'];
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);
1069 if (PMA_SQP_isError()) {
1070 unset($parsed_sql);
1074 // Analyze it
1075 if (isset($parsed_sql)) {
1076 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1078 // Same as below (append LIMIT), append the remembered ORDER BY
1079 if ($GLOBALS['cfg']['RememberSorting']
1080 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1081 && isset($GLOBALS['sql_order_to_append'])
1083 $query_base = $analyzed_display_query[0]['section_before_limit']
1084 . "\n" . $GLOBALS['sql_order_to_append']
1085 . $analyzed_display_query[0]['section_after_limit'];
1087 // Need to reparse query
1088 $parsed_sql = PMA_SQP_parse($query_base);
1089 // update the $analyzed_display_query
1090 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1091 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1094 // Here we append the LIMIT added for navigation, to
1095 // enable its display. Adding it higher in the code
1096 // to $sql_query would create a problem when
1097 // using the Refresh or Edit links.
1099 // Only append it on SELECTs.
1102 * @todo what would be the best to do when someone hits Refresh:
1103 * use the current LIMITs ?
1106 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1107 && isset($GLOBALS['sql_limit_to_append'])
1109 $query_base = $analyzed_display_query[0]['section_before_limit']
1110 . "\n" . $GLOBALS['sql_limit_to_append']
1111 . $analyzed_display_query[0]['section_after_limit'];
1112 // Need to reparse query
1113 $parsed_sql = PMA_SQP_parse($query_base);
1117 if (! empty($GLOBALS['show_as_php'])) {
1118 $query_base = '$sql = "' . $query_base;
1119 } elseif (! empty($GLOBALS['validatequery'])) {
1120 try {
1121 $query_base = PMA_validateSQL($query_base);
1122 } catch (Exception $e) {
1123 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1125 } elseif (isset($parsed_sql)) {
1126 $query_base = PMA_formatSql($parsed_sql, $query_base);
1129 // Prepares links that may be displayed to edit/explain the query
1130 // (don't go to default pages, we must go to the page
1131 // where the query box is available)
1133 // Basic url query part
1134 $url_params = array();
1135 if (! isset($GLOBALS['db'])) {
1136 $GLOBALS['db'] = '';
1138 if (strlen($GLOBALS['db'])) {
1139 $url_params['db'] = $GLOBALS['db'];
1140 if (strlen($GLOBALS['table'])) {
1141 $url_params['table'] = $GLOBALS['table'];
1142 $edit_link = 'tbl_sql.php';
1143 } else {
1144 $edit_link = 'db_sql.php';
1146 } else {
1147 $edit_link = 'server_sql.php';
1150 // Want to have the query explained
1151 // but only explain a SELECT (that has not been explained)
1152 /* SQL-Parser-Analyzer */
1153 $explain_link = '';
1154 $is_select = false;
1155 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1156 $explain_params = $url_params;
1157 // Detect if we are validating as well
1158 // To preserve the validate uRL data
1159 if (! empty($GLOBALS['validatequery'])) {
1160 $explain_params['validatequery'] = 1;
1162 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1163 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1164 $_message = __('Explain SQL');
1165 $is_select = true;
1166 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1167 $explain_params['sql_query'] = substr($sql_query, 8);
1168 $_message = __('Skip Explain SQL');
1170 if (isset($explain_params['sql_query'])) {
1171 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1172 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1174 } //show explain
1176 $url_params['sql_query'] = $sql_query;
1177 $url_params['show_query'] = 1;
1179 // even if the query is big and was truncated, offer the chance
1180 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1181 if (! empty($cfg['SQLQuery']['Edit'])) {
1182 if ($cfg['EditInWindow'] == true) {
1183 $onclick = 'window.parent.focus_querywindow(\''
1184 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1185 } else {
1186 $onclick = '';
1189 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1190 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1191 } else {
1192 $edit_link = '';
1195 $url_qpart = PMA_generate_common_url($url_params);
1197 // Also we would like to get the SQL formed in some nice
1198 // php-code
1199 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1200 $php_params = $url_params;
1202 if (! empty($GLOBALS['show_as_php'])) {
1203 $_message = __('Without PHP Code');
1204 } else {
1205 $php_params['show_as_php'] = 1;
1206 $_message = __('Create PHP Code');
1209 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1210 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1212 if (isset($GLOBALS['show_as_php'])) {
1213 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1214 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1216 } else {
1217 $php_link = '';
1218 } //show as php
1220 // Refresh query
1221 if (! empty($cfg['SQLQuery']['Refresh'])
1222 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1223 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1225 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1226 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1227 } else {
1228 $refresh_link = '';
1229 } //refresh
1231 if (! empty($cfg['SQLValidator']['use'])
1232 && ! empty($cfg['SQLQuery']['Validate'])
1234 $validate_params = $url_params;
1235 if (!empty($GLOBALS['validatequery'])) {
1236 $validate_message = __('Skip Validate SQL');
1237 } else {
1238 $validate_params['validatequery'] = 1;
1239 $validate_message = __('Validate SQL');
1242 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1243 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1244 } else {
1245 $validate_link = '';
1246 } //validator
1248 if (!empty($GLOBALS['validatequery'])) {
1249 echo '<div class="sqlvalidate">';
1250 } else {
1251 echo '<code class="sql">';
1253 if ($query_too_big) {
1254 echo $shortened_query_base;
1255 } else {
1256 echo $query_base;
1259 //Clean up the end of the PHP
1260 if (! empty($GLOBALS['show_as_php'])) {
1261 echo '";';
1263 if (!empty($GLOBALS['validatequery'])) {
1264 echo '</div>';
1265 } else {
1266 echo '</code>';
1269 echo '<div class="tools">';
1270 // avoid displaying a Profiling checkbox that could
1271 // be checked, which would reexecute an INSERT, for example
1272 if (! empty($refresh_link)) {
1273 PMA_profilingCheckbox($sql_query);
1275 // if needed, generate an invisible form that contains controls for the
1276 // Inline link; this way, the behavior of the Inline link does not
1277 // depend on the profiling support or on the refresh link
1278 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1279 echo '<form action="sql.php" method="post">';
1280 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1281 echo '<input type="hidden" name="sql_query" value="'
1282 . htmlspecialchars($sql_query) . '" />';
1283 echo '</form>';
1286 // in the tools div, only display the Inline link when not in ajax
1287 // mode because 1) it currently does not work and 2) we would
1288 // have two similar mechanisms on the page for the same goal
1289 if ($is_select
1290 || $GLOBALS['is_ajax_request'] === false
1291 && ! $query_too_big
1293 // see in js/functions.js the jQuery code attached to id inline_edit
1294 // document.write conflicts with jQuery, hence used $().append()
1295 echo "<script type=\"text/javascript\">\n" .
1296 "//<![CDATA[\n" .
1297 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1298 PMA_escapeJsString(__('Inline edit of this query')) .
1299 "\" class=\"inline_edit_sql\">" .
1300 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1301 "</a>]');\n" .
1302 "//]]>\n" .
1303 "</script>";
1305 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1306 echo '</div>';
1308 echo '</div>';
1309 if ($GLOBALS['is_ajax_request'] === false) {
1310 echo '<br class="clearfloat" />';
1313 // If we are in an Ajax request, we have most probably been called in
1314 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1315 // to PMA_ajaxResponse(), which will encode it for JSON.
1316 if ($GLOBALS['is_ajax_request'] == true
1317 && ! isset($GLOBALS['buffer_message'])
1319 $buffer_contents = ob_get_contents();
1320 ob_end_clean();
1321 return $buffer_contents;
1323 return null;
1324 } // end of the 'PMA_showMessage()' function
1327 * Verifies if current MySQL server supports profiling
1329 * @access public
1331 * @return boolean whether profiling is supported
1333 function PMA_profilingSupported()
1335 if (! PMA_cacheExists('profiling_supported', true)) {
1336 // 5.0.37 has profiling but for example, 5.1.20 does not
1337 // (avoid a trip to the server for MySQL before 5.0.37)
1338 // and do not set a constant as we might be switching servers
1339 if (defined('PMA_MYSQL_INT_VERSION')
1340 && PMA_MYSQL_INT_VERSION >= 50037
1341 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1343 PMA_cacheSet('profiling_supported', true, true);
1344 } else {
1345 PMA_cacheSet('profiling_supported', false, true);
1349 return PMA_cacheGet('profiling_supported', true);
1353 * Displays a form with the Profiling checkbox
1355 * @param string $sql_query sql query
1357 * @access public
1359 function PMA_profilingCheckbox($sql_query)
1361 if (PMA_profilingSupported()) {
1362 echo '<form action="sql.php" method="post">' . "\n";
1363 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1364 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1365 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1366 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1367 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1368 echo '</form>' . "\n";
1373 * Formats $value to byte view
1375 * @param double $value the value to format
1376 * @param int $limes the sensitiveness
1377 * @param int $comma the number of decimals to retain
1379 * @return array the formatted value and its unit
1381 * @access public
1383 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1385 if ($value === null) {
1386 return null;
1389 $byteUnits = array(
1390 /* l10n: shortcuts for Byte */
1391 __('B'),
1392 /* l10n: shortcuts for Kilobyte */
1393 __('KiB'),
1394 /* l10n: shortcuts for Megabyte */
1395 __('MiB'),
1396 /* l10n: shortcuts for Gigabyte */
1397 __('GiB'),
1398 /* l10n: shortcuts for Terabyte */
1399 __('TiB'),
1400 /* l10n: shortcuts for Petabyte */
1401 __('PiB'),
1402 /* l10n: shortcuts for Exabyte */
1403 __('EiB')
1406 $dh = PMA_pow(10, $comma);
1407 $li = PMA_pow(10, $limes);
1408 $unit = $byteUnits[0];
1410 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1411 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1412 // use 1024.0 to avoid integer overflow on 64-bit machines
1413 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1414 $unit = $byteUnits[$d];
1415 break 1;
1416 } // end if
1417 } // end for
1419 if ($unit != $byteUnits[0]) {
1420 // if the unit is not bytes (as represented in current language)
1421 // reformat with max length of 5
1422 // 4th parameter=true means do not reformat if value < 1
1423 $return_value = PMA_formatNumber($value, 5, $comma, true);
1424 } else {
1425 // do not reformat, just handle the locale
1426 $return_value = PMA_formatNumber($value, 0);
1429 return array(trim($return_value), $unit);
1430 } // end of the 'PMA_formatByteDown' function
1433 * Changes thousands and decimal separators to locale specific values.
1435 * @param string $value the value
1437 * @return string
1439 function PMA_localizeNumber($value)
1441 return str_replace(
1442 array(',', '.'),
1443 array(
1444 /* l10n: Thousands separator */
1445 __(','),
1446 /* l10n: Decimal separator */
1447 __('.'),
1449 $value
1454 * Formats $value to the given length and appends SI prefixes
1455 * with a $length of 0 no truncation occurs, number is only formated
1456 * to the current locale
1458 * examples:
1459 * <code>
1460 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1461 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1462 * echo PMA_formatNumber(-0.003, 6); // -3 m
1463 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1464 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1465 * echo PMA_formatNumber(0, 6); // 0
1466 * </code>
1468 * @param double $value the value to format
1469 * @param integer $digits_left number of digits left of the comma
1470 * @param integer $digits_right number of digits right of the comma
1471 * @param boolean $only_down do not reformat numbers below 1
1472 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1473 * (default: true)
1475 * @return string the formatted value and its unit
1477 * @access public
1479 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1480 $only_down = false, $noTrailingZero = true)
1482 if ($value==0) {
1483 return '0';
1486 $originalValue = $value;
1487 //number_format is not multibyte safe, str_replace is safe
1488 if ($digits_left === 0) {
1489 $value = number_format($value, $digits_right);
1490 if ($originalValue != 0 && floatval($value) == 0) {
1491 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1494 return PMA_localizeNumber($value);
1497 // this units needs no translation, ISO
1498 $units = array(
1499 -8 => 'y',
1500 -7 => 'z',
1501 -6 => 'a',
1502 -5 => 'f',
1503 -4 => 'p',
1504 -3 => 'n',
1505 -2 => '&micro;',
1506 -1 => 'm',
1507 0 => ' ',
1508 1 => 'k',
1509 2 => 'M',
1510 3 => 'G',
1511 4 => 'T',
1512 5 => 'P',
1513 6 => 'E',
1514 7 => 'Z',
1515 8 => 'Y'
1518 // check for negative value to retain sign
1519 if ($value < 0) {
1520 $sign = '-';
1521 $value = abs($value);
1522 } else {
1523 $sign = '';
1526 $dh = PMA_pow(10, $digits_right);
1529 * This gives us the right SI prefix already,
1530 * but $digits_left parameter not incorporated
1532 $d = floor(log10($value) / 3);
1534 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1535 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1536 * to use, then lower the SI prefix
1538 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1539 if ($digits_left > $cur_digits) {
1540 $d-= floor(($digits_left - $cur_digits)/3);
1543 if ($d<0 && $only_down) {
1544 $d=0;
1547 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1548 $unit = $units[$d];
1550 // If we dont want any zeros after the comma just add the thousand seperator
1551 if ($noTrailingZero) {
1552 $value = PMA_localizeNumber(
1553 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1555 } else {
1556 //number_format is not multibyte safe, str_replace is safe
1557 $value = PMA_localizeNumber(number_format($value, $digits_right));
1560 if ($originalValue!=0 && floatval($value) == 0) {
1561 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1564 return $sign . $value . ' ' . $unit;
1565 } // end of the 'PMA_formatNumber' function
1568 * Returns the number of bytes when a formatted size is given
1570 * @param string $formatted_size the size expression (for example 8MB)
1572 * @return integer The numerical part of the expression (for example 8)
1574 function PMA_extractValueFromFormattedSize($formatted_size)
1576 $return_value = -1;
1578 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1579 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1580 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1581 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1582 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1583 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1585 return $return_value;
1586 }// end of the 'PMA_extractValueFromFormattedSize' function
1589 * Writes localised date
1591 * @param string $timestamp the current timestamp
1592 * @param string $format format
1594 * @return string the formatted date
1596 * @access public
1598 function PMA_localisedDate($timestamp = -1, $format = '')
1600 $month = array(
1601 /* l10n: Short month name */
1602 __('Jan'),
1603 /* l10n: Short month name */
1604 __('Feb'),
1605 /* l10n: Short month name */
1606 __('Mar'),
1607 /* l10n: Short month name */
1608 __('Apr'),
1609 /* l10n: Short month name */
1610 _pgettext('Short month name', 'May'),
1611 /* l10n: Short month name */
1612 __('Jun'),
1613 /* l10n: Short month name */
1614 __('Jul'),
1615 /* l10n: Short month name */
1616 __('Aug'),
1617 /* l10n: Short month name */
1618 __('Sep'),
1619 /* l10n: Short month name */
1620 __('Oct'),
1621 /* l10n: Short month name */
1622 __('Nov'),
1623 /* l10n: Short month name */
1624 __('Dec'));
1625 $day_of_week = array(
1626 /* l10n: Short week day name */
1627 _pgettext('Short week day name', 'Sun'),
1628 /* l10n: Short week day name */
1629 __('Mon'),
1630 /* l10n: Short week day name */
1631 __('Tue'),
1632 /* l10n: Short week day name */
1633 __('Wed'),
1634 /* l10n: Short week day name */
1635 __('Thu'),
1636 /* l10n: Short week day name */
1637 __('Fri'),
1638 /* l10n: Short week day name */
1639 __('Sat'));
1641 if ($format == '') {
1642 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1643 $format = __('%B %d, %Y at %I:%M %p');
1646 if ($timestamp == -1) {
1647 $timestamp = time();
1650 $date = preg_replace(
1651 '@%[aA]@',
1652 $day_of_week[(int)strftime('%w', $timestamp)],
1653 $format
1655 $date = preg_replace(
1656 '@%[bB]@',
1657 $month[(int)strftime('%m', $timestamp)-1],
1658 $date
1661 return strftime($date, $timestamp);
1662 } // end of the 'PMA_localisedDate()' function
1666 * returns a tab for tabbed navigation.
1667 * If the variables $link and $args ar left empty, an inactive tab is created
1669 * @param array $tab array with all options
1670 * @param array $url_params
1672 * @return string html code for one tab, a link if valid otherwise a span
1674 * @access public
1676 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1678 // default values
1679 $defaults = array(
1680 'text' => '',
1681 'class' => '',
1682 'active' => null,
1683 'link' => '',
1684 'sep' => '?',
1685 'attr' => '',
1686 'args' => '',
1687 'warning' => '',
1688 'fragment' => '',
1689 'id' => '',
1692 $tab = array_merge($defaults, $tab);
1694 // determine additionnal style-class
1695 if (empty($tab['class'])) {
1696 if (! empty($tab['active'])
1697 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1699 $tab['class'] = 'active';
1700 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1701 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1702 && empty($tab['warning'])) {
1703 $tab['class'] = 'active';
1707 if (!empty($tab['warning'])) {
1708 $tab['class'] .= ' error';
1709 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1712 // If there are any tab specific URL parameters, merge those with
1713 // the general URL parameters
1714 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1715 $url_params = array_merge($url_params, $tab['url_params']);
1718 // build the link
1719 if (!empty($tab['link'])) {
1720 $tab['link'] = htmlentities($tab['link']);
1721 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1722 if (! empty($tab['args'])) {
1723 foreach ($tab['args'] as $param => $value) {
1724 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1725 . '=' . urlencode($value);
1730 if (! empty($tab['fragment'])) {
1731 $tab['link'] .= $tab['fragment'];
1734 // display icon, even if iconic is disabled but the link-text is missing
1735 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1736 && isset($tab['icon'])
1738 // avoid generating an alt tag, because it only illustrates
1739 // the text that follows and if browser does not display
1740 // images, the text is duplicated
1741 $tab['text'] = PMA_getImage(htmlentities($tab['icon'])) . $tab['text'];
1743 } elseif (empty($tab['text'])) {
1744 // check to not display an empty link-text
1745 $tab['text'] = '?';
1746 trigger_error(
1747 'empty linktext in function ' . __FUNCTION__ . '()',
1748 E_USER_NOTICE
1752 //Set the id for the tab, if set in the params
1753 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1754 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1756 if (!empty($tab['link'])) {
1757 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1758 .$id_string
1759 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1760 . $tab['text'] . '</a>';
1761 } else {
1762 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1763 . $tab['text'] . '</span>';
1766 $out .= '</li>';
1767 return $out;
1768 } // end of the 'PMA_generate_html_tab()' function
1771 * returns html-code for a tab navigation
1773 * @param array $tabs one element per tab
1774 * @param string $url_params
1775 * @param string $base_dir
1776 * @param string $menu_id
1778 * @return string html-code for tab-navigation
1780 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='', $menu_id='topmenu')
1782 $tab_navigation = '<div id="' . htmlentities($menu_id) . 'container" class="menucontainer">'
1783 .'<ul id="' . htmlentities($menu_id) . '">';
1785 foreach ($tabs as $tab) {
1786 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1789 $tab_navigation .=
1790 '</ul>' . "\n"
1791 .'<div class="clearfloat"></div>'
1792 .'</div>' . "\n";
1794 return $tab_navigation;
1799 * Displays a link, or a button if the link's URL is too large, to
1800 * accommodate some browsers' limitations
1802 * @param string $url the URL
1803 * @param string $message the link message
1804 * @param mixed $tag_params string: js confirmation
1805 * array: additional tag params (f.e. style="")
1806 * @param boolean $new_form we set this to false when we are already in
1807 * a form, to avoid generating nested forms
1808 * @param boolean $strip_img whether to strip the image
1809 * @param string $target target
1811 * @return string the results to be echoed or saved in an array
1813 function PMA_linkOrButton($url, $message, $tag_params = array(),
1814 $new_form = true, $strip_img = false, $target = '')
1816 $url_length = strlen($url);
1817 // with this we should be able to catch case of image upload
1818 // into a (MEDIUM) BLOB; not worth generating even a form for these
1819 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1820 return '';
1824 if (! is_array($tag_params)) {
1825 $tmp = $tag_params;
1826 $tag_params = array();
1827 if (!empty($tmp)) {
1828 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1830 unset($tmp);
1832 if (! empty($target)) {
1833 $tag_params['target'] = htmlentities($target);
1836 $tag_params_strings = array();
1837 foreach ($tag_params as $par_name => $par_value) {
1838 // htmlspecialchars() only on non javascript
1839 $par_value = substr($par_name, 0, 2) == 'on'
1840 ? $par_value
1841 : htmlspecialchars($par_value);
1842 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1845 $displayed_message = '';
1846 // Add text if not already added
1847 if (stristr($message, '<img')
1848 && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
1849 && strip_tags($message)==$message
1851 $displayed_message = '<span>'
1852 . htmlspecialchars(
1853 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1855 . '</span>';
1858 // Suhosin: Check that each query parameter is not above maximum
1859 $in_suhosin_limits = true;
1860 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1861 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1862 $query_parts = PMA_splitURLQuery($url);
1863 foreach ($query_parts as $query_pair) {
1864 list($eachvar, $eachval) = explode('=', $query_pair);
1865 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1866 $in_suhosin_limits = false;
1867 break;
1873 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1874 // no whitespace within an <a> else Safari will make it part of the link
1875 $ret = "\n" . '<a href="' . $url . '" '
1876 . implode(' ', $tag_params_strings) . '>'
1877 . $message . $displayed_message . '</a>' . "\n";
1878 } else {
1879 // no spaces (linebreaks) at all
1880 // or after the hidden fields
1881 // IE will display them all
1883 // add class=link to submit button
1884 if (empty($tag_params['class'])) {
1885 $tag_params['class'] = 'link';
1888 if (! isset($query_parts)) {
1889 $query_parts = PMA_splitURLQuery($url);
1891 $url_parts = parse_url($url);
1893 if ($new_form) {
1894 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1895 . ' method="post"' . $target . ' style="display: inline;">';
1896 $subname_open = '';
1897 $subname_close = '';
1898 $submit_link = '#';
1899 } else {
1900 $query_parts[] = 'redirect=' . $url_parts['path'];
1901 if (empty($GLOBALS['subform_counter'])) {
1902 $GLOBALS['subform_counter'] = 0;
1904 $GLOBALS['subform_counter']++;
1905 $ret = '';
1906 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1907 $subname_close = ']';
1908 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1910 foreach ($query_parts as $query_pair) {
1911 list($eachvar, $eachval) = explode('=', $query_pair);
1912 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1913 . $subname_close . '" value="'
1914 . htmlspecialchars(urldecode($eachval)) . '" />';
1915 } // end while
1917 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1918 . implode(' ', $tag_params_strings) . '>'
1919 . $message . ' ' . $displayed_message . '</a>' . "\n";
1921 if ($new_form) {
1922 $ret .= '</form>';
1924 } // end if... else...
1926 return $ret;
1927 } // end of the 'PMA_linkOrButton()' function
1931 * Splits a URL string by parameter
1933 * @param string $url the URL
1935 * @return array the parameter/value pairs, for example [0] db=sakila
1937 function PMA_splitURLQuery($url)
1939 // decode encoded url separators
1940 $separator = PMA_get_arg_separator();
1941 // on most places separator is still hard coded ...
1942 if ($separator !== '&') {
1943 // ... so always replace & with $separator
1944 $url = str_replace(htmlentities('&'), $separator, $url);
1945 $url = str_replace('&', $separator, $url);
1947 $url = str_replace(htmlentities($separator), $separator, $url);
1948 // end decode
1950 $url_parts = parse_url($url);
1951 return explode($separator, $url_parts['query']);
1955 * Returns a given timespan value in a readable format.
1957 * @param int $seconds the timespan
1959 * @return string the formatted value
1961 function PMA_timespanFormat($seconds)
1963 $days = floor($seconds / 86400);
1964 if ($days > 0) {
1965 $seconds -= $days * 86400;
1967 $hours = floor($seconds / 3600);
1968 if ($days > 0 || $hours > 0) {
1969 $seconds -= $hours * 3600;
1971 $minutes = floor($seconds / 60);
1972 if ($days > 0 || $hours > 0 || $minutes > 0) {
1973 $seconds -= $minutes * 60;
1975 return sprintf(
1976 __('%s days, %s hours, %s minutes and %s seconds'),
1977 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1982 * Takes a string and outputs each character on a line for itself. Used
1983 * mainly for horizontalflipped display mode.
1984 * Takes care of special html-characters.
1985 * Fulfills todo-item
1986 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1988 * @param string $string The string
1989 * @param string $Separator The Separator (defaults to "<br />\n")
1991 * @access public
1992 * @todo add a multibyte safe function PMA_STR_split()
1994 * @return string The flipped string
1996 function PMA_flipstring($string, $Separator = "<br />\n")
1998 $format_string = '';
1999 $charbuff = false;
2001 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
2002 $char = $string{$i};
2003 $append = false;
2005 if ($char == '&') {
2006 $format_string .= $charbuff;
2007 $charbuff = $char;
2008 } elseif ($char == ';' && !empty($charbuff)) {
2009 $format_string .= $charbuff . $char;
2010 $charbuff = false;
2011 $append = true;
2012 } elseif (! empty($charbuff)) {
2013 $charbuff .= $char;
2014 } else {
2015 $format_string .= $char;
2016 $append = true;
2019 // do not add separator after the last character
2020 if ($append && ($i != $str_len - 1)) {
2021 $format_string .= $Separator;
2025 return $format_string;
2029 * Function added to avoid path disclosures.
2030 * Called by each script that needs parameters, it displays
2031 * an error message and, by default, stops the execution.
2033 * Not sure we could use a strMissingParameter message here,
2034 * would have to check if the error message file is always available
2036 * @param array $params The names of the parameters needed by the calling script.
2037 * @param bool $die Stop the execution?
2038 * (Set this manually to false in the calling script
2039 * until you know all needed parameters to check).
2040 * @param bool $request Whether to include this list in checking for special params.
2042 * @global string path to current script
2043 * @global boolean flag whether any special variable was required
2045 * @access public
2046 * @todo use PMA_fatalError() if $die === true?
2048 function PMA_checkParameters($params, $die = true, $request = true)
2050 global $checked_special;
2052 if (! isset($checked_special)) {
2053 $checked_special = false;
2056 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2057 $found_error = false;
2058 $error_message = '';
2060 foreach ($params as $param) {
2061 if ($request && $param != 'db' && $param != 'table') {
2062 $checked_special = true;
2065 if (! isset($GLOBALS[$param])) {
2066 $error_message .= $reported_script_name
2067 . ': ' . __('Missing parameter:') . ' '
2068 . $param
2069 . PMA_showDocu('faqmissingparameters')
2070 . '<br />';
2071 $found_error = true;
2074 if ($found_error) {
2076 * display html meta tags
2078 include_once './libraries/header_meta_style.inc.php';
2079 echo '</head><body><p>' . $error_message . '</p></body></html>';
2080 if ($die) {
2081 exit();
2084 } // end function
2087 * Function to generate unique condition for specified row.
2089 * @param resource $handle current query result
2090 * @param integer $fields_cnt number of fields
2091 * @param array $fields_meta meta information about fields
2092 * @param array $row current row
2093 * @param boolean $force_unique generate condition only on pk or unique
2095 * @access public
2097 * @return array the calculated condition and whether condition is unique
2099 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2101 $primary_key = '';
2102 $unique_key = '';
2103 $nonprimary_condition = '';
2104 $preferred_condition = '';
2105 $primary_key_array = array();
2106 $unique_key_array = array();
2107 $nonprimary_condition_array = array();
2108 $condition_array = array();
2110 for ($i = 0; $i < $fields_cnt; ++$i) {
2111 $condition = '';
2112 $con_key = '';
2113 $con_val = '';
2114 $field_flags = PMA_DBI_field_flags($handle, $i);
2115 $meta = $fields_meta[$i];
2117 // do not use a column alias in a condition
2118 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2119 $meta->orgname = $meta->name;
2121 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2122 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2124 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2125 // need (string) === (string)
2126 // '' !== 0 but '' == 0
2127 if ((string) $select_expr['alias'] === (string) $meta->name) {
2128 $meta->orgname = $select_expr['column'];
2129 break;
2130 } // end if
2131 } // end foreach
2135 // Do not use a table alias in a condition.
2136 // Test case is:
2137 // select * from galerie x WHERE
2138 //(select count(*) from galerie y where y.datum=x.datum)>1
2140 // But orgtable is present only with mysqli extension so the
2141 // fix is only for mysqli.
2142 // Also, do not use the original table name if we are dealing with
2143 // a view because this view might be updatable.
2144 // (The isView() verification should not be costly in most cases
2145 // because there is some caching in the function).
2146 if (isset($meta->orgtable)
2147 && $meta->table != $meta->orgtable
2148 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2150 $meta->table = $meta->orgtable;
2153 // to fix the bug where float fields (primary or not)
2154 // can't be matched because of the imprecision of
2155 // floating comparison, use CONCAT
2156 // (also, the syntax "CONCAT(field) IS NULL"
2157 // that we need on the next "if" will work)
2158 if ($meta->type == 'real') {
2159 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2160 . PMA_backquote($meta->orgname) . ')';
2161 } else {
2162 $con_key = PMA_backquote($meta->table) . '.'
2163 . PMA_backquote($meta->orgname);
2164 } // end if... else...
2165 $condition = ' ' . $con_key . ' ';
2167 if (! isset($row[$i]) || is_null($row[$i])) {
2168 $con_val = 'IS NULL';
2169 } else {
2170 // timestamp is numeric on some MySQL 4.1
2171 // for real we use CONCAT above and it should compare to string
2172 if ($meta->numeric
2173 && $meta->type != 'timestamp'
2174 && $meta->type != 'real'
2176 $con_val = '= ' . $row[$i];
2177 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2178 // hexify only if this is a true not empty BLOB or a BINARY
2179 && stristr($field_flags, 'BINARY')
2180 && !empty($row[$i])) {
2181 // do not waste memory building a too big condition
2182 if (strlen($row[$i]) < 1000) {
2183 // use a CAST if possible, to avoid problems
2184 // if the field contains wildcard characters % or _
2185 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2186 } else {
2187 // this blob won't be part of the final condition
2188 $con_val = null;
2190 } elseif (in_array($meta->type, PMA_getGISDatatypes())
2191 && ! empty($row[$i])
2193 // do not build a too big condition
2194 if (strlen($row[$i]) < 5000) {
2195 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2196 } else {
2197 $condition = '';
2199 } elseif ($meta->type == 'bit') {
2200 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2201 } else {
2202 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2205 if ($con_val != null) {
2206 $condition .= $con_val . ' AND';
2207 if ($meta->primary_key > 0) {
2208 $primary_key .= $condition;
2209 $primary_key_array[$con_key] = $con_val;
2210 } elseif ($meta->unique_key > 0) {
2211 $unique_key .= $condition;
2212 $unique_key_array[$con_key] = $con_val;
2214 $nonprimary_condition .= $condition;
2215 $nonprimary_condition_array[$con_key] = $con_val;
2217 } // end for
2219 // Correction University of Virginia 19991216:
2220 // prefer primary or unique keys for condition,
2221 // but use conjunction of all values if no primary key
2222 $clause_is_unique = true;
2223 if ($primary_key) {
2224 $preferred_condition = $primary_key;
2225 $condition_array = $primary_key_array;
2226 } elseif ($unique_key) {
2227 $preferred_condition = $unique_key;
2228 $condition_array = $unique_key_array;
2229 } elseif (! $force_unique) {
2230 $preferred_condition = $nonprimary_condition;
2231 $condition_array = $nonprimary_condition_array;
2232 $clause_is_unique = false;
2235 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2236 return(array($where_clause, $clause_is_unique, $condition_array));
2237 } // end function
2240 * Generate a button or image tag
2242 * @param string $button_name name of button element
2243 * @param string $button_class class of button element
2244 * @param string $image_name name of image element
2245 * @param string $text text to display
2246 * @param string $image image to display
2247 * @param string $value value
2249 * @access public
2251 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2252 $image, $value = '')
2254 if ($value == '') {
2255 $value = $text;
2257 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2258 echo ' <input type="submit" name="' . $button_name . '"'
2259 .' value="' . htmlspecialchars($value) . '"'
2260 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2261 return;
2264 /* Opera has trouble with <input type="image"> */
2265 /* IE has trouble with <button> */
2266 if (PMA_USR_BROWSER_AGENT != 'IE') {
2267 echo '<button class="' . $button_class . '" type="submit"'
2268 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2269 .' title="' . htmlspecialchars($text) . '">' . "\n"
2270 . PMA_getIcon($image, $text)
2271 .'</button>' . "\n";
2272 } else {
2273 echo '<input type="image" name="' . $image_name
2274 . '" value="' . htmlspecialchars($value)
2275 . '" title="' . htmlspecialchars($text)
2276 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2277 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2278 ? '&nbsp;' . htmlspecialchars($text)
2279 : '') . "\n";
2281 } // end function
2284 * Generate a pagination selector for browsing resultsets
2286 * @param int $rows Number of rows in the pagination set
2287 * @param int $pageNow current page number
2288 * @param int $nbTotalPage number of total pages
2289 * @param int $showAll If the number of pages is lower than this
2290 * variable, no pages will be omitted in pagination
2291 * @param int $sliceStart How many rows at the beginning should always be shown?
2292 * @param int $sliceEnd How many rows at the end should always be shown?
2293 * @param int $percent Percentage of calculation page offsets to hop to a
2294 * next page
2295 * @param int $range Near the current page, how many pages should
2296 * be considered "nearby" and displayed as well?
2297 * @param string $prompt The prompt to display (sometimes empty)
2299 * @return string
2301 * @access public
2303 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2304 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2305 $range = 10, $prompt = '')
2307 $increment = floor($nbTotalPage / $percent);
2308 $pageNowMinusRange = ($pageNow - $range);
2309 $pageNowPlusRange = ($pageNow + $range);
2311 $gotopage = $prompt . ' <select id="pageselector" ';
2312 if ($GLOBALS['cfg']['AjaxEnable']) {
2313 $gotopage .= ' class="ajax"';
2315 $gotopage .= ' name="pos" >' . "\n";
2316 if ($nbTotalPage < $showAll) {
2317 $pages = range(1, $nbTotalPage);
2318 } else {
2319 $pages = array();
2321 // Always show first X pages
2322 for ($i = 1; $i <= $sliceStart; $i++) {
2323 $pages[] = $i;
2326 // Always show last X pages
2327 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2328 $pages[] = $i;
2331 // Based on the number of results we add the specified
2332 // $percent percentage to each page number,
2333 // so that we have a representing page number every now and then to
2334 // immediately jump to specific pages.
2335 // As soon as we get near our currently chosen page ($pageNow -
2336 // $range), every page number will be shown.
2337 $i = $sliceStart;
2338 $x = $nbTotalPage - $sliceEnd;
2339 $met_boundary = false;
2340 while ($i <= $x) {
2341 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2342 // If our pageselector comes near the current page, we use 1
2343 // counter increments
2344 $i++;
2345 $met_boundary = true;
2346 } else {
2347 // We add the percentage increment to our current page to
2348 // hop to the next one in range
2349 $i += $increment;
2351 // Make sure that we do not cross our boundaries.
2352 if ($i > $pageNowMinusRange && ! $met_boundary) {
2353 $i = $pageNowMinusRange;
2357 if ($i > 0 && $i <= $x) {
2358 $pages[] = $i;
2362 // Since because of ellipsing of the current page some numbers may be double,
2363 // we unify our array:
2364 sort($pages);
2365 $pages = array_unique($pages);
2368 foreach ($pages as $i) {
2369 if ($i == $pageNow) {
2370 $selected = 'selected="selected" style="font-weight: bold"';
2371 } else {
2372 $selected = '';
2374 $gotopage .= ' <option ' . $selected
2375 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2378 $gotopage .= ' </select><noscript><input type="submit" value="'
2379 . __('Go') . '" /></noscript>';
2381 return $gotopage;
2382 } // end function
2386 * Generate navigation for a list
2388 * @param int $count number of elements in the list
2389 * @param int $pos current position in the list
2390 * @param array $_url_params url parameters
2391 * @param string $script script name for form target
2392 * @param string $frame target frame
2393 * @param int $max_count maximum number of elements to display from the list
2395 * @access public
2397 * @todo use $pos from $_url_params
2399 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2402 if ($max_count < $count) {
2403 echo 'frame_navigation' == $frame
2404 ? '<div id="navidbpageselector">' . "\n"
2405 : '';
2406 echo __('Page number:');
2407 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2409 // Move to the beginning or to the previous page
2410 if ($pos > 0) {
2411 // patch #474210 - part 1
2412 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2413 $caption1 = '&lt;&lt;';
2414 $caption2 = ' &lt; ';
2415 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2416 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2417 } else {
2418 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2419 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2420 $title1 = '';
2421 $title2 = '';
2422 } // end if... else...
2423 $_url_params['pos'] = 0;
2424 echo '<a' . $title1 . ' href="' . $script
2425 . PMA_generate_common_url($_url_params) . '" target="'
2426 . $frame . '">' . $caption1 . '</a>';
2427 $_url_params['pos'] = $pos - $max_count;
2428 echo '<a' . $title2 . ' href="' . $script
2429 . PMA_generate_common_url($_url_params) . '" target="'
2430 . $frame . '">' . $caption2 . '</a>';
2433 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2434 echo PMA_generate_common_hidden_inputs($_url_params);
2435 echo PMA_pageselector(
2436 $max_count,
2437 floor(($pos + 1) / $max_count) + 1,
2438 ceil($count / $max_count)
2440 echo '</form>';
2442 if ($pos + $max_count < $count) {
2443 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2444 $caption3 = ' &gt; ';
2445 $caption4 = '&gt;&gt;';
2446 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2447 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2448 } else {
2449 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2450 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2451 $title3 = '';
2452 $title4 = '';
2453 } // end if... else...
2454 $_url_params['pos'] = $pos + $max_count;
2455 echo '<a' . $title3 . ' href="' . $script
2456 . PMA_generate_common_url($_url_params) . '" target="'
2457 . $frame . '">' . $caption3 . '</a>';
2458 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2459 if ($_url_params['pos'] == $count) {
2460 $_url_params['pos'] = $count - $max_count;
2462 echo '<a' . $title4 . ' href="' . $script
2463 . PMA_generate_common_url($_url_params) . '" target="'
2464 . $frame . '">' . $caption4 . '</a>';
2466 echo "\n";
2467 if ('frame_navigation' == $frame) {
2468 echo '</div>' . "\n";
2474 * replaces %u in given path with current user name
2476 * example:
2477 * <code>
2478 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2480 * </code>
2482 * @param string $dir with wildcard for user
2484 * @return string per user directory
2486 function PMA_userDir($dir)
2488 // add trailing slash
2489 if (substr($dir, -1) != '/') {
2490 $dir .= '/';
2493 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2497 * returns html code for db link to default db page
2499 * @param string $database database
2501 * @return string html link to default db page
2503 function PMA_getDbLink($database = null)
2505 if (! strlen($database)) {
2506 if (! strlen($GLOBALS['db'])) {
2507 return '';
2509 $database = $GLOBALS['db'];
2510 } else {
2511 $database = PMA_unescape_mysql_wildcards($database);
2514 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2515 . PMA_generate_common_url($database) . '" title="'
2516 . sprintf(
2517 __('Jump to database &quot;%s&quot;.'),
2518 htmlspecialchars($database)
2520 . '">' . htmlspecialchars($database) . '</a>';
2524 * Displays a lightbulb hint explaining a known external bug
2525 * that affects a functionality
2527 * @param string $functionality localized message explaining the func.
2528 * @param string $component 'mysql' (eventually, 'php')
2529 * @param string $minimum_version of this component
2530 * @param string $bugref bug reference for this component
2532 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2534 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2535 echo PMA_showHint(
2536 sprintf(
2537 __('The %s functionality is affected by a known bug, see %s'),
2538 $functionality,
2539 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2546 * Generates and echoes an HTML checkbox
2548 * @param string $html_field_name the checkbox HTML field
2549 * @param string $label label for checkbox
2550 * @param boolean $checked is it initially checked?
2551 * @param boolean $onclick should it submit the form on click?
2553 * @return the HTML for the checkbox
2555 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2558 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2559 . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
2560 . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
2561 . $html_field_name . '">' . $label . '</label>';
2565 * Generates and echoes a set of radio HTML fields
2567 * @param string $html_field_name the radio HTML field
2568 * @param array $choices the choices values and labels
2569 * @param string $checked_choice the choice to check by default
2570 * @param boolean $line_break whether to add an HTML line break after a choice
2571 * @param boolean $escape_label whether to use htmlspecialchars() on label
2572 * @param string $class enclose each choice with a div of this class
2574 * @return the HTML for the tadio buttons
2576 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2577 $line_break = true, $escape_label = true, $class='')
2579 foreach ($choices as $choice_value => $choice_label) {
2580 if (! empty($class)) {
2581 echo '<div class="' . $class . '">';
2583 $html_field_id = $html_field_name . '_' . $choice_value;
2584 echo '<input type="radio" name="' . $html_field_name . '" id="'
2585 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2586 if ($choice_value == $checked_choice) {
2587 echo ' checked="checked"';
2589 echo ' />' . "\n";
2590 echo '<label for="' . $html_field_id . '">'
2591 . ($escape_label ? htmlspecialchars($choice_label) : $choice_label)
2592 . '</label>';
2593 if ($line_break) {
2594 echo '<br />';
2596 if (! empty($class)) {
2597 echo '</div>';
2599 echo "\n";
2604 * Generates and returns an HTML dropdown
2606 * @param string $select_name name for the select element
2607 * @param array $choices choices values
2608 * @param string $active_choice the choice to select by default
2609 * @param string $id id of the select element; can be different in case
2610 * the dropdown is present more than once on the page
2612 * @return string
2614 * @todo support titles
2616 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2618 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2619 . htmlspecialchars($id) . '">';
2620 foreach ($choices as $one_choice_value => $one_choice_label) {
2621 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2622 if ($one_choice_value == $active_choice) {
2623 $result .= ' selected="selected"';
2625 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2627 $result .= '</select>';
2628 return $result;
2632 * Generates a slider effect (jQjuery)
2633 * Takes care of generating the initial <div> and the link
2634 * controlling the slider; you have to generate the </div> yourself
2635 * after the sliding section.
2637 * @param string $id the id of the <div> on which to apply the effect
2638 * @param string $message the message to show as a link
2640 function PMA_generate_slider_effect($id, $message)
2642 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2643 echo '<div id="' . $id . '">';
2644 return;
2647 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2648 * opening the <div> with PHP itself instead of JavaScript.
2650 * @todo find a better solution that uses $.append(), the recommended method
2651 * maybe by using an additional param, the id of the div to append to
2654 <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); ?>">
2655 <?php
2659 * Creates an AJAX sliding toggle button
2660 * (or and equivalent form when AJAX is disabled)
2662 * @param string $action The URL for the request to be executed
2663 * @param string $select_name The name for the dropdown box
2664 * @param array $options An array of options (see rte_footer.lib.php)
2665 * @param string $callback A JS snippet to execute when the request is
2666 * successfully processed
2668 * @return string HTML code for the toggle button
2670 function PMA_toggleButton($action, $select_name, $options, $callback)
2672 // Do the logic first
2673 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2674 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2675 if ($options[1]['selected'] == true) {
2676 $state = 'on';
2677 } else if ($options[0]['selected'] == true) {
2678 $state = 'off';
2679 } else {
2680 $state = 'on';
2682 $selected1 = '';
2683 $selected0 = '';
2684 if ($options[1]['selected'] == true) {
2685 $selected1 = " selected='selected'";
2686 } else if ($options[0]['selected'] == true) {
2687 $selected0 = " selected='selected'";
2689 // Generate output
2690 $retval = "<!-- TOGGLE START -->\n";
2691 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2692 $retval .= "<noscript>\n";
2694 $retval .= "<div class='wrapper'>\n";
2695 $retval .= " <form action='$action' method='post'>\n";
2696 $retval .= " <select name='$select_name'>\n";
2697 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2698 $retval .= " {$options[1]['label']}\n";
2699 $retval .= " </option>\n";
2700 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2701 $retval .= " {$options[0]['label']}\n";
2702 $retval .= " </option>\n";
2703 $retval .= " </select>\n";
2704 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2705 $retval .= " </form>\n";
2706 $retval .= "</div>\n";
2707 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2708 $retval .= "</noscript>\n";
2709 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2710 $retval .= " <div class='toggleButton'>\n";
2711 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2712 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2713 $retval .= " alt='' />\n";
2714 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2715 $retval .= " <tbody>\n";
2716 $retval .= " <td class='toggleOn'>\n";
2717 $retval .= " <span class='hide'>$link_on</span>\n";
2718 $retval .= " <div>";
2719 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2720 $retval .= " </td>\n";
2721 $retval .= " <td><div>&nbsp;</div></td>\n";
2722 $retval .= " <td class='toggleOff'>\n";
2723 $retval .= " <span class='hide'>$link_off</span>\n";
2724 $retval .= " <div>";
2725 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2726 $retval .= " </div>\n";
2727 $retval .= " </tbody>\n";
2728 $retval .= " </tr></table>\n";
2729 $retval .= " <span class='hide callback'>$callback</span>\n";
2730 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2731 $retval .= " </div>\n";
2732 $retval .= " </div>\n";
2733 $retval .= "</div>\n";
2735 $retval .= "<!-- TOGGLE END -->";
2737 return $retval;
2738 } // end PMA_toggleButton()
2741 * Clears cache content which needs to be refreshed on user change.
2743 * @return nothing
2745 function PMA_clearUserCache()
2747 PMA_cacheUnset('is_superuser', true);
2751 * Verifies if something is cached in the session
2753 * @param string $var variable name
2754 * @param int|true $server server
2756 * @return boolean
2758 function PMA_cacheExists($var, $server = 0)
2760 if (true === $server) {
2761 $server = $GLOBALS['server'];
2763 return isset($_SESSION['cache']['server_' . $server][$var]);
2767 * Gets cached information from the session
2769 * @param string $var varibale name
2770 * @param int|true $server server
2772 * @return mixed
2774 function PMA_cacheGet($var, $server = 0)
2776 if (true === $server) {
2777 $server = $GLOBALS['server'];
2779 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2780 return $_SESSION['cache']['server_' . $server][$var];
2781 } else {
2782 return null;
2787 * Caches information in the session
2789 * @param string $var variable name
2790 * @param mixed $val value
2791 * @param int|true $server server
2793 * @return mixed
2795 function PMA_cacheSet($var, $val = null, $server = 0)
2797 if (true === $server) {
2798 $server = $GLOBALS['server'];
2800 $_SESSION['cache']['server_' . $server][$var] = $val;
2804 * Removes cached information from the session
2806 * @param string $var variable name
2807 * @param int|true $server server
2809 * @return nothing
2811 function PMA_cacheUnset($var, $server = 0)
2813 if (true === $server) {
2814 $server = $GLOBALS['server'];
2816 unset($_SESSION['cache']['server_' . $server][$var]);
2820 * Converts a bit value to printable format;
2821 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2822 * function because in PHP, decbin() supports only 32 bits
2824 * @param numeric $value coming from a BIT field
2825 * @param integer $length length
2827 * @return string the printable value
2829 function PMA_printable_bit_value($value, $length)
2831 $printable = '';
2832 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2833 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2835 $printable = substr($printable, -$length);
2836 return $printable;
2840 * Verifies whether the value contains a non-printable character
2842 * @param string $value value
2844 * @return boolean
2846 function PMA_contains_nonprintable_ascii($value)
2848 return preg_match('@[^[:print:]]@', $value);
2852 * Converts a BIT type default value
2853 * for example, b'010' becomes 010
2855 * @param string $bit_default_value value
2857 * @return string the converted value
2859 function PMA_convert_bit_default_value($bit_default_value)
2861 return strtr($bit_default_value, array("b" => "", "'" => ""));
2865 * Extracts the various parts from a field type spec
2867 * @param string $fieldspec Field specification
2869 * @return array associative array containing type, spec_in_brackets
2870 * and possibly enum_set_values (another array)
2872 function PMA_extractFieldSpec($fieldspec)
2874 $first_bracket_pos = strpos($fieldspec, '(');
2875 if ($first_bracket_pos) {
2876 $spec_in_brackets = chop(
2877 substr(
2878 $fieldspec,
2879 $first_bracket_pos + 1,
2880 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2883 // convert to lowercase just to be sure
2884 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2885 } else {
2886 $type = strtolower($fieldspec);
2887 $spec_in_brackets = '';
2890 if ('enum' == $type || 'set' == $type) {
2891 // Define our working vars
2892 $enum_set_values = array();
2893 $working = "";
2894 $in_string = false;
2895 $index = 0;
2897 // While there is another character to process
2898 while (isset($fieldspec[$index])) {
2899 // Grab the char to look at
2900 $char = $fieldspec[$index];
2902 // If it is a single quote, needs to be handled specially
2903 if ($char == "'") {
2904 // If we are not currently in a string, begin one
2905 if (! $in_string) {
2906 $in_string = true;
2907 $working = "";
2908 } else {
2909 // Otherwise, it may be either an end of a string,
2910 // or a 'double quote' which can be handled as-is
2911 // Check out the next character (if possible)
2912 $has_next = isset($fieldspec[$index + 1]);
2913 $next = $has_next ? $fieldspec[$index + 1] : null;
2915 //If we have reached the end of our 'working' string (because
2916 //there are no more chars,or the next char is not another quote)
2917 if (! $has_next || $next != "'") {
2918 $enum_set_values[] = $working;
2919 $in_string = false;
2921 } elseif ($next == "'") {
2922 // Otherwise, this is a 'double quote',
2923 // and can be added to the working string
2924 $working .= "'";
2925 // Skip the next char; we already know what it is
2926 $index++;
2929 } elseif ('\\' == $char
2930 && isset($fieldspec[$index + 1])
2931 && "'" == $fieldspec[$index + 1]
2933 // escaping of a quote?
2934 $working .= "'";
2935 $index++;
2936 } else {
2937 // Otherwise, add it to our working string like normal
2938 $working .= $char;
2940 // Increment character index
2941 $index++;
2942 } // end while
2943 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2944 $binary = false;
2945 $unsigned = false;
2946 $zerofill = false;
2947 } else {
2948 $enum_set_values = array();
2950 /* Create printable type name */
2951 $printtype = strtolower($fieldspec);
2953 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2954 // this would be a BINARY or VARBINARY field type;
2955 // by the way, a BLOB should not show the BINARY attribute
2956 // because this is not accepted in MySQL syntax.
2957 if (preg_match('@binary@', $printtype) && ! preg_match('@binary[\(]@', $printtype)) {
2958 $printtype = preg_replace('@binary@', '', $printtype);
2959 $binary = true;
2960 } else {
2961 $binary = false;
2963 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2964 $zerofill = ($zerofill_cnt > 0);
2965 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
2966 $unsigned = ($unsigned_cnt > 0);
2967 $printtype = trim($printtype);
2971 $attribute = ' ';
2972 if ($binary) {
2973 $attribute = 'BINARY';
2975 if ($unsigned) {
2976 $attribute = 'UNSIGNED';
2978 if ($zerofill) {
2979 $attribute = 'UNSIGNED ZEROFILL';
2982 return array(
2983 'type' => $type,
2984 'spec_in_brackets' => $spec_in_brackets,
2985 'enum_set_values' => $enum_set_values,
2986 'print_type' => $printtype,
2987 'binary' => $binary,
2988 'unsigned' => $unsigned,
2989 'zerofill' => $zerofill,
2990 'attribute' => $attribute,
2995 * Verifies if this table's engine supports foreign keys
2997 * @param string $engine engine
2999 * @return boolean
3001 function PMA_foreignkey_supported($engine)
3003 $engine = strtoupper($engine);
3004 if ('INNODB' == $engine || 'PBXT' == $engine) {
3005 return true;
3006 } else {
3007 return false;
3012 * Replaces some characters by a displayable equivalent
3014 * @param string $content content
3016 * @return string the content with characters replaced
3018 function PMA_replace_binary_contents($content)
3020 $result = str_replace("\x00", '\0', $content);
3021 $result = str_replace("\x08", '\b', $result);
3022 $result = str_replace("\x0a", '\n', $result);
3023 $result = str_replace("\x0d", '\r', $result);
3024 $result = str_replace("\x1a", '\Z', $result);
3025 return $result;
3029 * Converts GIS data to Well Known Text format
3031 * @param binary $data GIS data
3032 * @param bool $includeSRID Add SRID to the WKT
3034 * @return GIS data in Well Know Text format
3036 function PMA_asWKT($data, $includeSRID = false)
3038 // Convert to WKT format
3039 $hex = bin2hex($data);
3040 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3041 if ($includeSRID) {
3042 $wktsql .= ", SRID(x'" . $hex . "')";
3044 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
3045 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
3046 $wktval = $wktarr[0];
3047 if ($includeSRID) {
3048 $srid = $wktarr[1];
3049 $wktval = "'" . $wktval . "'," . $srid;
3051 @PMA_DBI_free_result($wktresult);
3052 return $wktval;
3056 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3058 * @param string $string string
3060 * @return string with the chars replaced
3063 function PMA_duplicateFirstNewline($string)
3065 $first_occurence = strpos($string, "\r\n");
3066 if ($first_occurence === 0) {
3067 $string = "\n".$string;
3069 return $string;
3073 * Get the action word corresponding to a script name
3074 * in order to display it as a title in navigation panel
3076 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3077 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3079 * @return array
3081 function PMA_getTitleForTarget($target)
3083 $mapping = array(
3084 // Values for $cfg['DefaultTabTable']
3085 'tbl_structure.php' => __('Structure'),
3086 'tbl_sql.php' => __('SQL'),
3087 'tbl_select.php' =>__('Search'),
3088 'tbl_change.php' =>__('Insert'),
3089 'sql.php' => __('Browse'),
3091 // Values for $cfg['DefaultTabDatabase']
3092 'db_structure.php' => __('Structure'),
3093 'db_sql.php' => __('SQL'),
3094 'db_search.php' => __('Search'),
3095 'db_operations.php' => __('Operations'),
3097 return $mapping[$target];
3101 * Formats user string, expanding @VARIABLES@, accepting strftime format string.
3103 * @param string $string Text where to do expansion.
3104 * @param function $escape Function to call for escaping variable values.
3105 * @param array $updates Array with overrides for default parameters
3106 * (obtained from GLOBALS).
3108 * @return string
3110 function PMA_expandUserString($string, $escape = null, $updates = array())
3112 /* Content */
3113 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
3114 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3115 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3116 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3117 ? $GLOBALS['cfg']['Server']['verbose']
3118 : $GLOBALS['cfg']['Server']['host'];
3119 $vars['database'] = $GLOBALS['db'];
3120 $vars['table'] = $GLOBALS['table'];
3121 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3123 /* Update forced variables */
3124 foreach ($updates as $key => $val) {
3125 $vars[$key] = $val;
3128 /* Replacement mapping */
3130 * The __VAR__ ones are for backward compatibility, because user
3131 * might still have it in cookies.
3133 $replace = array(
3134 '@HTTP_HOST@' => $vars['http_host'],
3135 '@SERVER@' => $vars['server_name'],
3136 '__SERVER__' => $vars['server_name'],
3137 '@VERBOSE@' => $vars['server_verbose'],
3138 '@VSERVER@' => $vars['server_verbose_or_name'],
3139 '@DATABASE@' => $vars['database'],
3140 '__DB__' => $vars['database'],
3141 '@TABLE@' => $vars['table'],
3142 '__TABLE__' => $vars['table'],
3143 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3146 /* Optional escaping */
3147 if (!is_null($escape)) {
3148 foreach ($replace as $key => $val) {
3149 $replace[$key] = $escape($val);
3153 /* Backward compatibility in 3.5.x */
3154 if (strpos($string, '@FIELDS@') !== false) {
3155 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3158 /* Fetch columns list if required */
3159 if (strpos($string, '@COLUMNS@') !== false) {
3160 $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3162 $column_names = array();
3163 foreach ($columns_list as $column) {
3164 if (! is_null($escape)) {
3165 $column_names[] = $escape($column['Field']);
3166 } else {
3167 $column_names[] = $field['Field'];
3171 $replace['@COLUMNS@'] = implode(',', $column_names);
3174 /* Do the replacement */
3175 return strtr(strftime($string), $replace);
3179 * function that generates a json output for an ajax request and ends script
3180 * execution
3182 * @param PMA_Message|string $message message string containing the
3183 * html of the message
3184 * @param bool $success success whether the ajax request
3185 * was successfull
3186 * @param array $extra_data extra data optional -
3187 * any other data as part of the json request
3189 * @return nothing
3191 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3193 $response = array();
3194 if ( $success == true ) {
3195 $response['success'] = true;
3196 if ($message instanceof PMA_Message) {
3197 $response['message'] = $message->getDisplay();
3198 } else {
3199 $response['message'] = $message;
3201 } else {
3202 $response['success'] = false;
3203 if ($message instanceof PMA_Message) {
3204 $response['error'] = $message->getDisplay();
3205 } else {
3206 $response['error'] = $message;
3210 // If extra_data has been provided, append it to the response array
3211 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3212 $response = array_merge($response, $extra_data);
3215 // Set the Content-Type header to JSON so that jQuery parses the
3216 // response correctly.
3218 // At this point, other headers might have been sent;
3219 // even if $GLOBALS['is_header_sent'] is true,
3220 // we have to send these additional headers.
3221 header('Cache-Control: no-cache');
3222 header("Content-Type: application/json");
3224 echo json_encode($response);
3226 if (!defined('TESTSUITE'))
3227 exit;
3231 * Display the form used to browse anywhere on the local server for a file to import
3233 * @param string $max_upload_size maximum upload size
3235 * @return nothing
3237 function PMA_browseUploadFile($max_upload_size)
3239 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3240 echo '<div id="upload_form_status" style="display: none;"></div>';
3241 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3242 echo '<input type="file" name="import_file" id="input_import_file" />';
3243 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3244 // some browsers should respect this :)
3245 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3249 * Display the form used to select a file to import from the server upload directory
3251 * @param array $import_list array of import types
3252 * @param string $uploaddir upload directory
3254 * @return nothing
3256 function PMA_selectUploadFile($import_list, $uploaddir)
3258 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3259 $extensions = '';
3260 foreach ($import_list as $key => $val) {
3261 if (!empty($extensions)) {
3262 $extensions .= '|';
3264 $extensions .= $val['extension'];
3266 $matcher = '@\.(' . $extensions . ')(\.('
3267 . PMA_supportedDecompressions() . '))?$@';
3269 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3270 ? $local_import_file
3271 : '';
3272 $files = PMA_getFileSelectOptions(
3273 PMA_userDir($uploaddir),
3274 $matcher,
3275 $active
3277 if ($files === false) {
3278 PMA_Message::error(
3279 __('The directory you set for upload work cannot be reached')
3280 )->display();
3281 } elseif (!empty($files)) {
3282 echo "\n";
3283 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3284 echo ' <option value="">&nbsp;</option>' . "\n";
3285 echo $files;
3286 echo ' </select>' . "\n";
3287 } elseif (empty ($files)) {
3288 echo '<i>' . __('There are no files to upload') . '</i>';
3293 * Build titles and icons for action links
3295 * @return array the action titles
3297 function PMA_buildActionTitles()
3299 $titles = array();
3301 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3302 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3303 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3304 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3305 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3306 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3307 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3308 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3309 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3310 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3311 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3312 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3313 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3314 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3315 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3316 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3317 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3318 return $titles;
3322 * This function processes the datatypes supported by the DB, as specified in
3323 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3324 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3326 * @param bool $html Whether to generate an html snippet or an array
3327 * @param string $selected The value to mark as selected in HTML mode
3329 * @return mixed An HTML snippet or an array of datatypes.
3332 function PMA_getSupportedDatatypes($html = false, $selected = '')
3334 global $cfg;
3336 if ($html) {
3337 // NOTE: the SELECT tag in not included in this snippet.
3338 $retval = '';
3339 foreach ($cfg['ColumnTypes'] as $key => $value) {
3340 if (is_array($value)) {
3341 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3342 foreach ($value as $subvalue) {
3343 if ($subvalue == $selected) {
3344 $retval .= "<option selected='selected'>";
3345 $retval .= $subvalue;
3346 $retval .= "</option>";
3347 } else if ($subvalue === '-') {
3348 $retval .= "<option disabled='disabled'>";
3349 $retval .= $subvalue;
3350 $retval .= "</option>";
3351 } else {
3352 $retval .= "<option>$subvalue</option>";
3355 $retval .= '</optgroup>';
3356 } else {
3357 if ($selected == $value) {
3358 $retval .= "<option selected='selected'>$value</option>";
3359 } else {
3360 $retval .= "<option>$value</option>";
3364 } else {
3365 $retval = array();
3366 foreach ($cfg['ColumnTypes'] as $value) {
3367 if (is_array($value)) {
3368 foreach ($value as $subvalue) {
3369 if ($subvalue !== '-') {
3370 $retval[] = $subvalue;
3373 } else {
3374 if ($value !== '-') {
3375 $retval[] = $value;
3381 return $retval;
3382 } // end PMA_getSupportedDatatypes()
3385 * Returns a list of datatypes that are not (yet) handled by PMA.
3386 * Used by: tbl_change.php and libraries/db_routines.inc.php
3388 * @return array list of datatypes
3390 function PMA_unsupportedDatatypes()
3392 $no_support_types = array();
3393 return $no_support_types;
3397 * Return GIS data types
3399 * @param bool $upper_case whether to return values in upper case
3401 * @return array GIS data types
3403 function PMA_getGISDatatypes($upper_case = false)
3405 $gis_data_types = array(
3406 'geometry',
3407 'point',
3408 'linestring',
3409 'polygon',
3410 'multipoint',
3411 'multilinestring',
3412 'multipolygon',
3413 'geometrycollection'
3415 if ($upper_case) {
3416 for ($i = 0; $i < count($gis_data_types); $i++) {
3417 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3421 return $gis_data_types;
3425 * Generates GIS data based on the string passed.
3427 * @param string $gis_string GIS string
3429 * @return GIS data enclosed in 'GeomFromText' function
3431 function PMA_createGISData($gis_string)
3433 $gis_string = trim($gis_string);
3434 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3435 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3436 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3437 return 'GeomFromText(' . $gis_string . ')';
3438 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3439 return "GeomFromText('" . $gis_string . "')";
3440 } else {
3441 return $gis_string;
3446 * Returns the names and details of the functions
3447 * that can be applied on geometry data typess.
3449 * @param string $geom_type if provided the output is limited to the functions
3450 * that are applicable to the provided geometry type.
3451 * @param bool $binary if set to false functions that take two geometries
3452 * as arguments will not be included.
3453 * @param bool $display if set to true seperators will be added to the
3454 * output array.
3456 * @return array names and details of the functions that can be applied on
3457 * geometry data typess.
3459 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3461 $funcs = array();
3462 if ($display) {
3463 $funcs[] = array('display' => ' ');
3466 // Unary functions common to all geomety types
3467 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3468 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3469 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3470 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3471 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3472 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3474 $geom_type = trim(strtolower($geom_type));
3475 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3476 $funcs[] = array('display' => '--------');
3479 // Unary functions that are specific to each geomety type
3480 if ($geom_type == 'point') {
3481 $funcs['X'] = array('params' => 1, 'type' => 'float');
3482 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3484 } elseif ($geom_type == 'multipoint') {
3485 // no fucntions here
3486 } elseif ($geom_type == 'linestring') {
3487 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3488 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3489 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3490 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3491 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3493 } elseif ($geom_type == 'multilinestring') {
3494 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3495 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3497 } elseif ($geom_type == 'polygon') {
3498 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3499 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3500 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3502 } elseif ($geom_type == 'multipolygon') {
3503 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3504 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3505 // Not yet implemented in MySQL
3506 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3508 } elseif ($geom_type == 'geometrycollection') {
3509 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3512 // If we are asked for binary functions as well
3513 if ($binary) {
3514 // section seperator
3515 if ($display) {
3516 $funcs[] = array('display' => '--------');
3518 if (PMA_MYSQL_INT_VERSION < 50601) {
3519 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3520 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3521 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3522 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3523 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3524 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3525 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3526 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3527 } else {
3528 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3529 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3530 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3531 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3532 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3533 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3534 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3535 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3536 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3540 if ($display) {
3541 $funcs[] = array('display' => '--------');
3543 // Minimum bounding rectangle functions
3544 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3545 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3546 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3547 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3548 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3549 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3550 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3552 return $funcs;
3556 * Creates a dropdown box with MySQL functions for a particular column.
3558 * @param array $field Data about the column for which
3559 * to generate the dropdown
3560 * @param bool $insert_mode Whether the operation is 'insert'
3562 * @global array $cfg PMA configuration
3563 * @global array $analyzed_sql Analyzed SQL query
3564 * @global mixed $data (null/string) FIXME: what is this for?
3566 * @return string An HTML snippet of a dropdown list with function
3567 * names appropriate for the requested column.
3569 function PMA_getFunctionsForField($field, $insert_mode)
3571 global $cfg, $analyzed_sql, $data;
3573 $selected = '';
3574 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3575 // or something similar. Then directly look up the entry in the
3576 // RestrictFunctions array, which'll then reveal the available dropdown options
3577 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3578 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3580 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3581 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3582 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3583 } else {
3584 $dropdown = array();
3585 $default_function = '';
3587 $dropdown_built = array();
3588 $op_spacing_needed = false;
3589 // what function defined as default?
3590 // for the first timestamp we don't set the default function
3591 // if there is a default value for the timestamp
3592 // (not including CURRENT_TIMESTAMP)
3593 // and the column does not have the
3594 // ON UPDATE DEFAULT TIMESTAMP attribute.
3595 if ($field['True_Type'] == 'timestamp'
3596 && empty($field['Default'])
3597 && empty($data)
3598 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3600 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3602 // For primary keys of type char(36) or varchar(36) UUID if the default function
3603 // Only applies to insert mode, as it would silently trash data on updates.
3604 if ($insert_mode
3605 && $field['Key'] == 'PRI'
3606 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3608 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3610 // this is set only when appropriate and is always true
3611 if (isset($field['display_binary_as_hex'])) {
3612 $default_function = 'UNHEX';
3615 // Create the output
3616 $retval = ' <option></option>' . "\n";
3617 // loop on the dropdown array and print all available options for that field.
3618 foreach ($dropdown as $each_dropdown) {
3619 $retval .= ' ';
3620 $retval .= '<option';
3621 if ($default_function === $each_dropdown) {
3622 $retval .= ' selected="selected"';
3624 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3625 $dropdown_built[$each_dropdown] = 'true';
3626 $op_spacing_needed = true;
3628 // For compatibility's sake, do not let out all other functions. Instead
3629 // print a separator (blank) and then show ALL functions which weren't shown
3630 // yet.
3631 $cnt_functions = count($cfg['Functions']);
3632 for ($j = 0; $j < $cnt_functions; $j++) {
3633 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3634 || $dropdown_built[$cfg['Functions'][$j]] != 'true'
3636 // Is current function defined as default?
3637 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3638 || (! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3639 ? ' selected="selected"'
3640 : '';
3641 if ($op_spacing_needed == true) {
3642 $retval .= ' ';
3643 $retval .= '<option value="">--------</option>' . "\n";
3644 $op_spacing_needed = false;
3647 $retval .= ' ';
3648 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3649 . '</option>' . "\n";
3651 } // end for
3653 return $retval;
3654 } // end PMA_getFunctionsForField()
3657 * Checks if the current user has a specific privilege and returns true if the
3658 * user indeed has that privilege or false if (s)he doesn't. This function must
3659 * only be used for features that are available since MySQL 5, because it
3660 * relies on the INFORMATION_SCHEMA database to be present.
3662 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3663 * // Checks if the currently logged in user has the global
3664 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3665 * // user has this privilege on database 'mydb'.
3667 * @param string $priv The privilege to check
3668 * @param mixed $db null, to only check global privileges
3669 * string, db name where to also check for privileges
3670 * @param mixed $tbl null, to only check global privileges
3671 * string, db name where to also check for privileges
3673 * @return bool
3675 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3677 // Get the username for the current user in the format
3678 // required to use in the information schema database.
3679 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3680 if ($user === false) {
3681 return false;
3683 $user = explode('@', $user);
3684 $username = "''";
3685 $username .= str_replace("'", "''", $user[0]);
3686 $username .= "''@''";
3687 $username .= str_replace("'", "''", $user[1]);
3688 $username .= "''";
3689 // Prepage the query
3690 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3691 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3692 // Check global privileges first.
3693 if (PMA_DBI_fetch_value(
3694 sprintf(
3695 $query,
3696 'USER_PRIVILEGES',
3697 $username,
3698 $priv
3702 return true;
3704 // If a database name was provided and user does not have the
3705 // required global privilege, try database-wise permissions.
3706 if ($db !== null) {
3707 $query .= " AND TABLE_SCHEMA='%s'";
3708 if (PMA_DBI_fetch_value(
3709 sprintf(
3710 $query,
3711 'SCHEMA_PRIVILEGES',
3712 $username,
3713 $priv,
3714 PMA_sqlAddSlashes($db)
3718 return true;
3720 } else {
3721 // There was no database name provided and the user
3722 // does not have the correct global privilege.
3723 return false;
3725 // If a table name was also provided and we still didn't
3726 // find any valid privileges, try table-wise privileges.
3727 if ($tbl !== null) {
3728 $query .= " AND TABLE_NAME='%s'";
3729 if ($retval = PMA_DBI_fetch_value(
3730 sprintf(
3731 $query,
3732 'TABLE_PRIVILEGES',
3733 $username,
3734 $priv,
3735 PMA_sqlAddSlashes($db),
3736 PMA_sqlAddSlashes($tbl)
3740 return true;
3743 // If we reached this point, the user does not
3744 // have even valid table-wise privileges.
3745 return false;
3749 * Returns server type for current connection
3751 * Known types are: Drizzle, MariaDB and MySQL (default)
3753 * @return string
3755 function PMA_getServerType()
3757 $server_type = 'MySQL';
3758 if (PMA_DRIZZLE) {
3759 $server_type = 'Drizzle';
3760 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3761 $server_type = 'MariaDB';
3762 } else if (stripos(PMA_MYSQL_VERSION_COMMENT, 'percona') !== false) {
3763 $server_type = 'Percona Server';
3765 return $server_type;
3769 * Analyzes the limit clause and return the start and length attributes of it.
3771 * @param string $limit_clause limit clause
3773 * @return array Start and length attributes of the limit clause
3775 function PMA_analyzeLimitClause($limit_clause)
3777 $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
3778 return array(
3779 'start' => trim($start_and_length[0]),
3780 'length' => trim($start_and_length[1])
3785 * Outputs HTML code for print button.
3787 * @return nothing
3789 function PMA_printButton()
3791 echo '<p class="print_ignore">';
3792 echo '<input type="button" id="print" value="' . __('Print') . '" />';
3793 echo '</p>';