avoid marking the Browse tab active after a click, when there are no rows
[phpmyadmin/crack.git] / libraries / common.lib.php
blob2fb6ee014df6c25b3b5a11d253e94c4c35ecded3
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 $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()
424 * @uses strtolower()
425 * @uses urlencode()
426 * @uses str_replace()
427 * @uses nl2br()
428 * @uses substr()
429 * @uses preg_replace()
430 * @uses preg_match()
431 * @uses explode()
432 * @uses implode()
433 * @uses is_array()
434 * @uses function_exists()
435 * @uses htmlspecialchars()
436 * @uses trim()
437 * @uses strstr()
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
447 * @access public
449 function PMA_mysqlDie($error_message = '', $the_query = '',
450 $is_modify_link = true, $back_url = '', $exit = true)
452 global $table, $db;
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) == '') {
472 $formatted_sql = '';
473 } else {
474 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
476 // ---
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
481 // username/password
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";
490 // ---
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) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
499 } else {
500 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($db) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
502 if ($GLOBALS['cfg']['PropertiesIconic']) {
503 echo $doedit_goto
504 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
505 . '</a>';
506 } else {
507 echo ' ['
508 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
509 . ']' . "\n";
511 } // end if
512 echo ' </p>' . "\n"
513 .' <p>' . "\n"
514 .' ' . $formatted_sql . "\n"
515 .' </p>' . "\n";
516 } // end if
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)
526 echo '<p>' . "\n"
527 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
528 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
529 . "\n"
530 . '</p>' . "\n";
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(' ', '&nbsp;&nbsp;', $error_message);
537 // Replace TAB-characters with their HTML-counterpart
538 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
539 // Replace linebreaks
540 $error_message = nl2br($error_message);
542 echo '<code>' . "\n"
543 . $error_message . "\n"
544 . '</code><br />' . "\n";
546 // feature request #1036254:
547 // Add a link by MySQL-Error #1062 - Duplicate entry
548 // 2004-10-20 by mkkeck
549 // 2005-01-17 modified by mkkeck bugfix
550 if (substr($error_message, 1, 4) == '1062') {
551 // get the duplicate entry
553 // get table name
555 * @todo what would be the best delimiter, while avoiding special
556 * characters that can become high-ascii after editing, depending
557 * upon which editor is used by the developer?
559 $error_table = array();
560 if (preg_match('@ALTER\s*TABLE\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
561 $error_table = $error_table[1];
562 } elseif (preg_match('@INSERT\s*INTO\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
563 $error_table = $error_table[1];
564 } elseif (preg_match('@UPDATE\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
565 $error_table = $error_table[1];
566 } elseif (preg_match('@INSERT\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
567 $error_table = $error_table[1];
570 // get fields
571 $error_fields = array();
572 if (preg_match('@\(([^\)]+)\)@i', $the_query, $error_fields)) {
573 $error_fields = explode(',', $error_fields[1]);
574 } elseif (preg_match('@(`[^`]+`)\s*=@i', $the_query, $error_fields)) {
575 $error_fields = explode(',', $error_fields[1]);
577 if (is_array($error_table) || is_array($error_fields)) {
579 // duplicate value
580 $duplicate_value = array();
581 preg_match('@\'([^\']+)\'@i', $tmp_mysql_error, $duplicate_value);
582 $duplicate_value = $duplicate_value[1];
584 $sql = '
585 SELECT *
586 FROM ' . PMA_backquote($error_table) . '
587 WHERE CONCAT_WS("-", ' . implode(', ', $error_fields) . ')
588 = "' . PMA_sqlAddslashes($duplicate_value) . '"
589 ORDER BY ' . implode(', ', $error_fields);
590 unset($error_table, $error_fields, $duplicate_value);
592 echo ' <form method="post" action="import.php" style="padding: 0; margin: 0">' ."\n"
593 .' <input type="hidden" name="sql_query" value="' . htmlspecialchars($sql) . '" />' . "\n"
594 .' ' . PMA_generate_common_hidden_inputs($db, $table) . "\n"
595 .' <input type="submit" name="submit" value="' . $GLOBALS['strBrowse'] . '" />' . "\n"
596 .' </form>' . "\n";
597 unset($sql);
599 } // end of show duplicate entry
601 echo '</div>';
602 echo '<fieldset class="tblFooters">';
604 if (!empty($back_url) && $exit) {
605 $goto_back_url='<a href="' . (strstr($back_url, '?') ? $back_url . '&amp;no_history=true' : $back_url . '?no_history=true') . '">';
606 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
608 echo ' </fieldset>' . "\n\n";
609 if ($exit) {
611 * display footer and exit
613 require_once './libraries/footer.inc.php';
615 } // end of the 'PMA_mysqlDie()' function
618 * Returns a string formatted with CONVERT ... USING
619 * if MySQL supports it
621 * @uses PMA_MYSQL_INT_VERSION
622 * @uses $GLOBALS['collation_connection']
623 * @uses explode()
624 * @param string the string itself
625 * @param string the mode: quoted or unquoted (this one by default)
627 * @return the formatted string
629 * @access private
631 function PMA_convert_using($string, $mode='unquoted')
633 if ($mode == 'quoted') {
634 $possible_quote = "'";
635 } else {
636 $possible_quote = "";
639 if (PMA_MYSQL_INT_VERSION >= 40100) {
640 list($conn_charset) = explode('_', $GLOBALS['collation_connection']);
641 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $conn_charset . ")";
642 } else {
643 $converted_string = $possible_quote . $string . $possible_quote;
645 return $converted_string;
646 } // end function
649 * Send HTTP header, taking IIS limits into account (600 seems ok)
651 * @uses PMA_IS_IIS
652 * @uses PMA_COMING_FROM_COOKIE_LOGIN
653 * @uses PMA_get_arg_separator()
654 * @uses SID
655 * @uses strlen()
656 * @uses strpos()
657 * @uses header()
658 * @uses session_write_close()
659 * @uses headers_sent()
660 * @uses function_exists()
661 * @uses debug_print_backtrace()
662 * @uses trigger_error()
663 * @uses defined()
664 * @param string $uri the header to send
665 * @return boolean always true
667 function PMA_sendHeaderLocation($uri)
669 if (PMA_IS_IIS && strlen($uri) > 600) {
671 echo '<html><head><title>- - -</title>' . "\n";
672 echo '<meta http-equiv="expires" content="0">' . "\n";
673 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
674 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
675 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
676 echo '<script type="text/javascript">' . "\n";
677 echo '//<![CDATA[' . "\n";
678 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
679 echo '//]]>' . "\n";
680 echo '</script>' . "\n";
681 echo '</head>' . "\n";
682 echo '<body>' . "\n";
683 echo '<script type="text/javascript">' . "\n";
684 echo '//<![CDATA[' . "\n";
685 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
686 echo '//]]>' . "\n";
687 echo '</script></body></html>' . "\n";
689 } else {
690 if (SID) {
691 if (strpos($uri, '?') === false) {
692 header('Location: ' . $uri . '?' . SID);
693 } else {
694 $separator = PMA_get_arg_separator();
695 header('Location: ' . $uri . $separator . SID);
697 } else {
698 session_write_close();
699 if (headers_sent()) {
700 if (function_exists('debug_print_backtrace')) {
701 echo '<pre>';
702 debug_print_backtrace();
703 echo '</pre>';
705 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
707 // bug #1523784: IE6 does not like 'Refresh: 0', it
708 // results in a blank page
709 // but we need it when coming from the cookie login panel)
710 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
711 header('Refresh: 0; ' . $uri);
712 } else {
713 header('Location: ' . $uri);
720 * returns array with tables of given db with extended information and grouped
722 * @uses $cfg['LeftFrameTableSeparator']
723 * @uses $cfg['LeftFrameTableLevel']
724 * @uses $cfg['ShowTooltipAliasTB']
725 * @uses $cfg['NaturalOrder']
726 * @uses PMA_backquote()
727 * @uses count()
728 * @uses array_merge
729 * @uses uksort()
730 * @uses strstr()
731 * @uses explode()
732 * @param string $db name of db
733 * @param string $tables name of tables
734 * return array (recursive) grouped table list
736 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
738 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
740 if (null === $tables) {
741 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
742 if ($GLOBALS['cfg']['NaturalOrder']) {
743 uksort($tables, 'strnatcasecmp');
747 if (count($tables) < 1) {
748 return $tables;
751 $default = array(
752 'Name' => '',
753 'Rows' => 0,
754 'Comment' => '',
755 'disp_name' => '',
758 $table_groups = array();
760 foreach ($tables as $table_name => $table) {
762 // check for correct row count
763 if (null === $table['Rows']) {
764 // Do not check exact row count here,
765 // if row count is invalid possibly the table is defect
766 // and this would break left frame;
767 // but we can check row count if this is a view,
768 // since PMA_Table::countRecords() returns a limited row count
769 // in this case.
771 // set this because PMA_Table::countRecords() can use it
772 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
774 if ($tbl_is_view) {
775 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
776 $return = true);
780 // in $group we save the reference to the place in $table_groups
781 // where to store the table info
782 if ($GLOBALS['cfg']['LeftFrameDBTree']
783 && $sep && strstr($table_name, $sep))
785 $parts = explode($sep, $table_name);
787 $group =& $table_groups;
788 $i = 0;
789 $group_name_full = '';
790 while ($i < count($parts) - 1
791 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
792 $group_name = $parts[$i] . $sep;
793 $group_name_full .= $group_name;
795 if (!isset($group[$group_name])) {
796 $group[$group_name] = array();
797 $group[$group_name]['is' . $sep . 'group'] = true;
798 $group[$group_name]['tab' . $sep . 'count'] = 1;
799 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
800 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
801 $table = $group[$group_name];
802 $group[$group_name] = array();
803 $group[$group_name][$group_name] = $table;
804 unset($table);
805 $group[$group_name]['is' . $sep . 'group'] = true;
806 $group[$group_name]['tab' . $sep . 'count'] = 1;
807 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
808 } else {
809 $group[$group_name]['tab' . $sep . 'count']++;
811 $group =& $group[$group_name];
812 $i++;
814 } else {
815 if (!isset($table_groups[$table_name])) {
816 $table_groups[$table_name] = array();
818 $group =& $table_groups;
822 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
823 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
824 // switch tooltip and name
825 $table['Comment'] = $table['Name'];
826 $table['disp_name'] = $table['Comment'];
827 } else {
828 $table['disp_name'] = $table['Name'];
831 $group[$table_name] = array_merge($default, $table);
834 return $table_groups;
837 /* ----------------------- Set of misc functions ----------------------- */
841 * Adds backquotes on both sides of a database, table or field name.
842 * and escapes backquotes inside the name with another backquote
844 * example:
845 * <code>
846 * echo PMA_backquote('owner`s db'); // `owner``s db`
848 * </code>
850 * @uses PMA_backquote()
851 * @uses is_array()
852 * @uses strlen()
853 * @uses str_replace()
854 * @param mixed $a_name the database, table or field name to "backquote"
855 * or array of it
856 * @param boolean $do_it a flag to bypass this function (used by dump
857 * functions)
858 * @return mixed the "backquoted" database, table or field name if the
859 * current MySQL release is >= 3.23.6, the original one
860 * else
861 * @access public
863 function PMA_backquote($a_name, $do_it = true)
865 if (! $do_it) {
866 return $a_name;
869 if (is_array($a_name)) {
870 $result = array();
871 foreach ($a_name as $key => $val) {
872 $result[$key] = PMA_backquote($val);
874 return $result;
877 // '0' is also empty for php :-(
878 if (strlen($a_name) && $a_name !== '*') {
879 return '`' . str_replace('`', '``', $a_name) . '`';
880 } else {
881 return $a_name;
883 } // end of the 'PMA_backquote()' function
887 * Defines the <CR><LF> value depending on the user OS.
889 * @uses PMA_USR_OS
890 * @return string the <CR><LF> value to use
892 * @access public
894 function PMA_whichCrlf()
896 $the_crlf = "\n";
898 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
899 // Win case
900 if (PMA_USR_OS == 'Win') {
901 $the_crlf = "\r\n";
903 // Others
904 else {
905 $the_crlf = "\n";
908 return $the_crlf;
909 } // end of the 'PMA_whichCrlf()' function
912 * Reloads navigation if needed.
914 * @uses $GLOBALS['reload']
915 * @uses $GLOBALS['db']
916 * @uses PMA_generate_common_url()
917 * @global array configuration
919 * @access public
921 function PMA_reloadNavigation()
923 global $cfg;
925 // Reloads the navigation frame via JavaScript if required
926 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
927 echo "\n";
928 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
930 <script type="text/javascript">
931 //<![CDATA[
932 if (typeof(window.parent) != 'undefined'
933 && typeof(window.parent.frame_navigation) != 'undefined') {
934 window.parent.goTo('<?php echo $reload_url; ?>');
936 //]]>
937 </script>
938 <?php
939 unset($GLOBALS['reload']);
944 * displays the message and the query
945 * usually the message is the result of the query executed
947 * @param string $message the message to display
948 * @param string $sql_query the query to display
949 * @global array the configuration array
950 * @uses $cfg
951 * @access public
953 function PMA_showMessage($message, $sql_query = null)
955 global $cfg;
956 $query_too_big = false;
958 if (null === $sql_query) {
959 if (! empty($GLOBALS['display_query'])) {
960 $sql_query = $GLOBALS['display_query'];
961 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
962 $sql_query = $GLOBALS['unparsed_sql'];
963 } elseif (! empty($GLOBALS['sql_query'])) {
964 $sql_query = $GLOBALS['sql_query'];
965 } else {
966 $sql_query = '';
970 // Corrects the tooltip text via JS if required
971 // @todo this is REALLY the wrong place to do this - very unexpected here
972 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
973 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
974 if ($result) {
975 $tbl_status = PMA_DBI_fetch_assoc($result);
976 $tooltip = (empty($tbl_status['Comment']))
977 ? ''
978 : $tbl_status['Comment'] . ' ';
979 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
980 PMA_DBI_free_result($result);
981 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
982 echo "\n";
983 echo '<script type="text/javascript">' . "\n";
984 echo '//<![CDATA[' . "\n";
985 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
986 echo '//]]>' . "\n";
987 echo '</script>' . "\n";
988 } // end if
989 } // end if ... elseif
991 // Checks if the table needs to be repaired after a TRUNCATE query.
992 // @todo what about $GLOBALS['display_query']???
993 // @todo this is REALLY the wrong place to do this - very unexpected here
994 if (strlen($GLOBALS['table'])
995 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
996 if (!isset($tbl_status)) {
997 $result = @PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
998 if ($result) {
999 $tbl_status = PMA_DBI_fetch_assoc($result);
1000 PMA_DBI_free_result($result);
1003 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
1004 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1007 unset($tbl_status);
1008 echo '<br />' . "\n";
1010 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1011 if (!empty($GLOBALS['show_error_header'])) {
1012 echo '<div class="error">' . "\n";
1013 echo '<h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
1016 echo '<div class="notice">';
1017 echo PMA_sanitize($message);
1018 if (isset($GLOBALS['special_message'])) {
1019 echo PMA_sanitize($GLOBALS['special_message']);
1020 unset($GLOBALS['special_message']);
1022 echo '</div>';
1024 if (!empty($GLOBALS['show_error_header'])) {
1025 echo '</div>';
1028 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1029 // Basic url query part
1030 $url_qpart = '?' . PMA_generate_common_url($GLOBALS['db'], $GLOBALS['table']);
1032 // Html format the query to be displayed
1033 // The nl2br function isn't used because its result isn't a valid
1034 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
1035 // If we want to show some sql code it is easiest to create it here
1036 /* SQL-Parser-Analyzer */
1038 if (!empty($GLOBALS['show_as_php'])) {
1039 $new_line = '\'<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
1041 if (isset($new_line)) {
1042 /* SQL-Parser-Analyzer */
1043 $query_base = PMA_sqlAddslashes(htmlspecialchars($sql_query), false, false, true);
1044 /* SQL-Parser-Analyzer */
1045 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
1046 } else {
1047 $query_base = $sql_query;
1050 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1051 $query_too_big = true;
1052 $query_base = nl2br(htmlspecialchars($sql_query));
1053 unset($GLOBALS['parsed_sql']);
1056 // Parse SQL if needed
1057 // (here, use "! empty" because when deleting a bookmark,
1058 // $GLOBALS['parsed_sql'] is set but empty
1059 if (! empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1060 $parsed_sql = $GLOBALS['parsed_sql'];
1061 } else {
1062 // when the query is large (for example an INSERT of binary
1063 // data), the parser chokes; so avoid parsing the query
1064 if (! $query_too_big) {
1065 $parsed_sql = PMA_SQP_parse($query_base);
1069 // Analyze it
1070 if (isset($parsed_sql)) {
1071 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1074 // Here we append the LIMIT added for navigation, to
1075 // enable its display. Adding it higher in the code
1076 // to $sql_query would create a problem when
1077 // using the Refresh or Edit links.
1079 // Only append it on SELECTs.
1082 * @todo what would be the best to do when someone hits Refresh:
1083 * use the current LIMITs ?
1086 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1087 && isset($GLOBALS['sql_limit_to_append'])) {
1088 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1089 // Need to reparse query
1090 $parsed_sql = PMA_SQP_parse($query_base);
1093 if (!empty($GLOBALS['show_as_php'])) {
1094 $query_base = '$sql = \'' . $query_base;
1095 } elseif (!empty($GLOBALS['validatequery'])) {
1096 $query_base = PMA_validateSQL($query_base);
1097 } else {
1098 if (isset($parsed_sql)) {
1099 $query_base = PMA_formatSql($parsed_sql, $query_base);
1103 // Prepares links that may be displayed to edit/explain the query
1104 // (don't go to default pages, we must go to the page
1105 // where the query box is available)
1107 $edit_target = strlen($GLOBALS['db']) ? (strlen($GLOBALS['table']) ? 'tbl_sql.php' : 'db_sql.php') : 'server_sql.php';
1109 if (isset($cfg['SQLQuery']['Edit'])
1110 && ($cfg['SQLQuery']['Edit'] == true)
1111 && (!empty($edit_target))
1112 && ! $query_too_big) {
1114 if ($cfg['EditInWindow'] == true) {
1115 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1116 } else {
1117 $onclick = '';
1120 $edit_link = $edit_target
1121 . $url_qpart
1122 . '&amp;sql_query=' . urlencode($sql_query)
1123 . '&amp;show_query=1#querybox';
1124 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1125 } else {
1126 $edit_link = '';
1129 // Want to have the query explained (Mike Beck 2002-05-22)
1130 // but only explain a SELECT (that has not been explained)
1131 /* SQL-Parser-Analyzer */
1132 if (isset($cfg['SQLQuery']['Explain'])
1133 && $cfg['SQLQuery']['Explain'] == true
1134 && ! $query_too_big) {
1136 // Detect if we are validating as well
1137 // To preserve the validate uRL data
1138 if (!empty($GLOBALS['validatequery'])) {
1139 $explain_link_validate = '&amp;validatequery=1';
1140 } else {
1141 $explain_link_validate = '';
1144 $explain_link = 'import.php'
1145 . $url_qpart
1146 . $explain_link_validate
1147 . '&amp;sql_query=';
1149 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1150 $explain_link .= urlencode('EXPLAIN ' . $sql_query);
1151 $message = $GLOBALS['strExplain'];
1152 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1153 $explain_link .= urlencode(substr($sql_query, 8));
1154 $message = $GLOBALS['strNoExplain'];
1155 } else {
1156 $explain_link = '';
1158 if (!empty($explain_link)) {
1159 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1161 } else {
1162 $explain_link = '';
1163 } //show explain
1165 // Also we would like to get the SQL formed in some nice
1166 // php-code (Mike Beck 2002-05-22)
1167 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1168 && $cfg['SQLQuery']['ShowAsPHP'] == true
1169 && ! $query_too_big) {
1170 $php_link = 'import.php'
1171 . $url_qpart
1172 . '&amp;show_query=1'
1173 . '&amp;sql_query=' . urlencode($sql_query)
1174 . '&amp;show_as_php=';
1176 if (!empty($GLOBALS['show_as_php'])) {
1177 $php_link .= '0';
1178 $message = $GLOBALS['strNoPhp'];
1179 } else {
1180 $php_link .= '1';
1181 $message = $GLOBALS['strPhp'];
1183 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1185 if (isset($GLOBALS['show_as_php'])) {
1186 $runquery_link
1187 = 'import.php'
1188 . $url_qpart
1189 . '&amp;show_query=1'
1190 . '&amp;sql_query=' . urlencode($sql_query);
1191 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1194 } else {
1195 $php_link = '';
1196 } //show as php
1198 // Refresh query
1199 if (isset($cfg['SQLQuery']['Refresh'])
1200 && $cfg['SQLQuery']['Refresh']
1201 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1203 $refresh_link = 'import.php'
1204 . $url_qpart
1205 . '&amp;show_query=1'
1206 . '&amp;sql_query=' . urlencode($sql_query);
1207 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1208 } else {
1209 $refresh_link = '';
1210 } //show as php
1212 if (isset($cfg['SQLValidator']['use'])
1213 && $cfg['SQLValidator']['use'] == true
1214 && isset($cfg['SQLQuery']['Validate'])
1215 && $cfg['SQLQuery']['Validate'] == true) {
1216 $validate_link = 'import.php'
1217 . $url_qpart
1218 . '&amp;show_query=1'
1219 . '&amp;sql_query=' . urlencode($sql_query)
1220 . '&amp;validatequery=';
1221 if (!empty($GLOBALS['validatequery'])) {
1222 $validate_link .= '0';
1223 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1224 } else {
1225 $validate_link .= '1';
1226 $validate_message = $GLOBALS['strValidateSQL'] ;
1228 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1229 } else {
1230 $validate_link = '';
1231 } //validator
1233 // why this?
1234 //unset($sql_query);
1236 // Displays the message
1237 echo '<fieldset class="">' . "\n";
1238 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1239 echo ' <div>';
1240 // when uploading a 700 Kio binary file into a LONGBLOB,
1241 // I get a white page, strlen($query_base) is 2 x 700 Kio
1242 // so put a hard limit here (let's say 1000)
1243 if ($query_too_big) {
1244 echo ' ' . substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1245 } else {
1246 echo ' ' . $query_base;
1249 //Clean up the end of the PHP
1250 if (!empty($GLOBALS['show_as_php'])) {
1251 echo '\';';
1253 echo ' </div>';
1254 echo '</fieldset>' . "\n";
1256 if (!empty($edit_target)) {
1257 echo '<fieldset class="tblFooters">';
1258 PMA_profilingCheckbox($sql_query);
1259 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1260 echo '</fieldset>';
1263 echo '</div><br />' . "\n";
1264 } // end of the 'PMA_showMessage()' function
1268 * Displays a form with the Profiling checkbox
1270 * @param string $sql_query
1271 * @access public
1273 * @author Marc Delisle
1275 function PMA_profilingCheckbox($sql_query) {
1276 if (PMA_MYSQL_INT_VERSION >= 50037) {
1277 echo '<form action="sql.php" method="post" />' . "\n";
1278 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1279 echo '<input type="hidden" name="sql_query" value="' . $sql_query . '" />' . "\n";
1280 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1281 echo '<input type="checkbox" name="profiling" id="profiling"' . (isset($_SESSION['profiling']) ? ' checked="checked"' : '') . ' onclick="this.form.submit();" /><label for="profiling">' . $GLOBALS['strProfiling'] . '</label>' . "\n";
1282 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1283 echo '</form>' . "\n";
1288 * Displays the results of SHOW PROFILE
1290 * @param array the results
1291 * @access public
1293 * @author Marc Delisle
1295 function PMA_profilingResults($profiling_results) {
1296 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1297 echo '<table>' . "\n";
1298 echo ' <tr>' . "\n";
1299 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1300 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1301 echo ' </tr>' . "\n";
1303 foreach($profiling_results as $one_result) {
1304 echo ' <tr>' . "\n";
1305 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1306 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1308 echo '</table>' . "\n";
1309 echo '</fieldset>' . "\n";
1313 * Formats $value to byte view
1315 * @param double the value to format
1316 * @param integer the sensitiveness
1317 * @param integer the number of decimals to retain
1319 * @return array the formatted value and its unit
1321 * @access public
1323 * @author staybyte
1324 * @version 1.2 - 18 July 2002
1326 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1328 $dh = PMA_pow(10, $comma);
1329 $li = PMA_pow(10, $limes);
1330 $return_value = $value;
1331 $unit = $GLOBALS['byteUnits'][0];
1333 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1334 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1335 // use 1024.0 to avoid integer overflow on 64-bit machines
1336 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1337 $unit = $GLOBALS['byteUnits'][$d];
1338 break 1;
1339 } // end if
1340 } // end for
1342 if ($unit != $GLOBALS['byteUnits'][0]) {
1343 $return_value = PMA_formatNumber($value, 5, $comma);
1344 } else {
1345 $return_value = PMA_formatNumber($value, 0);
1348 return array($return_value, $unit);
1349 } // end of the 'PMA_formatByteDown' function
1352 * Formats $value to the given length and appends SI prefixes
1353 * $comma is not substracted from the length
1354 * with a $length of 0 no truncation occurs, number is only formated
1355 * to the current locale
1357 * examples:
1358 * <code>
1359 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1360 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1361 * echo PMA_formatNumber(-0.003, 6); // -3 m
1362 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1363 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1364 * echo PMA_formatNumber(0, 6); // 0
1366 * </code>
1367 * @param double $value the value to format
1368 * @param integer $length the max length
1369 * @param integer $comma the number of decimals to retain
1370 * @param boolean $only_down do not reformat numbers below 1
1372 * @return string the formatted value and its unit
1374 * @access public
1376 * @author staybyte, sebastian mendel
1377 * @version 1.1.0 - 2005-10-27
1379 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1381 //number_format is not multibyte safe, str_replace is safe
1382 if ($length === 0) {
1383 return str_replace(array(',', '.'),
1384 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1385 number_format($value, $comma));
1388 // this units needs no translation, ISO
1389 $units = array(
1390 -8 => 'y',
1391 -7 => 'z',
1392 -6 => 'a',
1393 -5 => 'f',
1394 -4 => 'p',
1395 -3 => 'n',
1396 -2 => '&micro;',
1397 -1 => 'm',
1398 0 => ' ',
1399 1 => 'k',
1400 2 => 'M',
1401 3 => 'G',
1402 4 => 'T',
1403 5 => 'P',
1404 6 => 'E',
1405 7 => 'Z',
1406 8 => 'Y'
1409 // we need at least 3 digits to be displayed
1410 if (3 > $length + $comma) {
1411 $length = 3 - $comma;
1414 // check for negativ value to retain sign
1415 if ($value < 0) {
1416 $sign = '-';
1417 $value = abs($value);
1418 } else {
1419 $sign = '';
1422 $dh = PMA_pow(10, $comma);
1423 $li = PMA_pow(10, $length);
1424 $unit = $units[0];
1426 if ($value >= 1) {
1427 for ($d = 8; $d >= 0; $d--) {
1428 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1429 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1430 $unit = $units[$d];
1431 break 1;
1432 } // end if
1433 } // end for
1434 } elseif (!$only_down && (float) $value !== 0.0) {
1435 for ($d = -8; $d <= 8; $d++) {
1436 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1437 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1438 $unit = $units[$d];
1439 break 1;
1440 } // end if
1441 } // end for
1442 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1444 //number_format is not multibyte safe, str_replace is safe
1445 $value = str_replace(array(',', '.'),
1446 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1447 number_format($value, $comma));
1449 return $sign . $value . ' ' . $unit;
1450 } // end of the 'PMA_formatNumber' function
1453 * Extracts ENUM / SET options from a type definition string
1455 * @param string The column type definition
1457 * @return array The options or
1458 * boolean false in case of an error.
1460 * @author rabus
1462 function PMA_getEnumSetOptions($type_def)
1464 $open = strpos($type_def, '(');
1465 $close = strrpos($type_def, ')');
1466 if (!$open || !$close) {
1467 return false;
1469 $options = substr($type_def, $open + 2, $close - $open - 3);
1470 $options = explode('\',\'', $options);
1471 return $options;
1472 } // end of the 'PMA_getEnumSetOptions' function
1475 * Writes localised date
1477 * @param string the current timestamp
1479 * @return string the formatted date
1481 * @access public
1483 function PMA_localisedDate($timestamp = -1, $format = '')
1485 global $datefmt, $month, $day_of_week;
1487 if ($format == '') {
1488 $format = $datefmt;
1491 if ($timestamp == -1) {
1492 $timestamp = time();
1495 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1496 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1498 return strftime($date, $timestamp);
1499 } // end of the 'PMA_localisedDate()' function
1503 * returns a tab for tabbed navigation.
1504 * If the variables $link and $args ar left empty, an inactive tab is created
1506 * @uses $GLOBALS['strEmpty']
1507 * @uses $GLOBALS['strDrop']
1508 * @uses $GLOBALS['active_page']
1509 * @uses $GLOBALS['url_query']
1510 * @uses $cfg['MainPageIconic']
1511 * @uses $GLOBALS['pmaThemeImage']
1512 * @uses PMA_generate_common_url()
1513 * @uses E_USER_NOTICE
1514 * @uses htmlentities()
1515 * @uses urlencode()
1516 * @uses sprintf()
1517 * @uses trigger_error()
1518 * @uses array_merge()
1519 * @uses basename()
1520 * @param array $tab array with all options
1521 * @return string html code for one tab, a link if valid otherwise a span
1522 * @access public
1524 function PMA_getTab($tab)
1526 // default values
1527 $defaults = array(
1528 'text' => '',
1529 'class' => '',
1530 'active' => false,
1531 'link' => '',
1532 'sep' => '?',
1533 'attr' => '',
1534 'args' => '',
1535 'warning' => '',
1536 'fragment' => '',
1539 $tab = array_merge($defaults, $tab);
1541 // determine additionnal style-class
1542 if (empty($tab['class'])) {
1543 if ($tab['text'] == $GLOBALS['strEmpty']
1544 || $tab['text'] == $GLOBALS['strDrop']) {
1545 $tab['class'] = 'caution';
1546 } elseif (!empty($tab['active'])
1547 || (isset($GLOBALS['active_page'])
1548 && $GLOBALS['active_page'] == $tab['link'])
1549 || (basename(PMA_getenv('PHP_SELF')) == $tab['link'] && empty($tab['warning'])))
1551 $tab['class'] = 'active';
1555 if (!empty($tab['warning'])) {
1556 $tab['class'] .= ' warning';
1557 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1560 // build the link
1561 if (!empty($tab['link'])) {
1562 $tab['link'] = htmlentities($tab['link']);
1563 $tab['link'] = $tab['link'] . $tab['sep']
1564 .(empty($GLOBALS['url_query']) ?
1565 PMA_generate_common_url() : $GLOBALS['url_query']);
1566 if (!empty($tab['args'])) {
1567 foreach ($tab['args'] as $param => $value) {
1568 $tab['link'] .= '&amp;' . urlencode($param) . '='
1569 . urlencode($value);
1574 if (! empty($tab['fragment'])) {
1575 $tab['link'] .= $tab['fragment'];
1578 // display icon, even if iconic is disabled but the link-text is missing
1579 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1580 && isset($tab['icon'])) {
1581 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1582 .'%1$s" width="16" height="16" alt="%2$s" />%2$s';
1583 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1585 // check to not display an empty link-text
1586 elseif (empty($tab['text'])) {
1587 $tab['text'] = '?';
1588 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1589 E_USER_NOTICE);
1592 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1594 if (!empty($tab['link'])) {
1595 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1596 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1597 . $tab['text'] . '</a>';
1598 } else {
1599 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1600 . $tab['text'] . '</span>';
1603 $out .= '</li>';
1604 return $out;
1605 } // end of the 'PMA_getTab()' function
1608 * returns html-code for a tab navigation
1610 * @uses PMA_getTab()
1611 * @uses htmlentities()
1612 * @param array $tabs one element per tab
1613 * @param string $tag_id id used for the html-tag
1614 * @return string html-code for tab-navigation
1616 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1618 $tab_navigation =
1619 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1620 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1622 foreach ($tabs as $tab) {
1623 $tab_navigation .= PMA_getTab($tab) . "\n";
1626 $tab_navigation .=
1627 '</ul>' . "\n"
1628 .'<div class="clearfloat"></div>'
1629 .'</div>' . "\n";
1631 return $tab_navigation;
1636 * Displays a link, or a button if the link's URL is too large, to
1637 * accommodate some browsers' limitations
1639 * @param string the URL
1640 * @param string the link message
1641 * @param mixed $tag_params string: js confirmation
1642 * array: additional tag params (f.e. style="")
1643 * @param boolean $new_form we set this to false when we are already in
1644 * a form, to avoid generating nested forms
1646 * @return string the results to be echoed or saved in an array
1648 function PMA_linkOrButton($url, $message, $tag_params = array(),
1649 $new_form = true, $strip_img = false, $target = '')
1651 if (! is_array($tag_params)) {
1652 $tmp = $tag_params;
1653 $tag_params = array();
1654 if (!empty($tmp)) {
1655 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1657 unset($tmp);
1659 if (! empty($target)) {
1660 $tag_params['target'] = htmlentities($target);
1663 $tag_params_strings = array();
1664 foreach ($tag_params as $par_name => $par_value) {
1665 // htmlspecialchars() only on non javascript
1666 $par_value = substr($par_name, 0, 2) == 'on'
1667 ? $par_value
1668 : htmlspecialchars($par_value);
1669 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1672 // previously the limit was set to 2047, it seems 1000 is better
1673 if (strlen($url) <= 1000) {
1674 // no whitespace within an <a> else Safari will make it part of the link
1675 $ret = "\n" . '<a href="' . $url . '" '
1676 . implode(' ', $tag_params_strings) . '>'
1677 . $message . '</a>' . "\n";
1678 } else {
1679 // no spaces (linebreaks) at all
1680 // or after the hidden fields
1681 // IE will display them all
1683 // add class=link to submit button
1684 if (empty($tag_params['class'])) {
1685 $tag_params['class'] = 'link';
1688 // decode encoded url separators
1689 $separator = PMA_get_arg_separator();
1690 // on most places separator is still hard coded ...
1691 if ($separator !== '&') {
1692 // ... so always replace & with $separator
1693 $url = str_replace(htmlentities('&'), $separator, $url);
1694 $url = str_replace('&', $separator, $url);
1696 $url = str_replace(htmlentities($separator), $separator, $url);
1697 // end decode
1699 $url_parts = parse_url($url);
1700 $query_parts = explode($separator, $url_parts['query']);
1701 if ($new_form) {
1702 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1703 . ' method="post"' . $target . ' style="display: inline;">';
1704 $subname_open = '';
1705 $subname_close = '';
1706 $submit_name = '';
1707 } else {
1708 $query_parts[] = 'redirect=' . $url_parts['path'];
1709 if (empty($GLOBALS['subform_counter'])) {
1710 $GLOBALS['subform_counter'] = 0;
1712 $GLOBALS['subform_counter']++;
1713 $ret = '';
1714 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1715 $subname_close = ']';
1716 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1718 foreach ($query_parts as $query_pair) {
1719 list($eachvar, $eachval) = explode('=', $query_pair);
1720 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1721 . $subname_close . '" value="'
1722 . htmlspecialchars(urldecode($eachval)) . '" />';
1723 } // end while
1725 if (stristr($message, '<img')) {
1726 if ($strip_img) {
1727 $message = trim(strip_tags($message));
1728 $ret .= '<input type="submit"' . $submit_name . ' '
1729 . implode(' ', $tag_params_strings)
1730 . ' value="' . htmlspecialchars($message) . '" />';
1731 } else {
1732 $ret .= '<input type="image"' . $submit_name . ' '
1733 . implode(' ', $tag_params_strings)
1734 . ' src="' . preg_replace(
1735 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1736 . ' value="' . htmlspecialchars(
1737 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1738 $message))
1739 . '" />';
1741 } else {
1742 $message = trim(strip_tags($message));
1743 $ret .= '<input type="submit"' . $submit_name . ' '
1744 . implode(' ', $tag_params_strings)
1745 . ' value="' . htmlspecialchars($message) . '" />';
1747 if ($new_form) {
1748 $ret .= '</form>';
1750 } // end if... else...
1752 return $ret;
1753 } // end of the 'PMA_linkOrButton()' function
1757 * Returns a given timespan value in a readable format.
1759 * @uses $GLOBALS['timespanfmt']
1760 * @uses sprintf()
1761 * @uses floor()
1762 * @param int the timespan
1764 * @return string the formatted value
1766 function PMA_timespanFormat($seconds)
1768 $return_string = '';
1769 $days = floor($seconds / 86400);
1770 if ($days > 0) {
1771 $seconds -= $days * 86400;
1773 $hours = floor($seconds / 3600);
1774 if ($days > 0 || $hours > 0) {
1775 $seconds -= $hours * 3600;
1777 $minutes = floor($seconds / 60);
1778 if ($days > 0 || $hours > 0 || $minutes > 0) {
1779 $seconds -= $minutes * 60;
1781 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1785 * Takes a string and outputs each character on a line for itself. Used
1786 * mainly for horizontalflipped display mode.
1787 * Takes care of special html-characters.
1788 * Fulfills todo-item
1789 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1791 * @todo add a multibyte safe function PMA_STR_split()
1792 * @uses strlen
1793 * @param string The string
1794 * @param string The Separator (defaults to "<br />\n")
1796 * @access public
1797 * @author Garvin Hicking <me@supergarv.de>
1798 * @return string The flipped string
1800 function PMA_flipstring($string, $Separator = "<br />\n")
1802 $format_string = '';
1803 $charbuff = false;
1805 for ($i = 0; $i < strlen($string); $i++) {
1806 $char = $string{$i};
1807 $append = false;
1809 if ($char == '&') {
1810 $format_string .= $charbuff;
1811 $charbuff = $char;
1812 $append = true;
1813 } elseif (!empty($charbuff)) {
1814 $charbuff .= $char;
1815 } elseif ($char == ';' && !empty($charbuff)) {
1816 $format_string .= $charbuff;
1817 $charbuff = false;
1818 $append = true;
1819 } else {
1820 $format_string .= $char;
1821 $append = true;
1824 if ($append && ($i != strlen($string))) {
1825 $format_string .= $Separator;
1829 return $format_string;
1834 * Function added to avoid path disclosures.
1835 * Called by each script that needs parameters, it displays
1836 * an error message and, by default, stops the execution.
1838 * Not sure we could use a strMissingParameter message here,
1839 * would have to check if the error message file is always available
1841 * @todo localize error message
1842 * @todo use PMA_fatalError() if $die === true?
1843 * @uses PMA_getenv()
1844 * @uses header_meta_style.inc.php
1845 * basename
1846 * @param array The names of the parameters needed by the calling
1847 * script.
1848 * @param boolean Stop the execution?
1849 * (Set this manually to false in the calling script
1850 * until you know all needed parameters to check).
1851 * @param boolean Whether to include this list in checking for special params.
1852 * @global string path to current script
1853 * @global boolean flag whether any special variable was required
1855 * @access public
1856 * @author Marc Delisle (lem9@users.sourceforge.net)
1858 function PMA_checkParameters($params, $die = true, $request = true)
1860 global $checked_special;
1862 if (!isset($checked_special)) {
1863 $checked_special = false;
1866 $reported_script_name = basename(PMA_getenv('PHP_SELF'));
1867 $found_error = false;
1868 $error_message = '';
1870 foreach ($params as $param) {
1871 if ($request && $param != 'db' && $param != 'table') {
1872 $checked_special = true;
1875 if (!isset($GLOBALS[$param])) {
1876 $error_message .= $reported_script_name
1877 . ': Missing parameter: ' . $param
1878 . ' <a href="./Documentation.html#faqmissingparameters"'
1879 . ' target="documentation"> (FAQ 2.8)</a><br />';
1880 $found_error = true;
1883 if ($found_error) {
1885 * display html meta tags
1887 require_once './libraries/header_meta_style.inc.php';
1888 echo '</head><body><p>' . $error_message . '</p></body></html>';
1889 if ($die) {
1890 exit();
1893 } // end function
1896 * Function to generate unique condition for specified row.
1898 * @uses PMA_MYSQL_INT_VERSION
1899 * @uses $GLOBALS['analyzed_sql'][0]
1900 * @uses PMA_DBI_field_flags()
1901 * @uses PMA_backquote()
1902 * @uses PMA_sqlAddslashes()
1903 * @uses stristr()
1904 * @uses bin2hex()
1905 * @uses preg_replace()
1906 * @param resource $handle current query result
1907 * @param integer $fields_cnt number of fields
1908 * @param array $fields_meta meta information about fields
1909 * @param array $row current row
1910 * @param boolean $force_unique generate condition only on pk or unique
1912 * @access public
1913 * @author Michal Cihar (michal@cihar.com) and others...
1914 * @return string calculated condition
1916 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1918 $primary_key = '';
1919 $unique_key = '';
1920 $nonprimary_condition = '';
1921 $preferred_condition = '';
1923 for ($i = 0; $i < $fields_cnt; ++$i) {
1924 $condition = '';
1925 $field_flags = PMA_DBI_field_flags($handle, $i);
1926 $meta = $fields_meta[$i];
1928 // do not use a column alias in a condition
1929 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1930 $meta->orgname = $meta->name;
1932 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1933 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1934 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1935 as $select_expr) {
1936 // need (string) === (string)
1937 // '' !== 0 but '' == 0
1938 if ((string) $select_expr['alias'] === (string) $meta->name) {
1939 $meta->orgname = $select_expr['column'];
1940 break;
1941 } // end if
1942 } // end foreach
1946 // Do not use a table alias in a condition.
1947 // Test case is:
1948 // select * from galerie x WHERE
1949 //(select count(*) from galerie y where y.datum=x.datum)>1
1951 // But orgtable is present only with mysqli extension so the
1952 // fix is only for mysqli.
1953 if (isset($meta->orgtable) && $meta->table != $meta->orgtable) {
1954 $meta->table = $meta->orgtable;
1957 // to fix the bug where float fields (primary or not)
1958 // can't be matched because of the imprecision of
1959 // floating comparison, use CONCAT
1960 // (also, the syntax "CONCAT(field) IS NULL"
1961 // that we need on the next "if" will work)
1962 if ($meta->type == 'real') {
1963 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1964 . PMA_backquote($meta->orgname) . ') ';
1965 } else {
1966 // string and blob fields have to be converted using
1967 // the system character set (always utf8) since
1968 // mysql4.1 can use different charset for fields.
1969 if (PMA_MYSQL_INT_VERSION >= 40100
1970 && ($meta->type == 'string' || $meta->type == 'blob')) {
1971 $condition = ' CONVERT(' . PMA_backquote($meta->table) . '.'
1972 . PMA_backquote($meta->orgname) . ' USING utf8) ';
1973 } else {
1974 $condition = ' ' . PMA_backquote($meta->table) . '.'
1975 . PMA_backquote($meta->orgname) . ' ';
1977 } // end if... else...
1979 if (!isset($row[$i]) || is_null($row[$i])) {
1980 $condition .= 'IS NULL AND';
1981 } else {
1982 // timestamp is numeric on some MySQL 4.1
1983 if ($meta->numeric && $meta->type != 'timestamp') {
1984 $condition .= '= ' . $row[$i] . ' AND';
1985 } elseif ($meta->type == 'blob'
1986 // hexify only if this is a true not empty BLOB
1987 && stristr($field_flags, 'BINARY')
1988 && !empty($row[$i])) {
1989 // do not waste memory building a too big condition
1990 if (strlen($row[$i]) < 1000) {
1991 if (PMA_MYSQL_INT_VERSION < 40002) {
1992 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
1993 } else {
1994 // use a CAST if possible, to avoid problems
1995 // if the field contains wildcard characters % or _
1996 $condition .= '= CAST(0x' . bin2hex($row[$i])
1997 . ' AS BINARY) AND';
1999 } else {
2000 // this blob won't be part of the final condition
2001 $condition = '';
2003 } else {
2004 $condition .= '= \''
2005 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2008 if ($meta->primary_key > 0) {
2009 $primary_key .= $condition;
2010 } elseif ($meta->unique_key > 0) {
2011 $unique_key .= $condition;
2013 $nonprimary_condition .= $condition;
2014 } // end for
2016 // Correction University of Virginia 19991216:
2017 // prefer primary or unique keys for condition,
2018 // but use conjunction of all values if no primary key
2019 if ($primary_key) {
2020 $preferred_condition = $primary_key;
2021 } elseif ($unique_key) {
2022 $preferred_condition = $unique_key;
2023 } elseif (! $force_unique) {
2024 $preferred_condition = $nonprimary_condition;
2027 return preg_replace('|\s?AND$|', '', $preferred_condition);
2028 } // end function
2031 * Generate a button or image tag
2033 * @uses PMA_USR_BROWSER_AGENT
2034 * @uses $GLOBALS['pmaThemeImage']
2035 * @uses $GLOBALS['cfg']['PropertiesIconic']
2036 * @param string name of button element
2037 * @param string class of button element
2038 * @param string name of image element
2039 * @param string text to display
2040 * @param string image to display
2042 * @access public
2043 * @author Michal Cihar (michal@cihar.com)
2045 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2046 $image)
2048 /* Opera has trouble with <input type="image"> */
2049 /* IE has trouble with <button> */
2050 if (PMA_USR_BROWSER_AGENT != 'IE') {
2051 echo '<button class="' . $button_class . '" type="submit"'
2052 .' name="' . $button_name . '" value="' . $text . '"'
2053 .' title="' . $text . '">' . "\n"
2054 .'<img class="icon" src="' . $GLOBALS['pmaThemeImage'] . $image . '"'
2055 .' title="' . $text . '" alt="' . $text . '" width="16"'
2056 .' height="16" />'
2057 .($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n"
2058 .'</button>' . "\n";
2059 } else {
2060 echo '<input type="image" name="' . $image_name . '" value="'
2061 . $text . '" title="' . $text . '" src="' . $GLOBALS['pmaThemeImage']
2062 . $image . '" />'
2063 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n";
2065 } // end function
2068 * Generate a pagination selector for browsing resultsets
2070 * @uses $GLOBALS['strPageNumber']
2071 * @uses range()
2072 * @param string URL for the JavaScript
2073 * @param string Number of rows in the pagination set
2074 * @param string current page number
2075 * @param string number of total pages
2076 * @param string If the number of pages is lower than this
2077 * variable, no pages will be ommitted in
2078 * pagination
2079 * @param string How many rows at the beginning should always
2080 * be shown?
2081 * @param string How many rows at the end should always
2082 * be shown?
2083 * @param string Percentage of calculation page offsets to
2084 * hop to a next page
2085 * @param string Near the current page, how many pages should
2086 * be considered "nearby" and displayed as
2087 * well?
2088 * @param string The prompt to display (sometimes empty)
2090 * @access public
2091 * @author Garvin Hicking (pma@supergarv.de)
2093 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2094 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2095 $range = 10, $prompt = '')
2097 $gotopage = $prompt
2098 . ' <select name="goToPage" onchange="goToUrl(this, \''
2099 . $url . '\');">' . "\n";
2100 if ($nbTotalPage < $showAll) {
2101 $pages = range(1, $nbTotalPage);
2102 } else {
2103 $pages = array();
2105 // Always show first X pages
2106 for ($i = 1; $i <= $sliceStart; $i++) {
2107 $pages[] = $i;
2110 // Always show last X pages
2111 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2112 $pages[] = $i;
2115 // garvin: Based on the number of results we add the specified
2116 // $percent percentate to each page number,
2117 // so that we have a representing page number every now and then to
2118 // immideately jump to specific pages.
2119 // As soon as we get near our currently chosen page ($pageNow -
2120 // $range), every page number will be
2121 // shown.
2122 $i = $sliceStart;
2123 $x = $nbTotalPage - $sliceEnd;
2124 $met_boundary = false;
2125 while ($i <= $x) {
2126 if ($i >= ($pageNow - $range) && $i <= ($pageNow + $range)) {
2127 // If our pageselector comes near the current page, we use 1
2128 // counter increments
2129 $i++;
2130 $met_boundary = true;
2131 } else {
2132 // We add the percentate increment to our current page to
2133 // hop to the next one in range
2134 $i = $i + floor($nbTotalPage / $percent);
2136 // Make sure that we do not cross our boundaries.
2137 if ($i > ($pageNow - $range) && !$met_boundary) {
2138 $i = $pageNow - $range;
2142 if ($i > 0 && $i <= $x) {
2143 $pages[] = $i;
2147 // Since because of ellipsing of the current page some numbers may be double,
2148 // we unify our array:
2149 sort($pages);
2150 $pages = array_unique($pages);
2153 foreach ($pages as $i) {
2154 if ($i == $pageNow) {
2155 $selected = 'selected="selected" style="font-weight: bold"';
2156 } else {
2157 $selected = '';
2159 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2162 $gotopage .= ' </select>';
2164 return $gotopage;
2165 } // end function
2169 * Generate navigation for a list
2171 * @todo use $pos from $_url_params
2172 * @uses $GLOBALS['strPageNumber']
2173 * @uses range()
2174 * @param integer number of elements in the list
2175 * @param integer current position in the list
2176 * @param array url parameters
2177 * @param string script name for form target
2178 * @param string target frame
2179 * @param integer maximum number of elements to display from the list
2181 * @access public
2183 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2185 if ($max_count < $count) {
2186 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2187 echo $GLOBALS['strPageNumber'];
2188 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2190 // Move to the beginning or to the previous page
2191 if ($pos > 0) {
2192 // loic1: patch #474210 from Gosha Sakovich - part 1
2193 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2194 $caption1 = '&lt;&lt;';
2195 $caption2 = ' &lt; ';
2196 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2197 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2198 } else {
2199 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2200 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2201 $title1 = '';
2202 $title2 = '';
2203 } // end if... else...
2204 $_url_params['pos'] = 0;
2205 echo '<a' . $title1 . ' href="' . $script
2206 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2207 . $caption1 . '</a>';
2208 $_url_params['pos'] = $pos - $max_count;
2209 echo '<a' . $title2 . ' href="' . $script
2210 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2211 . $caption2 . '</a>';
2214 echo '<form action="./' . $script . '" method="post">' . "\n";
2215 echo PMA_generate_common_hidden_inputs($_url_params);
2216 echo PMA_pageselector(
2217 $script . PMA_generate_common_url($_url_params) . '&',
2218 $max_count,
2219 floor(($pos + 1) / $max_count) + 1,
2220 ceil($count / $max_count));
2221 echo '</form>';
2223 if ($pos + $max_count < $count) {
2224 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2225 $caption3 = ' &gt; ';
2226 $caption4 = '&gt;&gt;';
2227 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2228 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2229 } else {
2230 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2231 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2232 $title3 = '';
2233 $title4 = '';
2234 } // end if... else...
2235 $_url_params['pos'] = $pos + $max_count;
2236 echo '<a' . $title3 . ' href="' . $script
2237 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2238 . $caption3 . '</a>';
2239 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2240 echo '<a' . $title4 . ' href="' . $script
2241 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2242 . $caption4 . '</a>';
2244 echo "\n";
2245 if ('frame_navigation' == $frame) {
2246 echo '</div>' . "\n";
2252 * replaces %u in given path with current user name
2254 * example:
2255 * <code>
2256 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2258 * </code>
2259 * @uses $cfg['Server']['user']
2260 * @uses substr()
2261 * @uses str_replace()
2262 * @param string $dir with wildcard for user
2263 * @return string per user directory
2265 function PMA_userDir($dir)
2267 // add trailing slash
2268 if (substr($dir, -1) != '/') {
2269 $dir .= '/';
2272 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2276 * returns html code for db link to default db page
2278 * @uses $cfg['DefaultTabDatabase']
2279 * @uses $GLOBALS['db']
2280 * @uses $GLOBALS['strJumpToDB']
2281 * @uses PMA_generate_common_url()
2282 * @uses PMA_unescape_mysql_wildcards()
2283 * @uses strlen()
2284 * @uses sprintf()
2285 * @uses htmlspecialchars()
2286 * @param string $database
2287 * @return string html link to default db page
2289 function PMA_getDbLink($database = null)
2291 if (!strlen($database)) {
2292 if (!strlen($GLOBALS['db'])) {
2293 return '';
2295 $database = $GLOBALS['db'];
2296 } else {
2297 $database = PMA_unescape_mysql_wildcards($database);
2300 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2301 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2302 .htmlspecialchars($database) . '</a>';
2306 * Displays a lightbulb hint explaining a known external bug
2307 * that affects a functionality
2309 * @uses PMA_MYSQL_INT_VERSION
2310 * @uses $GLOBALS['strKnownExternalBug']
2311 * @uses PMA_showHint()
2312 * @uses sprintf()
2313 * @param string $functionality localized message explaining the func.
2314 * @param string $component 'mysql' (eventually, 'php')
2315 * @param string $minimum_version of this component
2316 * @param string $bugref bug reference for this component
2318 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2320 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2321 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));