Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / libraries / common.lib.php
blob522e471e4f5d4b204420960a4638c1dc80db37c7
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 * Exponential expression / raise number into power
12 * @param string $base
13 * @param string $exp
14 * @param mixed $use_function pow function to use, or false for auto-detect
15 * @return mixed string or float
17 function PMA_pow($base, $exp, $use_function = false)
19 static $pow_function = null;
21 if (null == $pow_function) {
22 if (function_exists('bcpow')) {
23 // BCMath Arbitrary Precision Mathematics Function
24 $pow_function = 'bcpow';
25 } elseif (function_exists('gmp_pow')) {
26 // GMP Function
27 $pow_function = 'gmp_pow';
28 } else {
29 // PHP function
30 $pow_function = 'pow';
34 if (! $use_function) {
35 $use_function = $pow_function;
38 if ($exp < 0 && 'pow' != $use_function) {
39 return false;
41 switch ($use_function) {
42 case 'bcpow' :
43 // bcscale() needed for testing PMA_pow() with base values < 1
44 bcscale(10);
45 $pow = bcpow($base, $exp);
46 break;
47 case 'gmp_pow' :
48 $pow = gmp_strval(gmp_pow($base, $exp));
49 break;
50 case 'pow' :
51 $base = (float) $base;
52 $exp = (int) $exp;
53 $pow = pow($base, $exp);
54 break;
55 default:
56 $pow = $use_function($base, $exp);
59 return $pow;
62 /**
63 * string PMA_getIcon(string $icon)
65 * @param string $icon name of icon file
66 * @param string $alternate alternate text
67 * @param boolean $container include in container
68 * @param boolean $force_text whether to force alternate text to be displayed
69 * @return html img tag
71 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
73 $include_icon = false;
74 $include_text = false;
75 $include_box = false;
76 $alternate = htmlspecialchars($alternate);
77 $button = '';
79 if ($GLOBALS['cfg']['PropertiesIconic']) {
80 $include_icon = true;
83 if ($force_text
84 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
85 || ! $include_icon) {
86 // $cfg['PropertiesIconic'] is false or both
87 // OR we have no $include_icon
88 $include_text = true;
91 if ($include_text && $include_icon && $container) {
92 // we have icon, text and request for container
93 $include_box = true;
96 // Always use a span (we rely on this in js/sql.js)
97 $button .= '<span class="nowrap">';
99 if ($include_icon) {
100 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
101 . ' title="' . $alternate . '" alt="' . $alternate . '"'
102 . ' class="icon" width="16" height="16" />';
105 if ($include_icon && $include_text) {
106 $button .= ' ';
109 if ($include_text) {
110 $button .= $alternate;
113 $button .= '</span>';
115 return $button;
119 * Displays the maximum size for an upload
121 * @param integer $max_upload_size the size
122 * @return string the message
124 * @access public
126 function PMA_displayMaximumUploadSize($max_upload_size)
128 // I have to reduce the second parameter (sensitiveness) from 6 to 4
129 // to avoid weird results like 512 kKib
130 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
131 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
135 * Generates a hidden field which should indicate to the browser
136 * the maximum size for upload
138 * @param integer $max_size the size
139 * @return string the INPUT field
141 * @access public
143 function PMA_generateHiddenMaxFileSize($max_size)
145 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
149 * Add slashes before "'" and "\" characters so a value containing them can
150 * be used in a sql comparison.
152 * @param string $a_string the string to slash
153 * @param bool $is_like whether the string will be used in a 'LIKE' clause
154 * (it then requires two more escaped sequences) or not
155 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
156 * (converts \n to \\n, \r to \\r)
157 * @param bool $php_code whether this function is used as part of the
158 * "Create PHP code" dialog
160 * @return string the slashed string
162 * @access public
164 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
166 if ($is_like) {
167 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
168 } else {
169 $a_string = str_replace('\\', '\\\\', $a_string);
172 if ($crlf) {
173 $a_string = str_replace("\n", '\n', $a_string);
174 $a_string = str_replace("\r", '\r', $a_string);
175 $a_string = str_replace("\t", '\t', $a_string);
178 if ($php_code) {
179 $a_string = str_replace('\'', '\\\'', $a_string);
180 } else {
181 $a_string = str_replace('\'', '\'\'', $a_string);
184 return $a_string;
185 } // end of the 'PMA_sqlAddSlashes()' function
189 * Add slashes before "_" and "%" characters for using them in MySQL
190 * database, table and field names.
191 * Note: This function does not escape backslashes!
193 * @param string $name the string to escape
194 * @return string the escaped string
196 * @access public
198 function PMA_escape_mysql_wildcards($name)
200 $name = str_replace('_', '\\_', $name);
201 $name = str_replace('%', '\\%', $name);
203 return $name;
204 } // end of the 'PMA_escape_mysql_wildcards()' function
207 * removes slashes before "_" and "%" characters
208 * Note: This function does not unescape backslashes!
210 * @param string $name the string to escape
211 * @return string the escaped string
212 * @access public
214 function PMA_unescape_mysql_wildcards($name)
216 $name = str_replace('\\_', '_', $name);
217 $name = str_replace('\\%', '%', $name);
219 return $name;
220 } // end of the 'PMA_unescape_mysql_wildcards()' function
223 * removes quotes (',",`) from a quoted string
225 * checks if the sting is quoted and removes this quotes
227 * @param string $quoted_string string to remove quotes from
228 * @param string $quote type of quote to remove
229 * @return string unqoted string
231 function PMA_unQuote($quoted_string, $quote = null)
233 $quotes = array();
235 if (null === $quote) {
236 $quotes[] = '`';
237 $quotes[] = '"';
238 $quotes[] = "'";
239 } else {
240 $quotes[] = $quote;
243 foreach ($quotes as $quote) {
244 if (substr($quoted_string, 0, 1) === $quote
245 && substr($quoted_string, -1, 1) === $quote) {
246 $unquoted_string = substr($quoted_string, 1, -1);
247 // replace escaped quotes
248 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
249 return $unquoted_string;
253 return $quoted_string;
257 * format sql strings
259 * @todo move into PMA_Sql
260 * @param mixed $parsed_sql pre-parsed SQL structure
261 * @param string $unparsed_sql
262 * @return string the formatted sql
264 * @global array the configuration array
265 * @global boolean whether the current statement is a multiple one or not
267 * @access public
270 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
272 global $cfg;
274 // Check that we actually have a valid set of parsed data
275 // well, not quite
276 // first check for the SQL parser having hit an error
277 if (PMA_SQP_isError()) {
278 return htmlspecialchars($parsed_sql['raw']);
280 // then check for an array
281 if (! is_array($parsed_sql)) {
282 // We don't so just return the input directly
283 // This is intended to be used for when the SQL Parser is turned off
284 $formatted_sql = '<pre>' . "\n"
285 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
286 . '</pre>';
287 return $formatted_sql;
290 $formatted_sql = '';
292 switch ($cfg['SQP']['fmtType']) {
293 case 'none':
294 if ($unparsed_sql != '') {
295 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
296 } else {
297 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
299 break;
300 case 'html':
301 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
302 break;
303 case 'text':
304 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
305 break;
306 default:
307 break;
308 } // end switch
310 return $formatted_sql;
311 } // end of the "PMA_formatSql()" function
315 * Displays a link to the official MySQL documentation
317 * @param string $chapter chapter of "HTML, one page per chapter" documentation
318 * @param string $link contains name of page/anchor that is being linked
319 * @param bool $big_icon whether to use big icon (like in left frame)
320 * @param string $anchor anchor to page part
321 * @param bool $just_open whether only the opening <a> tag should be returned
323 * @return string the html link
325 * @access public
327 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
329 global $cfg;
331 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
332 return '';
335 // Fixup for newly used names:
336 $chapter = str_replace('_', '-', strtolower($chapter));
337 $link = str_replace('_', '-', strtolower($link));
339 switch ($cfg['MySQLManualType']) {
340 case 'chapters':
341 if (empty($chapter)) {
342 $chapter = 'index';
344 if (empty($anchor)) {
345 $anchor = $link;
347 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
348 break;
349 case 'big':
350 if (empty($anchor)) {
351 $anchor = $link;
353 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
354 break;
355 case 'searchable':
356 if (empty($link)) {
357 $link = 'index';
359 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
360 if (!empty($anchor)) {
361 $url .= '#' . $anchor;
363 break;
364 case 'viewable':
365 default:
366 if (empty($link)) {
367 $link = 'index';
369 $mysql = '5.0';
370 $lang = 'en';
371 if (defined('PMA_MYSQL_INT_VERSION')) {
372 if (PMA_MYSQL_INT_VERSION >= 50500) {
373 $mysql = '5.5';
374 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
375 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
376 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
377 $mysql = '5.1';
378 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
379 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
380 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
381 $mysql = '5.0';
382 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
383 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
386 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
387 if (!empty($anchor)) {
388 $url .= '#' . $anchor;
390 break;
393 if ($just_open) {
394 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
395 } elseif ($big_icon) {
396 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
397 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
398 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
399 } else {
400 return '[<a href="' . PMA_linkURL($url) . '" target="mysql_doc">' . __('Documentation') . '</a>]';
402 } // end of the 'PMA_showMySQLDocu()' function
406 * Displays a link to the phpMyAdmin documentation
408 * @param string $anchor anchor in documentation
409 * @return string the html link
411 * @access public
413 function PMA_showDocu($anchor) {
414 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
415 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
416 } else {
417 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
419 } // end of the 'PMA_showDocu()' function
422 * Displays a link to the PHP documentation
424 * @param string $target anchor in documentation
425 * @return string the html link
427 * @access public
429 function PMA_showPHPDocu($target) {
430 $url = PMA_getPHPDocLink($target);
432 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
433 return '<a href="' . $url . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
434 } else {
435 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
437 } // end of the 'PMA_showPHPDocu()' function
440 * returns HTML for a footnote marker and add the messsage to the footnotes
442 * @param string $message the error message
443 * @param bool $bbcode
444 * @param string $type
445 * @return string html code for a footnote marker
446 * @access public
448 function PMA_showHint($message, $bbcode = false, $type = 'notice')
450 if ($message instanceof PMA_Message) {
451 $key = $message->getHash();
452 $type = $message->getLevel();
453 } else {
454 $key = md5($message);
457 if (! isset($GLOBALS['footnotes'][$key])) {
458 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
459 $GLOBALS['footnotes'] = array();
461 $nr = count($GLOBALS['footnotes']) + 1;
462 // this is the first instance of this message
463 $instance = 1;
464 $GLOBALS['footnotes'][$key] = array(
465 'note' => $message,
466 'type' => $type,
467 'nr' => $nr,
468 'instance' => $instance
470 } else {
471 $nr = $GLOBALS['footnotes'][$key]['nr'];
472 // another instance of this message (to ensure ids are unique)
473 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
476 if ($bbcode) {
477 return '[sup]' . $nr . '[/sup]';
480 // footnotemarker used in js/tooltip.js
481 return '<sup class="footnotemarker">' . $nr . '</sup>' .
482 '<img class="footnotemarker" id="footnote_' . $nr . '_' . $instance . '" src="' .
483 $GLOBALS['pmaThemeImage'] . 'b_help.png" alt="" />';
487 * Displays a MySQL error message in the right frame.
489 * @param string $error_message the error message
490 * @param string $the_query the sql query that failed
491 * @param bool $is_modify_link whether to show a "modify" link or not
492 * @param string $back_url the "back" link url (full path is not required)
493 * @param bool $exit EXIT the page?
495 * @global string the curent table
496 * @global string the current db
498 * @access public
500 function PMA_mysqlDie($error_message = '', $the_query = '',
501 $is_modify_link = true, $back_url = '', $exit = true)
503 global $table, $db;
506 * start http output, display html headers
508 require_once './libraries/header.inc.php';
510 $error_msg_output = '';
512 if (!$error_message) {
513 $error_message = PMA_DBI_getError();
515 if (!$the_query && !empty($GLOBALS['sql_query'])) {
516 $the_query = $GLOBALS['sql_query'];
519 // --- Added to solve bug #641765
520 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
521 $formatted_sql = htmlspecialchars($the_query);
522 } elseif (empty($the_query) || trim($the_query) == '') {
523 $formatted_sql = '';
524 } else {
525 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
526 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
527 } else {
528 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
531 // ---
532 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
533 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
534 // if the config password is wrong, or the MySQL server does not
535 // respond, do not show the query that would reveal the
536 // username/password
537 if (!empty($the_query) && !strstr($the_query, 'connect')) {
538 // --- Added to solve bug #641765
539 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
540 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
541 $error_msg_output .= '<br />' . "\n";
543 // ---
544 // modified to show the help on sql errors
545 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
546 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
547 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
549 if ($is_modify_link) {
550 $_url_params = array(
551 'sql_query' => $the_query,
552 'show_query' => 1,
554 if (strlen($table)) {
555 $_url_params['db'] = $db;
556 $_url_params['table'] = $table;
557 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
558 } elseif (strlen($db)) {
559 $_url_params['db'] = $db;
560 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
561 } else {
562 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
565 $error_msg_output .= $doedit_goto
566 . PMA_getIcon('b_edit.png', __('Edit'))
567 . '</a>';
568 } // end if
569 $error_msg_output .= ' </p>' . "\n"
570 .' <p>' . "\n"
571 .' ' . $formatted_sql . "\n"
572 .' </p>' . "\n";
573 } // end if
575 if (!empty($error_message)) {
576 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
578 // modified to show the help on error-returns
579 // (now error-messages-server)
580 $error_msg_output .= '<p>' . "\n"
581 . ' <strong>' . __('MySQL said: ') . '</strong>'
582 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
583 . "\n"
584 . '</p>' . "\n";
586 // The error message will be displayed within a CODE segment.
587 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
589 // Replace all non-single blanks with their HTML-counterpart
590 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
591 // Replace TAB-characters with their HTML-counterpart
592 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
593 // Replace linebreaks
594 $error_message = nl2br($error_message);
596 $error_msg_output .= '<code>' . "\n"
597 . $error_message . "\n"
598 . '</code><br />' . "\n";
599 $error_msg_output .= '</div>';
601 $_SESSION['Import_message']['message'] = $error_msg_output;
603 if ($exit) {
605 * If in an Ajax request
606 * - avoid displaying a Back link
607 * - use PMA_ajaxResponse() to transmit the message and exit
609 if($GLOBALS['is_ajax_request'] == true) {
610 PMA_ajaxResponse($error_msg_output, false);
612 if (! empty($back_url)) {
613 if (strstr($back_url, '?')) {
614 $back_url .= '&amp;no_history=true';
615 } else {
616 $back_url .= '?no_history=true';
619 $_SESSION['Import_message']['go_back_url'] = $back_url;
621 $error_msg_output .= '<fieldset class="tblFooters">';
622 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
623 $error_msg_output .= '</fieldset>' . "\n\n";
626 echo $error_msg_output;
628 * display footer and exit
630 require './libraries/footer.inc.php';
631 } else {
632 echo $error_msg_output;
634 } // end of the 'PMA_mysqlDie()' function
637 * returns array with tables of given db with extended information and grouped
639 * @param string $db name of db
640 * @param string $tables name of tables
641 * @param integer $limit_offset list offset
642 * @param int|bool $limit_count max tables to return
643 * @return array (recursive) grouped table list
645 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
647 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
649 if (null === $tables) {
650 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
651 if ($GLOBALS['cfg']['NaturalOrder']) {
652 uksort($tables, 'strnatcasecmp');
656 if (count($tables) < 1) {
657 return $tables;
660 $default = array(
661 'Name' => '',
662 'Rows' => 0,
663 'Comment' => '',
664 'disp_name' => '',
667 $table_groups = array();
669 // for blobstreaming - list of blobstreaming tables
671 // load PMA configuration
672 $PMA_Config = $GLOBALS['PMA_Config'];
674 foreach ($tables as $table_name => $table) {
675 // if BS tables exist
676 if (PMA_BS_IsHiddenTable($table_name)) {
677 continue;
680 // check for correct row count
681 if (null === $table['Rows']) {
682 // Do not check exact row count here,
683 // if row count is invalid possibly the table is defect
684 // and this would break left frame;
685 // but we can check row count if this is a view or the
686 // information_schema database
687 // since PMA_Table::countRecords() returns a limited row count
688 // in this case.
690 // set this because PMA_Table::countRecords() can use it
691 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
693 if ($tbl_is_view || strtolower($db) == 'information_schema'
694 || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
695 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'], false, true);
699 // in $group we save the reference to the place in $table_groups
700 // where to store the table info
701 if ($GLOBALS['cfg']['LeftFrameDBTree']
702 && $sep && strstr($table_name, $sep))
704 $parts = explode($sep, $table_name);
706 $group =& $table_groups;
707 $i = 0;
708 $group_name_full = '';
709 $parts_cnt = count($parts) - 1;
710 while ($i < $parts_cnt
711 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
712 $group_name = $parts[$i] . $sep;
713 $group_name_full .= $group_name;
715 if (! isset($group[$group_name])) {
716 $group[$group_name] = array();
717 $group[$group_name]['is' . $sep . 'group'] = true;
718 $group[$group_name]['tab' . $sep . 'count'] = 1;
719 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
720 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
721 $table = $group[$group_name];
722 $group[$group_name] = array();
723 $group[$group_name][$group_name] = $table;
724 unset($table);
725 $group[$group_name]['is' . $sep . 'group'] = true;
726 $group[$group_name]['tab' . $sep . 'count'] = 1;
727 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
728 } else {
729 $group[$group_name]['tab' . $sep . 'count']++;
731 $group =& $group[$group_name];
732 $i++;
734 } else {
735 if (! isset($table_groups[$table_name])) {
736 $table_groups[$table_name] = array();
738 $group =& $table_groups;
742 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
743 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
744 // switch tooltip and name
745 $table['Comment'] = $table['Name'];
746 $table['disp_name'] = $table['Comment'];
747 } else {
748 $table['disp_name'] = $table['Name'];
751 $group[$table_name] = array_merge($default, $table);
754 return $table_groups;
757 /* ----------------------- Set of misc functions ----------------------- */
761 * Adds backquotes on both sides of a database, table or field name.
762 * and escapes backquotes inside the name with another backquote
764 * example:
765 * <code>
766 * echo PMA_backquote('owner`s db'); // `owner``s db`
768 * </code>
770 * @param mixed $a_name the database, table or field name to "backquote"
771 * or array of it
772 * @param boolean $do_it a flag to bypass this function (used by dump
773 * functions)
774 * @return mixed the "backquoted" database, table or field name
775 * @access public
777 function PMA_backquote($a_name, $do_it = true)
779 if (is_array($a_name)) {
780 foreach ($a_name as &$data) {
781 $data = PMA_backquote($data, $do_it);
783 return $a_name;
786 if (! $do_it) {
787 global $PMA_SQPdata_forbidden_word;
789 if(! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
790 return $a_name;
794 // '0' is also empty for php :-(
795 if (strlen($a_name) && $a_name !== '*') {
796 return '`' . str_replace('`', '``', $a_name) . '`';
797 } else {
798 return $a_name;
800 } // end of the 'PMA_backquote()' function
803 * Defines the <CR><LF> value depending on the user OS.
805 * @return string the <CR><LF> value to use
807 * @access public
809 function PMA_whichCrlf()
811 $the_crlf = "\n";
813 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
814 // Win case
815 if (PMA_USR_OS == 'Win') {
816 $the_crlf = "\r\n";
818 // Others
819 else {
820 $the_crlf = "\n";
823 return $the_crlf;
824 } // end of the 'PMA_whichCrlf()' function
827 * Reloads navigation if needed.
829 * @param $jsonly prints out pure JavaScript
830 * @global array configuration
832 * @access public
834 function PMA_reloadNavigation($jsonly=false)
836 global $cfg;
838 // Reloads the navigation frame via JavaScript if required
839 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
840 // one of the reasons for a reload is when a table is dropped
841 // in this case, get rid of the table limit offset, otherwise
842 // we have a problem when dropping a table on the last page
843 // and the offset becomes greater than the total number of tables
844 unset($_SESSION['tmp_user_values']['table_limit_offset']);
845 echo "\n";
846 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
847 if (!$jsonly)
848 echo '<script type="text/javascript">' . PHP_EOL;
850 //<![CDATA[
851 if (typeof(window.parent) != 'undefined'
852 && typeof(window.parent.frame_navigation) != 'undefined'
853 && window.parent.goTo) {
854 window.parent.goTo('<?php echo $reload_url; ?>');
856 //]]>
857 <?php
858 if (!$jsonly)
859 echo '</script>' . PHP_EOL;
861 unset($GLOBALS['reload']);
866 * displays the message and the query
867 * usually the message is the result of the query executed
869 * @param string $message the message to display
870 * @param string $sql_query the query to display
871 * @param string $type the type (level) of the message
872 * @param boolean $is_view is this a message after a VIEW operation?
873 * @global array the configuration array
874 * @access public
876 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
879 * PMA_ajaxResponse uses this function to collect the string of HTML generated
880 * for showing the message. Use output buffering to collect it and return it
881 * in a string. In some special cases on sql.php, buffering has to be disabled
882 * and hence we check with $GLOBALS['buffer_message']
884 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
885 ob_start();
887 global $cfg;
889 if (null === $sql_query) {
890 if (! empty($GLOBALS['display_query'])) {
891 $sql_query = $GLOBALS['display_query'];
892 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
893 $sql_query = $GLOBALS['unparsed_sql'];
894 } elseif (! empty($GLOBALS['sql_query'])) {
895 $sql_query = $GLOBALS['sql_query'];
896 } else {
897 $sql_query = '';
901 if (isset($GLOBALS['using_bookmark_message'])) {
902 $GLOBALS['using_bookmark_message']->display();
903 unset($GLOBALS['using_bookmark_message']);
906 // Corrects the tooltip text via JS if required
907 // @todo this is REALLY the wrong place to do this - very unexpected here
908 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
909 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
910 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
911 echo "\n";
912 echo '<script type="text/javascript">' . "\n";
913 echo '//<![CDATA[' . "\n";
914 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
915 echo '//]]>' . "\n";
916 echo '</script>' . "\n";
917 } // end if ... elseif
919 // Checks if the table needs to be repaired after a TRUNCATE query.
920 // @todo what about $GLOBALS['display_query']???
921 // @todo this is REALLY the wrong place to do this - very unexpected here
922 if (strlen($GLOBALS['table'])
923 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
924 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
925 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
928 unset($tbl_status);
930 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
931 // check for it's presence before using it
932 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
934 if ($message instanceof PMA_Message) {
935 if (isset($GLOBALS['special_message'])) {
936 $message->addMessage($GLOBALS['special_message']);
937 unset($GLOBALS['special_message']);
939 $message->display();
940 $type = $message->getLevel();
941 } else {
942 echo '<div class="' . $type . '">';
943 echo PMA_sanitize($message);
944 if (isset($GLOBALS['special_message'])) {
945 echo PMA_sanitize($GLOBALS['special_message']);
946 unset($GLOBALS['special_message']);
948 echo '</div>';
951 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
952 // Html format the query to be displayed
953 // If we want to show some sql code it is easiest to create it here
954 /* SQL-Parser-Analyzer */
956 if (! empty($GLOBALS['show_as_php'])) {
957 $new_line = '\\n"<br />' . "\n"
958 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
959 $query_base = htmlspecialchars(addslashes($sql_query));
960 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
961 } else {
962 $query_base = $sql_query;
965 $query_too_big = false;
967 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
968 // when the query is large (for example an INSERT of binary
969 // data), the parser chokes; so avoid parsing the query
970 $query_too_big = true;
971 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
972 } elseif (! empty($GLOBALS['parsed_sql'])
973 && $query_base == $GLOBALS['parsed_sql']['raw']) {
974 // (here, use "! empty" because when deleting a bookmark,
975 // $GLOBALS['parsed_sql'] is set but empty
976 $parsed_sql = $GLOBALS['parsed_sql'];
977 } else {
978 // Parse SQL if needed
979 $parsed_sql = PMA_SQP_parse($query_base);
980 if (PMA_SQP_isError()) {
981 unset($parsed_sql);
985 // Analyze it
986 if (isset($parsed_sql)) {
987 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
989 // Same as below (append LIMIT), append the remembered ORDER BY
990 if ($GLOBALS['cfg']['RememberSorting']
991 && isset($analyzed_display_query[0]['queryflags']['select_from'])
992 && isset($GLOBALS['sql_order_to_append'])) {
993 $query_base = $analyzed_display_query[0]['section_before_limit']
994 . "\n" . $GLOBALS['sql_order_to_append']
995 . $analyzed_display_query[0]['section_after_limit'];
997 // Need to reparse query
998 $parsed_sql = PMA_SQP_parse($query_base);
999 // update the $analyzed_display_query
1000 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1001 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1004 // Here we append the LIMIT added for navigation, to
1005 // enable its display. Adding it higher in the code
1006 // to $sql_query would create a problem when
1007 // using the Refresh or Edit links.
1009 // Only append it on SELECTs.
1012 * @todo what would be the best to do when someone hits Refresh:
1013 * use the current LIMITs ?
1016 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1017 && isset($GLOBALS['sql_limit_to_append'])) {
1018 $query_base = $analyzed_display_query[0]['section_before_limit']
1019 . "\n" . $GLOBALS['sql_limit_to_append']
1020 . $analyzed_display_query[0]['section_after_limit'];
1021 // Need to reparse query
1022 $parsed_sql = PMA_SQP_parse($query_base);
1026 if (! empty($GLOBALS['show_as_php'])) {
1027 $query_base = '$sql = "' . $query_base;
1028 } elseif (! empty($GLOBALS['validatequery'])) {
1029 try {
1030 $query_base = PMA_validateSQL($query_base);
1031 } catch (Exception $e) {
1032 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1034 } elseif (isset($parsed_sql)) {
1035 $query_base = PMA_formatSql($parsed_sql, $query_base);
1038 // Prepares links that may be displayed to edit/explain the query
1039 // (don't go to default pages, we must go to the page
1040 // where the query box is available)
1042 // Basic url query part
1043 $url_params = array();
1044 if (! isset($GLOBALS['db'])) {
1045 $GLOBALS['db'] = '';
1047 if (strlen($GLOBALS['db'])) {
1048 $url_params['db'] = $GLOBALS['db'];
1049 if (strlen($GLOBALS['table'])) {
1050 $url_params['table'] = $GLOBALS['table'];
1051 $edit_link = 'tbl_sql.php';
1052 } else {
1053 $edit_link = 'db_sql.php';
1055 } else {
1056 $edit_link = 'server_sql.php';
1059 // Want to have the query explained
1060 // but only explain a SELECT (that has not been explained)
1061 /* SQL-Parser-Analyzer */
1062 $explain_link = '';
1063 $is_select = false;
1064 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1065 $explain_params = $url_params;
1066 // Detect if we are validating as well
1067 // To preserve the validate uRL data
1068 if (! empty($GLOBALS['validatequery'])) {
1069 $explain_params['validatequery'] = 1;
1071 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1072 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1073 $_message = __('Explain SQL');
1074 $is_select = true;
1075 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1076 $explain_params['sql_query'] = substr($sql_query, 8);
1077 $_message = __('Skip Explain SQL');
1079 if (isset($explain_params['sql_query'])) {
1080 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1081 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1083 } //show explain
1085 $url_params['sql_query'] = $sql_query;
1086 $url_params['show_query'] = 1;
1088 // even if the query is big and was truncated, offer the chance
1089 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1090 if (! empty($cfg['SQLQuery']['Edit'])) {
1091 if ($cfg['EditInWindow'] == true) {
1092 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1093 } else {
1094 $onclick = '';
1097 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1098 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1099 } else {
1100 $edit_link = '';
1103 $url_qpart = PMA_generate_common_url($url_params);
1105 // Also we would like to get the SQL formed in some nice
1106 // php-code
1107 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1108 $php_params = $url_params;
1110 if (! empty($GLOBALS['show_as_php'])) {
1111 $_message = __('Without PHP Code');
1112 } else {
1113 $php_params['show_as_php'] = 1;
1114 $_message = __('Create PHP Code');
1117 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1118 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1120 if (isset($GLOBALS['show_as_php'])) {
1121 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1122 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1124 } else {
1125 $php_link = '';
1126 } //show as php
1128 // Refresh query
1129 if (! empty($cfg['SQLQuery']['Refresh'])
1130 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1131 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1132 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1133 } else {
1134 $refresh_link = '';
1135 } //show as php
1137 if (! empty($cfg['SQLValidator']['use'])
1138 && ! empty($cfg['SQLQuery']['Validate'])) {
1139 $validate_params = $url_params;
1140 if (!empty($GLOBALS['validatequery'])) {
1141 $validate_message = __('Skip Validate SQL') ;
1142 } else {
1143 $validate_params['validatequery'] = 1;
1144 $validate_message = __('Validate SQL') ;
1147 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1148 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1149 } else {
1150 $validate_link = '';
1151 } //validator
1153 if (!empty($GLOBALS['validatequery'])) {
1154 echo '<div class="sqlvalidate">';
1155 } else {
1156 echo '<code class="sql">';
1158 if ($query_too_big) {
1159 echo $shortened_query_base;
1160 } else {
1161 echo $query_base;
1164 //Clean up the end of the PHP
1165 if (! empty($GLOBALS['show_as_php'])) {
1166 echo '";';
1168 if (!empty($GLOBALS['validatequery'])) {
1169 echo '</div>';
1170 } else {
1171 echo '</code>';
1174 echo '<div class="tools">';
1175 // avoid displaying a Profiling checkbox that could
1176 // be checked, which would reexecute an INSERT, for example
1177 if (! empty($refresh_link)) {
1178 PMA_profilingCheckbox($sql_query);
1180 // if needed, generate an invisible form that contains controls for the
1181 // Inline link; this way, the behavior of the Inline link does not
1182 // depend on the profiling support or on the refresh link
1183 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1184 echo '<form action="sql.php" method="post">';
1185 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1186 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1187 echo '</form>';
1190 // in the tools div, only display the Inline link when not in ajax
1191 // mode because 1) it currently does not work and 2) we would
1192 // have two similar mechanisms on the page for the same goal
1193 if ($is_select || $GLOBALS['is_ajax_request'] === false) {
1194 // see in js/functions.js the jQuery code attached to id inline_edit
1195 // document.write conflicts with jQuery, hence used $().append()
1196 echo "<script type=\"text/javascript\">\n" .
1197 "//<![CDATA[\n" .
1198 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1199 PMA_escapeJsString(__('Inline edit of this query')) .
1200 "\" class=\"inline_edit_sql\">" .
1201 PMA_escapeJsString(__('Inline')) .
1202 "</a>]');\n" .
1203 "//]]>\n" .
1204 "</script>";
1206 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1207 echo '</div>';
1209 echo '</div>';
1210 if ($GLOBALS['is_ajax_request'] === false) {
1211 echo '<br class="clearfloat" />';
1214 // If we are in an Ajax request, we have most probably been called in
1215 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1216 // to PMA_ajaxResponse(), which will encode it for JSON.
1217 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1218 $buffer_contents = ob_get_contents();
1219 ob_end_clean();
1220 return $buffer_contents;
1222 } // end of the 'PMA_showMessage()' function
1225 * Verifies if current MySQL server supports profiling
1227 * @access public
1228 * @return boolean whether profiling is supported
1231 function PMA_profilingSupported()
1233 if (! PMA_cacheExists('profiling_supported', true)) {
1234 // 5.0.37 has profiling but for example, 5.1.20 does not
1235 // (avoid a trip to the server for MySQL before 5.0.37)
1236 // and do not set a constant as we might be switching servers
1237 if (defined('PMA_MYSQL_INT_VERSION')
1238 && PMA_MYSQL_INT_VERSION >= 50037
1239 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1240 PMA_cacheSet('profiling_supported', true, true);
1241 } else {
1242 PMA_cacheSet('profiling_supported', false, true);
1246 return PMA_cacheGet('profiling_supported', true);
1250 * Displays a form with the Profiling checkbox
1252 * @param string $sql_query
1253 * @access public
1256 function PMA_profilingCheckbox($sql_query)
1258 if (PMA_profilingSupported()) {
1259 echo '<form action="sql.php" method="post">' . "\n";
1260 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1261 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1262 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1263 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1264 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1265 echo '</form>' . "\n";
1270 * Formats $value to byte view
1272 * @param double $value the value to format
1273 * @param int $limes the sensitiveness
1274 * @param int $comma the number of decimals to retain
1276 * @return array the formatted value and its unit
1278 * @access public
1280 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1282 if ($value === null) {
1283 return null;
1286 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1287 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1289 $dh = PMA_pow(10, $comma);
1290 $li = PMA_pow(10, $limes);
1291 $unit = $byteUnits[0];
1293 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1294 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1295 // use 1024.0 to avoid integer overflow on 64-bit machines
1296 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1297 $unit = $byteUnits[$d];
1298 break 1;
1299 } // end if
1300 } // end for
1302 if ($unit != $byteUnits[0]) {
1303 // if the unit is not bytes (as represented in current language)
1304 // reformat with max length of 5
1305 // 4th parameter=true means do not reformat if value < 1
1306 $return_value = PMA_formatNumber($value, 5, $comma, true);
1307 } else {
1308 // do not reformat, just handle the locale
1309 $return_value = PMA_formatNumber($value, 0);
1312 return array(trim($return_value), $unit);
1313 } // end of the 'PMA_formatByteDown' function
1316 * Changes thousands and decimal separators to locale specific values.
1318 * @param $value
1319 * @return string
1321 function PMA_localizeNumber($value)
1323 return str_replace(
1324 array(',', '.'),
1325 array(
1326 /* l10n: Thousands separator */
1327 __(','),
1328 /* l10n: Decimal separator */
1329 __('.'),
1331 $value);
1335 * Formats $value to the given length and appends SI prefixes
1336 * with a $length of 0 no truncation occurs, number is only formated
1337 * to the current locale
1339 * examples:
1340 * <code>
1341 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1342 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1343 * echo PMA_formatNumber(-0.003, 6); // -3 m
1344 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1345 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1346 * echo PMA_formatNumber(0, 6); // 0
1348 * </code>
1349 * @param double $value the value to format
1350 * @param integer $digits_left number of digits left of the comma
1351 * @param integer $digits_right number of digits right of the comma
1352 * @param boolean $only_down do not reformat numbers below 1
1353 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1355 * @return string the formatted value and its unit
1357 * @access public
1359 * @version 1.1.0 - 2005-10-27
1361 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1363 if($value==0) return '0';
1365 $originalValue = $value;
1366 //number_format is not multibyte safe, str_replace is safe
1367 if ($digits_left === 0) {
1368 $value = number_format($value, $digits_right);
1369 if($originalValue!=0 && floatval($value) == 0) $value = ' <'.(1/PMA_pow(10,$digits_right));
1371 return PMA_localizeNumber($value);
1374 // this units needs no translation, ISO
1375 $units = array(
1376 -8 => 'y',
1377 -7 => 'z',
1378 -6 => 'a',
1379 -5 => 'f',
1380 -4 => 'p',
1381 -3 => 'n',
1382 -2 => '&micro;',
1383 -1 => 'm',
1384 0 => ' ',
1385 1 => 'k',
1386 2 => 'M',
1387 3 => 'G',
1388 4 => 'T',
1389 5 => 'P',
1390 6 => 'E',
1391 7 => 'Z',
1392 8 => 'Y'
1395 // check for negative value to retain sign
1396 if ($value < 0) {
1397 $sign = '-';
1398 $value = abs($value);
1399 } else {
1400 $sign = '';
1403 $dh = PMA_pow(10, $digits_right);
1405 // This gives us the right SI prefix already, but $digits_left parameter not incorporated
1406 $d = floor(log10($value) / 3);
1407 // Lowering the SI prefix by 1 gives us an additional 3 zeros
1408 // So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits) to use, then lower the SI prefix
1409 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1410 if($digits_left > $cur_digits) {
1411 $d-= floor(($digits_left - $cur_digits)/3);
1414 if($d<0 && $only_down) $d=0;
1416 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1417 $unit = $units[$d];
1419 // If we dont want any zeros after the comma just add the thousand seperator
1420 if($noTrailingZero)
1421 $value = PMA_localizeNumber(preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$value));
1422 else
1423 $value = PMA_localizeNumber(number_format($value, $digits_right)); //number_format is not multibyte safe, str_replace is safe
1425 if($originalValue!=0 && floatval($value) == 0) return ' <'.(1/PMA_pow(10,$digits_right)).' '.$unit;
1427 return $sign . $value . ' ' . $unit;
1428 } // end of the 'PMA_formatNumber' function
1431 * Returns the number of bytes when a formatted size is given
1433 * @param string $formatted_size the size expression (for example 8MB)
1434 * @return integer The numerical part of the expression (for example 8)
1436 function PMA_extractValueFromFormattedSize($formatted_size)
1438 $return_value = -1;
1440 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1441 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1442 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1443 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1444 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1445 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1447 return $return_value;
1448 }// end of the 'PMA_extractValueFromFormattedSize' function
1451 * Writes localised date
1453 * @param string $timestamp the current timestamp
1454 * @param string $format format
1455 * @return string the formatted date
1457 * @access public
1459 function PMA_localisedDate($timestamp = -1, $format = '')
1461 $month = array(
1462 /* l10n: Short month name */
1463 __('Jan'),
1464 /* l10n: Short month name */
1465 __('Feb'),
1466 /* l10n: Short month name */
1467 __('Mar'),
1468 /* l10n: Short month name */
1469 __('Apr'),
1470 /* l10n: Short month name */
1471 _pgettext('Short month name', 'May'),
1472 /* l10n: Short month name */
1473 __('Jun'),
1474 /* l10n: Short month name */
1475 __('Jul'),
1476 /* l10n: Short month name */
1477 __('Aug'),
1478 /* l10n: Short month name */
1479 __('Sep'),
1480 /* l10n: Short month name */
1481 __('Oct'),
1482 /* l10n: Short month name */
1483 __('Nov'),
1484 /* l10n: Short month name */
1485 __('Dec'));
1486 $day_of_week = array(
1487 /* l10n: Short week day name */
1488 __('Sun'),
1489 /* l10n: Short week day name */
1490 __('Mon'),
1491 /* l10n: Short week day name */
1492 __('Tue'),
1493 /* l10n: Short week day name */
1494 __('Wed'),
1495 /* l10n: Short week day name */
1496 __('Thu'),
1497 /* l10n: Short week day name */
1498 __('Fri'),
1499 /* l10n: Short week day name */
1500 __('Sat'));
1502 if ($format == '') {
1503 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1504 $format = __('%B %d, %Y at %I:%M %p');
1507 if ($timestamp == -1) {
1508 $timestamp = time();
1511 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1512 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1514 return strftime($date, $timestamp);
1515 } // end of the 'PMA_localisedDate()' function
1519 * returns a tab for tabbed navigation.
1520 * If the variables $link and $args ar left empty, an inactive tab is created
1522 * @param array $tab array with all options
1523 * @param array $url_params
1524 * @return string html code for one tab, a link if valid otherwise a span
1525 * @access public
1527 function PMA_generate_html_tab($tab, $url_params = array())
1529 // default values
1530 $defaults = array(
1531 'text' => '',
1532 'class' => '',
1533 'active' => null,
1534 'link' => '',
1535 'sep' => '?',
1536 'attr' => '',
1537 'args' => '',
1538 'warning' => '',
1539 'fragment' => '',
1540 'id' => '',
1543 $tab = array_merge($defaults, $tab);
1545 // determine additionnal style-class
1546 if (empty($tab['class'])) {
1547 if (! empty($tab['active'])
1548 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1549 $tab['class'] = 'active';
1550 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1551 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1552 && empty($tab['warning'])) {
1553 $tab['class'] = 'active';
1557 if (!empty($tab['warning'])) {
1558 $tab['class'] .= ' error';
1559 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1562 // If there are any tab specific URL parameters, merge those with the general URL parameters
1563 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1564 $url_params = array_merge($url_params, $tab['url_params']);
1567 // build the link
1568 if (!empty($tab['link'])) {
1569 $tab['link'] = htmlentities($tab['link']);
1570 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1571 if (! empty($tab['args'])) {
1572 foreach ($tab['args'] as $param => $value) {
1573 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1574 . urlencode($value);
1579 if (! empty($tab['fragment'])) {
1580 $tab['link'] .= $tab['fragment'];
1583 // display icon, even if iconic is disabled but the link-text is missing
1584 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1585 && isset($tab['icon'])) {
1586 // avoid generating an alt tag, because it only illustrates
1587 // the text that follows and if browser does not display
1588 // images, the text is duplicated
1589 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1590 .'%1$s" width="16" height="16" alt="" />%2$s';
1591 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1593 // check to not display an empty link-text
1594 elseif (empty($tab['text'])) {
1595 $tab['text'] = '?';
1596 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1597 E_USER_NOTICE);
1600 //Set the id for the tab, if set in the params
1601 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1602 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1604 if (!empty($tab['link'])) {
1605 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1606 .$id_string
1607 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1608 . $tab['text'] . '</a>';
1609 } else {
1610 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1611 . $tab['text'] . '</span>';
1614 $out .= '</li>';
1615 return $out;
1616 } // end of the 'PMA_generate_html_tab()' function
1619 * returns html-code for a tab navigation
1621 * @param array $tabs one element per tab
1622 * @param string $url_params
1623 * @return string html-code for tab-navigation
1625 function PMA_generate_html_tabs($tabs, $url_params)
1627 $tag_id = 'topmenu';
1628 $tab_navigation =
1629 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1630 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1632 foreach ($tabs as $tab) {
1633 $tab_navigation .= PMA_generate_html_tab($tab, $url_params);
1636 $tab_navigation .=
1637 '</ul>' . "\n"
1638 .'<div class="clearfloat"></div>'
1639 .'</div>' . "\n";
1641 return $tab_navigation;
1646 * Displays a link, or a button if the link's URL is too large, to
1647 * accommodate some browsers' limitations
1649 * @param string $url the URL
1650 * @param string $message the link message
1651 * @param mixed $tag_params string: js confirmation
1652 * array: additional tag params (f.e. style="")
1653 * @param boolean $new_form we set this to false when we are already in
1654 * a form, to avoid generating nested forms
1655 * @param boolean $strip_img
1656 * @param string $target
1658 * @return string the results to be echoed or saved in an array
1660 function PMA_linkOrButton($url, $message, $tag_params = array(),
1661 $new_form = true, $strip_img = false, $target = '')
1663 $url_length = strlen($url);
1664 // with this we should be able to catch case of image upload
1665 // into a (MEDIUM) BLOB; not worth generating even a form for these
1666 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1667 return '';
1670 if (! is_array($tag_params)) {
1671 $tmp = $tag_params;
1672 $tag_params = array();
1673 if (!empty($tmp)) {
1674 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1676 unset($tmp);
1678 if (! empty($target)) {
1679 $tag_params['target'] = htmlentities($target);
1682 $tag_params_strings = array();
1683 foreach ($tag_params as $par_name => $par_value) {
1684 // htmlspecialchars() only on non javascript
1685 $par_value = substr($par_name, 0, 2) == 'on'
1686 ? $par_value
1687 : htmlspecialchars($par_value);
1688 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1691 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1692 // no whitespace within an <a> else Safari will make it part of the link
1693 $ret = "\n" . '<a href="' . $url . '" '
1694 . implode(' ', $tag_params_strings) . '>'
1695 . $message . '</a>' . "\n";
1696 } else {
1697 // no spaces (linebreaks) at all
1698 // or after the hidden fields
1699 // IE will display them all
1701 // add class=link to submit button
1702 if (empty($tag_params['class'])) {
1703 $tag_params['class'] = 'link';
1706 // decode encoded url separators
1707 $separator = PMA_get_arg_separator();
1708 // on most places separator is still hard coded ...
1709 if ($separator !== '&') {
1710 // ... so always replace & with $separator
1711 $url = str_replace(htmlentities('&'), $separator, $url);
1712 $url = str_replace('&', $separator, $url);
1714 $url = str_replace(htmlentities($separator), $separator, $url);
1715 // end decode
1717 $url_parts = parse_url($url);
1718 $query_parts = explode($separator, $url_parts['query']);
1719 if ($new_form) {
1720 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1721 . ' method="post"' . $target . ' style="display: inline;">';
1722 $subname_open = '';
1723 $subname_close = '';
1724 $submit_name = '';
1725 } else {
1726 $query_parts[] = 'redirect=' . $url_parts['path'];
1727 if (empty($GLOBALS['subform_counter'])) {
1728 $GLOBALS['subform_counter'] = 0;
1730 $GLOBALS['subform_counter']++;
1731 $ret = '';
1732 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1733 $subname_close = ']';
1734 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1736 foreach ($query_parts as $query_pair) {
1737 list($eachvar, $eachval) = explode('=', $query_pair);
1738 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1739 . $subname_close . '" value="'
1740 . htmlspecialchars(urldecode($eachval)) . '" />';
1741 } // end while
1743 if (stristr($message, '<img')) {
1744 if ($strip_img) {
1745 $message = trim(strip_tags($message));
1746 $ret .= '<input type="submit"' . $submit_name . ' '
1747 . implode(' ', $tag_params_strings)
1748 . ' value="' . htmlspecialchars($message) . '" />';
1749 } else {
1750 $displayed_message = htmlspecialchars(
1751 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1752 $message));
1753 $ret .= '<input type="image"' . $submit_name . ' '
1754 . implode(' ', $tag_params_strings)
1755 . ' src="' . preg_replace(
1756 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1757 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1758 // Here we cannot obey PropertiesIconic completely as a
1759 // generated link would have a length over LinkLengthLimit
1760 // but we can at least show the message.
1761 // If PropertiesIconic is false or 'both'
1762 if ($GLOBALS['cfg']['PropertiesIconic'] !== true) {
1763 $ret .= ' <span class="clickprevimage">' . $displayed_message . '</span>';
1766 } else {
1767 $message = trim(strip_tags($message));
1768 $ret .= '<input type="submit"' . $submit_name . ' '
1769 . implode(' ', $tag_params_strings)
1770 . ' value="' . htmlspecialchars($message) . '" />';
1772 if ($new_form) {
1773 $ret .= '</form>';
1775 } // end if... else...
1777 return $ret;
1778 } // end of the 'PMA_linkOrButton()' function
1782 * Returns a given timespan value in a readable format.
1784 * @param int $seconds the timespan
1786 * @return string the formatted value
1788 function PMA_timespanFormat($seconds)
1790 $days = floor($seconds / 86400);
1791 if ($days > 0) {
1792 $seconds -= $days * 86400;
1794 $hours = floor($seconds / 3600);
1795 if ($days > 0 || $hours > 0) {
1796 $seconds -= $hours * 3600;
1798 $minutes = floor($seconds / 60);
1799 if ($days > 0 || $hours > 0 || $minutes > 0) {
1800 $seconds -= $minutes * 60;
1802 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1806 * Takes a string and outputs each character on a line for itself. Used
1807 * mainly for horizontalflipped display mode.
1808 * Takes care of special html-characters.
1809 * Fulfills todo-item
1810 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1812 * @todo add a multibyte safe function PMA_STR_split()
1813 * @param string $string The string
1814 * @param string $Separator The Separator (defaults to "<br />\n")
1816 * @access public
1817 * @return string The flipped string
1819 function PMA_flipstring($string, $Separator = "<br />\n")
1821 $format_string = '';
1822 $charbuff = false;
1824 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1825 $char = $string{$i};
1826 $append = false;
1828 if ($char == '&') {
1829 $format_string .= $charbuff;
1830 $charbuff = $char;
1831 } elseif ($char == ';' && !empty($charbuff)) {
1832 $format_string .= $charbuff . $char;
1833 $charbuff = false;
1834 $append = true;
1835 } elseif (! empty($charbuff)) {
1836 $charbuff .= $char;
1837 } else {
1838 $format_string .= $char;
1839 $append = true;
1842 // do not add separator after the last character
1843 if ($append && ($i != $str_len - 1)) {
1844 $format_string .= $Separator;
1848 return $format_string;
1853 * Function added to avoid path disclosures.
1854 * Called by each script that needs parameters, it displays
1855 * an error message and, by default, stops the execution.
1857 * Not sure we could use a strMissingParameter message here,
1858 * would have to check if the error message file is always available
1860 * @todo localize error message
1861 * @todo use PMA_fatalError() if $die === true?
1862 * @param array $params The names of the parameters needed by the calling script.
1863 * @param bool $die Stop the execution?
1864 * (Set this manually to false in the calling script
1865 * until you know all needed parameters to check).
1866 * @param bool $request Whether to include this list in checking for special params.
1867 * @global string path to current script
1868 * @global boolean flag whether any special variable was required
1870 * @access public
1872 function PMA_checkParameters($params, $die = true, $request = true)
1874 global $checked_special;
1876 if (! isset($checked_special)) {
1877 $checked_special = false;
1880 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1881 $found_error = false;
1882 $error_message = '';
1884 foreach ($params as $param) {
1885 if ($request && $param != 'db' && $param != 'table') {
1886 $checked_special = true;
1889 if (! isset($GLOBALS[$param])) {
1890 $error_message .= $reported_script_name
1891 . ': Missing parameter: ' . $param
1892 . PMA_showDocu('faqmissingparameters')
1893 . '<br />';
1894 $found_error = true;
1897 if ($found_error) {
1899 * display html meta tags
1901 require_once './libraries/header_meta_style.inc.php';
1902 echo '</head><body><p>' . $error_message . '</p></body></html>';
1903 if ($die) {
1904 exit();
1907 } // end function
1910 * Function to generate unique condition for specified row.
1912 * @param resource $handle current query result
1913 * @param integer $fields_cnt number of fields
1914 * @param array $fields_meta meta information about fields
1915 * @param array $row current row
1916 * @param boolean $force_unique generate condition only on pk or unique
1918 * @access public
1919 * @return array the calculated condition and whether condition is unique
1921 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1923 $primary_key = '';
1924 $unique_key = '';
1925 $nonprimary_condition = '';
1926 $preferred_condition = '';
1928 for ($i = 0; $i < $fields_cnt; ++$i) {
1929 $condition = '';
1930 $field_flags = PMA_DBI_field_flags($handle, $i);
1931 $meta = $fields_meta[$i];
1933 // do not use a column alias in a condition
1934 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1935 $meta->orgname = $meta->name;
1937 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1938 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1939 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1940 as $select_expr) {
1941 // need (string) === (string)
1942 // '' !== 0 but '' == 0
1943 if ((string) $select_expr['alias'] === (string) $meta->name) {
1944 $meta->orgname = $select_expr['column'];
1945 break;
1946 } // end if
1947 } // end foreach
1951 // Do not use a table alias in a condition.
1952 // Test case is:
1953 // select * from galerie x WHERE
1954 //(select count(*) from galerie y where y.datum=x.datum)>1
1956 // But orgtable is present only with mysqli extension so the
1957 // fix is only for mysqli.
1958 // Also, do not use the original table name if we are dealing with
1959 // a view because this view might be updatable.
1960 // (The isView() verification should not be costly in most cases
1961 // because there is some caching in the function).
1962 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1963 $meta->table = $meta->orgtable;
1966 // to fix the bug where float fields (primary or not)
1967 // can't be matched because of the imprecision of
1968 // floating comparison, use CONCAT
1969 // (also, the syntax "CONCAT(field) IS NULL"
1970 // that we need on the next "if" will work)
1971 if ($meta->type == 'real') {
1972 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1973 . PMA_backquote($meta->orgname) . ') ';
1974 } else {
1975 $condition = ' ' . PMA_backquote($meta->table) . '.'
1976 . PMA_backquote($meta->orgname) . ' ';
1977 } // end if... else...
1979 if (! isset($row[$i]) || is_null($row[$i])) {
1980 $condition .= 'IS NULL AND';
1981 } else {
1982 // timestamp is numeric on some MySQL 4.1
1983 // for real we use CONCAT above and it should compare to string
1984 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
1985 $condition .= '= ' . $row[$i] . ' AND';
1986 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1987 // hexify only if this is a true not empty BLOB or a BINARY
1988 && stristr($field_flags, 'BINARY')
1989 && !empty($row[$i])) {
1990 // do not waste memory building a too big condition
1991 if (strlen($row[$i]) < 1000) {
1992 // use a CAST if possible, to avoid problems
1993 // if the field contains wildcard characters % or _
1994 $condition .= '= CAST(0x' . bin2hex($row[$i])
1995 . ' AS BINARY) AND';
1996 } else {
1997 // this blob won't be part of the final condition
1998 $condition = '';
2000 } elseif ($meta->type == 'bit') {
2001 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2002 } else {
2003 $condition .= '= \''
2004 . PMA_sqlAddSlashes($row[$i], false, true) . '\' AND';
2007 if ($meta->primary_key > 0) {
2008 $primary_key .= $condition;
2009 } elseif ($meta->unique_key > 0) {
2010 $unique_key .= $condition;
2012 $nonprimary_condition .= $condition;
2013 } // end for
2015 // Correction University of Virginia 19991216:
2016 // prefer primary or unique keys for condition,
2017 // but use conjunction of all values if no primary key
2018 $clause_is_unique = true;
2019 if ($primary_key) {
2020 $preferred_condition = $primary_key;
2021 } elseif ($unique_key) {
2022 $preferred_condition = $unique_key;
2023 } elseif (! $force_unique) {
2024 $preferred_condition = $nonprimary_condition;
2025 $clause_is_unique = false;
2028 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2029 return(array($where_clause, $clause_is_unique));
2030 } // end function
2033 * Generate a button or image tag
2035 * @param string $button_name name of button element
2036 * @param string $button_class class of button element
2037 * @param string $image_name name of image element
2038 * @param string $text text to display
2039 * @param string $image image to display
2040 * @param string $value
2042 * @access public
2044 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2045 $image, $value = '')
2047 if ($value == '') {
2048 $value = $text;
2050 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2051 echo ' <input type="submit" name="' . $button_name . '"'
2052 .' value="' . htmlspecialchars($value) . '"'
2053 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2054 return;
2057 /* Opera has trouble with <input type="image"> */
2058 /* IE has trouble with <button> */
2059 if (PMA_USR_BROWSER_AGENT != 'IE') {
2060 echo '<button class="' . $button_class . '" type="submit"'
2061 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2062 .' title="' . htmlspecialchars($text) . '">' . "\n"
2063 . PMA_getIcon($image, $text)
2064 .'</button>' . "\n";
2065 } else {
2066 echo '<input type="image" name="' . $image_name . '" value="'
2067 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2068 . $image . '" />'
2069 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2071 } // end function
2074 * Generate a pagination selector for browsing resultsets
2076 * @param int $rows Number of rows in the pagination set
2077 * @param int $pageNow current page number
2078 * @param int $nbTotalPage number of total pages
2079 * @param int $showAll If the number of pages is lower than this
2080 * variable, no pages will be omitted in pagination
2081 * @param int $sliceStart How many rows at the beginning should always be shown?
2082 * @param int $sliceEnd How many rows at the end should always be shown?
2083 * @param int $percent Percentage of calculation page offsets to hop to a next page
2084 * @param int $range Near the current page, how many pages should
2085 * be considered "nearby" and displayed as well?
2086 * @param string $prompt The prompt to display (sometimes empty)
2088 * @return string
2089 * @access public
2091 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2092 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2093 $range = 10, $prompt = '')
2095 $increment = floor($nbTotalPage / $percent);
2096 $pageNowMinusRange = ($pageNow - $range);
2097 $pageNowPlusRange = ($pageNow + $range);
2099 $gotopage = $prompt . ' <select id="pageselector" ';
2100 if ($GLOBALS['cfg']['AjaxEnable']) {
2101 $gotopage .= ' class="ajax"';
2103 $gotopage .= ' name="pos" >' . "\n";
2104 if ($nbTotalPage < $showAll) {
2105 $pages = range(1, $nbTotalPage);
2106 } else {
2107 $pages = array();
2109 // Always show first X pages
2110 for ($i = 1; $i <= $sliceStart; $i++) {
2111 $pages[] = $i;
2114 // Always show last X pages
2115 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2116 $pages[] = $i;
2119 // Based on the number of results we add the specified
2120 // $percent percentage to each page number,
2121 // so that we have a representing page number every now and then to
2122 // immediately jump to specific pages.
2123 // As soon as we get near our currently chosen page ($pageNow -
2124 // $range), every page number will be shown.
2125 $i = $sliceStart;
2126 $x = $nbTotalPage - $sliceEnd;
2127 $met_boundary = false;
2128 while ($i <= $x) {
2129 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2130 // If our pageselector comes near the current page, we use 1
2131 // counter increments
2132 $i++;
2133 $met_boundary = true;
2134 } else {
2135 // We add the percentage increment to our current page to
2136 // hop to the next one in range
2137 $i += $increment;
2139 // Make sure that we do not cross our boundaries.
2140 if ($i > $pageNowMinusRange && ! $met_boundary) {
2141 $i = $pageNowMinusRange;
2145 if ($i > 0 && $i <= $x) {
2146 $pages[] = $i;
2150 // Since because of ellipsing of the current page some numbers may be double,
2151 // we unify our array:
2152 sort($pages);
2153 $pages = array_unique($pages);
2156 foreach ($pages as $i) {
2157 if ($i == $pageNow) {
2158 $selected = 'selected="selected" style="font-weight: bold"';
2159 } else {
2160 $selected = '';
2162 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2165 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2167 return $gotopage;
2168 } // end function
2172 * Generate navigation for a list
2174 * @todo use $pos from $_url_params
2175 * @param integer number of elements in the list
2176 * @param integer current position in the list
2177 * @param array url parameters
2178 * @param string script name for form target
2179 * @param string target frame
2180 * @param integer maximum number of elements to display from the list
2182 * @access public
2184 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2186 if ($max_count < $count) {
2187 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2188 echo __('Page number:');
2189 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2191 // Move to the beginning or to the previous page
2192 if ($pos > 0) {
2193 // patch #474210 - part 1
2194 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2195 $caption1 = '&lt;&lt;';
2196 $caption2 = ' &lt; ';
2197 $title1 = ' title="' . __('Begin') . '"';
2198 $title2 = ' title="' . __('Previous') . '"';
2199 } else {
2200 $caption1 = __('Begin') . ' &lt;&lt;';
2201 $caption2 = __('Previous') . ' &lt;';
2202 $title1 = '';
2203 $title2 = '';
2204 } // end if... else...
2205 $_url_params['pos'] = 0;
2206 echo '<a' . $title1 . ' href="' . $script
2207 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2208 . $caption1 . '</a>';
2209 $_url_params['pos'] = $pos - $max_count;
2210 echo '<a' . $title2 . ' href="' . $script
2211 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2212 . $caption2 . '</a>';
2215 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2216 echo PMA_generate_common_hidden_inputs($_url_params);
2217 echo PMA_pageselector(
2218 $max_count,
2219 floor(($pos + 1) / $max_count) + 1,
2220 ceil($count / $max_count));
2221 echo '</form>';
2223 if ($pos + $max_count < $count) {
2224 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2225 $caption3 = ' &gt; ';
2226 $caption4 = '&gt;&gt;';
2227 $title3 = ' title="' . __('Next') . '"';
2228 $title4 = ' title="' . __('End') . '"';
2229 } else {
2230 $caption3 = '&gt; ' . __('Next');
2231 $caption4 = '&gt;&gt; ' . __('End');
2232 $title3 = '';
2233 $title4 = '';
2234 } // end if... else...
2235 $_url_params['pos'] = $pos + $max_count;
2236 echo '<a' . $title3 . ' href="' . $script
2237 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2238 . $caption3 . '</a>';
2239 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2240 if ($_url_params['pos'] == $count) {
2241 $_url_params['pos'] = $count - $max_count;
2243 echo '<a' . $title4 . ' href="' . $script
2244 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2245 . $caption4 . '</a>';
2247 echo "\n";
2248 if ('frame_navigation' == $frame) {
2249 echo '</div>' . "\n";
2255 * replaces %u in given path with current user name
2257 * example:
2258 * <code>
2259 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2261 * </code>
2262 * @param string $dir with wildcard for user
2263 * @return string per user directory
2265 function PMA_userDir($dir)
2267 // add trailing slash
2268 if (substr($dir, -1) != '/') {
2269 $dir .= '/';
2272 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2276 * returns html code for db link to default db page
2278 * @param string $database
2279 * @return string html link to default db page
2281 function PMA_getDbLink($database = null)
2283 if (! strlen($database)) {
2284 if (! strlen($GLOBALS['db'])) {
2285 return '';
2287 $database = $GLOBALS['db'];
2288 } else {
2289 $database = PMA_unescape_mysql_wildcards($database);
2292 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2293 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2294 .htmlspecialchars($database) . '</a>';
2298 * Displays a lightbulb hint explaining a known external bug
2299 * that affects a functionality
2301 * @param string $functionality localized message explaining the func.
2302 * @param string $component 'mysql' (eventually, 'php')
2303 * @param string $minimum_version of this component
2304 * @param string $bugref bug reference for this component
2306 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2308 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2309 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2314 * Generates and echoes an HTML checkbox
2316 * @param string $html_field_name the checkbox HTML field
2317 * @param string $label
2318 * @param boolean $checked is it initially checked?
2319 * @param boolean $onclick should it submit the form on click?
2321 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2323 echo '<input type="checkbox" name="' . $html_field_name . '" id="' . $html_field_name . '"' . ($checked ? ' checked="checked"' : '') . ($onclick ? ' onclick="this.form.submit();"' : '') . ' /><label for="' . $html_field_name . '">' . $label . '</label>';
2327 * Generates and echoes a set of radio HTML fields
2329 * @param string $html_field_name the radio HTML field
2330 * @param array $choices the choices values and labels
2331 * @param string $checked_choice the choice to check by default
2332 * @param boolean $line_break whether to add an HTML line break after a choice
2333 * @param boolean $escape_label whether to use htmlspecialchars() on label
2334 * @param string $class enclose each choice with a div of this class
2336 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2337 foreach ($choices as $choice_value => $choice_label) {
2338 if (! empty($class)) {
2339 echo '<div class="' . $class . '">';
2341 $html_field_id = $html_field_name . '_' . $choice_value;
2342 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2343 if ($choice_value == $checked_choice) {
2344 echo ' checked="checked"';
2346 echo ' />' . "\n";
2347 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2348 if ($line_break) {
2349 echo '<br />';
2351 if (! empty($class)) {
2352 echo '</div>';
2354 echo "\n";
2359 * Generates and returns an HTML dropdown
2361 * @param string $select_name
2362 * @param array $choices the choices values
2363 * @param string $active_choice the choice to select by default
2364 * @param string $id the id of the select element; can be different in case
2365 * the dropdown is present more than once on the page
2366 * @todo support titles
2368 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2370 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2371 foreach ($choices as $one_choice_value => $one_choice_label) {
2372 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2373 if ($one_choice_value == $active_choice) {
2374 $result .= ' selected="selected"';
2376 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2378 $result .= '</select>';
2379 return $result;
2383 * Generates a slider effect (jQjuery)
2384 * Takes care of generating the initial <div> and the link
2385 * controlling the slider; you have to generate the </div> yourself
2386 * after the sliding section.
2388 * @param string $id the id of the <div> on which to apply the effect
2389 * @param string $message the message to show as a link
2391 function PMA_generate_slider_effect($id, $message)
2393 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2394 echo '<div id="' . $id . '">';
2395 return;
2398 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2399 * opening the <div> with PHP itself instead of JavaScript.
2401 * @todo find a better solution that uses $.append(), the recommended method
2402 * maybe by using an additional param, the id of the div to append to
2405 <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); ?>">
2406 <?php
2410 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2412 * @param string $action The URL for the request to be executed
2413 * @param string $select_name The name for the dropdown box
2414 * @param array $options An array of options (see rte_footer.lib.php)
2415 * @param string $callback A JS snippet to execute when the request is
2416 * successfully processed
2418 * @return string HTML code for the toggle button
2420 function PMA_toggleButton($action, $select_name, $options, $callback)
2422 // Do the logic first
2423 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2424 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2425 if ($options[1]['selected'] == true) {
2426 $state = 'on';
2427 } else if ($options[0]['selected'] == true) {
2428 $state = 'off';
2429 } else {
2430 $state = 'on';
2432 $selected1 = '';
2433 $selected0 = '';
2434 if ($options[1]['selected'] == true) {
2435 $selected1 = " selected='selected'";
2436 } else if ($options[0]['selected'] == true) {
2437 $selected0 = " selected='selected'";
2439 // Generate output
2440 $retval = "<!-- TOGGLE START -->\n";
2441 if ($GLOBALS['cfg']['AjaxEnable']) {
2442 $retval .= "<noscript>\n";
2444 $retval .= "<div class='wrapper'>\n";
2445 $retval .= " <form action='$action' method='post'>\n";
2446 $retval .= " <select name='$select_name'>\n";
2447 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2448 $retval .= " {$options[1]['label']}\n";
2449 $retval .= " </option>\n";
2450 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2451 $retval .= " {$options[0]['label']}\n";
2452 $retval .= " </option>\n";
2453 $retval .= " </select>\n";
2454 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2455 $retval .= " </form>\n";
2456 $retval .= "</div>\n";
2457 if ($GLOBALS['cfg']['AjaxEnable']) {
2458 $retval .= "</noscript>\n";
2459 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2460 $retval .= " <div class='toggleButton'>\n";
2461 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2462 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2463 $retval .= " alt='' />\n";
2464 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2465 $retval .= " <tbody>\n";
2466 $retval .= " <td class='toggleOn'>\n";
2467 $retval .= " <span class='hide'>$link_on</span>\n";
2468 $retval .= " <div>";
2469 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2470 $retval .= " </td>\n";
2471 $retval .= " <td><div>&nbsp;</div></td>\n";
2472 $retval .= " <td class='toggleOff'>\n";
2473 $retval .= " <span class='hide'>$link_off</span>\n";
2474 $retval .= " <div>";
2475 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2476 $retval .= " </div>\n";
2477 $retval .= " </tbody>\n";
2478 $retval .= " </tr></table>\n";
2479 $retval .= " <span class='hide callback'>$callback</span>\n";
2480 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2481 $retval .= " </div>\n";
2482 $retval .= " </div>\n";
2483 $retval .= "</div>\n";
2485 $retval .= "<!-- TOGGLE END -->";
2487 return $retval;
2488 } // end PMA_toggleButton()
2491 * Clears cache content which needs to be refreshed on user change.
2493 function PMA_clearUserCache() {
2494 PMA_cacheUnset('is_superuser', true);
2498 * Verifies if something is cached in the session
2500 * @param string $var
2501 * @param scalar $server
2502 * @return boolean
2504 function PMA_cacheExists($var, $server = 0)
2506 if (true === $server) {
2507 $server = $GLOBALS['server'];
2509 return isset($_SESSION['cache']['server_' . $server][$var]);
2513 * Gets cached information from the session
2515 * @param string $var
2516 * @param scalar $server
2517 * @return mixed
2519 function PMA_cacheGet($var, $server = 0)
2521 if (true === $server) {
2522 $server = $GLOBALS['server'];
2524 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2525 return $_SESSION['cache']['server_' . $server][$var];
2526 } else {
2527 return null;
2532 * Caches information in the session
2534 * @param string $var
2535 * @param mixed $val
2536 * @param integer $server
2537 * @return mixed
2539 function PMA_cacheSet($var, $val = null, $server = 0)
2541 if (true === $server) {
2542 $server = $GLOBALS['server'];
2544 $_SESSION['cache']['server_' . $server][$var] = $val;
2548 * Removes cached information from the session
2550 * @param string $var
2551 * @param scalar $server
2553 function PMA_cacheUnset($var, $server = 0)
2555 if (true === $server) {
2556 $server = $GLOBALS['server'];
2558 unset($_SESSION['cache']['server_' . $server][$var]);
2562 * Converts a bit value to printable format;
2563 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2564 * function because in PHP, decbin() supports only 32 bits
2566 * @param numeric $value coming from a BIT field
2567 * @param integer $length
2568 * @return string the printable value
2570 function PMA_printable_bit_value($value, $length) {
2571 $printable = '';
2572 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2573 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2575 $printable = substr($printable, -$length);
2576 return $printable;
2580 * Verifies whether the value contains a non-printable character
2582 * @param string $value
2583 * @return boolean
2585 function PMA_contains_nonprintable_ascii($value) {
2586 return preg_match('@[^[:print:]]@', $value);
2590 * Converts a BIT type default value
2591 * for example, b'010' becomes 010
2593 * @param string $bit_default_value
2594 * @return string the converted value
2596 function PMA_convert_bit_default_value($bit_default_value) {
2597 return strtr($bit_default_value, array("b" => "", "'" => ""));
2601 * Extracts the various parts from a field type spec
2603 * @param string $fieldspec
2604 * @return array associative array containing type, spec_in_brackets
2605 * and possibly enum_set_values (another array)
2607 function PMA_extractFieldSpec($fieldspec) {
2608 $first_bracket_pos = strpos($fieldspec, '(');
2609 if ($first_bracket_pos) {
2610 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2611 // convert to lowercase just to be sure
2612 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2613 } else {
2614 $type = $fieldspec;
2615 $spec_in_brackets = '';
2618 if ('enum' == $type || 'set' == $type) {
2619 // Define our working vars
2620 $enum_set_values = array();
2621 $working = "";
2622 $in_string = false;
2623 $index = 0;
2625 // While there is another character to process
2626 while (isset($fieldspec[$index])) {
2627 // Grab the char to look at
2628 $char = $fieldspec[$index];
2630 // If it is a single quote, needs to be handled specially
2631 if ($char == "'") {
2632 // If we are not currently in a string, begin one
2633 if (! $in_string) {
2634 $in_string = true;
2635 $working = "";
2636 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2637 } else {
2638 // Check out the next character (if possible)
2639 $has_next = isset($fieldspec[$index + 1]);
2640 $next = $has_next ? $fieldspec[$index + 1] : null;
2642 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2643 if (! $has_next || $next != "'") {
2644 $enum_set_values[] = $working;
2645 $in_string = false;
2647 // Otherwise, this is a 'double quote', and can be added to the working string
2648 } elseif ($next == "'") {
2649 $working .= "'";
2650 // Skip the next char; we already know what it is
2651 $index++;
2654 // escaping of a quote?
2655 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2656 $working .= "'";
2657 $index++;
2658 // Otherwise, add it to our working string like normal
2659 } else {
2660 $working .= $char;
2662 // Increment character index
2663 $index++;
2664 } // end while
2665 } else {
2666 $enum_set_values = array();
2669 return array(
2670 'type' => $type,
2671 'spec_in_brackets' => $spec_in_brackets,
2672 'enum_set_values' => $enum_set_values
2677 * Verifies if this table's engine supports foreign keys
2679 * @param string $engine
2680 * @return boolean
2682 function PMA_foreignkey_supported($engine) {
2683 $engine = strtoupper($engine);
2684 if ('INNODB' == $engine || 'PBXT' == $engine) {
2685 return true;
2686 } else {
2687 return false;
2692 * Replaces some characters by a displayable equivalent
2694 * @param string $content
2695 * @return string the content with characters replaced
2697 function PMA_replace_binary_contents($content) {
2698 $result = str_replace("\x00", '\0', $content);
2699 $result = str_replace("\x08", '\b', $result);
2700 $result = str_replace("\x0a", '\n', $result);
2701 $result = str_replace("\x0d", '\r', $result);
2702 $result = str_replace("\x1a", '\Z', $result);
2703 return $result;
2707 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2709 * @param string $string
2710 * @return string with the chars replaced
2713 function PMA_duplicateFirstNewline($string) {
2714 $first_occurence = strpos($string, "\r\n");
2715 if ($first_occurence === 0){
2716 $string = "\n".$string;
2718 return $string;
2722 * Get the action word corresponding to a script name
2723 * in order to display it as a title in navigation panel
2725 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2726 * or $cfg['DefaultTabDatabase']
2727 * @return array
2729 function PMA_getTitleForTarget($target) {
2730 $mapping = array(
2731 // Values for $cfg['DefaultTabTable']
2732 'tbl_structure.php' => __('Structure'),
2733 'tbl_sql.php' => __('SQL'),
2734 'tbl_select.php' =>__('Search'),
2735 'tbl_change.php' =>__('Insert'),
2736 'sql.php' => __('Browse'),
2738 // Values for $cfg['DefaultTabDatabase']
2739 'db_structure.php' => __('Structure'),
2740 'db_sql.php' => __('SQL'),
2741 'db_search.php' => __('Search'),
2742 'db_operations.php' => __('Operations'),
2744 return $mapping[$target];
2748 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2750 * @param string $string Text where to do expansion.
2751 * @param function $escape Function to call for escaping variable values.
2752 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2753 * @return string
2755 function PMA_expandUserString($string, $escape = null, $updates = array()) {
2756 /* Content */
2757 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2758 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2759 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2760 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2761 $vars['database'] = $GLOBALS['db'];
2762 $vars['table'] = $GLOBALS['table'];
2763 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2765 /* Update forced variables */
2766 foreach($updates as $key => $val) {
2767 $vars[$key] = $val;
2770 /* Replacement mapping */
2772 * The __VAR__ ones are for backward compatibility, because user
2773 * might still have it in cookies.
2775 $replace = array(
2776 '@HTTP_HOST@' => $vars['http_host'],
2777 '@SERVER@' => $vars['server_name'],
2778 '__SERVER__' => $vars['server_name'],
2779 '@VERBOSE@' => $vars['server_verbose'],
2780 '@VSERVER@' => $vars['server_verbose_or_name'],
2781 '@DATABASE@' => $vars['database'],
2782 '__DB__' => $vars['database'],
2783 '@TABLE@' => $vars['table'],
2784 '__TABLE__' => $vars['table'],
2785 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2788 /* Optional escaping */
2789 if (!is_null($escape)) {
2790 foreach($replace as $key => $val) {
2791 $replace[$key] = $escape($val);
2795 /* Fetch fields list if required */
2796 if (strpos($string, '@FIELDS@') !== false) {
2797 $fields_list = PMA_DBI_fetch_result(
2798 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2799 . '.' . PMA_backquote($GLOBALS['table']));
2801 $field_names = array();
2802 foreach ($fields_list as $field) {
2803 if (!is_null($escape)) {
2804 $field_names[] = $escape($field['Field']);
2805 } else {
2806 $field_names[] = $field['Field'];
2810 $replace['@FIELDS@'] = implode(',', $field_names);
2813 /* Do the replacement */
2814 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2818 * function that generates a json output for an ajax request and ends script
2819 * execution
2821 * @param bool $message message string containing the html of the message
2822 * @param bool $success success whether the ajax request was successfull
2823 * @param array $extra_data extra_data optional - any other data as part of the json request
2826 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2828 $response = array();
2829 if( $success == true ) {
2830 $response['success'] = true;
2831 if ($message instanceof PMA_Message) {
2832 $response['message'] = $message->getDisplay();
2834 else {
2835 $response['message'] = $message;
2838 else {
2839 $response['success'] = false;
2840 if($message instanceof PMA_Message) {
2841 $response['error'] = $message->getDisplay();
2843 else {
2844 $response['error'] = $message;
2848 // If extra_data has been provided, append it to the response array
2849 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2850 $response = array_merge($response, $extra_data);
2853 // Set the Content-Type header to JSON so that jQuery parses the
2854 // response correctly.
2856 // At this point, other headers might have been sent;
2857 // even if $GLOBALS['is_header_sent'] is true,
2858 // we have to send these additional headers.
2859 header('Cache-Control: no-cache');
2860 header("Content-Type: application/json");
2862 echo json_encode($response);
2863 exit;
2867 * Display the form used to browse anywhere on the local server for the file to import
2869 * @param $max_upload_size
2871 function PMA_browseUploadFile($max_upload_size) {
2872 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2873 echo '<div id="upload_form_status" style="display: none;"></div>';
2874 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2875 echo '<input type="file" name="import_file" id="input_import_file" />';
2876 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2877 // some browsers should respect this :)
2878 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2882 * Display the form used to select a file to import from the server upload directory
2884 * @param $import_list
2885 * @param $uploaddir
2887 function PMA_selectUploadFile($import_list, $uploaddir) {
2888 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2889 $extensions = '';
2890 foreach ($import_list as $key => $val) {
2891 if (!empty($extensions)) {
2892 $extensions .= '|';
2894 $extensions .= $val['extension'];
2896 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2898 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2899 if ($files === false) {
2900 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2901 } elseif (!empty($files)) {
2902 echo "\n";
2903 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2904 echo ' <option value="">&nbsp;</option>' . "\n";
2905 echo $files;
2906 echo ' </select>' . "\n";
2907 } elseif (empty ($files)) {
2908 echo '<i>' . __('There are no files to upload') . '</i>';
2913 * Build titles and icons for action links
2915 * @return array the action titles
2917 function PMA_buildActionTitles() {
2918 $titles = array();
2920 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2921 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2922 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2923 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2924 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2925 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2926 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2927 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2928 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2929 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2930 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2931 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
2932 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'), true);
2933 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'), true);
2934 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'), true);
2935 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'), true);
2936 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'), true);
2937 return $titles;
2941 * This function processes the datatypes supported by the DB, as specified in
2942 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
2943 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
2945 * @param bool $html Whether to generate an html snippet or an array
2946 * @param string $selected The value to mark as selected in HTML mode
2948 * @return mixed An HTML snippet or an array of datatypes.
2951 function PMA_getSupportedDatatypes($html = false, $selected = '')
2953 global $cfg;
2955 if ($html) {
2956 // NOTE: the SELECT tag in not included in this snippet.
2957 $retval = '';
2958 foreach ($cfg['ColumnTypes'] as $key => $value) {
2959 if (is_array($value)) {
2960 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
2961 foreach ($value as $subvalue) {
2962 if ($subvalue == $selected) {
2963 $retval .= "<option selected='selected'>";
2964 $retval .= $subvalue;
2965 $retval .= "</option>";
2966 } else if ($subvalue === '-') {
2967 $retval .= "<option disabled='disabled'>";
2968 $retval .= $subvalue;
2969 $retval .= "</option>";
2970 } else {
2971 $retval .= "<option>$subvalue</option>";
2974 $retval .= '</optgroup>';
2975 } else {
2976 if ($selected == $value) {
2977 $retval .= "<option selected='selected'>$value</option>";
2978 } else {
2979 $retval .= "<option>$value</option>";
2983 } else {
2984 $retval = array();
2985 foreach ($cfg['ColumnTypes'] as $value) {
2986 if (is_array($value)) {
2987 foreach ($value as $subvalue) {
2988 if ($subvalue !== '-') {
2989 $retval[] = $subvalue;
2992 } else {
2993 if ($value !== '-') {
2994 $retval[] = $value;
3000 return $retval;
3001 } // end PMA_getSupportedDatatypes()
3004 * Returns a list of datatypes that are not (yet) handled by PMA.
3005 * Used by: tbl_change.php and libraries/db_routines.inc.php
3007 * @return array list of datatypes
3010 function PMA_unsupportedDatatypes() {
3011 // These GIS data types are not yet supported.
3012 $no_support_types = array('geometry',
3013 'point',
3014 'linestring',
3015 'polygon',
3016 'multipoint',
3017 'multilinestring',
3018 'multipolygon',
3019 'geometrycollection'
3022 return $no_support_types;
3026 * Creates a dropdown box with MySQL functions for a particular column.
3028 * @param array $field Data about the column for which
3029 * to generate the dropdown
3030 * @param bool $insert_mode Whether the operation is 'insert'
3032 * @global array $cfg PMA configuration
3033 * @global array $analyzed_sql Analyzed SQL query
3034 * @global mixed $data (null/string) FIXME: what is this for?
3036 * @return string An HTML snippet of a dropdown list with function
3037 * names appropriate for the requested column.
3039 function PMA_getFunctionsForField($field, $insert_mode)
3041 global $cfg, $analyzed_sql, $data;
3043 $selected = '';
3044 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3045 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3046 // which will then reveal the available dropdown options
3047 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3048 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3049 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3050 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3051 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3052 } else {
3053 $dropdown = array();
3054 $default_function = '';
3056 $dropdown_built = array();
3057 $op_spacing_needed = false;
3058 // what function defined as default?
3059 // for the first timestamp we don't set the default function
3060 // if there is a default value for the timestamp
3061 // (not including CURRENT_TIMESTAMP)
3062 // and the column does not have the
3063 // ON UPDATE DEFAULT TIMESTAMP attribute.
3064 if ($field['True_Type'] == 'timestamp'
3065 && empty($field['Default'])
3066 && empty($data)
3067 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3068 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3070 // For primary keys of type char(36) or varchar(36) UUID if the default function
3071 // Only applies to insert mode, as it would silently trash data on updates.
3072 if ($insert_mode
3073 && $field['Key'] == 'PRI'
3074 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3076 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3078 // this is set only when appropriate and is always true
3079 if (isset($field['display_binary_as_hex'])) {
3080 $default_function = 'UNHEX';
3083 // Create the output
3084 $retval = ' <option></option>' . "\n";
3085 // loop on the dropdown array and print all available options for that field.
3086 foreach ($dropdown as $each_dropdown){
3087 $retval .= ' ';
3088 $retval .= '<option';
3089 if ($default_function === $each_dropdown) {
3090 $retval .= ' selected="selected"';
3092 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3093 $dropdown_built[$each_dropdown] = 'true';
3094 $op_spacing_needed = true;
3096 // For compatibility's sake, do not let out all other functions. Instead
3097 // print a separator (blank) and then show ALL functions which weren't shown
3098 // yet.
3099 $cnt_functions = count($cfg['Functions']);
3100 for ($j = 0; $j < $cnt_functions; $j++) {
3101 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3102 // Is current function defined as default?
3103 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3104 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3105 ? ' selected="selected"'
3106 : '';
3107 if ($op_spacing_needed == true) {
3108 $retval .= ' ';
3109 $retval .= '<option value="">--------</option>' . "\n";
3110 $op_spacing_needed = false;
3113 $retval .= ' ';
3114 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3116 } // end for
3118 return $retval;
3119 } // end PMA_getFunctionsForField()
3122 * Checks if the current user has a specific privilege and returns true if the
3123 * user indeed has that privilege or false if (s)he doesn't. This function must
3124 * only be used for features that are available since MySQL 5, because it
3125 * relies on the INFORMATION_SCHEMA database to be present.
3127 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3128 * // Checks if the currently logged in user has the global
3129 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3130 * // user has this privilege on database 'mydb'.
3133 * @param string $priv The privilege to check
3134 * @param mixed $db null, to only check global privileges
3135 * string, db name where to also check for privileges
3136 * @param mixed $tbl null, to only check global privileges
3137 * string, db name where to also check for privileges
3139 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3141 // Get the username for the current user in the format
3142 // required to use in the information schema database.
3143 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3144 if ($user === false) {
3145 return false;
3147 $user = explode('@', $user);
3148 $username = "''";
3149 $username .= str_replace("'", "''", $user[0]);
3150 $username .= "''@''";
3151 $username .= str_replace("'", "''", $user[1]);
3152 $username .= "''";
3153 // Prepage the query
3154 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3155 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3156 // Check global privileges first.
3157 if (PMA_DBI_fetch_value(sprintf($query,
3158 'USER_PRIVILEGES',
3159 $username,
3160 $priv))) {
3161 return true;
3163 // If a database name was provided and user does not have the
3164 // required global privilege, try database-wise permissions.
3165 if ($db !== null) {
3166 $query .= " AND TABLE_SCHEMA='%s'";
3167 if (PMA_DBI_fetch_value(sprintf($query,
3168 'SCHEMA_PRIVILEGES',
3169 $username,
3170 $priv,
3171 PMA_sqlAddSlashes($db)))) {
3172 return true;
3174 } else {
3175 // There was no database name provided and the user
3176 // does not have the correct global privilege.
3177 return false;
3179 // If a table name was also provided and we still didn't
3180 // find any valid privileges, try table-wise privileges.
3181 if ($tbl !== null) {
3182 $query .= " AND TABLE_NAME='%s'";
3183 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3184 'TABLE_PRIVILEGES',
3185 $username,
3186 $priv,
3187 PMA_sqlAddSlashes($db),
3188 PMA_sqlAddSlashes($tbl)))) {
3189 return true;
3192 // If we reached this point, the user does not
3193 // have even valid table-wise privileges.
3194 return false;
3198 * Returns server type for current connection
3200 * Known types are: Drizzle, MariaDB and MySQL (default)
3202 * @return string
3204 function PMA_getServerType()
3206 $server_type = 'MySQL';
3207 if (PMA_DRIZZLE) {
3208 $server_type = 'Drizzle';
3209 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3210 $server_type = 'MariaDB';
3212 return $server_type;