Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / libraries / common.lib.php
blob777baa05f927d8dae675ce81559ad2bb6d150157
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 * string PMA_getIcon(string $icon)
76 * @param string $icon name of icon file
77 * @param string $alternate alternate text
78 * @param boolean $force_text whether to force alternate text to be displayed
79 * @param boolean $noSprite If true, the image source will be not replaced with a CSS Sprite
81 * @return html img tag
83 function PMA_getIcon($icon, $alternate = '', $force_text = false, $noSprite = false)
85 // $cfg['PropertiesIconic'] is true or both
86 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
87 // $cfg['PropertiesIconic'] is false or both
88 // OR we have no $include_icon
89 $include_text = ($force_text || true !== $GLOBALS['cfg']['PropertiesIconic']);
90 $alternate = htmlspecialchars($alternate);
91 $button = '';
93 // Always use a span (we rely on this in js/sql.js)
94 $button .= '<span class="nowrap">';
96 if ($include_icon) {
97 if($noSprite) {
98 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
99 . ' class="icon" width="16" height="16" />';
100 } else {
101 $button .= '<img src="themes/dot.gif"'
102 . ' title="' . $alternate . '" alt="' . $alternate . '"'
103 . ' class="icon ic_' . str_replace(array('.gif','.png'), '', $icon) . '" />';
107 if ($include_icon && $include_text) {
108 $button .= ' ';
111 if ($include_text) {
112 $button .= $alternate;
115 $button .= '</span>';
117 return $button;
121 * Displays the maximum size for an upload
123 * @param integer $max_upload_size the size
125 * @return string the message
127 * @access public
129 function PMA_displayMaximumUploadSize($max_upload_size)
131 // I have to reduce the second parameter (sensitiveness) from 6 to 4
132 // to avoid weird results like 512 kKib
133 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
134 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
138 * Generates a hidden field which should indicate to the browser
139 * the maximum size for upload
141 * @param integer $max_size the size
143 * @return string the INPUT field
145 * @access public
147 function PMA_generateHiddenMaxFileSize($max_size)
149 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
153 * Add slashes before "'" and "\" characters so a value containing them can
154 * be used in a sql comparison.
156 * @param string $a_string the string to slash
157 * @param bool $is_like whether the string will be used in a 'LIKE' clause
158 * (it then requires two more escaped sequences) or not
159 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
160 * (converts \n to \\n, \r to \\r)
161 * @param bool $php_code whether this function is used as part of the
162 * "Create PHP code" dialog
164 * @return string the slashed string
166 * @access public
168 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
170 if ($is_like) {
171 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
172 } else {
173 $a_string = str_replace('\\', '\\\\', $a_string);
176 if ($crlf) {
177 $a_string = strtr(
178 $a_string,
179 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
183 if ($php_code) {
184 $a_string = str_replace('\'', '\\\'', $a_string);
185 } else {
186 $a_string = str_replace('\'', '\'\'', $a_string);
189 return $a_string;
190 } // end of the 'PMA_sqlAddSlashes()' function
194 * Add slashes before "_" and "%" characters for using them in MySQL
195 * database, table and field names.
196 * Note: This function does not escape backslashes!
198 * @param string $name the string to escape
200 * @return string the escaped string
202 * @access public
204 function PMA_escape_mysql_wildcards($name)
206 return strtr($name, array('_' => '\\_', '%' => '\\%'));
207 } // end of the 'PMA_escape_mysql_wildcards()' function
210 * removes slashes before "_" and "%" characters
211 * Note: This function does not unescape backslashes!
213 * @param string $name the string to escape
215 * @return string the escaped string
217 * @access public
219 function PMA_unescape_mysql_wildcards($name)
221 return strtr($name, array('\\_' => '_', '\\%' => '%'));
222 } // end of the 'PMA_unescape_mysql_wildcards()' function
225 * removes quotes (',",`) from a quoted string
227 * checks if the sting is quoted and removes this quotes
229 * @param string $quoted_string string to remove quotes from
230 * @param string $quote type of quote to remove
232 * @return string unqoted string
234 function PMA_unQuote($quoted_string, $quote = null)
236 $quotes = array();
238 if (null === $quote) {
239 $quotes[] = '`';
240 $quotes[] = '"';
241 $quotes[] = "'";
242 } else {
243 $quotes[] = $quote;
246 foreach ($quotes as $quote) {
247 if (substr($quoted_string, 0, 1) === $quote
248 && substr($quoted_string, -1, 1) === $quote) {
249 $unquoted_string = substr($quoted_string, 1, -1);
250 // replace escaped quotes
251 $unquoted_string = str_replace(
252 $quote . $quote,
253 $quote,
254 $unquoted_string);
255 return $unquoted_string;
259 return $quoted_string;
263 * format sql strings
265 * @todo move into PMA_Sql
266 * @param mixed $parsed_sql pre-parsed SQL structure
267 * @param string $unparsed_sql raw SQL string
269 * @return string the formatted sql
271 * @global array the configuration array
272 * @global boolean whether the current statement is a multiple one or not
274 * @access public
277 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
279 global $cfg;
281 // Check that we actually have a valid set of parsed data
282 // well, not quite
283 // first check for the SQL parser having hit an error
284 if (PMA_SQP_isError()) {
285 return htmlspecialchars($parsed_sql['raw']);
287 // then check for an array
288 if (! is_array($parsed_sql)) {
289 // We don't so just return the input directly
290 // This is intended to be used for when the SQL Parser is turned off
291 $formatted_sql = "<pre>\n";
292 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
293 $formatted_sql .= $unparsed_sql;
294 } else {
295 $formatted_sql .= $parsed_sql;
297 $formatted_sql .= "\n</pre>";
298 return $formatted_sql;
301 $formatted_sql = '';
303 switch ($cfg['SQP']['fmtType']) {
304 case 'none':
305 if ($unparsed_sql != '') {
306 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
307 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
308 . '</pre></span>';
309 } else {
310 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
312 break;
313 case 'html':
314 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
315 break;
316 case 'text':
317 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
318 break;
319 default:
320 break;
321 } // end switch
323 return $formatted_sql;
324 } // end of the "PMA_formatSql()" function
328 * Displays a link to the official MySQL documentation
330 * @param string $chapter chapter of "HTML, one page per chapter" documentation
331 * @param string $link contains name of page/anchor that is being linked
332 * @param bool $big_icon whether to use big icon (like in left frame)
333 * @param string $anchor anchor to page part
334 * @param bool $just_open whether only the opening <a> tag should be returned
336 * @return string the html link
338 * @access public
340 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
342 global $cfg;
344 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
345 return '';
348 // Fixup for newly used names:
349 $chapter = str_replace('_', '-', strtolower($chapter));
350 $link = str_replace('_', '-', strtolower($link));
352 switch ($cfg['MySQLManualType']) {
353 case 'chapters':
354 if (empty($chapter)) {
355 $chapter = 'index';
357 if (empty($anchor)) {
358 $anchor = $link;
360 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
361 break;
362 case 'big':
363 if (empty($anchor)) {
364 $anchor = $link;
366 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
367 break;
368 case 'searchable':
369 if (empty($link)) {
370 $link = 'index';
372 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
373 if (!empty($anchor)) {
374 $url .= '#' . $anchor;
376 break;
377 case 'viewable':
378 default:
379 if (empty($link)) {
380 $link = 'index';
382 $mysql = '5.0';
383 $lang = 'en';
384 if (defined('PMA_MYSQL_INT_VERSION')) {
385 if (PMA_MYSQL_INT_VERSION >= 50500) {
386 $mysql = '5.5';
387 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
388 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
389 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
390 $mysql = '5.1';
391 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
392 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
393 } else {
394 $mysql = '5.0';
395 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
396 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
399 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
400 if (!empty($anchor)) {
401 $url .= '#' . $anchor;
403 break;
406 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
407 if ($just_open) {
408 return $open_link;
409 } elseif ($big_icon) {
410 return $open_link . '<img class="icon ic_b_sqlhelp" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
411 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
412 return $open_link . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
413 } else {
414 return '[' . $open_link . __('Documentation') . '</a>]';
416 } // end of the 'PMA_showMySQLDocu()' function
420 * Displays a link to the phpMyAdmin documentation
422 * @param string $anchor anchor in documentation
424 * @return string the html link
426 * @access public
428 function PMA_showDocu($anchor)
430 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
431 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
432 } else {
433 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
435 } // end of the 'PMA_showDocu()' function
438 * Displays a link to the PHP documentation
440 * @param string $target anchor in documentation
442 * @return string the html link
444 * @access public
446 function PMA_showPHPDocu($target)
448 $url = PMA_getPHPDocLink($target);
450 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
451 return '<a href="' . $url . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
452 } else {
453 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
455 } // end of the 'PMA_showPHPDocu()' function
458 * returns HTML for a footnote marker and add the messsage to the footnotes
460 * @param string $message the error message
461 * @param bool $bbcode
462 * @param string $type
464 * @return string html code for a footnote marker
466 * @access public
468 function PMA_showHint($message, $bbcode = false, $type = 'notice')
470 if ($message instanceof PMA_Message) {
471 $key = $message->getHash();
472 $type = $message->getLevel();
473 } else {
474 $key = md5($message);
477 if (! isset($GLOBALS['footnotes'][$key])) {
478 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
479 $GLOBALS['footnotes'] = array();
481 $nr = count($GLOBALS['footnotes']) + 1;
482 $GLOBALS['footnotes'][$key] = array(
483 'note' => $message,
484 'type' => $type,
485 'nr' => $nr,
487 } else {
488 $nr = $GLOBALS['footnotes'][$key]['nr'];
491 if ($bbcode) {
492 return '[sup]' . $nr . '[/sup]';
495 // footnotemarker used in js/tooltip.js
496 return '<sup class="footnotemarker">' . $nr . '</sup>' .
497 '<img class="footnotemarker footnote_' . $nr . ' ic_b_help" src="themes/dot.gif" alt="" />';
501 * Displays a MySQL error message in the right frame.
503 * @param string $error_message the error message
504 * @param string $the_query the sql query that failed
505 * @param bool $is_modify_link whether to show a "modify" link or not
506 * @param string $back_url the "back" link url (full path is not required)
507 * @param bool $exit EXIT the page?
509 * @global string the curent table
510 * @global string the current db
512 * @access public
514 function PMA_mysqlDie($error_message = '', $the_query = '',
515 $is_modify_link = true, $back_url = '', $exit = true)
517 global $table, $db;
520 * start http output, display html headers
522 require_once './libraries/header.inc.php';
524 $error_msg_output = '';
526 if (!$error_message) {
527 $error_message = PMA_DBI_getError();
529 if (!$the_query && !empty($GLOBALS['sql_query'])) {
530 $the_query = $GLOBALS['sql_query'];
533 // --- Added to solve bug #641765
534 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
535 $formatted_sql = htmlspecialchars($the_query);
536 } elseif (empty($the_query) || trim($the_query) == '') {
537 $formatted_sql = '';
538 } else {
539 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
540 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
541 } else {
542 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
545 // ---
546 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
547 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
548 // if the config password is wrong, or the MySQL server does not
549 // respond, do not show the query that would reveal the
550 // username/password
551 if (!empty($the_query) && !strstr($the_query, 'connect')) {
552 // --- Added to solve bug #641765
553 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
554 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
555 $error_msg_output .= '<br />' . "\n";
557 // ---
558 // modified to show the help on sql errors
559 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
560 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
561 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
563 if ($is_modify_link) {
564 $_url_params = array(
565 'sql_query' => $the_query,
566 'show_query' => 1,
568 if (strlen($table)) {
569 $_url_params['db'] = $db;
570 $_url_params['table'] = $table;
571 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
572 } elseif (strlen($db)) {
573 $_url_params['db'] = $db;
574 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
575 } else {
576 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
579 $error_msg_output .= $doedit_goto
580 . PMA_getIcon('b_edit.png', __('Edit'))
581 . '</a>';
582 } // end if
583 $error_msg_output .= ' </p>' . "\n"
584 .' <p>' . "\n"
585 .' ' . $formatted_sql . "\n"
586 .' </p>' . "\n";
587 } // end if
589 if (!empty($error_message)) {
590 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
592 // modified to show the help on error-returns
593 // (now error-messages-server)
594 $error_msg_output .= '<p>' . "\n"
595 . ' <strong>' . __('MySQL said: ') . '</strong>'
596 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
597 . "\n"
598 . '</p>' . "\n";
600 // The error message will be displayed within a CODE segment.
601 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
603 // Replace all non-single blanks with their HTML-counterpart
604 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
605 // Replace TAB-characters with their HTML-counterpart
606 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
607 // Replace linebreaks
608 $error_message = nl2br($error_message);
610 $error_msg_output .= '<code>' . "\n"
611 . $error_message . "\n"
612 . '</code><br />' . "\n";
613 $error_msg_output .= '</div>';
615 $_SESSION['Import_message']['message'] = $error_msg_output;
617 if ($exit) {
619 * If in an Ajax request
620 * - avoid displaying a Back link
621 * - use PMA_ajaxResponse() to transmit the message and exit
623 if ($GLOBALS['is_ajax_request'] == true) {
624 PMA_ajaxResponse($error_msg_output, false);
626 if (! empty($back_url)) {
627 if (strstr($back_url, '?')) {
628 $back_url .= '&amp;no_history=true';
629 } else {
630 $back_url .= '?no_history=true';
633 $_SESSION['Import_message']['go_back_url'] = $back_url;
635 $error_msg_output .= '<fieldset class="tblFooters">';
636 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
637 $error_msg_output .= '</fieldset>' . "\n\n";
640 echo $error_msg_output;
642 * display footer and exit
644 require './libraries/footer.inc.php';
645 } else {
646 echo $error_msg_output;
648 } // end of the 'PMA_mysqlDie()' function
651 * returns array with tables of given db with extended information and grouped
653 * @param string $db name of db
654 * @param string $tables name of tables
655 * @param integer $limit_offset list offset
656 * @param int|bool $limit_count max tables to return
658 * @return array (recursive) grouped table list
660 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
662 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
664 if (null === $tables) {
665 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
666 if ($GLOBALS['cfg']['NaturalOrder']) {
667 uksort($tables, 'strnatcasecmp');
671 if (count($tables) < 1) {
672 return $tables;
675 $default = array(
676 'Name' => '',
677 'Rows' => 0,
678 'Comment' => '',
679 'disp_name' => '',
682 $table_groups = array();
684 // for blobstreaming - list of blobstreaming tables
686 // load PMA configuration
687 $PMA_Config = $GLOBALS['PMA_Config'];
689 foreach ($tables as $table_name => $table) {
690 // if BS tables exist
691 if (PMA_BS_IsHiddenTable($table_name)) {
692 continue;
695 // check for correct row count
696 if (null === $table['Rows']) {
697 // Do not check exact row count here,
698 // if row count is invalid possibly the table is defect
699 // and this would break left frame;
700 // but we can check row count if this is a view or the
701 // information_schema database
702 // since PMA_Table::countRecords() returns a limited row count
703 // in this case.
705 // set this because PMA_Table::countRecords() can use it
706 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
708 if ($tbl_is_view || strtolower($db) == 'information_schema'
709 || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
710 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'], false, true);
714 // in $group we save the reference to the place in $table_groups
715 // where to store the table info
716 if ($GLOBALS['cfg']['LeftFrameDBTree']
717 && $sep && strstr($table_name, $sep))
719 $parts = explode($sep, $table_name);
721 $group =& $table_groups;
722 $i = 0;
723 $group_name_full = '';
724 $parts_cnt = count($parts) - 1;
725 while ($i < $parts_cnt
726 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
727 $group_name = $parts[$i] . $sep;
728 $group_name_full .= $group_name;
730 if (! isset($group[$group_name])) {
731 $group[$group_name] = array();
732 $group[$group_name]['is' . $sep . 'group'] = true;
733 $group[$group_name]['tab' . $sep . 'count'] = 1;
734 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
735 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
736 $table = $group[$group_name];
737 $group[$group_name] = array();
738 $group[$group_name][$group_name] = $table;
739 unset($table);
740 $group[$group_name]['is' . $sep . 'group'] = true;
741 $group[$group_name]['tab' . $sep . 'count'] = 1;
742 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
743 } else {
744 $group[$group_name]['tab' . $sep . 'count']++;
746 $group =& $group[$group_name];
747 $i++;
749 } else {
750 if (! isset($table_groups[$table_name])) {
751 $table_groups[$table_name] = array();
753 $group =& $table_groups;
757 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
758 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
759 // switch tooltip and name
760 $table['Comment'] = $table['Name'];
761 $table['disp_name'] = $table['Comment'];
762 } else {
763 $table['disp_name'] = $table['Name'];
766 $group[$table_name] = array_merge($default, $table);
769 return $table_groups;
772 /* ----------------------- Set of misc functions ----------------------- */
776 * Adds backquotes on both sides of a database, table or field name.
777 * and escapes backquotes inside the name with another backquote
779 * example:
780 * <code>
781 * echo PMA_backquote('owner`s db'); // `owner``s db`
783 * </code>
785 * @param mixed $a_name the database, table or field name to "backquote"
786 * or array of it
787 * @param boolean $do_it a flag to bypass this function (used by dump
788 * functions)
790 * @return mixed the "backquoted" database, table or field name
792 * @access public
794 function PMA_backquote($a_name, $do_it = true)
796 if (is_array($a_name)) {
797 foreach ($a_name as &$data) {
798 $data = PMA_backquote($data, $do_it);
800 return $a_name;
803 if (! $do_it) {
804 global $PMA_SQPdata_forbidden_word;
806 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
807 return $a_name;
811 // '0' is also empty for php :-(
812 if (strlen($a_name) && $a_name !== '*') {
813 return '`' . str_replace('`', '``', $a_name) . '`';
814 } else {
815 return $a_name;
817 } // end of the 'PMA_backquote()' function
820 * Defines the <CR><LF> value depending on the user OS.
822 * @return string the <CR><LF> value to use
824 * @access public
826 function PMA_whichCrlf()
828 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
829 // Win case
830 if (PMA_USR_OS == 'Win') {
831 $the_crlf = "\r\n";
833 // Others
834 else {
835 $the_crlf = "\n";
838 return $the_crlf;
839 } // end of the 'PMA_whichCrlf()' function
842 * Reloads navigation if needed.
844 * @param bool $jsonly prints out pure JavaScript
846 * @access public
848 function PMA_reloadNavigation($jsonly=false)
850 // Reloads the navigation frame via JavaScript if required
851 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
852 // one of the reasons for a reload is when a table is dropped
853 // in this case, get rid of the table limit offset, otherwise
854 // we have a problem when dropping a table on the last page
855 // and the offset becomes greater than the total number of tables
856 unset($_SESSION['tmp_user_values']['table_limit_offset']);
857 echo "\n";
858 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
859 if (!$jsonly) {
860 echo '<script type="text/javascript">' . PHP_EOL;
863 //<![CDATA[
864 if (typeof(window.parent) != 'undefined'
865 && typeof(window.parent.frame_navigation) != 'undefined'
866 && window.parent.goTo) {
867 window.parent.goTo('<?php echo $reload_url; ?>');
869 //]]>
870 <?php
871 if (!$jsonly) {
872 echo '</script>' . PHP_EOL;
875 unset($GLOBALS['reload']);
880 * displays the message and the query
881 * usually the message is the result of the query executed
883 * @param string $message the message to display
884 * @param string $sql_query the query to display
885 * @param string $type the type (level) of the message
886 * @param boolean $is_view is this a message after a VIEW operation?
888 * @return string
890 * @access public
892 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
895 * PMA_ajaxResponse uses this function to collect the string of HTML generated
896 * for showing the message. Use output buffering to collect it and return it
897 * in a string. In some special cases on sql.php, buffering has to be disabled
898 * and hence we check with $GLOBALS['buffer_message']
900 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
901 ob_start();
903 global $cfg;
905 if (null === $sql_query) {
906 if (! empty($GLOBALS['display_query'])) {
907 $sql_query = $GLOBALS['display_query'];
908 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
909 $sql_query = $GLOBALS['unparsed_sql'];
910 } elseif (! empty($GLOBALS['sql_query'])) {
911 $sql_query = $GLOBALS['sql_query'];
912 } else {
913 $sql_query = '';
917 if (isset($GLOBALS['using_bookmark_message'])) {
918 $GLOBALS['using_bookmark_message']->display();
919 unset($GLOBALS['using_bookmark_message']);
922 // Corrects the tooltip text via JS if required
923 // @todo this is REALLY the wrong place to do this - very unexpected here
924 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
925 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
926 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
927 echo "\n";
928 echo '<script type="text/javascript">' . "\n";
929 echo '//<![CDATA[' . "\n";
930 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
931 echo '//]]>' . "\n";
932 echo '</script>' . "\n";
933 } // end if ... elseif
935 // Checks if the table needs to be repaired after a TRUNCATE query.
936 // @todo what about $GLOBALS['display_query']???
937 // @todo this is REALLY the wrong place to do this - very unexpected here
938 if (strlen($GLOBALS['table'])
939 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
940 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
941 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
944 unset($tbl_status);
946 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
947 // check for it's presence before using it
948 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
950 if ($message instanceof PMA_Message) {
951 if (isset($GLOBALS['special_message'])) {
952 $message->addMessage($GLOBALS['special_message']);
953 unset($GLOBALS['special_message']);
955 $message->display();
956 $type = $message->getLevel();
957 } else {
958 echo '<div class="' . $type . '">';
959 echo PMA_sanitize($message);
960 if (isset($GLOBALS['special_message'])) {
961 echo PMA_sanitize($GLOBALS['special_message']);
962 unset($GLOBALS['special_message']);
964 echo '</div>';
967 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
968 // Html format the query to be displayed
969 // If we want to show some sql code it is easiest to create it here
970 /* SQL-Parser-Analyzer */
972 if (! empty($GLOBALS['show_as_php'])) {
973 $new_line = '\\n"<br />' . "\n"
974 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
975 $query_base = htmlspecialchars(addslashes($sql_query));
976 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
977 } else {
978 $query_base = $sql_query;
981 $query_too_big = false;
983 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
984 // when the query is large (for example an INSERT of binary
985 // data), the parser chokes; so avoid parsing the query
986 $query_too_big = true;
987 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
988 } elseif (! empty($GLOBALS['parsed_sql'])
989 && $query_base == $GLOBALS['parsed_sql']['raw']) {
990 // (here, use "! empty" because when deleting a bookmark,
991 // $GLOBALS['parsed_sql'] is set but empty
992 $parsed_sql = $GLOBALS['parsed_sql'];
993 } else {
994 // Parse SQL if needed
995 $parsed_sql = PMA_SQP_parse($query_base);
996 if (PMA_SQP_isError()) {
997 unset($parsed_sql);
1001 // Analyze it
1002 if (isset($parsed_sql)) {
1003 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1005 // Same as below (append LIMIT), append the remembered ORDER BY
1006 if ($GLOBALS['cfg']['RememberSorting']
1007 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1008 && isset($GLOBALS['sql_order_to_append'])) {
1009 $query_base = $analyzed_display_query[0]['section_before_limit']
1010 . "\n" . $GLOBALS['sql_order_to_append']
1011 . $analyzed_display_query[0]['section_after_limit'];
1013 // Need to reparse query
1014 $parsed_sql = PMA_SQP_parse($query_base);
1015 // update the $analyzed_display_query
1016 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1017 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1020 // Here we append the LIMIT added for navigation, to
1021 // enable its display. Adding it higher in the code
1022 // to $sql_query would create a problem when
1023 // using the Refresh or Edit links.
1025 // Only append it on SELECTs.
1028 * @todo what would be the best to do when someone hits Refresh:
1029 * use the current LIMITs ?
1032 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1033 && isset($GLOBALS['sql_limit_to_append'])) {
1034 $query_base = $analyzed_display_query[0]['section_before_limit']
1035 . "\n" . $GLOBALS['sql_limit_to_append']
1036 . $analyzed_display_query[0]['section_after_limit'];
1037 // Need to reparse query
1038 $parsed_sql = PMA_SQP_parse($query_base);
1042 if (! empty($GLOBALS['show_as_php'])) {
1043 $query_base = '$sql = "' . $query_base;
1044 } elseif (! empty($GLOBALS['validatequery'])) {
1045 try {
1046 $query_base = PMA_validateSQL($query_base);
1047 } catch (Exception $e) {
1048 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1050 } elseif (isset($parsed_sql)) {
1051 $query_base = PMA_formatSql($parsed_sql, $query_base);
1054 // Prepares links that may be displayed to edit/explain the query
1055 // (don't go to default pages, we must go to the page
1056 // where the query box is available)
1058 // Basic url query part
1059 $url_params = array();
1060 if (! isset($GLOBALS['db'])) {
1061 $GLOBALS['db'] = '';
1063 if (strlen($GLOBALS['db'])) {
1064 $url_params['db'] = $GLOBALS['db'];
1065 if (strlen($GLOBALS['table'])) {
1066 $url_params['table'] = $GLOBALS['table'];
1067 $edit_link = 'tbl_sql.php';
1068 } else {
1069 $edit_link = 'db_sql.php';
1071 } else {
1072 $edit_link = 'server_sql.php';
1075 // Want to have the query explained
1076 // but only explain a SELECT (that has not been explained)
1077 /* SQL-Parser-Analyzer */
1078 $explain_link = '';
1079 $is_select = false;
1080 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1081 $explain_params = $url_params;
1082 // Detect if we are validating as well
1083 // To preserve the validate uRL data
1084 if (! empty($GLOBALS['validatequery'])) {
1085 $explain_params['validatequery'] = 1;
1087 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1088 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1089 $_message = __('Explain SQL');
1090 $is_select = true;
1091 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1092 $explain_params['sql_query'] = substr($sql_query, 8);
1093 $_message = __('Skip Explain SQL');
1095 if (isset($explain_params['sql_query'])) {
1096 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1097 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1099 } //show explain
1101 $url_params['sql_query'] = $sql_query;
1102 $url_params['show_query'] = 1;
1104 // even if the query is big and was truncated, offer the chance
1105 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1106 if (! empty($cfg['SQLQuery']['Edit'])) {
1107 if ($cfg['EditInWindow'] == true) {
1108 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1109 } else {
1110 $onclick = '';
1113 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1114 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1115 } else {
1116 $edit_link = '';
1119 $url_qpart = PMA_generate_common_url($url_params);
1121 // Also we would like to get the SQL formed in some nice
1122 // php-code
1123 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1124 $php_params = $url_params;
1126 if (! empty($GLOBALS['show_as_php'])) {
1127 $_message = __('Without PHP Code');
1128 } else {
1129 $php_params['show_as_php'] = 1;
1130 $_message = __('Create PHP Code');
1133 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1134 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1136 if (isset($GLOBALS['show_as_php'])) {
1137 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1138 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1140 } else {
1141 $php_link = '';
1142 } //show as php
1144 // Refresh query
1145 if (! empty($cfg['SQLQuery']['Refresh'])
1146 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1147 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1148 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1149 } else {
1150 $refresh_link = '';
1151 } //show as php
1153 if (! empty($cfg['SQLValidator']['use'])
1154 && ! empty($cfg['SQLQuery']['Validate'])) {
1155 $validate_params = $url_params;
1156 if (!empty($GLOBALS['validatequery'])) {
1157 $validate_message = __('Skip Validate SQL') ;
1158 } else {
1159 $validate_params['validatequery'] = 1;
1160 $validate_message = __('Validate SQL') ;
1163 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1164 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1165 } else {
1166 $validate_link = '';
1167 } //validator
1169 if (!empty($GLOBALS['validatequery'])) {
1170 echo '<div class="sqlvalidate">';
1171 } else {
1172 echo '<code class="sql">';
1174 if ($query_too_big) {
1175 echo $shortened_query_base;
1176 } else {
1177 echo $query_base;
1180 //Clean up the end of the PHP
1181 if (! empty($GLOBALS['show_as_php'])) {
1182 echo '";';
1184 if (!empty($GLOBALS['validatequery'])) {
1185 echo '</div>';
1186 } else {
1187 echo '</code>';
1190 echo '<div class="tools">';
1191 // avoid displaying a Profiling checkbox that could
1192 // be checked, which would reexecute an INSERT, for example
1193 if (! empty($refresh_link)) {
1194 PMA_profilingCheckbox($sql_query);
1196 // if needed, generate an invisible form that contains controls for the
1197 // Inline link; this way, the behavior of the Inline link does not
1198 // depend on the profiling support or on the refresh link
1199 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1200 echo '<form action="sql.php" method="post">';
1201 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1202 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1203 echo '</form>';
1206 // in the tools div, only display the Inline link when not in ajax
1207 // mode because 1) it currently does not work and 2) we would
1208 // have two similar mechanisms on the page for the same goal
1209 if ($is_select || $GLOBALS['is_ajax_request'] === false && ! $query_too_big) {
1210 // see in js/functions.js the jQuery code attached to id inline_edit
1211 // document.write conflicts with jQuery, hence used $().append()
1212 echo "<script type=\"text/javascript\">\n" .
1213 "//<![CDATA[\n" .
1214 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1215 PMA_escapeJsString(__('Inline edit of this query')) .
1216 "\" class=\"inline_edit_sql\">" .
1217 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1218 "</a>]');\n" .
1219 "//]]>\n" .
1220 "</script>";
1222 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1223 echo '</div>';
1225 echo '</div>';
1226 if ($GLOBALS['is_ajax_request'] === false) {
1227 echo '<br class="clearfloat" />';
1230 // If we are in an Ajax request, we have most probably been called in
1231 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1232 // to PMA_ajaxResponse(), which will encode it for JSON.
1233 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1234 $buffer_contents = ob_get_contents();
1235 ob_end_clean();
1236 return $buffer_contents;
1238 return null;
1239 } // end of the 'PMA_showMessage()' function
1242 * Verifies if current MySQL server supports profiling
1244 * @access public
1246 * @return boolean whether profiling is supported
1248 function PMA_profilingSupported()
1250 if (! PMA_cacheExists('profiling_supported', true)) {
1251 // 5.0.37 has profiling but for example, 5.1.20 does not
1252 // (avoid a trip to the server for MySQL before 5.0.37)
1253 // and do not set a constant as we might be switching servers
1254 if (defined('PMA_MYSQL_INT_VERSION')
1255 && PMA_MYSQL_INT_VERSION >= 50037
1256 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1257 PMA_cacheSet('profiling_supported', true, true);
1258 } else {
1259 PMA_cacheSet('profiling_supported', false, true);
1263 return PMA_cacheGet('profiling_supported', true);
1267 * Displays a form with the Profiling checkbox
1269 * @param string $sql_query
1270 * @access public
1272 function PMA_profilingCheckbox($sql_query)
1274 if (PMA_profilingSupported()) {
1275 echo '<form action="sql.php" method="post">' . "\n";
1276 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1277 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1278 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1279 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1280 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1281 echo '</form>' . "\n";
1286 * Formats $value to byte view
1288 * @param double $value the value to format
1289 * @param int $limes the sensitiveness
1290 * @param int $comma the number of decimals to retain
1292 * @return array the formatted value and its unit
1294 * @access public
1296 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1298 if ($value === null) {
1299 return null;
1302 $byteUnits = array(
1303 /* l10n: shortcuts for Byte */
1304 __('B'),
1305 /* l10n: shortcuts for Kilobyte */
1306 __('KiB'),
1307 /* l10n: shortcuts for Megabyte */
1308 __('MiB'),
1309 /* l10n: shortcuts for Gigabyte */
1310 __('GiB'),
1311 /* l10n: shortcuts for Terabyte */
1312 __('TiB'),
1313 /* l10n: shortcuts for Petabyte */
1314 __('PiB'),
1315 /* l10n: shortcuts for Exabyte */
1316 __('EiB')
1319 $dh = PMA_pow(10, $comma);
1320 $li = PMA_pow(10, $limes);
1321 $unit = $byteUnits[0];
1323 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1324 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1325 // use 1024.0 to avoid integer overflow on 64-bit machines
1326 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1327 $unit = $byteUnits[$d];
1328 break 1;
1329 } // end if
1330 } // end for
1332 if ($unit != $byteUnits[0]) {
1333 // if the unit is not bytes (as represented in current language)
1334 // reformat with max length of 5
1335 // 4th parameter=true means do not reformat if value < 1
1336 $return_value = PMA_formatNumber($value, 5, $comma, true);
1337 } else {
1338 // do not reformat, just handle the locale
1339 $return_value = PMA_formatNumber($value, 0);
1342 return array(trim($return_value), $unit);
1343 } // end of the 'PMA_formatByteDown' function
1346 * Changes thousands and decimal separators to locale specific values.
1348 * @param $value
1350 * @return string
1352 function PMA_localizeNumber($value)
1354 return str_replace(
1355 array(',', '.'),
1356 array(
1357 /* l10n: Thousands separator */
1358 __(','),
1359 /* l10n: Decimal separator */
1360 __('.'),
1362 $value);
1366 * Formats $value to the given length and appends SI prefixes
1367 * with a $length of 0 no truncation occurs, number is only formated
1368 * to the current locale
1370 * examples:
1371 * <code>
1372 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1373 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1374 * echo PMA_formatNumber(-0.003, 6); // -3 m
1375 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1376 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1377 * echo PMA_formatNumber(0, 6); // 0
1379 * </code>
1380 * @param double $value the value to format
1381 * @param integer $digits_left number of digits left of the comma
1382 * @param integer $digits_right number of digits right of the comma
1383 * @param boolean $only_down do not reformat numbers below 1
1384 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1386 * @return string the formatted value and its unit
1388 * @access public
1390 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1392 if ($value==0) return '0';
1394 $originalValue = $value;
1395 //number_format is not multibyte safe, str_replace is safe
1396 if ($digits_left === 0) {
1397 $value = number_format($value, $digits_right);
1398 if ($originalValue != 0 && floatval($value) == 0) {
1399 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1402 return PMA_localizeNumber($value);
1405 // this units needs no translation, ISO
1406 $units = array(
1407 -8 => 'y',
1408 -7 => 'z',
1409 -6 => 'a',
1410 -5 => 'f',
1411 -4 => 'p',
1412 -3 => 'n',
1413 -2 => '&micro;',
1414 -1 => 'm',
1415 0 => ' ',
1416 1 => 'k',
1417 2 => 'M',
1418 3 => 'G',
1419 4 => 'T',
1420 5 => 'P',
1421 6 => 'E',
1422 7 => 'Z',
1423 8 => 'Y'
1426 // check for negative value to retain sign
1427 if ($value < 0) {
1428 $sign = '-';
1429 $value = abs($value);
1430 } else {
1431 $sign = '';
1434 $dh = PMA_pow(10, $digits_right);
1437 * This gives us the right SI prefix already,
1438 * but $digits_left parameter not incorporated
1440 $d = floor(log10($value) / 3);
1442 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1443 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1444 * to use, then lower the SI prefix
1446 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1447 if ($digits_left > $cur_digits) {
1448 $d-= floor(($digits_left - $cur_digits)/3);
1451 if ($d<0 && $only_down) $d=0;
1453 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1454 $unit = $units[$d];
1456 // If we dont want any zeros after the comma just add the thousand seperator
1457 if ($noTrailingZero) {
1458 $value = PMA_localizeNumber(
1459 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1461 } else {
1462 //number_format is not multibyte safe, str_replace is safe
1463 $value = PMA_localizeNumber(number_format($value, $digits_right));
1466 if ($originalValue!=0 && floatval($value) == 0) {
1467 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1470 return $sign . $value . ' ' . $unit;
1471 } // end of the 'PMA_formatNumber' function
1474 * Returns the number of bytes when a formatted size is given
1476 * @param string $formatted_size the size expression (for example 8MB)
1478 * @return integer The numerical part of the expression (for example 8)
1480 function PMA_extractValueFromFormattedSize($formatted_size)
1482 $return_value = -1;
1484 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1485 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1486 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1487 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1488 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1489 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1491 return $return_value;
1492 }// end of the 'PMA_extractValueFromFormattedSize' function
1495 * Writes localised date
1497 * @param string $timestamp the current timestamp
1498 * @param string $format format
1500 * @return string the formatted date
1502 * @access public
1504 function PMA_localisedDate($timestamp = -1, $format = '')
1506 $month = array(
1507 /* l10n: Short month name */
1508 __('Jan'),
1509 /* l10n: Short month name */
1510 __('Feb'),
1511 /* l10n: Short month name */
1512 __('Mar'),
1513 /* l10n: Short month name */
1514 __('Apr'),
1515 /* l10n: Short month name */
1516 _pgettext('Short month name', 'May'),
1517 /* l10n: Short month name */
1518 __('Jun'),
1519 /* l10n: Short month name */
1520 __('Jul'),
1521 /* l10n: Short month name */
1522 __('Aug'),
1523 /* l10n: Short month name */
1524 __('Sep'),
1525 /* l10n: Short month name */
1526 __('Oct'),
1527 /* l10n: Short month name */
1528 __('Nov'),
1529 /* l10n: Short month name */
1530 __('Dec'));
1531 $day_of_week = array(
1532 /* l10n: Short week day name */
1533 _pgettext('Short week day name', 'Sun'),
1534 /* l10n: Short week day name */
1535 __('Mon'),
1536 /* l10n: Short week day name */
1537 __('Tue'),
1538 /* l10n: Short week day name */
1539 __('Wed'),
1540 /* l10n: Short week day name */
1541 __('Thu'),
1542 /* l10n: Short week day name */
1543 __('Fri'),
1544 /* l10n: Short week day name */
1545 __('Sat'));
1547 if ($format == '') {
1548 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1549 $format = __('%B %d, %Y at %I:%M %p');
1552 if ($timestamp == -1) {
1553 $timestamp = time();
1556 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1557 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1559 return strftime($date, $timestamp);
1560 } // end of the 'PMA_localisedDate()' function
1564 * returns a tab for tabbed navigation.
1565 * If the variables $link and $args ar left empty, an inactive tab is created
1567 * @param array $tab array with all options
1568 * @param array $url_params
1570 * @return string html code for one tab, a link if valid otherwise a span
1572 * @access public
1574 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1576 // default values
1577 $defaults = array(
1578 'text' => '',
1579 'class' => '',
1580 'active' => null,
1581 'link' => '',
1582 'sep' => '?',
1583 'attr' => '',
1584 'args' => '',
1585 'warning' => '',
1586 'fragment' => '',
1587 'id' => '',
1590 $tab = array_merge($defaults, $tab);
1592 // determine additionnal style-class
1593 if (empty($tab['class'])) {
1594 if (! empty($tab['active'])
1595 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1596 $tab['class'] = 'active';
1597 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1598 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1599 && empty($tab['warning'])) {
1600 $tab['class'] = 'active';
1604 if (!empty($tab['warning'])) {
1605 $tab['class'] .= ' error';
1606 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1609 // If there are any tab specific URL parameters, merge those with the general URL parameters
1610 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1611 $url_params = array_merge($url_params, $tab['url_params']);
1614 // build the link
1615 if (!empty($tab['link'])) {
1616 $tab['link'] = htmlentities($tab['link']);
1617 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1618 if (! empty($tab['args'])) {
1619 foreach ($tab['args'] as $param => $value) {
1620 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1621 . urlencode($value);
1626 if (! empty($tab['fragment'])) {
1627 $tab['link'] .= $tab['fragment'];
1630 // display icon, even if iconic is disabled but the link-text is missing
1631 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1632 && isset($tab['icon'])) {
1633 // avoid generating an alt tag, because it only illustrates
1634 // the text that follows and if browser does not display
1635 // images, the text is duplicated
1636 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1637 .' width="16" height="16" alt="" />%2$s';
1638 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1640 // check to not display an empty link-text
1641 elseif (empty($tab['text'])) {
1642 $tab['text'] = '?';
1643 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1644 E_USER_NOTICE);
1647 //Set the id for the tab, if set in the params
1648 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1649 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1651 if (!empty($tab['link'])) {
1652 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1653 .$id_string
1654 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1655 . $tab['text'] . '</a>';
1656 } else {
1657 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1658 . $tab['text'] . '</span>';
1661 $out .= '</li>';
1662 return $out;
1663 } // end of the 'PMA_generate_html_tab()' function
1666 * returns html-code for a tab navigation
1668 * @param array $tabs one element per tab
1669 * @param string $url_params
1671 * @return string html-code for tab-navigation
1673 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1675 $tag_id = 'topmenu';
1676 $tab_navigation =
1677 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1678 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1680 foreach ($tabs as $tab) {
1681 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1684 $tab_navigation .=
1685 '</ul>' . "\n"
1686 .'<div class="clearfloat"></div>'
1687 .'</div>' . "\n";
1689 return $tab_navigation;
1694 * Displays a link, or a button if the link's URL is too large, to
1695 * accommodate some browsers' limitations
1697 * @param string $url the URL
1698 * @param string $message the link message
1699 * @param mixed $tag_params string: js confirmation
1700 * array: additional tag params (f.e. style="")
1701 * @param boolean $new_form we set this to false when we are already in
1702 * a form, to avoid generating nested forms
1703 * @param boolean $strip_img
1704 * @param string $target
1706 * @return string the results to be echoed or saved in an array
1708 function PMA_linkOrButton($url, $message, $tag_params = array(),
1709 $new_form = true, $strip_img = false, $target = '')
1711 $url_length = strlen($url);
1712 // with this we should be able to catch case of image upload
1713 // into a (MEDIUM) BLOB; not worth generating even a form for these
1714 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1715 return '';
1719 if (! is_array($tag_params)) {
1720 $tmp = $tag_params;
1721 $tag_params = array();
1722 if (!empty($tmp)) {
1723 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1725 unset($tmp);
1727 if (! empty($target)) {
1728 $tag_params['target'] = htmlentities($target);
1731 $tag_params_strings = array();
1732 foreach ($tag_params as $par_name => $par_value) {
1733 // htmlspecialchars() only on non javascript
1734 $par_value = substr($par_name, 0, 2) == 'on'
1735 ? $par_value
1736 : htmlspecialchars($par_value);
1737 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1740 $displayed_message = '';
1741 // Add text if not already added
1742 if (stristr($message, '<img') && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true) && strip_tags($message)==$message) {
1743 $displayed_message = '<span>' . htmlspecialchars(preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)) . '</span>';
1746 // Suhosin: Check that each query parameter is not above maximum
1747 $in_suhosin_limits = true;
1748 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1749 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1750 $query_parts = PMA_splitURLQuery($url);
1751 foreach($query_parts as $query_pair) {
1752 list($eachvar, $eachval) = explode('=', $query_pair);
1753 if(strlen($eachval) > $suhosin_get_MaxValueLength) {
1754 $in_suhosin_limits = false;
1755 break;
1761 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1762 // no whitespace within an <a> else Safari will make it part of the link
1763 $ret = "\n" . '<a href="' . $url . '" '
1764 . implode(' ', $tag_params_strings) . '>'
1765 . $message . $displayed_message . '</a>' . "\n";
1766 } else {
1767 // no spaces (linebreaks) at all
1768 // or after the hidden fields
1769 // IE will display them all
1771 // add class=link to submit button
1772 if (empty($tag_params['class'])) {
1773 $tag_params['class'] = 'link';
1776 if (! isset($query_parts)) {
1777 $query_parts = PMA_splitURLQuery($url);
1779 $url_parts = parse_url($url);
1781 if ($new_form) {
1782 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1783 . ' method="post"' . $target . ' style="display: inline;">';
1784 $subname_open = '';
1785 $subname_close = '';
1786 $submit_link = '#';
1787 } else {
1788 $query_parts[] = 'redirect=' . $url_parts['path'];
1789 if (empty($GLOBALS['subform_counter'])) {
1790 $GLOBALS['subform_counter'] = 0;
1792 $GLOBALS['subform_counter']++;
1793 $ret = '';
1794 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1795 $subname_close = ']';
1796 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1798 foreach ($query_parts as $query_pair) {
1799 list($eachvar, $eachval) = explode('=', $query_pair);
1800 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1801 . $subname_close . '" value="'
1802 . htmlspecialchars(urldecode($eachval)) . '" />';
1803 } // end while
1805 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1806 . implode(' ', $tag_params_strings) . '>'
1807 . $message . ' ' . $displayed_message . '</a>' . "\n";
1809 if ($new_form) {
1810 $ret .= '</form>';
1812 } // end if... else...
1814 return $ret;
1815 } // end of the 'PMA_linkOrButton()' function
1819 * Splits a URL string by parameter
1821 * @param string $url the URL
1822 * @return array the parameter/value pairs, for example [0] db=sakila
1824 function PMA_splitURLQuery($url) {
1825 // decode encoded url separators
1826 $separator = PMA_get_arg_separator();
1827 // on most places separator is still hard coded ...
1828 if ($separator !== '&') {
1829 // ... so always replace & with $separator
1830 $url = str_replace(htmlentities('&'), $separator, $url);
1831 $url = str_replace('&', $separator, $url);
1833 $url = str_replace(htmlentities($separator), $separator, $url);
1834 // end decode
1836 $url_parts = parse_url($url);
1837 return explode($separator, $url_parts['query']);
1841 * Returns a given timespan value in a readable format.
1843 * @param int $seconds the timespan
1845 * @return string the formatted value
1847 function PMA_timespanFormat($seconds)
1849 $days = floor($seconds / 86400);
1850 if ($days > 0) {
1851 $seconds -= $days * 86400;
1853 $hours = floor($seconds / 3600);
1854 if ($days > 0 || $hours > 0) {
1855 $seconds -= $hours * 3600;
1857 $minutes = floor($seconds / 60);
1858 if ($days > 0 || $hours > 0 || $minutes > 0) {
1859 $seconds -= $minutes * 60;
1861 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1865 * Takes a string and outputs each character on a line for itself. Used
1866 * mainly for horizontalflipped display mode.
1867 * Takes care of special html-characters.
1868 * Fulfills todo-item
1869 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1871 * @todo add a multibyte safe function PMA_STR_split()
1872 * @param string $string The string
1873 * @param string $Separator The Separator (defaults to "<br />\n")
1875 * @access public
1877 * @return string The flipped string
1879 function PMA_flipstring($string, $Separator = "<br />\n")
1881 $format_string = '';
1882 $charbuff = false;
1884 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1885 $char = $string{$i};
1886 $append = false;
1888 if ($char == '&') {
1889 $format_string .= $charbuff;
1890 $charbuff = $char;
1891 } elseif ($char == ';' && !empty($charbuff)) {
1892 $format_string .= $charbuff . $char;
1893 $charbuff = false;
1894 $append = true;
1895 } elseif (! empty($charbuff)) {
1896 $charbuff .= $char;
1897 } else {
1898 $format_string .= $char;
1899 $append = true;
1902 // do not add separator after the last character
1903 if ($append && ($i != $str_len - 1)) {
1904 $format_string .= $Separator;
1908 return $format_string;
1912 * Function added to avoid path disclosures.
1913 * Called by each script that needs parameters, it displays
1914 * an error message and, by default, stops the execution.
1916 * Not sure we could use a strMissingParameter message here,
1917 * would have to check if the error message file is always available
1919 * @todo use PMA_fatalError() if $die === true?
1920 * @param array $params The names of the parameters needed by the calling script.
1921 * @param bool $die Stop the execution?
1922 * (Set this manually to false in the calling script
1923 * until you know all needed parameters to check).
1924 * @param bool $request Whether to include this list in checking for special params.
1925 * @global string path to current script
1926 * @global boolean flag whether any special variable was required
1928 * @access public
1930 function PMA_checkParameters($params, $die = true, $request = true)
1932 global $checked_special;
1934 if (! isset($checked_special)) {
1935 $checked_special = false;
1938 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1939 $found_error = false;
1940 $error_message = '';
1942 foreach ($params as $param) {
1943 if ($request && $param != 'db' && $param != 'table') {
1944 $checked_special = true;
1947 if (! isset($GLOBALS[$param])) {
1948 $error_message .= $reported_script_name
1949 . ': ' . __('Missing parameter:') . ' '
1950 . $param
1951 . PMA_showDocu('faqmissingparameters')
1952 . '<br />';
1953 $found_error = true;
1956 if ($found_error) {
1958 * display html meta tags
1960 require_once './libraries/header_meta_style.inc.php';
1961 echo '</head><body><p>' . $error_message . '</p></body></html>';
1962 if ($die) {
1963 exit();
1966 } // end function
1969 * Function to generate unique condition for specified row.
1971 * @param resource $handle current query result
1972 * @param integer $fields_cnt number of fields
1973 * @param array $fields_meta meta information about fields
1974 * @param array $row current row
1975 * @param boolean $force_unique generate condition only on pk or unique
1977 * @access public
1979 * @return array the calculated condition and whether condition is unique
1981 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1983 $primary_key = '';
1984 $unique_key = '';
1985 $nonprimary_condition = '';
1986 $preferred_condition = '';
1987 $primary_key_array = array();
1988 $unique_key_array = array();
1989 $nonprimary_condition_array = array();
1990 $condition_array = array();
1992 for ($i = 0; $i < $fields_cnt; ++$i) {
1993 $condition = '';
1994 $con_key = '';
1995 $con_val = '';
1996 $field_flags = PMA_DBI_field_flags($handle, $i);
1997 $meta = $fields_meta[$i];
1999 // do not use a column alias in a condition
2000 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2001 $meta->orgname = $meta->name;
2003 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2004 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2005 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2006 // need (string) === (string)
2007 // '' !== 0 but '' == 0
2008 if ((string) $select_expr['alias'] === (string) $meta->name) {
2009 $meta->orgname = $select_expr['column'];
2010 break;
2011 } // end if
2012 } // end foreach
2016 // Do not use a table alias in a condition.
2017 // Test case is:
2018 // select * from galerie x WHERE
2019 //(select count(*) from galerie y where y.datum=x.datum)>1
2021 // But orgtable is present only with mysqli extension so the
2022 // fix is only for mysqli.
2023 // Also, do not use the original table name if we are dealing with
2024 // a view because this view might be updatable.
2025 // (The isView() verification should not be costly in most cases
2026 // because there is some caching in the function).
2027 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
2028 $meta->table = $meta->orgtable;
2031 // to fix the bug where float fields (primary or not)
2032 // can't be matched because of the imprecision of
2033 // floating comparison, use CONCAT
2034 // (also, the syntax "CONCAT(field) IS NULL"
2035 // that we need on the next "if" will work)
2036 if ($meta->type == 'real') {
2037 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2038 . PMA_backquote($meta->orgname) . ')';
2039 } else {
2040 $con_key = PMA_backquote($meta->table) . '.'
2041 . PMA_backquote($meta->orgname);
2042 } // end if... else...
2043 $condition = ' ' . $con_key . ' ';
2045 if (! isset($row[$i]) || is_null($row[$i])) {
2046 $con_val = 'IS NULL';
2047 } else {
2048 // timestamp is numeric on some MySQL 4.1
2049 // for real we use CONCAT above and it should compare to string
2050 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
2051 $con_val = '= ' . $row[$i];
2052 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2053 // hexify only if this is a true not empty BLOB or a BINARY
2054 && stristr($field_flags, 'BINARY')
2055 && !empty($row[$i])) {
2056 // do not waste memory building a too big condition
2057 if (strlen($row[$i]) < 1000) {
2058 // use a CAST if possible, to avoid problems
2059 // if the field contains wildcard characters % or _
2060 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2061 } else {
2062 // this blob won't be part of the final condition
2063 $con_val = null;
2065 } elseif ($meta->type == 'bit') {
2066 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2067 } else {
2068 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2071 if ($con_val != null) {
2072 $condition .= $con_val . ' AND';
2073 if ($meta->primary_key > 0) {
2074 $primary_key .= $condition;
2075 $primary_key_array[$con_key] = $con_val;
2076 } elseif ($meta->unique_key > 0) {
2077 $unique_key .= $condition;
2078 $unique_key_array[$con_key] = $con_val;
2080 $nonprimary_condition .= $condition;
2081 $nonprimary_condition_array[$con_key] = $con_val;
2083 } // end for
2085 // Correction University of Virginia 19991216:
2086 // prefer primary or unique keys for condition,
2087 // but use conjunction of all values if no primary key
2088 $clause_is_unique = true;
2089 if ($primary_key) {
2090 $preferred_condition = $primary_key;
2091 $condition_array = $primary_key_array;
2092 } elseif ($unique_key) {
2093 $preferred_condition = $unique_key;
2094 $condition_array = $unique_key_array;
2095 } elseif (! $force_unique) {
2096 $preferred_condition = $nonprimary_condition;
2097 $condition_array = $nonprimary_condition_array;
2098 $clause_is_unique = false;
2101 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2102 return(array($where_clause, $clause_is_unique, $condition_array));
2103 } // end function
2106 * Generate a button or image tag
2108 * @param string $button_name name of button element
2109 * @param string $button_class class of button element
2110 * @param string $image_name name of image element
2111 * @param string $text text to display
2112 * @param string $image image to display
2113 * @param string $value
2115 * @access public
2117 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2118 $image, $value = '')
2120 if ($value == '') {
2121 $value = $text;
2123 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2124 echo ' <input type="submit" name="' . $button_name . '"'
2125 .' value="' . htmlspecialchars($value) . '"'
2126 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2127 return;
2130 /* Opera has trouble with <input type="image"> */
2131 /* IE has trouble with <button> */
2132 if (PMA_USR_BROWSER_AGENT != 'IE') {
2133 echo '<button class="' . $button_class . '" type="submit"'
2134 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2135 .' title="' . htmlspecialchars($text) . '">' . "\n"
2136 . PMA_getIcon($image, $text)
2137 .'</button>' . "\n";
2138 } else {
2139 echo '<input type="image" name="' . $image_name . '" value="'
2140 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2141 . $image . '" />'
2142 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2144 } // end function
2147 * Generate a pagination selector for browsing resultsets
2149 * @param int $rows Number of rows in the pagination set
2150 * @param int $pageNow current page number
2151 * @param int $nbTotalPage number of total pages
2152 * @param int $showAll If the number of pages is lower than this
2153 * variable, no pages will be omitted in pagination
2154 * @param int $sliceStart How many rows at the beginning should always be shown?
2155 * @param int $sliceEnd How many rows at the end should always be shown?
2156 * @param int $percent Percentage of calculation page offsets to hop to a next page
2157 * @param int $range Near the current page, how many pages should
2158 * be considered "nearby" and displayed as well?
2159 * @param string $prompt The prompt to display (sometimes empty)
2161 * @return string
2163 * @access public
2165 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2166 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2167 $range = 10, $prompt = '')
2169 $increment = floor($nbTotalPage / $percent);
2170 $pageNowMinusRange = ($pageNow - $range);
2171 $pageNowPlusRange = ($pageNow + $range);
2173 $gotopage = $prompt . ' <select id="pageselector" ';
2174 if ($GLOBALS['cfg']['AjaxEnable']) {
2175 $gotopage .= ' class="ajax"';
2177 $gotopage .= ' name="pos" >' . "\n";
2178 if ($nbTotalPage < $showAll) {
2179 $pages = range(1, $nbTotalPage);
2180 } else {
2181 $pages = array();
2183 // Always show first X pages
2184 for ($i = 1; $i <= $sliceStart; $i++) {
2185 $pages[] = $i;
2188 // Always show last X pages
2189 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2190 $pages[] = $i;
2193 // Based on the number of results we add the specified
2194 // $percent percentage to each page number,
2195 // so that we have a representing page number every now and then to
2196 // immediately jump to specific pages.
2197 // As soon as we get near our currently chosen page ($pageNow -
2198 // $range), every page number will be shown.
2199 $i = $sliceStart;
2200 $x = $nbTotalPage - $sliceEnd;
2201 $met_boundary = false;
2202 while ($i <= $x) {
2203 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2204 // If our pageselector comes near the current page, we use 1
2205 // counter increments
2206 $i++;
2207 $met_boundary = true;
2208 } else {
2209 // We add the percentage increment to our current page to
2210 // hop to the next one in range
2211 $i += $increment;
2213 // Make sure that we do not cross our boundaries.
2214 if ($i > $pageNowMinusRange && ! $met_boundary) {
2215 $i = $pageNowMinusRange;
2219 if ($i > 0 && $i <= $x) {
2220 $pages[] = $i;
2224 // Since because of ellipsing of the current page some numbers may be double,
2225 // we unify our array:
2226 sort($pages);
2227 $pages = array_unique($pages);
2230 foreach ($pages as $i) {
2231 if ($i == $pageNow) {
2232 $selected = 'selected="selected" style="font-weight: bold"';
2233 } else {
2234 $selected = '';
2236 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2239 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2241 return $gotopage;
2242 } // end function
2246 * Generate navigation for a list
2248 * @todo use $pos from $_url_params
2249 * @param int $count number of elements in the list
2250 * @param int $pos current position in the list
2251 * @param array $_url_params url parameters
2252 * @param string $script script name for form target
2253 * @param string $frame target frame
2254 * @param int $max_count maximum number of elements to display from the list
2256 * @access public
2258 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2261 if ($max_count < $count) {
2262 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2263 echo __('Page number:');
2264 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2266 // Move to the beginning or to the previous page
2267 if ($pos > 0) {
2268 // patch #474210 - part 1
2269 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2270 $caption1 = '&lt;&lt;';
2271 $caption2 = ' &lt; ';
2272 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2273 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2274 } else {
2275 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2276 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2277 $title1 = '';
2278 $title2 = '';
2279 } // end if... else...
2280 $_url_params['pos'] = 0;
2281 echo '<a' . $title1 . ' href="' . $script
2282 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2283 . $caption1 . '</a>';
2284 $_url_params['pos'] = $pos - $max_count;
2285 echo '<a' . $title2 . ' href="' . $script
2286 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2287 . $caption2 . '</a>';
2290 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2291 echo PMA_generate_common_hidden_inputs($_url_params);
2292 echo PMA_pageselector(
2293 $max_count,
2294 floor(($pos + 1) / $max_count) + 1,
2295 ceil($count / $max_count));
2296 echo '</form>';
2298 if ($pos + $max_count < $count) {
2299 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2300 $caption3 = ' &gt; ';
2301 $caption4 = '&gt;&gt;';
2302 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2303 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2304 } else {
2305 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2306 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2307 $title3 = '';
2308 $title4 = '';
2309 } // end if... else...
2310 $_url_params['pos'] = $pos + $max_count;
2311 echo '<a' . $title3 . ' href="' . $script
2312 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2313 . $caption3 . '</a>';
2314 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2315 if ($_url_params['pos'] == $count) {
2316 $_url_params['pos'] = $count - $max_count;
2318 echo '<a' . $title4 . ' href="' . $script
2319 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2320 . $caption4 . '</a>';
2322 echo "\n";
2323 if ('frame_navigation' == $frame) {
2324 echo '</div>' . "\n";
2330 * replaces %u in given path with current user name
2332 * example:
2333 * <code>
2334 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2336 * </code>
2338 * @param string $dir with wildcard for user
2340 * @return string per user directory
2342 function PMA_userDir($dir)
2344 // add trailing slash
2345 if (substr($dir, -1) != '/') {
2346 $dir .= '/';
2349 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2353 * returns html code for db link to default db page
2355 * @param string $database
2357 * @return string html link to default db page
2359 function PMA_getDbLink($database = null)
2361 if (! strlen($database)) {
2362 if (! strlen($GLOBALS['db'])) {
2363 return '';
2365 $database = $GLOBALS['db'];
2366 } else {
2367 $database = PMA_unescape_mysql_wildcards($database);
2370 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2371 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2372 .htmlspecialchars($database) . '</a>';
2376 * Displays a lightbulb hint explaining a known external bug
2377 * that affects a functionality
2379 * @param string $functionality localized message explaining the func.
2380 * @param string $component 'mysql' (eventually, 'php')
2381 * @param string $minimum_version of this component
2382 * @param string $bugref bug reference for this component
2384 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2386 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2387 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2392 * Generates and echoes an HTML checkbox
2394 * @param string $html_field_name the checkbox HTML field
2395 * @param string $label label for checkbox
2396 * @param boolean $checked is it initially checked?
2397 * @param boolean $onclick should it submit the form on click?
2399 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2402 echo '<input type="checkbox" name="' . $html_field_name . '" id="' . $html_field_name . '"' . ($checked ? ' checked="checked"' : '') . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="' . $html_field_name . '">' . $label . '</label>';
2406 * Generates and echoes a set of radio HTML fields
2408 * @param string $html_field_name the radio HTML field
2409 * @param array $choices the choices values and labels
2410 * @param string $checked_choice the choice to check by default
2411 * @param boolean $line_break whether to add an HTML line break after a choice
2412 * @param boolean $escape_label whether to use htmlspecialchars() on label
2413 * @param string $class enclose each choice with a div of this class
2415 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='')
2417 foreach ($choices as $choice_value => $choice_label) {
2418 if (! empty($class)) {
2419 echo '<div class="' . $class . '">';
2421 $html_field_id = $html_field_name . '_' . $choice_value;
2422 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2423 if ($choice_value == $checked_choice) {
2424 echo ' checked="checked"';
2426 echo ' />' . "\n";
2427 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2428 if ($line_break) {
2429 echo '<br />';
2431 if (! empty($class)) {
2432 echo '</div>';
2434 echo "\n";
2439 * Generates and returns an HTML dropdown
2441 * @param string $select_name
2442 * @param array $choices choices values
2443 * @param string $active_choice the choice to select by default
2444 * @param string $id id of the select element; can be different in case
2445 * the dropdown is present more than once on the page
2446 * @return string
2448 * @todo support titles
2450 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2452 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2453 foreach ($choices as $one_choice_value => $one_choice_label) {
2454 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2455 if ($one_choice_value == $active_choice) {
2456 $result .= ' selected="selected"';
2458 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2460 $result .= '</select>';
2461 return $result;
2465 * Generates a slider effect (jQjuery)
2466 * Takes care of generating the initial <div> and the link
2467 * controlling the slider; you have to generate the </div> yourself
2468 * after the sliding section.
2470 * @param string $id the id of the <div> on which to apply the effect
2471 * @param string $message the message to show as a link
2473 function PMA_generate_slider_effect($id, $message)
2475 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2476 echo '<div id="' . $id . '">';
2477 return;
2480 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2481 * opening the <div> with PHP itself instead of JavaScript.
2483 * @todo find a better solution that uses $.append(), the recommended method
2484 * maybe by using an additional param, the id of the div to append to
2487 <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); ?>">
2488 <?php
2492 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2494 * @param string $action The URL for the request to be executed
2495 * @param string $select_name The name for the dropdown box
2496 * @param array $options An array of options (see rte_footer.lib.php)
2497 * @param string $callback A JS snippet to execute when the request is
2498 * successfully processed
2500 * @return string HTML code for the toggle button
2502 function PMA_toggleButton($action, $select_name, $options, $callback)
2504 // Do the logic first
2505 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2506 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2507 if ($options[1]['selected'] == true) {
2508 $state = 'on';
2509 } else if ($options[0]['selected'] == true) {
2510 $state = 'off';
2511 } else {
2512 $state = 'on';
2514 $selected1 = '';
2515 $selected0 = '';
2516 if ($options[1]['selected'] == true) {
2517 $selected1 = " selected='selected'";
2518 } else if ($options[0]['selected'] == true) {
2519 $selected0 = " selected='selected'";
2521 // Generate output
2522 $retval = "<!-- TOGGLE START -->\n";
2523 if ($GLOBALS['cfg']['AjaxEnable']) {
2524 $retval .= "<noscript>\n";
2526 $retval .= "<div class='wrapper'>\n";
2527 $retval .= " <form action='$action' method='post'>\n";
2528 $retval .= " <select name='$select_name'>\n";
2529 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2530 $retval .= " {$options[1]['label']}\n";
2531 $retval .= " </option>\n";
2532 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2533 $retval .= " {$options[0]['label']}\n";
2534 $retval .= " </option>\n";
2535 $retval .= " </select>\n";
2536 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2537 $retval .= " </form>\n";
2538 $retval .= "</div>\n";
2539 if ($GLOBALS['cfg']['AjaxEnable']) {
2540 $retval .= "</noscript>\n";
2541 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2542 $retval .= " <div class='toggleButton'>\n";
2543 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2544 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2545 $retval .= " alt='' />\n";
2546 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2547 $retval .= " <tbody>\n";
2548 $retval .= " <td class='toggleOn'>\n";
2549 $retval .= " <span class='hide'>$link_on</span>\n";
2550 $retval .= " <div>";
2551 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2552 $retval .= " </td>\n";
2553 $retval .= " <td><div>&nbsp;</div></td>\n";
2554 $retval .= " <td class='toggleOff'>\n";
2555 $retval .= " <span class='hide'>$link_off</span>\n";
2556 $retval .= " <div>";
2557 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2558 $retval .= " </div>\n";
2559 $retval .= " </tbody>\n";
2560 $retval .= " </tr></table>\n";
2561 $retval .= " <span class='hide callback'>$callback</span>\n";
2562 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2563 $retval .= " </div>\n";
2564 $retval .= " </div>\n";
2565 $retval .= "</div>\n";
2567 $retval .= "<!-- TOGGLE END -->";
2569 return $retval;
2570 } // end PMA_toggleButton()
2573 * Clears cache content which needs to be refreshed on user change.
2575 function PMA_clearUserCache()
2577 PMA_cacheUnset('is_superuser', true);
2581 * Verifies if something is cached in the session
2583 * @param string $var
2584 * @param int|true $server
2586 * @return boolean
2588 function PMA_cacheExists($var, $server = 0)
2590 if (true === $server) {
2591 $server = $GLOBALS['server'];
2593 return isset($_SESSION['cache']['server_' . $server][$var]);
2597 * Gets cached information from the session
2599 * @param string $var
2600 * @param int|true $server
2602 * @return mixed
2604 function PMA_cacheGet($var, $server = 0)
2606 if (true === $server) {
2607 $server = $GLOBALS['server'];
2609 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2610 return $_SESSION['cache']['server_' . $server][$var];
2611 } else {
2612 return null;
2617 * Caches information in the session
2619 * @param string $var
2620 * @param mixed $val
2621 * @param int|true $server
2623 * @return mixed
2625 function PMA_cacheSet($var, $val = null, $server = 0)
2627 if (true === $server) {
2628 $server = $GLOBALS['server'];
2630 $_SESSION['cache']['server_' . $server][$var] = $val;
2634 * Removes cached information from the session
2636 * @param string $var
2637 * @param int|true $server
2639 function PMA_cacheUnset($var, $server = 0)
2641 if (true === $server) {
2642 $server = $GLOBALS['server'];
2644 unset($_SESSION['cache']['server_' . $server][$var]);
2648 * Converts a bit value to printable format;
2649 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2650 * function because in PHP, decbin() supports only 32 bits
2652 * @param numeric $value coming from a BIT field
2653 * @param integer $length
2655 * @return string the printable value
2657 function PMA_printable_bit_value($value, $length)
2659 $printable = '';
2660 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2661 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2663 $printable = substr($printable, -$length);
2664 return $printable;
2668 * Verifies whether the value contains a non-printable character
2670 * @param string $value
2672 * @return boolean
2674 function PMA_contains_nonprintable_ascii($value)
2676 return preg_match('@[^[:print:]]@', $value);
2680 * Converts a BIT type default value
2681 * for example, b'010' becomes 010
2683 * @param string $bit_default_value
2685 * @return string the converted value
2687 function PMA_convert_bit_default_value($bit_default_value)
2689 return strtr($bit_default_value, array("b" => "", "'" => ""));
2693 * Extracts the various parts from a field type spec
2695 * @param string $fieldspec
2697 * @return array associative array containing type, spec_in_brackets
2698 * and possibly enum_set_values (another array)
2700 function PMA_extractFieldSpec($fieldspec)
2702 $first_bracket_pos = strpos($fieldspec, '(');
2703 if ($first_bracket_pos) {
2704 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2705 // convert to lowercase just to be sure
2706 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2707 } else {
2708 $type = strtolower($fieldspec);
2709 $spec_in_brackets = '';
2712 if ('enum' == $type || 'set' == $type) {
2713 // Define our working vars
2714 $enum_set_values = array();
2715 $working = "";
2716 $in_string = false;
2717 $index = 0;
2719 // While there is another character to process
2720 while (isset($fieldspec[$index])) {
2721 // Grab the char to look at
2722 $char = $fieldspec[$index];
2724 // If it is a single quote, needs to be handled specially
2725 if ($char == "'") {
2726 // If we are not currently in a string, begin one
2727 if (! $in_string) {
2728 $in_string = true;
2729 $working = "";
2730 } else {
2731 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2732 // Check out the next character (if possible)
2733 $has_next = isset($fieldspec[$index + 1]);
2734 $next = $has_next ? $fieldspec[$index + 1] : null;
2736 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2737 if (! $has_next || $next != "'") {
2738 $enum_set_values[] = $working;
2739 $in_string = false;
2741 // Otherwise, this is a 'double quote', and can be added to the working string
2742 } elseif ($next == "'") {
2743 $working .= "'";
2744 // Skip the next char; we already know what it is
2745 $index++;
2748 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2749 // escaping of a quote?
2750 $working .= "'";
2751 $index++;
2752 } else {
2753 // Otherwise, add it to our working string like normal
2754 $working .= $char;
2756 // Increment character index
2757 $index++;
2758 } // end while
2759 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2760 $binary = false;
2761 $unsigned = false;
2762 $zerofill = false;
2763 } else {
2764 $enum_set_values = array();
2766 /* Create printable type name */
2767 $printtype = strtolower($fieldspec);
2769 // strip the "BINARY" attribute, except if we find "BINARY(" because
2770 // this would be a BINARY or VARBINARY field type
2771 if (!preg_match('@binary[\(]@', $printtype)) {
2772 $binary = strpos($printtype, 'blob') !== false || strpos($printtype, 'binary') !== false;
2773 $printtype = preg_replace('@binary@', '', $printtype);
2774 } else {
2775 $binary = false;
2777 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2778 $zerofill = ($zerofill_cnt > 0);
2779 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
2780 $unsigned = ($unsigned_cnt > 0);
2781 $printtype = trim($printtype);
2785 $attribute = ' ';
2786 if ($binary) {
2787 $attribute = 'BINARY';
2789 if ($unsigned) {
2790 $attribute = 'UNSIGNED';
2792 if ($zerofill) {
2793 $attribute = 'UNSIGNED ZEROFILL';
2796 return array(
2797 'type' => $type,
2798 'spec_in_brackets' => $spec_in_brackets,
2799 'enum_set_values' => $enum_set_values,
2800 'print_type' => $printtype,
2801 'binary' => $binary,
2802 'unsigned' => $unsigned,
2803 'zerofill' => $zerofill,
2804 'attribute' => $attribute,
2809 * Verifies if this table's engine supports foreign keys
2811 * @param string $engine
2813 * @return boolean
2815 function PMA_foreignkey_supported($engine)
2817 $engine = strtoupper($engine);
2818 if ('INNODB' == $engine || 'PBXT' == $engine) {
2819 return true;
2820 } else {
2821 return false;
2826 * Replaces some characters by a displayable equivalent
2828 * @param string $content
2830 * @return string the content with characters replaced
2832 function PMA_replace_binary_contents($content)
2834 $result = str_replace("\x00", '\0', $content);
2835 $result = str_replace("\x08", '\b', $result);
2836 $result = str_replace("\x0a", '\n', $result);
2837 $result = str_replace("\x0d", '\r', $result);
2838 $result = str_replace("\x1a", '\Z', $result);
2839 return $result;
2843 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2845 * @param string $string
2847 * @return string with the chars replaced
2850 function PMA_duplicateFirstNewline($string)
2852 $first_occurence = strpos($string, "\r\n");
2853 if ($first_occurence === 0) {
2854 $string = "\n".$string;
2856 return $string;
2860 * Get the action word corresponding to a script name
2861 * in order to display it as a title in navigation panel
2863 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2864 * or $cfg['DefaultTabDatabase']
2866 * @return array
2868 function PMA_getTitleForTarget($target)
2870 $mapping = array(
2871 // Values for $cfg['DefaultTabTable']
2872 'tbl_structure.php' => __('Structure'),
2873 'tbl_sql.php' => __('SQL'),
2874 'tbl_select.php' =>__('Search'),
2875 'tbl_change.php' =>__('Insert'),
2876 'sql.php' => __('Browse'),
2878 // Values for $cfg['DefaultTabDatabase']
2879 'db_structure.php' => __('Structure'),
2880 'db_sql.php' => __('SQL'),
2881 'db_search.php' => __('Search'),
2882 'db_operations.php' => __('Operations'),
2884 return $mapping[$target];
2888 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2890 * @param string $string Text where to do expansion.
2891 * @param function $escape Function to call for escaping variable values.
2892 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2894 * @return string
2896 function PMA_expandUserString($string, $escape = null, $updates = array())
2898 /* Content */
2899 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2900 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2901 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2902 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2903 $vars['database'] = $GLOBALS['db'];
2904 $vars['table'] = $GLOBALS['table'];
2905 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2907 /* Update forced variables */
2908 foreach ($updates as $key => $val) {
2909 $vars[$key] = $val;
2912 /* Replacement mapping */
2914 * The __VAR__ ones are for backward compatibility, because user
2915 * might still have it in cookies.
2917 $replace = array(
2918 '@HTTP_HOST@' => $vars['http_host'],
2919 '@SERVER@' => $vars['server_name'],
2920 '__SERVER__' => $vars['server_name'],
2921 '@VERBOSE@' => $vars['server_verbose'],
2922 '@VSERVER@' => $vars['server_verbose_or_name'],
2923 '@DATABASE@' => $vars['database'],
2924 '__DB__' => $vars['database'],
2925 '@TABLE@' => $vars['table'],
2926 '__TABLE__' => $vars['table'],
2927 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2930 /* Optional escaping */
2931 if (!is_null($escape)) {
2932 foreach ($replace as $key => $val) {
2933 $replace[$key] = $escape($val);
2937 /* Fetch fields list if required */
2938 if (strpos($string, '@FIELDS@') !== false) {
2939 $fields_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
2941 $field_names = array();
2942 foreach ($fields_list as $field) {
2943 if (!is_null($escape)) {
2944 $field_names[] = $escape($field['Field']);
2945 } else {
2946 $field_names[] = $field['Field'];
2950 $replace['@FIELDS@'] = implode(',', $field_names);
2953 /* Do the replacement */
2954 return strtr(strftime($string), $replace);
2958 * function that generates a json output for an ajax request and ends script
2959 * execution
2961 * @param bool $message message string containing the html of the message
2962 * @param bool $success success whether the ajax request was successfull
2963 * @param array $extra_data extra_data optional - any other data as part of the json request
2966 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2968 $response = array();
2969 if ( $success == true ) {
2970 $response['success'] = true;
2971 if ($message instanceof PMA_Message) {
2972 $response['message'] = $message->getDisplay();
2974 else {
2975 $response['message'] = $message;
2978 else {
2979 $response['success'] = false;
2980 if ($message instanceof PMA_Message) {
2981 $response['error'] = $message->getDisplay();
2983 else {
2984 $response['error'] = $message;
2988 // If extra_data has been provided, append it to the response array
2989 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
2990 $response = array_merge($response, $extra_data);
2993 // Set the Content-Type header to JSON so that jQuery parses the
2994 // response correctly.
2996 // At this point, other headers might have been sent;
2997 // even if $GLOBALS['is_header_sent'] is true,
2998 // we have to send these additional headers.
2999 header('Cache-Control: no-cache');
3000 header("Content-Type: application/json");
3002 echo json_encode($response);
3004 if (!defined('TESTSUITE'))
3005 exit;
3009 * Display the form used to browse anywhere on the local server for the file to import
3011 * @param $max_upload_size
3013 function PMA_browseUploadFile($max_upload_size)
3015 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3016 echo '<div id="upload_form_status" style="display: none;"></div>';
3017 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3018 echo '<input type="file" name="import_file" id="input_import_file" />';
3019 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3020 // some browsers should respect this :)
3021 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3025 * Display the form used to select a file to import from the server upload directory
3027 * @param $import_list
3028 * @param $uploaddir
3030 function PMA_selectUploadFile($import_list, $uploaddir)
3032 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3033 $extensions = '';
3034 foreach ($import_list as $key => $val) {
3035 if (!empty($extensions)) {
3036 $extensions .= '|';
3038 $extensions .= $val['extension'];
3040 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
3042 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
3043 if ($files === false) {
3044 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
3045 } elseif (!empty($files)) {
3046 echo "\n";
3047 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3048 echo ' <option value="">&nbsp;</option>' . "\n";
3049 echo $files;
3050 echo ' </select>' . "\n";
3051 } elseif (empty ($files)) {
3052 echo '<i>' . __('There are no files to upload') . '</i>';
3057 * Build titles and icons for action links
3059 * @return array the action titles
3061 function PMA_buildActionTitles()
3063 $titles = array();
3065 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3066 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3067 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3068 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3069 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3070 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3071 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3072 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3073 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3074 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3075 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3076 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3077 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3078 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3079 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3080 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3081 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3082 return $titles;
3086 * This function processes the datatypes supported by the DB, as specified in
3087 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3088 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3090 * @param bool $html Whether to generate an html snippet or an array
3091 * @param string $selected The value to mark as selected in HTML mode
3093 * @return mixed An HTML snippet or an array of datatypes.
3096 function PMA_getSupportedDatatypes($html = false, $selected = '')
3098 global $cfg;
3100 if ($html) {
3101 // NOTE: the SELECT tag in not included in this snippet.
3102 $retval = '';
3103 foreach ($cfg['ColumnTypes'] as $key => $value) {
3104 if (is_array($value)) {
3105 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3106 foreach ($value as $subvalue) {
3107 if ($subvalue == $selected) {
3108 $retval .= "<option selected='selected'>";
3109 $retval .= $subvalue;
3110 $retval .= "</option>";
3111 } else if ($subvalue === '-') {
3112 $retval .= "<option disabled='disabled'>";
3113 $retval .= $subvalue;
3114 $retval .= "</option>";
3115 } else {
3116 $retval .= "<option>$subvalue</option>";
3119 $retval .= '</optgroup>';
3120 } else {
3121 if ($selected == $value) {
3122 $retval .= "<option selected='selected'>$value</option>";
3123 } else {
3124 $retval .= "<option>$value</option>";
3128 } else {
3129 $retval = array();
3130 foreach ($cfg['ColumnTypes'] as $value) {
3131 if (is_array($value)) {
3132 foreach ($value as $subvalue) {
3133 if ($subvalue !== '-') {
3134 $retval[] = $subvalue;
3137 } else {
3138 if ($value !== '-') {
3139 $retval[] = $value;
3145 return $retval;
3146 } // end PMA_getSupportedDatatypes()
3149 * Returns a list of datatypes that are not (yet) handled by PMA.
3150 * Used by: tbl_change.php and libraries/db_routines.inc.php
3152 * @return array list of datatypes
3155 function PMA_unsupportedDatatypes()
3157 // These GIS data types are not yet supported.
3158 $no_support_types = array('geometry',
3159 'point',
3160 'linestring',
3161 'polygon',
3162 'multipoint',
3163 'multilinestring',
3164 'multipolygon',
3165 'geometrycollection'
3168 return $no_support_types;
3172 * Creates a dropdown box with MySQL functions for a particular column.
3174 * @param array $field Data about the column for which
3175 * to generate the dropdown
3176 * @param bool $insert_mode Whether the operation is 'insert'
3178 * @global array $cfg PMA configuration
3179 * @global array $analyzed_sql Analyzed SQL query
3180 * @global mixed $data (null/string) FIXME: what is this for?
3182 * @return string An HTML snippet of a dropdown list with function
3183 * names appropriate for the requested column.
3185 function PMA_getFunctionsForField($field, $insert_mode)
3187 global $cfg, $analyzed_sql, $data;
3189 $selected = '';
3190 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3191 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3192 // which will then reveal the available dropdown options
3193 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3194 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3195 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3196 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3197 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3198 } else {
3199 $dropdown = array();
3200 $default_function = '';
3202 $dropdown_built = array();
3203 $op_spacing_needed = false;
3204 // what function defined as default?
3205 // for the first timestamp we don't set the default function
3206 // if there is a default value for the timestamp
3207 // (not including CURRENT_TIMESTAMP)
3208 // and the column does not have the
3209 // ON UPDATE DEFAULT TIMESTAMP attribute.
3210 if ($field['True_Type'] == 'timestamp'
3211 && empty($field['Default'])
3212 && empty($data)
3213 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3214 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3216 // For primary keys of type char(36) or varchar(36) UUID if the default function
3217 // Only applies to insert mode, as it would silently trash data on updates.
3218 if ($insert_mode
3219 && $field['Key'] == 'PRI'
3220 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3222 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3224 // this is set only when appropriate and is always true
3225 if (isset($field['display_binary_as_hex'])) {
3226 $default_function = 'UNHEX';
3229 // Create the output
3230 $retval = ' <option></option>' . "\n";
3231 // loop on the dropdown array and print all available options for that field.
3232 foreach ($dropdown as $each_dropdown) {
3233 $retval .= ' ';
3234 $retval .= '<option';
3235 if ($default_function === $each_dropdown) {
3236 $retval .= ' selected="selected"';
3238 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3239 $dropdown_built[$each_dropdown] = 'true';
3240 $op_spacing_needed = true;
3242 // For compatibility's sake, do not let out all other functions. Instead
3243 // print a separator (blank) and then show ALL functions which weren't shown
3244 // yet.
3245 $cnt_functions = count($cfg['Functions']);
3246 for ($j = 0; $j < $cnt_functions; $j++) {
3247 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3248 // Is current function defined as default?
3249 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3250 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3251 ? ' selected="selected"'
3252 : '';
3253 if ($op_spacing_needed == true) {
3254 $retval .= ' ';
3255 $retval .= '<option value="">--------</option>' . "\n";
3256 $op_spacing_needed = false;
3259 $retval .= ' ';
3260 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3262 } // end for
3264 return $retval;
3265 } // end PMA_getFunctionsForField()
3268 * Checks if the current user has a specific privilege and returns true if the
3269 * user indeed has that privilege or false if (s)he doesn't. This function must
3270 * only be used for features that are available since MySQL 5, because it
3271 * relies on the INFORMATION_SCHEMA database to be present.
3273 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3274 * // Checks if the currently logged in user has the global
3275 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3276 * // user has this privilege on database 'mydb'.
3279 * @param string $priv The privilege to check
3280 * @param mixed $db null, to only check global privileges
3281 * string, db name where to also check for privileges
3282 * @param mixed $tbl null, to only check global privileges
3283 * string, db name where to also check for privileges
3285 * @return bool
3287 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3289 // Get the username for the current user in the format
3290 // required to use in the information schema database.
3291 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3292 if ($user === false) {
3293 return false;
3295 $user = explode('@', $user);
3296 $username = "''";
3297 $username .= str_replace("'", "''", $user[0]);
3298 $username .= "''@''";
3299 $username .= str_replace("'", "''", $user[1]);
3300 $username .= "''";
3301 // Prepage the query
3302 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3303 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3304 // Check global privileges first.
3305 if (PMA_DBI_fetch_value(sprintf($query,
3306 'USER_PRIVILEGES',
3307 $username,
3308 $priv))) {
3309 return true;
3311 // If a database name was provided and user does not have the
3312 // required global privilege, try database-wise permissions.
3313 if ($db !== null) {
3314 $query .= " AND TABLE_SCHEMA='%s'";
3315 if (PMA_DBI_fetch_value(sprintf($query,
3316 'SCHEMA_PRIVILEGES',
3317 $username,
3318 $priv,
3319 PMA_sqlAddSlashes($db)))) {
3320 return true;
3322 } else {
3323 // There was no database name provided and the user
3324 // does not have the correct global privilege.
3325 return false;
3327 // If a table name was also provided and we still didn't
3328 // find any valid privileges, try table-wise privileges.
3329 if ($tbl !== null) {
3330 $query .= " AND TABLE_NAME='%s'";
3331 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3332 'TABLE_PRIVILEGES',
3333 $username,
3334 $priv,
3335 PMA_sqlAddSlashes($db),
3336 PMA_sqlAddSlashes($tbl)))) {
3337 return true;
3340 // If we reached this point, the user does not
3341 // have even valid table-wise privileges.
3342 return false;
3346 * Returns server type for current connection
3348 * Known types are: Drizzle, MariaDB and MySQL (default)
3350 * @return string
3352 function PMA_getServerType()
3354 $server_type = 'MySQL';
3355 if (PMA_DRIZZLE) {
3356 $server_type = 'Drizzle';
3357 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3358 $server_type = 'MariaDB';
3360 return $server_type;