2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Misc functions used all over the scripts.
10 * Exponential expression / raise number into power
12 * @uses function_exists()
19 * @param string pow function use, or false for auto-detect
20 * @return mixed string or float
22 function PMA_pow($base, $exp, $use_function = false)
24 static $pow_function = null;
26 if (null == $pow_function) {
27 if (function_exists('bcpow')) {
28 // BCMath Arbitrary Precision Mathematics Function
29 $pow_function = 'bcpow';
30 } elseif (function_exists('gmp_pow')) {
32 $pow_function = 'gmp_pow';
35 $pow_function = 'pow';
39 if (! $use_function) {
40 $use_function = $pow_function;
43 if ($exp < 0 && 'pow' != $use_function) {
46 switch ($use_function) {
48 // bcscale() needed for testing PMA_pow() with base values < 1
50 $pow = bcpow($base, $exp);
53 $pow = gmp_strval(gmp_pow($base, $exp));
56 $base = (float) $base;
58 $pow = pow($base, $exp);
61 $pow = $use_function($base, $exp);
68 * string PMA_getIcon(string $icon)
70 * @uses $GLOBALS['pmaThemeImage']
71 * @uses $GLOBALS['cfg']['PropertiesIconic']
72 * @uses htmlspecialchars()
73 * @param string $icon name of icon file
74 * @param string $alternate alternate text
75 * @param boolean $container include in container
76 * @param boolean $$force_text whether to force alternate text to be displayed
77 * @return html img tag
79 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
81 $include_icon = false;
82 $include_text = false;
84 $alternate = htmlspecialchars($alternate);
87 if ($GLOBALS['cfg']['PropertiesIconic']) {
92 ||
! (true === $GLOBALS['cfg']['PropertiesIconic'])
94 // $cfg['PropertiesIconic'] is false or both
95 // OR we have no $include_icon
99 if ($include_text && $include_icon && $container) {
100 // we have icon, text and request for container
105 $button .= '<span class="nowrap">';
109 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
110 . ' title="' . $alternate . '" alt="' . $alternate . '"'
111 . ' class="icon" width="16" height="16" />';
114 if ($include_icon && $include_text) {
119 $button .= $alternate;
123 $button .= '</span>';
130 * Displays the maximum size for an upload
132 * @uses PMA_formatByteDown()
134 * @param integer the size
136 * @return string the message
140 function PMA_displayMaximumUploadSize($max_upload_size)
142 // I have to reduce the second parameter (sensitiveness) from 6 to 4
143 // to avoid weird results like 512 kKib
144 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
145 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
149 * Generates a hidden field which should indicate to the browser
150 * the maximum size for upload
152 * @param integer the size
154 * @return string the INPUT field
158 function PMA_generateHiddenMaxFileSize($max_size)
160 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
164 * Add slashes before "'" and "\" characters so a value containing them can
165 * be used in a sql comparison.
167 * @uses str_replace()
168 * @param string the string to slash
169 * @param boolean whether the string will be used in a 'LIKE' clause
170 * (it then requires two more escaped sequences) or not
171 * @param boolean whether to treat cr/lfs as escape-worthy entities
172 * (converts \n to \\n, \r to \\r)
174 * @param boolean whether this function is used as part of the
175 * "Create PHP code" dialog
177 * @return string the slashed string
181 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
184 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
186 $a_string = str_replace('\\', '\\\\', $a_string);
190 $a_string = str_replace("\n", '\n', $a_string);
191 $a_string = str_replace("\r", '\r', $a_string);
192 $a_string = str_replace("\t", '\t', $a_string);
196 $a_string = str_replace('\'', '\\\'', $a_string);
198 $a_string = str_replace('\'', '\'\'', $a_string);
202 } // end of the 'PMA_sqlAddslashes()' function
206 * Add slashes before "_" and "%" characters for using them in MySQL
207 * database, table and field names.
208 * Note: This function does not escape backslashes!
210 * @uses str_replace()
211 * @param string the string to escape
213 * @return string the escaped string
217 function PMA_escape_mysql_wildcards($name)
219 $name = str_replace('_', '\\_', $name);
220 $name = str_replace('%', '\\%', $name);
223 } // end of the 'PMA_escape_mysql_wildcards()' function
226 * removes slashes before "_" and "%" characters
227 * Note: This function does not unescape backslashes!
229 * @uses str_replace()
230 * @param string $name the string to escape
231 * @return string the escaped string
234 function PMA_unescape_mysql_wildcards($name)
236 $name = str_replace('\\_', '_', $name);
237 $name = str_replace('\\%', '%', $name);
240 } // end of the 'PMA_unescape_mysql_wildcards()' function
243 * removes quotes (',",`) from a quoted string
245 * checks if the sting is quoted and removes this quotes
247 * @uses str_replace()
249 * @param string $quoted_string string to remove quotes from
250 * @param string $quote type of quote to remove
251 * @return string unqoted string
253 function PMA_unQuote($quoted_string, $quote = null)
257 if (null === $quote) {
265 foreach ($quotes as $quote) {
266 if (substr($quoted_string, 0, 1) === $quote
267 && substr($quoted_string, -1, 1) === $quote) {
268 $unquoted_string = substr($quoted_string, 1, -1);
269 // replace escaped quotes
270 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
271 return $unquoted_string;
275 return $quoted_string;
281 * @todo move into PMA_Sql
282 * @uses PMA_SQP_isError()
283 * @uses PMA_SQP_formatHtml()
284 * @uses PMA_SQP_formatNone()
286 * @param mixed pre-parsed SQL structure
288 * @return string the formatted sql
290 * @global array the configuration array
291 * @global boolean whether the current statement is a multiple one or not
296 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
300 // Check that we actually have a valid set of parsed data
302 // first check for the SQL parser having hit an error
303 if (PMA_SQP_isError()) {
304 return htmlspecialchars($parsed_sql['raw']);
306 // then check for an array
307 if (!is_array($parsed_sql)) {
308 // We don't so just return the input directly
309 // This is intended to be used for when the SQL Parser is turned off
310 $formatted_sql = '<pre>' . "\n"
311 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ?
$unparsed_sql : $parsed_sql) . "\n"
313 return $formatted_sql;
318 switch ($cfg['SQP']['fmtType']) {
320 if ($unparsed_sql != '') {
321 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
323 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
327 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
330 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
336 return $formatted_sql;
337 } // end of the "PMA_formatSql()" function
341 * Displays a link to the official MySQL documentation
343 * @uses $cfg['MySQLManualType']
344 * @uses $cfg['MySQLManualBase']
345 * @uses $cfg['ReplaceHelpImg']
346 * @uses $GLOBALS['pmaThemeImage']
347 * @uses PMA_MYSQL_INT_VERSION
349 * @uses str_replace()
350 * @param string chapter of "HTML, one page per chapter" documentation
351 * @param string contains name of page/anchor that is being linked
352 * @param bool whether to use big icon (like in left frame)
353 * @param string anchor to page part
355 * @return string the html link
359 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
363 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
367 // Fixup for newly used names:
368 $chapter = str_replace('_', '-', strtolower($chapter));
369 $link = str_replace('_', '-', strtolower($link));
371 switch ($cfg['MySQLManualType']) {
373 if (empty($chapter)) {
376 if (empty($anchor)) {
379 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
382 if (empty($anchor)) {
385 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
391 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
392 if (!empty($anchor)) {
393 $url .= '#' . $anchor;
403 if (defined('PMA_MYSQL_INT_VERSION')) {
404 if (PMA_MYSQL_INT_VERSION
>= 50100) {
406 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
407 $lang = _pgettext('$mysql_5_1_doc_lang', 'en');
408 } elseif (PMA_MYSQL_INT_VERSION
>= 50000) {
410 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
411 $lang = _pgettext('$mysql_5_0_doc_lang', 'en');
414 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
415 if (!empty($anchor)) {
416 $url .= '#' . $anchor;
422 return '<a href="' . $url . '" target="mysql_doc">';
423 } elseif ($big_icon) {
424 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
425 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
426 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
428 return '[<a href="' . $url . '" target="mysql_doc">' . __('Documentation') . '</a>]';
430 } // end of the 'PMA_showMySQLDocu()' function
434 * Displays a link to the phpMyAdmin documentation
436 * @param string anchor in documentation
438 * @return string the html link
442 function PMA_showDocu($anchor) {
443 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
444 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>';
446 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
448 } // end of the 'PMA_showDocu()' function
451 * returns HTML for a footnote marker and add the messsage to the footnotes
453 * @uses $GLOBALS['footnotes']
454 * @param string the error message
455 * @return string html code for a footnote marker
458 function PMA_showHint($message, $bbcode = false, $type = 'notice')
460 if ($message instanceof PMA_Message
) {
461 $key = $message->getHash();
462 $type = $message->getLevel();
464 $key = md5($message);
467 if (! isset($GLOBALS['footnotes'][$key])) {
468 if (empty($GLOBALS['footnotes']) ||
! is_array($GLOBALS['footnotes'])) {
469 $GLOBALS['footnotes'] = array();
471 $nr = count($GLOBALS['footnotes']) +
1;
472 // this is the first instance of this message
474 $GLOBALS['footnotes'][$key] = array(
478 'instance' => $instance
481 $nr = $GLOBALS['footnotes'][$key]['nr'];
482 // another instance of this message (to ensure ids are unique)
483 $instance = ++
$GLOBALS['footnotes'][$key]['instance'];
487 return '[sup]' . $nr . '[/sup]';
490 // footnotemarker used in js/tooltip.js
491 return '<sup class="footnotemarker">' . $nr . '</sup>' .
492 '<img class="footnotemarker" id="footnote_' . $nr . '_' . $instance . '" src="' .
493 $GLOBALS['pmaThemeImage'] . 'b_help.png" alt="" />';
497 * Displays a MySQL error message in the right frame.
499 * @uses footer.inc.php
500 * @uses header.inc.php
501 * @uses $GLOBALS['sql_query']
502 * @uses $GLOBALS['pmaThemeImage']
503 * @uses $GLOBALS['cfg']['PropertiesIconic']
504 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
505 * @uses PMA_backquote()
506 * @uses PMA_DBI_getError()
507 * @uses PMA_formatSql()
508 * @uses PMA_generate_common_hidden_inputs()
509 * @uses PMA_generate_common_url()
510 * @uses PMA_showMySQLDocu()
511 * @uses PMA_sqlAddslashes()
512 * @uses PMA_SQP_isError()
513 * @uses PMA_SQP_parse()
514 * @uses PMA_SQP_getErrorString()
517 * @uses str_replace()
520 * @uses preg_replace()
525 * @uses function_exists()
526 * @uses htmlspecialchars()
529 * @param string the error message
530 * @param string the sql query that failed
531 * @param boolean whether to show a "modify" link or not
532 * @param string the "back" link url (full path is not required)
533 * @param boolean EXIT the page?
535 * @global string the curent table
536 * @global string the current db
540 function PMA_mysqlDie($error_message = '', $the_query = '',
541 $is_modify_link = true, $back_url = '', $exit = true)
546 * start http output, display html headers
548 require_once './libraries/header.inc.php';
550 $error_msg_output = '';
552 if (!$error_message) {
553 $error_message = PMA_DBI_getError();
555 if (!$the_query && !empty($GLOBALS['sql_query'])) {
556 $the_query = $GLOBALS['sql_query'];
559 // --- Added to solve bug #641765
560 // Robbat2 - 12 January 2003, 9:46PM
561 // Revised, Robbat2 - 13 January 2003, 2:59PM
562 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
563 $formatted_sql = htmlspecialchars($the_query);
564 } elseif (empty($the_query) ||
trim($the_query) == '') {
567 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
568 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
570 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
574 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
575 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
576 // if the config password is wrong, or the MySQL server does not
577 // respond, do not show the query that would reveal the
579 if (!empty($the_query) && !strstr($the_query, 'connect')) {
580 // --- Added to solve bug #641765
581 // Robbat2 - 12 January 2003, 9:46PM
582 // Revised, Robbat2 - 13 January 2003, 2:59PM
583 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
584 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
585 $error_msg_output .= '<br />' . "\n";
588 // modified to show the help on sql errors
589 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
590 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
591 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
593 if ($is_modify_link) {
594 $_url_params = array(
595 'sql_query' => $the_query,
598 if (strlen($table)) {
599 $_url_params['db'] = $db;
600 $_url_params['table'] = $table;
601 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
602 } elseif (strlen($db)) {
603 $_url_params['db'] = $db;
604 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
606 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
609 $error_msg_output .= $doedit_goto
610 . PMA_getIcon('b_edit.png', __('Edit'))
613 $error_msg_output .= ' </p>' . "\n"
615 .' ' . $formatted_sql . "\n"
619 if (!empty($error_message)) {
620 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
622 // modified to show the help on error-returns
623 // (now error-messages-server)
624 $error_msg_output .= '<p>' . "\n"
625 . ' <strong>' . __('MySQL said: ') . '</strong>'
626 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
630 // The error message will be displayed within a CODE segment.
631 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
633 // Replace all non-single blanks with their HTML-counterpart
634 $error_message = str_replace(' ', ' ', $error_message);
635 // Replace TAB-characters with their HTML-counterpart
636 $error_message = str_replace("\t", ' ', $error_message);
637 // Replace linebreaks
638 $error_message = nl2br($error_message);
640 $error_msg_output .= '<code>' . "\n"
641 . $error_message . "\n"
642 . '</code><br />' . "\n";
643 $error_msg_output .= '</div>';
645 $_SESSION['Import_message']['message'] = $error_msg_output;
648 if (! empty($back_url)) {
649 if (strstr($back_url, '?')) {
650 $back_url .= '&no_history=true';
652 $back_url .= '?no_history=true';
655 $_SESSION['Import_message']['go_back_url'] = $back_url;
657 $error_msg_output .= '<fieldset class="tblFooters">';
658 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
659 $error_msg_output .= '</fieldset>' . "\n\n";
663 * If in an Ajax request, don't just echo and exit. Use PMA_ajaxResponse()
665 if($GLOBALS['is_ajax_request'] == true) {
666 PMA_ajaxResponse($error_msg_output, false);
668 echo $error_msg_output;
670 * display footer and exit
672 require './libraries/footer.inc.php';
674 echo $error_msg_output;
676 } // end of the 'PMA_mysqlDie()' function
679 * returns array with tables of given db with extended information and grouped
681 * @uses $cfg['LeftFrameTableSeparator']
682 * @uses $cfg['LeftFrameTableLevel']
683 * @uses $cfg['ShowTooltipAliasTB']
684 * @uses $cfg['NaturalOrder']
685 * @uses PMA_backquote()
691 * @param string $db name of db
692 * @param string $tables name of tables
693 * @param integer $limit_offset list offset
694 * @param integer $limit_count max tables to return
695 * return array (recursive) grouped table list
697 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
699 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
701 if (null === $tables) {
702 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
703 if ($GLOBALS['cfg']['NaturalOrder']) {
704 uksort($tables, 'strnatcasecmp');
708 if (count($tables) < 1) {
719 $table_groups = array();
721 // for blobstreaming - list of blobstreaming tables
723 // load PMA configuration
724 $PMA_Config = $GLOBALS['PMA_Config'];
726 foreach ($tables as $table_name => $table) {
727 // if BS tables exist
728 if (PMA_BS_IsHiddenTable($table_name)) {
732 // check for correct row count
733 if (null === $table['Rows']) {
734 // Do not check exact row count here,
735 // if row count is invalid possibly the table is defect
736 // and this would break left frame;
737 // but we can check row count if this is a view or the
738 // information_schema database
739 // since PMA_Table::countRecords() returns a limited row count
742 // set this because PMA_Table::countRecords() can use it
743 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
745 if ($tbl_is_view ||
'information_schema' == $db) {
746 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name']);
750 // in $group we save the reference to the place in $table_groups
751 // where to store the table info
752 if ($GLOBALS['cfg']['LeftFrameDBTree']
753 && $sep && strstr($table_name, $sep))
755 $parts = explode($sep, $table_name);
757 $group =& $table_groups;
759 $group_name_full = '';
760 $parts_cnt = count($parts) - 1;
761 while ($i < $parts_cnt
762 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
763 $group_name = $parts[$i] . $sep;
764 $group_name_full .= $group_name;
766 if (!isset($group[$group_name])) {
767 $group[$group_name] = array();
768 $group[$group_name]['is' . $sep . 'group'] = true;
769 $group[$group_name]['tab' . $sep . 'count'] = 1;
770 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
771 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
772 $table = $group[$group_name];
773 $group[$group_name] = array();
774 $group[$group_name][$group_name] = $table;
776 $group[$group_name]['is' . $sep . 'group'] = true;
777 $group[$group_name]['tab' . $sep . 'count'] = 1;
778 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
780 $group[$group_name]['tab' . $sep . 'count']++
;
782 $group =& $group[$group_name];
786 if (!isset($table_groups[$table_name])) {
787 $table_groups[$table_name] = array();
789 $group =& $table_groups;
793 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
794 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
795 // switch tooltip and name
796 $table['Comment'] = $table['Name'];
797 $table['disp_name'] = $table['Comment'];
799 $table['disp_name'] = $table['Name'];
802 $group[$table_name] = array_merge($default, $table);
805 return $table_groups;
808 /* ----------------------- Set of misc functions ----------------------- */
812 * Adds backquotes on both sides of a database, table or field name.
813 * and escapes backquotes inside the name with another backquote
817 * echo PMA_backquote('owner`s db'); // `owner``s db`
821 * @uses PMA_backquote()
824 * @uses str_replace()
825 * @param mixed $a_name the database, table or field name to "backquote"
827 * @param boolean $do_it a flag to bypass this function (used by dump
829 * @return mixed the "backquoted" database, table or field name if the
830 * current MySQL release is >= 3.23.6, the original one
834 function PMA_backquote($a_name, $do_it = true)
836 if (is_array($a_name)) {
837 foreach ($a_name as &$data) {
838 $data = PMA_backquote($data, $do_it);
844 global $PMA_SQPdata_forbidden_word;
845 global $PMA_SQPdata_forbidden_word_cnt;
847 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
852 // '0' is also empty for php :-(
853 if (strlen($a_name) && $a_name !== '*') {
854 return '`' . str_replace('`', '``', $a_name) . '`';
858 } // end of the 'PMA_backquote()' function
862 * Defines the <CR><LF> value depending on the user OS.
865 * @return string the <CR><LF> value to use
869 function PMA_whichCrlf()
873 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
875 if (PMA_USR_OS
== 'Win') {
884 } // end of the 'PMA_whichCrlf()' function
887 * Reloads navigation if needed.
889 * @param $jsonly prints out pure JavaScript
890 * @uses $GLOBALS['reload']
891 * @uses $GLOBALS['db']
892 * @uses PMA_generate_common_url()
893 * @global array configuration
897 function PMA_reloadNavigation($jsonly=false)
901 // Reloads the navigation frame via JavaScript if required
902 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
903 // one of the reasons for a reload is when a table is dropped
904 // in this case, get rid of the table limit offset, otherwise
905 // we have a problem when dropping a table on the last page
906 // and the offset becomes greater than the total number of tables
907 unset($_SESSION['tmp_user_values']['table_limit_offset']);
909 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
911 echo '<script type="text/javascript">' . PHP_EOL
;
914 if (typeof(window
.parent
) != 'undefined'
915 && typeof(window
.parent
.frame_navigation
) != 'undefined'
916 && window
.parent
.goTo) {
917 window
.parent
.goTo('<?php echo $reload_url; ?>');
922 echo '</script>' . PHP_EOL
;
924 unset($GLOBALS['reload']);
929 * displays the message and the query
930 * usually the message is the result of the query executed
932 * @param string $message the message to display
933 * @param string $sql_query the query to display
934 * @param string $type the type (level) of the message
935 * @param boolean $is_view is this a message after a VIEW operation?
936 * @global array the configuration array
940 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
943 * PMA_ajaxResponse uses this function to collect the string of HTML generated
944 * for showing the message. Use output buffering to collect it and return it
945 * in a string. In some special cases on sql.php, buffering has to be disabled
946 * and hence we check with $GLOBALS['buffer_message']
948 if( $GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message']) ) {
953 if (null === $sql_query) {
954 if (! empty($GLOBALS['display_query'])) {
955 $sql_query = $GLOBALS['display_query'];
956 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
957 $sql_query = $GLOBALS['unparsed_sql'];
958 } elseif (! empty($GLOBALS['sql_query'])) {
959 $sql_query = $GLOBALS['sql_query'];
965 // Corrects the tooltip text via JS if required
966 // @todo this is REALLY the wrong place to do this - very unexpected here
967 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
968 $tooltip = PMA_Table
::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
969 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
971 echo '<script type="text/javascript">' . "\n";
972 echo '//<![CDATA[' . "\n";
973 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
975 echo '</script>' . "\n";
976 } // end if ... elseif
978 // Checks if the table needs to be repaired after a TRUNCATE query.
979 // @todo what about $GLOBALS['display_query']???
980 // @todo this is REALLY the wrong place to do this - very unexpected here
981 if (strlen($GLOBALS['table'])
982 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
983 if (PMA_Table
::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
984 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
989 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
990 // check for it's presence before using it
991 echo '<div align="' . ( isset($GLOBALS['cell_align_left']) ?
$GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
993 if ($message instanceof PMA_Message
) {
994 if (isset($GLOBALS['special_message'])) {
995 $message->addMessage($GLOBALS['special_message']);
996 unset($GLOBALS['special_message']);
999 $type = $message->getLevel();
1001 echo '<div class="' . $type . '">';
1002 echo PMA_sanitize($message);
1003 if (isset($GLOBALS['special_message'])) {
1004 echo PMA_sanitize($GLOBALS['special_message']);
1005 unset($GLOBALS['special_message']);
1010 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1011 // Html format the query to be displayed
1012 // If we want to show some sql code it is easiest to create it here
1013 /* SQL-Parser-Analyzer */
1015 if (! empty($GLOBALS['show_as_php'])) {
1016 $new_line = '\\n"<br />' . "\n"
1017 . ' . "';
1018 $query_base = htmlspecialchars(addslashes($sql_query));
1019 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1021 $query_base = $sql_query;
1024 $query_too_big = false;
1026 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1027 // when the query is large (for example an INSERT of binary
1028 // data), the parser chokes; so avoid parsing the query
1029 $query_too_big = true;
1030 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1031 } elseif (! empty($GLOBALS['parsed_sql'])
1032 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1033 // (here, use "! empty" because when deleting a bookmark,
1034 // $GLOBALS['parsed_sql'] is set but empty
1035 $parsed_sql = $GLOBALS['parsed_sql'];
1037 // Parse SQL if needed
1038 $parsed_sql = PMA_SQP_parse($query_base);
1039 if (PMA_SQP_isError()) {
1045 if (isset($parsed_sql)) {
1046 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1047 // Here we append the LIMIT added for navigation, to
1048 // enable its display. Adding it higher in the code
1049 // to $sql_query would create a problem when
1050 // using the Refresh or Edit links.
1052 // Only append it on SELECTs.
1055 * @todo what would be the best to do when someone hits Refresh:
1056 * use the current LIMITs ?
1059 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1060 && isset($GLOBALS['sql_limit_to_append'])) {
1061 $query_base = $analyzed_display_query[0]['section_before_limit']
1062 . "\n" . $GLOBALS['sql_limit_to_append']
1063 . $analyzed_display_query[0]['section_after_limit'];
1064 // Need to reparse query
1065 $parsed_sql = PMA_SQP_parse($query_base);
1069 if (! empty($GLOBALS['show_as_php'])) {
1070 $query_base = '$sql = "' . $query_base;
1071 } elseif (! empty($GLOBALS['validatequery'])) {
1073 $query_base = PMA_validateSQL($query_base);
1074 } catch (Exception
$e) {
1075 PMA_Message
::error(__('Failed to connect to SQL validator!'))->display();
1077 } elseif (isset($parsed_sql)) {
1078 $query_base = PMA_formatSql($parsed_sql, $query_base);
1081 // Prepares links that may be displayed to edit/explain the query
1082 // (don't go to default pages, we must go to the page
1083 // where the query box is available)
1085 // Basic url query part
1086 $url_params = array();
1087 if (! isset($GLOBALS['db'])) {
1088 $GLOBALS['db'] = '';
1090 if (strlen($GLOBALS['db'])) {
1091 $url_params['db'] = $GLOBALS['db'];
1092 if (strlen($GLOBALS['table'])) {
1093 $url_params['table'] = $GLOBALS['table'];
1094 $edit_link = 'tbl_sql.php';
1096 $edit_link = 'db_sql.php';
1099 $edit_link = 'server_sql.php';
1102 // Want to have the query explained (Mike Beck 2002-05-22)
1103 // but only explain a SELECT (that has not been explained)
1104 /* SQL-Parser-Analyzer */
1106 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1107 $explain_params = $url_params;
1108 // Detect if we are validating as well
1109 // To preserve the validate uRL data
1110 if (! empty($GLOBALS['validatequery'])) {
1111 $explain_params['validatequery'] = 1;
1114 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1115 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1116 $_message = __('Explain SQL');
1117 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1118 $explain_params['sql_query'] = substr($sql_query, 8);
1119 $_message = __('Skip Explain SQL');
1121 if (isset($explain_params['sql_query'])) {
1122 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1123 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1127 $url_params['sql_query'] = $sql_query;
1128 $url_params['show_query'] = 1;
1130 // even if the query is big and was truncated, offer the chance
1131 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1132 if (! empty($cfg['SQLQuery']['Edit'])) {
1133 if ($cfg['EditInWindow'] == true) {
1134 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1139 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1140 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1145 $url_qpart = PMA_generate_common_url($url_params);
1147 // Also we would like to get the SQL formed in some nice
1148 // php-code (Mike Beck 2002-05-22)
1149 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1150 $php_params = $url_params;
1152 if (! empty($GLOBALS['show_as_php'])) {
1153 $_message = __('Without PHP Code');
1155 $php_params['show_as_php'] = 1;
1156 $_message = __('Create PHP Code');
1159 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1160 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1162 if (isset($GLOBALS['show_as_php'])) {
1163 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1164 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1171 if (! empty($cfg['SQLQuery']['Refresh'])
1172 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1173 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1174 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1179 if (! empty($cfg['SQLValidator']['use'])
1180 && ! empty($cfg['SQLQuery']['Validate'])) {
1181 $validate_params = $url_params;
1182 if (!empty($GLOBALS['validatequery'])) {
1183 $validate_message = __('Skip Validate SQL') ;
1185 $validate_params['validatequery'] = 1;
1186 $validate_message = __('Validate SQL') ;
1189 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1190 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1192 $validate_link = '';
1195 if (!empty($GLOBALS['validatequery'])) {
1196 echo '<div class="sqlvalidate">';
1198 echo '<code class="sql">';
1200 if ($query_too_big) {
1201 echo $shortened_query_base;
1206 //Clean up the end of the PHP
1207 if (! empty($GLOBALS['show_as_php'])) {
1210 if (!empty($GLOBALS['validatequery'])) {
1216 echo '<div class="tools">';
1217 // avoid displaying a Profiling checkbox that could
1218 // be checked, which would reexecute an INSERT, for example
1219 if (! empty($refresh_link)) {
1220 PMA_profilingCheckbox($sql_query);
1222 // if needed, generate an invisible form that contains controls for the
1223 // Inline link; this way, the behavior of the Inline link does not
1224 // depend on the profiling support or on the refresh link
1225 if (empty($refresh_link) ||
! PMA_profilingSupported()) {
1226 echo '<form action="sql.php" method="post">';
1227 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1228 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1232 // in the tools div, only display the Inline link when not in ajax
1233 // mode because 1) it currently does not work and 2) we would
1234 // have two similar mechanisms on the page for the same goal
1235 if ($GLOBALS['is_ajax_request'] === false) {
1236 // see in js/functions.js the jQuery code attached to id inline_edit
1237 // document.write conflicts with jQuery, hence used $().append()
1238 echo "<script type=\"text/javascript\">\n" .
1240 "$('.tools').append('[<a href=\"#\" title=\"" .
1241 PMA_escapeJsString(__('Inline edit of this query')) .
1242 "\" id=\"inline_edit\">" .
1243 PMA_escapeJsString(__('Inline')) .
1248 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1251 echo '</div><br />' . "\n";
1253 // If we are in an Ajax request, we have most probably been called in
1254 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1255 // to PMA_ajaxResponse(), which will encode it for JSON.
1256 if( $GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message']) ) {
1257 $buffer_contents = ob_get_contents();
1259 return $buffer_contents;
1261 } // end of the 'PMA_showMessage()' function
1264 * Verifies if current MySQL server supports profiling
1266 * @uses $_SESSION['profiling_supported'] for caching
1267 * @uses $GLOBALS['server']
1268 * @uses PMA_DBI_fetch_value()
1269 * @uses PMA_MYSQL_INT_VERSION
1272 * @return boolean whether profiling is supported
1275 function PMA_profilingSupported()
1277 if (! PMA_cacheExists('profiling_supported', true)) {
1278 // 5.0.37 has profiling but for example, 5.1.20 does not
1279 // (avoid a trip to the server for MySQL before 5.0.37)
1280 // and do not set a constant as we might be switching servers
1281 if (defined('PMA_MYSQL_INT_VERSION')
1282 && PMA_MYSQL_INT_VERSION
>= 50037
1283 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1284 PMA_cacheSet('profiling_supported', true, true);
1286 PMA_cacheSet('profiling_supported', false, true);
1290 return PMA_cacheGet('profiling_supported', true);
1294 * Displays a form with the Profiling checkbox
1296 * @param string $sql_query
1300 function PMA_profilingCheckbox($sql_query)
1302 if (PMA_profilingSupported()) {
1303 echo '<form action="sql.php" method="post">' . "\n";
1304 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1305 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1306 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1307 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1308 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1309 echo '</form>' . "\n";
1314 * Displays the results of SHOW PROFILE
1316 * @param array the results
1317 * @param boolean show chart
1321 function PMA_profilingResults($profiling_results, $show_chart = false)
1323 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1324 echo '<div style="float: left;">';
1325 echo '<table>' . "\n";
1326 echo ' <tr>' . "\n";
1327 echo ' <th>' . __('Status') . '</th>' . "\n";
1328 echo ' <th>' . __('Time') . '</th>' . "\n";
1329 echo ' </tr>' . "\n";
1331 foreach($profiling_results as $one_result) {
1332 echo ' <tr>' . "\n";
1333 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1334 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1337 echo '</table>' . "\n";
1341 require_once './libraries/chart.lib.php';
1342 echo '<div style="float: left;">';
1343 PMA_chart_profiling($profiling_results);
1347 echo '</fieldset>' . "\n";
1351 * Formats $value to byte view
1353 * @param double the value to format
1354 * @param integer the sensitiveness
1355 * @param integer the number of decimals to retain
1357 * @return array the formatted value and its unit
1361 * @version 1.2 - 18 July 2002
1363 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1365 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1366 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1368 $dh = PMA_pow(10, $comma);
1369 $li = PMA_pow(10, $limes);
1370 $return_value = $value;
1371 $unit = $byteUnits[0];
1373 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1374 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1375 // use 1024.0 to avoid integer overflow on 64-bit machines
1376 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1377 $unit = $byteUnits[$d];
1382 if ($unit != $byteUnits[0]) {
1383 // if the unit is not bytes (as represented in current language)
1384 // reformat with max length of 5
1385 // 4th parameter=true means do not reformat if value < 1
1386 $return_value = PMA_formatNumber($value, 5, $comma, true);
1388 // do not reformat, just handle the locale
1389 $return_value = PMA_formatNumber($value, 0);
1392 return array(trim($return_value), $unit);
1393 } // end of the 'PMA_formatByteDown' function
1396 * Changes thousands and decimal separators to locale specific values.
1398 function PMA_localizeNumber($value)
1403 /* l10n: Thousands separator */
1405 /* l10n: Decimal separator */
1412 * Formats $value to the given length and appends SI prefixes
1413 * $comma is not substracted from the length
1414 * with a $length of 0 no truncation occurs, number is only formated
1415 * to the current locale
1419 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1420 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1421 * echo PMA_formatNumber(-0.003, 6); // -3 m
1422 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1423 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1424 * echo PMA_formatNumber(0, 6); // 0
1427 * @param double $value the value to format
1428 * @param integer $length the max length
1429 * @param integer $comma the number of decimals to retain
1430 * @param boolean $only_down do not reformat numbers below 1
1432 * @return string the formatted value and its unit
1436 * @version 1.1.0 - 2005-10-27
1438 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1440 //number_format is not multibyte safe, str_replace is safe
1441 if ($length === 0) {
1442 return PMA_localizeNumber(number_format($value, $comma));
1445 // this units needs no translation, ISO
1466 // we need at least 3 digits to be displayed
1467 if (3 > $length +
$comma) {
1468 $length = 3 - $comma;
1471 // check for negative value to retain sign
1474 $value = abs($value);
1479 $dh = PMA_pow(10, $comma);
1480 $li = PMA_pow(10, $length);
1484 for ($d = 8; $d >= 0; $d--) {
1485 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1486 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1491 } elseif (!$only_down && (float) $value !== 0.0) {
1492 for ($d = -8; $d <= 8; $d++
) {
1493 // force using pow() because of the negative exponent
1494 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1495 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1500 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1502 //number_format is not multibyte safe, str_replace is safe
1503 $value = PMA_localizeNumber(number_format($value, $comma));
1505 return $sign . $value . ' ' . $unit;
1506 } // end of the 'PMA_formatNumber' function
1509 * Returns the number of bytes when a formatted size is given
1511 * @param string $size the size expression (for example 8MB)
1513 * @return integer The numerical part of the expression (for example 8)
1515 function PMA_extractValueFromFormattedSize($formatted_size)
1519 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1520 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1521 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1522 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1523 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1524 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1526 return $return_value;
1527 }// end of the 'PMA_extractValueFromFormattedSize' function
1530 * Writes localised date
1532 * @param string the current timestamp
1534 * @return string the formatted date
1538 function PMA_localisedDate($timestamp = -1, $format = '')
1541 /* l10n: Short month name */
1543 /* l10n: Short month name */
1545 /* l10n: Short month name */
1547 /* l10n: Short month name */
1549 /* l10n: Short month name */
1550 _pgettext('Short month name', 'May'),
1551 /* l10n: Short month name */
1553 /* l10n: Short month name */
1555 /* l10n: Short month name */
1557 /* l10n: Short month name */
1559 /* l10n: Short month name */
1561 /* l10n: Short month name */
1563 /* l10n: Short month name */
1565 $day_of_week = array(
1566 /* l10n: Short week day name */
1568 /* l10n: Short week day name */
1570 /* l10n: Short week day name */
1572 /* l10n: Short week day name */
1574 /* l10n: Short week day name */
1576 /* l10n: Short week day name */
1578 /* l10n: Short week day name */
1581 if ($format == '') {
1582 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1583 $format = __('%B %d, %Y at %I:%M %p');
1586 if ($timestamp == -1) {
1587 $timestamp = time();
1590 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1591 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1593 return strftime($date, $timestamp);
1594 } // end of the 'PMA_localisedDate()' function
1598 * returns a tab for tabbed navigation.
1599 * If the variables $link and $args ar left empty, an inactive tab is created
1601 * @uses $GLOBALS['PMA_PHP_SELF']
1602 * @uses $GLOBALS['active_page']
1603 * @uses $GLOBALS['url_query']
1604 * @uses $cfg['MainPageIconic']
1605 * @uses $GLOBALS['pmaThemeImage']
1606 * @uses PMA_generate_common_url()
1607 * @uses E_USER_NOTICE
1608 * @uses htmlentities()
1611 * @uses trigger_error()
1612 * @uses array_merge()
1614 * @param array $tab array with all options
1615 * @param array $url_params
1616 * @return string html code for one tab, a link if valid otherwise a span
1619 function PMA_generate_html_tab($tab, $url_params = array())
1635 $tab = array_merge($defaults, $tab);
1637 // determine additionnal style-class
1638 if (empty($tab['class'])) {
1639 if ($tab['text'] == __('Empty')
1640 ||
$tab['text'] == __('Drop')) {
1641 $tab['class'] = 'caution';
1642 } elseif (! empty($tab['active'])
1643 ||
PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1644 $tab['class'] = 'active';
1645 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1646 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1647 && empty($tab['warning'])) {
1648 $tab['class'] = 'active';
1652 if (!empty($tab['warning'])) {
1653 $tab['class'] .= ' warning';
1654 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1657 // If there are any tab specific URL parameters, merge those with the general URL parameters
1658 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1659 $url_params = array_merge($url_params, $tab['url_params']);
1663 if (!empty($tab['link'])) {
1664 $tab['link'] = htmlentities($tab['link']);
1665 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1666 if (! empty($tab['args'])) {
1667 foreach ($tab['args'] as $param => $value) {
1668 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1669 . urlencode($value);
1674 if (! empty($tab['fragment'])) {
1675 $tab['link'] .= $tab['fragment'];
1678 // display icon, even if iconic is disabled but the link-text is missing
1679 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1680 && isset($tab['icon'])) {
1681 // avoid generating an alt tag, because it only illustrates
1682 // the text that follows and if browser does not display
1683 // images, the text is duplicated
1684 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1685 .'%1$s" width="16" height="16" alt="" />%2$s';
1686 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1688 // check to not display an empty link-text
1689 elseif (empty($tab['text'])) {
1691 trigger_error('empty linktext in function ' . __FUNCTION__
. '()',
1695 //Set the id for the tab, if set in the params
1696 $id_string = ( empty($tab['id']) ?
'' : ' id="'.$tab['id'].'" ' );
1697 $out = '<li' . ($tab['class'] == 'active' ?
' class="active"' : '') . '>';
1699 if (!empty($tab['link'])) {
1700 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1702 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1703 . $tab['text'] . '</a>';
1705 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1706 . $tab['text'] . '</span>';
1711 } // end of the 'PMA_generate_html_tab()' function
1714 * returns html-code for a tab navigation
1716 * @uses PMA_generate_html_tab()
1717 * @uses htmlentities()
1718 * @param array $tabs one element per tab
1719 * @param string $url_params
1720 * @return string html-code for tab-navigation
1722 function PMA_generate_html_tabs($tabs, $url_params)
1724 $tag_id = 'topmenu';
1726 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1727 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1729 foreach ($tabs as $tab) {
1730 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1735 .'<div class="clearfloat"></div>'
1738 return $tab_navigation;
1743 * Displays a link, or a button if the link's URL is too large, to
1744 * accommodate some browsers' limitations
1746 * @param string the URL
1747 * @param string the link message
1748 * @param mixed $tag_params string: js confirmation
1749 * array: additional tag params (f.e. style="")
1750 * @param boolean $new_form we set this to false when we are already in
1751 * a form, to avoid generating nested forms
1753 * @return string the results to be echoed or saved in an array
1755 function PMA_linkOrButton($url, $message, $tag_params = array(),
1756 $new_form = true, $strip_img = false, $target = '')
1758 $url_length = strlen($url);
1759 // with this we should be able to catch case of image upload
1760 // into a (MEDIUM) BLOB; not worth generating even a form for these
1761 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1765 if (! is_array($tag_params)) {
1767 $tag_params = array();
1769 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1773 if (! empty($target)) {
1774 $tag_params['target'] = htmlentities($target);
1777 $tag_params_strings = array();
1778 foreach ($tag_params as $par_name => $par_value) {
1779 // htmlspecialchars() only on non javascript
1780 $par_value = substr($par_name, 0, 2) == 'on'
1782 : htmlspecialchars($par_value);
1783 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1786 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1787 // no whitespace within an <a> else Safari will make it part of the link
1788 $ret = "\n" . '<a href="' . $url . '" '
1789 . implode(' ', $tag_params_strings) . '>'
1790 . $message . '</a>' . "\n";
1792 // no spaces (linebreaks) at all
1793 // or after the hidden fields
1794 // IE will display them all
1796 // add class=link to submit button
1797 if (empty($tag_params['class'])) {
1798 $tag_params['class'] = 'link';
1801 // decode encoded url separators
1802 $separator = PMA_get_arg_separator();
1803 // on most places separator is still hard coded ...
1804 if ($separator !== '&') {
1805 // ... so always replace & with $separator
1806 $url = str_replace(htmlentities('&'), $separator, $url);
1807 $url = str_replace('&', $separator, $url);
1809 $url = str_replace(htmlentities($separator), $separator, $url);
1812 $url_parts = parse_url($url);
1813 $query_parts = explode($separator, $url_parts['query']);
1815 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1816 . ' method="post"' . $target . ' style="display: inline;">';
1818 $subname_close = '';
1821 $query_parts[] = 'redirect=' . $url_parts['path'];
1822 if (empty($GLOBALS['subform_counter'])) {
1823 $GLOBALS['subform_counter'] = 0;
1825 $GLOBALS['subform_counter']++
;
1827 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1828 $subname_close = ']';
1829 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1831 foreach ($query_parts as $query_pair) {
1832 list($eachvar, $eachval) = explode('=', $query_pair);
1833 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1834 . $subname_close . '" value="'
1835 . htmlspecialchars(urldecode($eachval)) . '" />';
1838 if (stristr($message, '<img')) {
1840 $message = trim(strip_tags($message));
1841 $ret .= '<input type="submit"' . $submit_name . ' '
1842 . implode(' ', $tag_params_strings)
1843 . ' value="' . htmlspecialchars($message) . '" />';
1845 $displayed_message = htmlspecialchars(
1846 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1848 $ret .= '<input type="image"' . $submit_name . ' '
1849 . implode(' ', $tag_params_strings)
1850 . ' src="' . preg_replace(
1851 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1852 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1855 $message = trim(strip_tags($message));
1856 $ret .= '<input type="submit"' . $submit_name . ' '
1857 . implode(' ', $tag_params_strings)
1858 . ' value="' . htmlspecialchars($message) . '" />';
1863 } // end if... else...
1866 } // end of the 'PMA_linkOrButton()' function
1870 * Returns a given timespan value in a readable format.
1874 * @param int the timespan
1876 * @return string the formatted value
1878 function PMA_timespanFormat($seconds)
1880 $return_string = '';
1881 $days = floor($seconds / 86400);
1883 $seconds -= $days * 86400;
1885 $hours = floor($seconds / 3600);
1886 if ($days > 0 ||
$hours > 0) {
1887 $seconds -= $hours * 3600;
1889 $minutes = floor($seconds / 60);
1890 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1891 $seconds -= $minutes * 60;
1893 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1897 * Takes a string and outputs each character on a line for itself. Used
1898 * mainly for horizontalflipped display mode.
1899 * Takes care of special html-characters.
1900 * Fulfills todo-item
1901 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1903 * @todo add a multibyte safe function PMA_STR_split()
1905 * @param string The string
1906 * @param string The Separator (defaults to "<br />\n")
1909 * @return string The flipped string
1911 function PMA_flipstring($string, $Separator = "<br />\n")
1913 $format_string = '';
1916 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++
) {
1917 $char = $string{$i};
1921 $format_string .= $charbuff;
1923 } elseif ($char == ';' && !empty($charbuff)) {
1924 $format_string .= $charbuff . $char;
1927 } elseif (! empty($charbuff)) {
1930 $format_string .= $char;
1934 // do not add separator after the last character
1935 if ($append && ($i != $str_len - 1)) {
1936 $format_string .= $Separator;
1940 return $format_string;
1945 * Function added to avoid path disclosures.
1946 * Called by each script that needs parameters, it displays
1947 * an error message and, by default, stops the execution.
1949 * Not sure we could use a strMissingParameter message here,
1950 * would have to check if the error message file is always available
1952 * @todo localize error message
1953 * @todo use PMA_fatalError() if $die === true?
1954 * @uses PMA_getenv()
1955 * @uses header_meta_style.inc.php
1956 * @uses $GLOBALS['PMA_PHP_SELF']
1958 * @param array The names of the parameters needed by the calling
1960 * @param boolean Stop the execution?
1961 * (Set this manually to false in the calling script
1962 * until you know all needed parameters to check).
1963 * @param boolean Whether to include this list in checking for special params.
1964 * @global string path to current script
1965 * @global boolean flag whether any special variable was required
1969 function PMA_checkParameters($params, $die = true, $request = true)
1971 global $checked_special;
1973 if (!isset($checked_special)) {
1974 $checked_special = false;
1977 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1978 $found_error = false;
1979 $error_message = '';
1981 foreach ($params as $param) {
1982 if ($request && $param != 'db' && $param != 'table') {
1983 $checked_special = true;
1986 if (!isset($GLOBALS[$param])) {
1987 $error_message .= $reported_script_name
1988 . ': Missing parameter: ' . $param
1989 . PMA_showDocu('faqmissingparameters')
1991 $found_error = true;
1996 * display html meta tags
1998 require_once './libraries/header_meta_style.inc.php';
1999 echo '</head><body><p>' . $error_message . '</p></body></html>';
2007 * Function to generate unique condition for specified row.
2009 * @uses $GLOBALS['analyzed_sql'][0]
2010 * @uses PMA_DBI_field_flags()
2011 * @uses PMA_backquote()
2012 * @uses PMA_sqlAddslashes()
2013 * @uses PMA_printable_bit_value()
2016 * @uses preg_replace()
2017 * @param resource $handle current query result
2018 * @param integer $fields_cnt number of fields
2019 * @param array $fields_meta meta information about fields
2020 * @param array $row current row
2021 * @param boolean $force_unique generate condition only on pk or unique
2024 * @return string the calculated condition and whether condition is unique
2026 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
2030 $nonprimary_condition = '';
2031 $preferred_condition = '';
2033 for ($i = 0; $i < $fields_cnt; ++
$i) {
2035 $field_flags = PMA_DBI_field_flags($handle, $i);
2036 $meta = $fields_meta[$i];
2038 // do not use a column alias in a condition
2039 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
2040 $meta->orgname
= $meta->name
;
2042 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2043 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2044 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2046 // need (string) === (string)
2047 // '' !== 0 but '' == 0
2048 if ((string) $select_expr['alias'] === (string) $meta->name
) {
2049 $meta->orgname
= $select_expr['column'];
2056 // Do not use a table alias in a condition.
2058 // select * from galerie x WHERE
2059 //(select count(*) from galerie y where y.datum=x.datum)>1
2061 // But orgtable is present only with mysqli extension so the
2062 // fix is only for mysqli.
2063 // Also, do not use the original table name if we are dealing with
2064 // a view because this view might be updatable.
2065 // (The isView() verification should not be costly in most cases
2066 // because there is some caching in the function).
2067 if (isset($meta->orgtable
) && $meta->table
!= $meta->orgtable
&& ! PMA_Table
::isView($GLOBALS['db'], $meta->table
)) {
2068 $meta->table
= $meta->orgtable
;
2071 // to fix the bug where float fields (primary or not)
2072 // can't be matched because of the imprecision of
2073 // floating comparison, use CONCAT
2074 // (also, the syntax "CONCAT(field) IS NULL"
2075 // that we need on the next "if" will work)
2076 if ($meta->type
== 'real') {
2077 $condition = ' CONCAT(' . PMA_backquote($meta->table
) . '.'
2078 . PMA_backquote($meta->orgname
) . ') ';
2080 $condition = ' ' . PMA_backquote($meta->table
) . '.'
2081 . PMA_backquote($meta->orgname
) . ' ';
2082 } // end if... else...
2084 if (!isset($row[$i]) ||
is_null($row[$i])) {
2085 $condition .= 'IS NULL AND';
2087 // timestamp is numeric on some MySQL 4.1
2088 // for real we use CONCAT above and it should compare to string
2089 if ($meta->numeric && $meta->type
!= 'timestamp' && $meta->type
!= 'real') {
2090 $condition .= '= ' . $row[$i] . ' AND';
2091 } elseif (($meta->type
== 'blob' ||
$meta->type
== 'string')
2092 // hexify only if this is a true not empty BLOB or a BINARY
2093 && stristr($field_flags, 'BINARY')
2094 && !empty($row[$i])) {
2095 // do not waste memory building a too big condition
2096 if (strlen($row[$i]) < 1000) {
2097 // use a CAST if possible, to avoid problems
2098 // if the field contains wildcard characters % or _
2099 $condition .= '= CAST(0x' . bin2hex($row[$i])
2100 . ' AS BINARY) AND';
2102 // this blob won't be part of the final condition
2105 } elseif ($meta->type
== 'bit') {
2106 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length
) . "' AND";
2108 $condition .= '= \''
2109 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2112 if ($meta->primary_key
> 0) {
2113 $primary_key .= $condition;
2114 } elseif ($meta->unique_key
> 0) {
2115 $unique_key .= $condition;
2117 $nonprimary_condition .= $condition;
2120 // Correction University of Virginia 19991216:
2121 // prefer primary or unique keys for condition,
2122 // but use conjunction of all values if no primary key
2123 $clause_is_unique = true;
2125 $preferred_condition = $primary_key;
2126 } elseif ($unique_key) {
2127 $preferred_condition = $unique_key;
2128 } elseif (! $force_unique) {
2129 $preferred_condition = $nonprimary_condition;
2130 $clause_is_unique = false;
2133 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2134 return(array($where_clause, $clause_is_unique));
2138 * Generate a button or image tag
2140 * @uses PMA_USR_BROWSER_AGENT
2141 * @uses $GLOBALS['pmaThemeImage']
2142 * @uses $GLOBALS['cfg']['PropertiesIconic']
2143 * @param string name of button element
2144 * @param string class of button element
2145 * @param string name of image element
2146 * @param string text to display
2147 * @param string image to display
2151 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2154 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2155 echo ' <input type="submit" name="' . $button_name . '"'
2156 .' value="' . htmlspecialchars($text) . '"'
2157 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2161 /* Opera has trouble with <input type="image"> */
2162 /* IE has trouble with <button> */
2163 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2164 echo '<button class="' . $button_class . '" type="submit"'
2165 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2166 .' title="' . htmlspecialchars($text) . '">' . "\n"
2167 . PMA_getIcon($image, $text)
2168 .'</button>' . "\n";
2170 echo '<input type="image" name="' . $image_name . '" value="'
2171 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2173 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ?
' ' . htmlspecialchars($text) : '') . "\n";
2178 * Generate a pagination selector for browsing resultsets
2180 * @todo $url is not javascript escaped!?
2182 * @param string URL for the JavaScript
2183 * @param string Number of rows in the pagination set
2184 * @param string current page number
2185 * @param string number of total pages
2186 * @param string If the number of pages is lower than this
2187 * variable, no pages will be omitted in
2189 * @param string How many rows at the beginning should always
2191 * @param string How many rows at the end should always
2193 * @param string Percentage of calculation page offsets to
2194 * hop to a next page
2195 * @param string Near the current page, how many pages should
2196 * be considered "nearby" and displayed as
2198 * @param string The prompt to display (sometimes empty)
2202 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2203 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2204 $range = 10, $prompt = '')
2206 $increment = floor($nbTotalPage / $percent);
2207 $pageNowMinusRange = ($pageNow - $range);
2208 $pageNowPlusRange = ($pageNow +
$range);
2211 . ' <select id="pageselector" name="pos" >' . "\n";
2212 if ($nbTotalPage < $showAll) {
2213 $pages = range(1, $nbTotalPage);
2217 // Always show first X pages
2218 for ($i = 1; $i <= $sliceStart; $i++
) {
2222 // Always show last X pages
2223 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2227 // Based on the number of results we add the specified
2228 // $percent percentage to each page number,
2229 // so that we have a representing page number every now and then to
2230 // immediately jump to specific pages.
2231 // As soon as we get near our currently chosen page ($pageNow -
2232 // $range), every page number will be shown.
2234 $x = $nbTotalPage - $sliceEnd;
2235 $met_boundary = false;
2237 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2238 // If our pageselector comes near the current page, we use 1
2239 // counter increments
2241 $met_boundary = true;
2243 // We add the percentage increment to our current page to
2244 // hop to the next one in range
2247 // Make sure that we do not cross our boundaries.
2248 if ($i > $pageNowMinusRange && ! $met_boundary) {
2249 $i = $pageNowMinusRange;
2253 if ($i > 0 && $i <= $x) {
2258 // Since because of ellipsing of the current page some numbers may be double,
2259 // we unify our array:
2261 $pages = array_unique($pages);
2264 foreach ($pages as $i) {
2265 if ($i == $pageNow) {
2266 $selected = 'selected="selected" style="font-weight: bold"';
2270 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2273 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2280 * Generate navigation for a list
2282 * @todo use $pos from $_url_params
2284 * @param integer number of elements in the list
2285 * @param integer current position in the list
2286 * @param array url parameters
2287 * @param string script name for form target
2288 * @param string target frame
2289 * @param integer maximum number of elements to display from the list
2293 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2295 if ($max_count < $count) {
2296 echo 'frame_navigation' == $frame ?
'<div id="navidbpageselector">' . "\n" : '';
2297 echo __('Page number:');
2298 echo 'frame_navigation' == $frame ?
'<br />' : ' ';
2300 // Move to the beginning or to the previous page
2302 // patch #474210 - part 1
2303 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2304 $caption1 = '<<';
2305 $caption2 = ' < ';
2306 $title1 = ' title="' . __('Begin') . '"';
2307 $title2 = ' title="' . __('Previous') . '"';
2309 $caption1 = __('Begin') . ' <<';
2310 $caption2 = __('Previous') . ' <';
2313 } // end if... else...
2314 $_url_params['pos'] = 0;
2315 echo '<a' . $title1 . ' href="' . $script
2316 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2317 . $caption1 . '</a>';
2318 $_url_params['pos'] = $pos - $max_count;
2319 echo '<a' . $title2 . ' href="' . $script
2320 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2321 . $caption2 . '</a>';
2324 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2325 echo PMA_generate_common_hidden_inputs($_url_params);
2326 echo PMA_pageselector(
2327 $script . PMA_generate_common_url($_url_params) . '&',
2329 floor(($pos +
1) / $max_count) +
1,
2330 ceil($count / $max_count));
2333 if ($pos +
$max_count < $count) {
2334 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2335 $caption3 = ' > ';
2336 $caption4 = '>>';
2337 $title3 = ' title="' . __('Next') . '"';
2338 $title4 = ' title="' . __('End') . '"';
2340 $caption3 = '> ' . __('Next');
2341 $caption4 = '>> ' . __('End');
2344 } // end if... else...
2345 $_url_params['pos'] = $pos +
$max_count;
2346 echo '<a' . $title3 . ' href="' . $script
2347 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2348 . $caption3 . '</a>';
2349 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2350 if ($_url_params['pos'] == $count) {
2351 $_url_params['pos'] = $count - $max_count;
2353 echo '<a' . $title4 . ' href="' . $script
2354 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2355 . $caption4 . '</a>';
2358 if ('frame_navigation' == $frame) {
2359 echo '</div>' . "\n";
2365 * replaces %u in given path with current user name
2369 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2372 * @uses $cfg['Server']['user']
2374 * @uses str_replace()
2375 * @param string $dir with wildcard for user
2376 * @return string per user directory
2378 function PMA_userDir($dir)
2380 // add trailing slash
2381 if (substr($dir, -1) != '/') {
2385 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2389 * returns html code for db link to default db page
2391 * @uses $cfg['DefaultTabDatabase']
2392 * @uses $GLOBALS['db']
2393 * @uses PMA_generate_common_url()
2394 * @uses PMA_unescape_mysql_wildcards()
2397 * @uses htmlspecialchars()
2398 * @param string $database
2399 * @return string html link to default db page
2401 function PMA_getDbLink($database = null)
2403 if (!strlen($database)) {
2404 if (!strlen($GLOBALS['db'])) {
2407 $database = $GLOBALS['db'];
2409 $database = PMA_unescape_mysql_wildcards($database);
2412 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2413 .' title="' . sprintf(__('Jump to database "%s".'), htmlspecialchars($database)) . '">'
2414 .htmlspecialchars($database) . '</a>';
2418 * Displays a lightbulb hint explaining a known external bug
2419 * that affects a functionality
2421 * @uses PMA_MYSQL_INT_VERSION
2422 * @uses PMA_showHint()
2424 * @param string $functionality localized message explaining the func.
2425 * @param string $component 'mysql' (eventually, 'php')
2426 * @param string $minimum_version of this component
2427 * @param string $bugref bug reference for this component
2429 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2431 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION
< $minimum_version) {
2432 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, 'http://bugs.mysql.com/' . $bugref));
2437 * Generates and echoes an HTML checkbox
2439 * @param string $html_field_name the checkbox HTML field
2440 * @param string $label
2441 * @param boolean $checked is it initially checked?
2442 * @param boolean $onclick should it submit the form on click?
2444 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2446 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>';
2450 * Generates and echoes a set of radio HTML fields
2452 * @uses htmlspecialchars()
2453 * @param string $html_field_name the radio HTML field
2454 * @param array $choices the choices values and labels
2455 * @param string $checked_choice the choice to check by default
2456 * @param boolean $line_break whether to add an HTML line break after a choice
2457 * @param boolean $escape_label whether to use htmlspecialchars() on label
2458 * @param string $class enclose each choice with a div of this class
2460 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2461 foreach ($choices as $choice_value => $choice_label) {
2462 if (! empty($class)) {
2463 echo '<div class="' . $class . '">';
2465 $html_field_id = $html_field_name . '_' . $choice_value;
2466 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2467 if ($choice_value == $checked_choice) {
2468 echo ' checked="checked"';
2471 echo '<label for="' . $html_field_id . '">' . ($escape_label ?
htmlspecialchars($choice_label) : $choice_label) . '</label>';
2475 if (! empty($class)) {
2483 * Generates and returns an HTML dropdown
2485 * @uses htmlspecialchars()
2486 * @param string $select_name
2487 * @param array $choices the choices values
2488 * @param string $active_choice the choice to select by default
2489 * @param string $id the id of the select element; can be different in case
2490 * the dropdown is present more than once on the page
2491 * @todo support titles
2493 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2495 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2496 foreach ($choices as $one_choice_value => $one_choice_label) {
2497 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2498 if ($one_choice_value == $active_choice) {
2499 $result .= ' selected="selected"';
2501 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2503 $result .= '</select>';
2508 * Generates a slider effect (jQjuery)
2509 * Takes care of generating the initial <div> and the link
2510 * controlling the slider; you have to generate the </div> yourself
2511 * after the sliding section.
2513 * @uses $GLOBALS['cfg']['InitialSlidersState']
2514 * @param string $id the id of the <div> on which to apply the effect
2515 * @param string $message the message to show as a link
2517 function PMA_generate_slider_effect($id, $message)
2519 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2520 echo '<div id="' . $id . '">';
2524 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2525 * opening the <div> with PHP itself instead of JavaScript.
2527 * @todo find a better solution that uses $.append(), the recommended method
2528 * maybe by using an additional param, the id of the div to append to
2531 <div id
="<?php echo $id; ?>" <?php
echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ?
' style="display: none; overflow:auto;"' : ''; ?
>>
2532 <script type
="text/javascript">
2535 function PMA_set_status_label_
<?php
echo $id; ?
>() {
2536 if ($
('#<?php echo $id; ?>').css('display') == 'none') {
2537 $
('#anchor_status_<?php echo $id; ?>').text('+ ');
2539 $
('#anchor_status_<?php echo $id; ?>').text('- ');
2543 $
(document
).ready(function() {
2545 $
('<span id="anchor_status_<?php echo $id; ?>"><span>')
2546 .insertBefore('#<?php echo $id; ?>')
2548 PMA_set_status_label_
<?php
echo $id; ?
>();
2550 $
('<a href="#<?php echo $id; ?>" id="anchor_<?php echo $id; ?>"><?php echo htmlspecialchars($message); ?></a>')
2551 .insertBefore('#<?php echo $id; ?>')
2553 // the callback should be the 4th parameter but
2554 // it only works as the second parameter
2555 $
('#<?php echo $id; ?>').toggle('drop', function() {
2556 PMA_set_status_label_
<?php
echo $id; ?
>();
2563 <div id
="<?php echo $id; ?>"></div
>
2569 * Verifies if something is cached in the session
2571 * @param string $var
2572 * @param scalar $server
2575 function PMA_cacheExists($var, $server = 0)
2577 if (true === $server) {
2578 $server = $GLOBALS['server'];
2580 return isset($_SESSION['cache']['server_' . $server][$var]);
2584 * Gets cached information from the session
2586 * @param string $var
2587 * @param scalar $server
2590 function PMA_cacheGet($var, $server = 0)
2592 if (true === $server) {
2593 $server = $GLOBALS['server'];
2595 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2596 return $_SESSION['cache']['server_' . $server][$var];
2603 * Caches information in the session
2605 * @param string $var
2607 * @param integer $server
2610 function PMA_cacheSet($var, $val = null, $server = 0)
2612 if (true === $server) {
2613 $server = $GLOBALS['server'];
2615 $_SESSION['cache']['server_' . $server][$var] = $val;
2619 * Removes cached information from the session
2621 * @param string $var
2622 * @param scalar $server
2624 function PMA_cacheUnset($var, $server = 0)
2626 if (true === $server) {
2627 $server = $GLOBALS['server'];
2629 unset($_SESSION['cache']['server_' . $server][$var]);
2633 * Converts a bit value to printable format;
2634 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2635 * function because in PHP, decbin() supports only 32 bits
2642 * @param numeric $value coming from a BIT field
2643 * @param integer $length
2644 * @return string the printable value
2646 function PMA_printable_bit_value($value, $length) {
2648 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++
) {
2649 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2651 $printable = substr($printable, -$length);
2656 * Verifies whether the value contains a non-printable character
2658 * @uses preg_match()
2659 * @param string $value
2662 function PMA_contains_nonprintable_ascii($value) {
2663 return preg_match('@[^[:print:]]@', $value);
2667 * Converts a BIT type default value
2668 * for example, b'010' becomes 010
2671 * @param string $bit_default_value
2672 * @return string the converted value
2674 function PMA_convert_bit_default_value($bit_default_value) {
2675 return strtr($bit_default_value, array("b" => "", "'" => ""));
2679 * Extracts the various parts from a field type spec
2684 * @param string $fieldspec
2685 * @return array associative array containing type, spec_in_brackets
2686 * and possibly enum_set_values (another array)
2688 function PMA_extractFieldSpec($fieldspec) {
2689 $first_bracket_pos = strpos($fieldspec, '(');
2690 if ($first_bracket_pos) {
2691 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos +
1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2692 // convert to lowercase just to be sure
2693 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2696 $spec_in_brackets = '';
2699 if ('enum' == $type ||
'set' == $type) {
2700 // Define our working vars
2701 $enum_set_values = array();
2706 // While there is another character to process
2707 while (isset($fieldspec[$index])) {
2708 // Grab the char to look at
2709 $char = $fieldspec[$index];
2711 // If it is a single quote, needs to be handled specially
2713 // If we are not currently in a string, begin one
2717 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2719 // Check out the next character (if possible)
2720 $has_next = isset($fieldspec[$index +
1]);
2721 $next = $has_next ?
$fieldspec[$index +
1] : null;
2723 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2724 if (! $has_next ||
$next != "'") {
2725 $enum_set_values[] = $working;
2728 // Otherwise, this is a 'double quote', and can be added to the working string
2729 } elseif ($next == "'") {
2731 // Skip the next char; we already know what it is
2735 // escaping of a quote?
2736 } elseif ('\\' == $char && isset($fieldspec[$index +
1]) && "'" == $fieldspec[$index +
1]) {
2739 // Otherwise, add it to our working string like normal
2743 // Increment character index
2747 $enum_set_values = array();
2752 'spec_in_brackets' => $spec_in_brackets,
2753 'enum_set_values' => $enum_set_values
2758 * Verifies if this table's engine supports foreign keys
2760 * @uses strtoupper()
2761 * @param string $engine
2764 function PMA_foreignkey_supported($engine) {
2765 $engine = strtoupper($engine);
2766 if ('INNODB' == $engine ||
'PBXT' == $engine) {
2774 * Replaces some characters by a displayable equivalent
2776 * @uses str_replace()
2777 * @param string $content
2778 * @return string the content with characters replaced
2780 function PMA_replace_binary_contents($content) {
2781 $result = str_replace("\x00", '\0', $content);
2782 $result = str_replace("\x08", '\b', $result);
2783 $result = str_replace("\x0a", '\n', $result);
2784 $result = str_replace("\x0d", '\r', $result);
2785 $result = str_replace("\x1a", '\Z', $result);
2791 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2794 * @return string with the chars replaced
2797 function PMA_duplicateFirstNewline($string){
2798 $first_occurence = strpos($string, "\r\n");
2799 if ($first_occurence === 0){
2800 $string = "\n".$string;
2806 * get the action word corresponding to a script name
2807 * in order to display it as a title in navigation panel
2810 * @param string a valid value for $cfg['LeftDefaultTabTable']
2811 * or $cfg['DefaultTabTable']
2812 * or $cfg['DefaultTabDatabase']
2814 function PMA_getTitleForTarget($target) {
2817 // Values for $cfg['DefaultTabTable']
2818 'tbl_structure.php' => __('Structure'),
2819 'tbl_sql.php' => __('SQL'),
2820 'tbl_select.php' =>__('Search'),
2821 'tbl_change.php' =>__('Insert'),
2822 'sql.php' => __('Browse'),
2824 // Values for $cfg['DefaultTabDatabase']
2825 'db_structure.php' => __('Structure'),
2826 'db_sql.php' => __('SQL'),
2827 'db_search.php' => __('Search'),
2828 'db_operations.php' => __('Operations'),
2830 return $mapping[$target];
2834 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2836 * @param string Text where to do expansion.
2837 * @param function Function to call for escaping variable values.
2838 * @param array Array with overrides for default parameters (obtained from GLOBALS).
2840 function PMA_expandUserString($string, $escape = NULL, $updates = array()) {
2842 $vars['http_host'] = PMA_getenv('HTTP_HOST') ?
PMA_getenv('HTTP_HOST') : '';
2843 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2844 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2845 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ?
$GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2846 $vars['database'] = $GLOBALS['db'];
2847 $vars['table'] = $GLOBALS['table'];
2848 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION
;
2850 /* Update forced variables */
2851 foreach($updates as $key => $val) {
2855 /* Replacement mapping */
2857 * The __VAR__ ones are for backward compatibility, because user
2858 * might still have it in cookies.
2861 '@HTTP_HOST@' => $vars['http_host'],
2862 '@SERVER@' => $vars['server_name'],
2863 '__SERVER__' => $vars['server_name'],
2864 '@VERBOSE@' => $vars['server_verbose'],
2865 '@VSERVER@' => $vars['server_verbose_or_name'],
2866 '@DATABASE@' => $vars['database'],
2867 '__DB__' => $vars['database'],
2868 '@TABLE@' => $vars['table'],
2869 '__TABLE__' => $vars['table'],
2870 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2873 /* Optional escaping */
2874 if (!is_null($escape)) {
2875 foreach($replace as $key => $val) {
2876 $replace[$key] = $escape($val);
2880 /* Fetch fields list if required */
2881 if (strpos($string, '@FIELDS@') !== FALSE) {
2882 $fields_list = PMA_DBI_fetch_result(
2883 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2884 . '.' . PMA_backquote($GLOBALS['table']));
2886 $field_names = array();
2887 foreach ($fields_list as $field) {
2888 if (!is_null($escape)) {
2889 $field_names[] = $escape($field['Field']);
2891 $field_names[] = $field['Field'];
2895 $replace['@FIELDS@'] = implode(',', $field_names);
2898 /* Do the replacement */
2899 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2903 * function that generates a json output for an ajax request and ends script
2906 * @param boolean success whether the ajax request was successfull
2907 * @param string message string containing the html of the message
2908 * @param array extra_data optional - any other data as part of the json request
2911 * @uses json_encode()
2913 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2915 $response = array();
2916 if( $success == true ) {
2917 $response['success'] = true;
2918 if ($message instanceof PMA_Message
) {
2919 $response['message'] = $message->getDisplay();
2922 $response['message'] = $message;
2926 $response['success'] = false;
2927 if($message instanceof PMA_Message
) {
2928 $response['error'] = $message->getDisplay();
2931 $response['error'] = $message;
2935 // If extra_data has been provided, append it to the response array
2936 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2937 $response = array_merge($response, $extra_data);
2940 // Set the Content-Type header to JSON so that jQuery parses the response correctly
2941 if(!isset($GLOBALS['is_header_sent'])) {
2942 header('Cache-Control: no-cache');
2943 header("Content-Type: application/json");
2945 echo json_encode($response);
2950 * Display the form used to browse anywhere on the local server for the file to import
2952 function PMA_browseUploadFile($max_upload_size) {
2954 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2955 echo '<div id="upload_form_status" style="display: none;"></div>';
2956 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2957 echo '<input type="file" name="import_file" id="input_import_file" />';
2958 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2959 // some browsers should respect this :)
2960 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2964 * Display the form used to select a file to import from the server upload directory
2966 function PMA_selectUploadFile($import_list, $uploaddir) {
2967 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2969 foreach ($import_list as $key => $val) {
2970 if (!empty($extensions)) {
2973 $extensions .= $val['extension'];
2975 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2977 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ?
$local_import_file : '');
2978 if ($files === FALSE) {
2979 PMA_Message
::error(__('The directory you set for upload work cannot be reached'))->display();
2980 } elseif (!empty($files)) {
2982 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2983 echo ' <option value=""> </option>' . "\n";
2985 echo ' </select>' . "\n";
2986 } elseif (empty ($files)) {
2987 echo '<i>There are no files to upload</i>';
2992 * Build titles and icons for action links
2994 * @return array the action titles
2995 * @uses PMA_getIcon()
2997 function PMA_buildActionTitles() {
3000 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
3001 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
3002 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
3003 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
3004 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
3005 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
3006 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
3007 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
3008 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
3009 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
3010 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);