2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Misc functions used all over the scripts.
11 * Exponential expression / raise number into power
13 * @uses function_exists()
20 * @param string pow function use, or false for auto-detect
21 * @return mixed string or float
23 function PMA_pow($base, $exp, $use_function = false)
25 static $pow_function = null;
27 if (null == $pow_function) {
28 if (function_exists('bcpow')) {
29 // BCMath Arbitrary Precision Mathematics Function
30 $pow_function = 'bcpow';
31 } elseif (function_exists('gmp_pow')) {
33 $pow_function = 'gmp_pow';
36 $pow_function = 'pow';
40 if (! $use_function) {
41 $use_function = $pow_function;
44 if ($exp < 0 && 'pow' != $use_function) {
47 switch ($use_function) {
49 // bcscale() needed for testing PMA_pow() with base values < 1
51 $pow = bcpow($base, $exp);
54 $pow = gmp_strval(gmp_pow($base, $exp));
57 $base = (float) $base;
59 $pow = pow($base, $exp);
62 $pow = $use_function($base, $exp);
69 * string PMA_getIcon(string $icon)
71 * @uses $GLOBALS['pmaThemeImage']
72 * @uses $GLOBALS['cfg']['PropertiesIconic']
73 * @uses htmlspecialchars()
74 * @param string $icon name of icon file
75 * @param string $alternate alternate text
76 * @param boolean $container include in container
77 * @param boolean $$force_text whether to force alternate text to be displayed
78 * @return html img tag
80 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
82 $include_icon = false;
83 $include_text = false;
85 $alternate = htmlspecialchars($alternate);
88 if ($GLOBALS['cfg']['PropertiesIconic']) {
93 ||
! (true === $GLOBALS['cfg']['PropertiesIconic'])
95 // $cfg['PropertiesIconic'] is false or both
96 // OR we have no $include_icon
100 if ($include_text && $include_icon && $container) {
101 // we have icon, text and request for container
106 $button .= '<div class="nowrap">';
110 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
111 . ' title="' . $alternate . '" alt="' . $alternate . '"'
112 . ' class="icon" width="16" height="16" />';
115 if ($include_icon && $include_text) {
120 $button .= $alternate;
131 * Displays the maximum size for an upload
133 * @uses __('Max: %s%s')
134 * @uses PMA_formatByteDown()
136 * @param integer the size
138 * @return string the message
142 function PMA_displayMaximumUploadSize($max_upload_size)
144 // I have to reduce the second parameter (sensitiveness) from 6 to 4
145 // to avoid weird results like 512 kKib
146 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
147 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
151 * Generates a hidden field which should indicate to the browser
152 * the maximum size for upload
154 * @param integer the size
156 * @return string the INPUT field
160 function PMA_generateHiddenMaxFileSize($max_size)
162 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
166 * Add slashes before "'" and "\" characters so a value containing them can
167 * be used in a sql comparison.
169 * @uses str_replace()
170 * @param string the string to slash
171 * @param boolean whether the string will be used in a 'LIKE' clause
172 * (it then requires two more escaped sequences) or not
173 * @param boolean whether to treat cr/lfs as escape-worthy entities
174 * (converts \n to \\n, \r to \\r)
176 * @param boolean whether this function is used as part of the
177 * "Create PHP code" dialog
179 * @return string the slashed string
183 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
186 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
188 $a_string = str_replace('\\', '\\\\', $a_string);
192 $a_string = str_replace("\n", '\n', $a_string);
193 $a_string = str_replace("\r", '\r', $a_string);
194 $a_string = str_replace("\t", '\t', $a_string);
198 $a_string = str_replace('\'', '\\\'', $a_string);
200 $a_string = str_replace('\'', '\'\'', $a_string);
204 } // end of the 'PMA_sqlAddslashes()' function
208 * Add slashes before "_" and "%" characters for using them in MySQL
209 * database, table and field names.
210 * Note: This function does not escape backslashes!
212 * @uses str_replace()
213 * @param string the string to escape
215 * @return string the escaped string
219 function PMA_escape_mysql_wildcards($name)
221 $name = str_replace('_', '\\_', $name);
222 $name = str_replace('%', '\\%', $name);
225 } // end of the 'PMA_escape_mysql_wildcards()' function
228 * removes slashes before "_" and "%" characters
229 * Note: This function does not unescape backslashes!
231 * @uses str_replace()
232 * @param string $name the string to escape
233 * @return string the escaped string
236 function PMA_unescape_mysql_wildcards($name)
238 $name = str_replace('\\_', '_', $name);
239 $name = str_replace('\\%', '%', $name);
242 } // end of the 'PMA_unescape_mysql_wildcards()' function
245 * removes quotes (',",`) from a quoted string
247 * checks if the sting is quoted and removes this quotes
249 * @uses str_replace()
251 * @param string $quoted_string string to remove quotes from
252 * @param string $quote type of quote to remove
253 * @return string unqoted string
255 function PMA_unQuote($quoted_string, $quote = null)
259 if (null === $quote) {
267 foreach ($quotes as $quote) {
268 if (substr($quoted_string, 0, 1) === $quote
269 && substr($quoted_string, -1, 1) === $quote) {
270 $unquoted_string = substr($quoted_string, 1, -1);
271 // replace escaped quotes
272 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
273 return $unquoted_string;
277 return $quoted_string;
283 * @todo move into PMA_Sql
284 * @uses PMA_SQP_isError()
285 * @uses PMA_SQP_formatHtml()
286 * @uses PMA_SQP_formatNone()
288 * @param mixed pre-parsed SQL structure
290 * @return string the formatted sql
292 * @global array the configuration array
293 * @global boolean whether the current statement is a multiple one or not
298 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
302 // Check that we actually have a valid set of parsed data
304 // first check for the SQL parser having hit an error
305 if (PMA_SQP_isError()) {
306 return htmlspecialchars($parsed_sql['raw']);
308 // then check for an array
309 if (!is_array($parsed_sql)) {
310 // We don't so just return the input directly
311 // This is intended to be used for when the SQL Parser is turned off
312 $formatted_sql = '<pre>' . "\n"
313 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ?
$unparsed_sql : $parsed_sql) . "\n"
315 return $formatted_sql;
320 switch ($cfg['SQP']['fmtType']) {
322 if ($unparsed_sql != '') {
323 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
325 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
329 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
332 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
333 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
339 return $formatted_sql;
340 } // end of the "PMA_formatSql()" function
344 * Displays a link to the official MySQL documentation
346 * @uses $cfg['MySQLManualType']
347 * @uses $cfg['MySQLManualBase']
348 * @uses $cfg['ReplaceHelpImg']
349 * @uses __('Documentation')
350 * @uses $GLOBALS['pmaThemeImage']
351 * @uses PMA_MYSQL_INT_VERSION
353 * @uses str_replace()
354 * @param string chapter of "HTML, one page per chapter" documentation
355 * @param string contains name of page/anchor that is being linked
356 * @param bool whether to use big icon (like in left frame)
357 * @param string anchor to page part
359 * @return string the html link
363 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
367 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
371 // Fixup for newly used names:
372 $chapter = str_replace('_', '-', strtolower($chapter));
373 $link = str_replace('_', '-', strtolower($link));
375 switch ($cfg['MySQLManualType']) {
377 if (empty($chapter)) {
380 if (empty($anchor)) {
383 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
386 if (empty($anchor)) {
389 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
395 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
396 if (!empty($anchor)) {
397 $url .= '#' . $anchor;
407 if (defined('PMA_MYSQL_INT_VERSION')) {
408 if (PMA_MYSQL_INT_VERSION
>= 50100) {
410 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
411 $lang = _pgettext('$mysql_5_1_doc_lang', 'en');
412 } elseif (PMA_MYSQL_INT_VERSION
>= 50000) {
414 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
415 $lang = _pgettext('$mysql_5_0_doc_lang', 'en');
418 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
419 if (!empty($anchor)) {
420 $url .= '#' . $anchor;
426 return '<a href="' . $url . '" target="mysql_doc">';
427 } elseif ($big_icon) {
428 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>';
429 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
430 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>';
432 return '[<a href="' . $url . '" target="mysql_doc">' . __('Documentation') . '</a>]';
434 } // end of the 'PMA_showMySQLDocu()' function
438 * Displays a link to the phpMyAdmin documentation
440 * @param string anchor in documentation
442 * @return string the html link
446 function PMA_showDocu($anchor) {
447 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
448 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>';
450 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
452 } // end of the 'PMA_showDocu()' function
455 * returns HTML for a footnote marker and add the messsage to the footnotes
457 * @uses $GLOBALS['footnotes']
458 * @param string the error message
459 * @return string html code for a footnote marker
462 function PMA_showHint($message, $bbcode = false, $type = 'notice')
464 if ($message instanceof PMA_Message
) {
465 $key = $message->getHash();
466 $type = $message->getLevel();
468 $key = md5($message);
471 if (! isset($GLOBALS['footnotes'][$key])) {
472 if (empty($GLOBALS['footnotes']) ||
! is_array($GLOBALS['footnotes'])) {
473 $GLOBALS['footnotes'] = array();
475 $nr = count($GLOBALS['footnotes']) +
1;
476 // this is the first instance of this message
478 $GLOBALS['footnotes'][$key] = array(
482 'instance' => $instance
485 $nr = $GLOBALS['footnotes'][$key]['nr'];
486 // another instance of this message (to ensure ids are unique)
487 $instance = ++
$GLOBALS['footnotes'][$key]['instance'];
491 return '[sup]' . $nr . '[/sup]';
494 // footnotemarker used in js/tooltip.js
495 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
499 * Displays a MySQL error message in the right frame.
501 * @uses footer.inc.php
502 * @uses header.inc.php
503 * @uses $GLOBALS['sql_query']
505 * @uses __('SQL query')
506 * @uses $GLOBALS['pmaThemeImage']
508 * @uses __('MySQL said: ')
509 * @uses $GLOBALS['cfg']['PropertiesIconic']
510 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
511 * @uses PMA_backquote()
512 * @uses PMA_DBI_getError()
513 * @uses PMA_formatSql()
514 * @uses PMA_generate_common_hidden_inputs()
515 * @uses PMA_generate_common_url()
516 * @uses PMA_showMySQLDocu()
517 * @uses PMA_sqlAddslashes()
518 * @uses PMA_SQP_isError()
519 * @uses PMA_SQP_parse()
520 * @uses PMA_SQP_getErrorString()
523 * @uses str_replace()
526 * @uses preg_replace()
531 * @uses function_exists()
532 * @uses htmlspecialchars()
535 * @param string the error message
536 * @param string the sql query that failed
537 * @param boolean whether to show a "modify" link or not
538 * @param string the "back" link url (full path is not required)
539 * @param boolean EXIT the page?
541 * @global string the curent table
542 * @global string the current db
546 function PMA_mysqlDie($error_message = '', $the_query = '',
547 $is_modify_link = true, $back_url = '', $exit = true)
552 * start http output, display html headers
554 require_once './libraries/header.inc.php';
556 $error_msg_output = '';
558 if (!$error_message) {
559 $error_message = PMA_DBI_getError();
561 if (!$the_query && !empty($GLOBALS['sql_query'])) {
562 $the_query = $GLOBALS['sql_query'];
565 // --- Added to solve bug #641765
566 // Robbat2 - 12 January 2003, 9:46PM
567 // Revised, Robbat2 - 13 January 2003, 2:59PM
568 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
569 $formatted_sql = htmlspecialchars($the_query);
570 } elseif (empty($the_query) ||
trim($the_query) == '') {
573 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
574 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
576 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
580 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
581 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
582 // if the config password is wrong, or the MySQL server does not
583 // respond, do not show the query that would reveal the
585 if (!empty($the_query) && !strstr($the_query, 'connect')) {
586 // --- Added to solve bug #641765
587 // Robbat2 - 12 January 2003, 9:46PM
588 // Revised, Robbat2 - 13 January 2003, 2:59PM
589 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
590 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
591 $error_msg_output .= '<br />' . "\n";
594 // modified to show the help on sql errors
595 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
596 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
597 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
599 if ($is_modify_link) {
600 $_url_params = array(
601 'sql_query' => $the_query,
604 if (strlen($table)) {
605 $_url_params['db'] = $db;
606 $_url_params['table'] = $table;
607 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
608 } elseif (strlen($db)) {
609 $_url_params['db'] = $db;
610 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
612 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
615 $error_msg_output .= $doedit_goto
616 . PMA_getIcon('b_edit.png', __('Edit'))
619 $error_msg_output .= ' </p>' . "\n"
621 .' ' . $formatted_sql . "\n"
625 $tmp_mysql_error = ''; // for saving the original $error_message
626 if (!empty($error_message)) {
627 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
628 $error_message = htmlspecialchars($error_message);
629 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
631 // modified to show the help on error-returns
632 // (now error-messages-server)
633 $error_msg_output .= '<p>' . "\n"
634 . ' <strong>' . __('MySQL said: ') . '</strong>'
635 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
639 // The error message will be displayed within a CODE segment.
640 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
642 // Replace all non-single blanks with their HTML-counterpart
643 $error_message = str_replace(' ', ' ', $error_message);
644 // Replace TAB-characters with their HTML-counterpart
645 $error_message = str_replace("\t", ' ', $error_message);
646 // Replace linebreaks
647 $error_message = nl2br($error_message);
649 $error_msg_output .= '<code>' . "\n"
650 . $error_message . "\n"
651 . '</code><br />' . "\n";
652 $error_msg_output .= '</div>';
654 $_SESSION['Import_message']['message'] = $error_msg_output;
657 if (! empty($back_url)) {
658 if (strstr($back_url, '?')) {
659 $back_url .= '&no_history=true';
661 $back_url .= '?no_history=true';
664 $_SESSION['Import_message']['go_back_url'] = $back_url;
666 $error_msg_output .= '<fieldset class="tblFooters">';
667 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
668 $error_msg_output .= '</fieldset>' . "\n\n";
671 echo $error_msg_output;
673 * display footer and exit
676 require_once './libraries/footer.inc.php';
678 echo $error_msg_output;
680 } // end of the 'PMA_mysqlDie()' function
683 * Send HTTP header, taking IIS limits into account (600 seems ok)
686 * @uses PMA_COMING_FROM_COOKIE_LOGIN
687 * @uses PMA_get_arg_separator()
692 * @uses session_write_close()
693 * @uses headers_sent()
694 * @uses function_exists()
695 * @uses debug_print_backtrace()
696 * @uses trigger_error()
698 * @param string $uri the header to send
699 * @return boolean always true
701 function PMA_sendHeaderLocation($uri)
703 if (PMA_IS_IIS
&& strlen($uri) > 600) {
705 echo '<html><head><title>- - -</title>' . "\n";
706 echo '<meta http-equiv="expires" content="0">' . "\n";
707 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
708 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
709 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
710 echo '<script type="text/javascript">' . "\n";
711 echo '//<![CDATA[' . "\n";
712 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
714 echo '</script>' . "\n";
715 echo '</head>' . "\n";
716 echo '<body>' . "\n";
717 echo '<script type="text/javascript">' . "\n";
718 echo '//<![CDATA[' . "\n";
719 echo 'document.write(\'<p><a href="' . $uri . '">' . __('Go') . '</a></p>\');' . "\n";
721 echo '</script></body></html>' . "\n";
725 if (strpos($uri, '?') === false) {
726 header('Location: ' . $uri . '?' . SID
);
728 $separator = PMA_get_arg_separator();
729 header('Location: ' . $uri . $separator . SID
);
732 session_write_close();
733 if (headers_sent()) {
734 if (function_exists('debug_print_backtrace')) {
736 debug_print_backtrace();
739 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
741 // bug #1523784: IE6 does not like 'Refresh: 0', it
742 // results in a blank page
743 // but we need it when coming from the cookie login panel)
744 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
745 header('Refresh: 0; ' . $uri);
747 header('Location: ' . $uri);
754 * returns array with tables of given db with extended information and grouped
756 * @uses $cfg['LeftFrameTableSeparator']
757 * @uses $cfg['LeftFrameTableLevel']
758 * @uses $cfg['ShowTooltipAliasTB']
759 * @uses $cfg['NaturalOrder']
760 * @uses PMA_backquote()
766 * @param string $db name of db
767 * @param string $tables name of tables
768 * @param integer $limit_offset list offset
769 * @param integer $limit_count max tables to return
770 * return array (recursive) grouped table list
772 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
774 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
776 if (null === $tables) {
777 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
778 if ($GLOBALS['cfg']['NaturalOrder']) {
779 uksort($tables, 'strnatcasecmp');
783 if (count($tables) < 1) {
794 $table_groups = array();
796 // for blobstreaming - list of blobstreaming tables
798 // load PMA configuration
799 $PMA_Config = $GLOBALS['PMA_Config'];
801 // if PMA configuration exists
802 if (!empty($PMA_Config))
803 $session_bs_tables = $GLOBALS['PMA_Config']->get('BLOBSTREAMING_TABLES');
805 foreach ($tables as $table_name => $table) {
806 // if BS tables exist
807 if (isset($session_bs_tables))
808 // compare table name to tables in list of blobstreaming tables
809 foreach ($session_bs_tables as $table_key=>$table_val)
810 // if table is in list, skip outer foreach loop
811 if ($table_name == $table_key)
814 // check for correct row count
815 if (null === $table['Rows']) {
816 // Do not check exact row count here,
817 // if row count is invalid possibly the table is defect
818 // and this would break left frame;
819 // but we can check row count if this is a view or the
820 // information_schema database
821 // since PMA_Table::countRecords() returns a limited row count
824 // set this because PMA_Table::countRecords() can use it
825 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
827 if ($tbl_is_view ||
'information_schema' == $db) {
828 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name']);
832 // in $group we save the reference to the place in $table_groups
833 // where to store the table info
834 if ($GLOBALS['cfg']['LeftFrameDBTree']
835 && $sep && strstr($table_name, $sep))
837 $parts = explode($sep, $table_name);
839 $group =& $table_groups;
841 $group_name_full = '';
842 $parts_cnt = count($parts) - 1;
843 while ($i < $parts_cnt
844 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
845 $group_name = $parts[$i] . $sep;
846 $group_name_full .= $group_name;
848 if (!isset($group[$group_name])) {
849 $group[$group_name] = array();
850 $group[$group_name]['is' . $sep . 'group'] = true;
851 $group[$group_name]['tab' . $sep . 'count'] = 1;
852 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
853 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
854 $table = $group[$group_name];
855 $group[$group_name] = array();
856 $group[$group_name][$group_name] = $table;
858 $group[$group_name]['is' . $sep . 'group'] = true;
859 $group[$group_name]['tab' . $sep . 'count'] = 1;
860 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
862 $group[$group_name]['tab' . $sep . 'count']++
;
864 $group =& $group[$group_name];
868 if (!isset($table_groups[$table_name])) {
869 $table_groups[$table_name] = array();
871 $group =& $table_groups;
875 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
876 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
877 // switch tooltip and name
878 $table['Comment'] = $table['Name'];
879 $table['disp_name'] = $table['Comment'];
881 $table['disp_name'] = $table['Name'];
884 $group[$table_name] = array_merge($default, $table);
887 return $table_groups;
890 /* ----------------------- Set of misc functions ----------------------- */
894 * Adds backquotes on both sides of a database, table or field name.
895 * and escapes backquotes inside the name with another backquote
899 * echo PMA_backquote('owner`s db'); // `owner``s db`
903 * @uses PMA_backquote()
906 * @uses str_replace()
907 * @param mixed $a_name the database, table or field name to "backquote"
909 * @param boolean $do_it a flag to bypass this function (used by dump
911 * @return mixed the "backquoted" database, table or field name if the
912 * current MySQL release is >= 3.23.6, the original one
916 function PMA_backquote($a_name, $do_it = true)
918 if (is_array($a_name)) {
919 foreach ($a_name as &$data) {
920 $data = PMA_backquote($data, $do_it);
926 global $PMA_SQPdata_forbidden_word;
927 global $PMA_SQPdata_forbidden_word_cnt;
929 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
934 // '0' is also empty for php :-(
935 if (strlen($a_name) && $a_name !== '*') {
936 return '`' . str_replace('`', '``', $a_name) . '`';
940 } // end of the 'PMA_backquote()' function
944 * Defines the <CR><LF> value depending on the user OS.
947 * @return string the <CR><LF> value to use
951 function PMA_whichCrlf()
955 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
957 if (PMA_USR_OS
== 'Win') {
966 } // end of the 'PMA_whichCrlf()' function
969 * Reloads navigation if needed.
971 * @param $jsonly prints out pure JavaScript
972 * @uses $GLOBALS['reload']
973 * @uses $GLOBALS['db']
974 * @uses PMA_generate_common_url()
975 * @global array configuration
979 function PMA_reloadNavigation($jsonly=false)
983 // Reloads the navigation frame via JavaScript if required
984 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
985 // one of the reasons for a reload is when a table is dropped
986 // in this case, get rid of the table limit offset, otherwise
987 // we have a problem when dropping a table on the last page
988 // and the offset becomes greater than the total number of tables
989 unset($_SESSION['tmp_user_values']['table_limit_offset']);
991 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
993 echo '<script type="text/javascript">' . PHP_EOL
;
996 if (typeof(window
.parent
) != 'undefined'
997 && typeof(window
.parent
.frame_navigation
) != 'undefined'
998 && window
.parent
.goTo) {
999 window
.parent
.goTo('<?php echo $reload_url; ?>');
1004 echo '</script>' . PHP_EOL
;
1006 unset($GLOBALS['reload']);
1011 * displays the message and the query
1012 * usually the message is the result of the query executed
1014 * @param string $message the message to display
1015 * @param string $sql_query the query to display
1016 * @param string $type the type (level) of the message
1017 * @param boolean $is_view is this a message after a VIEW operation?
1018 * @global array the configuration array
1022 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
1026 if (null === $sql_query) {
1027 if (! empty($GLOBALS['display_query'])) {
1028 $sql_query = $GLOBALS['display_query'];
1029 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1030 $sql_query = $GLOBALS['unparsed_sql'];
1031 } elseif (! empty($GLOBALS['sql_query'])) {
1032 $sql_query = $GLOBALS['sql_query'];
1038 // Corrects the tooltip text via JS if required
1039 // @todo this is REALLY the wrong place to do this - very unexpected here
1040 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1041 $tooltip = PMA_Table
::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1042 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1044 echo '<script type="text/javascript">' . "\n";
1045 echo '//<![CDATA[' . "\n";
1046 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1047 echo '//]]>' . "\n";
1048 echo '</script>' . "\n";
1049 } // end if ... elseif
1051 // Checks if the table needs to be repaired after a TRUNCATE query.
1052 // @todo what about $GLOBALS['display_query']???
1053 // @todo this is REALLY the wrong place to do this - very unexpected here
1054 if (strlen($GLOBALS['table'])
1055 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1056 if (PMA_Table
::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1057 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1062 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1064 if ($message instanceof PMA_Message
) {
1065 if (isset($GLOBALS['special_message'])) {
1066 $message->addMessage($GLOBALS['special_message']);
1067 unset($GLOBALS['special_message']);
1069 $message->display();
1070 $type = $message->getLevel();
1072 echo '<div class="' . $type . '">';
1073 echo PMA_sanitize($message);
1074 if (isset($GLOBALS['special_message'])) {
1075 echo PMA_sanitize($GLOBALS['special_message']);
1076 unset($GLOBALS['special_message']);
1081 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1082 // Html format the query to be displayed
1083 // If we want to show some sql code it is easiest to create it here
1084 /* SQL-Parser-Analyzer */
1086 if (! empty($GLOBALS['show_as_php'])) {
1087 $new_line = '\\n"<br />' . "\n"
1088 . ' . "';
1089 $query_base = htmlspecialchars(addslashes($sql_query));
1090 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1092 $query_base = $sql_query;
1095 $query_too_big = false;
1097 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1098 // when the query is large (for example an INSERT of binary
1099 // data), the parser chokes; so avoid parsing the query
1100 $query_too_big = true;
1101 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1102 } elseif (! empty($GLOBALS['parsed_sql'])
1103 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1104 // (here, use "! empty" because when deleting a bookmark,
1105 // $GLOBALS['parsed_sql'] is set but empty
1106 $parsed_sql = $GLOBALS['parsed_sql'];
1108 // Parse SQL if needed
1109 $parsed_sql = PMA_SQP_parse($query_base);
1113 if (isset($parsed_sql)) {
1114 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1115 // Here we append the LIMIT added for navigation, to
1116 // enable its display. Adding it higher in the code
1117 // to $sql_query would create a problem when
1118 // using the Refresh or Edit links.
1120 // Only append it on SELECTs.
1123 * @todo what would be the best to do when someone hits Refresh:
1124 * use the current LIMITs ?
1127 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1128 && isset($GLOBALS['sql_limit_to_append'])) {
1129 $query_base = $analyzed_display_query[0]['section_before_limit']
1130 . "\n" . $GLOBALS['sql_limit_to_append']
1131 . $analyzed_display_query[0]['section_after_limit'];
1132 // Need to reparse query
1133 $parsed_sql = PMA_SQP_parse($query_base);
1137 if (! empty($GLOBALS['show_as_php'])) {
1138 $query_base = '$sql = "' . $query_base;
1139 } elseif (! empty($GLOBALS['validatequery'])) {
1140 $query_base = PMA_validateSQL($query_base);
1141 } elseif (isset($parsed_sql)) {
1142 $query_base = PMA_formatSql($parsed_sql, $query_base);
1145 // Prepares links that may be displayed to edit/explain the query
1146 // (don't go to default pages, we must go to the page
1147 // where the query box is available)
1149 // Basic url query part
1150 $url_params = array();
1151 if (strlen($GLOBALS['db'])) {
1152 $url_params['db'] = $GLOBALS['db'];
1153 if (strlen($GLOBALS['table'])) {
1154 $url_params['table'] = $GLOBALS['table'];
1155 $edit_link = 'tbl_sql.php';
1157 $edit_link = 'db_sql.php';
1160 $edit_link = 'server_sql.php';
1163 // Want to have the query explained (Mike Beck 2002-05-22)
1164 // but only explain a SELECT (that has not been explained)
1165 /* SQL-Parser-Analyzer */
1167 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1168 $explain_params = $url_params;
1169 // Detect if we are validating as well
1170 // To preserve the validate uRL data
1171 if (! empty($GLOBALS['validatequery'])) {
1172 $explain_params['validatequery'] = 1;
1175 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1176 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1177 $_message = __('Explain SQL');
1178 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1179 $explain_params['sql_query'] = substr($sql_query, 8);
1180 $_message = __('Skip Explain SQL');
1182 if (isset($explain_params['sql_query'])) {
1183 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1184 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1188 $url_params['sql_query'] = $sql_query;
1189 $url_params['show_query'] = 1;
1191 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1192 if ($cfg['EditInWindow'] == true) {
1193 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1198 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1199 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1204 $url_qpart = PMA_generate_common_url($url_params);
1206 // Also we would like to get the SQL formed in some nice
1207 // php-code (Mike Beck 2002-05-22)
1208 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1209 $php_params = $url_params;
1211 if (! empty($GLOBALS['show_as_php'])) {
1212 $_message = __('Without PHP Code');
1214 $php_params['show_as_php'] = 1;
1215 $_message = __('Create PHP Code');
1218 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1219 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1221 if (isset($GLOBALS['show_as_php'])) {
1222 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1223 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1230 if (! empty($cfg['SQLQuery']['Refresh'])
1231 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1232 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1233 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1238 if (! empty($cfg['SQLValidator']['use'])
1239 && ! empty($cfg['SQLQuery']['Validate'])) {
1240 $validate_params = $url_params;
1241 if (!empty($GLOBALS['validatequery'])) {
1242 $validate_message = __('Skip Validate SQL') ;
1244 $validate_params['validatequery'] = 1;
1245 $validate_message = __('Validate SQL') ;
1248 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1249 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1251 $validate_link = '';
1254 echo '<code class="sql">';
1255 if ($query_too_big) {
1256 echo $shortened_query_base;
1261 //Clean up the end of the PHP
1262 if (! empty($GLOBALS['show_as_php'])) {
1267 echo '<div class="tools">';
1268 // avoid displaying a Profiling checkbox that could
1269 // be checked, which would reexecute an INSERT, for example
1270 if (! empty($refresh_link)) {
1271 PMA_profilingCheckbox($sql_query);
1273 $inline_edit = "<script type=\"text/javascript\">\n" .
1275 "document.write('[<a href=\"#\" title=\"" .
1276 PMA_escapeJsString(__('Inline edit of this query')) .
1277 "\" id=\"inline_edit\">" .
1278 PMA_escapeJsString(__('Inline')) .
1282 echo $inline_edit . $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1285 echo '</div><br />' . "\n";
1286 } // end of the 'PMA_showMessage()' function
1289 * Verifies if current MySQL server supports profiling
1291 * @uses $_SESSION['profiling_supported'] for caching
1292 * @uses $GLOBALS['server']
1293 * @uses PMA_DBI_fetch_value()
1294 * @uses PMA_MYSQL_INT_VERSION
1297 * @return boolean whether profiling is supported
1300 function PMA_profilingSupported()
1302 if (! PMA_cacheExists('profiling_supported', true)) {
1303 // 5.0.37 has profiling but for example, 5.1.20 does not
1304 // (avoid a trip to the server for MySQL before 5.0.37)
1305 // and do not set a constant as we might be switching servers
1306 if (defined('PMA_MYSQL_INT_VERSION')
1307 && PMA_MYSQL_INT_VERSION
>= 50037
1308 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1309 PMA_cacheSet('profiling_supported', true, true);
1311 PMA_cacheSet('profiling_supported', false, true);
1315 return PMA_cacheGet('profiling_supported', true);
1319 * Displays a form with the Profiling checkbox
1321 * @param string $sql_query
1325 function PMA_profilingCheckbox($sql_query)
1327 if (PMA_profilingSupported()) {
1328 echo '<form action="sql.php" method="post">' . "\n";
1329 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1330 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1331 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1332 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1333 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1334 echo '</form>' . "\n";
1339 * Displays the results of SHOW PROFILE
1341 * @param array the results
1345 function PMA_profilingResults($profiling_results)
1347 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1348 echo '<table>' . "\n";
1349 echo ' <tr>' . "\n";
1350 echo ' <th>' . __('Status') . '</th>' . "\n";
1351 echo ' <th>' . __('Time') . '</th>' . "\n";
1352 echo ' </tr>' . "\n";
1354 foreach($profiling_results as $one_result) {
1355 echo ' <tr>' . "\n";
1356 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1357 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1359 echo '</table>' . "\n";
1360 echo '</fieldset>' . "\n";
1364 * Formats $value to byte view
1366 * @param double the value to format
1367 * @param integer the sensitiveness
1368 * @param integer the number of decimals to retain
1370 * @return array the formatted value and its unit
1374 * @version 1.2 - 18 July 2002
1376 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1378 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1379 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1381 $dh = PMA_pow(10, $comma);
1382 $li = PMA_pow(10, $limes);
1383 $return_value = $value;
1384 $unit = $byteUnits[0];
1386 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1387 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1388 // use 1024.0 to avoid integer overflow on 64-bit machines
1389 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1390 $unit = $byteUnits[$d];
1395 if ($unit != $byteUnits[0]) {
1396 // if the unit is not bytes (as represented in current language)
1397 // reformat with max length of 5
1398 // 4th parameter=true means do not reformat if value < 1
1399 $return_value = PMA_formatNumber($value, 5, $comma, true);
1401 // do not reformat, just handle the locale
1402 $return_value = PMA_formatNumber($value, 0);
1405 return array(trim($return_value), $unit);
1406 } // end of the 'PMA_formatByteDown' function
1409 * Changes thousands and decimal separators to locale specific values.
1411 function PMA_localizeNumber($value)
1416 /* l10n: Thousands separator */
1418 /* l10n: Decimal separator */
1425 * Formats $value to the given length and appends SI prefixes
1426 * $comma is not substracted from the length
1427 * with a $length of 0 no truncation occurs, number is only formated
1428 * to the current locale
1432 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1433 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1434 * echo PMA_formatNumber(-0.003, 6); // -3 m
1435 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1436 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1437 * echo PMA_formatNumber(0, 6); // 0
1440 * @param double $value the value to format
1441 * @param integer $length the max length
1442 * @param integer $comma the number of decimals to retain
1443 * @param boolean $only_down do not reformat numbers below 1
1445 * @return string the formatted value and its unit
1449 * @version 1.1.0 - 2005-10-27
1451 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1453 //number_format is not multibyte safe, str_replace is safe
1454 if ($length === 0) {
1455 return PMA_localizeNumber(number_format($value, $comma));
1458 // this units needs no translation, ISO
1479 // we need at least 3 digits to be displayed
1480 if (3 > $length +
$comma) {
1481 $length = 3 - $comma;
1484 // check for negative value to retain sign
1487 $value = abs($value);
1492 $dh = PMA_pow(10, $comma);
1493 $li = PMA_pow(10, $length);
1497 for ($d = 8; $d >= 0; $d--) {
1498 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1499 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1504 } elseif (!$only_down && (float) $value !== 0.0) {
1505 for ($d = -8; $d <= 8; $d++
) {
1506 // force using pow() because of the negative exponent
1507 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1508 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1513 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1515 //number_format is not multibyte safe, str_replace is safe
1516 $value = PMA_localizeNumber(number_format($value, $comma));
1518 return $sign . $value . ' ' . $unit;
1519 } // end of the 'PMA_formatNumber' function
1522 * Returns the number of bytes when a formatted size is given
1524 * @param string $size the size expression (for example 8MB)
1526 * @return integer The numerical part of the expression (for example 8)
1528 function PMA_extractValueFromFormattedSize($formatted_size)
1532 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1533 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1534 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1535 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1536 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1537 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1539 return $return_value;
1540 }// end of the 'PMA_extractValueFromFormattedSize' function
1543 * Writes localised date
1545 * @param string the current timestamp
1547 * @return string the formatted date
1551 function PMA_localisedDate($timestamp = -1, $format = '')
1554 /* l10n: Short month name */
1556 /* l10n: Short month name */
1558 /* l10n: Short month name */
1560 /* l10n: Short month name */
1562 /* l10n: Short month name */
1563 _pgettext('Short month name', 'May'),
1564 /* l10n: Short month name */
1566 /* l10n: Short month name */
1568 /* l10n: Short month name */
1570 /* l10n: Short month name */
1572 /* l10n: Short month name */
1574 /* l10n: Short month name */
1576 /* l10n: Short month name */
1578 $day_of_week = array(
1579 /* l10n: Short week day name */
1581 /* l10n: Short week day name */
1583 /* l10n: Short week day name */
1585 /* l10n: Short week day name */
1587 /* l10n: Short week day name */
1589 /* l10n: Short week day name */
1591 /* l10n: Short week day name */
1594 if ($format == '') {
1595 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1596 $format = __('%B %d, %Y at %I:%M %p');
1599 if ($timestamp == -1) {
1600 $timestamp = time();
1603 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1604 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1606 return strftime($date, $timestamp);
1607 } // end of the 'PMA_localisedDate()' function
1611 * returns a tab for tabbed navigation.
1612 * If the variables $link and $args ar left empty, an inactive tab is created
1614 * @uses $GLOBALS['PMA_PHP_SELF']
1617 * @uses $GLOBALS['active_page']
1618 * @uses $GLOBALS['url_query']
1619 * @uses $cfg['MainPageIconic']
1620 * @uses $GLOBALS['pmaThemeImage']
1621 * @uses PMA_generate_common_url()
1622 * @uses E_USER_NOTICE
1623 * @uses htmlentities()
1626 * @uses trigger_error()
1627 * @uses array_merge()
1629 * @param array $tab array with all options
1630 * @param array $url_params
1631 * @return string html code for one tab, a link if valid otherwise a span
1634 function PMA_generate_html_tab($tab, $url_params = array())
1649 $tab = array_merge($defaults, $tab);
1651 // determine additionnal style-class
1652 if (empty($tab['class'])) {
1653 if ($tab['text'] == __('Empty')
1654 ||
$tab['text'] == __('Drop')) {
1655 $tab['class'] = 'caution';
1656 } elseif (! empty($tab['active'])
1657 ||
PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1658 $tab['class'] = 'active';
1659 } elseif (empty($GLOBALS['active_page'])
1660 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1661 && empty($tab['warning'])) {
1662 $tab['class'] = 'active';
1666 if (!empty($tab['warning'])) {
1667 $tab['class'] .= ' warning';
1668 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1671 // If there are any tab specific URL parameters, merge those with the general URL parameters
1672 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1673 $url_params = array_merge($url_params, $tab['url_params']);
1677 if (!empty($tab['link'])) {
1678 $tab['link'] = htmlentities($tab['link']);
1679 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1680 if (! empty($tab['args'])) {
1681 foreach ($tab['args'] as $param => $value) {
1682 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1683 . urlencode($value);
1688 if (! empty($tab['fragment'])) {
1689 $tab['link'] .= $tab['fragment'];
1692 // display icon, even if iconic is disabled but the link-text is missing
1693 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1694 && isset($tab['icon'])) {
1695 // avoid generating an alt tag, because it only illustrates
1696 // the text that follows and if browser does not display
1697 // images, the text is duplicated
1698 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1699 .'%1$s" width="16" height="16" alt="" />%2$s';
1700 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1702 // check to not display an empty link-text
1703 elseif (empty($tab['text'])) {
1705 trigger_error('empty linktext in function ' . __FUNCTION__
. '()',
1709 $out = '<li' . ($tab['class'] == 'active' ?
' class="active"' : '') . '>';
1711 if (!empty($tab['link'])) {
1712 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1713 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1714 . $tab['text'] . '</a>';
1716 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1717 . $tab['text'] . '</span>';
1722 } // end of the 'PMA_generate_html_tab()' function
1725 * returns html-code for a tab navigation
1727 * @uses PMA_generate_html_tab()
1728 * @uses htmlentities()
1729 * @param array $tabs one element per tab
1730 * @param string $url_params
1731 * @return string html-code for tab-navigation
1733 function PMA_generate_html_tabs($tabs, $url_params)
1735 $tag_id = 'topmenu';
1737 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1738 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1740 foreach ($tabs as $tab) {
1741 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1746 .'<div class="clearfloat"></div>'
1749 return $tab_navigation;
1754 * Displays a link, or a button if the link's URL is too large, to
1755 * accommodate some browsers' limitations
1757 * @param string the URL
1758 * @param string the link message
1759 * @param mixed $tag_params string: js confirmation
1760 * array: additional tag params (f.e. style="")
1761 * @param boolean $new_form we set this to false when we are already in
1762 * a form, to avoid generating nested forms
1764 * @return string the results to be echoed or saved in an array
1766 function PMA_linkOrButton($url, $message, $tag_params = array(),
1767 $new_form = true, $strip_img = false, $target = '')
1769 if (! is_array($tag_params)) {
1771 $tag_params = array();
1773 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1777 if (! empty($target)) {
1778 $tag_params['target'] = htmlentities($target);
1781 $tag_params_strings = array();
1782 foreach ($tag_params as $par_name => $par_value) {
1783 // htmlspecialchars() only on non javascript
1784 $par_value = substr($par_name, 0, 2) == 'on'
1786 : htmlspecialchars($par_value);
1787 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1790 if (strlen($url) <= $GLOBALS['cfg']['LinkLengthLimit']) {
1791 // no whitespace within an <a> else Safari will make it part of the link
1792 $ret = "\n" . '<a href="' . $url . '" '
1793 . implode(' ', $tag_params_strings) . '>'
1794 . $message . '</a>' . "\n";
1796 // no spaces (linebreaks) at all
1797 // or after the hidden fields
1798 // IE will display them all
1800 // add class=link to submit button
1801 if (empty($tag_params['class'])) {
1802 $tag_params['class'] = 'link';
1805 // decode encoded url separators
1806 $separator = PMA_get_arg_separator();
1807 // on most places separator is still hard coded ...
1808 if ($separator !== '&') {
1809 // ... so always replace & with $separator
1810 $url = str_replace(htmlentities('&'), $separator, $url);
1811 $url = str_replace('&', $separator, $url);
1813 $url = str_replace(htmlentities($separator), $separator, $url);
1816 $url_parts = parse_url($url);
1817 $query_parts = explode($separator, $url_parts['query']);
1819 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1820 . ' method="post"' . $target . ' style="display: inline;">';
1822 $subname_close = '';
1825 $query_parts[] = 'redirect=' . $url_parts['path'];
1826 if (empty($GLOBALS['subform_counter'])) {
1827 $GLOBALS['subform_counter'] = 0;
1829 $GLOBALS['subform_counter']++
;
1831 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1832 $subname_close = ']';
1833 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1835 foreach ($query_parts as $query_pair) {
1836 list($eachvar, $eachval) = explode('=', $query_pair);
1837 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1838 . $subname_close . '" value="'
1839 . htmlspecialchars(urldecode($eachval)) . '" />';
1842 if (stristr($message, '<img')) {
1844 $message = trim(strip_tags($message));
1845 $ret .= '<input type="submit"' . $submit_name . ' '
1846 . implode(' ', $tag_params_strings)
1847 . ' value="' . htmlspecialchars($message) . '" />';
1849 $displayed_message = htmlspecialchars(
1850 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1852 $ret .= '<input type="image"' . $submit_name . ' '
1853 . implode(' ', $tag_params_strings)
1854 . ' src="' . preg_replace(
1855 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1856 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1859 $message = trim(strip_tags($message));
1860 $ret .= '<input type="submit"' . $submit_name . ' '
1861 . implode(' ', $tag_params_strings)
1862 . ' value="' . htmlspecialchars($message) . '" />';
1867 } // end if... else...
1870 } // end of the 'PMA_linkOrButton()' function
1874 * Returns a given timespan value in a readable format.
1876 * @uses __('%s days, %s hours, %s minutes and %s seconds')
1879 * @param int the timespan
1881 * @return string the formatted value
1883 function PMA_timespanFormat($seconds)
1885 $return_string = '';
1886 $days = floor($seconds / 86400);
1888 $seconds -= $days * 86400;
1890 $hours = floor($seconds / 3600);
1891 if ($days > 0 ||
$hours > 0) {
1892 $seconds -= $hours * 3600;
1894 $minutes = floor($seconds / 60);
1895 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1896 $seconds -= $minutes * 60;
1898 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1902 * Takes a string and outputs each character on a line for itself. Used
1903 * mainly for horizontalflipped display mode.
1904 * Takes care of special html-characters.
1905 * Fulfills todo-item
1906 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1908 * @todo add a multibyte safe function PMA_STR_split()
1910 * @param string The string
1911 * @param string The Separator (defaults to "<br />\n")
1914 * @return string The flipped string
1916 function PMA_flipstring($string, $Separator = "<br />\n")
1918 $format_string = '';
1921 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++
) {
1922 $char = $string{$i};
1926 $format_string .= $charbuff;
1928 } elseif ($char == ';' && !empty($charbuff)) {
1929 $format_string .= $charbuff . $char;
1932 } elseif (! empty($charbuff)) {
1935 $format_string .= $char;
1939 // do not add separator after the last character
1940 if ($append && ($i != $str_len - 1)) {
1941 $format_string .= $Separator;
1945 return $format_string;
1950 * Function added to avoid path disclosures.
1951 * Called by each script that needs parameters, it displays
1952 * an error message and, by default, stops the execution.
1954 * Not sure we could use a strMissingParameter message here,
1955 * would have to check if the error message file is always available
1957 * @todo localize error message
1958 * @todo use PMA_fatalError() if $die === true?
1959 * @uses PMA_getenv()
1960 * @uses header_meta_style.inc.php
1961 * @uses $GLOBALS['PMA_PHP_SELF']
1963 * @param array The names of the parameters needed by the calling
1965 * @param boolean Stop the execution?
1966 * (Set this manually to false in the calling script
1967 * until you know all needed parameters to check).
1968 * @param boolean Whether to include this list in checking for special params.
1969 * @global string path to current script
1970 * @global boolean flag whether any special variable was required
1974 function PMA_checkParameters($params, $die = true, $request = true)
1976 global $checked_special;
1978 if (!isset($checked_special)) {
1979 $checked_special = false;
1982 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1983 $found_error = false;
1984 $error_message = '';
1986 foreach ($params as $param) {
1987 if ($request && $param != 'db' && $param != 'table') {
1988 $checked_special = true;
1991 if (!isset($GLOBALS[$param])) {
1992 $error_message .= $reported_script_name
1993 . ': Missing parameter: ' . $param
1994 . PMA_showDocu('faqmissingparameters')
1996 $found_error = true;
2001 * display html meta tags
2003 require_once './libraries/header_meta_style.inc.php';
2004 echo '</head><body><p>' . $error_message . '</p></body></html>';
2012 * Function to generate unique condition for specified row.
2014 * @uses $GLOBALS['analyzed_sql'][0]
2015 * @uses PMA_DBI_field_flags()
2016 * @uses PMA_backquote()
2017 * @uses PMA_sqlAddslashes()
2018 * @uses PMA_printable_bit_value()
2021 * @uses preg_replace()
2022 * @param resource $handle current query result
2023 * @param integer $fields_cnt number of fields
2024 * @param array $fields_meta meta information about fields
2025 * @param array $row current row
2026 * @param boolean $force_unique generate condition only on pk or unique
2029 * @return string the calculated condition and whether condition is unique
2031 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
2035 $nonprimary_condition = '';
2036 $preferred_condition = '';
2038 for ($i = 0; $i < $fields_cnt; ++
$i) {
2040 $field_flags = PMA_DBI_field_flags($handle, $i);
2041 $meta = $fields_meta[$i];
2043 // do not use a column alias in a condition
2044 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
2045 $meta->orgname
= $meta->name
;
2047 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2048 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2049 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2051 // need (string) === (string)
2052 // '' !== 0 but '' == 0
2053 if ((string) $select_expr['alias'] === (string) $meta->name
) {
2054 $meta->orgname
= $select_expr['column'];
2061 // Do not use a table alias in a condition.
2063 // select * from galerie x WHERE
2064 //(select count(*) from galerie y where y.datum=x.datum)>1
2066 // But orgtable is present only with mysqli extension so the
2067 // fix is only for mysqli.
2068 // Also, do not use the original table name if we are dealing with
2069 // a view because this view might be updatable.
2070 // (The isView() verification should not be costly in most cases
2071 // because there is some caching in the function).
2072 if (isset($meta->orgtable
) && $meta->table
!= $meta->orgtable
&& ! PMA_Table
::isView($GLOBALS['db'], $meta->table
)) {
2073 $meta->table
= $meta->orgtable
;
2076 // to fix the bug where float fields (primary or not)
2077 // can't be matched because of the imprecision of
2078 // floating comparison, use CONCAT
2079 // (also, the syntax "CONCAT(field) IS NULL"
2080 // that we need on the next "if" will work)
2081 if ($meta->type
== 'real') {
2082 $condition = ' CONCAT(' . PMA_backquote($meta->table
) . '.'
2083 . PMA_backquote($meta->orgname
) . ') ';
2085 $condition = ' ' . PMA_backquote($meta->table
) . '.'
2086 . PMA_backquote($meta->orgname
) . ' ';
2087 } // end if... else...
2089 if (!isset($row[$i]) ||
is_null($row[$i])) {
2090 $condition .= 'IS NULL AND';
2092 // timestamp is numeric on some MySQL 4.1
2093 if ($meta->numeric && $meta->type
!= 'timestamp') {
2094 $condition .= '= ' . $row[$i] . ' AND';
2095 } elseif (($meta->type
== 'blob' ||
$meta->type
== 'string')
2096 // hexify only if this is a true not empty BLOB or a BINARY
2097 && stristr($field_flags, 'BINARY')
2098 && !empty($row[$i])) {
2099 // do not waste memory building a too big condition
2100 if (strlen($row[$i]) < 1000) {
2101 // use a CAST if possible, to avoid problems
2102 // if the field contains wildcard characters % or _
2103 $condition .= '= CAST(0x' . bin2hex($row[$i])
2104 . ' AS BINARY) AND';
2106 // this blob won't be part of the final condition
2109 } elseif ($meta->type
== 'bit') {
2110 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length
) . "' AND";
2112 $condition .= '= \''
2113 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2116 if ($meta->primary_key
> 0) {
2117 $primary_key .= $condition;
2118 } elseif ($meta->unique_key
> 0) {
2119 $unique_key .= $condition;
2121 $nonprimary_condition .= $condition;
2124 // Correction University of Virginia 19991216:
2125 // prefer primary or unique keys for condition,
2126 // but use conjunction of all values if no primary key
2127 $clause_is_unique = true;
2129 $preferred_condition = $primary_key;
2130 } elseif ($unique_key) {
2131 $preferred_condition = $unique_key;
2132 } elseif (! $force_unique) {
2133 $preferred_condition = $nonprimary_condition;
2134 $clause_is_unique = false;
2137 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2138 return(array($where_clause, $clause_is_unique));
2142 * Generate a button or image tag
2144 * @uses PMA_USR_BROWSER_AGENT
2145 * @uses $GLOBALS['pmaThemeImage']
2146 * @uses $GLOBALS['cfg']['PropertiesIconic']
2147 * @param string name of button element
2148 * @param string class of button element
2149 * @param string name of image element
2150 * @param string text to display
2151 * @param string image to display
2155 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2158 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2159 echo ' <input type="submit" name="' . $button_name . '"'
2160 .' value="' . htmlspecialchars($text) . '"'
2161 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2165 /* Opera has trouble with <input type="image"> */
2166 /* IE has trouble with <button> */
2167 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2168 echo '<button class="' . $button_class . '" type="submit"'
2169 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2170 .' title="' . htmlspecialchars($text) . '">' . "\n"
2171 . PMA_getIcon($image, $text)
2172 .'</button>' . "\n";
2174 echo '<input type="image" name="' . $image_name . '" value="'
2175 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2177 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ?
' ' . htmlspecialchars($text) : '') . "\n";
2182 * Generate a pagination selector for browsing resultsets
2184 * @todo $url is not javascript escaped!?
2185 * @uses __('Page number:')
2187 * @param string URL for the JavaScript
2188 * @param string Number of rows in the pagination set
2189 * @param string current page number
2190 * @param string number of total pages
2191 * @param string If the number of pages is lower than this
2192 * variable, no pages will be omitted in
2194 * @param string How many rows at the beginning should always
2196 * @param string How many rows at the end should always
2198 * @param string Percentage of calculation page offsets to
2199 * hop to a next page
2200 * @param string Near the current page, how many pages should
2201 * be considered "nearby" and displayed as
2203 * @param string The prompt to display (sometimes empty)
2207 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2208 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2209 $range = 10, $prompt = '')
2211 $increment = floor($nbTotalPage / $percent);
2212 $pageNowMinusRange = ($pageNow - $range);
2213 $pageNowPlusRange = ($pageNow +
$range);
2216 . ' <select name="pos" onchange="goToUrl(this, \''
2217 . $url . '\');">' . "\n";
2218 if ($nbTotalPage < $showAll) {
2219 $pages = range(1, $nbTotalPage);
2223 // Always show first X pages
2224 for ($i = 1; $i <= $sliceStart; $i++
) {
2228 // Always show last X pages
2229 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2233 // Based on the number of results we add the specified
2234 // $percent percentage to each page number,
2235 // so that we have a representing page number every now and then to
2236 // immediately jump to specific pages.
2237 // As soon as we get near our currently chosen page ($pageNow -
2238 // $range), every page number will be shown.
2240 $x = $nbTotalPage - $sliceEnd;
2241 $met_boundary = false;
2243 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2244 // If our pageselector comes near the current page, we use 1
2245 // counter increments
2247 $met_boundary = true;
2249 // We add the percentage increment to our current page to
2250 // hop to the next one in range
2253 // Make sure that we do not cross our boundaries.
2254 if ($i > $pageNowMinusRange && ! $met_boundary) {
2255 $i = $pageNowMinusRange;
2259 if ($i > 0 && $i <= $x) {
2264 // Since because of ellipsing of the current page some numbers may be double,
2265 // we unify our array:
2267 $pages = array_unique($pages);
2270 foreach ($pages as $i) {
2271 if ($i == $pageNow) {
2272 $selected = 'selected="selected" style="font-weight: bold"';
2276 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2279 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2286 * Generate navigation for a list
2288 * @todo use $pos from $_url_params
2289 * @uses __('Page number:')
2291 * @param integer number of elements in the list
2292 * @param integer current position in the list
2293 * @param array url parameters
2294 * @param string script name for form target
2295 * @param string target frame
2296 * @param integer maximum number of elements to display from the list
2300 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2302 if ($max_count < $count) {
2303 echo 'frame_navigation' == $frame ?
'<div id="navidbpageselector">' . "\n" : '';
2304 echo __('Page number:');
2305 echo 'frame_navigation' == $frame ?
'<br />' : ' ';
2307 // Move to the beginning or to the previous page
2309 // patch #474210 - part 1
2310 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2311 $caption1 = '<<';
2312 $caption2 = ' < ';
2313 $title1 = ' title="' . __('Begin') . '"';
2314 $title2 = ' title="' . __('Previous') . '"';
2316 $caption1 = __('Begin') . ' <<';
2317 $caption2 = __('Previous') . ' <';
2320 } // end if... else...
2321 $_url_params['pos'] = 0;
2322 echo '<a' . $title1 . ' href="' . $script
2323 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2324 . $caption1 . '</a>';
2325 $_url_params['pos'] = $pos - $max_count;
2326 echo '<a' . $title2 . ' href="' . $script
2327 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2328 . $caption2 . '</a>';
2331 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2332 echo PMA_generate_common_hidden_inputs($_url_params);
2333 echo PMA_pageselector(
2334 $script . PMA_generate_common_url($_url_params) . '&',
2336 floor(($pos +
1) / $max_count) +
1,
2337 ceil($count / $max_count));
2340 if ($pos +
$max_count < $count) {
2341 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2342 $caption3 = ' > ';
2343 $caption4 = '>>';
2344 $title3 = ' title="' . __('Next') . '"';
2345 $title4 = ' title="' . __('End') . '"';
2347 $caption3 = '> ' . __('Next');
2348 $caption4 = '>> ' . __('End');
2351 } // end if... else...
2352 $_url_params['pos'] = $pos +
$max_count;
2353 echo '<a' . $title3 . ' href="' . $script
2354 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2355 . $caption3 . '</a>';
2356 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2357 if ($_url_params['pos'] == $count) {
2358 $_url_params['pos'] = $count - $max_count;
2360 echo '<a' . $title4 . ' href="' . $script
2361 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2362 . $caption4 . '</a>';
2365 if ('frame_navigation' == $frame) {
2366 echo '</div>' . "\n";
2372 * replaces %u in given path with current user name
2376 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2379 * @uses $cfg['Server']['user']
2381 * @uses str_replace()
2382 * @param string $dir with wildcard for user
2383 * @return string per user directory
2385 function PMA_userDir($dir)
2387 // add trailing slash
2388 if (substr($dir, -1) != '/') {
2392 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2396 * returns html code for db link to default db page
2398 * @uses $cfg['DefaultTabDatabase']
2399 * @uses $GLOBALS['db']
2400 * @uses __('Jump to database "%s".')
2401 * @uses PMA_generate_common_url()
2402 * @uses PMA_unescape_mysql_wildcards()
2405 * @uses htmlspecialchars()
2406 * @param string $database
2407 * @return string html link to default db page
2409 function PMA_getDbLink($database = null)
2411 if (!strlen($database)) {
2412 if (!strlen($GLOBALS['db'])) {
2415 $database = $GLOBALS['db'];
2417 $database = PMA_unescape_mysql_wildcards($database);
2420 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2421 .' title="' . sprintf(__('Jump to database "%s".'), htmlspecialchars($database)) . '">'
2422 .htmlspecialchars($database) . '</a>';
2426 * Displays a lightbulb hint explaining a known external bug
2427 * that affects a functionality
2429 * @uses PMA_MYSQL_INT_VERSION
2430 * @uses __('The %s functionality is affected by a known bug, see %s')
2431 * @uses PMA_showHint()
2433 * @param string $functionality localized message explaining the func.
2434 * @param string $component 'mysql' (eventually, 'php')
2435 * @param string $minimum_version of this component
2436 * @param string $bugref bug reference for this component
2438 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2440 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION
< $minimum_version) {
2441 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, 'http://bugs.mysql.com/' . $bugref));
2446 * Generates and echoes an HTML checkbox
2448 * @param string $html_field_name the checkbox HTML field
2449 * @param string $label
2450 * @param boolean $checked is it initially checked?
2451 * @param boolean $onclick should it submit the form on click?
2453 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2455 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>';
2459 * Generates and echoes a set of radio HTML fields
2461 * @uses htmlspecialchars()
2462 * @param string $html_field_name the radio HTML field
2463 * @param array $choices the choices values and labels
2464 * @param string $checked_choice the choice to check by default
2465 * @param boolean $line_break whether to add an HTML line break after a choice
2466 * @param boolean $escape_label whether to use htmlspecialchars() on label
2467 * @param string $class enclose each choice with a div of this class
2469 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2470 foreach ($choices as $choice_value => $choice_label) {
2471 if (! empty($class)) {
2472 echo '<div class="' . $class . '">';
2474 $html_field_id = $html_field_name . '_' . $choice_value;
2475 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2476 if ($choice_value == $checked_choice) {
2477 echo ' checked="checked"';
2480 echo '<label for="' . $html_field_id . '">' . ($escape_label ?
htmlspecialchars($choice_label) : $choice_label) . '</label>';
2484 if (! empty($class)) {
2492 * Generates and returns an HTML dropdown
2494 * @uses htmlspecialchars()
2495 * @param string $select_name
2496 * @param array $choices the choices values
2497 * @param string $active_choice the choice to select by default
2498 * @param string $id the id of the select element; can be different in case
2499 * the dropdown is present more than once on the page
2500 * @todo support titles
2502 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2504 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2505 foreach ($choices as $one_choice_value => $one_choice_label) {
2506 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2507 if ($one_choice_value == $active_choice) {
2508 $result .= ' selected="selected"';
2510 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2512 $result .= '</select>';
2517 * Generates a slider effect (jQjuery)
2518 * Takes care of generating the initial <div> and the link
2519 * controlling the slider; you have to generate the </div> yourself
2520 * after the sliding section.
2522 * @uses $GLOBALS['cfg']['InitialSlidersState']
2523 * @param string $id the id of the <div> on which to apply the effect
2524 * @param string $message the message to show as a link
2526 function PMA_generate_slider_effect($id, $message)
2528 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2529 echo '<div id="' . $id . '">';
2533 <script type
="text/javascript">
2535 document
.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg
']['InitialSlidersState
'] == 'closed
' ? ' style
="display: none; overflow:auto;"' : ''; ?>>');
2537 function PMA_set_status_label_
<?php
echo $id; ?
>() {
2538 if ($
('#<?php echo $id; ?>').css('display') == 'none') {
2539 $
('#anchor_status_<?php echo $id; ?>').text('+ ');
2541 $
('#anchor_status_<?php echo $id; ?>').text('- ');
2545 $
(document
).ready(function() {
2547 $
('<span id="anchor_status_<?php echo $id; ?>"><span>')
2548 .insertBefore('#<?php echo $id; ?>')
2550 PMA_set_status_label_
<?php
echo $id; ?
>();
2552 $
('<a href="#<?php echo $id; ?>" id="anchor_<?php echo $id; ?>"><?php echo htmlspecialchars($message); ?></a>')
2553 .insertBefore('#<?php echo $id; ?>')
2555 // the callback should be the 4th parameter but
2556 // it only works as the second parameter
2557 $
('#<?php echo $id; ?>').toggle('drop', function() {
2558 PMA_set_status_label_
<?php
echo $id; ?
>();
2565 <div id
="<?php echo $id; ?>">
2571 * Verifies if something is cached in the session
2573 * @param string $var
2574 * @param scalar $server
2577 function PMA_cacheExists($var, $server = 0)
2579 if (true === $server) {
2580 $server = $GLOBALS['server'];
2582 return isset($_SESSION['cache']['server_' . $server][$var]);
2586 * Gets cached information from the session
2588 * @param string $var
2589 * @param scalar $server
2592 function PMA_cacheGet($var, $server = 0)
2594 if (true === $server) {
2595 $server = $GLOBALS['server'];
2597 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2598 return $_SESSION['cache']['server_' . $server][$var];
2605 * Caches information in the session
2607 * @param string $var
2609 * @param integer $server
2612 function PMA_cacheSet($var, $val = null, $server = 0)
2614 if (true === $server) {
2615 $server = $GLOBALS['server'];
2617 $_SESSION['cache']['server_' . $server][$var] = $val;
2621 * Removes cached information from the session
2623 * @param string $var
2624 * @param scalar $server
2626 function PMA_cacheUnset($var, $server = 0)
2628 if (true === $server) {
2629 $server = $GLOBALS['server'];
2631 unset($_SESSION['cache']['server_' . $server][$var]);
2635 * Converts a bit value to printable format;
2636 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2637 * function because in PHP, decbin() supports only 32 bits
2644 * @param numeric $value coming from a BIT field
2645 * @param integer $length
2646 * @return string the printable value
2648 function PMA_printable_bit_value($value, $length) {
2650 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++
) {
2651 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2653 $printable = substr($printable, -$length);
2658 * Verifies whether the value contains a non-printable character
2660 * @uses preg_match()
2661 * @param string $value
2664 function PMA_contains_nonprintable_ascii($value) {
2665 return preg_match('@[^[:print:]]@', $value);
2669 * Converts a BIT type default value
2670 * for example, b'010' becomes 010
2673 * @param string $bit_default_value
2674 * @return string the converted value
2676 function PMA_convert_bit_default_value($bit_default_value) {
2677 return strtr($bit_default_value, array("b" => "", "'" => ""));
2681 * Extracts the various parts from a field type spec
2686 * @param string $fieldspec
2687 * @return array associative array containing type, spec_in_brackets
2688 * and possibly enum_set_values (another array)
2690 function PMA_extractFieldSpec($fieldspec) {
2691 $first_bracket_pos = strpos($fieldspec, '(');
2692 if ($first_bracket_pos) {
2693 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos +
1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2694 // convert to lowercase just to be sure
2695 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2698 $spec_in_brackets = '';
2701 if ('enum' == $type ||
'set' == $type) {
2702 // Define our working vars
2703 $enum_set_values = array();
2708 // While there is another character to process
2709 while (isset($fieldspec[$index])) {
2710 // Grab the char to look at
2711 $char = $fieldspec[$index];
2713 // If it is a single quote, needs to be handled specially
2715 // If we are not currently in a string, begin one
2719 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2721 // Check out the next character (if possible)
2722 $has_next = isset($fieldspec[$index +
1]);
2723 $next = $has_next ?
$fieldspec[$index +
1] : null;
2725 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2726 if (! $has_next ||
$next != "'") {
2727 $enum_set_values[] = $working;
2730 // Otherwise, this is a 'double quote', and can be added to the working string
2731 } elseif ($next == "'") {
2733 // Skip the next char; we already know what it is
2737 // escaping of a quote?
2738 } elseif ('\\' == $char && isset($fieldspec[$index +
1]) && "'" == $fieldspec[$index +
1]) {
2741 // Otherwise, add it to our working string like normal
2745 // Increment character index
2749 $enum_set_values = array();
2754 'spec_in_brackets' => $spec_in_brackets,
2755 'enum_set_values' => $enum_set_values
2760 * Verifies if this table's engine supports foreign keys
2762 * @uses strtoupper()
2763 * @param string $engine
2766 function PMA_foreignkey_supported($engine) {
2767 $engine = strtoupper($engine);
2768 if ('INNODB' == $engine ||
'PBXT' == $engine) {
2776 * Replaces some characters by a displayable equivalent
2778 * @uses str_replace()
2779 * @param string $content
2780 * @return string the content with characters replaced
2782 function PMA_replace_binary_contents($content) {
2783 $result = str_replace("\x00", '\0', $content);
2784 $result = str_replace("\x08", '\b', $result);
2785 $result = str_replace("\x0a", '\n', $result);
2786 $result = str_replace("\x0d", '\r', $result);
2787 $result = str_replace("\x1a", '\Z', $result);
2793 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2796 * @return string with the chars replaced
2799 function PMA_duplicateFirstNewline($string){
2800 $first_occurence = strpos($string, "\r\n");
2801 if ($first_occurence === 0){
2802 $string = "\n".$string;
2808 * get the action word corresponding to a script name
2809 * in order to display it as a title in navigation panel
2812 * @param string a valid value for $cfg['LeftDefaultTabTable']
2813 * or $cfg['DefaultTabTable']
2814 * or $cfg['DefaultTabDatabase']
2816 function PMA_getTitleForTarget($target) {
2819 // Values for $cfg['DefaultTabTable']
2820 'tbl_structure.php' => __('Structure'),
2821 'tbl_sql.php' => __('SQL'),
2822 'tbl_select.php' =>__('Search'),
2823 'tbl_change.php' =>__('Insert'),
2824 'sql.php' => __('Browse'),
2826 // Values for $cfg['DefaultTabDatabase']
2827 'db_structure.php' => __('Structure'),
2828 'db_sql.php' => __('SQL'),
2829 'db_search.php' => __('Search'),
2830 'db_operations.php' => __('Operations'),
2832 return $mapping[$target];
2835 function PMA_js($code, $print=true)
2837 // these generated newlines are needed
2839 $out .= '<script type="text/javascript">'."\n";
2840 $out .= "\n" . '// <![CDATA[' . "\n";
2842 $out .= "\n" . '// ]]>' . "\n";
2843 $out .= '</script>'."\n";