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 $GLOBALS['strMaximumSize']
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($GLOBALS['strMaximumSize'], $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
297 * @author Robin Johnson <robbat2@users.sourceforge.net>
299 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
303 // Check that we actually have a valid set of parsed data
305 // first check for the SQL parser having hit an error
306 if (PMA_SQP_isError()) {
307 return htmlspecialchars($parsed_sql['raw']);
309 // then check for an array
310 if (!is_array($parsed_sql)) {
311 // We don't so just return the input directly
312 // This is intended to be used for when the SQL Parser is turned off
313 $formatted_sql = '<pre>' . "\n"
314 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ?
$unparsed_sql : $parsed_sql) . "\n"
316 return $formatted_sql;
321 switch ($cfg['SQP']['fmtType']) {
323 if ($unparsed_sql != '') {
324 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
326 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
330 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
333 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
334 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
340 return $formatted_sql;
341 } // end of the "PMA_formatSql()" function
345 * Displays a link to the official MySQL documentation
347 * @uses $cfg['MySQLManualType']
348 * @uses $cfg['MySQLManualBase']
349 * @uses $cfg['ReplaceHelpImg']
350 * @uses $GLOBALS['mysql_4_1_doc_lang']
351 * @uses $GLOBALS['mysql_5_1_doc_lang']
352 * @uses $GLOBALS['mysql_5_0_doc_lang']
353 * @uses $GLOBALS['strDocu']
354 * @uses $GLOBALS['pmaThemeImage']
355 * @uses PMA_MYSQL_INT_VERSION
357 * @uses str_replace()
358 * @param string chapter of "HTML, one page per chapter" documentation
359 * @param string contains name of page/anchor that is being linked
360 * @param bool whether to use big icon (like in left frame)
361 * @param string anchor to page part
363 * @return string the html link
367 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '')
371 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
375 // Fixup for newly used names:
376 $chapter = str_replace('_', '-', strtolower($chapter));
377 $link = str_replace('_', '-', strtolower($link));
379 switch ($cfg['MySQLManualType']) {
381 if (empty($chapter)) {
384 if (empty($anchor)) {
387 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
390 if (empty($anchor)) {
393 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
399 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
400 if (!empty($anchor)) {
401 $url .= '#' . $anchor;
411 if (defined('PMA_MYSQL_INT_VERSION')) {
412 if (PMA_MYSQL_INT_VERSION
>= 50100) {
414 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
415 $lang = $GLOBALS['mysql_5_1_doc_lang'];
417 } elseif (PMA_MYSQL_INT_VERSION
>= 50000) {
419 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
420 $lang = $GLOBALS['mysql_5_0_doc_lang'];
424 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
425 if (!empty($anchor)) {
426 $url .= '#' . $anchor;
432 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
433 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
434 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
436 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
438 } // end of the 'PMA_showMySQLDocu()' function
442 * Displays a link to the phpMyAdmin documentation
444 * @param string anchor in documentation
446 * @return string the html link
450 function PMA_showDocu($anchor) {
451 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
452 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
454 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . $GLOBALS['strDocu'] . '</a>]';
456 } // end of the 'PMA_showDocu()' function
459 * returns HTML for a footnote marker and add the messsage to the footnotes
461 * @uses $GLOBALS['footnotes']
462 * @param string the error message
463 * @return string html code for a footnote marker
466 function PMA_showHint($message, $bbcode = false, $type = 'notice')
468 if ($message instanceof PMA_Message
) {
469 $key = $message->getHash();
470 $type = $message->getLevel();
472 $key = md5($message);
475 if (! isset($GLOBALS['footnotes'][$key])) {
476 if (empty($GLOBALS['footnotes']) ||
! is_array($GLOBALS['footnotes'])) {
477 $GLOBALS['footnotes'] = array();
479 $nr = count($GLOBALS['footnotes']) +
1;
480 // this is the first instance of this message
482 $GLOBALS['footnotes'][$key] = array(
486 'instance' => $instance
489 $nr = $GLOBALS['footnotes'][$key]['nr'];
490 // another instance of this message (to ensure ids are unique)
491 $instance = ++
$GLOBALS['footnotes'][$key]['instance'];
495 return '[sup]' . $nr . '[/sup]';
498 // footnotemarker used in js/tooltip.js
499 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
503 * Displays a MySQL error message in the right frame.
505 * @uses footer.inc.php
506 * @uses header.inc.php
507 * @uses $GLOBALS['sql_query']
508 * @uses $GLOBALS['strError']
509 * @uses $GLOBALS['strSQLQuery']
510 * @uses $GLOBALS['pmaThemeImage']
511 * @uses $GLOBALS['strEdit']
512 * @uses $GLOBALS['strMySQLSaid']
513 * @uses $GLOBALS['cfg']['PropertiesIconic']
514 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
515 * @uses PMA_backquote()
516 * @uses PMA_DBI_getError()
517 * @uses PMA_formatSql()
518 * @uses PMA_generate_common_hidden_inputs()
519 * @uses PMA_generate_common_url()
520 * @uses PMA_showMySQLDocu()
521 * @uses PMA_sqlAddslashes()
522 * @uses PMA_SQP_isError()
523 * @uses PMA_SQP_parse()
524 * @uses PMA_SQP_getErrorString()
527 * @uses str_replace()
530 * @uses preg_replace()
535 * @uses function_exists()
536 * @uses htmlspecialchars()
539 * @param string the error message
540 * @param string the sql query that failed
541 * @param boolean whether to show a "modify" link or not
542 * @param string the "back" link url (full path is not required)
543 * @param boolean EXIT the page?
545 * @global string the curent table
546 * @global string the current db
550 function PMA_mysqlDie($error_message = '', $the_query = '',
551 $is_modify_link = true, $back_url = '', $exit = true)
556 * start http output, display html headers
558 require_once './libraries/header.inc.php';
560 $error_msg_output = '';
562 if (!$error_message) {
563 $error_message = PMA_DBI_getError();
565 if (!$the_query && !empty($GLOBALS['sql_query'])) {
566 $the_query = $GLOBALS['sql_query'];
569 // --- Added to solve bug #641765
570 // Robbat2 - 12 January 2003, 9:46PM
571 // Revised, Robbat2 - 13 January 2003, 2:59PM
572 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
573 $formatted_sql = htmlspecialchars($the_query);
574 } elseif (empty($the_query) ||
trim($the_query) == '') {
577 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
578 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
580 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
584 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
585 $error_msg_output .= ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
586 // if the config password is wrong, or the MySQL server does not
587 // respond, do not show the query that would reveal the
589 if (!empty($the_query) && !strstr($the_query, 'connect')) {
590 // --- Added to solve bug #641765
591 // Robbat2 - 12 January 2003, 9:46PM
592 // Revised, Robbat2 - 13 January 2003, 2:59PM
593 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
594 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
595 $error_msg_output .= '<br />' . "\n";
598 // modified to show me the help on sql errors (Michael Keck)
599 $error_msg_output .= ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
600 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
601 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
603 if ($is_modify_link) {
604 $_url_params = array(
605 'sql_query' => $the_query,
608 if (strlen($table)) {
609 $_url_params['db'] = $db;
610 $_url_params['table'] = $table;
611 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
612 } elseif (strlen($db)) {
613 $_url_params['db'] = $db;
614 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
616 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
619 $error_msg_output .= $doedit_goto
620 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
623 $error_msg_output .= ' </p>' . "\n"
625 .' ' . $formatted_sql . "\n"
629 $tmp_mysql_error = ''; // for saving the original $error_message
630 if (!empty($error_message)) {
631 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
632 $error_message = htmlspecialchars($error_message);
633 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
635 // modified to show me the help on error-returns (Michael Keck)
636 // (now error-messages-server)
637 $error_msg_output .= '<p>' . "\n"
638 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
639 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
643 // The error message will be displayed within a CODE segment.
644 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
646 // Replace all non-single blanks with their HTML-counterpart
647 $error_message = str_replace(' ', ' ', $error_message);
648 // Replace TAB-characters with their HTML-counterpart
649 $error_message = str_replace("\t", ' ', $error_message);
650 // Replace linebreaks
651 $error_message = nl2br($error_message);
653 $error_msg_output .= '<code>' . "\n"
654 . $error_message . "\n"
655 . '</code><br />' . "\n";
656 $error_msg_output .= '</div>';
658 $_SESSION['Import_message']['message'] = $error_msg_output;
661 if (! empty($back_url)) {
662 if (strstr($back_url, '?')) {
663 $back_url .= '&no_history=true';
665 $back_url .= '?no_history=true';
668 $_SESSION['Import_message']['go_back_url'] = $back_url;
670 $error_msg_output .= '<fieldset class="tblFooters">';
671 $error_msg_output .= '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
672 $error_msg_output .= '</fieldset>' . "\n\n";
675 echo $error_msg_output;
677 * display footer and exit
680 require_once './libraries/footer.inc.php';
682 echo $error_msg_output;
684 } // end of the 'PMA_mysqlDie()' function
687 * Send HTTP header, taking IIS limits into account (600 seems ok)
690 * @uses PMA_COMING_FROM_COOKIE_LOGIN
691 * @uses PMA_get_arg_separator()
696 * @uses session_write_close()
697 * @uses headers_sent()
698 * @uses function_exists()
699 * @uses debug_print_backtrace()
700 * @uses trigger_error()
702 * @param string $uri the header to send
703 * @return boolean always true
705 function PMA_sendHeaderLocation($uri)
707 if (PMA_IS_IIS
&& strlen($uri) > 600) {
709 echo '<html><head><title>- - -</title>' . "\n";
710 echo '<meta http-equiv="expires" content="0">' . "\n";
711 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
712 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
713 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
714 echo '<script type="text/javascript">' . "\n";
715 echo '//<![CDATA[' . "\n";
716 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
718 echo '</script>' . "\n";
719 echo '</head>' . "\n";
720 echo '<body>' . "\n";
721 echo '<script type="text/javascript">' . "\n";
722 echo '//<![CDATA[' . "\n";
723 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
725 echo '</script></body></html>' . "\n";
729 if (strpos($uri, '?') === false) {
730 header('Location: ' . $uri . '?' . SID
);
732 $separator = PMA_get_arg_separator();
733 header('Location: ' . $uri . $separator . SID
);
736 session_write_close();
737 if (headers_sent()) {
738 if (function_exists('debug_print_backtrace')) {
740 debug_print_backtrace();
743 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
745 // bug #1523784: IE6 does not like 'Refresh: 0', it
746 // results in a blank page
747 // but we need it when coming from the cookie login panel)
748 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
749 header('Refresh: 0; ' . $uri);
751 header('Location: ' . $uri);
758 * returns array with tables of given db with extended information and grouped
760 * @uses $cfg['LeftFrameTableSeparator']
761 * @uses $cfg['LeftFrameTableLevel']
762 * @uses $cfg['ShowTooltipAliasTB']
763 * @uses $cfg['NaturalOrder']
764 * @uses PMA_backquote()
770 * @param string $db name of db
771 * @param string $tables name of tables
772 * @param integer $limit_offset list offset
773 * @param integer $limit_count max tables to return
774 * return array (recursive) grouped table list
776 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
778 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
780 if (null === $tables) {
781 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
782 if ($GLOBALS['cfg']['NaturalOrder']) {
783 uksort($tables, 'strnatcasecmp');
787 if (count($tables) < 1) {
798 $table_groups = array();
800 // for blobstreaming - list of blobstreaming tables - rajk
802 // load PMA configuration
803 $PMA_Config = $_SESSION['PMA_Config'];
805 // if PMA configuration exists
806 if (!empty($PMA_Config))
807 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
809 foreach ($tables as $table_name => $table) {
810 // if BS tables exist
811 if (isset($session_bs_tables))
812 // compare table name to tables in list of blobstreaming tables
813 foreach ($session_bs_tables as $table_key=>$table_val)
814 // if table is in list, skip outer foreach loop
815 if ($table_name == $table_key)
818 // check for correct row count
819 if (null === $table['Rows']) {
820 // Do not check exact row count here,
821 // if row count is invalid possibly the table is defect
822 // and this would break left frame;
823 // but we can check row count if this is a view or the
824 // information_schema database
825 // since PMA_Table::countRecords() returns a limited row count
828 // set this because PMA_Table::countRecords() can use it
829 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
831 if ($tbl_is_view ||
'information_schema' == $db) {
832 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name']);
836 // in $group we save the reference to the place in $table_groups
837 // where to store the table info
838 if ($GLOBALS['cfg']['LeftFrameDBTree']
839 && $sep && strstr($table_name, $sep))
841 $parts = explode($sep, $table_name);
843 $group =& $table_groups;
845 $group_name_full = '';
846 $parts_cnt = count($parts) - 1;
847 while ($i < $parts_cnt
848 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
849 $group_name = $parts[$i] . $sep;
850 $group_name_full .= $group_name;
852 if (!isset($group[$group_name])) {
853 $group[$group_name] = array();
854 $group[$group_name]['is' . $sep . 'group'] = true;
855 $group[$group_name]['tab' . $sep . 'count'] = 1;
856 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
857 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
858 $table = $group[$group_name];
859 $group[$group_name] = array();
860 $group[$group_name][$group_name] = $table;
862 $group[$group_name]['is' . $sep . 'group'] = true;
863 $group[$group_name]['tab' . $sep . 'count'] = 1;
864 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
866 $group[$group_name]['tab' . $sep . 'count']++
;
868 $group =& $group[$group_name];
872 if (!isset($table_groups[$table_name])) {
873 $table_groups[$table_name] = array();
875 $group =& $table_groups;
879 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
880 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
881 // switch tooltip and name
882 $table['Comment'] = $table['Name'];
883 $table['disp_name'] = $table['Comment'];
885 $table['disp_name'] = $table['Name'];
888 $group[$table_name] = array_merge($default, $table);
891 return $table_groups;
894 /* ----------------------- Set of misc functions ----------------------- */
898 * Adds backquotes on both sides of a database, table or field name.
899 * and escapes backquotes inside the name with another backquote
903 * echo PMA_backquote('owner`s db'); // `owner``s db`
907 * @uses PMA_backquote()
910 * @uses str_replace()
911 * @param mixed $a_name the database, table or field name to "backquote"
913 * @param boolean $do_it a flag to bypass this function (used by dump
915 * @return mixed the "backquoted" database, table or field name if the
916 * current MySQL release is >= 3.23.6, the original one
920 function PMA_backquote($a_name, $do_it = true)
922 if (is_array($a_name)) {
923 foreach ($a_name as &$data) {
924 $data = PMA_backquote($data, $do_it);
930 global $PMA_SQPdata_forbidden_word;
931 global $PMA_SQPdata_forbidden_word_cnt;
933 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
938 // '0' is also empty for php :-(
939 if (strlen($a_name) && $a_name !== '*') {
940 return '`' . str_replace('`', '``', $a_name) . '`';
944 } // end of the 'PMA_backquote()' function
948 * Defines the <CR><LF> value depending on the user OS.
951 * @return string the <CR><LF> value to use
955 function PMA_whichCrlf()
959 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
961 if (PMA_USR_OS
== 'Win') {
970 } // end of the 'PMA_whichCrlf()' function
973 * Reloads navigation if needed.
975 * @param $jsonly prints out pure JavaScript
976 * @uses $GLOBALS['reload']
977 * @uses $GLOBALS['db']
978 * @uses PMA_generate_common_url()
979 * @global array configuration
983 function PMA_reloadNavigation($jsonly=false)
987 // Reloads the navigation frame via JavaScript if required
988 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
989 // one of the reasons for a reload is when a table is dropped
990 // in this case, get rid of the table limit offset, otherwise
991 // we have a problem when dropping a table on the last page
992 // and the offset becomes greater than the total number of tables
993 unset($_SESSION['tmp_user_values']['table_limit_offset']);
995 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
997 echo '<script type="text/javascript">' . PHP_EOL
;
1000 if (typeof(window
.parent
) != 'undefined'
1001 && typeof(window
.parent
.frame_navigation
) != 'undefined'
1002 && window
.parent
.goTo) {
1003 window
.parent
.goTo('<?php echo $reload_url; ?>');
1008 echo '</script>' . PHP_EOL
;
1010 unset($GLOBALS['reload']);
1015 * displays the message and the query
1016 * usually the message is the result of the query executed
1018 * @param string $message the message to display
1019 * @param string $sql_query the query to display
1020 * @param string $type the type (level) of the message
1021 * @global array the configuration array
1025 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
1029 if (null === $sql_query) {
1030 if (! empty($GLOBALS['display_query'])) {
1031 $sql_query = $GLOBALS['display_query'];
1032 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1033 $sql_query = $GLOBALS['unparsed_sql'];
1034 } elseif (! empty($GLOBALS['sql_query'])) {
1035 $sql_query = $GLOBALS['sql_query'];
1041 // Corrects the tooltip text via JS if required
1042 // @todo this is REALLY the wrong place to do this - very unexpected here
1043 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1044 $tooltip = PMA_Table
::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1045 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1047 echo '<script type="text/javascript">' . "\n";
1048 echo '//<![CDATA[' . "\n";
1049 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1050 echo '//]]>' . "\n";
1051 echo '</script>' . "\n";
1052 } // end if ... elseif
1054 // Checks if the table needs to be repaired after a TRUNCATE query.
1055 // @todo what about $GLOBALS['display_query']???
1056 // @todo this is REALLY the wrong place to do this - very unexpected here
1057 if (strlen($GLOBALS['table'])
1058 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1059 if (PMA_Table
::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1060 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1065 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1067 if ($message instanceof PMA_Message
) {
1068 if (isset($GLOBALS['special_message'])) {
1069 $message->addMessage($GLOBALS['special_message']);
1070 unset($GLOBALS['special_message']);
1072 $message->display();
1073 $type = $message->getLevel();
1075 echo '<div class="' . $type . '">';
1076 echo PMA_sanitize($message);
1077 if (isset($GLOBALS['special_message'])) {
1078 echo PMA_sanitize($GLOBALS['special_message']);
1079 unset($GLOBALS['special_message']);
1084 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1085 // Html format the query to be displayed
1086 // If we want to show some sql code it is easiest to create it here
1087 /* SQL-Parser-Analyzer */
1089 if (! empty($GLOBALS['show_as_php'])) {
1090 $new_line = '\\n"<br />' . "\n"
1091 . ' . "';
1092 $query_base = htmlspecialchars(addslashes($sql_query));
1093 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1095 $query_base = $sql_query;
1098 $query_too_big = false;
1100 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1101 // when the query is large (for example an INSERT of binary
1102 // data), the parser chokes; so avoid parsing the query
1103 $query_too_big = true;
1104 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1105 } elseif (! empty($GLOBALS['parsed_sql'])
1106 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1107 // (here, use "! empty" because when deleting a bookmark,
1108 // $GLOBALS['parsed_sql'] is set but empty
1109 $parsed_sql = $GLOBALS['parsed_sql'];
1111 // Parse SQL if needed
1112 $parsed_sql = PMA_SQP_parse($query_base);
1116 if (isset($parsed_sql)) {
1117 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1118 // Here we append the LIMIT added for navigation, to
1119 // enable its display. Adding it higher in the code
1120 // to $sql_query would create a problem when
1121 // using the Refresh or Edit links.
1123 // Only append it on SELECTs.
1126 * @todo what would be the best to do when someone hits Refresh:
1127 * use the current LIMITs ?
1130 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1131 && isset($GLOBALS['sql_limit_to_append'])) {
1132 $query_base = $analyzed_display_query[0]['section_before_limit']
1133 . "\n" . $GLOBALS['sql_limit_to_append']
1134 . $analyzed_display_query[0]['section_after_limit'];
1135 // Need to reparse query
1136 $parsed_sql = PMA_SQP_parse($query_base);
1140 if (! empty($GLOBALS['show_as_php'])) {
1141 $query_base = '$sql = "' . $query_base;
1142 } elseif (! empty($GLOBALS['validatequery'])) {
1143 $query_base = PMA_validateSQL($query_base);
1144 } elseif (isset($parsed_sql)) {
1145 $query_base = PMA_formatSql($parsed_sql, $query_base);
1148 // Prepares links that may be displayed to edit/explain the query
1149 // (don't go to default pages, we must go to the page
1150 // where the query box is available)
1152 // Basic url query part
1153 $url_params = array();
1154 if (strlen($GLOBALS['db'])) {
1155 $url_params['db'] = $GLOBALS['db'];
1156 if (strlen($GLOBALS['table'])) {
1157 $url_params['table'] = $GLOBALS['table'];
1158 $edit_link = 'tbl_sql.php';
1160 $edit_link = 'db_sql.php';
1163 $edit_link = 'server_sql.php';
1166 // Want to have the query explained (Mike Beck 2002-05-22)
1167 // but only explain a SELECT (that has not been explained)
1168 /* SQL-Parser-Analyzer */
1170 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1171 $explain_params = $url_params;
1172 // Detect if we are validating as well
1173 // To preserve the validate uRL data
1174 if (! empty($GLOBALS['validatequery'])) {
1175 $explain_params['validatequery'] = 1;
1178 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1179 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1180 $_message = $GLOBALS['strExplain'];
1181 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1182 $explain_params['sql_query'] = substr($sql_query, 8);
1183 $_message = $GLOBALS['strNoExplain'];
1185 if (isset($explain_params['sql_query'])) {
1186 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1187 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1191 $url_params['sql_query'] = $sql_query;
1192 $url_params['show_query'] = 1;
1194 // even if the query is big and was truncated, offer the chance
1195 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1196 if (! empty($cfg['SQLQuery']['Edit'])) {
1197 if ($cfg['EditInWindow'] == true) {
1198 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1203 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1204 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1209 $url_qpart = PMA_generate_common_url($url_params);
1211 // Also we would like to get the SQL formed in some nice
1212 // php-code (Mike Beck 2002-05-22)
1213 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1214 $php_params = $url_params;
1216 if (! empty($GLOBALS['show_as_php'])) {
1217 $_message = $GLOBALS['strNoPhp'];
1219 $php_params['show_as_php'] = 1;
1220 $_message = $GLOBALS['strPhp'];
1223 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1224 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1226 if (isset($GLOBALS['show_as_php'])) {
1227 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1228 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1235 if (! empty($cfg['SQLQuery']['Refresh'])
1236 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1237 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1238 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1243 if (! empty($cfg['SQLValidator']['use'])
1244 && ! empty($cfg['SQLQuery']['Validate'])) {
1245 $validate_params = $url_params;
1246 if (!empty($GLOBALS['validatequery'])) {
1247 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1249 $validate_params['validatequery'] = 1;
1250 $validate_message = $GLOBALS['strValidateSQL'] ;
1253 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1254 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1256 $validate_link = '';
1259 echo '<code class="sql">';
1260 if ($query_too_big) {
1261 echo $shortened_query_base;
1266 //Clean up the end of the PHP
1267 if (! empty($GLOBALS['show_as_php'])) {
1272 echo '<div class="tools">';
1273 // avoid displaying a Profiling checkbox that could
1274 // be checked, which would reexecute an INSERT, for example
1275 if (! empty($refresh_link)) {
1276 PMA_profilingCheckbox($sql_query);
1278 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1281 echo '</div><br />' . "\n";
1282 } // end of the 'PMA_showMessage()' function
1285 * Verifies if current MySQL server supports profiling
1287 * @uses $_SESSION['profiling_supported'] for caching
1288 * @uses $GLOBALS['server']
1289 * @uses PMA_DBI_fetch_value()
1290 * @uses PMA_MYSQL_INT_VERSION
1293 * @return boolean whether profiling is supported
1295 * @author Marc Delisle
1297 function PMA_profilingSupported()
1299 if (! PMA_cacheExists('profiling_supported', true)) {
1300 // 5.0.37 has profiling but for example, 5.1.20 does not
1301 // (avoid a trip to the server for MySQL before 5.0.37)
1302 // and do not set a constant as we might be switching servers
1303 if (defined('PMA_MYSQL_INT_VERSION')
1304 && PMA_MYSQL_INT_VERSION
>= 50037
1305 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1306 PMA_cacheSet('profiling_supported', true, true);
1308 PMA_cacheSet('profiling_supported', false, true);
1312 return PMA_cacheGet('profiling_supported', true);
1316 * Displays a form with the Profiling checkbox
1318 * @param string $sql_query
1321 * @author Marc Delisle
1323 function PMA_profilingCheckbox($sql_query)
1325 if (PMA_profilingSupported()) {
1326 echo '<form action="sql.php" method="post">' . "\n";
1327 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1328 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1329 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1330 PMA_display_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1331 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1332 echo '</form>' . "\n";
1337 * Displays the results of SHOW PROFILE
1339 * @param array the results
1342 * @author Marc Delisle
1344 function PMA_profilingResults($profiling_results)
1346 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1347 echo '<table>' . "\n";
1348 echo ' <tr>' . "\n";
1349 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1350 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1351 echo ' </tr>' . "\n";
1353 foreach($profiling_results as $one_result) {
1354 echo ' <tr>' . "\n";
1355 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1356 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1358 echo '</table>' . "\n";
1359 echo '</fieldset>' . "\n";
1363 * Formats $value to byte view
1365 * @param double the value to format
1366 * @param integer the sensitiveness
1367 * @param integer the number of decimals to retain
1369 * @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 $dh = PMA_pow(10, $comma);
1379 $li = PMA_pow(10, $limes);
1380 $return_value = $value;
1381 $unit = $GLOBALS['byteUnits'][0];
1383 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1384 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1385 // use 1024.0 to avoid integer overflow on 64-bit machines
1386 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1387 $unit = $GLOBALS['byteUnits'][$d];
1392 if ($unit != $GLOBALS['byteUnits'][0]) {
1393 // if the unit is not bytes (as represented in current language)
1394 // reformat with max length of 5
1395 // 4th parameter=true means do not reformat if value < 1
1396 $return_value = PMA_formatNumber($value, 5, $comma, true);
1398 // do not reformat, just handle the locale
1399 $return_value = PMA_formatNumber($value, 0);
1402 return array(trim($return_value), $unit);
1403 } // end of the 'PMA_formatByteDown' function
1406 * Formats $value to the given length and appends SI prefixes
1407 * $comma is not substracted from the length
1408 * with a $length of 0 no truncation occurs, number is only formated
1409 * to the current locale
1413 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1414 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1415 * echo PMA_formatNumber(-0.003, 6); // -3 m
1416 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1417 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1418 * echo PMA_formatNumber(0, 6); // 0
1421 * @param double $value the value to format
1422 * @param integer $length the max length
1423 * @param integer $comma the number of decimals to retain
1424 * @param boolean $only_down do not reformat numbers below 1
1426 * @return string the formatted value and its unit
1430 * @author staybyte, sebastian mendel
1431 * @version 1.1.0 - 2005-10-27
1433 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1435 //number_format is not multibyte safe, str_replace is safe
1436 if ($length === 0) {
1437 return str_replace(array(',', '.'),
1438 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1439 number_format($value, $comma));
1442 // this units needs no translation, ISO
1463 // we need at least 3 digits to be displayed
1464 if (3 > $length +
$comma) {
1465 $length = 3 - $comma;
1468 // check for negative value to retain sign
1471 $value = abs($value);
1476 $dh = PMA_pow(10, $comma);
1477 $li = PMA_pow(10, $length);
1481 for ($d = 8; $d >= 0; $d--) {
1482 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1483 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1488 } elseif (!$only_down && (float) $value !== 0.0) {
1489 for ($d = -8; $d <= 8; $d++
) {
1490 // force using pow() because of the negative exponent
1491 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1492 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1497 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1499 //number_format is not multibyte safe, str_replace is safe
1500 $value = str_replace(array(',', '.'),
1501 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1502 number_format($value, $comma));
1504 return $sign . $value . ' ' . $unit;
1505 } // end of the 'PMA_formatNumber' function
1508 * Writes localised date
1510 * @param string the current timestamp
1512 * @return string the formatted date
1516 function PMA_localisedDate($timestamp = -1, $format = '')
1518 global $datefmt, $month, $day_of_week;
1520 if ($format == '') {
1524 if ($timestamp == -1) {
1525 $timestamp = time();
1528 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1529 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1531 return strftime($date, $timestamp);
1532 } // end of the 'PMA_localisedDate()' function
1536 * returns a tab for tabbed navigation.
1537 * If the variables $link and $args ar left empty, an inactive tab is created
1539 * @uses $GLOBALS['PMA_PHP_SELF']
1540 * @uses $GLOBALS['strEmpty']
1541 * @uses $GLOBALS['strDrop']
1542 * @uses $GLOBALS['active_page']
1543 * @uses $GLOBALS['url_query']
1544 * @uses $cfg['MainPageIconic']
1545 * @uses $GLOBALS['pmaThemeImage']
1546 * @uses PMA_generate_common_url()
1547 * @uses E_USER_NOTICE
1548 * @uses htmlentities()
1551 * @uses trigger_error()
1552 * @uses array_merge()
1554 * @param array $tab array with all options
1555 * @param array $url_params
1556 * @return string html code for one tab, a link if valid otherwise a span
1559 function PMA_generate_html_tab($tab, $url_params = array())
1574 $tab = array_merge($defaults, $tab);
1576 // determine additionnal style-class
1577 if (empty($tab['class'])) {
1578 if ($tab['text'] == $GLOBALS['strEmpty']
1579 ||
$tab['text'] == $GLOBALS['strDrop']) {
1580 $tab['class'] = 'caution';
1581 } elseif (! empty($tab['active'])
1582 ||
PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1583 $tab['class'] = 'active';
1584 } elseif (empty($GLOBALS['active_page'])
1585 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1586 && empty($tab['warning'])) {
1587 $tab['class'] = 'active';
1591 if (!empty($tab['warning'])) {
1592 $tab['class'] .= ' warning';
1593 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1596 // If there are any tab specific URL parameters, merge those with the general URL parameters
1597 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1598 $url_params = array_merge($url_params, $tab['url_params']);
1602 if (!empty($tab['link'])) {
1603 $tab['link'] = htmlentities($tab['link']);
1604 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1605 if (! empty($tab['args'])) {
1606 foreach ($tab['args'] as $param => $value) {
1607 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1608 . urlencode($value);
1613 if (! empty($tab['fragment'])) {
1614 $tab['link'] .= $tab['fragment'];
1617 // display icon, even if iconic is disabled but the link-text is missing
1618 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1619 && isset($tab['icon'])) {
1620 // avoid generating an alt tag, because it only illustrates
1621 // the text that follows and if browser does not display
1622 // images, the text is duplicated
1623 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1624 .'%1$s" width="16" height="16" alt="" />%2$s';
1625 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1627 // check to not display an empty link-text
1628 elseif (empty($tab['text'])) {
1630 trigger_error('empty linktext in function ' . __FUNCTION__
. '()',
1634 $out = '<li' . ($tab['class'] == 'active' ?
' class="active"' : '') . '>';
1636 if (!empty($tab['link'])) {
1637 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1638 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1639 . $tab['text'] . '</a>';
1641 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1642 . $tab['text'] . '</span>';
1647 } // end of the 'PMA_generate_html_tab()' function
1650 * returns html-code for a tab navigation
1652 * @uses PMA_generate_html_tab()
1653 * @uses htmlentities()
1654 * @param array $tabs one element per tab
1655 * @param string $url_params
1656 * @return string html-code for tab-navigation
1658 function PMA_generate_html_tabs($tabs, $url_params)
1660 $tag_id = 'topmenu';
1662 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1663 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1665 foreach ($tabs as $tab) {
1666 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1671 .'<div class="clearfloat"></div>'
1674 return $tab_navigation;
1679 * Displays a link, or a button if the link's URL is too large, to
1680 * accommodate some browsers' limitations
1682 * @param string the URL
1683 * @param string the link message
1684 * @param mixed $tag_params string: js confirmation
1685 * array: additional tag params (f.e. style="")
1686 * @param boolean $new_form we set this to false when we are already in
1687 * a form, to avoid generating nested forms
1689 * @return string the results to be echoed or saved in an array
1691 function PMA_linkOrButton($url, $message, $tag_params = array(),
1692 $new_form = true, $strip_img = false, $target = '')
1694 $url_length = strlen($url);
1695 // with this we should be able to catch case of image upload
1696 // into a (MEDIUM) BLOB; not worth generating even a form for these
1697 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1701 if (! is_array($tag_params)) {
1703 $tag_params = array();
1705 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1709 if (! empty($target)) {
1710 $tag_params['target'] = htmlentities($target);
1713 $tag_params_strings = array();
1714 foreach ($tag_params as $par_name => $par_value) {
1715 // htmlspecialchars() only on non javascript
1716 $par_value = substr($par_name, 0, 2) == 'on'
1718 : htmlspecialchars($par_value);
1719 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1722 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1723 // no whitespace within an <a> else Safari will make it part of the link
1724 $ret = "\n" . '<a href="' . $url . '" '
1725 . implode(' ', $tag_params_strings) . '>'
1726 . $message . '</a>' . "\n";
1728 // no spaces (linebreaks) at all
1729 // or after the hidden fields
1730 // IE will display them all
1732 // add class=link to submit button
1733 if (empty($tag_params['class'])) {
1734 $tag_params['class'] = 'link';
1737 // decode encoded url separators
1738 $separator = PMA_get_arg_separator();
1739 // on most places separator is still hard coded ...
1740 if ($separator !== '&') {
1741 // ... so always replace & with $separator
1742 $url = str_replace(htmlentities('&'), $separator, $url);
1743 $url = str_replace('&', $separator, $url);
1745 $url = str_replace(htmlentities($separator), $separator, $url);
1748 $url_parts = parse_url($url);
1749 $query_parts = explode($separator, $url_parts['query']);
1751 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1752 . ' method="post"' . $target . ' style="display: inline;">';
1754 $subname_close = '';
1757 $query_parts[] = 'redirect=' . $url_parts['path'];
1758 if (empty($GLOBALS['subform_counter'])) {
1759 $GLOBALS['subform_counter'] = 0;
1761 $GLOBALS['subform_counter']++
;
1763 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1764 $subname_close = ']';
1765 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1767 foreach ($query_parts as $query_pair) {
1768 list($eachvar, $eachval) = explode('=', $query_pair);
1769 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1770 . $subname_close . '" value="'
1771 . htmlspecialchars(urldecode($eachval)) . '" />';
1774 if (stristr($message, '<img')) {
1776 $message = trim(strip_tags($message));
1777 $ret .= '<input type="submit"' . $submit_name . ' '
1778 . implode(' ', $tag_params_strings)
1779 . ' value="' . htmlspecialchars($message) . '" />';
1781 $displayed_message = htmlspecialchars(
1782 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1784 $ret .= '<input type="image"' . $submit_name . ' '
1785 . implode(' ', $tag_params_strings)
1786 . ' src="' . preg_replace(
1787 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1788 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1791 $message = trim(strip_tags($message));
1792 $ret .= '<input type="submit"' . $submit_name . ' '
1793 . implode(' ', $tag_params_strings)
1794 . ' value="' . htmlspecialchars($message) . '" />';
1799 } // end if... else...
1802 } // end of the 'PMA_linkOrButton()' function
1806 * Returns a given timespan value in a readable format.
1808 * @uses $GLOBALS['timespanfmt']
1811 * @param int the timespan
1813 * @return string the formatted value
1815 function PMA_timespanFormat($seconds)
1817 $return_string = '';
1818 $days = floor($seconds / 86400);
1820 $seconds -= $days * 86400;
1822 $hours = floor($seconds / 3600);
1823 if ($days > 0 ||
$hours > 0) {
1824 $seconds -= $hours * 3600;
1826 $minutes = floor($seconds / 60);
1827 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1828 $seconds -= $minutes * 60;
1830 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1834 * Takes a string and outputs each character on a line for itself. Used
1835 * mainly for horizontalflipped display mode.
1836 * Takes care of special html-characters.
1837 * Fulfills todo-item
1838 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1840 * @todo add a multibyte safe function PMA_STR_split()
1842 * @param string The string
1843 * @param string The Separator (defaults to "<br />\n")
1846 * @author Garvin Hicking <me@supergarv.de>
1847 * @return string The flipped string
1849 function PMA_flipstring($string, $Separator = "<br />\n")
1851 $format_string = '';
1854 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++
) {
1855 $char = $string{$i};
1859 $format_string .= $charbuff;
1861 } elseif ($char == ';' && !empty($charbuff)) {
1862 $format_string .= $charbuff . $char;
1865 } elseif (! empty($charbuff)) {
1868 $format_string .= $char;
1872 // do not add separator after the last character
1873 if ($append && ($i != $str_len - 1)) {
1874 $format_string .= $Separator;
1878 return $format_string;
1883 * Function added to avoid path disclosures.
1884 * Called by each script that needs parameters, it displays
1885 * an error message and, by default, stops the execution.
1887 * Not sure we could use a strMissingParameter message here,
1888 * would have to check if the error message file is always available
1890 * @todo localize error message
1891 * @todo use PMA_fatalError() if $die === true?
1892 * @uses PMA_getenv()
1893 * @uses header_meta_style.inc.php
1894 * @uses $GLOBALS['PMA_PHP_SELF']
1896 * @param array The names of the parameters needed by the calling
1898 * @param boolean Stop the execution?
1899 * (Set this manually to false in the calling script
1900 * until you know all needed parameters to check).
1901 * @param boolean Whether to include this list in checking for special params.
1902 * @global string path to current script
1903 * @global boolean flag whether any special variable was required
1906 * @author Marc Delisle (lem9@users.sourceforge.net)
1908 function PMA_checkParameters($params, $die = true, $request = true)
1910 global $checked_special;
1912 if (!isset($checked_special)) {
1913 $checked_special = false;
1916 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1917 $found_error = false;
1918 $error_message = '';
1920 foreach ($params as $param) {
1921 if ($request && $param != 'db' && $param != 'table') {
1922 $checked_special = true;
1925 if (!isset($GLOBALS[$param])) {
1926 $error_message .= $reported_script_name
1927 . ': Missing parameter: ' . $param
1928 . ' <a href="./Documentation.html#faqmissingparameters"'
1929 . ' target="documentation"> (FAQ 2.8)</a><br />';
1930 $found_error = true;
1935 * display html meta tags
1937 require_once './libraries/header_meta_style.inc.php';
1938 echo '</head><body><p>' . $error_message . '</p></body></html>';
1946 * Function to generate unique condition for specified row.
1948 * @uses $GLOBALS['analyzed_sql'][0]
1949 * @uses PMA_DBI_field_flags()
1950 * @uses PMA_backquote()
1951 * @uses PMA_sqlAddslashes()
1952 * @uses PMA_printable_bit_value()
1955 * @uses preg_replace()
1956 * @param resource $handle current query result
1957 * @param integer $fields_cnt number of fields
1958 * @param array $fields_meta meta information about fields
1959 * @param array $row current row
1960 * @param boolean $force_unique generate condition only on pk or unique
1963 * @author Michal Cihar (michal@cihar.com) and others...
1964 * @return string the calculated condition and whether condition is unique
1966 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1970 $nonprimary_condition = '';
1971 $preferred_condition = '';
1973 for ($i = 0; $i < $fields_cnt; ++
$i) {
1975 $field_flags = PMA_DBI_field_flags($handle, $i);
1976 $meta = $fields_meta[$i];
1978 // do not use a column alias in a condition
1979 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
1980 $meta->orgname
= $meta->name
;
1982 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1983 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1984 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1986 // need (string) === (string)
1987 // '' !== 0 but '' == 0
1988 if ((string) $select_expr['alias'] === (string) $meta->name
) {
1989 $meta->orgname
= $select_expr['column'];
1996 // Do not use a table alias in a condition.
1998 // select * from galerie x WHERE
1999 //(select count(*) from galerie y where y.datum=x.datum)>1
2001 // But orgtable is present only with mysqli extension so the
2002 // fix is only for mysqli.
2003 // Also, do not use the original table name if we are dealing with
2004 // a view because this view might be updatable.
2005 // (The isView() verification should not be costly in most cases
2006 // because there is some caching in the function).
2007 if (isset($meta->orgtable
) && $meta->table
!= $meta->orgtable
&& ! PMA_Table
::isView($GLOBALS['db'], $meta->table
)) {
2008 $meta->table
= $meta->orgtable
;
2011 // to fix the bug where float fields (primary or not)
2012 // can't be matched because of the imprecision of
2013 // floating comparison, use CONCAT
2014 // (also, the syntax "CONCAT(field) IS NULL"
2015 // that we need on the next "if" will work)
2016 if ($meta->type
== 'real') {
2017 $condition = ' CONCAT(' . PMA_backquote($meta->table
) . '.'
2018 . PMA_backquote($meta->orgname
) . ') ';
2020 $condition = ' ' . PMA_backquote($meta->table
) . '.'
2021 . PMA_backquote($meta->orgname
) . ' ';
2022 } // end if... else...
2024 if (!isset($row[$i]) ||
is_null($row[$i])) {
2025 $condition .= 'IS NULL AND';
2027 // timestamp is numeric on some MySQL 4.1
2028 if ($meta->numeric && $meta->type
!= 'timestamp') {
2029 $condition .= '= ' . $row[$i] . ' AND';
2030 } elseif (($meta->type
== 'blob' ||
$meta->type
== 'string')
2031 // hexify only if this is a true not empty BLOB or a BINARY
2032 && stristr($field_flags, 'BINARY')
2033 && !empty($row[$i])) {
2034 // do not waste memory building a too big condition
2035 if (strlen($row[$i]) < 1000) {
2036 // use a CAST if possible, to avoid problems
2037 // if the field contains wildcard characters % or _
2038 $condition .= '= CAST(0x' . bin2hex($row[$i])
2039 . ' AS BINARY) AND';
2041 // this blob won't be part of the final condition
2044 } elseif ($meta->type
== 'bit') {
2045 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length
) . "' AND";
2047 $condition .= '= \''
2048 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2051 if ($meta->primary_key
> 0) {
2052 $primary_key .= $condition;
2053 } elseif ($meta->unique_key
> 0) {
2054 $unique_key .= $condition;
2056 $nonprimary_condition .= $condition;
2059 // Correction University of Virginia 19991216:
2060 // prefer primary or unique keys for condition,
2061 // but use conjunction of all values if no primary key
2062 $clause_is_unique = true;
2064 $preferred_condition = $primary_key;
2065 } elseif ($unique_key) {
2066 $preferred_condition = $unique_key;
2067 } elseif (! $force_unique) {
2068 $preferred_condition = $nonprimary_condition;
2069 $clause_is_unique = false;
2072 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2073 return(array($where_clause, $clause_is_unique));
2077 * Generate a button or image tag
2079 * @uses PMA_USR_BROWSER_AGENT
2080 * @uses $GLOBALS['pmaThemeImage']
2081 * @uses $GLOBALS['cfg']['PropertiesIconic']
2082 * @param string name of button element
2083 * @param string class of button element
2084 * @param string name of image element
2085 * @param string text to display
2086 * @param string image to display
2089 * @author Michal Cihar (michal@cihar.com)
2091 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2094 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2095 echo ' <input type="submit" name="' . $button_name . '"'
2096 .' value="' . htmlspecialchars($text) . '"'
2097 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2101 /* Opera has trouble with <input type="image"> */
2102 /* IE has trouble with <button> */
2103 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2104 echo '<button class="' . $button_class . '" type="submit"'
2105 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2106 .' title="' . htmlspecialchars($text) . '">' . "\n"
2107 . PMA_getIcon($image, $text)
2108 .'</button>' . "\n";
2110 echo '<input type="image" name="' . $image_name . '" value="'
2111 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2113 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ?
' ' . htmlspecialchars($text) : '') . "\n";
2118 * Generate a pagination selector for browsing resultsets
2120 * @todo $url is not javascript escaped!?
2121 * @uses $GLOBALS['strPageNumber']
2123 * @param string URL for the JavaScript
2124 * @param string Number of rows in the pagination set
2125 * @param string current page number
2126 * @param string number of total pages
2127 * @param string If the number of pages is lower than this
2128 * variable, no pages will be omitted in
2130 * @param string How many rows at the beginning should always
2132 * @param string How many rows at the end should always
2134 * @param string Percentage of calculation page offsets to
2135 * hop to a next page
2136 * @param string Near the current page, how many pages should
2137 * be considered "nearby" and displayed as
2139 * @param string The prompt to display (sometimes empty)
2142 * @author Garvin Hicking (pma@supergarv.de)
2144 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2145 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2146 $range = 10, $prompt = '')
2148 $increment = floor($nbTotalPage / $percent);
2149 $pageNowMinusRange = ($pageNow - $range);
2150 $pageNowPlusRange = ($pageNow +
$range);
2153 . ' <select name="pos" onchange="goToUrl(this, \''
2154 . $url . '\');">' . "\n";
2155 if ($nbTotalPage < $showAll) {
2156 $pages = range(1, $nbTotalPage);
2160 // Always show first X pages
2161 for ($i = 1; $i <= $sliceStart; $i++
) {
2165 // Always show last X pages
2166 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2170 // garvin: Based on the number of results we add the specified
2171 // $percent percentage to each page number,
2172 // so that we have a representing page number every now and then to
2173 // immediately jump to specific pages.
2174 // As soon as we get near our currently chosen page ($pageNow -
2175 // $range), every page number will be shown.
2177 $x = $nbTotalPage - $sliceEnd;
2178 $met_boundary = false;
2180 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2181 // If our pageselector comes near the current page, we use 1
2182 // counter increments
2184 $met_boundary = true;
2186 // We add the percentage increment to our current page to
2187 // hop to the next one in range
2190 // Make sure that we do not cross our boundaries.
2191 if ($i > $pageNowMinusRange && ! $met_boundary) {
2192 $i = $pageNowMinusRange;
2196 if ($i > 0 && $i <= $x) {
2201 // Since because of ellipsing of the current page some numbers may be double,
2202 // we unify our array:
2204 $pages = array_unique($pages);
2207 foreach ($pages as $i) {
2208 if ($i == $pageNow) {
2209 $selected = 'selected="selected" style="font-weight: bold"';
2213 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2216 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2223 * Generate navigation for a list
2225 * @todo use $pos from $_url_params
2226 * @uses $GLOBALS['strPageNumber']
2228 * @param integer number of elements in the list
2229 * @param integer current position in the list
2230 * @param array url parameters
2231 * @param string script name for form target
2232 * @param string target frame
2233 * @param integer maximum number of elements to display from the list
2237 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2239 if ($max_count < $count) {
2240 echo 'frame_navigation' == $frame ?
'<div id="navidbpageselector">' . "\n" : '';
2241 echo $GLOBALS['strPageNumber'];
2242 echo 'frame_navigation' == $frame ?
'<br />' : ' ';
2244 // Move to the beginning or to the previous page
2246 // loic1: patch #474210 from Gosha Sakovich - part 1
2247 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2248 $caption1 = '<<';
2249 $caption2 = ' < ';
2250 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2251 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2253 $caption1 = $GLOBALS['strPos1'] . ' <<';
2254 $caption2 = $GLOBALS['strPrevious'] . ' <';
2257 } // end if... else...
2258 $_url_params['pos'] = 0;
2259 echo '<a' . $title1 . ' href="' . $script
2260 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2261 . $caption1 . '</a>';
2262 $_url_params['pos'] = $pos - $max_count;
2263 echo '<a' . $title2 . ' href="' . $script
2264 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2265 . $caption2 . '</a>';
2268 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2269 echo PMA_generate_common_hidden_inputs($_url_params);
2270 echo PMA_pageselector(
2271 $script . PMA_generate_common_url($_url_params) . '&',
2273 floor(($pos +
1) / $max_count) +
1,
2274 ceil($count / $max_count));
2277 if ($pos +
$max_count < $count) {
2278 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2279 $caption3 = ' > ';
2280 $caption4 = '>>';
2281 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2282 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2284 $caption3 = '> ' . $GLOBALS['strNext'];
2285 $caption4 = '>> ' . $GLOBALS['strEnd'];
2288 } // end if... else...
2289 $_url_params['pos'] = $pos +
$max_count;
2290 echo '<a' . $title3 . ' href="' . $script
2291 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2292 . $caption3 . '</a>';
2293 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2294 if ($_url_params['pos'] == $count) {
2295 $_url_params['pos'] = $count - $max_count;
2297 echo '<a' . $title4 . ' href="' . $script
2298 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2299 . $caption4 . '</a>';
2302 if ('frame_navigation' == $frame) {
2303 echo '</div>' . "\n";
2309 * replaces %u in given path with current user name
2313 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2316 * @uses $cfg['Server']['user']
2318 * @uses str_replace()
2319 * @param string $dir with wildcard for user
2320 * @return string per user directory
2322 function PMA_userDir($dir)
2324 // add trailing slash
2325 if (substr($dir, -1) != '/') {
2329 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2333 * returns html code for db link to default db page
2335 * @uses $cfg['DefaultTabDatabase']
2336 * @uses $GLOBALS['db']
2337 * @uses $GLOBALS['strJumpToDB']
2338 * @uses PMA_generate_common_url()
2339 * @uses PMA_unescape_mysql_wildcards()
2342 * @uses htmlspecialchars()
2343 * @param string $database
2344 * @return string html link to default db page
2346 function PMA_getDbLink($database = null)
2348 if (!strlen($database)) {
2349 if (!strlen($GLOBALS['db'])) {
2352 $database = $GLOBALS['db'];
2354 $database = PMA_unescape_mysql_wildcards($database);
2357 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2358 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2359 .htmlspecialchars($database) . '</a>';
2363 * Displays a lightbulb hint explaining a known external bug
2364 * that affects a functionality
2366 * @uses PMA_MYSQL_INT_VERSION
2367 * @uses $GLOBALS['strKnownExternalBug']
2368 * @uses PMA_showHint()
2370 * @param string $functionality localized message explaining the func.
2371 * @param string $component 'mysql' (eventually, 'php')
2372 * @param string $minimum_version of this component
2373 * @param string $bugref bug reference for this component
2375 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2377 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION
< $minimum_version) {
2378 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2383 * Generates and echoes an HTML checkbox
2385 * @param string $html_field_name the checkbox HTML field
2386 * @param string $label
2387 * @param boolean $checked is it initially checked?
2388 * @param boolean $onclick should it submit the form on click?
2390 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2392 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>';
2396 * Generates and echoes a set of radio HTML fields
2398 * @uses htmlspecialchars()
2399 * @param string $html_field_name the radio HTML field
2400 * @param array $choices the choices values and labels
2401 * @param string $checked_choice the choice to check by default
2402 * @param boolean $line_break whether to add an HTML line break after a choice
2403 * @param boolean $escape_label whether to use htmlspecialchars() on label
2404 * @param string $class enclose each choice with a div of this class
2406 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2407 foreach ($choices as $choice_value => $choice_label) {
2408 if (! empty($class)) {
2409 echo '<div class="' . $class . '">';
2411 $html_field_id = $html_field_name . '_' . $choice_value;
2412 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2413 if ($choice_value == $checked_choice) {
2414 echo ' checked="checked"';
2417 echo '<label for="' . $html_field_id . '">' . ($escape_label ?
htmlspecialchars($choice_label) : $choice_label) . '</label>';
2421 if (! empty($class)) {
2429 * Generates and returns an HTML dropdown
2431 * @uses htmlspecialchars()
2432 * @param string $select_name
2433 * @param array $choices the choices values
2434 * @param string $active_choice the choice to select by default
2435 * @param string $id the id of the select element; can be different in case
2436 * the dropdown is present more than once on the page
2437 * @todo support titles
2439 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2441 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2442 foreach ($choices as $one_choice_value => $one_choice_label) {
2443 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2444 if ($one_choice_value == $active_choice) {
2445 $result .= ' selected="selected"';
2447 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2449 $result .= '</select>';
2454 * Generates a slider effect (Mootools)
2455 * Takes care of generating the initial <div> and the link
2456 * controlling the slider; you have to generate the </div> yourself
2457 * after the sliding section.
2459 * @uses $GLOBALS['cfg']['InitialSlidersState']
2460 * @param string $id the id of the <div> on which to apply the effect
2461 * @param string $message the message to show as a link
2463 function PMA_generate_slider_effect($id, $message)
2465 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2466 echo '<div id="' . $id . '">';
2470 <script type
="text/javascript">
2472 window
.addEvent('domready', function(){
2478 var anchor
<?php
echo $id; ?
> = new Element('a', {
2479 'id': 'toggle_<?php echo $id; ?>',
2480 'href': 'javascript:void(0)',
2482 'click': function(){
2483 mySlide
<?php
echo $id; ?
>.toggle();
2488 anchor
<?php
echo $id; ?
>.appendText('<?php echo $message; ?>');
2489 anchor
<?php
echo $id; ?
>.injectBefore('<?php echo $id; ?>');
2491 var slider_status
<?php
echo $id; ?
> = new Element('span', {
2492 'id': 'slider_status_<?php echo $id; ?>'
2494 slider_status
<?php
echo $id; ?
>.appendText('<?php echo $GLOBALS['cfg
']['InitialSlidersState
'] == 'closed
' ? '+
' : '-';?> ');
2495 slider_status
<?php
echo $id; ?
>.injectBefore('toggle_<?php echo $id; ?>');
2497 var mySlide
<?php
echo $id; ?
> = new Fx
.Slide('<?php echo $id; ?>');
2499 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2501 mySlide
<?php
echo $id; ?
>.hide();
2505 mySlide
<?php
echo $id; ?
>.addEvent('complete', function() {
2506 $
('slider_status_<?php echo $id; ?>').set('html', status
[mySlide
<?php
echo $id; ?
>.open
]);
2509 $
('<?php echo $id; ?>').style
.display
="block";
2511 document
.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg
']['InitialSlidersState
'] == 'closed
' ? ' style
="display: none;"' : ''; ?>>');
2515 <div id
="<?php echo $id; ?>" />
2521 * Verifies if something is cached in the session
2523 * @param string $var
2524 * @param scalar $server
2527 function PMA_cacheExists($var, $server = 0)
2529 if (true === $server) {
2530 $server = $GLOBALS['server'];
2532 return isset($_SESSION['cache']['server_' . $server][$var]);
2536 * Gets cached information from the session
2538 * @param string $var
2539 * @param scalar $server
2542 function PMA_cacheGet($var, $server = 0)
2544 if (true === $server) {
2545 $server = $GLOBALS['server'];
2547 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2548 return $_SESSION['cache']['server_' . $server][$var];
2555 * Caches information in the session
2557 * @param string $var
2559 * @param integer $server
2562 function PMA_cacheSet($var, $val = null, $server = 0)
2564 if (true === $server) {
2565 $server = $GLOBALS['server'];
2567 $_SESSION['cache']['server_' . $server][$var] = $val;
2571 * Removes cached information from the session
2573 * @param string $var
2574 * @param scalar $server
2576 function PMA_cacheUnset($var, $server = 0)
2578 if (true === $server) {
2579 $server = $GLOBALS['server'];
2581 unset($_SESSION['cache']['server_' . $server][$var]);
2585 * Converts a bit value to printable format;
2586 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2587 * function because in PHP, decbin() supports only 32 bits
2594 * @param numeric $value coming from a BIT field
2595 * @param integer $length
2596 * @return string the printable value
2598 function PMA_printable_bit_value($value, $length) {
2600 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++
) {
2601 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2603 $printable = substr($printable, -$length);
2608 * Verifies whether the value contains a non-printable character
2610 * @uses preg_match()
2611 * @param string $value
2614 function PMA_contains_nonprintable_ascii($value) {
2615 return preg_match('@[^[:print:]]@', $value);
2619 * Converts a BIT type default value
2620 * for example, b'010' becomes 010
2623 * @param string $bit_default_value
2624 * @return string the converted value
2626 function PMA_convert_bit_default_value($bit_default_value) {
2627 return strtr($bit_default_value, array("b" => "", "'" => ""));
2631 * Extracts the various parts from a field type spec
2636 * @param string $fieldspec
2637 * @return array associative array containing type, spec_in_brackets
2638 * and possibly enum_set_values (another array)
2639 * @author Marc Delisle
2640 * @author Joshua Hogendorn
2642 function PMA_extractFieldSpec($fieldspec) {
2643 $first_bracket_pos = strpos($fieldspec, '(');
2644 if ($first_bracket_pos) {
2645 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos +
1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2646 // convert to lowercase just to be sure
2647 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2650 $spec_in_brackets = '';
2653 if ('enum' == $type ||
'set' == $type) {
2654 // Define our working vars
2655 $enum_set_values = array();
2660 // While there is another character to process
2661 while (isset($fieldspec[$index])) {
2662 // Grab the char to look at
2663 $char = $fieldspec[$index];
2665 // If it is a single quote, needs to be handled specially
2667 // If we are not currently in a string, begin one
2671 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2673 // Check out the next character (if possible)
2674 $has_next = isset($fieldspec[$index +
1]);
2675 $next = $has_next ?
$fieldspec[$index +
1] : null;
2677 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2678 if (! $has_next ||
$next != "'") {
2679 $enum_set_values[] = $working;
2682 // Otherwise, this is a 'double quote', and can be added to the working string
2683 } elseif ($next == "'") {
2685 // Skip the next char; we already know what it is
2689 // escaping of a quote?
2690 } elseif ('\\' == $char && isset($fieldspec[$index +
1]) && "'" == $fieldspec[$index +
1]) {
2693 // Otherwise, add it to our working string like normal
2697 // Increment character index
2701 $enum_set_values = array();
2706 'spec_in_brackets' => $spec_in_brackets,
2707 'enum_set_values' => $enum_set_values
2712 * Verifies if this table's engine supports foreign keys
2714 * @uses strtoupper()
2715 * @param string $engine
2718 function PMA_foreignkey_supported($engine) {
2719 $engine = strtoupper($engine);
2720 if ('INNODB' == $engine ||
'PBXT' == $engine) {
2728 * Replaces some characters by a displayable equivalent
2730 * @uses str_replace()
2731 * @param string $content
2732 * @return string the content with characters replaced
2734 function PMA_replace_binary_contents($content) {
2735 $result = str_replace("\x00", '\0', $content);
2736 $result = str_replace("\x08", '\b', $result);
2737 $result = str_replace("\x0a", '\n', $result);
2738 $result = str_replace("\x0d", '\r', $result);
2739 $result = str_replace("\x1a", '\Z', $result);
2745 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2748 * @return string with the chars replaced
2751 function PMA_duplicateFirstNewline($string){
2752 $first_occurence = strpos($string, "\r\n");
2753 if ($first_occurence === 0){
2754 $string = "\n".$string;
2760 * get the action word corresponding to a script name
2761 * in order to display it as a title in navigation panel
2764 * @param string a valid value for $cfg['LeftDefaultTabTable']
2765 * or $cfg['DefaultTabTable']
2766 * or $cfg['DefaultTabDatabase']
2768 function PMA_getTitleForTarget($target) {
2769 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];
2773 * The function creates javascript and html code, which run given mootools/JS code when DOM is ready
2775 * @param String $code - Mootools/JS code, which will be run
2776 * @param boolena $print - If true, then the code is printed, otherwise is returned
2778 * @return String - the code
2780 function PMA_js_mootools_domready($code, $print=true)
2782 // these generated newlines are needed
2784 $out .= '<script type="text/javascript">';
2785 $out .= "\n" . '// <![CDATA[' . "\n";
2786 $out .= 'window.addEvent(\'domready\',function() {';
2789 $out .= "\n" . '// ]]>' . "\n";
2790 $out .= '</script>';
2798 function PMA_js($code, $print=true)
2800 // these generated newlines are needed
2802 $out .= '<script type="text/javascript">'."\n";
2803 $out .= "\n" . '// <![CDATA[' . "\n";
2805 $out .= "\n" . '// ]]>' . "\n";
2806 $out .= '</script>'."\n";