Quick fixes for XML export
[phpmyadmin.git] / libraries / common.lib.php
blob18ff4f4f15e30a684577a12047eb7e4dc2cd4419
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 } else {
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 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
812 // Win case
813 if (PMA_USR_OS == 'Win') {
814 $the_crlf = "\r\n";
816 // Others
817 else {
818 $the_crlf = "\n";
821 return $the_crlf;
822 } // end of the 'PMA_whichCrlf()' function
825 * Reloads navigation if needed.
827 * @param bool $jsonly prints out pure JavaScript
829 * @access public
831 function PMA_reloadNavigation($jsonly=false)
833 // Reloads the navigation frame via JavaScript if required
834 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
835 // one of the reasons for a reload is when a table is dropped
836 // in this case, get rid of the table limit offset, otherwise
837 // we have a problem when dropping a table on the last page
838 // and the offset becomes greater than the total number of tables
839 unset($_SESSION['tmp_user_values']['table_limit_offset']);
840 echo "\n";
841 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
842 if (!$jsonly)
843 echo '<script type="text/javascript">' . PHP_EOL;
845 //<![CDATA[
846 if (typeof(window.parent) != 'undefined'
847 && typeof(window.parent.frame_navigation) != 'undefined'
848 && window.parent.goTo) {
849 window.parent.goTo('<?php echo $reload_url; ?>');
851 //]]>
852 <?php
853 if (!$jsonly)
854 echo '</script>' . PHP_EOL;
856 unset($GLOBALS['reload']);
861 * displays the message and the query
862 * usually the message is the result of the query executed
864 * @param string $message the message to display
865 * @param string $sql_query the query to display
866 * @param string $type the type (level) of the message
867 * @param boolean $is_view is this a message after a VIEW operation?
868 * @return string
869 * @access public
871 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
874 * PMA_ajaxResponse uses this function to collect the string of HTML generated
875 * for showing the message. Use output buffering to collect it and return it
876 * in a string. In some special cases on sql.php, buffering has to be disabled
877 * and hence we check with $GLOBALS['buffer_message']
879 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
880 ob_start();
882 global $cfg;
884 if (null === $sql_query) {
885 if (! empty($GLOBALS['display_query'])) {
886 $sql_query = $GLOBALS['display_query'];
887 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
888 $sql_query = $GLOBALS['unparsed_sql'];
889 } elseif (! empty($GLOBALS['sql_query'])) {
890 $sql_query = $GLOBALS['sql_query'];
891 } else {
892 $sql_query = '';
896 if (isset($GLOBALS['using_bookmark_message'])) {
897 $GLOBALS['using_bookmark_message']->display();
898 unset($GLOBALS['using_bookmark_message']);
901 // Corrects the tooltip text via JS if required
902 // @todo this is REALLY the wrong place to do this - very unexpected here
903 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
904 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
905 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
906 echo "\n";
907 echo '<script type="text/javascript">' . "\n";
908 echo '//<![CDATA[' . "\n";
909 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
910 echo '//]]>' . "\n";
911 echo '</script>' . "\n";
912 } // end if ... elseif
914 // Checks if the table needs to be repaired after a TRUNCATE query.
915 // @todo what about $GLOBALS['display_query']???
916 // @todo this is REALLY the wrong place to do this - very unexpected here
917 if (strlen($GLOBALS['table'])
918 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
919 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
920 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
923 unset($tbl_status);
925 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
926 // check for it's presence before using it
927 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
929 if ($message instanceof PMA_Message) {
930 if (isset($GLOBALS['special_message'])) {
931 $message->addMessage($GLOBALS['special_message']);
932 unset($GLOBALS['special_message']);
934 $message->display();
935 $type = $message->getLevel();
936 } else {
937 echo '<div class="' . $type . '">';
938 echo PMA_sanitize($message);
939 if (isset($GLOBALS['special_message'])) {
940 echo PMA_sanitize($GLOBALS['special_message']);
941 unset($GLOBALS['special_message']);
943 echo '</div>';
946 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
947 // Html format the query to be displayed
948 // If we want to show some sql code it is easiest to create it here
949 /* SQL-Parser-Analyzer */
951 if (! empty($GLOBALS['show_as_php'])) {
952 $new_line = '\\n"<br />' . "\n"
953 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
954 $query_base = htmlspecialchars(addslashes($sql_query));
955 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
956 } else {
957 $query_base = $sql_query;
960 $query_too_big = false;
962 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
963 // when the query is large (for example an INSERT of binary
964 // data), the parser chokes; so avoid parsing the query
965 $query_too_big = true;
966 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
967 } elseif (! empty($GLOBALS['parsed_sql'])
968 && $query_base == $GLOBALS['parsed_sql']['raw']) {
969 // (here, use "! empty" because when deleting a bookmark,
970 // $GLOBALS['parsed_sql'] is set but empty
971 $parsed_sql = $GLOBALS['parsed_sql'];
972 } else {
973 // Parse SQL if needed
974 $parsed_sql = PMA_SQP_parse($query_base);
975 if (PMA_SQP_isError()) {
976 unset($parsed_sql);
980 // Analyze it
981 if (isset($parsed_sql)) {
982 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
984 // Same as below (append LIMIT), append the remembered ORDER BY
985 if ($GLOBALS['cfg']['RememberSorting']
986 && isset($analyzed_display_query[0]['queryflags']['select_from'])
987 && isset($GLOBALS['sql_order_to_append'])) {
988 $query_base = $analyzed_display_query[0]['section_before_limit']
989 . "\n" . $GLOBALS['sql_order_to_append']
990 . $analyzed_display_query[0]['section_after_limit'];
992 // Need to reparse query
993 $parsed_sql = PMA_SQP_parse($query_base);
994 // update the $analyzed_display_query
995 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
996 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
999 // Here we append the LIMIT added for navigation, to
1000 // enable its display. Adding it higher in the code
1001 // to $sql_query would create a problem when
1002 // using the Refresh or Edit links.
1004 // Only append it on SELECTs.
1007 * @todo what would be the best to do when someone hits Refresh:
1008 * use the current LIMITs ?
1011 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1012 && isset($GLOBALS['sql_limit_to_append'])) {
1013 $query_base = $analyzed_display_query[0]['section_before_limit']
1014 . "\n" . $GLOBALS['sql_limit_to_append']
1015 . $analyzed_display_query[0]['section_after_limit'];
1016 // Need to reparse query
1017 $parsed_sql = PMA_SQP_parse($query_base);
1021 if (! empty($GLOBALS['show_as_php'])) {
1022 $query_base = '$sql = "' . $query_base;
1023 } elseif (! empty($GLOBALS['validatequery'])) {
1024 try {
1025 $query_base = PMA_validateSQL($query_base);
1026 } catch (Exception $e) {
1027 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1029 } elseif (isset($parsed_sql)) {
1030 $query_base = PMA_formatSql($parsed_sql, $query_base);
1033 // Prepares links that may be displayed to edit/explain the query
1034 // (don't go to default pages, we must go to the page
1035 // where the query box is available)
1037 // Basic url query part
1038 $url_params = array();
1039 if (! isset($GLOBALS['db'])) {
1040 $GLOBALS['db'] = '';
1042 if (strlen($GLOBALS['db'])) {
1043 $url_params['db'] = $GLOBALS['db'];
1044 if (strlen($GLOBALS['table'])) {
1045 $url_params['table'] = $GLOBALS['table'];
1046 $edit_link = 'tbl_sql.php';
1047 } else {
1048 $edit_link = 'db_sql.php';
1050 } else {
1051 $edit_link = 'server_sql.php';
1054 // Want to have the query explained
1055 // but only explain a SELECT (that has not been explained)
1056 /* SQL-Parser-Analyzer */
1057 $explain_link = '';
1058 $is_select = false;
1059 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1060 $explain_params = $url_params;
1061 // Detect if we are validating as well
1062 // To preserve the validate uRL data
1063 if (! empty($GLOBALS['validatequery'])) {
1064 $explain_params['validatequery'] = 1;
1066 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1067 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1068 $_message = __('Explain SQL');
1069 $is_select = true;
1070 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1071 $explain_params['sql_query'] = substr($sql_query, 8);
1072 $_message = __('Skip Explain SQL');
1074 if (isset($explain_params['sql_query'])) {
1075 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1076 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1078 } //show explain
1080 $url_params['sql_query'] = $sql_query;
1081 $url_params['show_query'] = 1;
1083 // even if the query is big and was truncated, offer the chance
1084 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1085 if (! empty($cfg['SQLQuery']['Edit'])) {
1086 if ($cfg['EditInWindow'] == true) {
1087 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1088 } else {
1089 $onclick = '';
1092 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1093 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1094 } else {
1095 $edit_link = '';
1098 $url_qpart = PMA_generate_common_url($url_params);
1100 // Also we would like to get the SQL formed in some nice
1101 // php-code
1102 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1103 $php_params = $url_params;
1105 if (! empty($GLOBALS['show_as_php'])) {
1106 $_message = __('Without PHP Code');
1107 } else {
1108 $php_params['show_as_php'] = 1;
1109 $_message = __('Create PHP Code');
1112 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1113 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1115 if (isset($GLOBALS['show_as_php'])) {
1116 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1117 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1119 } else {
1120 $php_link = '';
1121 } //show as php
1123 // Refresh query
1124 if (! empty($cfg['SQLQuery']['Refresh'])
1125 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1126 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1127 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1128 } else {
1129 $refresh_link = '';
1130 } //show as php
1132 if (! empty($cfg['SQLValidator']['use'])
1133 && ! empty($cfg['SQLQuery']['Validate'])) {
1134 $validate_params = $url_params;
1135 if (!empty($GLOBALS['validatequery'])) {
1136 $validate_message = __('Skip Validate SQL') ;
1137 } else {
1138 $validate_params['validatequery'] = 1;
1139 $validate_message = __('Validate SQL') ;
1142 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1143 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1144 } else {
1145 $validate_link = '';
1146 } //validator
1148 if (!empty($GLOBALS['validatequery'])) {
1149 echo '<div class="sqlvalidate">';
1150 } else {
1151 echo '<code class="sql">';
1153 if ($query_too_big) {
1154 echo $shortened_query_base;
1155 } else {
1156 echo $query_base;
1159 //Clean up the end of the PHP
1160 if (! empty($GLOBALS['show_as_php'])) {
1161 echo '";';
1163 if (!empty($GLOBALS['validatequery'])) {
1164 echo '</div>';
1165 } else {
1166 echo '</code>';
1169 echo '<div class="tools">';
1170 // avoid displaying a Profiling checkbox that could
1171 // be checked, which would reexecute an INSERT, for example
1172 if (! empty($refresh_link)) {
1173 PMA_profilingCheckbox($sql_query);
1175 // if needed, generate an invisible form that contains controls for the
1176 // Inline link; this way, the behavior of the Inline link does not
1177 // depend on the profiling support or on the refresh link
1178 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1179 echo '<form action="sql.php" method="post">';
1180 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1181 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1182 echo '</form>';
1185 // in the tools div, only display the Inline link when not in ajax
1186 // mode because 1) it currently does not work and 2) we would
1187 // have two similar mechanisms on the page for the same goal
1188 if ($is_select || $GLOBALS['is_ajax_request'] === false) {
1189 // see in js/functions.js the jQuery code attached to id inline_edit
1190 // document.write conflicts with jQuery, hence used $().append()
1191 echo "<script type=\"text/javascript\">\n" .
1192 "//<![CDATA[\n" .
1193 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1194 PMA_escapeJsString(__('Inline edit of this query')) .
1195 "\" class=\"inline_edit_sql\">" .
1196 PMA_escapeJsString(__('Inline')) .
1197 "</a>]');\n" .
1198 "//]]>\n" .
1199 "</script>";
1201 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1202 echo '</div>';
1204 echo '</div>';
1205 if ($GLOBALS['is_ajax_request'] === false) {
1206 echo '<br class="clearfloat" />';
1209 // If we are in an Ajax request, we have most probably been called in
1210 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1211 // to PMA_ajaxResponse(), which will encode it for JSON.
1212 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1213 $buffer_contents = ob_get_contents();
1214 ob_end_clean();
1215 return $buffer_contents;
1217 return null;
1218 } // end of the 'PMA_showMessage()' function
1221 * Verifies if current MySQL server supports profiling
1223 * @access public
1224 * @return boolean whether profiling is supported
1226 function PMA_profilingSupported()
1228 if (! PMA_cacheExists('profiling_supported', true)) {
1229 // 5.0.37 has profiling but for example, 5.1.20 does not
1230 // (avoid a trip to the server for MySQL before 5.0.37)
1231 // and do not set a constant as we might be switching servers
1232 if (defined('PMA_MYSQL_INT_VERSION')
1233 && PMA_MYSQL_INT_VERSION >= 50037
1234 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1235 PMA_cacheSet('profiling_supported', true, true);
1236 } else {
1237 PMA_cacheSet('profiling_supported', false, true);
1241 return PMA_cacheGet('profiling_supported', true);
1245 * Displays a form with the Profiling checkbox
1247 * @param string $sql_query
1248 * @access public
1250 function PMA_profilingCheckbox($sql_query)
1252 if (PMA_profilingSupported()) {
1253 echo '<form action="sql.php" method="post">' . "\n";
1254 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1255 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1256 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1257 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1258 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1259 echo '</form>' . "\n";
1264 * Formats $value to byte view
1266 * @param double $value the value to format
1267 * @param int $limes the sensitiveness
1268 * @param int $comma the number of decimals to retain
1270 * @return array the formatted value and its unit
1272 * @access public
1274 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1276 if ($value === null) {
1277 return null;
1280 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1281 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1283 $dh = PMA_pow(10, $comma);
1284 $li = PMA_pow(10, $limes);
1285 $unit = $byteUnits[0];
1287 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1288 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1289 // use 1024.0 to avoid integer overflow on 64-bit machines
1290 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1291 $unit = $byteUnits[$d];
1292 break 1;
1293 } // end if
1294 } // end for
1296 if ($unit != $byteUnits[0]) {
1297 // if the unit is not bytes (as represented in current language)
1298 // reformat with max length of 5
1299 // 4th parameter=true means do not reformat if value < 1
1300 $return_value = PMA_formatNumber($value, 5, $comma, true);
1301 } else {
1302 // do not reformat, just handle the locale
1303 $return_value = PMA_formatNumber($value, 0);
1306 return array(trim($return_value), $unit);
1307 } // end of the 'PMA_formatByteDown' function
1310 * Changes thousands and decimal separators to locale specific values.
1312 * @param $value
1313 * @return string
1315 function PMA_localizeNumber($value)
1317 return str_replace(
1318 array(',', '.'),
1319 array(
1320 /* l10n: Thousands separator */
1321 __(','),
1322 /* l10n: Decimal separator */
1323 __('.'),
1325 $value);
1329 * Formats $value to the given length and appends SI prefixes
1330 * with a $length of 0 no truncation occurs, number is only formated
1331 * to the current locale
1333 * examples:
1334 * <code>
1335 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1336 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1337 * echo PMA_formatNumber(-0.003, 6); // -3 m
1338 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1339 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1340 * echo PMA_formatNumber(0, 6); // 0
1342 * </code>
1343 * @param double $value the value to format
1344 * @param integer $digits_left number of digits left of the comma
1345 * @param integer $digits_right number of digits right of the comma
1346 * @param boolean $only_down do not reformat numbers below 1
1347 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1349 * @return string the formatted value and its unit
1351 * @access public
1353 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1355 if($value==0) return '0';
1357 $originalValue = $value;
1358 //number_format is not multibyte safe, str_replace is safe
1359 if ($digits_left === 0) {
1360 $value = number_format($value, $digits_right);
1361 if($originalValue!=0 && floatval($value) == 0) $value = ' <'.(1/PMA_pow(10,$digits_right));
1363 return PMA_localizeNumber($value);
1366 // this units needs no translation, ISO
1367 $units = array(
1368 -8 => 'y',
1369 -7 => 'z',
1370 -6 => 'a',
1371 -5 => 'f',
1372 -4 => 'p',
1373 -3 => 'n',
1374 -2 => '&micro;',
1375 -1 => 'm',
1376 0 => ' ',
1377 1 => 'k',
1378 2 => 'M',
1379 3 => 'G',
1380 4 => 'T',
1381 5 => 'P',
1382 6 => 'E',
1383 7 => 'Z',
1384 8 => 'Y'
1387 // check for negative value to retain sign
1388 if ($value < 0) {
1389 $sign = '-';
1390 $value = abs($value);
1391 } else {
1392 $sign = '';
1395 $dh = PMA_pow(10, $digits_right);
1397 // This gives us the right SI prefix already, but $digits_left parameter not incorporated
1398 $d = floor(log10($value) / 3);
1399 // Lowering the SI prefix by 1 gives us an additional 3 zeros
1400 // So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits) to use, then lower the SI prefix
1401 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1402 if($digits_left > $cur_digits) {
1403 $d-= floor(($digits_left - $cur_digits)/3);
1406 if($d<0 && $only_down) $d=0;
1408 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1409 $unit = $units[$d];
1411 // If we dont want any zeros after the comma just add the thousand seperator
1412 if($noTrailingZero)
1413 $value = PMA_localizeNumber(preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$value));
1414 else
1415 $value = PMA_localizeNumber(number_format($value, $digits_right)); //number_format is not multibyte safe, str_replace is safe
1417 if($originalValue!=0 && floatval($value) == 0) return ' <'.(1/PMA_pow(10,$digits_right)).' '.$unit;
1419 return $sign . $value . ' ' . $unit;
1420 } // end of the 'PMA_formatNumber' function
1423 * Returns the number of bytes when a formatted size is given
1425 * @param string $formatted_size the size expression (for example 8MB)
1426 * @return integer The numerical part of the expression (for example 8)
1428 function PMA_extractValueFromFormattedSize($formatted_size)
1430 $return_value = -1;
1432 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1433 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1434 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1435 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1436 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1437 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1439 return $return_value;
1440 }// end of the 'PMA_extractValueFromFormattedSize' function
1443 * Writes localised date
1445 * @param string $timestamp the current timestamp
1446 * @param string $format format
1447 * @return string the formatted date
1449 * @access public
1451 function PMA_localisedDate($timestamp = -1, $format = '')
1453 $month = array(
1454 /* l10n: Short month name */
1455 __('Jan'),
1456 /* l10n: Short month name */
1457 __('Feb'),
1458 /* l10n: Short month name */
1459 __('Mar'),
1460 /* l10n: Short month name */
1461 __('Apr'),
1462 /* l10n: Short month name */
1463 _pgettext('Short month name', 'May'),
1464 /* l10n: Short month name */
1465 __('Jun'),
1466 /* l10n: Short month name */
1467 __('Jul'),
1468 /* l10n: Short month name */
1469 __('Aug'),
1470 /* l10n: Short month name */
1471 __('Sep'),
1472 /* l10n: Short month name */
1473 __('Oct'),
1474 /* l10n: Short month name */
1475 __('Nov'),
1476 /* l10n: Short month name */
1477 __('Dec'));
1478 $day_of_week = array(
1479 /* l10n: Short week day name */
1480 __('Sun'),
1481 /* l10n: Short week day name */
1482 __('Mon'),
1483 /* l10n: Short week day name */
1484 __('Tue'),
1485 /* l10n: Short week day name */
1486 __('Wed'),
1487 /* l10n: Short week day name */
1488 __('Thu'),
1489 /* l10n: Short week day name */
1490 __('Fri'),
1491 /* l10n: Short week day name */
1492 __('Sat'));
1494 if ($format == '') {
1495 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1496 $format = __('%B %d, %Y at %I:%M %p');
1499 if ($timestamp == -1) {
1500 $timestamp = time();
1503 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1504 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1506 return strftime($date, $timestamp);
1507 } // end of the 'PMA_localisedDate()' function
1511 * returns a tab for tabbed navigation.
1512 * If the variables $link and $args ar left empty, an inactive tab is created
1514 * @param array $tab array with all options
1515 * @param array $url_params
1516 * @return string html code for one tab, a link if valid otherwise a span
1517 * @access public
1519 function PMA_generate_html_tab($tab, $url_params = array())
1521 // default values
1522 $defaults = array(
1523 'text' => '',
1524 'class' => '',
1525 'active' => null,
1526 'link' => '',
1527 'sep' => '?',
1528 'attr' => '',
1529 'args' => '',
1530 'warning' => '',
1531 'fragment' => '',
1532 'id' => '',
1535 $tab = array_merge($defaults, $tab);
1537 // determine additionnal style-class
1538 if (empty($tab['class'])) {
1539 if (! empty($tab['active'])
1540 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1541 $tab['class'] = 'active';
1542 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1543 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1544 && empty($tab['warning'])) {
1545 $tab['class'] = 'active';
1549 if (!empty($tab['warning'])) {
1550 $tab['class'] .= ' error';
1551 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1554 // If there are any tab specific URL parameters, merge those with the general URL parameters
1555 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1556 $url_params = array_merge($url_params, $tab['url_params']);
1559 // build the link
1560 if (!empty($tab['link'])) {
1561 $tab['link'] = htmlentities($tab['link']);
1562 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1563 if (! empty($tab['args'])) {
1564 foreach ($tab['args'] as $param => $value) {
1565 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1566 . urlencode($value);
1571 if (! empty($tab['fragment'])) {
1572 $tab['link'] .= $tab['fragment'];
1575 // display icon, even if iconic is disabled but the link-text is missing
1576 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1577 && isset($tab['icon'])) {
1578 // avoid generating an alt tag, because it only illustrates
1579 // the text that follows and if browser does not display
1580 // images, the text is duplicated
1581 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1582 .'%1$s" width="16" height="16" alt="" />%2$s';
1583 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1585 // check to not display an empty link-text
1586 elseif (empty($tab['text'])) {
1587 $tab['text'] = '?';
1588 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1589 E_USER_NOTICE);
1592 //Set the id for the tab, if set in the params
1593 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1594 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1596 if (!empty($tab['link'])) {
1597 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1598 .$id_string
1599 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1600 . $tab['text'] . '</a>';
1601 } else {
1602 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1603 . $tab['text'] . '</span>';
1606 $out .= '</li>';
1607 return $out;
1608 } // end of the 'PMA_generate_html_tab()' function
1611 * returns html-code for a tab navigation
1613 * @param array $tabs one element per tab
1614 * @param string $url_params
1615 * @return string html-code for tab-navigation
1617 function PMA_generate_html_tabs($tabs, $url_params)
1619 $tag_id = 'topmenu';
1620 $tab_navigation =
1621 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1622 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1624 foreach ($tabs as $tab) {
1625 $tab_navigation .= PMA_generate_html_tab($tab, $url_params);
1628 $tab_navigation .=
1629 '</ul>' . "\n"
1630 .'<div class="clearfloat"></div>'
1631 .'</div>' . "\n";
1633 return $tab_navigation;
1638 * Displays a link, or a button if the link's URL is too large, to
1639 * accommodate some browsers' limitations
1641 * @param string $url the URL
1642 * @param string $message the link message
1643 * @param mixed $tag_params string: js confirmation
1644 * array: additional tag params (f.e. style="")
1645 * @param boolean $new_form we set this to false when we are already in
1646 * a form, to avoid generating nested forms
1647 * @param boolean $strip_img
1648 * @param string $target
1650 * @return string the results to be echoed or saved in an array
1652 function PMA_linkOrButton($url, $message, $tag_params = array(),
1653 $new_form = true, $strip_img = false, $target = '')
1655 $url_length = strlen($url);
1656 // with this we should be able to catch case of image upload
1657 // into a (MEDIUM) BLOB; not worth generating even a form for these
1658 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1659 return '';
1662 if (! is_array($tag_params)) {
1663 $tmp = $tag_params;
1664 $tag_params = array();
1665 if (!empty($tmp)) {
1666 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1668 unset($tmp);
1670 if (! empty($target)) {
1671 $tag_params['target'] = htmlentities($target);
1674 $tag_params_strings = array();
1675 foreach ($tag_params as $par_name => $par_value) {
1676 // htmlspecialchars() only on non javascript
1677 $par_value = substr($par_name, 0, 2) == 'on'
1678 ? $par_value
1679 : htmlspecialchars($par_value);
1680 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1683 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1684 // no whitespace within an <a> else Safari will make it part of the link
1685 $ret = "\n" . '<a href="' . $url . '" '
1686 . implode(' ', $tag_params_strings) . '>'
1687 . $message . '</a>' . "\n";
1688 } else {
1689 // no spaces (linebreaks) at all
1690 // or after the hidden fields
1691 // IE will display them all
1693 // add class=link to submit button
1694 if (empty($tag_params['class'])) {
1695 $tag_params['class'] = 'link';
1698 // decode encoded url separators
1699 $separator = PMA_get_arg_separator();
1700 // on most places separator is still hard coded ...
1701 if ($separator !== '&') {
1702 // ... so always replace & with $separator
1703 $url = str_replace(htmlentities('&'), $separator, $url);
1704 $url = str_replace('&', $separator, $url);
1706 $url = str_replace(htmlentities($separator), $separator, $url);
1707 // end decode
1709 $url_parts = parse_url($url);
1710 $query_parts = explode($separator, $url_parts['query']);
1711 if ($new_form) {
1712 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1713 . ' method="post"' . $target . ' style="display: inline;">';
1714 $subname_open = '';
1715 $subname_close = '';
1716 $submit_name = '';
1717 } else {
1718 $query_parts[] = 'redirect=' . $url_parts['path'];
1719 if (empty($GLOBALS['subform_counter'])) {
1720 $GLOBALS['subform_counter'] = 0;
1722 $GLOBALS['subform_counter']++;
1723 $ret = '';
1724 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1725 $subname_close = ']';
1726 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1728 foreach ($query_parts as $query_pair) {
1729 list($eachvar, $eachval) = explode('=', $query_pair);
1730 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1731 . $subname_close . '" value="'
1732 . htmlspecialchars(urldecode($eachval)) . '" />';
1733 } // end while
1735 if (stristr($message, '<img')) {
1736 if ($strip_img) {
1737 $message = trim(strip_tags($message));
1738 $ret .= '<input type="submit"' . $submit_name . ' '
1739 . implode(' ', $tag_params_strings)
1740 . ' value="' . htmlspecialchars($message) . '" />';
1741 } else {
1742 $displayed_message = htmlspecialchars(
1743 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1744 $message));
1745 $ret .= '<input type="image"' . $submit_name . ' '
1746 . implode(' ', $tag_params_strings)
1747 . ' src="' . preg_replace(
1748 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1749 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1750 // Here we cannot obey PropertiesIconic completely as a
1751 // generated link would have a length over LinkLengthLimit
1752 // but we can at least show the message.
1753 // If PropertiesIconic is false or 'both'
1754 if ($GLOBALS['cfg']['PropertiesIconic'] !== true) {
1755 $ret .= ' <span class="clickprevimage">' . $displayed_message . '</span>';
1758 } else {
1759 $message = trim(strip_tags($message));
1760 $ret .= '<input type="submit"' . $submit_name . ' '
1761 . implode(' ', $tag_params_strings)
1762 . ' value="' . htmlspecialchars($message) . '" />';
1764 if ($new_form) {
1765 $ret .= '</form>';
1767 } // end if... else...
1769 return $ret;
1770 } // end of the 'PMA_linkOrButton()' function
1774 * Returns a given timespan value in a readable format.
1776 * @param int $seconds the timespan
1778 * @return string the formatted value
1780 function PMA_timespanFormat($seconds)
1782 $days = floor($seconds / 86400);
1783 if ($days > 0) {
1784 $seconds -= $days * 86400;
1786 $hours = floor($seconds / 3600);
1787 if ($days > 0 || $hours > 0) {
1788 $seconds -= $hours * 3600;
1790 $minutes = floor($seconds / 60);
1791 if ($days > 0 || $hours > 0 || $minutes > 0) {
1792 $seconds -= $minutes * 60;
1794 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1798 * Takes a string and outputs each character on a line for itself. Used
1799 * mainly for horizontalflipped display mode.
1800 * Takes care of special html-characters.
1801 * Fulfills todo-item
1802 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1804 * @todo add a multibyte safe function PMA_STR_split()
1805 * @param string $string The string
1806 * @param string $Separator The Separator (defaults to "<br />\n")
1808 * @access public
1809 * @return string The flipped string
1811 function PMA_flipstring($string, $Separator = "<br />\n")
1813 $format_string = '';
1814 $charbuff = false;
1816 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1817 $char = $string{$i};
1818 $append = false;
1820 if ($char == '&') {
1821 $format_string .= $charbuff;
1822 $charbuff = $char;
1823 } elseif ($char == ';' && !empty($charbuff)) {
1824 $format_string .= $charbuff . $char;
1825 $charbuff = false;
1826 $append = true;
1827 } elseif (! empty($charbuff)) {
1828 $charbuff .= $char;
1829 } else {
1830 $format_string .= $char;
1831 $append = true;
1834 // do not add separator after the last character
1835 if ($append && ($i != $str_len - 1)) {
1836 $format_string .= $Separator;
1840 return $format_string;
1844 * Function added to avoid path disclosures.
1845 * Called by each script that needs parameters, it displays
1846 * an error message and, by default, stops the execution.
1848 * Not sure we could use a strMissingParameter message here,
1849 * would have to check if the error message file is always available
1851 * @todo localize error message
1852 * @todo use PMA_fatalError() if $die === true?
1853 * @param array $params The names of the parameters needed by the calling script.
1854 * @param bool $die Stop the execution?
1855 * (Set this manually to false in the calling script
1856 * until you know all needed parameters to check).
1857 * @param bool $request Whether to include this list in checking for special params.
1858 * @global string path to current script
1859 * @global boolean flag whether any special variable was required
1861 * @access public
1863 function PMA_checkParameters($params, $die = true, $request = true)
1865 global $checked_special;
1867 if (! isset($checked_special)) {
1868 $checked_special = false;
1871 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1872 $found_error = false;
1873 $error_message = '';
1875 foreach ($params as $param) {
1876 if ($request && $param != 'db' && $param != 'table') {
1877 $checked_special = true;
1880 if (! isset($GLOBALS[$param])) {
1881 $error_message .= $reported_script_name
1882 . ': Missing parameter: ' . $param
1883 . PMA_showDocu('faqmissingparameters')
1884 . '<br />';
1885 $found_error = true;
1888 if ($found_error) {
1890 * display html meta tags
1892 require_once './libraries/header_meta_style.inc.php';
1893 echo '</head><body><p>' . $error_message . '</p></body></html>';
1894 if ($die) {
1895 exit();
1898 } // end function
1901 * Function to generate unique condition for specified row.
1903 * @param resource $handle current query result
1904 * @param integer $fields_cnt number of fields
1905 * @param array $fields_meta meta information about fields
1906 * @param array $row current row
1907 * @param boolean $force_unique generate condition only on pk or unique
1909 * @access public
1910 * @return array the calculated condition and whether condition is unique
1912 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1914 $primary_key = '';
1915 $unique_key = '';
1916 $nonprimary_condition = '';
1917 $preferred_condition = '';
1919 for ($i = 0; $i < $fields_cnt; ++$i) {
1920 $condition = '';
1921 $field_flags = PMA_DBI_field_flags($handle, $i);
1922 $meta = $fields_meta[$i];
1924 // do not use a column alias in a condition
1925 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1926 $meta->orgname = $meta->name;
1928 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1929 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1930 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
1931 // need (string) === (string)
1932 // '' !== 0 but '' == 0
1933 if ((string) $select_expr['alias'] === (string) $meta->name) {
1934 $meta->orgname = $select_expr['column'];
1935 break;
1936 } // end if
1937 } // end foreach
1941 // Do not use a table alias in a condition.
1942 // Test case is:
1943 // select * from galerie x WHERE
1944 //(select count(*) from galerie y where y.datum=x.datum)>1
1946 // But orgtable is present only with mysqli extension so the
1947 // fix is only for mysqli.
1948 // Also, do not use the original table name if we are dealing with
1949 // a view because this view might be updatable.
1950 // (The isView() verification should not be costly in most cases
1951 // because there is some caching in the function).
1952 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1953 $meta->table = $meta->orgtable;
1956 // to fix the bug where float fields (primary or not)
1957 // can't be matched because of the imprecision of
1958 // floating comparison, use CONCAT
1959 // (also, the syntax "CONCAT(field) IS NULL"
1960 // that we need on the next "if" will work)
1961 if ($meta->type == 'real') {
1962 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1963 . PMA_backquote($meta->orgname) . ') ';
1964 } else {
1965 $condition = ' ' . PMA_backquote($meta->table) . '.'
1966 . PMA_backquote($meta->orgname) . ' ';
1967 } // end if... else...
1969 if (! isset($row[$i]) || is_null($row[$i])) {
1970 $condition .= 'IS NULL AND';
1971 } else {
1972 // timestamp is numeric on some MySQL 4.1
1973 // for real we use CONCAT above and it should compare to string
1974 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
1975 $condition .= '= ' . $row[$i] . ' AND';
1976 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1977 // hexify only if this is a true not empty BLOB or a BINARY
1978 && stristr($field_flags, 'BINARY')
1979 && !empty($row[$i])) {
1980 // do not waste memory building a too big condition
1981 if (strlen($row[$i]) < 1000) {
1982 // use a CAST if possible, to avoid problems
1983 // if the field contains wildcard characters % or _
1984 $condition .= '= CAST(0x' . bin2hex($row[$i])
1985 . ' AS BINARY) AND';
1986 } else {
1987 // this blob won't be part of the final condition
1988 $condition = '';
1990 } elseif ($meta->type == 'bit') {
1991 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
1992 } else {
1993 $condition .= '= \''
1994 . PMA_sqlAddSlashes($row[$i], false, true) . '\' AND';
1997 if ($meta->primary_key > 0) {
1998 $primary_key .= $condition;
1999 } elseif ($meta->unique_key > 0) {
2000 $unique_key .= $condition;
2002 $nonprimary_condition .= $condition;
2003 } // end for
2005 // Correction University of Virginia 19991216:
2006 // prefer primary or unique keys for condition,
2007 // but use conjunction of all values if no primary key
2008 $clause_is_unique = true;
2009 if ($primary_key) {
2010 $preferred_condition = $primary_key;
2011 } elseif ($unique_key) {
2012 $preferred_condition = $unique_key;
2013 } elseif (! $force_unique) {
2014 $preferred_condition = $nonprimary_condition;
2015 $clause_is_unique = false;
2018 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2019 return(array($where_clause, $clause_is_unique));
2020 } // end function
2023 * Generate a button or image tag
2025 * @param string $button_name name of button element
2026 * @param string $button_class class of button element
2027 * @param string $image_name name of image element
2028 * @param string $text text to display
2029 * @param string $image image to display
2030 * @param string $value
2032 * @access public
2034 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2035 $image, $value = '')
2037 if ($value == '') {
2038 $value = $text;
2040 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2041 echo ' <input type="submit" name="' . $button_name . '"'
2042 .' value="' . htmlspecialchars($value) . '"'
2043 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2044 return;
2047 /* Opera has trouble with <input type="image"> */
2048 /* IE has trouble with <button> */
2049 if (PMA_USR_BROWSER_AGENT != 'IE') {
2050 echo '<button class="' . $button_class . '" type="submit"'
2051 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2052 .' title="' . htmlspecialchars($text) . '">' . "\n"
2053 . PMA_getIcon($image, $text)
2054 .'</button>' . "\n";
2055 } else {
2056 echo '<input type="image" name="' . $image_name . '" value="'
2057 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2058 . $image . '" />'
2059 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2061 } // end function
2064 * Generate a pagination selector for browsing resultsets
2066 * @param int $rows Number of rows in the pagination set
2067 * @param int $pageNow current page number
2068 * @param int $nbTotalPage number of total pages
2069 * @param int $showAll If the number of pages is lower than this
2070 * variable, no pages will be omitted in pagination
2071 * @param int $sliceStart How many rows at the beginning should always be shown?
2072 * @param int $sliceEnd How many rows at the end should always be shown?
2073 * @param int $percent Percentage of calculation page offsets to hop to a next page
2074 * @param int $range Near the current page, how many pages should
2075 * be considered "nearby" and displayed as well?
2076 * @param string $prompt The prompt to display (sometimes empty)
2078 * @return string
2079 * @access public
2081 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2082 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2083 $range = 10, $prompt = '')
2085 $increment = floor($nbTotalPage / $percent);
2086 $pageNowMinusRange = ($pageNow - $range);
2087 $pageNowPlusRange = ($pageNow + $range);
2089 $gotopage = $prompt . ' <select id="pageselector" ';
2090 if ($GLOBALS['cfg']['AjaxEnable']) {
2091 $gotopage .= ' class="ajax"';
2093 $gotopage .= ' name="pos" >' . "\n";
2094 if ($nbTotalPage < $showAll) {
2095 $pages = range(1, $nbTotalPage);
2096 } else {
2097 $pages = array();
2099 // Always show first X pages
2100 for ($i = 1; $i <= $sliceStart; $i++) {
2101 $pages[] = $i;
2104 // Always show last X pages
2105 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2106 $pages[] = $i;
2109 // Based on the number of results we add the specified
2110 // $percent percentage to each page number,
2111 // so that we have a representing page number every now and then to
2112 // immediately jump to specific pages.
2113 // As soon as we get near our currently chosen page ($pageNow -
2114 // $range), every page number will be shown.
2115 $i = $sliceStart;
2116 $x = $nbTotalPage - $sliceEnd;
2117 $met_boundary = false;
2118 while ($i <= $x) {
2119 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2120 // If our pageselector comes near the current page, we use 1
2121 // counter increments
2122 $i++;
2123 $met_boundary = true;
2124 } else {
2125 // We add the percentage increment to our current page to
2126 // hop to the next one in range
2127 $i += $increment;
2129 // Make sure that we do not cross our boundaries.
2130 if ($i > $pageNowMinusRange && ! $met_boundary) {
2131 $i = $pageNowMinusRange;
2135 if ($i > 0 && $i <= $x) {
2136 $pages[] = $i;
2140 // Since because of ellipsing of the current page some numbers may be double,
2141 // we unify our array:
2142 sort($pages);
2143 $pages = array_unique($pages);
2146 foreach ($pages as $i) {
2147 if ($i == $pageNow) {
2148 $selected = 'selected="selected" style="font-weight: bold"';
2149 } else {
2150 $selected = '';
2152 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2155 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2157 return $gotopage;
2158 } // end function
2162 * Generate navigation for a list
2164 * @todo use $pos from $_url_params
2165 * @param int $count number of elements in the list
2166 * @param int $pos current position in the list
2167 * @param array $_url_params url parameters
2168 * @param string $script script name for form target
2169 * @param string $frame target frame
2170 * @param int $max_count maximum number of elements to display from the list
2172 * @access public
2174 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2176 if ($max_count < $count) {
2177 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2178 echo __('Page number:');
2179 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2181 // Move to the beginning or to the previous page
2182 if ($pos > 0) {
2183 // patch #474210 - part 1
2184 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2185 $caption1 = '&lt;&lt;';
2186 $caption2 = ' &lt; ';
2187 $title1 = ' title="' . __('Begin') . '"';
2188 $title2 = ' title="' . __('Previous') . '"';
2189 } else {
2190 $caption1 = __('Begin') . ' &lt;&lt;';
2191 $caption2 = __('Previous') . ' &lt;';
2192 $title1 = '';
2193 $title2 = '';
2194 } // end if... else...
2195 $_url_params['pos'] = 0;
2196 echo '<a' . $title1 . ' href="' . $script
2197 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2198 . $caption1 . '</a>';
2199 $_url_params['pos'] = $pos - $max_count;
2200 echo '<a' . $title2 . ' href="' . $script
2201 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2202 . $caption2 . '</a>';
2205 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2206 echo PMA_generate_common_hidden_inputs($_url_params);
2207 echo PMA_pageselector(
2208 $max_count,
2209 floor(($pos + 1) / $max_count) + 1,
2210 ceil($count / $max_count));
2211 echo '</form>';
2213 if ($pos + $max_count < $count) {
2214 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2215 $caption3 = ' &gt; ';
2216 $caption4 = '&gt;&gt;';
2217 $title3 = ' title="' . __('Next') . '"';
2218 $title4 = ' title="' . __('End') . '"';
2219 } else {
2220 $caption3 = '&gt; ' . __('Next');
2221 $caption4 = '&gt;&gt; ' . __('End');
2222 $title3 = '';
2223 $title4 = '';
2224 } // end if... else...
2225 $_url_params['pos'] = $pos + $max_count;
2226 echo '<a' . $title3 . ' href="' . $script
2227 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2228 . $caption3 . '</a>';
2229 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2230 if ($_url_params['pos'] == $count) {
2231 $_url_params['pos'] = $count - $max_count;
2233 echo '<a' . $title4 . ' href="' . $script
2234 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2235 . $caption4 . '</a>';
2237 echo "\n";
2238 if ('frame_navigation' == $frame) {
2239 echo '</div>' . "\n";
2245 * replaces %u in given path with current user name
2247 * example:
2248 * <code>
2249 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2251 * </code>
2252 * @param string $dir with wildcard for user
2253 * @return string per user directory
2255 function PMA_userDir($dir)
2257 // add trailing slash
2258 if (substr($dir, -1) != '/') {
2259 $dir .= '/';
2262 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2266 * returns html code for db link to default db page
2268 * @param string $database
2269 * @return string html link to default db page
2271 function PMA_getDbLink($database = null)
2273 if (! strlen($database)) {
2274 if (! strlen($GLOBALS['db'])) {
2275 return '';
2277 $database = $GLOBALS['db'];
2278 } else {
2279 $database = PMA_unescape_mysql_wildcards($database);
2282 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2283 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2284 .htmlspecialchars($database) . '</a>';
2288 * Displays a lightbulb hint explaining a known external bug
2289 * that affects a functionality
2291 * @param string $functionality localized message explaining the func.
2292 * @param string $component 'mysql' (eventually, 'php')
2293 * @param string $minimum_version of this component
2294 * @param string $bugref bug reference for this component
2296 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2298 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2299 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2304 * Generates and echoes an HTML checkbox
2306 * @param string $html_field_name the checkbox HTML field
2307 * @param string $label
2308 * @param boolean $checked is it initially checked?
2309 * @param boolean $onclick should it submit the form on click?
2311 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2313 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>';
2317 * Generates and echoes a set of radio HTML fields
2319 * @param string $html_field_name the radio HTML field
2320 * @param array $choices the choices values and labels
2321 * @param string $checked_choice the choice to check by default
2322 * @param boolean $line_break whether to add an HTML line break after a choice
2323 * @param boolean $escape_label whether to use htmlspecialchars() on label
2324 * @param string $class enclose each choice with a div of this class
2326 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2327 foreach ($choices as $choice_value => $choice_label) {
2328 if (! empty($class)) {
2329 echo '<div class="' . $class . '">';
2331 $html_field_id = $html_field_name . '_' . $choice_value;
2332 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2333 if ($choice_value == $checked_choice) {
2334 echo ' checked="checked"';
2336 echo ' />' . "\n";
2337 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2338 if ($line_break) {
2339 echo '<br />';
2341 if (! empty($class)) {
2342 echo '</div>';
2344 echo "\n";
2349 * Generates and returns an HTML dropdown
2351 * @param string $select_name
2352 * @param array $choices choices values
2353 * @param string $active_choice the choice to select by default
2354 * @param string $id id of the select element; can be different in case
2355 * the dropdown is present more than once on the page
2356 * @return string
2357 * @todo support titles
2359 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2361 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2362 foreach ($choices as $one_choice_value => $one_choice_label) {
2363 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2364 if ($one_choice_value == $active_choice) {
2365 $result .= ' selected="selected"';
2367 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2369 $result .= '</select>';
2370 return $result;
2374 * Generates a slider effect (jQjuery)
2375 * Takes care of generating the initial <div> and the link
2376 * controlling the slider; you have to generate the </div> yourself
2377 * after the sliding section.
2379 * @param string $id the id of the <div> on which to apply the effect
2380 * @param string $message the message to show as a link
2382 function PMA_generate_slider_effect($id, $message)
2384 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2385 echo '<div id="' . $id . '">';
2386 return;
2389 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2390 * opening the <div> with PHP itself instead of JavaScript.
2392 * @todo find a better solution that uses $.append(), the recommended method
2393 * maybe by using an additional param, the id of the div to append to
2396 <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); ?>">
2397 <?php
2401 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2403 * @param string $action The URL for the request to be executed
2404 * @param string $select_name The name for the dropdown box
2405 * @param array $options An array of options (see rte_footer.lib.php)
2406 * @param string $callback A JS snippet to execute when the request is
2407 * successfully processed
2409 * @return string HTML code for the toggle button
2411 function PMA_toggleButton($action, $select_name, $options, $callback)
2413 // Do the logic first
2414 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2415 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2416 if ($options[1]['selected'] == true) {
2417 $state = 'on';
2418 } else if ($options[0]['selected'] == true) {
2419 $state = 'off';
2420 } else {
2421 $state = 'on';
2423 $selected1 = '';
2424 $selected0 = '';
2425 if ($options[1]['selected'] == true) {
2426 $selected1 = " selected='selected'";
2427 } else if ($options[0]['selected'] == true) {
2428 $selected0 = " selected='selected'";
2430 // Generate output
2431 $retval = "<!-- TOGGLE START -->\n";
2432 if ($GLOBALS['cfg']['AjaxEnable']) {
2433 $retval .= "<noscript>\n";
2435 $retval .= "<div class='wrapper'>\n";
2436 $retval .= " <form action='$action' method='post'>\n";
2437 $retval .= " <select name='$select_name'>\n";
2438 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2439 $retval .= " {$options[1]['label']}\n";
2440 $retval .= " </option>\n";
2441 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2442 $retval .= " {$options[0]['label']}\n";
2443 $retval .= " </option>\n";
2444 $retval .= " </select>\n";
2445 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2446 $retval .= " </form>\n";
2447 $retval .= "</div>\n";
2448 if ($GLOBALS['cfg']['AjaxEnable']) {
2449 $retval .= "</noscript>\n";
2450 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2451 $retval .= " <div class='toggleButton'>\n";
2452 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2453 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2454 $retval .= " alt='' />\n";
2455 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2456 $retval .= " <tbody>\n";
2457 $retval .= " <td class='toggleOn'>\n";
2458 $retval .= " <span class='hide'>$link_on</span>\n";
2459 $retval .= " <div>";
2460 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2461 $retval .= " </td>\n";
2462 $retval .= " <td><div>&nbsp;</div></td>\n";
2463 $retval .= " <td class='toggleOff'>\n";
2464 $retval .= " <span class='hide'>$link_off</span>\n";
2465 $retval .= " <div>";
2466 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2467 $retval .= " </div>\n";
2468 $retval .= " </tbody>\n";
2469 $retval .= " </tr></table>\n";
2470 $retval .= " <span class='hide callback'>$callback</span>\n";
2471 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2472 $retval .= " </div>\n";
2473 $retval .= " </div>\n";
2474 $retval .= "</div>\n";
2476 $retval .= "<!-- TOGGLE END -->";
2478 return $retval;
2479 } // end PMA_toggleButton()
2482 * Clears cache content which needs to be refreshed on user change.
2484 function PMA_clearUserCache() {
2485 PMA_cacheUnset('is_superuser', true);
2489 * Verifies if something is cached in the session
2491 * @param string $var
2492 * @param int|true $server
2493 * @return boolean
2495 function PMA_cacheExists($var, $server = 0)
2497 if (true === $server) {
2498 $server = $GLOBALS['server'];
2500 return isset($_SESSION['cache']['server_' . $server][$var]);
2504 * Gets cached information from the session
2506 * @param string $var
2507 * @param int|true $server
2508 * @return mixed
2510 function PMA_cacheGet($var, $server = 0)
2512 if (true === $server) {
2513 $server = $GLOBALS['server'];
2515 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2516 return $_SESSION['cache']['server_' . $server][$var];
2517 } else {
2518 return null;
2523 * Caches information in the session
2525 * @param string $var
2526 * @param mixed $val
2527 * @param int|true $server
2528 * @return mixed
2530 function PMA_cacheSet($var, $val = null, $server = 0)
2532 if (true === $server) {
2533 $server = $GLOBALS['server'];
2535 $_SESSION['cache']['server_' . $server][$var] = $val;
2539 * Removes cached information from the session
2541 * @param string $var
2542 * @param int|true $server
2544 function PMA_cacheUnset($var, $server = 0)
2546 if (true === $server) {
2547 $server = $GLOBALS['server'];
2549 unset($_SESSION['cache']['server_' . $server][$var]);
2553 * Converts a bit value to printable format;
2554 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2555 * function because in PHP, decbin() supports only 32 bits
2557 * @param numeric $value coming from a BIT field
2558 * @param integer $length
2559 * @return string the printable value
2561 function PMA_printable_bit_value($value, $length) {
2562 $printable = '';
2563 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2564 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2566 $printable = substr($printable, -$length);
2567 return $printable;
2571 * Verifies whether the value contains a non-printable character
2573 * @param string $value
2574 * @return boolean
2576 function PMA_contains_nonprintable_ascii($value) {
2577 return preg_match('@[^[:print:]]@', $value);
2581 * Converts a BIT type default value
2582 * for example, b'010' becomes 010
2584 * @param string $bit_default_value
2585 * @return string the converted value
2587 function PMA_convert_bit_default_value($bit_default_value) {
2588 return strtr($bit_default_value, array("b" => "", "'" => ""));
2592 * Extracts the various parts from a field type spec
2594 * @param string $fieldspec
2595 * @return array associative array containing type, spec_in_brackets
2596 * and possibly enum_set_values (another array)
2598 function PMA_extractFieldSpec($fieldspec) {
2599 $first_bracket_pos = strpos($fieldspec, '(');
2600 if ($first_bracket_pos) {
2601 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2602 // convert to lowercase just to be sure
2603 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2604 } else {
2605 $type = $fieldspec;
2606 $spec_in_brackets = '';
2609 if ('enum' == $type || 'set' == $type) {
2610 // Define our working vars
2611 $enum_set_values = array();
2612 $working = "";
2613 $in_string = false;
2614 $index = 0;
2616 // While there is another character to process
2617 while (isset($fieldspec[$index])) {
2618 // Grab the char to look at
2619 $char = $fieldspec[$index];
2621 // If it is a single quote, needs to be handled specially
2622 if ($char == "'") {
2623 // If we are not currently in a string, begin one
2624 if (! $in_string) {
2625 $in_string = true;
2626 $working = "";
2627 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2628 } else {
2629 // Check out the next character (if possible)
2630 $has_next = isset($fieldspec[$index + 1]);
2631 $next = $has_next ? $fieldspec[$index + 1] : null;
2633 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2634 if (! $has_next || $next != "'") {
2635 $enum_set_values[] = $working;
2636 $in_string = false;
2638 // Otherwise, this is a 'double quote', and can be added to the working string
2639 } elseif ($next == "'") {
2640 $working .= "'";
2641 // Skip the next char; we already know what it is
2642 $index++;
2645 // escaping of a quote?
2646 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2647 $working .= "'";
2648 $index++;
2649 // Otherwise, add it to our working string like normal
2650 } else {
2651 $working .= $char;
2653 // Increment character index
2654 $index++;
2655 } // end while
2656 } else {
2657 $enum_set_values = array();
2660 return array(
2661 'type' => $type,
2662 'spec_in_brackets' => $spec_in_brackets,
2663 'enum_set_values' => $enum_set_values
2668 * Verifies if this table's engine supports foreign keys
2670 * @param string $engine
2671 * @return boolean
2673 function PMA_foreignkey_supported($engine) {
2674 $engine = strtoupper($engine);
2675 if ('INNODB' == $engine || 'PBXT' == $engine) {
2676 return true;
2677 } else {
2678 return false;
2683 * Replaces some characters by a displayable equivalent
2685 * @param string $content
2686 * @return string the content with characters replaced
2688 function PMA_replace_binary_contents($content) {
2689 $result = str_replace("\x00", '\0', $content);
2690 $result = str_replace("\x08", '\b', $result);
2691 $result = str_replace("\x0a", '\n', $result);
2692 $result = str_replace("\x0d", '\r', $result);
2693 $result = str_replace("\x1a", '\Z', $result);
2694 return $result;
2698 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2700 * @param string $string
2701 * @return string with the chars replaced
2704 function PMA_duplicateFirstNewline($string) {
2705 $first_occurence = strpos($string, "\r\n");
2706 if ($first_occurence === 0){
2707 $string = "\n".$string;
2709 return $string;
2713 * Get the action word corresponding to a script name
2714 * in order to display it as a title in navigation panel
2716 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2717 * or $cfg['DefaultTabDatabase']
2718 * @return array
2720 function PMA_getTitleForTarget($target) {
2721 $mapping = array(
2722 // Values for $cfg['DefaultTabTable']
2723 'tbl_structure.php' => __('Structure'),
2724 'tbl_sql.php' => __('SQL'),
2725 'tbl_select.php' =>__('Search'),
2726 'tbl_change.php' =>__('Insert'),
2727 'sql.php' => __('Browse'),
2729 // Values for $cfg['DefaultTabDatabase']
2730 'db_structure.php' => __('Structure'),
2731 'db_sql.php' => __('SQL'),
2732 'db_search.php' => __('Search'),
2733 'db_operations.php' => __('Operations'),
2735 return $mapping[$target];
2739 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2741 * @param string $string Text where to do expansion.
2742 * @param function $escape Function to call for escaping variable values.
2743 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2744 * @return string
2746 function PMA_expandUserString($string, $escape = null, $updates = array()) {
2747 /* Content */
2748 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2749 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2750 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2751 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2752 $vars['database'] = $GLOBALS['db'];
2753 $vars['table'] = $GLOBALS['table'];
2754 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2756 /* Update forced variables */
2757 foreach($updates as $key => $val) {
2758 $vars[$key] = $val;
2761 /* Replacement mapping */
2763 * The __VAR__ ones are for backward compatibility, because user
2764 * might still have it in cookies.
2766 $replace = array(
2767 '@HTTP_HOST@' => $vars['http_host'],
2768 '@SERVER@' => $vars['server_name'],
2769 '__SERVER__' => $vars['server_name'],
2770 '@VERBOSE@' => $vars['server_verbose'],
2771 '@VSERVER@' => $vars['server_verbose_or_name'],
2772 '@DATABASE@' => $vars['database'],
2773 '__DB__' => $vars['database'],
2774 '@TABLE@' => $vars['table'],
2775 '__TABLE__' => $vars['table'],
2776 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2779 /* Optional escaping */
2780 if (!is_null($escape)) {
2781 foreach($replace as $key => $val) {
2782 $replace[$key] = $escape($val);
2786 /* Fetch fields list if required */
2787 if (strpos($string, '@FIELDS@') !== false) {
2788 $fields_list = PMA_DBI_fetch_result(
2789 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2790 . '.' . PMA_backquote($GLOBALS['table']));
2792 $field_names = array();
2793 foreach ($fields_list as $field) {
2794 if (!is_null($escape)) {
2795 $field_names[] = $escape($field['Field']);
2796 } else {
2797 $field_names[] = $field['Field'];
2801 $replace['@FIELDS@'] = implode(',', $field_names);
2804 /* Do the replacement */
2805 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2809 * function that generates a json output for an ajax request and ends script
2810 * execution
2812 * @param bool $message message string containing the html of the message
2813 * @param bool $success success whether the ajax request was successfull
2814 * @param array $extra_data extra_data optional - any other data as part of the json request
2817 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2819 $response = array();
2820 if( $success == true ) {
2821 $response['success'] = true;
2822 if ($message instanceof PMA_Message) {
2823 $response['message'] = $message->getDisplay();
2825 else {
2826 $response['message'] = $message;
2829 else {
2830 $response['success'] = false;
2831 if($message instanceof PMA_Message) {
2832 $response['error'] = $message->getDisplay();
2834 else {
2835 $response['error'] = $message;
2839 // If extra_data has been provided, append it to the response array
2840 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2841 $response = array_merge($response, $extra_data);
2844 // Set the Content-Type header to JSON so that jQuery parses the
2845 // response correctly.
2847 // At this point, other headers might have been sent;
2848 // even if $GLOBALS['is_header_sent'] is true,
2849 // we have to send these additional headers.
2850 header('Cache-Control: no-cache');
2851 header("Content-Type: application/json");
2853 echo json_encode($response);
2854 exit;
2858 * Display the form used to browse anywhere on the local server for the file to import
2860 * @param $max_upload_size
2862 function PMA_browseUploadFile($max_upload_size) {
2863 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2864 echo '<div id="upload_form_status" style="display: none;"></div>';
2865 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2866 echo '<input type="file" name="import_file" id="input_import_file" />';
2867 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2868 // some browsers should respect this :)
2869 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2873 * Display the form used to select a file to import from the server upload directory
2875 * @param $import_list
2876 * @param $uploaddir
2878 function PMA_selectUploadFile($import_list, $uploaddir) {
2879 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2880 $extensions = '';
2881 foreach ($import_list as $key => $val) {
2882 if (!empty($extensions)) {
2883 $extensions .= '|';
2885 $extensions .= $val['extension'];
2887 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2889 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2890 if ($files === false) {
2891 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2892 } elseif (!empty($files)) {
2893 echo "\n";
2894 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2895 echo ' <option value="">&nbsp;</option>' . "\n";
2896 echo $files;
2897 echo ' </select>' . "\n";
2898 } elseif (empty ($files)) {
2899 echo '<i>' . __('There are no files to upload') . '</i>';
2904 * Build titles and icons for action links
2906 * @return array the action titles
2908 function PMA_buildActionTitles() {
2909 $titles = array();
2911 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2912 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2913 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2914 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2915 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2916 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2917 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2918 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2919 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2920 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2921 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2922 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
2923 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'), true);
2924 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'), true);
2925 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'), true);
2926 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'), true);
2927 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'), true);
2928 return $titles;
2932 * This function processes the datatypes supported by the DB, as specified in
2933 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
2934 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
2936 * @param bool $html Whether to generate an html snippet or an array
2937 * @param string $selected The value to mark as selected in HTML mode
2939 * @return mixed An HTML snippet or an array of datatypes.
2942 function PMA_getSupportedDatatypes($html = false, $selected = '')
2944 global $cfg;
2946 if ($html) {
2947 // NOTE: the SELECT tag in not included in this snippet.
2948 $retval = '';
2949 foreach ($cfg['ColumnTypes'] as $key => $value) {
2950 if (is_array($value)) {
2951 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
2952 foreach ($value as $subvalue) {
2953 if ($subvalue == $selected) {
2954 $retval .= "<option selected='selected'>";
2955 $retval .= $subvalue;
2956 $retval .= "</option>";
2957 } else if ($subvalue === '-') {
2958 $retval .= "<option disabled='disabled'>";
2959 $retval .= $subvalue;
2960 $retval .= "</option>";
2961 } else {
2962 $retval .= "<option>$subvalue</option>";
2965 $retval .= '</optgroup>';
2966 } else {
2967 if ($selected == $value) {
2968 $retval .= "<option selected='selected'>$value</option>";
2969 } else {
2970 $retval .= "<option>$value</option>";
2974 } else {
2975 $retval = array();
2976 foreach ($cfg['ColumnTypes'] as $value) {
2977 if (is_array($value)) {
2978 foreach ($value as $subvalue) {
2979 if ($subvalue !== '-') {
2980 $retval[] = $subvalue;
2983 } else {
2984 if ($value !== '-') {
2985 $retval[] = $value;
2991 return $retval;
2992 } // end PMA_getSupportedDatatypes()
2995 * Returns a list of datatypes that are not (yet) handled by PMA.
2996 * Used by: tbl_change.php and libraries/db_routines.inc.php
2998 * @return array list of datatypes
3001 function PMA_unsupportedDatatypes() {
3002 // These GIS data types are not yet supported.
3003 $no_support_types = array('geometry',
3004 'point',
3005 'linestring',
3006 'polygon',
3007 'multipoint',
3008 'multilinestring',
3009 'multipolygon',
3010 'geometrycollection'
3013 return $no_support_types;
3017 * Creates a dropdown box with MySQL functions for a particular column.
3019 * @param array $field Data about the column for which
3020 * to generate the dropdown
3021 * @param bool $insert_mode Whether the operation is 'insert'
3023 * @global array $cfg PMA configuration
3024 * @global array $analyzed_sql Analyzed SQL query
3025 * @global mixed $data (null/string) FIXME: what is this for?
3027 * @return string An HTML snippet of a dropdown list with function
3028 * names appropriate for the requested column.
3030 function PMA_getFunctionsForField($field, $insert_mode)
3032 global $cfg, $analyzed_sql, $data;
3034 $selected = '';
3035 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3036 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3037 // which will then reveal the available dropdown options
3038 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3039 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3040 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3041 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3042 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3043 } else {
3044 $dropdown = array();
3045 $default_function = '';
3047 $dropdown_built = array();
3048 $op_spacing_needed = false;
3049 // what function defined as default?
3050 // for the first timestamp we don't set the default function
3051 // if there is a default value for the timestamp
3052 // (not including CURRENT_TIMESTAMP)
3053 // and the column does not have the
3054 // ON UPDATE DEFAULT TIMESTAMP attribute.
3055 if ($field['True_Type'] == 'timestamp'
3056 && empty($field['Default'])
3057 && empty($data)
3058 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3059 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3061 // For primary keys of type char(36) or varchar(36) UUID if the default function
3062 // Only applies to insert mode, as it would silently trash data on updates.
3063 if ($insert_mode
3064 && $field['Key'] == 'PRI'
3065 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3067 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3069 // this is set only when appropriate and is always true
3070 if (isset($field['display_binary_as_hex'])) {
3071 $default_function = 'UNHEX';
3074 // Create the output
3075 $retval = ' <option></option>' . "\n";
3076 // loop on the dropdown array and print all available options for that field.
3077 foreach ($dropdown as $each_dropdown){
3078 $retval .= ' ';
3079 $retval .= '<option';
3080 if ($default_function === $each_dropdown) {
3081 $retval .= ' selected="selected"';
3083 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3084 $dropdown_built[$each_dropdown] = 'true';
3085 $op_spacing_needed = true;
3087 // For compatibility's sake, do not let out all other functions. Instead
3088 // print a separator (blank) and then show ALL functions which weren't shown
3089 // yet.
3090 $cnt_functions = count($cfg['Functions']);
3091 for ($j = 0; $j < $cnt_functions; $j++) {
3092 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3093 // Is current function defined as default?
3094 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3095 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3096 ? ' selected="selected"'
3097 : '';
3098 if ($op_spacing_needed == true) {
3099 $retval .= ' ';
3100 $retval .= '<option value="">--------</option>' . "\n";
3101 $op_spacing_needed = false;
3104 $retval .= ' ';
3105 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3107 } // end for
3109 return $retval;
3110 } // end PMA_getFunctionsForField()
3113 * Checks if the current user has a specific privilege and returns true if the
3114 * user indeed has that privilege or false if (s)he doesn't. This function must
3115 * only be used for features that are available since MySQL 5, because it
3116 * relies on the INFORMATION_SCHEMA database to be present.
3118 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3119 * // Checks if the currently logged in user has the global
3120 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3121 * // user has this privilege on database 'mydb'.
3124 * @param string $priv The privilege to check
3125 * @param mixed $db null, to only check global privileges
3126 * string, db name where to also check for privileges
3127 * @param mixed $tbl null, to only check global privileges
3128 * string, db name where to also check for privileges
3129 * @return bool
3131 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3133 // Get the username for the current user in the format
3134 // required to use in the information schema database.
3135 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3136 if ($user === false) {
3137 return false;
3139 $user = explode('@', $user);
3140 $username = "''";
3141 $username .= str_replace("'", "''", $user[0]);
3142 $username .= "''@''";
3143 $username .= str_replace("'", "''", $user[1]);
3144 $username .= "''";
3145 // Prepage the query
3146 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3147 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3148 // Check global privileges first.
3149 if (PMA_DBI_fetch_value(sprintf($query,
3150 'USER_PRIVILEGES',
3151 $username,
3152 $priv))) {
3153 return true;
3155 // If a database name was provided and user does not have the
3156 // required global privilege, try database-wise permissions.
3157 if ($db !== null) {
3158 $query .= " AND TABLE_SCHEMA='%s'";
3159 if (PMA_DBI_fetch_value(sprintf($query,
3160 'SCHEMA_PRIVILEGES',
3161 $username,
3162 $priv,
3163 PMA_sqlAddSlashes($db)))) {
3164 return true;
3166 } else {
3167 // There was no database name provided and the user
3168 // does not have the correct global privilege.
3169 return false;
3171 // If a table name was also provided and we still didn't
3172 // find any valid privileges, try table-wise privileges.
3173 if ($tbl !== null) {
3174 $query .= " AND TABLE_NAME='%s'";
3175 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3176 'TABLE_PRIVILEGES',
3177 $username,
3178 $priv,
3179 PMA_sqlAddSlashes($db),
3180 PMA_sqlAddSlashes($tbl)))) {
3181 return true;
3184 // If we reached this point, the user does not
3185 // have even valid table-wise privileges.
3186 return false;
3190 * Returns server type for current connection
3192 * Known types are: Drizzle, MariaDB and MySQL (default)
3194 * @return string
3196 function PMA_getServerType()
3198 $server_type = 'MySQL';
3199 if (PMA_DRIZZLE) {
3200 $server_type = 'Drizzle';
3201 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3202 $server_type = 'MariaDB';
3204 return $server_type;