ChangeLog for XSS search
[phpmyadmin/crack.git] / libraries / common.lib.php
blob4dcbe8ee3bd650440f148e493e9015c6f0b772b2
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Misc functions used all over the scripts.
6 * @version $Id$
7 */
9 /**
10 * Exponential expression / raise number into power
12 * @uses function_exists()
13 * @uses bcpow()
14 * @uses gmp_pow()
15 * @uses gmp_strval()
16 * @uses pow()
17 * @param number $base
18 * @param number $exp
19 * @param string pow function use, or false for auto-detect
20 * @return mixed string or float
22 function PMA_pow($base, $exp, $use_function = false)
24 static $pow_function = null;
26 if ($exp < 0) {
27 return false;
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')) {
35 // GMP Function
36 $pow_function = 'gmp_pow';
37 } else {
38 // PHP function
39 $pow_function = 'pow';
43 if (! $use_function) {
44 $use_function = $pow_function;
47 switch ($use_function) {
48 case 'bcpow' :
49 //bcscale(10);
50 $pow = bcpow($base, $exp);
51 break;
52 case 'gmp_pow' :
53 $pow = gmp_strval(gmp_pow($base, $exp));
54 break;
55 case 'pow' :
56 $base = (float) $base;
57 $exp = (int) $exp;
58 $pow = pow($base, $exp);
59 break;
60 default:
61 $pow = $use_function($base, $exp);
64 return $pow;
67 /**
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" />';
80 } else {
81 return $alternate;
85 /**
86 * Displays the maximum size for an upload
88 * @uses $GLOBALS['strMaximumSize']
89 * @uses PMA_formatByteDown()
90 * @uses sprintf()
91 * @param integer the size
93 * @return string the message
95 * @access public
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
111 * @access public
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
134 * @access public
136 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
138 if ($is_like) {
139 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
140 } else {
141 $a_string = str_replace('\\', '\\\\', $a_string);
144 if ($crlf) {
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);
150 if ($php_code) {
151 $a_string = str_replace('\'', '\\\'', $a_string);
152 } else {
153 $a_string = str_replace('\'', '\'\'', $a_string);
156 return $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
170 * @access public
172 function PMA_escape_mysql_wildcards($name)
174 $name = str_replace('_', '\\_', $name);
175 $name = str_replace('%', '\\%', $name);
177 return $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
187 * @access public
189 function PMA_unescape_mysql_wildcards($name)
191 $name = str_replace('\\_', '_', $name);
192 $name = str_replace('\\%', '%', $name);
194 return $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()
203 * @uses substr()
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)
210 $quotes = array();
212 if (null === $quote) {
213 $quotes[] = '`';
214 $quotes[] = '"';
215 $quotes[] = "'";
216 } else {
217 $quotes[] = $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;
234 * format sql strings
236 * @todo move into PMA_Sql
237 * @uses PMA_SQP_isError()
238 * @uses PMA_SQP_formatHtml()
239 * @uses PMA_SQP_formatNone()
240 * @uses is_array()
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
248 * @access public
250 * @author Robin Johnson <robbat2@users.sourceforge.net>
252 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
254 global $cfg;
256 // Check that we actually have a valid set of parsed data
257 // well, not quite
258 // first check for the SQL parser having hit an error
259 if (PMA_SQP_isError()) {
260 return $parsed_sql;
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"
268 . '</pre>';
269 return $formatted_sql;
272 $formatted_sql = '';
274 switch ($cfg['SQP']['fmtType']) {
275 case 'none':
276 if ($unparsed_sql != '') {
277 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
278 } else {
279 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
281 break;
282 case 'html':
283 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
284 break;
285 case 'text':
286 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
287 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
288 break;
289 default:
290 break;
291 } // end switch
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
309 * @uses strtolower()
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
317 * @access public
319 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
321 global $cfg;
323 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
324 return '';
327 // Fixup for newly used names:
328 $chapter = str_replace('_', '-', strtolower($chapter));
329 $link = str_replace('_', '-', strtolower($link));
331 switch ($cfg['MySQLManualType']) {
332 case 'chapters':
333 if (empty($chapter)) {
334 $chapter = 'index';
336 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
337 break;
338 case 'big':
339 $url = $cfg['MySQLManualBase'] . '#' . $link;
340 break;
341 case 'searchable':
342 if (empty($link)) {
343 $link = 'index';
345 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
346 break;
347 case 'viewable':
348 default:
349 if (empty($link)) {
350 $link = 'index';
352 $mysql = '5.0';
353 $lang = 'en';
354 if (defined('PMA_MYSQL_INT_VERSION')) {
355 if (PMA_MYSQL_INT_VERSION < 50000) {
356 $mysql = '4.1';
357 if (!empty($GLOBALS['mysql_4_1_doc_lang'])) {
358 $lang = $GLOBALS['mysql_4_1_doc_lang'];
360 } elseif (PMA_MYSQL_INT_VERSION >= 50100) {
361 $mysql = '5.1';
362 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
363 $lang = $GLOBALS['mysql_5_1_doc_lang'];
365 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
366 $mysql = '5.0';
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';
373 break;
376 if ($big_icon) {
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>';
380 } else {
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
392 * @access public
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 $GLOBALS['cfg']['PropertiesIconic']
414 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
415 * @uses PMA_backquote()
416 * @uses PMA_DBI_getError()
417 * @uses PMA_formatSql()
418 * @uses PMA_generate_common_hidden_inputs()
419 * @uses PMA_generate_common_url()
420 * @uses PMA_showMySQLDocu()
421 * @uses PMA_sqlAddslashes()
422 * @uses PMA_SQP_isError()
423 * @uses PMA_SQP_parse()
424 * @uses PMA_SQP_getErrorString()
425 * @uses strtolower()
426 * @uses urlencode()
427 * @uses str_replace()
428 * @uses nl2br()
429 * @uses substr()
430 * @uses preg_replace()
431 * @uses preg_match()
432 * @uses explode()
433 * @uses implode()
434 * @uses is_array()
435 * @uses function_exists()
436 * @uses htmlspecialchars()
437 * @uses trim()
438 * @uses strstr()
439 * @param string the error message
440 * @param string the sql query that failed
441 * @param boolean whether to show a "modify" link or not
442 * @param string the "back" link url (full path is not required)
443 * @param boolean EXIT the page?
445 * @global string the curent table
446 * @global string the current db
448 * @access public
450 function PMA_mysqlDie($error_message = '', $the_query = '',
451 $is_modify_link = true, $back_url = '', $exit = true)
453 global $table, $db;
456 * start http output, display html headers
458 require_once './libraries/header.inc.php';
460 if (!$error_message) {
461 $error_message = PMA_DBI_getError();
463 if (!$the_query && !empty($GLOBALS['sql_query'])) {
464 $the_query = $GLOBALS['sql_query'];
467 // --- Added to solve bug #641765
468 // Robbat2 - 12 January 2003, 9:46PM
469 // Revised, Robbat2 - 13 January 2003, 2:59PM
470 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
471 $formatted_sql = htmlspecialchars($the_query);
472 } elseif (empty($the_query) || trim($the_query) == '') {
473 $formatted_sql = '';
474 } else {
475 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
476 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
477 } else {
478 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
481 // ---
482 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
483 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
484 // if the config password is wrong, or the MySQL server does not
485 // respond, do not show the query that would reveal the
486 // username/password
487 if (!empty($the_query) && !strstr($the_query, 'connect')) {
488 // --- Added to solve bug #641765
489 // Robbat2 - 12 January 2003, 9:46PM
490 // Revised, Robbat2 - 13 January 2003, 2:59PM
491 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
492 echo PMA_SQP_getErrorString() . "\n";
493 echo '<br />' . "\n";
495 // ---
496 // modified to show me the help on sql errors (Michael Keck)
497 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
498 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
499 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
501 if ($is_modify_link && strlen($db)) {
502 if (strlen($table)) {
503 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($db, $table) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
504 } else {
505 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($db) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
507 if ($GLOBALS['cfg']['PropertiesIconic']) {
508 echo $doedit_goto
509 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
510 . '</a>';
511 } else {
512 echo ' ['
513 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
514 . ']' . "\n";
516 } // end if
517 echo ' </p>' . "\n"
518 .' <p>' . "\n"
519 .' ' . $formatted_sql . "\n"
520 .' </p>' . "\n";
521 } // end if
523 $tmp_mysql_error = ''; // for saving the original $error_message
524 if (!empty($error_message)) {
525 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
526 $error_message = htmlspecialchars($error_message);
527 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
529 // modified to show me the help on error-returns (Michael Keck)
530 // (now error-messages-server)
531 echo '<p>' . "\n"
532 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
533 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
534 . "\n"
535 . '</p>' . "\n";
537 // The error message will be displayed within a CODE segment.
538 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
540 // Replace all non-single blanks with their HTML-counterpart
541 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
542 // Replace TAB-characters with their HTML-counterpart
543 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
544 // Replace linebreaks
545 $error_message = nl2br($error_message);
547 echo '<code>' . "\n"
548 . $error_message . "\n"
549 . '</code><br />' . "\n";
550 echo '</div>';
551 echo '<fieldset class="tblFooters">';
553 if (!empty($back_url) && $exit) {
554 $goto_back_url='<a href="' . (strstr($back_url, '?') ? $back_url . '&amp;no_history=true' : $back_url . '?no_history=true') . '">';
555 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
557 echo ' </fieldset>' . "\n\n";
558 if ($exit) {
560 * display footer and exit
562 require_once './libraries/footer.inc.php';
564 } // end of the 'PMA_mysqlDie()' function
567 * Returns a string formatted with CONVERT ... USING
568 * if MySQL supports it
570 * @uses PMA_MYSQL_INT_VERSION
571 * @uses $GLOBALS['collation_connection']
572 * @uses explode()
573 * @param string the string itself
574 * @param string the mode: quoted or unquoted (this one by default)
576 * @return the formatted string
578 * @access private
580 function PMA_convert_using($string, $mode='unquoted', $force_utf8 = false)
582 if ($mode == 'quoted') {
583 $possible_quote = "'";
584 } else {
585 $possible_quote = "";
588 if (PMA_MYSQL_INT_VERSION >= 40100) {
589 if ($force_utf8) {
590 $charset = 'utf8';
591 $collate = ' COLLATE utf8_bin';
592 } else {
593 list($charset) = explode('_', $GLOBALS['collation_connection']);
594 $collate = '';
596 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $charset . ")" . $collate;
597 } else {
598 $converted_string = $possible_quote . $string . $possible_quote;
600 return $converted_string;
601 } // end function
604 * Send HTTP header, taking IIS limits into account (600 seems ok)
606 * @uses PMA_IS_IIS
607 * @uses PMA_COMING_FROM_COOKIE_LOGIN
608 * @uses PMA_get_arg_separator()
609 * @uses SID
610 * @uses strlen()
611 * @uses strpos()
612 * @uses header()
613 * @uses session_write_close()
614 * @uses headers_sent()
615 * @uses function_exists()
616 * @uses debug_print_backtrace()
617 * @uses trigger_error()
618 * @uses defined()
619 * @param string $uri the header to send
620 * @return boolean always true
622 function PMA_sendHeaderLocation($uri)
624 if (PMA_IS_IIS && strlen($uri) > 600) {
625 require_once './libraries/js_escape.lib.php';
627 echo '<html><head><title>- - -</title>' . "\n";
628 echo '<meta http-equiv="expires" content="0">' . "\n";
629 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
630 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
631 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
632 echo '<script type="text/javascript">' . "\n";
633 echo '//<![CDATA[' . "\n";
634 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
635 echo '//]]>' . "\n";
636 echo '</script>' . "\n";
637 echo '</head>' . "\n";
638 echo '<body>' . "\n";
639 echo '<script type="text/javascript">' . "\n";
640 echo '//<![CDATA[' . "\n";
641 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
642 echo '//]]>' . "\n";
643 echo '</script></body></html>' . "\n";
645 } else {
646 if (SID) {
647 if (strpos($uri, '?') === false) {
648 header('Location: ' . $uri . '?' . SID);
649 } else {
650 $separator = PMA_get_arg_separator();
651 header('Location: ' . $uri . $separator . SID);
653 } else {
654 session_write_close();
655 if (headers_sent()) {
656 if (function_exists('debug_print_backtrace')) {
657 echo '<pre>';
658 debug_print_backtrace();
659 echo '</pre>';
661 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
663 // bug #1523784: IE6 does not like 'Refresh: 0', it
664 // results in a blank page
665 // but we need it when coming from the cookie login panel)
666 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
667 header('Refresh: 0; ' . $uri);
668 } else {
669 header('Location: ' . $uri);
676 * returns array with tables of given db with extended information and grouped
678 * @uses $cfg['LeftFrameTableSeparator']
679 * @uses $cfg['LeftFrameTableLevel']
680 * @uses $cfg['ShowTooltipAliasTB']
681 * @uses $cfg['NaturalOrder']
682 * @uses PMA_backquote()
683 * @uses count()
684 * @uses array_merge
685 * @uses uksort()
686 * @uses strstr()
687 * @uses explode()
688 * @param string $db name of db
689 * @param string $tables name of tables
690 * return array (recursive) grouped table list
692 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
694 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
696 if (null === $tables) {
697 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
698 if ($GLOBALS['cfg']['NaturalOrder']) {
699 uksort($tables, 'strnatcasecmp');
703 if (count($tables) < 1) {
704 return $tables;
707 $default = array(
708 'Name' => '',
709 'Rows' => 0,
710 'Comment' => '',
711 'disp_name' => '',
714 $table_groups = array();
716 foreach ($tables as $table_name => $table) {
718 // check for correct row count
719 if (null === $table['Rows']) {
720 // Do not check exact row count here,
721 // if row count is invalid possibly the table is defect
722 // and this would break left frame;
723 // but we can check row count if this is a view,
724 // since PMA_Table::countRecords() returns a limited row count
725 // in this case.
727 // set this because PMA_Table::countRecords() can use it
728 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
730 if ($tbl_is_view) {
731 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
732 $return = true);
736 // in $group we save the reference to the place in $table_groups
737 // where to store the table info
738 if ($GLOBALS['cfg']['LeftFrameDBTree']
739 && $sep && strstr($table_name, $sep))
741 $parts = explode($sep, $table_name);
743 $group =& $table_groups;
744 $i = 0;
745 $group_name_full = '';
746 while ($i < count($parts) - 1
747 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
748 $group_name = $parts[$i] . $sep;
749 $group_name_full .= $group_name;
751 if (!isset($group[$group_name])) {
752 $group[$group_name] = array();
753 $group[$group_name]['is' . $sep . 'group'] = true;
754 $group[$group_name]['tab' . $sep . 'count'] = 1;
755 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
756 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
757 $table = $group[$group_name];
758 $group[$group_name] = array();
759 $group[$group_name][$group_name] = $table;
760 unset($table);
761 $group[$group_name]['is' . $sep . 'group'] = true;
762 $group[$group_name]['tab' . $sep . 'count'] = 1;
763 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
764 } else {
765 $group[$group_name]['tab' . $sep . 'count']++;
767 $group =& $group[$group_name];
768 $i++;
770 } else {
771 if (!isset($table_groups[$table_name])) {
772 $table_groups[$table_name] = array();
774 $group =& $table_groups;
778 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
779 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
780 // switch tooltip and name
781 $table['Comment'] = $table['Name'];
782 $table['disp_name'] = $table['Comment'];
783 } else {
784 $table['disp_name'] = $table['Name'];
787 $group[$table_name] = array_merge($default, $table);
790 return $table_groups;
793 /* ----------------------- Set of misc functions ----------------------- */
797 * Adds backquotes on both sides of a database, table or field name.
798 * and escapes backquotes inside the name with another backquote
800 * example:
801 * <code>
802 * echo PMA_backquote('owner`s db'); // `owner``s db`
804 * </code>
806 * @uses PMA_backquote()
807 * @uses is_array()
808 * @uses strlen()
809 * @uses str_replace()
810 * @param mixed $a_name the database, table or field name to "backquote"
811 * or array of it
812 * @param boolean $do_it a flag to bypass this function (used by dump
813 * functions)
814 * @return mixed the "backquoted" database, table or field name if the
815 * current MySQL release is >= 3.23.6, the original one
816 * else
817 * @access public
819 function PMA_backquote($a_name, $do_it = true)
821 if (! $do_it) {
822 return $a_name;
825 if (is_array($a_name)) {
826 $result = array();
827 foreach ($a_name as $key => $val) {
828 $result[$key] = PMA_backquote($val);
830 return $result;
833 // '0' is also empty for php :-(
834 if (strlen($a_name) && $a_name !== '*') {
835 return '`' . str_replace('`', '``', $a_name) . '`';
836 } else {
837 return $a_name;
839 } // end of the 'PMA_backquote()' function
843 * Defines the <CR><LF> value depending on the user OS.
845 * @uses PMA_USR_OS
846 * @return string the <CR><LF> value to use
848 * @access public
850 function PMA_whichCrlf()
852 $the_crlf = "\n";
854 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
855 // Win case
856 if (PMA_USR_OS == 'Win') {
857 $the_crlf = "\r\n";
859 // Others
860 else {
861 $the_crlf = "\n";
864 return $the_crlf;
865 } // end of the 'PMA_whichCrlf()' function
868 * Reloads navigation if needed.
870 * @uses $GLOBALS['reload']
871 * @uses $GLOBALS['db']
872 * @uses PMA_generate_common_url()
873 * @global array configuration
875 * @access public
877 function PMA_reloadNavigation()
879 global $cfg;
881 // Reloads the navigation frame via JavaScript if required
882 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
883 // one of the reasons for a reload is when a table is dropped
884 // in this case, get rid of the table limit offset, otherwise
885 // we have a problem when dropping a table on the last page
886 // and the offset becomes greater than the total number of tables
887 unset($_SESSION['userconf']['table_limit_offset']);
888 echo "\n";
889 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
891 <script type="text/javascript">
892 //<![CDATA[
893 if (typeof(window.parent) != 'undefined'
894 && typeof(window.parent.frame_navigation) != 'undefined') {
895 window.parent.goTo('<?php echo $reload_url; ?>');
897 //]]>
898 </script>
899 <?php
900 unset($GLOBALS['reload']);
905 * displays the message and the query
906 * usually the message is the result of the query executed
908 * @param string $message the message to display
909 * @param string $sql_query the query to display
910 * @global array the configuration array
911 * @uses $cfg
912 * @access public
914 function PMA_showMessage($message, $sql_query = null)
916 global $cfg;
917 $query_too_big = false;
919 if (null === $sql_query) {
920 if (! empty($GLOBALS['display_query'])) {
921 $sql_query = $GLOBALS['display_query'];
922 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
923 $sql_query = $GLOBALS['unparsed_sql'];
924 } elseif (! empty($GLOBALS['sql_query'])) {
925 $sql_query = $GLOBALS['sql_query'];
926 } else {
927 $sql_query = '';
931 // Corrects the tooltip text via JS if required
932 // @todo this is REALLY the wrong place to do this - very unexpected here
933 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
934 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
935 if ($result) {
936 $tbl_status = PMA_DBI_fetch_assoc($result);
937 $tooltip = (empty($tbl_status['Comment']))
938 ? ''
939 : $tbl_status['Comment'] . ' ';
940 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
941 PMA_DBI_free_result($result);
942 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
943 echo "\n";
944 echo '<script type="text/javascript">' . "\n";
945 echo '//<![CDATA[' . "\n";
946 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
947 echo '//]]>' . "\n";
948 echo '</script>' . "\n";
949 } // end if
950 } // end if ... elseif
952 // Checks if the table needs to be repaired after a TRUNCATE query.
953 // @todo what about $GLOBALS['display_query']???
954 // @todo this is REALLY the wrong place to do this - very unexpected here
955 if (strlen($GLOBALS['table'])
956 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
957 if (!isset($tbl_status)) {
958 $result = @PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
959 if ($result) {
960 $tbl_status = PMA_DBI_fetch_assoc($result);
961 PMA_DBI_free_result($result);
964 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
965 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
968 unset($tbl_status);
969 echo '<br />' . "\n";
971 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
972 if (!empty($GLOBALS['show_error_header'])) {
973 echo '<div class="error">' . "\n";
974 echo '<h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
977 echo '<div class="notice">';
978 echo PMA_sanitize($message);
979 if (isset($GLOBALS['special_message'])) {
980 echo PMA_sanitize($GLOBALS['special_message']);
981 unset($GLOBALS['special_message']);
983 echo '</div>';
985 if (!empty($GLOBALS['show_error_header'])) {
986 echo '</div>';
989 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
990 // Basic url query part
991 $url_qpart = '?' . PMA_generate_common_url($GLOBALS['db'], $GLOBALS['table']);
993 // Html format the query to be displayed
994 // The nl2br function isn't used because its result isn't a valid
995 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
996 // If we want to show some sql code it is easiest to create it here
997 /* SQL-Parser-Analyzer */
999 if (!empty($GLOBALS['show_as_php'])) {
1000 $new_line = '\'<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
1002 if (isset($new_line)) {
1003 /* SQL-Parser-Analyzer */
1004 $query_base = PMA_sqlAddslashes(htmlspecialchars($sql_query), false, false, true);
1005 /* SQL-Parser-Analyzer */
1006 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
1007 } else {
1008 $query_base = $sql_query;
1011 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1012 $query_too_big = true;
1013 $query_base = nl2br(htmlspecialchars($sql_query));
1014 unset($GLOBALS['parsed_sql']);
1017 // Parse SQL if needed
1018 // (here, use "! empty" because when deleting a bookmark,
1019 // $GLOBALS['parsed_sql'] is set but empty
1020 if (! empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1021 $parsed_sql = $GLOBALS['parsed_sql'];
1022 } else {
1023 // when the query is large (for example an INSERT of binary
1024 // data), the parser chokes; so avoid parsing the query
1025 if (! $query_too_big) {
1026 $parsed_sql = PMA_SQP_parse($query_base);
1030 // Analyze it
1031 if (isset($parsed_sql)) {
1032 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1035 // Here we append the LIMIT added for navigation, to
1036 // enable its display. Adding it higher in the code
1037 // to $sql_query would create a problem when
1038 // using the Refresh or Edit links.
1040 // Only append it on SELECTs.
1043 * @todo what would be the best to do when someone hits Refresh:
1044 * use the current LIMITs ?
1047 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1048 && isset($GLOBALS['sql_limit_to_append'])) {
1049 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1050 // Need to reparse query
1051 $parsed_sql = PMA_SQP_parse($query_base);
1054 if (!empty($GLOBALS['show_as_php'])) {
1055 $query_base = '$sql = \'' . $query_base;
1056 } elseif (!empty($GLOBALS['validatequery'])) {
1057 $query_base = PMA_validateSQL($query_base);
1058 } else {
1059 if (isset($parsed_sql)) {
1060 $query_base = PMA_formatSql($parsed_sql, $query_base);
1064 // Prepares links that may be displayed to edit/explain the query
1065 // (don't go to default pages, we must go to the page
1066 // where the query box is available)
1068 $edit_target = strlen($GLOBALS['db']) ? (strlen($GLOBALS['table']) ? 'tbl_sql.php' : 'db_sql.php') : 'server_sql.php';
1070 if (isset($cfg['SQLQuery']['Edit'])
1071 && ($cfg['SQLQuery']['Edit'] == true)
1072 && (!empty($edit_target))
1073 && ! $query_too_big) {
1075 if ($cfg['EditInWindow'] == true) {
1076 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1077 } else {
1078 $onclick = '';
1081 $edit_link = $edit_target
1082 . $url_qpart
1083 . '&amp;sql_query=' . urlencode($sql_query)
1084 . '&amp;show_query=1#querybox';
1085 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1086 } else {
1087 $edit_link = '';
1090 // Want to have the query explained (Mike Beck 2002-05-22)
1091 // but only explain a SELECT (that has not been explained)
1092 /* SQL-Parser-Analyzer */
1093 if (isset($cfg['SQLQuery']['Explain'])
1094 && $cfg['SQLQuery']['Explain'] == true
1095 && ! $query_too_big) {
1097 // Detect if we are validating as well
1098 // To preserve the validate uRL data
1099 if (!empty($GLOBALS['validatequery'])) {
1100 $explain_link_validate = '&amp;validatequery=1';
1101 } else {
1102 $explain_link_validate = '';
1105 $explain_link = 'import.php'
1106 . $url_qpart
1107 . $explain_link_validate
1108 . '&amp;sql_query=';
1110 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1111 $explain_link .= urlencode('EXPLAIN ' . $sql_query);
1112 $message = $GLOBALS['strExplain'];
1113 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1114 $explain_link .= urlencode(substr($sql_query, 8));
1115 $message = $GLOBALS['strNoExplain'];
1116 } else {
1117 $explain_link = '';
1119 if (!empty($explain_link)) {
1120 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1122 } else {
1123 $explain_link = '';
1124 } //show explain
1126 // Also we would like to get the SQL formed in some nice
1127 // php-code (Mike Beck 2002-05-22)
1128 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1129 && $cfg['SQLQuery']['ShowAsPHP'] == true
1130 && ! $query_too_big) {
1131 $php_link = 'import.php'
1132 . $url_qpart
1133 . '&amp;show_query=1'
1134 . '&amp;sql_query=' . urlencode($sql_query)
1135 . '&amp;show_as_php=';
1137 if (!empty($GLOBALS['show_as_php'])) {
1138 $php_link .= '0';
1139 $message = $GLOBALS['strNoPhp'];
1140 } else {
1141 $php_link .= '1';
1142 $message = $GLOBALS['strPhp'];
1144 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1146 if (isset($GLOBALS['show_as_php'])) {
1147 $runquery_link
1148 = 'import.php'
1149 . $url_qpart
1150 . '&amp;show_query=1'
1151 . '&amp;sql_query=' . urlencode($sql_query);
1152 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1155 } else {
1156 $php_link = '';
1157 } //show as php
1159 // Refresh query
1160 if (isset($cfg['SQLQuery']['Refresh'])
1161 && $cfg['SQLQuery']['Refresh']
1162 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1164 $refresh_link = 'import.php'
1165 . $url_qpart
1166 . '&amp;show_query=1'
1167 . '&amp;sql_query=' . urlencode($sql_query);
1168 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1169 } else {
1170 $refresh_link = '';
1171 } //show as php
1173 if (isset($cfg['SQLValidator']['use'])
1174 && $cfg['SQLValidator']['use'] == true
1175 && isset($cfg['SQLQuery']['Validate'])
1176 && $cfg['SQLQuery']['Validate'] == true) {
1177 $validate_link = 'import.php'
1178 . $url_qpart
1179 . '&amp;show_query=1'
1180 . '&amp;sql_query=' . urlencode($sql_query)
1181 . '&amp;validatequery=';
1182 if (!empty($GLOBALS['validatequery'])) {
1183 $validate_link .= '0';
1184 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1185 } else {
1186 $validate_link .= '1';
1187 $validate_message = $GLOBALS['strValidateSQL'] ;
1189 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1190 } else {
1191 $validate_link = '';
1192 } //validator
1194 // why this?
1195 //unset($sql_query);
1197 // Displays the message
1198 echo '<fieldset class="">' . "\n";
1199 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1200 echo ' <div>';
1201 // when uploading a 700 Kio binary file into a LONGBLOB,
1202 // I get a white page, strlen($query_base) is 2 x 700 Kio
1203 // so put a hard limit here (let's say 1000)
1204 if ($query_too_big) {
1205 echo ' ' . substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1206 } else {
1207 echo ' ' . $query_base;
1210 //Clean up the end of the PHP
1211 if (!empty($GLOBALS['show_as_php'])) {
1212 echo '\';';
1214 echo ' </div>';
1215 echo '</fieldset>' . "\n";
1217 if (!empty($edit_target)) {
1218 echo '<fieldset class="tblFooters">';
1219 // avoid displaying a Profiling checkbox that could
1220 // be checked, which would reexecute an INSERT, for example
1221 if (! empty($refresh_link)) {
1222 PMA_profilingCheckbox($sql_query);
1224 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1225 echo '</fieldset>';
1228 echo '</div><br />' . "\n";
1229 } // end of the 'PMA_showMessage()' function
1233 * Verifies if current MySQL server supports profiling
1235 * @access public
1236 * @return boolean whether profiling is supported
1238 * @author Marc Delisle
1240 function PMA_profilingSupported() {
1241 // 5.0.37 has profiling but for example, 5.1.20 does not
1242 // (avoid a trip to the server for MySQL before 5.0.37)
1243 // and do not set a constant as we might be switching servers
1244 if (defined('PMA_MYSQL_INT_VERSION') && PMA_MYSQL_INT_VERSION >= 50037 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1245 return true;
1246 } else {
1247 return false;
1252 * Displays a form with the Profiling checkbox
1254 * @param string $sql_query
1255 * @access public
1257 * @author Marc Delisle
1259 function PMA_profilingCheckbox($sql_query) {
1260 if (PMA_profilingSupported()) {
1261 echo '<form action="sql.php" method="post">' . "\n";
1262 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1263 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1264 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1265 echo '<input type="checkbox" name="profiling" id="profiling"' . (isset($_SESSION['profiling']) ? ' checked="checked"' : '') . ' onclick="this.form.submit();" /><label for="profiling">' . $GLOBALS['strProfiling'] . '</label>' . "\n";
1266 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1267 echo '</form>' . "\n";
1272 * Displays the results of SHOW PROFILE
1274 * @param array the results
1275 * @access public
1277 * @author Marc Delisle
1279 function PMA_profilingResults($profiling_results) {
1280 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1281 echo '<table>' . "\n";
1282 echo ' <tr>' . "\n";
1283 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1284 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1285 echo ' </tr>' . "\n";
1287 foreach($profiling_results as $one_result) {
1288 echo ' <tr>' . "\n";
1289 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1290 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1292 echo '</table>' . "\n";
1293 echo '</fieldset>' . "\n";
1297 * Formats $value to byte view
1299 * @param double the value to format
1300 * @param integer the sensitiveness
1301 * @param integer the number of decimals to retain
1303 * @return array the formatted value and its unit
1305 * @access public
1307 * @author staybyte
1308 * @version 1.2 - 18 July 2002
1310 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1312 $dh = PMA_pow(10, $comma);
1313 $li = PMA_pow(10, $limes);
1314 $return_value = $value;
1315 $unit = $GLOBALS['byteUnits'][0];
1317 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1318 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1319 // use 1024.0 to avoid integer overflow on 64-bit machines
1320 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1321 $unit = $GLOBALS['byteUnits'][$d];
1322 break 1;
1323 } // end if
1324 } // end for
1326 if ($unit != $GLOBALS['byteUnits'][0]) {
1327 // if the unit is not bytes (as represented in current language)
1328 // reformat with max length of 5
1329 // 4th parameter=true means do not reformat if value < 1
1330 $return_value = PMA_formatNumber($value, 5, $comma, true);
1331 } else {
1332 // do not reformat, just handle the locale
1333 $return_value = PMA_formatNumber($value, 0);
1336 return array($return_value, $unit);
1337 } // end of the 'PMA_formatByteDown' function
1340 * Formats $value to the given length and appends SI prefixes
1341 * $comma is not substracted from the length
1342 * with a $length of 0 no truncation occurs, number is only formated
1343 * to the current locale
1345 * examples:
1346 * <code>
1347 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1348 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1349 * echo PMA_formatNumber(-0.003, 6); // -3 m
1350 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1351 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1352 * echo PMA_formatNumber(0, 6); // 0
1354 * </code>
1355 * @param double $value the value to format
1356 * @param integer $length the max length
1357 * @param integer $comma the number of decimals to retain
1358 * @param boolean $only_down do not reformat numbers below 1
1360 * @return string the formatted value and its unit
1362 * @access public
1364 * @author staybyte, sebastian mendel
1365 * @version 1.1.0 - 2005-10-27
1367 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1369 //number_format is not multibyte safe, str_replace is safe
1370 if ($length === 0) {
1371 return str_replace(array(',', '.'),
1372 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1373 number_format($value, $comma));
1376 // this units needs no translation, ISO
1377 $units = array(
1378 -8 => 'y',
1379 -7 => 'z',
1380 -6 => 'a',
1381 -5 => 'f',
1382 -4 => 'p',
1383 -3 => 'n',
1384 -2 => '&micro;',
1385 -1 => 'm',
1386 0 => ' ',
1387 1 => 'k',
1388 2 => 'M',
1389 3 => 'G',
1390 4 => 'T',
1391 5 => 'P',
1392 6 => 'E',
1393 7 => 'Z',
1394 8 => 'Y'
1397 // we need at least 3 digits to be displayed
1398 if (3 > $length + $comma) {
1399 $length = 3 - $comma;
1402 // check for negative value to retain sign
1403 if ($value < 0) {
1404 $sign = '-';
1405 $value = abs($value);
1406 } else {
1407 $sign = '';
1410 $dh = PMA_pow(10, $comma);
1411 $li = PMA_pow(10, $length);
1412 $unit = $units[0];
1414 if ($value >= 1) {
1415 for ($d = 8; $d >= 0; $d--) {
1416 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1417 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1418 $unit = $units[$d];
1419 break 1;
1420 } // end if
1421 } // end for
1422 } elseif (!$only_down && (float) $value !== 0.0) {
1423 for ($d = -8; $d <= 8; $d++) {
1424 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1425 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1426 $unit = $units[$d];
1427 break 1;
1428 } // end if
1429 } // end for
1430 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1432 //number_format is not multibyte safe, str_replace is safe
1433 $value = str_replace(array(',', '.'),
1434 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1435 number_format($value, $comma));
1437 return $sign . $value . ' ' . $unit;
1438 } // end of the 'PMA_formatNumber' function
1441 * Extracts ENUM / SET options from a type definition string
1443 * @param string The column type definition
1445 * @return array The options or
1446 * boolean false in case of an error.
1448 * @author rabus
1450 function PMA_getEnumSetOptions($type_def)
1452 $open = strpos($type_def, '(');
1453 $close = strrpos($type_def, ')');
1454 if (!$open || !$close) {
1455 return false;
1457 $options = substr($type_def, $open + 2, $close - $open - 3);
1458 $options = explode('\',\'', $options);
1459 return $options;
1460 } // end of the 'PMA_getEnumSetOptions' function
1463 * Writes localised date
1465 * @param string the current timestamp
1467 * @return string the formatted date
1469 * @access public
1471 function PMA_localisedDate($timestamp = -1, $format = '')
1473 global $datefmt, $month, $day_of_week;
1475 if ($format == '') {
1476 $format = $datefmt;
1479 if ($timestamp == -1) {
1480 $timestamp = time();
1483 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1484 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1486 return strftime($date, $timestamp);
1487 } // end of the 'PMA_localisedDate()' function
1491 * returns a tab for tabbed navigation.
1492 * If the variables $link and $args ar left empty, an inactive tab is created
1494 * @uses $GLOBALS['PMA_PHP_SELF']
1495 * @uses $GLOBALS['strEmpty']
1496 * @uses $GLOBALS['strDrop']
1497 * @uses $GLOBALS['active_page']
1498 * @uses $GLOBALS['url_query']
1499 * @uses $cfg['MainPageIconic']
1500 * @uses $GLOBALS['pmaThemeImage']
1501 * @uses PMA_generate_common_url()
1502 * @uses E_USER_NOTICE
1503 * @uses htmlentities()
1504 * @uses urlencode()
1505 * @uses sprintf()
1506 * @uses trigger_error()
1507 * @uses array_merge()
1508 * @uses basename()
1509 * @param array $tab array with all options
1510 * @return string html code for one tab, a link if valid otherwise a span
1511 * @access public
1513 function PMA_getTab($tab)
1515 // default values
1516 $defaults = array(
1517 'text' => '',
1518 'class' => '',
1519 'active' => false,
1520 'link' => '',
1521 'sep' => '?',
1522 'attr' => '',
1523 'args' => '',
1524 'warning' => '',
1525 'fragment' => '',
1528 $tab = array_merge($defaults, $tab);
1530 // determine additionnal style-class
1531 if (empty($tab['class'])) {
1532 if ($tab['text'] == $GLOBALS['strEmpty']
1533 || $tab['text'] == $GLOBALS['strDrop']) {
1534 $tab['class'] = 'caution';
1535 } elseif (!empty($tab['active'])
1536 || (isset($GLOBALS['active_page'])
1537 && $GLOBALS['active_page'] == $tab['link'])
1538 || (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'] && empty($tab['warning'])))
1540 $tab['class'] = 'active';
1544 if (!empty($tab['warning'])) {
1545 $tab['class'] .= ' warning';
1546 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1549 // build the link
1550 if (!empty($tab['link'])) {
1551 $tab['link'] = htmlentities($tab['link']);
1552 $tab['link'] = $tab['link'] . $tab['sep']
1553 .(empty($GLOBALS['url_query']) ?
1554 PMA_generate_common_url() : $GLOBALS['url_query']);
1555 if (!empty($tab['args'])) {
1556 foreach ($tab['args'] as $param => $value) {
1557 $tab['link'] .= '&amp;' . urlencode($param) . '='
1558 . urlencode($value);
1563 if (! empty($tab['fragment'])) {
1564 $tab['link'] .= $tab['fragment'];
1567 // display icon, even if iconic is disabled but the link-text is missing
1568 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1569 && isset($tab['icon'])) {
1570 // avoid generating an alt tag, because it only illustrates
1571 // the text that follows and if browser does not display
1572 // images, the text is duplicated
1573 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1574 .'%1$s" width="16" height="16" alt="" />%2$s';
1575 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1577 // check to not display an empty link-text
1578 elseif (empty($tab['text'])) {
1579 $tab['text'] = '?';
1580 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1581 E_USER_NOTICE);
1584 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1586 if (!empty($tab['link'])) {
1587 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1588 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1589 . $tab['text'] . '</a>';
1590 } else {
1591 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1592 . $tab['text'] . '</span>';
1595 $out .= '</li>';
1596 return $out;
1597 } // end of the 'PMA_getTab()' function
1600 * returns html-code for a tab navigation
1602 * @uses PMA_getTab()
1603 * @uses htmlentities()
1604 * @param array $tabs one element per tab
1605 * @param string $tag_id id used for the html-tag
1606 * @return string html-code for tab-navigation
1608 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1610 $tab_navigation =
1611 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1612 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1614 foreach ($tabs as $tab) {
1615 $tab_navigation .= PMA_getTab($tab) . "\n";
1618 $tab_navigation .=
1619 '</ul>' . "\n"
1620 .'<div class="clearfloat"></div>'
1621 .'</div>' . "\n";
1623 return $tab_navigation;
1628 * Displays a link, or a button if the link's URL is too large, to
1629 * accommodate some browsers' limitations
1631 * @param string the URL
1632 * @param string the link message
1633 * @param mixed $tag_params string: js confirmation
1634 * array: additional tag params (f.e. style="")
1635 * @param boolean $new_form we set this to false when we are already in
1636 * a form, to avoid generating nested forms
1638 * @return string the results to be echoed or saved in an array
1640 function PMA_linkOrButton($url, $message, $tag_params = array(),
1641 $new_form = true, $strip_img = false, $target = '')
1643 if (! is_array($tag_params)) {
1644 $tmp = $tag_params;
1645 $tag_params = array();
1646 if (!empty($tmp)) {
1647 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1649 unset($tmp);
1651 if (! empty($target)) {
1652 $tag_params['target'] = htmlentities($target);
1655 $tag_params_strings = array();
1656 foreach ($tag_params as $par_name => $par_value) {
1657 // htmlspecialchars() only on non javascript
1658 $par_value = substr($par_name, 0, 2) == 'on'
1659 ? $par_value
1660 : htmlspecialchars($par_value);
1661 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1664 // previously the limit was set to 2047, it seems 1000 is better
1665 if (strlen($url) <= 1000) {
1666 // no whitespace within an <a> else Safari will make it part of the link
1667 $ret = "\n" . '<a href="' . $url . '" '
1668 . implode(' ', $tag_params_strings) . '>'
1669 . $message . '</a>' . "\n";
1670 } else {
1671 // no spaces (linebreaks) at all
1672 // or after the hidden fields
1673 // IE will display them all
1675 // add class=link to submit button
1676 if (empty($tag_params['class'])) {
1677 $tag_params['class'] = 'link';
1680 // decode encoded url separators
1681 $separator = PMA_get_arg_separator();
1682 // on most places separator is still hard coded ...
1683 if ($separator !== '&') {
1684 // ... so always replace & with $separator
1685 $url = str_replace(htmlentities('&'), $separator, $url);
1686 $url = str_replace('&', $separator, $url);
1688 $url = str_replace(htmlentities($separator), $separator, $url);
1689 // end decode
1691 $url_parts = parse_url($url);
1692 $query_parts = explode($separator, $url_parts['query']);
1693 if ($new_form) {
1694 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1695 . ' method="post"' . $target . ' style="display: inline;">';
1696 $subname_open = '';
1697 $subname_close = '';
1698 $submit_name = '';
1699 } else {
1700 $query_parts[] = 'redirect=' . $url_parts['path'];
1701 if (empty($GLOBALS['subform_counter'])) {
1702 $GLOBALS['subform_counter'] = 0;
1704 $GLOBALS['subform_counter']++;
1705 $ret = '';
1706 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1707 $subname_close = ']';
1708 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1710 foreach ($query_parts as $query_pair) {
1711 list($eachvar, $eachval) = explode('=', $query_pair);
1712 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1713 . $subname_close . '" value="'
1714 . htmlspecialchars(urldecode($eachval)) . '" />';
1715 } // end while
1717 if (stristr($message, '<img')) {
1718 if ($strip_img) {
1719 $message = trim(strip_tags($message));
1720 $ret .= '<input type="submit"' . $submit_name . ' '
1721 . implode(' ', $tag_params_strings)
1722 . ' value="' . htmlspecialchars($message) . '" />';
1723 } else {
1724 $ret .= '<input type="image"' . $submit_name . ' '
1725 . implode(' ', $tag_params_strings)
1726 . ' src="' . preg_replace(
1727 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1728 . ' value="' . htmlspecialchars(
1729 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1730 $message))
1731 . '" />';
1733 } else {
1734 $message = trim(strip_tags($message));
1735 $ret .= '<input type="submit"' . $submit_name . ' '
1736 . implode(' ', $tag_params_strings)
1737 . ' value="' . htmlspecialchars($message) . '" />';
1739 if ($new_form) {
1740 $ret .= '</form>';
1742 } // end if... else...
1744 return $ret;
1745 } // end of the 'PMA_linkOrButton()' function
1749 * Returns a given timespan value in a readable format.
1751 * @uses $GLOBALS['timespanfmt']
1752 * @uses sprintf()
1753 * @uses floor()
1754 * @param int the timespan
1756 * @return string the formatted value
1758 function PMA_timespanFormat($seconds)
1760 $return_string = '';
1761 $days = floor($seconds / 86400);
1762 if ($days > 0) {
1763 $seconds -= $days * 86400;
1765 $hours = floor($seconds / 3600);
1766 if ($days > 0 || $hours > 0) {
1767 $seconds -= $hours * 3600;
1769 $minutes = floor($seconds / 60);
1770 if ($days > 0 || $hours > 0 || $minutes > 0) {
1771 $seconds -= $minutes * 60;
1773 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1777 * Takes a string and outputs each character on a line for itself. Used
1778 * mainly for horizontalflipped display mode.
1779 * Takes care of special html-characters.
1780 * Fulfills todo-item
1781 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1783 * @todo add a multibyte safe function PMA_STR_split()
1784 * @uses strlen
1785 * @param string The string
1786 * @param string The Separator (defaults to "<br />\n")
1788 * @access public
1789 * @author Garvin Hicking <me@supergarv.de>
1790 * @return string The flipped string
1792 function PMA_flipstring($string, $Separator = "<br />\n")
1794 $format_string = '';
1795 $charbuff = false;
1797 for ($i = 0; $i < strlen($string); $i++) {
1798 $char = $string{$i};
1799 $append = false;
1801 if ($char == '&') {
1802 $format_string .= $charbuff;
1803 $charbuff = $char;
1804 $append = true;
1805 } elseif (!empty($charbuff)) {
1806 $charbuff .= $char;
1807 } elseif ($char == ';' && !empty($charbuff)) {
1808 $format_string .= $charbuff;
1809 $charbuff = false;
1810 $append = true;
1811 } else {
1812 $format_string .= $char;
1813 $append = true;
1816 if ($append && ($i != strlen($string))) {
1817 $format_string .= $Separator;
1821 return $format_string;
1826 * Function added to avoid path disclosures.
1827 * Called by each script that needs parameters, it displays
1828 * an error message and, by default, stops the execution.
1830 * Not sure we could use a strMissingParameter message here,
1831 * would have to check if the error message file is always available
1833 * @todo localize error message
1834 * @todo use PMA_fatalError() if $die === true?
1835 * @uses PMA_getenv()
1836 * @uses header_meta_style.inc.php
1837 * @uses $GLOBALS['PMA_PHP_SELF']
1838 * basename
1839 * @param array The names of the parameters needed by the calling
1840 * script.
1841 * @param boolean Stop the execution?
1842 * (Set this manually to false in the calling script
1843 * until you know all needed parameters to check).
1844 * @param boolean Whether to include this list in checking for special params.
1845 * @global string path to current script
1846 * @global boolean flag whether any special variable was required
1848 * @access public
1849 * @author Marc Delisle (lem9@users.sourceforge.net)
1851 function PMA_checkParameters($params, $die = true, $request = true)
1853 global $checked_special;
1855 if (!isset($checked_special)) {
1856 $checked_special = false;
1859 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1860 $found_error = false;
1861 $error_message = '';
1863 foreach ($params as $param) {
1864 if ($request && $param != 'db' && $param != 'table') {
1865 $checked_special = true;
1868 if (!isset($GLOBALS[$param])) {
1869 $error_message .= $reported_script_name
1870 . ': Missing parameter: ' . $param
1871 . ' <a href="./Documentation.html#faqmissingparameters"'
1872 . ' target="documentation"> (FAQ 2.8)</a><br />';
1873 $found_error = true;
1876 if ($found_error) {
1878 * display html meta tags
1880 require_once './libraries/header_meta_style.inc.php';
1881 echo '</head><body><p>' . $error_message . '</p></body></html>';
1882 if ($die) {
1883 exit();
1886 } // end function
1889 * Function to generate unique condition for specified row.
1891 * @uses PMA_MYSQL_INT_VERSION
1892 * @uses $GLOBALS['analyzed_sql'][0]
1893 * @uses PMA_DBI_field_flags()
1894 * @uses PMA_backquote()
1895 * @uses PMA_sqlAddslashes()
1896 * @uses stristr()
1897 * @uses bin2hex()
1898 * @uses preg_replace()
1899 * @param resource $handle current query result
1900 * @param integer $fields_cnt number of fields
1901 * @param array $fields_meta meta information about fields
1902 * @param array $row current row
1903 * @param boolean $force_unique generate condition only on pk or unique
1905 * @access public
1906 * @author Michal Cihar (michal@cihar.com) and others...
1907 * @return string calculated condition
1909 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1911 $primary_key = '';
1912 $unique_key = '';
1913 $nonprimary_condition = '';
1914 $preferred_condition = '';
1916 for ($i = 0; $i < $fields_cnt; ++$i) {
1917 $condition = '';
1918 $field_flags = PMA_DBI_field_flags($handle, $i);
1919 $meta = $fields_meta[$i];
1921 // do not use a column alias in a condition
1922 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1923 $meta->orgname = $meta->name;
1925 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1926 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1927 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1928 as $select_expr) {
1929 // need (string) === (string)
1930 // '' !== 0 but '' == 0
1931 if ((string) $select_expr['alias'] === (string) $meta->name) {
1932 $meta->orgname = $select_expr['column'];
1933 break;
1934 } // end if
1935 } // end foreach
1939 // Do not use a table alias in a condition.
1940 // Test case is:
1941 // select * from galerie x WHERE
1942 //(select count(*) from galerie y where y.datum=x.datum)>1
1944 // But orgtable is present only with mysqli extension so the
1945 // fix is only for mysqli.
1946 if (isset($meta->orgtable) && $meta->table != $meta->orgtable) {
1947 $meta->table = $meta->orgtable;
1950 // to fix the bug where float fields (primary or not)
1951 // can't be matched because of the imprecision of
1952 // floating comparison, use CONCAT
1953 // (also, the syntax "CONCAT(field) IS NULL"
1954 // that we need on the next "if" will work)
1955 if ($meta->type == 'real') {
1956 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1957 . PMA_backquote($meta->orgname) . ') ';
1958 } else {
1959 // string and blob fields have to be converted using
1960 // the system character set (always utf8) since
1961 // mysql4.1 can use different charset for fields.
1962 if (PMA_MYSQL_INT_VERSION >= 40100
1963 && ($meta->type == 'string' || $meta->type == 'blob')) {
1964 $condition = ' CONVERT(' . PMA_backquote($meta->table) . '.'
1965 . PMA_backquote($meta->orgname) . ' USING utf8) ';
1966 } else {
1967 $condition = ' ' . PMA_backquote($meta->table) . '.'
1968 . PMA_backquote($meta->orgname) . ' ';
1970 } // end if... else...
1972 if (!isset($row[$i]) || is_null($row[$i])) {
1973 $condition .= 'IS NULL AND';
1974 } else {
1975 // timestamp is numeric on some MySQL 4.1
1976 if ($meta->numeric && $meta->type != 'timestamp') {
1977 $condition .= '= ' . $row[$i] . ' AND';
1978 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1979 // hexify only if this is a true not empty BLOB or a BINARY
1980 && stristr($field_flags, 'BINARY')
1981 && !empty($row[$i])) {
1982 // do not waste memory building a too big condition
1983 if (strlen($row[$i]) < 1000) {
1984 if (PMA_MYSQL_INT_VERSION < 40002) {
1985 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
1986 } else {
1987 // use a CAST if possible, to avoid problems
1988 // if the field contains wildcard characters % or _
1989 $condition .= '= CAST(0x' . bin2hex($row[$i])
1990 . ' AS BINARY) AND';
1992 } else {
1993 // this blob won't be part of the final condition
1994 $condition = '';
1996 } else {
1997 $condition .= '= \''
1998 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2001 if ($meta->primary_key > 0) {
2002 $primary_key .= $condition;
2003 } elseif ($meta->unique_key > 0) {
2004 $unique_key .= $condition;
2006 $nonprimary_condition .= $condition;
2007 } // end for
2009 // Correction University of Virginia 19991216:
2010 // prefer primary or unique keys for condition,
2011 // but use conjunction of all values if no primary key
2012 if ($primary_key) {
2013 $preferred_condition = $primary_key;
2014 } elseif ($unique_key) {
2015 $preferred_condition = $unique_key;
2016 } elseif (! $force_unique) {
2017 $preferred_condition = $nonprimary_condition;
2020 return preg_replace('|\s?AND$|', '', $preferred_condition);
2021 } // end function
2024 * Generate a button or image tag
2026 * @uses PMA_USR_BROWSER_AGENT
2027 * @uses $GLOBALS['pmaThemeImage']
2028 * @uses $GLOBALS['cfg']['PropertiesIconic']
2029 * @param string name of button element
2030 * @param string class of button element
2031 * @param string name of image element
2032 * @param string text to display
2033 * @param string image to display
2035 * @access public
2036 * @author Michal Cihar (michal@cihar.com)
2038 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2039 $image)
2041 /* Opera has trouble with <input type="image"> */
2042 /* IE has trouble with <button> */
2043 if (PMA_USR_BROWSER_AGENT != 'IE') {
2044 echo '<button class="' . $button_class . '" type="submit"'
2045 .' name="' . $button_name . '" value="' . $text . '"'
2046 .' title="' . $text . '">' . "\n"
2047 .'<img class="icon" src="' . $GLOBALS['pmaThemeImage'] . $image . '"'
2048 .' title="' . $text . '" alt="' . $text . '" width="16"'
2049 .' height="16" />'
2050 .($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n"
2051 .'</button>' . "\n";
2052 } else {
2053 echo '<input type="image" name="' . $image_name . '" value="'
2054 . $text . '" title="' . $text . '" src="' . $GLOBALS['pmaThemeImage']
2055 . $image . '" />'
2056 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n";
2058 } // end function
2061 * Generate a pagination selector for browsing resultsets
2063 * @uses $GLOBALS['strPageNumber']
2064 * @uses range()
2065 * @param string URL for the JavaScript
2066 * @param string Number of rows in the pagination set
2067 * @param string current page number
2068 * @param string number of total pages
2069 * @param string If the number of pages is lower than this
2070 * variable, no pages will be ommitted in
2071 * pagination
2072 * @param string How many rows at the beginning should always
2073 * be shown?
2074 * @param string How many rows at the end should always
2075 * be shown?
2076 * @param string Percentage of calculation page offsets to
2077 * hop to a next page
2078 * @param string Near the current page, how many pages should
2079 * be considered "nearby" and displayed as
2080 * well?
2081 * @param string The prompt to display (sometimes empty)
2083 * @access public
2084 * @author Garvin Hicking (pma@supergarv.de)
2086 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2087 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2088 $range = 10, $prompt = '')
2090 $gotopage = $prompt
2091 . ' <select name="pos" onchange="goToUrl(this, \''
2092 . $url . '\');">' . "\n";
2093 if ($nbTotalPage < $showAll) {
2094 $pages = range(1, $nbTotalPage);
2095 } else {
2096 $pages = array();
2098 // Always show first X pages
2099 for ($i = 1; $i <= $sliceStart; $i++) {
2100 $pages[] = $i;
2103 // Always show last X pages
2104 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2105 $pages[] = $i;
2108 // garvin: Based on the number of results we add the specified
2109 // $percent percentate to each page number,
2110 // so that we have a representing page number every now and then to
2111 // immideately jump to specific pages.
2112 // As soon as we get near our currently chosen page ($pageNow -
2113 // $range), every page number will be
2114 // shown.
2115 $i = $sliceStart;
2116 $x = $nbTotalPage - $sliceEnd;
2117 $met_boundary = false;
2118 while ($i <= $x) {
2119 if ($i >= ($pageNow - $range) && $i <= ($pageNow + $range)) {
2120 // If our pageselector comes near the current page, we use 1
2121 // counter increments
2122 $i++;
2123 $met_boundary = true;
2124 } else {
2125 // We add the percentate increment to our current page to
2126 // hop to the next one in range
2127 $i = $i + floor($nbTotalPage / $percent);
2129 // Make sure that we do not cross our boundaries.
2130 if ($i > ($pageNow - $range) && !$met_boundary) {
2131 $i = $pageNow - $range;
2135 if ($i > 0 && $i <= $x) {
2136 $pages[] = $i;
2140 // Since because of ellipsing of the current page some numbers may be double,
2141 // we unify our array:
2142 sort($pages);
2143 $pages = array_unique($pages);
2146 foreach ($pages as $i) {
2147 if ($i == $pageNow) {
2148 $selected = 'selected="selected" style="font-weight: bold"';
2149 } else {
2150 $selected = '';
2152 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2155 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2158 return $gotopage;
2159 } // end function
2163 * Generate navigation for a list
2165 * @todo use $pos from $_url_params
2166 * @uses $GLOBALS['strPageNumber']
2167 * @uses range()
2168 * @param integer number of elements in the list
2169 * @param integer current position in the list
2170 * @param array url parameters
2171 * @param string script name for form target
2172 * @param string target frame
2173 * @param integer maximum number of elements to display from the list
2175 * @access public
2177 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2179 if ($max_count < $count) {
2180 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2181 echo $GLOBALS['strPageNumber'];
2182 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2184 // Move to the beginning or to the previous page
2185 if ($pos > 0) {
2186 // loic1: patch #474210 from Gosha Sakovich - part 1
2187 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2188 $caption1 = '&lt;&lt;';
2189 $caption2 = ' &lt; ';
2190 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2191 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2192 } else {
2193 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2194 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2195 $title1 = '';
2196 $title2 = '';
2197 } // end if... else...
2198 $_url_params['pos'] = 0;
2199 echo '<a' . $title1 . ' href="' . $script
2200 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2201 . $caption1 . '</a>';
2202 $_url_params['pos'] = $pos - $max_count;
2203 echo '<a' . $title2 . ' href="' . $script
2204 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2205 . $caption2 . '</a>';
2208 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2209 echo PMA_generate_common_hidden_inputs($_url_params);
2210 echo PMA_pageselector(
2211 $script . PMA_generate_common_url($_url_params) . '&',
2212 $max_count,
2213 floor(($pos + 1) / $max_count) + 1,
2214 ceil($count / $max_count));
2215 echo '</form>';
2217 if ($pos + $max_count < $count) {
2218 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2219 $caption3 = ' &gt; ';
2220 $caption4 = '&gt;&gt;';
2221 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2222 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2223 } else {
2224 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2225 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2226 $title3 = '';
2227 $title4 = '';
2228 } // end if... else...
2229 $_url_params['pos'] = $pos + $max_count;
2230 echo '<a' . $title3 . ' href="' . $script
2231 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2232 . $caption3 . '</a>';
2233 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2234 if ($_url_params['pos'] == $count) {
2235 $_url_params['pos'] = $count - $max_count;
2237 echo '<a' . $title4 . ' href="' . $script
2238 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2239 . $caption4 . '</a>';
2241 echo "\n";
2242 if ('frame_navigation' == $frame) {
2243 echo '</div>' . "\n";
2249 * replaces %u in given path with current user name
2251 * example:
2252 * <code>
2253 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2255 * </code>
2256 * @uses $cfg['Server']['user']
2257 * @uses substr()
2258 * @uses str_replace()
2259 * @param string $dir with wildcard for user
2260 * @return string per user directory
2262 function PMA_userDir($dir)
2264 // add trailing slash
2265 if (substr($dir, -1) != '/') {
2266 $dir .= '/';
2269 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2273 * returns html code for db link to default db page
2275 * @uses $cfg['DefaultTabDatabase']
2276 * @uses $GLOBALS['db']
2277 * @uses $GLOBALS['strJumpToDB']
2278 * @uses PMA_generate_common_url()
2279 * @uses PMA_unescape_mysql_wildcards()
2280 * @uses strlen()
2281 * @uses sprintf()
2282 * @uses htmlspecialchars()
2283 * @param string $database
2284 * @return string html link to default db page
2286 function PMA_getDbLink($database = null)
2288 if (!strlen($database)) {
2289 if (!strlen($GLOBALS['db'])) {
2290 return '';
2292 $database = $GLOBALS['db'];
2293 } else {
2294 $database = PMA_unescape_mysql_wildcards($database);
2297 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2298 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2299 .htmlspecialchars($database) . '</a>';
2303 * Displays a lightbulb hint explaining a known external bug
2304 * that affects a functionality
2306 * @uses PMA_MYSQL_INT_VERSION
2307 * @uses $GLOBALS['strKnownExternalBug']
2308 * @uses PMA_showHint()
2309 * @uses sprintf()
2310 * @param string $functionality localized message explaining the func.
2311 * @param string $component 'mysql' (eventually, 'php')
2312 * @param string $minimum_version of this component
2313 * @param string $bugref bug reference for this component
2315 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2317 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2318 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2323 * Converts a bit value to printable format;
2324 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2325 * function because in PHP, decbin() supports only 32 bits
2327 * @uses ceil()
2328 * @uses decbin()
2329 * @uses ord()
2330 * @uses substr()
2331 * @uses sprintf()
2332 * @param numeric $value coming from a BIT field
2333 * @param integer $length
2334 * @return string the printable value
2336 function PMA_printable_bit_value($value, $length) {
2337 $printable = '';
2338 for ($i = 0; $i < ceil($length / 8); $i++) {
2339 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2341 $printable = substr($printable, -$length);
2342 return $printable;
2346 * Extracts the true field type and length from a field type spec
2348 * @uses strpos()
2349 * @uses chop()
2350 * @uses substr()
2351 * @param string $fieldspec
2352 * @return array associative array containing the type and length
2354 function PMA_extract_type_length($fieldspec) {
2355 $first_bracket_pos = strpos($fieldspec, '(');
2356 if ($first_bracket_pos) {
2357 $length = chop(substr($fieldspec, $first_bracket_pos + 1, (strpos($fieldspec, ')') - $first_bracket_pos - 1)));
2358 $type = chop(substr($fieldspec, 0, $first_bracket_pos));
2359 } else {
2360 $type = $fieldspec;
2361 $length = '';
2363 return array(
2364 'type' => $type,
2365 'length' => $length