2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Misc functions used all over the scripts.
10 * Exponential expression / raise number into power
12 * @uses function_exists()
19 * @param string pow function use, or false for auto-detect
20 * @return mixed string or float
22 function PMA_pow($base, $exp, $use_function = false)
24 static $pow_function = null;
30 if (null == $pow_function) {
31 if (function_exists('bcpow')) {
32 // BCMath Arbitrary Precision Mathematics Function
33 $pow_function = 'bcpow';
34 } elseif (function_exists('gmp_pow')) {
36 $pow_function = 'gmp_pow';
39 $pow_function = 'pow';
43 if (! $use_function) {
44 $use_function = $pow_function;
47 switch ($use_function) {
50 $pow = bcpow($base, $exp);
53 $pow = gmp_strval(gmp_pow($base, $exp));
56 $base = (float) $base;
58 $pow = pow($base, $exp);
61 $pow = $use_function($base, $exp);
68 * string PMA_getIcon(string $icon)
70 * @uses $GLOBALS['pmaThemeImage']
71 * @param $icon name of icon
72 * @return html img tag
74 function PMA_getIcon($icon, $alternate = '')
76 if ($GLOBALS['cfg']['PropertiesIconic']) {
77 return '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
78 . ' title="' . $alternate . '" alt="' . $alternate . '"'
79 . ' class="icon" width="16" height="16" />';
86 * Displays the maximum size for an upload
88 * @uses $GLOBALS['strMaximumSize']
89 * @uses PMA_formatByteDown()
91 * @param integer the size
93 * @return string the message
97 function PMA_displayMaximumUploadSize($max_upload_size)
99 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size);
100 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
104 * Generates a hidden field which should indicate to the browser
105 * the maximum size for upload
107 * @param integer the size
109 * @return string the INPUT field
113 function PMA_generateHiddenMaxFileSize($max_size)
115 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
119 * Add slashes before "'" and "\" characters so a value containing them can
120 * be used in a sql comparison.
122 * @uses str_replace()
123 * @param string the string to slash
124 * @param boolean whether the string will be used in a 'LIKE' clause
125 * (it then requires two more escaped sequences) or not
126 * @param boolean whether to treat cr/lfs as escape-worthy entities
127 * (converts \n to \\n, \r to \\r)
129 * @param boolean whether this function is used as part of the
130 * "Create PHP code" dialog
132 * @return string the slashed string
136 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
139 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
141 $a_string = str_replace('\\', '\\\\', $a_string);
145 $a_string = str_replace("\n", '\n', $a_string);
146 $a_string = str_replace("\r", '\r', $a_string);
147 $a_string = str_replace("\t", '\t', $a_string);
151 $a_string = str_replace('\'', '\\\'', $a_string);
153 $a_string = str_replace('\'', '\'\'', $a_string);
157 } // end of the 'PMA_sqlAddslashes()' function
161 * Add slashes before "_" and "%" characters for using them in MySQL
162 * database, table and field names.
163 * Note: This function does not escape backslashes!
165 * @uses str_replace()
166 * @param string the string to escape
168 * @return string the escaped string
172 function PMA_escape_mysql_wildcards($name)
174 $name = str_replace('_', '\\_', $name);
175 $name = str_replace('%', '\\%', $name);
178 } // end of the 'PMA_escape_mysql_wildcards()' function
181 * removes slashes before "_" and "%" characters
182 * Note: This function does not unescape backslashes!
184 * @uses str_replace()
185 * @param string $name the string to escape
186 * @return string the escaped string
189 function PMA_unescape_mysql_wildcards($name)
191 $name = str_replace('\\_', '_', $name);
192 $name = str_replace('\\%', '%', $name);
195 } // end of the 'PMA_unescape_mysql_wildcards()' function
198 * removes quotes (',",`) from a quoted string
200 * checks if the sting is quoted and removes this quotes
202 * @uses str_replace()
204 * @param string $quoted_string string to remove quotes from
205 * @param string $quote type of quote to remove
206 * @return string unqoted string
208 function PMA_unQuote($quoted_string, $quote = null)
212 if (null === $quote) {
220 foreach ($quotes as $quote) {
221 if (substr($quoted_string, 0, 1) === $quote
222 && substr($quoted_string, -1, 1) === $quote) {
223 $unquoted_string = substr($quoted_string, 1, -1);
224 // replace escaped quotes
225 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
226 return $unquoted_string;
230 return $quoted_string;
236 * @todo move into PMA_Sql
237 * @uses PMA_SQP_isError()
238 * @uses PMA_SQP_formatHtml()
239 * @uses PMA_SQP_formatNone()
241 * @param mixed pre-parsed SQL structure
243 * @return string the formatted sql
245 * @global array the configuration array
246 * @global boolean whether the current statement is a multiple one or not
250 * @author Robin Johnson <robbat2@users.sourceforge.net>
252 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
256 // Check that we actually have a valid set of parsed data
258 // first check for the SQL parser having hit an error
259 if (PMA_SQP_isError()) {
262 // then check for an array
263 if (!is_array($parsed_sql)) {
264 // We don't so just return the input directly
265 // This is intended to be used for when the SQL Parser is turned off
266 $formatted_sql = '<pre>' . "\n"
267 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ?
$unparsed_sql : $parsed_sql) . "\n"
269 return $formatted_sql;
274 switch ($cfg['SQP']['fmtType']) {
276 if ($unparsed_sql != '') {
277 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
279 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
283 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
286 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
287 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
293 return $formatted_sql;
294 } // end of the "PMA_formatSql()" function
298 * Displays a link to the official MySQL documentation
300 * @uses $cfg['MySQLManualType']
301 * @uses $cfg['MySQLManualBase']
302 * @uses $cfg['ReplaceHelpImg']
303 * @uses $GLOBALS['mysql_4_1_doc_lang']
304 * @uses $GLOBALS['mysql_5_1_doc_lang']
305 * @uses $GLOBALS['mysql_5_0_doc_lang']
306 * @uses $GLOBALS['strDocu']
307 * @uses $GLOBALS['pmaThemeImage']
308 * @uses PMA_MYSQL_INT_VERSION
310 * @uses str_replace()
311 * @param string chapter of "HTML, one page per chapter" documentation
312 * @param string contains name of page/anchor that is being linked
313 * @param bool whether to use big icon (like in left frame)
315 * @return string the html link
319 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
323 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
327 // Fixup for newly used names:
328 $chapter = str_replace('_', '-', strtolower($chapter));
329 $link = str_replace('_', '-', strtolower($link));
331 switch ($cfg['MySQLManualType']) {
333 if (empty($chapter)) {
336 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
339 $url = $cfg['MySQLManualBase'] . '#' . $link;
345 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
354 if (defined('PMA_MYSQL_INT_VERSION')) {
355 if (PMA_MYSQL_INT_VERSION
< 50000) {
357 if (!empty($GLOBALS['mysql_4_1_doc_lang'])) {
358 $lang = $GLOBALS['mysql_4_1_doc_lang'];
360 } elseif (PMA_MYSQL_INT_VERSION
>= 50100) {
362 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
363 $lang = $GLOBALS['mysql_5_1_doc_lang'];
365 } elseif (PMA_MYSQL_INT_VERSION
>= 50000) {
367 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
368 $lang = $GLOBALS['mysql_5_0_doc_lang'];
372 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
377 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>';
378 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
379 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>';
381 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
383 } // end of the 'PMA_showMySQLDocu()' function
386 * Displays a hint icon, on mouse over show the hint
388 * @uses $GLOBALS['pmaThemeImage']
389 * @uses PMA_jsFormat()
390 * @param string the error message
394 function PMA_showHint($hint_message)
396 //return '<img class="lightbulb" src="' . $GLOBALS['pmaThemeImage'] . 'b_tipp.png" width="16" height="16" border="0" alt="' . $hint_message . '" title="' . $hint_message . '" align="middle" onclick="alert(\'' . PMA_jsFormat($hint_message, false) . '\');" />';
397 return '<img class="lightbulb" src="' . $GLOBALS['pmaThemeImage']
398 . 'b_tipp.png" width="16" height="16" alt="Tip" title="Tip" onmouseover="pmaTooltip(\''
399 . PMA_jsFormat($hint_message, false) . '\'); return false;" onmouseout="swapTooltip(\'default\'); return false;" />';
403 * Displays a MySQL error message in the right frame.
405 * @uses footer.inc.php
406 * @uses header.inc.php
407 * @uses $GLOBALS['sql_query']
408 * @uses $GLOBALS['strError']
409 * @uses $GLOBALS['strSQLQuery']
410 * @uses $GLOBALS['pmaThemeImage']
411 * @uses $GLOBALS['strEdit']
412 * @uses $GLOBALS['strMySQLSaid']
413 * @uses $cfg['PropertiesIconic']
414 * @uses PMA_backquote()
415 * @uses PMA_DBI_getError()
416 * @uses PMA_formatSql()
417 * @uses PMA_generate_common_hidden_inputs()
418 * @uses PMA_generate_common_url()
419 * @uses PMA_showMySQLDocu()
420 * @uses PMA_sqlAddslashes()
421 * @uses PMA_SQP_isError()
422 * @uses PMA_SQP_parse()
423 * @uses PMA_SQP_getErrorString()
426 * @uses str_replace()
429 * @uses preg_replace()
434 * @uses function_exists()
435 * @uses htmlspecialchars()
438 * @param string the error message
439 * @param string the sql query that failed
440 * @param boolean whether to show a "modify" link or not
441 * @param string the "back" link url (full path is not required)
442 * @param boolean EXIT the page?
444 * @global string the curent table
445 * @global string the current db
449 function PMA_mysqlDie($error_message = '', $the_query = '',
450 $is_modify_link = true, $back_url = '', $exit = true)
455 * start http output, display html headers
457 require_once './libraries/header.inc.php';
459 if (!$error_message) {
460 $error_message = PMA_DBI_getError();
462 if (!$the_query && !empty($GLOBALS['sql_query'])) {
463 $the_query = $GLOBALS['sql_query'];
466 // --- Added to solve bug #641765
467 // Robbat2 - 12 January 2003, 9:46PM
468 // Revised, Robbat2 - 13 January 2003, 2:59PM
469 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
470 $formatted_sql = htmlspecialchars($the_query);
471 } elseif (empty($the_query) ||
trim($the_query) == '') {
474 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
477 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
478 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
479 // if the config password is wrong, or the MySQL server does not
480 // respond, do not show the query that would reveal the
482 if (!empty($the_query) && !strstr($the_query, 'connect')) {
483 // --- Added to solve bug #641765
484 // Robbat2 - 12 January 2003, 9:46PM
485 // Revised, Robbat2 - 13 January 2003, 2:59PM
486 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
487 echo PMA_SQP_getErrorString() . "\n";
488 echo '<br />' . "\n";
491 // modified to show me the help on sql errors (Michael Keck)
492 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
493 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
494 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
496 if ($is_modify_link && strlen($db)) {
497 if (strlen($table)) {
498 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($db, $table) . '&sql_query=' . urlencode($the_query) . '&show_query=1">';
500 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($db) . '&sql_query=' . urlencode($the_query) . '&show_query=1">';
502 if ($GLOBALS['cfg']['PropertiesIconic']) {
504 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
508 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
514 .' ' . $formatted_sql . "\n"
518 $tmp_mysql_error = ''; // for saving the original $error_message
519 if (!empty($error_message)) {
520 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
521 $error_message = htmlspecialchars($error_message);
522 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
524 // modified to show me the help on error-returns (Michael Keck)
525 // (now error-messages-server)
527 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
528 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
532 // The error message will be displayed within a CODE segment.
533 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
535 // Replace all non-single blanks with their HTML-counterpart
536 $error_message = str_replace(' ', ' ', $error_message);
537 // Replace TAB-characters with their HTML-counterpart
538 $error_message = str_replace("\t", ' ', $error_message);
539 // Replace linebreaks
540 $error_message = nl2br($error_message);
543 . $error_message . "\n"
544 . '</code><br />' . "\n";
546 echo '<fieldset class="tblFooters">';
548 if (!empty($back_url) && $exit) {
549 $goto_back_url='<a href="' . (strstr($back_url, '?') ?
$back_url . '&no_history=true' : $back_url . '?no_history=true') . '">';
550 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
552 echo ' </fieldset>' . "\n\n";
555 * display footer and exit
557 require_once './libraries/footer.inc.php';
559 } // end of the 'PMA_mysqlDie()' function
562 * Returns a string formatted with CONVERT ... USING
563 * if MySQL supports it
565 * @uses PMA_MYSQL_INT_VERSION
566 * @uses $GLOBALS['collation_connection']
568 * @param string the string itself
569 * @param string the mode: quoted or unquoted (this one by default)
571 * @return the formatted string
575 function PMA_convert_using($string, $mode='unquoted')
577 if ($mode == 'quoted') {
578 $possible_quote = "'";
580 $possible_quote = "";
583 if (PMA_MYSQL_INT_VERSION
>= 40100) {
584 list($conn_charset) = explode('_', $GLOBALS['collation_connection']);
585 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $conn_charset . ")";
587 $converted_string = $possible_quote . $string . $possible_quote;
589 return $converted_string;
593 * Send HTTP header, taking IIS limits into account (600 seems ok)
596 * @uses PMA_COMING_FROM_COOKIE_LOGIN
597 * @uses PMA_get_arg_separator()
602 * @uses session_write_close()
603 * @uses headers_sent()
604 * @uses function_exists()
605 * @uses debug_print_backtrace()
606 * @uses trigger_error()
608 * @param string $uri the header to send
609 * @return boolean always true
611 function PMA_sendHeaderLocation($uri)
613 if (PMA_IS_IIS
&& strlen($uri) > 600) {
615 echo '<html><head><title>- - -</title>' . "\n";
616 echo '<meta http-equiv="expires" content="0">' . "\n";
617 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
618 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
619 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
620 echo '<script type="text/javascript">' . "\n";
621 echo '//<![CDATA[' . "\n";
622 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
624 echo '</script>' . "\n";
625 echo '</head>' . "\n";
626 echo '<body>' . "\n";
627 echo '<script type="text/javascript">' . "\n";
628 echo '//<![CDATA[' . "\n";
629 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
631 echo '</script></body></html>' . "\n";
635 if (strpos($uri, '?') === false) {
636 header('Location: ' . $uri . '?' . SID
);
638 $separator = PMA_get_arg_separator();
639 header('Location: ' . $uri . $separator . SID
);
642 session_write_close();
643 if (headers_sent()) {
644 if (function_exists('debug_print_backtrace')) {
646 debug_print_backtrace();
649 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
651 // bug #1523784: IE6 does not like 'Refresh: 0', it
652 // results in a blank page
653 // but we need it when coming from the cookie login panel)
654 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
655 header('Refresh: 0; ' . $uri);
657 header('Location: ' . $uri);
664 * returns array with tables of given db with extended information and grouped
666 * @uses $cfg['LeftFrameTableSeparator']
667 * @uses $cfg['LeftFrameTableLevel']
668 * @uses $cfg['ShowTooltipAliasTB']
669 * @uses $cfg['NaturalOrder']
670 * @uses PMA_backquote()
676 * @param string $db name of db
677 * @param string $tables name of tables
678 * return array (recursive) grouped table list
680 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
682 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
684 if (null === $tables) {
685 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
686 if ($GLOBALS['cfg']['NaturalOrder']) {
687 uksort($tables, 'strnatcasecmp');
691 if (count($tables) < 1) {
702 $table_groups = array();
704 foreach ($tables as $table_name => $table) {
706 // check for correct row count
707 if (null === $table['Rows']) {
708 // Do not check exact row count here,
709 // if row count is invalid possibly the table is defect
710 // and this would break left frame;
711 // but we can check row count if this is a view,
712 // since PMA_Table::countRecords() returns a limited row count
715 // set this because PMA_Table::countRecords() can use it
716 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
719 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name'],
724 // in $group we save the reference to the place in $table_groups
725 // where to store the table info
726 if ($GLOBALS['cfg']['LeftFrameDBTree']
727 && $sep && strstr($table_name, $sep))
729 $parts = explode($sep, $table_name);
731 $group =& $table_groups;
733 $group_name_full = '';
734 while ($i < count($parts) - 1
735 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
736 $group_name = $parts[$i] . $sep;
737 $group_name_full .= $group_name;
739 if (!isset($group[$group_name])) {
740 $group[$group_name] = array();
741 $group[$group_name]['is' . $sep . 'group'] = true;
742 $group[$group_name]['tab' . $sep . 'count'] = 1;
743 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
744 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
745 $table = $group[$group_name];
746 $group[$group_name] = array();
747 $group[$group_name][$group_name] = $table;
749 $group[$group_name]['is' . $sep . 'group'] = true;
750 $group[$group_name]['tab' . $sep . 'count'] = 1;
751 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
753 $group[$group_name]['tab' . $sep . 'count']++
;
755 $group =& $group[$group_name];
759 if (!isset($table_groups[$table_name])) {
760 $table_groups[$table_name] = array();
762 $group =& $table_groups;
766 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
767 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
768 // switch tooltip and name
769 $table['Comment'] = $table['Name'];
770 $table['disp_name'] = $table['Comment'];
772 $table['disp_name'] = $table['Name'];
775 $group[$table_name] = array_merge($default, $table);
778 return $table_groups;
781 /* ----------------------- Set of misc functions ----------------------- */
785 * Adds backquotes on both sides of a database, table or field name.
786 * and escapes backquotes inside the name with another backquote
790 * echo PMA_backquote('owner`s db'); // `owner``s db`
794 * @uses PMA_backquote()
797 * @uses str_replace()
798 * @param mixed $a_name the database, table or field name to "backquote"
800 * @param boolean $do_it a flag to bypass this function (used by dump
802 * @return mixed the "backquoted" database, table or field name if the
803 * current MySQL release is >= 3.23.6, the original one
807 function PMA_backquote($a_name, $do_it = true)
813 if (is_array($a_name)) {
815 foreach ($a_name as $key => $val) {
816 $result[$key] = PMA_backquote($val);
821 // '0' is also empty for php :-(
822 if (strlen($a_name) && $a_name !== '*') {
823 return '`' . str_replace('`', '``', $a_name) . '`';
827 } // end of the 'PMA_backquote()' function
831 * Defines the <CR><LF> value depending on the user OS.
834 * @return string the <CR><LF> value to use
838 function PMA_whichCrlf()
842 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
844 if (PMA_USR_OS
== 'Win') {
853 } // end of the 'PMA_whichCrlf()' function
856 * Reloads navigation if needed.
858 * @uses $GLOBALS['reload']
859 * @uses $GLOBALS['db']
860 * @uses PMA_generate_common_url()
861 * @global array configuration
865 function PMA_reloadNavigation()
869 // Reloads the navigation frame via JavaScript if required
870 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
872 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
874 <script type
="text/javascript">
876 if (typeof(window
.parent
) != 'undefined'
877 && typeof(window
.parent
.frame_navigation
) != 'undefined') {
878 window
.parent
.goTo('<?php echo $reload_url; ?>');
883 unset($GLOBALS['reload']);
888 * displays the message and the query
889 * usually the message is the result of the query executed
891 * @param string $message the message to display
892 * @param string $sql_query the query to display
893 * @global array the configuration array
897 function PMA_showMessage($message, $sql_query = null)
900 $query_too_big = false;
902 if (null === $sql_query) {
903 if (! empty($GLOBALS['display_query'])) {
904 $sql_query = $GLOBALS['display_query'];
905 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
906 $sql_query = $GLOBALS['unparsed_sql'];
907 } elseif (! empty($GLOBALS['sql_query'])) {
908 $sql_query = $GLOBALS['sql_query'];
914 // Corrects the tooltip text via JS if required
915 // @todo this is REALLY the wrong place to do this - very unexpected here
916 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
917 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
919 $tbl_status = PMA_DBI_fetch_assoc($result);
920 $tooltip = (empty($tbl_status['Comment']))
922 : $tbl_status['Comment'] . ' ';
923 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
924 PMA_DBI_free_result($result);
925 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
927 echo '<script type="text/javascript">' . "\n";
928 echo '//<![CDATA[' . "\n";
929 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
931 echo '</script>' . "\n";
933 } // end if ... elseif
935 // Checks if the table needs to be repaired after a TRUNCATE query.
936 // @todo what about $GLOBALS['display_query']???
937 // @todo this is REALLY the wrong place to do this - very unexpected here
938 if (strlen($GLOBALS['table'])
939 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
940 if (!isset($tbl_status)) {
941 $result = @PMA_DBI_try_query
('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
943 $tbl_status = PMA_DBI_fetch_assoc($result);
944 PMA_DBI_free_result($result);
947 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
948 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
952 echo '<br />' . "\n";
954 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
955 if (!empty($GLOBALS['show_error_header'])) {
956 echo '<div class="error">' . "\n";
957 echo '<h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
960 echo '<div class="notice">';
961 echo PMA_sanitize($message);
962 if (isset($GLOBALS['special_message'])) {
963 echo PMA_sanitize($GLOBALS['special_message']);
964 unset($GLOBALS['special_message']);
968 if (!empty($GLOBALS['show_error_header'])) {
972 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
973 // Basic url query part
974 $url_qpart = '?' . PMA_generate_common_url($GLOBALS['db'], $GLOBALS['table']);
976 // Html format the query to be displayed
977 // The nl2br function isn't used because its result isn't a valid
978 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
979 // If we want to show some sql code it is easiest to create it here
980 /* SQL-Parser-Analyzer */
982 if (!empty($GLOBALS['show_as_php'])) {
983 $new_line = '\'<br />' . "\n" . ' . \' ';
985 if (isset($new_line)) {
986 /* SQL-Parser-Analyzer */
987 $query_base = PMA_sqlAddslashes(htmlspecialchars($sql_query), false, false, true);
988 /* SQL-Parser-Analyzer */
989 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
991 $query_base = $sql_query;
994 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
995 $query_too_big = true;
996 $query_base = nl2br(htmlspecialchars($sql_query));
997 unset($GLOBALS['parsed_sql']);
1000 // Parse SQL if needed
1001 // (here, use "! empty" because when deleting a bookmark,
1002 // $GLOBALS['parsed_sql'] is set but empty
1003 if (! empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1004 $parsed_sql = $GLOBALS['parsed_sql'];
1006 // when the query is large (for example an INSERT of binary
1007 // data), the parser chokes; so avoid parsing the query
1008 if (! $query_too_big) {
1009 $parsed_sql = PMA_SQP_parse($query_base);
1014 if (isset($parsed_sql)) {
1015 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1018 // Here we append the LIMIT added for navigation, to
1019 // enable its display. Adding it higher in the code
1020 // to $sql_query would create a problem when
1021 // using the Refresh or Edit links.
1023 // Only append it on SELECTs.
1026 * @todo what would be the best to do when someone hits Refresh:
1027 * use the current LIMITs ?
1030 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1031 && isset($GLOBALS['sql_limit_to_append'])) {
1032 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1033 // Need to reparse query
1034 $parsed_sql = PMA_SQP_parse($query_base);
1037 if (!empty($GLOBALS['show_as_php'])) {
1038 $query_base = '$sql = \'' . $query_base;
1039 } elseif (!empty($GLOBALS['validatequery'])) {
1040 $query_base = PMA_validateSQL($query_base);
1042 if (isset($parsed_sql)) {
1043 $query_base = PMA_formatSql($parsed_sql, $query_base);
1047 // Prepares links that may be displayed to edit/explain the query
1048 // (don't go to default pages, we must go to the page
1049 // where the query box is available)
1051 $edit_target = strlen($GLOBALS['db']) ?
(strlen($GLOBALS['table']) ?
'tbl_sql.php' : 'db_sql.php') : 'server_sql.php';
1053 if (isset($cfg['SQLQuery']['Edit'])
1054 && ($cfg['SQLQuery']['Edit'] == true)
1055 && (!empty($edit_target))
1056 && ! $query_too_big) {
1058 if ($cfg['EditInWindow'] == true) {
1059 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1064 $edit_link = $edit_target
1066 . '&sql_query=' . urlencode($sql_query)
1067 . '&show_query=1#querybox';
1068 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1073 // Want to have the query explained (Mike Beck 2002-05-22)
1074 // but only explain a SELECT (that has not been explained)
1075 /* SQL-Parser-Analyzer */
1076 if (isset($cfg['SQLQuery']['Explain'])
1077 && $cfg['SQLQuery']['Explain'] == true
1078 && ! $query_too_big) {
1080 // Detect if we are validating as well
1081 // To preserve the validate uRL data
1082 if (!empty($GLOBALS['validatequery'])) {
1083 $explain_link_validate = '&validatequery=1';
1085 $explain_link_validate = '';
1088 $explain_link = 'import.php'
1090 . $explain_link_validate
1091 . '&sql_query=';
1093 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1094 $explain_link .= urlencode('EXPLAIN ' . $sql_query);
1095 $message = $GLOBALS['strExplain'];
1096 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1097 $explain_link .= urlencode(substr($sql_query, 8));
1098 $message = $GLOBALS['strNoExplain'];
1102 if (!empty($explain_link)) {
1103 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1109 // Also we would like to get the SQL formed in some nice
1110 // php-code (Mike Beck 2002-05-22)
1111 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1112 && $cfg['SQLQuery']['ShowAsPHP'] == true
1113 && ! $query_too_big) {
1114 $php_link = 'import.php'
1116 . '&show_query=1'
1117 . '&sql_query=' . urlencode($sql_query)
1118 . '&show_as_php=';
1120 if (!empty($GLOBALS['show_as_php'])) {
1122 $message = $GLOBALS['strNoPhp'];
1125 $message = $GLOBALS['strPhp'];
1127 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1129 if (isset($GLOBALS['show_as_php'])) {
1133 . '&show_query=1'
1134 . '&sql_query=' . urlencode($sql_query);
1135 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1143 if (isset($cfg['SQLQuery']['Refresh'])
1144 && $cfg['SQLQuery']['Refresh']
1145 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1147 $refresh_link = 'import.php'
1149 . '&show_query=1'
1150 . '&sql_query=' . urlencode($sql_query);
1151 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1156 if (isset($cfg['SQLValidator']['use'])
1157 && $cfg['SQLValidator']['use'] == true
1158 && isset($cfg['SQLQuery']['Validate'])
1159 && $cfg['SQLQuery']['Validate'] == true) {
1160 $validate_link = 'import.php'
1162 . '&show_query=1'
1163 . '&sql_query=' . urlencode($sql_query)
1164 . '&validatequery=';
1165 if (!empty($GLOBALS['validatequery'])) {
1166 $validate_link .= '0';
1167 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1169 $validate_link .= '1';
1170 $validate_message = $GLOBALS['strValidateSQL'] ;
1172 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1174 $validate_link = '';
1178 //unset($sql_query);
1180 // Displays the message
1181 echo '<fieldset class="">' . "\n";
1182 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1184 // when uploading a 700 Kio binary file into a LONGBLOB,
1185 // I get a white page, strlen($query_base) is 2 x 700 Kio
1186 // so put a hard limit here (let's say 1000)
1187 if ($query_too_big) {
1188 echo ' ' . substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1190 echo ' ' . $query_base;
1193 //Clean up the end of the PHP
1194 if (!empty($GLOBALS['show_as_php'])) {
1198 echo '</fieldset>' . "\n";
1200 if (!empty($edit_target)) {
1201 echo '<fieldset class="tblFooters">';
1202 PMA_profilingCheckbox($sql_query);
1203 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1207 echo '</div><br />' . "\n";
1208 } // end of the 'PMA_showMessage()' function
1212 * Displays a form with the Profiling checkbox
1214 * @param string $sql_query
1217 * @author Marc Delisle
1219 function PMA_profilingCheckbox($sql_query) {
1220 // 5.0.37 has profiling but for example, 5.1.20 does not
1221 // (avoid doing a fetch_value for MySQL before 5.0.37)
1222 if (PMA_MYSQL_INT_VERSION
>= 50037 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1223 echo '<form action="sql.php" method="post">' . "\n";
1224 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1225 echo '<input type="hidden" name="sql_query" value="' . $sql_query . '" />' . "\n";
1226 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1227 echo '<input type="checkbox" name="profiling" id="profiling"' . (isset($_SESSION['profiling']) ?
' checked="checked"' : '') . ' onclick="this.form.submit();" /><label for="profiling">' . $GLOBALS['strProfiling'] . '</label>' . "\n";
1228 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1229 echo '</form>' . "\n";
1234 * Displays the results of SHOW PROFILE
1236 * @param array the results
1239 * @author Marc Delisle
1241 function PMA_profilingResults($profiling_results) {
1242 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1243 echo '<table>' . "\n";
1244 echo ' <tr>' . "\n";
1245 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1246 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1247 echo ' </tr>' . "\n";
1249 foreach($profiling_results as $one_result) {
1250 echo ' <tr>' . "\n";
1251 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1252 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1254 echo '</table>' . "\n";
1255 echo '</fieldset>' . "\n";
1259 * Formats $value to byte view
1261 * @param double the value to format
1262 * @param integer the sensitiveness
1263 * @param integer the number of decimals to retain
1265 * @return array the formatted value and its unit
1270 * @version 1.2 - 18 July 2002
1272 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1274 $dh = PMA_pow(10, $comma);
1275 $li = PMA_pow(10, $limes);
1276 $return_value = $value;
1277 $unit = $GLOBALS['byteUnits'][0];
1279 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1280 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1281 // use 1024.0 to avoid integer overflow on 64-bit machines
1282 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1283 $unit = $GLOBALS['byteUnits'][$d];
1288 if ($unit != $GLOBALS['byteUnits'][0]) {
1289 $return_value = PMA_formatNumber($value, 5, $comma);
1291 $return_value = PMA_formatNumber($value, 0);
1294 return array($return_value, $unit);
1295 } // end of the 'PMA_formatByteDown' function
1298 * Formats $value to the given length and appends SI prefixes
1299 * $comma is not substracted from the length
1300 * with a $length of 0 no truncation occurs, number is only formated
1301 * to the current locale
1305 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1306 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1307 * echo PMA_formatNumber(-0.003, 6); // -3 m
1308 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1309 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1310 * echo PMA_formatNumber(0, 6); // 0
1313 * @param double $value the value to format
1314 * @param integer $length the max length
1315 * @param integer $comma the number of decimals to retain
1316 * @param boolean $only_down do not reformat numbers below 1
1318 * @return string the formatted value and its unit
1322 * @author staybyte, sebastian mendel
1323 * @version 1.1.0 - 2005-10-27
1325 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1327 //number_format is not multibyte safe, str_replace is safe
1328 if ($length === 0) {
1329 return str_replace(array(',', '.'),
1330 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1331 number_format($value, $comma));
1334 // this units needs no translation, ISO
1355 // we need at least 3 digits to be displayed
1356 if (3 > $length +
$comma) {
1357 $length = 3 - $comma;
1360 // check for negativ value to retain sign
1363 $value = abs($value);
1368 $dh = PMA_pow(10, $comma);
1369 $li = PMA_pow(10, $length);
1373 for ($d = 8; $d >= 0; $d--) {
1374 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1375 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1380 } elseif (!$only_down && (float) $value !== 0.0) {
1381 for ($d = -8; $d <= 8; $d++
) {
1382 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1383 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1388 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1390 //number_format is not multibyte safe, str_replace is safe
1391 $value = str_replace(array(',', '.'),
1392 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1393 number_format($value, $comma));
1395 return $sign . $value . ' ' . $unit;
1396 } // end of the 'PMA_formatNumber' function
1399 * Extracts ENUM / SET options from a type definition string
1401 * @param string The column type definition
1403 * @return array The options or
1404 * boolean false in case of an error.
1408 function PMA_getEnumSetOptions($type_def)
1410 $open = strpos($type_def, '(');
1411 $close = strrpos($type_def, ')');
1412 if (!$open ||
!$close) {
1415 $options = substr($type_def, $open +
2, $close - $open - 3);
1416 $options = explode('\',\'', $options);
1418 } // end of the 'PMA_getEnumSetOptions' function
1421 * Writes localised date
1423 * @param string the current timestamp
1425 * @return string the formatted date
1429 function PMA_localisedDate($timestamp = -1, $format = '')
1431 global $datefmt, $month, $day_of_week;
1433 if ($format == '') {
1437 if ($timestamp == -1) {
1438 $timestamp = time();
1441 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1442 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1444 return strftime($date, $timestamp);
1445 } // end of the 'PMA_localisedDate()' function
1449 * returns a tab for tabbed navigation.
1450 * If the variables $link and $args ar left empty, an inactive tab is created
1452 * @uses $GLOBALS['PMA_PHP_SELF']
1453 * @uses $GLOBALS['strEmpty']
1454 * @uses $GLOBALS['strDrop']
1455 * @uses $GLOBALS['active_page']
1456 * @uses $GLOBALS['url_query']
1457 * @uses $cfg['MainPageIconic']
1458 * @uses $GLOBALS['pmaThemeImage']
1459 * @uses PMA_generate_common_url()
1460 * @uses E_USER_NOTICE
1461 * @uses htmlentities()
1464 * @uses trigger_error()
1465 * @uses array_merge()
1467 * @param array $tab array with all options
1468 * @return string html code for one tab, a link if valid otherwise a span
1471 function PMA_getTab($tab)
1486 $tab = array_merge($defaults, $tab);
1488 // determine additionnal style-class
1489 if (empty($tab['class'])) {
1490 if ($tab['text'] == $GLOBALS['strEmpty']
1491 ||
$tab['text'] == $GLOBALS['strDrop']) {
1492 $tab['class'] = 'caution';
1493 } elseif (!empty($tab['active'])
1494 ||
(isset($GLOBALS['active_page'])
1495 && $GLOBALS['active_page'] == $tab['link'])
1496 ||
(basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'] && empty($tab['warning'])))
1498 $tab['class'] = 'active';
1502 if (!empty($tab['warning'])) {
1503 $tab['class'] .= ' warning';
1504 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1508 if (!empty($tab['link'])) {
1509 $tab['link'] = htmlentities($tab['link']);
1510 $tab['link'] = $tab['link'] . $tab['sep']
1511 .(empty($GLOBALS['url_query']) ?
1512 PMA_generate_common_url() : $GLOBALS['url_query']);
1513 if (!empty($tab['args'])) {
1514 foreach ($tab['args'] as $param => $value) {
1515 $tab['link'] .= '&' . urlencode($param) . '='
1516 . urlencode($value);
1521 if (! empty($tab['fragment'])) {
1522 $tab['link'] .= $tab['fragment'];
1525 // display icon, even if iconic is disabled but the link-text is missing
1526 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1527 && isset($tab['icon'])) {
1528 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1529 .'%1$s" width="16" height="16" alt="%2$s" />%2$s';
1530 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1532 // check to not display an empty link-text
1533 elseif (empty($tab['text'])) {
1535 trigger_error('empty linktext in function ' . __FUNCTION__
. '()',
1539 $out = '<li' . ($tab['class'] == 'active' ?
' class="active"' : '') . '>';
1541 if (!empty($tab['link'])) {
1542 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1543 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1544 . $tab['text'] . '</a>';
1546 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1547 . $tab['text'] . '</span>';
1552 } // end of the 'PMA_getTab()' function
1555 * returns html-code for a tab navigation
1557 * @uses PMA_getTab()
1558 * @uses htmlentities()
1559 * @param array $tabs one element per tab
1560 * @param string $tag_id id used for the html-tag
1561 * @return string html-code for tab-navigation
1563 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1566 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1567 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1569 foreach ($tabs as $tab) {
1570 $tab_navigation .= PMA_getTab($tab) . "\n";
1575 .'<div class="clearfloat"></div>'
1578 return $tab_navigation;
1583 * Displays a link, or a button if the link's URL is too large, to
1584 * accommodate some browsers' limitations
1586 * @param string the URL
1587 * @param string the link message
1588 * @param mixed $tag_params string: js confirmation
1589 * array: additional tag params (f.e. style="")
1590 * @param boolean $new_form we set this to false when we are already in
1591 * a form, to avoid generating nested forms
1593 * @return string the results to be echoed or saved in an array
1595 function PMA_linkOrButton($url, $message, $tag_params = array(),
1596 $new_form = true, $strip_img = false, $target = '')
1598 if (! is_array($tag_params)) {
1600 $tag_params = array();
1602 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1606 if (! empty($target)) {
1607 $tag_params['target'] = htmlentities($target);
1610 $tag_params_strings = array();
1611 foreach ($tag_params as $par_name => $par_value) {
1612 // htmlspecialchars() only on non javascript
1613 $par_value = substr($par_name, 0, 2) == 'on'
1615 : htmlspecialchars($par_value);
1616 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1619 // previously the limit was set to 2047, it seems 1000 is better
1620 if (strlen($url) <= 1000) {
1621 // no whitespace within an <a> else Safari will make it part of the link
1622 $ret = "\n" . '<a href="' . $url . '" '
1623 . implode(' ', $tag_params_strings) . '>'
1624 . $message . '</a>' . "\n";
1626 // no spaces (linebreaks) at all
1627 // or after the hidden fields
1628 // IE will display them all
1630 // add class=link to submit button
1631 if (empty($tag_params['class'])) {
1632 $tag_params['class'] = 'link';
1635 // decode encoded url separators
1636 $separator = PMA_get_arg_separator();
1637 // on most places separator is still hard coded ...
1638 if ($separator !== '&') {
1639 // ... so always replace & with $separator
1640 $url = str_replace(htmlentities('&'), $separator, $url);
1641 $url = str_replace('&', $separator, $url);
1643 $url = str_replace(htmlentities($separator), $separator, $url);
1646 $url_parts = parse_url($url);
1647 $query_parts = explode($separator, $url_parts['query']);
1649 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1650 . ' method="post"' . $target . ' style="display: inline;">';
1652 $subname_close = '';
1655 $query_parts[] = 'redirect=' . $url_parts['path'];
1656 if (empty($GLOBALS['subform_counter'])) {
1657 $GLOBALS['subform_counter'] = 0;
1659 $GLOBALS['subform_counter']++
;
1661 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1662 $subname_close = ']';
1663 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1665 foreach ($query_parts as $query_pair) {
1666 list($eachvar, $eachval) = explode('=', $query_pair);
1667 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1668 . $subname_close . '" value="'
1669 . htmlspecialchars(urldecode($eachval)) . '" />';
1672 if (stristr($message, '<img')) {
1674 $message = trim(strip_tags($message));
1675 $ret .= '<input type="submit"' . $submit_name . ' '
1676 . implode(' ', $tag_params_strings)
1677 . ' value="' . htmlspecialchars($message) . '" />';
1679 $ret .= '<input type="image"' . $submit_name . ' '
1680 . implode(' ', $tag_params_strings)
1681 . ' src="' . preg_replace(
1682 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1683 . ' value="' . htmlspecialchars(
1684 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1689 $message = trim(strip_tags($message));
1690 $ret .= '<input type="submit"' . $submit_name . ' '
1691 . implode(' ', $tag_params_strings)
1692 . ' value="' . htmlspecialchars($message) . '" />';
1697 } // end if... else...
1700 } // end of the 'PMA_linkOrButton()' function
1704 * Returns a given timespan value in a readable format.
1706 * @uses $GLOBALS['timespanfmt']
1709 * @param int the timespan
1711 * @return string the formatted value
1713 function PMA_timespanFormat($seconds)
1715 $return_string = '';
1716 $days = floor($seconds / 86400);
1718 $seconds -= $days * 86400;
1720 $hours = floor($seconds / 3600);
1721 if ($days > 0 ||
$hours > 0) {
1722 $seconds -= $hours * 3600;
1724 $minutes = floor($seconds / 60);
1725 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1726 $seconds -= $minutes * 60;
1728 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1732 * Takes a string and outputs each character on a line for itself. Used
1733 * mainly for horizontalflipped display mode.
1734 * Takes care of special html-characters.
1735 * Fulfills todo-item
1736 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1738 * @todo add a multibyte safe function PMA_STR_split()
1740 * @param string The string
1741 * @param string The Separator (defaults to "<br />\n")
1744 * @author Garvin Hicking <me@supergarv.de>
1745 * @return string The flipped string
1747 function PMA_flipstring($string, $Separator = "<br />\n")
1749 $format_string = '';
1752 for ($i = 0; $i < strlen($string); $i++
) {
1753 $char = $string{$i};
1757 $format_string .= $charbuff;
1760 } elseif (!empty($charbuff)) {
1762 } elseif ($char == ';' && !empty($charbuff)) {
1763 $format_string .= $charbuff;
1767 $format_string .= $char;
1771 if ($append && ($i != strlen($string))) {
1772 $format_string .= $Separator;
1776 return $format_string;
1781 * Function added to avoid path disclosures.
1782 * Called by each script that needs parameters, it displays
1783 * an error message and, by default, stops the execution.
1785 * Not sure we could use a strMissingParameter message here,
1786 * would have to check if the error message file is always available
1788 * @todo localize error message
1789 * @todo use PMA_fatalError() if $die === true?
1790 * @uses PMA_getenv()
1791 * @uses header_meta_style.inc.php
1792 * @uses $GLOBALS['PMA_PHP_SELF']
1794 * @param array The names of the parameters needed by the calling
1796 * @param boolean Stop the execution?
1797 * (Set this manually to false in the calling script
1798 * until you know all needed parameters to check).
1799 * @param boolean Whether to include this list in checking for special params.
1800 * @global string path to current script
1801 * @global boolean flag whether any special variable was required
1804 * @author Marc Delisle (lem9@users.sourceforge.net)
1806 function PMA_checkParameters($params, $die = true, $request = true)
1808 global $checked_special;
1810 if (!isset($checked_special)) {
1811 $checked_special = false;
1814 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1815 $found_error = false;
1816 $error_message = '';
1818 foreach ($params as $param) {
1819 if ($request && $param != 'db' && $param != 'table') {
1820 $checked_special = true;
1823 if (!isset($GLOBALS[$param])) {
1824 $error_message .= $reported_script_name
1825 . ': Missing parameter: ' . $param
1826 . ' <a href="./Documentation.html#faqmissingparameters"'
1827 . ' target="documentation"> (FAQ 2.8)</a><br />';
1828 $found_error = true;
1833 * display html meta tags
1835 require_once './libraries/header_meta_style.inc.php';
1836 echo '</head><body><p>' . $error_message . '</p></body></html>';
1844 * Function to generate unique condition for specified row.
1846 * @uses PMA_MYSQL_INT_VERSION
1847 * @uses $GLOBALS['analyzed_sql'][0]
1848 * @uses PMA_DBI_field_flags()
1849 * @uses PMA_backquote()
1850 * @uses PMA_sqlAddslashes()
1853 * @uses preg_replace()
1854 * @param resource $handle current query result
1855 * @param integer $fields_cnt number of fields
1856 * @param array $fields_meta meta information about fields
1857 * @param array $row current row
1858 * @param boolean $force_unique generate condition only on pk or unique
1861 * @author Michal Cihar (michal@cihar.com) and others...
1862 * @return string calculated condition
1864 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1868 $nonprimary_condition = '';
1869 $preferred_condition = '';
1871 for ($i = 0; $i < $fields_cnt; ++
$i) {
1873 $field_flags = PMA_DBI_field_flags($handle, $i);
1874 $meta = $fields_meta[$i];
1876 // do not use a column alias in a condition
1877 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
1878 $meta->orgname
= $meta->name
;
1880 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1881 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1882 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1884 // need (string) === (string)
1885 // '' !== 0 but '' == 0
1886 if ((string) $select_expr['alias'] === (string) $meta->name
) {
1887 $meta->orgname
= $select_expr['column'];
1894 // Do not use a table alias in a condition.
1896 // select * from galerie x WHERE
1897 //(select count(*) from galerie y where y.datum=x.datum)>1
1899 // But orgtable is present only with mysqli extension so the
1900 // fix is only for mysqli.
1901 if (isset($meta->orgtable
) && $meta->table
!= $meta->orgtable
) {
1902 $meta->table
= $meta->orgtable
;
1905 // to fix the bug where float fields (primary or not)
1906 // can't be matched because of the imprecision of
1907 // floating comparison, use CONCAT
1908 // (also, the syntax "CONCAT(field) IS NULL"
1909 // that we need on the next "if" will work)
1910 if ($meta->type
== 'real') {
1911 $condition = ' CONCAT(' . PMA_backquote($meta->table
) . '.'
1912 . PMA_backquote($meta->orgname
) . ') ';
1914 // string and blob fields have to be converted using
1915 // the system character set (always utf8) since
1916 // mysql4.1 can use different charset for fields.
1917 if (PMA_MYSQL_INT_VERSION
>= 40100
1918 && ($meta->type
== 'string' ||
$meta->type
== 'blob')) {
1919 $condition = ' CONVERT(' . PMA_backquote($meta->table
) . '.'
1920 . PMA_backquote($meta->orgname
) . ' USING utf8) ';
1922 $condition = ' ' . PMA_backquote($meta->table
) . '.'
1923 . PMA_backquote($meta->orgname
) . ' ';
1925 } // end if... else...
1927 if (!isset($row[$i]) ||
is_null($row[$i])) {
1928 $condition .= 'IS NULL AND';
1930 // timestamp is numeric on some MySQL 4.1
1931 if ($meta->numeric && $meta->type
!= 'timestamp') {
1932 $condition .= '= ' . $row[$i] . ' AND';
1933 } elseif ($meta->type
== 'blob'
1934 // hexify only if this is a true not empty BLOB
1935 && stristr($field_flags, 'BINARY')
1936 && !empty($row[$i])) {
1937 // do not waste memory building a too big condition
1938 if (strlen($row[$i]) < 1000) {
1939 if (PMA_MYSQL_INT_VERSION
< 40002) {
1940 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
1942 // use a CAST if possible, to avoid problems
1943 // if the field contains wildcard characters % or _
1944 $condition .= '= CAST(0x' . bin2hex($row[$i])
1945 . ' AS BINARY) AND';
1948 // this blob won't be part of the final condition
1952 $condition .= '= \''
1953 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
1956 if ($meta->primary_key
> 0) {
1957 $primary_key .= $condition;
1958 } elseif ($meta->unique_key
> 0) {
1959 $unique_key .= $condition;
1961 $nonprimary_condition .= $condition;
1964 // Correction University of Virginia 19991216:
1965 // prefer primary or unique keys for condition,
1966 // but use conjunction of all values if no primary key
1968 $preferred_condition = $primary_key;
1969 } elseif ($unique_key) {
1970 $preferred_condition = $unique_key;
1971 } elseif (! $force_unique) {
1972 $preferred_condition = $nonprimary_condition;
1975 return preg_replace('|\s?AND$|', '', $preferred_condition);
1979 * Generate a button or image tag
1981 * @uses PMA_USR_BROWSER_AGENT
1982 * @uses $GLOBALS['pmaThemeImage']
1983 * @uses $GLOBALS['cfg']['PropertiesIconic']
1984 * @param string name of button element
1985 * @param string class of button element
1986 * @param string name of image element
1987 * @param string text to display
1988 * @param string image to display
1991 * @author Michal Cihar (michal@cihar.com)
1993 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
1996 /* Opera has trouble with <input type="image"> */
1997 /* IE has trouble with <button> */
1998 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
1999 echo '<button class="' . $button_class . '" type="submit"'
2000 .' name="' . $button_name . '" value="' . $text . '"'
2001 .' title="' . $text . '">' . "\n"
2002 .'<img class="icon" src="' . $GLOBALS['pmaThemeImage'] . $image . '"'
2003 .' title="' . $text . '" alt="' . $text . '" width="16"'
2005 .($GLOBALS['cfg']['PropertiesIconic'] === 'both' ?
' ' . $text : '') . "\n"
2006 .'</button>' . "\n";
2008 echo '<input type="image" name="' . $image_name . '" value="'
2009 . $text . '" title="' . $text . '" src="' . $GLOBALS['pmaThemeImage']
2011 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ?
' ' . $text : '') . "\n";
2016 * Generate a pagination selector for browsing resultsets
2018 * @uses $GLOBALS['strPageNumber']
2020 * @param string URL for the JavaScript
2021 * @param string Number of rows in the pagination set
2022 * @param string current page number
2023 * @param string number of total pages
2024 * @param string If the number of pages is lower than this
2025 * variable, no pages will be ommitted in
2027 * @param string How many rows at the beginning should always
2029 * @param string How many rows at the end should always
2031 * @param string Percentage of calculation page offsets to
2032 * hop to a next page
2033 * @param string Near the current page, how many pages should
2034 * be considered "nearby" and displayed as
2036 * @param string The prompt to display (sometimes empty)
2039 * @author Garvin Hicking (pma@supergarv.de)
2041 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2042 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2043 $range = 10, $prompt = '')
2046 . ' <select name="goToPage" onchange="goToUrl(this, \''
2047 . $url . '\');">' . "\n";
2048 if ($nbTotalPage < $showAll) {
2049 $pages = range(1, $nbTotalPage);
2053 // Always show first X pages
2054 for ($i = 1; $i <= $sliceStart; $i++
) {
2058 // Always show last X pages
2059 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2063 // garvin: Based on the number of results we add the specified
2064 // $percent percentate to each page number,
2065 // so that we have a representing page number every now and then to
2066 // immideately jump to specific pages.
2067 // As soon as we get near our currently chosen page ($pageNow -
2068 // $range), every page number will be
2071 $x = $nbTotalPage - $sliceEnd;
2072 $met_boundary = false;
2074 if ($i >= ($pageNow - $range) && $i <= ($pageNow +
$range)) {
2075 // If our pageselector comes near the current page, we use 1
2076 // counter increments
2078 $met_boundary = true;
2080 // We add the percentate increment to our current page to
2081 // hop to the next one in range
2082 $i = $i +
floor($nbTotalPage / $percent);
2084 // Make sure that we do not cross our boundaries.
2085 if ($i > ($pageNow - $range) && !$met_boundary) {
2086 $i = $pageNow - $range;
2090 if ($i > 0 && $i <= $x) {
2095 // Since because of ellipsing of the current page some numbers may be double,
2096 // we unify our array:
2098 $pages = array_unique($pages);
2101 foreach ($pages as $i) {
2102 if ($i == $pageNow) {
2103 $selected = 'selected="selected" style="font-weight: bold"';
2107 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2110 $gotopage .= ' </select>';
2117 * Generate navigation for a list
2119 * @todo use $pos from $_url_params
2120 * @uses $GLOBALS['strPageNumber']
2122 * @param integer number of elements in the list
2123 * @param integer current position in the list
2124 * @param array url parameters
2125 * @param string script name for form target
2126 * @param string target frame
2127 * @param integer maximum number of elements to display from the list
2131 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2133 if ($max_count < $count) {
2134 echo 'frame_navigation' == $frame ?
'<div id="navidbpageselector">' . "\n" : '';
2135 echo $GLOBALS['strPageNumber'];
2136 echo 'frame_navigation' == $frame ?
'<br />' : ' ';
2138 // Move to the beginning or to the previous page
2140 // loic1: patch #474210 from Gosha Sakovich - part 1
2141 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2142 $caption1 = '<<';
2143 $caption2 = ' < ';
2144 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2145 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2147 $caption1 = $GLOBALS['strPos1'] . ' <<';
2148 $caption2 = $GLOBALS['strPrevious'] . ' <';
2151 } // end if... else...
2152 $_url_params['pos'] = 0;
2153 echo '<a' . $title1 . ' href="' . $script
2154 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2155 . $caption1 . '</a>';
2156 $_url_params['pos'] = $pos - $max_count;
2157 echo '<a' . $title2 . ' href="' . $script
2158 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2159 . $caption2 . '</a>';
2162 echo '<form action="./' . $script . '" method="post">' . "\n";
2163 echo PMA_generate_common_hidden_inputs($_url_params);
2164 echo PMA_pageselector(
2165 $script . PMA_generate_common_url($_url_params) . '&',
2167 floor(($pos +
1) / $max_count) +
1,
2168 ceil($count / $max_count));
2171 if ($pos +
$max_count < $count) {
2172 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2173 $caption3 = ' > ';
2174 $caption4 = '>>';
2175 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2176 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2178 $caption3 = '> ' . $GLOBALS['strNext'];
2179 $caption4 = '>> ' . $GLOBALS['strEnd'];
2182 } // end if... else...
2183 $_url_params['pos'] = $pos +
$max_count;
2184 echo '<a' . $title3 . ' href="' . $script
2185 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2186 . $caption3 . '</a>';
2187 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2188 if ($_url_params['pos'] == $count) {
2189 $_url_params['pos'] = $count - $max_count;
2191 echo '<a' . $title4 . ' href="' . $script
2192 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2193 . $caption4 . '</a>';
2196 if ('frame_navigation' == $frame) {
2197 echo '</div>' . "\n";
2203 * replaces %u in given path with current user name
2207 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2210 * @uses $cfg['Server']['user']
2212 * @uses str_replace()
2213 * @param string $dir with wildcard for user
2214 * @return string per user directory
2216 function PMA_userDir($dir)
2218 // add trailing slash
2219 if (substr($dir, -1) != '/') {
2223 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2227 * returns html code for db link to default db page
2229 * @uses $cfg['DefaultTabDatabase']
2230 * @uses $GLOBALS['db']
2231 * @uses $GLOBALS['strJumpToDB']
2232 * @uses PMA_generate_common_url()
2233 * @uses PMA_unescape_mysql_wildcards()
2236 * @uses htmlspecialchars()
2237 * @param string $database
2238 * @return string html link to default db page
2240 function PMA_getDbLink($database = null)
2242 if (!strlen($database)) {
2243 if (!strlen($GLOBALS['db'])) {
2246 $database = $GLOBALS['db'];
2248 $database = PMA_unescape_mysql_wildcards($database);
2251 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2252 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2253 .htmlspecialchars($database) . '</a>';
2257 * Displays a lightbulb hint explaining a known external bug
2258 * that affects a functionality
2260 * @uses PMA_MYSQL_INT_VERSION
2261 * @uses $GLOBALS['strKnownExternalBug']
2262 * @uses PMA_showHint()
2264 * @param string $functionality localized message explaining the func.
2265 * @param string $component 'mysql' (eventually, 'php')
2266 * @param string $minimum_version of this component
2267 * @param string $bugref bug reference for this component
2269 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2271 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION
< $minimum_version) {
2272 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));