3.3.1 release
[phpmyadmin/crack.git] / libraries / common.lib.php
blob522a2242b4e2c45a2409ad19b025964d116d8821
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 * @package phpMyAdmin
8 */
10 /**
11 * Exponential expression / raise number into power
13 * @uses function_exists()
14 * @uses bcpow()
15 * @uses gmp_pow()
16 * @uses gmp_strval()
17 * @uses pow()
18 * @param number $base
19 * @param number $exp
20 * @param string pow function use, or false for auto-detect
21 * @return mixed string or float
23 function PMA_pow($base, $exp, $use_function = false)
25 static $pow_function = null;
27 if (null == $pow_function) {
28 if (function_exists('bcpow')) {
29 // BCMath Arbitrary Precision Mathematics Function
30 $pow_function = 'bcpow';
31 } elseif (function_exists('gmp_pow')) {
32 // GMP Function
33 $pow_function = 'gmp_pow';
34 } else {
35 // PHP function
36 $pow_function = 'pow';
40 if (! $use_function) {
41 $use_function = $pow_function;
44 if ($exp < 0 && 'pow' != $use_function) {
45 return false;
47 switch ($use_function) {
48 case 'bcpow' :
49 // bcscale() needed for testing PMA_pow() with base values < 1
50 bcscale(10);
51 $pow = bcpow($base, $exp);
52 break;
53 case 'gmp_pow' :
54 $pow = gmp_strval(gmp_pow($base, $exp));
55 break;
56 case 'pow' :
57 $base = (float) $base;
58 $exp = (int) $exp;
59 $pow = pow($base, $exp);
60 break;
61 default:
62 $pow = $use_function($base, $exp);
65 return $pow;
68 /**
69 * string PMA_getIcon(string $icon)
71 * @uses $GLOBALS['pmaThemeImage']
72 * @uses $GLOBALS['cfg']['PropertiesIconic']
73 * @uses htmlspecialchars()
74 * @param string $icon name of icon file
75 * @param string $alternate alternate text
76 * @param boolean $container include in container
77 * @param boolean $$force_text whether to force alternate text to be displayed
78 * @return html img tag
80 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
82 $include_icon = false;
83 $include_text = false;
84 $include_box = false;
85 $alternate = htmlspecialchars($alternate);
86 $button = '';
88 if ($GLOBALS['cfg']['PropertiesIconic']) {
89 $include_icon = true;
92 if ($force_text
93 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
94 || ! $include_icon) {
95 // $cfg['PropertiesIconic'] is false or both
96 // OR we have no $include_icon
97 $include_text = true;
100 if ($include_text && $include_icon && $container) {
101 // we have icon, text and request for container
102 $include_box = true;
105 if ($include_box) {
106 $button .= '<div class="nowrap">';
109 if ($include_icon) {
110 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
111 . ' title="' . $alternate . '" alt="' . $alternate . '"'
112 . ' class="icon" width="16" height="16" />';
115 if ($include_icon && $include_text) {
116 $button .= ' ';
119 if ($include_text) {
120 $button .= $alternate;
123 if ($include_box) {
124 $button .= '</div>';
127 return $button;
131 * Displays the maximum size for an upload
133 * @uses $GLOBALS['strMaximumSize']
134 * @uses PMA_formatByteDown()
135 * @uses sprintf()
136 * @param integer the size
138 * @return string the message
140 * @access public
142 function PMA_displayMaximumUploadSize($max_upload_size)
144 // I have to reduce the second parameter (sensitiveness) from 6 to 4
145 // to avoid weird results like 512 kKib
146 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
147 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
151 * Generates a hidden field which should indicate to the browser
152 * the maximum size for upload
154 * @param integer the size
156 * @return string the INPUT field
158 * @access public
160 function PMA_generateHiddenMaxFileSize($max_size)
162 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
166 * Add slashes before "'" and "\" characters so a value containing them can
167 * be used in a sql comparison.
169 * @uses str_replace()
170 * @param string the string to slash
171 * @param boolean whether the string will be used in a 'LIKE' clause
172 * (it then requires two more escaped sequences) or not
173 * @param boolean whether to treat cr/lfs as escape-worthy entities
174 * (converts \n to \\n, \r to \\r)
176 * @param boolean whether this function is used as part of the
177 * "Create PHP code" dialog
179 * @return string the slashed string
181 * @access public
183 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
185 if ($is_like) {
186 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
187 } else {
188 $a_string = str_replace('\\', '\\\\', $a_string);
191 if ($crlf) {
192 $a_string = str_replace("\n", '\n', $a_string);
193 $a_string = str_replace("\r", '\r', $a_string);
194 $a_string = str_replace("\t", '\t', $a_string);
197 if ($php_code) {
198 $a_string = str_replace('\'', '\\\'', $a_string);
199 } else {
200 $a_string = str_replace('\'', '\'\'', $a_string);
203 return $a_string;
204 } // end of the 'PMA_sqlAddslashes()' function
208 * Add slashes before "_" and "%" characters for using them in MySQL
209 * database, table and field names.
210 * Note: This function does not escape backslashes!
212 * @uses str_replace()
213 * @param string the string to escape
215 * @return string the escaped string
217 * @access public
219 function PMA_escape_mysql_wildcards($name)
221 $name = str_replace('_', '\\_', $name);
222 $name = str_replace('%', '\\%', $name);
224 return $name;
225 } // end of the 'PMA_escape_mysql_wildcards()' function
228 * removes slashes before "_" and "%" characters
229 * Note: This function does not unescape backslashes!
231 * @uses str_replace()
232 * @param string $name the string to escape
233 * @return string the escaped string
234 * @access public
236 function PMA_unescape_mysql_wildcards($name)
238 $name = str_replace('\\_', '_', $name);
239 $name = str_replace('\\%', '%', $name);
241 return $name;
242 } // end of the 'PMA_unescape_mysql_wildcards()' function
245 * removes quotes (',",`) from a quoted string
247 * checks if the sting is quoted and removes this quotes
249 * @uses str_replace()
250 * @uses substr()
251 * @param string $quoted_string string to remove quotes from
252 * @param string $quote type of quote to remove
253 * @return string unqoted string
255 function PMA_unQuote($quoted_string, $quote = null)
257 $quotes = array();
259 if (null === $quote) {
260 $quotes[] = '`';
261 $quotes[] = '"';
262 $quotes[] = "'";
263 } else {
264 $quotes[] = $quote;
267 foreach ($quotes as $quote) {
268 if (substr($quoted_string, 0, 1) === $quote
269 && substr($quoted_string, -1, 1) === $quote) {
270 $unquoted_string = substr($quoted_string, 1, -1);
271 // replace escaped quotes
272 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
273 return $unquoted_string;
277 return $quoted_string;
281 * format sql strings
283 * @todo move into PMA_Sql
284 * @uses PMA_SQP_isError()
285 * @uses PMA_SQP_formatHtml()
286 * @uses PMA_SQP_formatNone()
287 * @uses is_array()
288 * @param mixed pre-parsed SQL structure
290 * @return string the formatted sql
292 * @global array the configuration array
293 * @global boolean whether the current statement is a multiple one or not
295 * @access public
297 * @author Robin Johnson <robbat2@users.sourceforge.net>
299 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
301 global $cfg;
303 // Check that we actually have a valid set of parsed data
304 // well, not quite
305 // first check for the SQL parser having hit an error
306 if (PMA_SQP_isError()) {
307 return htmlspecialchars($parsed_sql['raw']);
309 // then check for an array
310 if (!is_array($parsed_sql)) {
311 // We don't so just return the input directly
312 // This is intended to be used for when the SQL Parser is turned off
313 $formatted_sql = '<pre>' . "\n"
314 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
315 . '</pre>';
316 return $formatted_sql;
319 $formatted_sql = '';
321 switch ($cfg['SQP']['fmtType']) {
322 case 'none':
323 if ($unparsed_sql != '') {
324 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
325 } else {
326 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
328 break;
329 case 'html':
330 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
331 break;
332 case 'text':
333 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
334 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
335 break;
336 default:
337 break;
338 } // end switch
340 return $formatted_sql;
341 } // end of the "PMA_formatSql()" function
345 * Displays a link to the official MySQL documentation
347 * @uses $cfg['MySQLManualType']
348 * @uses $cfg['MySQLManualBase']
349 * @uses $cfg['ReplaceHelpImg']
350 * @uses $GLOBALS['mysql_4_1_doc_lang']
351 * @uses $GLOBALS['mysql_5_1_doc_lang']
352 * @uses $GLOBALS['mysql_5_0_doc_lang']
353 * @uses $GLOBALS['strDocu']
354 * @uses $GLOBALS['pmaThemeImage']
355 * @uses PMA_MYSQL_INT_VERSION
356 * @uses strtolower()
357 * @uses str_replace()
358 * @param string chapter of "HTML, one page per chapter" documentation
359 * @param string contains name of page/anchor that is being linked
360 * @param bool whether to use big icon (like in left frame)
361 * @param string anchor to page part
363 * @return string the html link
365 * @access public
367 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '')
369 global $cfg;
371 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
372 return '';
375 // Fixup for newly used names:
376 $chapter = str_replace('_', '-', strtolower($chapter));
377 $link = str_replace('_', '-', strtolower($link));
379 switch ($cfg['MySQLManualType']) {
380 case 'chapters':
381 if (empty($chapter)) {
382 $chapter = 'index';
384 if (empty($anchor)) {
385 $anchor = $link;
387 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
388 break;
389 case 'big':
390 if (empty($anchor)) {
391 $anchor = $link;
393 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
394 break;
395 case 'searchable':
396 if (empty($link)) {
397 $link = 'index';
399 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
400 if (!empty($anchor)) {
401 $url .= '#' . $anchor;
403 break;
404 case 'viewable':
405 default:
406 if (empty($link)) {
407 $link = 'index';
409 $mysql = '5.0';
410 $lang = 'en';
411 if (defined('PMA_MYSQL_INT_VERSION')) {
412 if (PMA_MYSQL_INT_VERSION >= 50100) {
413 $mysql = '5.1';
414 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
415 $lang = $GLOBALS['mysql_5_1_doc_lang'];
417 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
418 $mysql = '5.0';
419 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
420 $lang = $GLOBALS['mysql_5_0_doc_lang'];
424 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
425 if (!empty($anchor)) {
426 $url .= '#' . $anchor;
428 break;
431 if ($big_icon) {
432 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
433 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
434 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
435 } else {
436 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
438 } // end of the 'PMA_showMySQLDocu()' function
442 * Displays a link to the phpMyAdmin documentation
444 * @param string anchor in documentation
446 * @return string the html link
448 * @access public
450 function PMA_showDocu($anchor) {
451 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
452 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
453 } else {
454 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . $GLOBALS['strDocu'] . '</a>]';
456 } // end of the 'PMA_showDocu()' function
459 * returns HTML for a footnote marker and add the messsage to the footnotes
461 * @uses $GLOBALS['footnotes']
462 * @param string the error message
463 * @return string html code for a footnote marker
464 * @access public
466 function PMA_showHint($message, $bbcode = false, $type = 'notice')
468 if ($message instanceof PMA_Message) {
469 $key = $message->getHash();
470 $type = $message->getLevel();
471 } else {
472 $key = md5($message);
475 if (! isset($GLOBALS['footnotes'][$key])) {
476 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
477 $GLOBALS['footnotes'] = array();
479 $nr = count($GLOBALS['footnotes']) + 1;
480 // this is the first instance of this message
481 $instance = 1;
482 $GLOBALS['footnotes'][$key] = array(
483 'note' => $message,
484 'type' => $type,
485 'nr' => $nr,
486 'instance' => $instance
488 } else {
489 $nr = $GLOBALS['footnotes'][$key]['nr'];
490 // another instance of this message (to ensure ids are unique)
491 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
494 if ($bbcode) {
495 return '[sup]' . $nr . '[/sup]';
498 // footnotemarker used in js/tooltip.js
499 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
503 * Displays a MySQL error message in the right frame.
505 * @uses footer.inc.php
506 * @uses header.inc.php
507 * @uses $GLOBALS['sql_query']
508 * @uses $GLOBALS['strError']
509 * @uses $GLOBALS['strSQLQuery']
510 * @uses $GLOBALS['pmaThemeImage']
511 * @uses $GLOBALS['strEdit']
512 * @uses $GLOBALS['strMySQLSaid']
513 * @uses $GLOBALS['cfg']['PropertiesIconic']
514 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
515 * @uses PMA_backquote()
516 * @uses PMA_DBI_getError()
517 * @uses PMA_formatSql()
518 * @uses PMA_generate_common_hidden_inputs()
519 * @uses PMA_generate_common_url()
520 * @uses PMA_showMySQLDocu()
521 * @uses PMA_sqlAddslashes()
522 * @uses PMA_SQP_isError()
523 * @uses PMA_SQP_parse()
524 * @uses PMA_SQP_getErrorString()
525 * @uses strtolower()
526 * @uses urlencode()
527 * @uses str_replace()
528 * @uses nl2br()
529 * @uses substr()
530 * @uses preg_replace()
531 * @uses preg_match()
532 * @uses explode()
533 * @uses implode()
534 * @uses is_array()
535 * @uses function_exists()
536 * @uses htmlspecialchars()
537 * @uses trim()
538 * @uses strstr()
539 * @param string the error message
540 * @param string the sql query that failed
541 * @param boolean whether to show a "modify" link or not
542 * @param string the "back" link url (full path is not required)
543 * @param boolean EXIT the page?
545 * @global string the curent table
546 * @global string the current db
548 * @access public
550 function PMA_mysqlDie($error_message = '', $the_query = '',
551 $is_modify_link = true, $back_url = '', $exit = true)
553 global $table, $db;
556 * start http output, display html headers
558 require_once './libraries/header.inc.php';
560 $error_msg_output = '';
562 if (!$error_message) {
563 $error_message = PMA_DBI_getError();
565 if (!$the_query && !empty($GLOBALS['sql_query'])) {
566 $the_query = $GLOBALS['sql_query'];
569 // --- Added to solve bug #641765
570 // Robbat2 - 12 January 2003, 9:46PM
571 // Revised, Robbat2 - 13 January 2003, 2:59PM
572 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
573 $formatted_sql = htmlspecialchars($the_query);
574 } elseif (empty($the_query) || trim($the_query) == '') {
575 $formatted_sql = '';
576 } else {
577 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
578 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
579 } else {
580 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
583 // ---
584 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
585 $error_msg_output .= ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
586 // if the config password is wrong, or the MySQL server does not
587 // respond, do not show the query that would reveal the
588 // username/password
589 if (!empty($the_query) && !strstr($the_query, 'connect')) {
590 // --- Added to solve bug #641765
591 // Robbat2 - 12 January 2003, 9:46PM
592 // Revised, Robbat2 - 13 January 2003, 2:59PM
593 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
594 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
595 $error_msg_output .= '<br />' . "\n";
597 // ---
598 // modified to show me the help on sql errors (Michael Keck)
599 $error_msg_output .= ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
600 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
601 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
603 if ($is_modify_link) {
604 $_url_params = array(
605 'sql_query' => $the_query,
606 'show_query' => 1,
608 if (strlen($table)) {
609 $_url_params['db'] = $db;
610 $_url_params['table'] = $table;
611 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
612 } elseif (strlen($db)) {
613 $_url_params['db'] = $db;
614 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
615 } else {
616 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
619 $error_msg_output .= $doedit_goto
620 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
621 . '</a>';
622 } // end if
623 $error_msg_output .= ' </p>' . "\n"
624 .' <p>' . "\n"
625 .' ' . $formatted_sql . "\n"
626 .' </p>' . "\n";
627 } // end if
629 $tmp_mysql_error = ''; // for saving the original $error_message
630 if (!empty($error_message)) {
631 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
632 $error_message = htmlspecialchars($error_message);
633 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
635 // modified to show me the help on error-returns (Michael Keck)
636 // (now error-messages-server)
637 $error_msg_output .= '<p>' . "\n"
638 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
639 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
640 . "\n"
641 . '</p>' . "\n";
643 // The error message will be displayed within a CODE segment.
644 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
646 // Replace all non-single blanks with their HTML-counterpart
647 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
648 // Replace TAB-characters with their HTML-counterpart
649 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
650 // Replace linebreaks
651 $error_message = nl2br($error_message);
653 $error_msg_output .= '<code>' . "\n"
654 . $error_message . "\n"
655 . '</code><br />' . "\n";
656 $error_msg_output .= '</div>';
658 $_SESSION['Import_message']['message'] = $error_msg_output;
660 if ($exit) {
661 if (! empty($back_url)) {
662 if (strstr($back_url, '?')) {
663 $back_url .= '&amp;no_history=true';
664 } else {
665 $back_url .= '?no_history=true';
668 $_SESSION['Import_message']['go_back_url'] = $back_url;
670 $error_msg_output .= '<fieldset class="tblFooters">';
671 $error_msg_output .= '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
672 $error_msg_output .= '</fieldset>' . "\n\n";
675 echo $error_msg_output;
677 * display footer and exit
680 require_once './libraries/footer.inc.php';
681 } else {
682 echo $error_msg_output;
684 } // end of the 'PMA_mysqlDie()' function
687 * Send HTTP header, taking IIS limits into account (600 seems ok)
689 * @uses PMA_IS_IIS
690 * @uses PMA_COMING_FROM_COOKIE_LOGIN
691 * @uses PMA_get_arg_separator()
692 * @uses SID
693 * @uses strlen()
694 * @uses strpos()
695 * @uses header()
696 * @uses session_write_close()
697 * @uses headers_sent()
698 * @uses function_exists()
699 * @uses debug_print_backtrace()
700 * @uses trigger_error()
701 * @uses defined()
702 * @param string $uri the header to send
703 * @return boolean always true
705 function PMA_sendHeaderLocation($uri)
707 if (PMA_IS_IIS && strlen($uri) > 600) {
709 echo '<html><head><title>- - -</title>' . "\n";
710 echo '<meta http-equiv="expires" content="0">' . "\n";
711 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
712 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
713 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
714 echo '<script type="text/javascript">' . "\n";
715 echo '//<![CDATA[' . "\n";
716 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
717 echo '//]]>' . "\n";
718 echo '</script>' . "\n";
719 echo '</head>' . "\n";
720 echo '<body>' . "\n";
721 echo '<script type="text/javascript">' . "\n";
722 echo '//<![CDATA[' . "\n";
723 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
724 echo '//]]>' . "\n";
725 echo '</script></body></html>' . "\n";
727 } else {
728 if (SID) {
729 if (strpos($uri, '?') === false) {
730 header('Location: ' . $uri . '?' . SID);
731 } else {
732 $separator = PMA_get_arg_separator();
733 header('Location: ' . $uri . $separator . SID);
735 } else {
736 session_write_close();
737 if (headers_sent()) {
738 if (function_exists('debug_print_backtrace')) {
739 echo '<pre>';
740 debug_print_backtrace();
741 echo '</pre>';
743 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
745 // bug #1523784: IE6 does not like 'Refresh: 0', it
746 // results in a blank page
747 // but we need it when coming from the cookie login panel)
748 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
749 header('Refresh: 0; ' . $uri);
750 } else {
751 header('Location: ' . $uri);
758 * returns array with tables of given db with extended information and grouped
760 * @uses $cfg['LeftFrameTableSeparator']
761 * @uses $cfg['LeftFrameTableLevel']
762 * @uses $cfg['ShowTooltipAliasTB']
763 * @uses $cfg['NaturalOrder']
764 * @uses PMA_backquote()
765 * @uses count()
766 * @uses array_merge
767 * @uses uksort()
768 * @uses strstr()
769 * @uses explode()
770 * @param string $db name of db
771 * @param string $tables name of tables
772 * @param integer $limit_offset list offset
773 * @param integer $limit_count max tables to return
774 * return array (recursive) grouped table list
776 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
778 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
780 if (null === $tables) {
781 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
782 if ($GLOBALS['cfg']['NaturalOrder']) {
783 uksort($tables, 'strnatcasecmp');
787 if (count($tables) < 1) {
788 return $tables;
791 $default = array(
792 'Name' => '',
793 'Rows' => 0,
794 'Comment' => '',
795 'disp_name' => '',
798 $table_groups = array();
800 // for blobstreaming - list of blobstreaming tables - rajk
802 // load PMA configuration
803 $PMA_Config = $_SESSION['PMA_Config'];
805 // if PMA configuration exists
806 if (!empty($PMA_Config))
807 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
809 foreach ($tables as $table_name => $table) {
810 // if BS tables exist
811 if (isset($session_bs_tables))
812 // compare table name to tables in list of blobstreaming tables
813 foreach ($session_bs_tables as $table_key=>$table_val)
814 // if table is in list, skip outer foreach loop
815 if ($table_name == $table_key)
816 continue 2;
818 // check for correct row count
819 if (null === $table['Rows']) {
820 // Do not check exact row count here,
821 // if row count is invalid possibly the table is defect
822 // and this would break left frame;
823 // but we can check row count if this is a view or the
824 // information_schema database
825 // since PMA_Table::countRecords() returns a limited row count
826 // in this case.
828 // set this because PMA_Table::countRecords() can use it
829 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
831 if ($tbl_is_view || 'information_schema' == $db) {
832 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
836 // in $group we save the reference to the place in $table_groups
837 // where to store the table info
838 if ($GLOBALS['cfg']['LeftFrameDBTree']
839 && $sep && strstr($table_name, $sep))
841 $parts = explode($sep, $table_name);
843 $group =& $table_groups;
844 $i = 0;
845 $group_name_full = '';
846 $parts_cnt = count($parts) - 1;
847 while ($i < $parts_cnt
848 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
849 $group_name = $parts[$i] . $sep;
850 $group_name_full .= $group_name;
852 if (!isset($group[$group_name])) {
853 $group[$group_name] = array();
854 $group[$group_name]['is' . $sep . 'group'] = true;
855 $group[$group_name]['tab' . $sep . 'count'] = 1;
856 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
857 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
858 $table = $group[$group_name];
859 $group[$group_name] = array();
860 $group[$group_name][$group_name] = $table;
861 unset($table);
862 $group[$group_name]['is' . $sep . 'group'] = true;
863 $group[$group_name]['tab' . $sep . 'count'] = 1;
864 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
865 } else {
866 $group[$group_name]['tab' . $sep . 'count']++;
868 $group =& $group[$group_name];
869 $i++;
871 } else {
872 if (!isset($table_groups[$table_name])) {
873 $table_groups[$table_name] = array();
875 $group =& $table_groups;
879 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
880 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
881 // switch tooltip and name
882 $table['Comment'] = $table['Name'];
883 $table['disp_name'] = $table['Comment'];
884 } else {
885 $table['disp_name'] = $table['Name'];
888 $group[$table_name] = array_merge($default, $table);
891 return $table_groups;
894 /* ----------------------- Set of misc functions ----------------------- */
898 * Adds backquotes on both sides of a database, table or field name.
899 * and escapes backquotes inside the name with another backquote
901 * example:
902 * <code>
903 * echo PMA_backquote('owner`s db'); // `owner``s db`
905 * </code>
907 * @uses PMA_backquote()
908 * @uses is_array()
909 * @uses strlen()
910 * @uses str_replace()
911 * @param mixed $a_name the database, table or field name to "backquote"
912 * or array of it
913 * @param boolean $do_it a flag to bypass this function (used by dump
914 * functions)
915 * @return mixed the "backquoted" database, table or field name if the
916 * current MySQL release is >= 3.23.6, the original one
917 * else
918 * @access public
920 function PMA_backquote($a_name, $do_it = true)
922 if (is_array($a_name)) {
923 foreach ($a_name as &$data) {
924 $data = PMA_backquote($data, $do_it);
926 return $a_name;
929 if (! $do_it) {
930 global $PMA_SQPdata_forbidden_word;
931 global $PMA_SQPdata_forbidden_word_cnt;
933 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
934 return $a_name;
938 // '0' is also empty for php :-(
939 if (strlen($a_name) && $a_name !== '*') {
940 return '`' . str_replace('`', '``', $a_name) . '`';
941 } else {
942 return $a_name;
944 } // end of the 'PMA_backquote()' function
948 * Defines the <CR><LF> value depending on the user OS.
950 * @uses PMA_USR_OS
951 * @return string the <CR><LF> value to use
953 * @access public
955 function PMA_whichCrlf()
957 $the_crlf = "\n";
959 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
960 // Win case
961 if (PMA_USR_OS == 'Win') {
962 $the_crlf = "\r\n";
964 // Others
965 else {
966 $the_crlf = "\n";
969 return $the_crlf;
970 } // end of the 'PMA_whichCrlf()' function
973 * Reloads navigation if needed.
975 * @param $jsonly prints out pure JavaScript
976 * @uses $GLOBALS['reload']
977 * @uses $GLOBALS['db']
978 * @uses PMA_generate_common_url()
979 * @global array configuration
981 * @access public
983 function PMA_reloadNavigation($jsonly=false)
985 global $cfg;
987 // Reloads the navigation frame via JavaScript if required
988 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
989 // one of the reasons for a reload is when a table is dropped
990 // in this case, get rid of the table limit offset, otherwise
991 // we have a problem when dropping a table on the last page
992 // and the offset becomes greater than the total number of tables
993 unset($_SESSION['tmp_user_values']['table_limit_offset']);
994 echo "\n";
995 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
996 if (!$jsonly)
997 echo '<script type="text/javascript">' . PHP_EOL;
999 //<![CDATA[
1000 if (typeof(window.parent) != 'undefined'
1001 && typeof(window.parent.frame_navigation) != 'undefined'
1002 && window.parent.goTo) {
1003 window.parent.goTo('<?php echo $reload_url; ?>');
1005 //]]>
1006 <?php
1007 if (!$jsonly)
1008 echo '</script>' . PHP_EOL;
1010 unset($GLOBALS['reload']);
1015 * displays the message and the query
1016 * usually the message is the result of the query executed
1018 * @param string $message the message to display
1019 * @param string $sql_query the query to display
1020 * @param string $type the type (level) of the message
1021 * @global array the configuration array
1022 * @uses $cfg
1023 * @access public
1025 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
1027 global $cfg;
1029 if (null === $sql_query) {
1030 if (! empty($GLOBALS['display_query'])) {
1031 $sql_query = $GLOBALS['display_query'];
1032 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1033 $sql_query = $GLOBALS['unparsed_sql'];
1034 } elseif (! empty($GLOBALS['sql_query'])) {
1035 $sql_query = $GLOBALS['sql_query'];
1036 } else {
1037 $sql_query = '';
1041 // Corrects the tooltip text via JS if required
1042 // @todo this is REALLY the wrong place to do this - very unexpected here
1043 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1044 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1045 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1046 echo "\n";
1047 echo '<script type="text/javascript">' . "\n";
1048 echo '//<![CDATA[' . "\n";
1049 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1050 echo '//]]>' . "\n";
1051 echo '</script>' . "\n";
1052 } // end if ... elseif
1054 // Checks if the table needs to be repaired after a TRUNCATE query.
1055 // @todo what about $GLOBALS['display_query']???
1056 // @todo this is REALLY the wrong place to do this - very unexpected here
1057 if (strlen($GLOBALS['table'])
1058 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1059 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1060 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1063 unset($tbl_status);
1065 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1067 if ($message instanceof PMA_Message) {
1068 if (isset($GLOBALS['special_message'])) {
1069 $message->addMessage($GLOBALS['special_message']);
1070 unset($GLOBALS['special_message']);
1072 $message->display();
1073 $type = $message->getLevel();
1074 } else {
1075 echo '<div class="' . $type . '">';
1076 echo PMA_sanitize($message);
1077 if (isset($GLOBALS['special_message'])) {
1078 echo PMA_sanitize($GLOBALS['special_message']);
1079 unset($GLOBALS['special_message']);
1081 echo '</div>';
1084 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1085 // Html format the query to be displayed
1086 // If we want to show some sql code it is easiest to create it here
1087 /* SQL-Parser-Analyzer */
1089 if (! empty($GLOBALS['show_as_php'])) {
1090 $new_line = '\\n"<br />' . "\n"
1091 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1092 $query_base = htmlspecialchars(addslashes($sql_query));
1093 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1094 } else {
1095 $query_base = $sql_query;
1098 $query_too_big = false;
1100 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1101 // when the query is large (for example an INSERT of binary
1102 // data), the parser chokes; so avoid parsing the query
1103 $query_too_big = true;
1104 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1105 } elseif (! empty($GLOBALS['parsed_sql'])
1106 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1107 // (here, use "! empty" because when deleting a bookmark,
1108 // $GLOBALS['parsed_sql'] is set but empty
1109 $parsed_sql = $GLOBALS['parsed_sql'];
1110 } else {
1111 // Parse SQL if needed
1112 $parsed_sql = PMA_SQP_parse($query_base);
1115 // Analyze it
1116 if (isset($parsed_sql)) {
1117 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1118 // Here we append the LIMIT added for navigation, to
1119 // enable its display. Adding it higher in the code
1120 // to $sql_query would create a problem when
1121 // using the Refresh or Edit links.
1123 // Only append it on SELECTs.
1126 * @todo what would be the best to do when someone hits Refresh:
1127 * use the current LIMITs ?
1130 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1131 && isset($GLOBALS['sql_limit_to_append'])) {
1132 $query_base = $analyzed_display_query[0]['section_before_limit']
1133 . "\n" . $GLOBALS['sql_limit_to_append']
1134 . $analyzed_display_query[0]['section_after_limit'];
1135 // Need to reparse query
1136 $parsed_sql = PMA_SQP_parse($query_base);
1140 if (! empty($GLOBALS['show_as_php'])) {
1141 $query_base = '$sql = "' . $query_base;
1142 } elseif (! empty($GLOBALS['validatequery'])) {
1143 $query_base = PMA_validateSQL($query_base);
1144 } elseif (isset($parsed_sql)) {
1145 $query_base = PMA_formatSql($parsed_sql, $query_base);
1148 // Prepares links that may be displayed to edit/explain the query
1149 // (don't go to default pages, we must go to the page
1150 // where the query box is available)
1152 // Basic url query part
1153 $url_params = array();
1154 if (strlen($GLOBALS['db'])) {
1155 $url_params['db'] = $GLOBALS['db'];
1156 if (strlen($GLOBALS['table'])) {
1157 $url_params['table'] = $GLOBALS['table'];
1158 $edit_link = 'tbl_sql.php';
1159 } else {
1160 $edit_link = 'db_sql.php';
1162 } else {
1163 $edit_link = 'server_sql.php';
1166 // Want to have the query explained (Mike Beck 2002-05-22)
1167 // but only explain a SELECT (that has not been explained)
1168 /* SQL-Parser-Analyzer */
1169 $explain_link = '';
1170 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1171 $explain_params = $url_params;
1172 // Detect if we are validating as well
1173 // To preserve the validate uRL data
1174 if (! empty($GLOBALS['validatequery'])) {
1175 $explain_params['validatequery'] = 1;
1178 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1179 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1180 $_message = $GLOBALS['strExplain'];
1181 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1182 $explain_params['sql_query'] = substr($sql_query, 8);
1183 $_message = $GLOBALS['strNoExplain'];
1185 if (isset($explain_params['sql_query'])) {
1186 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1187 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1189 } //show explain
1191 $url_params['sql_query'] = $sql_query;
1192 $url_params['show_query'] = 1;
1194 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1195 if ($cfg['EditInWindow'] == true) {
1196 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1197 } else {
1198 $onclick = '';
1201 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1202 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1203 } else {
1204 $edit_link = '';
1207 $url_qpart = PMA_generate_common_url($url_params);
1209 // Also we would like to get the SQL formed in some nice
1210 // php-code (Mike Beck 2002-05-22)
1211 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1212 $php_params = $url_params;
1214 if (! empty($GLOBALS['show_as_php'])) {
1215 $_message = $GLOBALS['strNoPhp'];
1216 } else {
1217 $php_params['show_as_php'] = 1;
1218 $_message = $GLOBALS['strPhp'];
1221 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1222 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1224 if (isset($GLOBALS['show_as_php'])) {
1225 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1226 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1228 } else {
1229 $php_link = '';
1230 } //show as php
1232 // Refresh query
1233 if (! empty($cfg['SQLQuery']['Refresh'])
1234 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1235 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1236 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1237 } else {
1238 $refresh_link = '';
1239 } //show as php
1241 if (! empty($cfg['SQLValidator']['use'])
1242 && ! empty($cfg['SQLQuery']['Validate'])) {
1243 $validate_params = $url_params;
1244 if (!empty($GLOBALS['validatequery'])) {
1245 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1246 } else {
1247 $validate_params['validatequery'] = 1;
1248 $validate_message = $GLOBALS['strValidateSQL'] ;
1251 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1252 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1253 } else {
1254 $validate_link = '';
1255 } //validator
1257 echo '<code class="sql">';
1258 if ($query_too_big) {
1259 echo $shortened_query_base;
1260 } else {
1261 echo $query_base;
1264 //Clean up the end of the PHP
1265 if (! empty($GLOBALS['show_as_php'])) {
1266 echo '";';
1268 echo '</code>';
1270 echo '<div class="tools">';
1271 // avoid displaying a Profiling checkbox that could
1272 // be checked, which would reexecute an INSERT, for example
1273 if (! empty($refresh_link)) {
1274 PMA_profilingCheckbox($sql_query);
1276 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1277 echo '</div>';
1279 echo '</div><br />' . "\n";
1280 } // end of the 'PMA_showMessage()' function
1283 * Verifies if current MySQL server supports profiling
1285 * @uses $_SESSION['profiling_supported'] for caching
1286 * @uses $GLOBALS['server']
1287 * @uses PMA_DBI_fetch_value()
1288 * @uses PMA_MYSQL_INT_VERSION
1289 * @uses defined()
1290 * @access public
1291 * @return boolean whether profiling is supported
1293 * @author Marc Delisle
1295 function PMA_profilingSupported()
1297 if (! PMA_cacheExists('profiling_supported', true)) {
1298 // 5.0.37 has profiling but for example, 5.1.20 does not
1299 // (avoid a trip to the server for MySQL before 5.0.37)
1300 // and do not set a constant as we might be switching servers
1301 if (defined('PMA_MYSQL_INT_VERSION')
1302 && PMA_MYSQL_INT_VERSION >= 50037
1303 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1304 PMA_cacheSet('profiling_supported', true, true);
1305 } else {
1306 PMA_cacheSet('profiling_supported', false, true);
1310 return PMA_cacheGet('profiling_supported', true);
1314 * Displays a form with the Profiling checkbox
1316 * @param string $sql_query
1317 * @access public
1319 * @author Marc Delisle
1321 function PMA_profilingCheckbox($sql_query)
1323 if (PMA_profilingSupported()) {
1324 echo '<form action="sql.php" method="post">' . "\n";
1325 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1326 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1327 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1328 PMA_display_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1329 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1330 echo '</form>' . "\n";
1335 * Displays the results of SHOW PROFILE
1337 * @param array the results
1338 * @access public
1340 * @author Marc Delisle
1342 function PMA_profilingResults($profiling_results)
1344 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1345 echo '<table>' . "\n";
1346 echo ' <tr>' . "\n";
1347 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1348 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1349 echo ' </tr>' . "\n";
1351 foreach($profiling_results as $one_result) {
1352 echo ' <tr>' . "\n";
1353 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1354 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1356 echo '</table>' . "\n";
1357 echo '</fieldset>' . "\n";
1361 * Formats $value to byte view
1363 * @param double the value to format
1364 * @param integer the sensitiveness
1365 * @param integer the number of decimals to retain
1367 * @return array the formatted value and its unit
1369 * @access public
1371 * @author staybyte
1372 * @version 1.2 - 18 July 2002
1374 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1376 $dh = PMA_pow(10, $comma);
1377 $li = PMA_pow(10, $limes);
1378 $return_value = $value;
1379 $unit = $GLOBALS['byteUnits'][0];
1381 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1382 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1383 // use 1024.0 to avoid integer overflow on 64-bit machines
1384 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1385 $unit = $GLOBALS['byteUnits'][$d];
1386 break 1;
1387 } // end if
1388 } // end for
1390 if ($unit != $GLOBALS['byteUnits'][0]) {
1391 // if the unit is not bytes (as represented in current language)
1392 // reformat with max length of 5
1393 // 4th parameter=true means do not reformat if value < 1
1394 $return_value = PMA_formatNumber($value, 5, $comma, true);
1395 } else {
1396 // do not reformat, just handle the locale
1397 $return_value = PMA_formatNumber($value, 0);
1400 return array($return_value, $unit);
1401 } // end of the 'PMA_formatByteDown' function
1404 * Formats $value to the given length and appends SI prefixes
1405 * $comma is not substracted from the length
1406 * with a $length of 0 no truncation occurs, number is only formated
1407 * to the current locale
1409 * examples:
1410 * <code>
1411 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1412 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1413 * echo PMA_formatNumber(-0.003, 6); // -3 m
1414 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1415 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1416 * echo PMA_formatNumber(0, 6); // 0
1418 * </code>
1419 * @param double $value the value to format
1420 * @param integer $length the max length
1421 * @param integer $comma the number of decimals to retain
1422 * @param boolean $only_down do not reformat numbers below 1
1424 * @return string the formatted value and its unit
1426 * @access public
1428 * @author staybyte, sebastian mendel
1429 * @version 1.1.0 - 2005-10-27
1431 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1433 //number_format is not multibyte safe, str_replace is safe
1434 if ($length === 0) {
1435 return str_replace(array(',', '.'),
1436 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1437 number_format($value, $comma));
1440 // this units needs no translation, ISO
1441 $units = array(
1442 -8 => 'y',
1443 -7 => 'z',
1444 -6 => 'a',
1445 -5 => 'f',
1446 -4 => 'p',
1447 -3 => 'n',
1448 -2 => '&micro;',
1449 -1 => 'm',
1450 0 => ' ',
1451 1 => 'k',
1452 2 => 'M',
1453 3 => 'G',
1454 4 => 'T',
1455 5 => 'P',
1456 6 => 'E',
1457 7 => 'Z',
1458 8 => 'Y'
1461 // we need at least 3 digits to be displayed
1462 if (3 > $length + $comma) {
1463 $length = 3 - $comma;
1466 // check for negative value to retain sign
1467 if ($value < 0) {
1468 $sign = '-';
1469 $value = abs($value);
1470 } else {
1471 $sign = '';
1474 $dh = PMA_pow(10, $comma);
1475 $li = PMA_pow(10, $length);
1476 $unit = $units[0];
1478 if ($value >= 1) {
1479 for ($d = 8; $d >= 0; $d--) {
1480 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1481 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1482 $unit = $units[$d];
1483 break 1;
1484 } // end if
1485 } // end for
1486 } elseif (!$only_down && (float) $value !== 0.0) {
1487 for ($d = -8; $d <= 8; $d++) {
1488 // force using pow() because of the negative exponent
1489 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1490 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1491 $unit = $units[$d];
1492 break 1;
1493 } // end if
1494 } // end for
1495 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1497 //number_format is not multibyte safe, str_replace is safe
1498 $value = str_replace(array(',', '.'),
1499 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1500 number_format($value, $comma));
1502 return $sign . $value . ' ' . $unit;
1503 } // end of the 'PMA_formatNumber' function
1506 * Writes localised date
1508 * @param string the current timestamp
1510 * @return string the formatted date
1512 * @access public
1514 function PMA_localisedDate($timestamp = -1, $format = '')
1516 global $datefmt, $month, $day_of_week;
1518 if ($format == '') {
1519 $format = $datefmt;
1522 if ($timestamp == -1) {
1523 $timestamp = time();
1526 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1527 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1529 return strftime($date, $timestamp);
1530 } // end of the 'PMA_localisedDate()' function
1534 * returns a tab for tabbed navigation.
1535 * If the variables $link and $args ar left empty, an inactive tab is created
1537 * @uses $GLOBALS['PMA_PHP_SELF']
1538 * @uses $GLOBALS['strEmpty']
1539 * @uses $GLOBALS['strDrop']
1540 * @uses $GLOBALS['active_page']
1541 * @uses $GLOBALS['url_query']
1542 * @uses $cfg['MainPageIconic']
1543 * @uses $GLOBALS['pmaThemeImage']
1544 * @uses PMA_generate_common_url()
1545 * @uses E_USER_NOTICE
1546 * @uses htmlentities()
1547 * @uses urlencode()
1548 * @uses sprintf()
1549 * @uses trigger_error()
1550 * @uses array_merge()
1551 * @uses basename()
1552 * @param array $tab array with all options
1553 * @param array $url_params
1554 * @return string html code for one tab, a link if valid otherwise a span
1555 * @access public
1557 function PMA_generate_html_tab($tab, $url_params = array())
1559 // default values
1560 $defaults = array(
1561 'text' => '',
1562 'class' => '',
1563 'active' => false,
1564 'link' => '',
1565 'sep' => '?',
1566 'attr' => '',
1567 'args' => '',
1568 'warning' => '',
1569 'fragment' => '',
1572 $tab = array_merge($defaults, $tab);
1574 // determine additionnal style-class
1575 if (empty($tab['class'])) {
1576 if ($tab['text'] == $GLOBALS['strEmpty']
1577 || $tab['text'] == $GLOBALS['strDrop']) {
1578 $tab['class'] = 'caution';
1579 } elseif (! empty($tab['active'])
1580 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1581 $tab['class'] = 'active';
1582 } elseif (empty($GLOBALS['active_page'])
1583 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1584 && empty($tab['warning'])) {
1585 $tab['class'] = 'active';
1589 if (!empty($tab['warning'])) {
1590 $tab['class'] .= ' warning';
1591 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1594 // build the link
1595 if (!empty($tab['link'])) {
1596 $tab['link'] = htmlentities($tab['link']);
1597 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1598 if (! empty($tab['args'])) {
1599 foreach ($tab['args'] as $param => $value) {
1600 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1601 . urlencode($value);
1606 if (! empty($tab['fragment'])) {
1607 $tab['link'] .= $tab['fragment'];
1610 // display icon, even if iconic is disabled but the link-text is missing
1611 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1612 && isset($tab['icon'])) {
1613 // avoid generating an alt tag, because it only illustrates
1614 // the text that follows and if browser does not display
1615 // images, the text is duplicated
1616 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1617 .'%1$s" width="16" height="16" alt="" />%2$s';
1618 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1620 // check to not display an empty link-text
1621 elseif (empty($tab['text'])) {
1622 $tab['text'] = '?';
1623 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1624 E_USER_NOTICE);
1627 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1629 if (!empty($tab['link'])) {
1630 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1631 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1632 . $tab['text'] . '</a>';
1633 } else {
1634 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1635 . $tab['text'] . '</span>';
1638 $out .= '</li>';
1639 return $out;
1640 } // end of the 'PMA_generate_html_tab()' function
1643 * returns html-code for a tab navigation
1645 * @uses PMA_generate_html_tab()
1646 * @uses htmlentities()
1647 * @param array $tabs one element per tab
1648 * @param string $url_params
1649 * @return string html-code for tab-navigation
1651 function PMA_generate_html_tabs($tabs, $url_params)
1653 $tag_id = 'topmenu';
1654 $tab_navigation =
1655 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1656 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1658 foreach ($tabs as $tab) {
1659 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1662 $tab_navigation .=
1663 '</ul>' . "\n"
1664 .'<div class="clearfloat"></div>'
1665 .'</div>' . "\n";
1667 return $tab_navigation;
1672 * Displays a link, or a button if the link's URL is too large, to
1673 * accommodate some browsers' limitations
1675 * @param string the URL
1676 * @param string the link message
1677 * @param mixed $tag_params string: js confirmation
1678 * array: additional tag params (f.e. style="")
1679 * @param boolean $new_form we set this to false when we are already in
1680 * a form, to avoid generating nested forms
1682 * @return string the results to be echoed or saved in an array
1684 function PMA_linkOrButton($url, $message, $tag_params = array(),
1685 $new_form = true, $strip_img = false, $target = '')
1687 if (! is_array($tag_params)) {
1688 $tmp = $tag_params;
1689 $tag_params = array();
1690 if (!empty($tmp)) {
1691 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1693 unset($tmp);
1695 if (! empty($target)) {
1696 $tag_params['target'] = htmlentities($target);
1699 $tag_params_strings = array();
1700 foreach ($tag_params as $par_name => $par_value) {
1701 // htmlspecialchars() only on non javascript
1702 $par_value = substr($par_name, 0, 2) == 'on'
1703 ? $par_value
1704 : htmlspecialchars($par_value);
1705 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1708 if (strlen($url) <= $GLOBALS['cfg']['LinkLengthLimit']) {
1709 // no whitespace within an <a> else Safari will make it part of the link
1710 $ret = "\n" . '<a href="' . $url . '" '
1711 . implode(' ', $tag_params_strings) . '>'
1712 . $message . '</a>' . "\n";
1713 } else {
1714 // no spaces (linebreaks) at all
1715 // or after the hidden fields
1716 // IE will display them all
1718 // add class=link to submit button
1719 if (empty($tag_params['class'])) {
1720 $tag_params['class'] = 'link';
1723 // decode encoded url separators
1724 $separator = PMA_get_arg_separator();
1725 // on most places separator is still hard coded ...
1726 if ($separator !== '&') {
1727 // ... so always replace & with $separator
1728 $url = str_replace(htmlentities('&'), $separator, $url);
1729 $url = str_replace('&', $separator, $url);
1731 $url = str_replace(htmlentities($separator), $separator, $url);
1732 // end decode
1734 $url_parts = parse_url($url);
1735 $query_parts = explode($separator, $url_parts['query']);
1736 if ($new_form) {
1737 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1738 . ' method="post"' . $target . ' style="display: inline;">';
1739 $subname_open = '';
1740 $subname_close = '';
1741 $submit_name = '';
1742 } else {
1743 $query_parts[] = 'redirect=' . $url_parts['path'];
1744 if (empty($GLOBALS['subform_counter'])) {
1745 $GLOBALS['subform_counter'] = 0;
1747 $GLOBALS['subform_counter']++;
1748 $ret = '';
1749 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1750 $subname_close = ']';
1751 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1753 foreach ($query_parts as $query_pair) {
1754 list($eachvar, $eachval) = explode('=', $query_pair);
1755 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1756 . $subname_close . '" value="'
1757 . htmlspecialchars(urldecode($eachval)) . '" />';
1758 } // end while
1760 if (stristr($message, '<img')) {
1761 if ($strip_img) {
1762 $message = trim(strip_tags($message));
1763 $ret .= '<input type="submit"' . $submit_name . ' '
1764 . implode(' ', $tag_params_strings)
1765 . ' value="' . htmlspecialchars($message) . '" />';
1766 } else {
1767 $displayed_message = htmlspecialchars(
1768 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1769 $message));
1770 $ret .= '<input type="image"' . $submit_name . ' '
1771 . implode(' ', $tag_params_strings)
1772 . ' src="' . preg_replace(
1773 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1774 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1776 } else {
1777 $message = trim(strip_tags($message));
1778 $ret .= '<input type="submit"' . $submit_name . ' '
1779 . implode(' ', $tag_params_strings)
1780 . ' value="' . htmlspecialchars($message) . '" />';
1782 if ($new_form) {
1783 $ret .= '</form>';
1785 } // end if... else...
1787 return $ret;
1788 } // end of the 'PMA_linkOrButton()' function
1792 * Returns a given timespan value in a readable format.
1794 * @uses $GLOBALS['timespanfmt']
1795 * @uses sprintf()
1796 * @uses floor()
1797 * @param int the timespan
1799 * @return string the formatted value
1801 function PMA_timespanFormat($seconds)
1803 $return_string = '';
1804 $days = floor($seconds / 86400);
1805 if ($days > 0) {
1806 $seconds -= $days * 86400;
1808 $hours = floor($seconds / 3600);
1809 if ($days > 0 || $hours > 0) {
1810 $seconds -= $hours * 3600;
1812 $minutes = floor($seconds / 60);
1813 if ($days > 0 || $hours > 0 || $minutes > 0) {
1814 $seconds -= $minutes * 60;
1816 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1820 * Takes a string and outputs each character on a line for itself. Used
1821 * mainly for horizontalflipped display mode.
1822 * Takes care of special html-characters.
1823 * Fulfills todo-item
1824 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1826 * @todo add a multibyte safe function PMA_STR_split()
1827 * @uses strlen
1828 * @param string The string
1829 * @param string The Separator (defaults to "<br />\n")
1831 * @access public
1832 * @author Garvin Hicking <me@supergarv.de>
1833 * @return string The flipped string
1835 function PMA_flipstring($string, $Separator = "<br />\n")
1837 $format_string = '';
1838 $charbuff = false;
1840 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1841 $char = $string{$i};
1842 $append = false;
1844 if ($char == '&') {
1845 $format_string .= $charbuff;
1846 $charbuff = $char;
1847 } elseif ($char == ';' && !empty($charbuff)) {
1848 $format_string .= $charbuff . $char;
1849 $charbuff = false;
1850 $append = true;
1851 } elseif (! empty($charbuff)) {
1852 $charbuff .= $char;
1853 } else {
1854 $format_string .= $char;
1855 $append = true;
1858 // do not add separator after the last character
1859 if ($append && ($i != $str_len - 1)) {
1860 $format_string .= $Separator;
1864 return $format_string;
1869 * Function added to avoid path disclosures.
1870 * Called by each script that needs parameters, it displays
1871 * an error message and, by default, stops the execution.
1873 * Not sure we could use a strMissingParameter message here,
1874 * would have to check if the error message file is always available
1876 * @todo localize error message
1877 * @todo use PMA_fatalError() if $die === true?
1878 * @uses PMA_getenv()
1879 * @uses header_meta_style.inc.php
1880 * @uses $GLOBALS['PMA_PHP_SELF']
1881 * basename
1882 * @param array The names of the parameters needed by the calling
1883 * script.
1884 * @param boolean Stop the execution?
1885 * (Set this manually to false in the calling script
1886 * until you know all needed parameters to check).
1887 * @param boolean Whether to include this list in checking for special params.
1888 * @global string path to current script
1889 * @global boolean flag whether any special variable was required
1891 * @access public
1892 * @author Marc Delisle (lem9@users.sourceforge.net)
1894 function PMA_checkParameters($params, $die = true, $request = true)
1896 global $checked_special;
1898 if (!isset($checked_special)) {
1899 $checked_special = false;
1902 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1903 $found_error = false;
1904 $error_message = '';
1906 foreach ($params as $param) {
1907 if ($request && $param != 'db' && $param != 'table') {
1908 $checked_special = true;
1911 if (!isset($GLOBALS[$param])) {
1912 $error_message .= $reported_script_name
1913 . ': Missing parameter: ' . $param
1914 . ' <a href="./Documentation.html#faqmissingparameters"'
1915 . ' target="documentation"> (FAQ 2.8)</a><br />';
1916 $found_error = true;
1919 if ($found_error) {
1921 * display html meta tags
1923 require_once './libraries/header_meta_style.inc.php';
1924 echo '</head><body><p>' . $error_message . '</p></body></html>';
1925 if ($die) {
1926 exit();
1929 } // end function
1932 * Function to generate unique condition for specified row.
1934 * @uses $GLOBALS['analyzed_sql'][0]
1935 * @uses PMA_DBI_field_flags()
1936 * @uses PMA_backquote()
1937 * @uses PMA_sqlAddslashes()
1938 * @uses PMA_printable_bit_value()
1939 * @uses stristr()
1940 * @uses bin2hex()
1941 * @uses preg_replace()
1942 * @param resource $handle current query result
1943 * @param integer $fields_cnt number of fields
1944 * @param array $fields_meta meta information about fields
1945 * @param array $row current row
1946 * @param boolean $force_unique generate condition only on pk or unique
1948 * @access public
1949 * @author Michal Cihar (michal@cihar.com) and others...
1950 * @return string the calculated condition and whether condition is unique
1952 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1954 $primary_key = '';
1955 $unique_key = '';
1956 $nonprimary_condition = '';
1957 $preferred_condition = '';
1959 for ($i = 0; $i < $fields_cnt; ++$i) {
1960 $condition = '';
1961 $field_flags = PMA_DBI_field_flags($handle, $i);
1962 $meta = $fields_meta[$i];
1964 // do not use a column alias in a condition
1965 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1966 $meta->orgname = $meta->name;
1968 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1969 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1970 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1971 as $select_expr) {
1972 // need (string) === (string)
1973 // '' !== 0 but '' == 0
1974 if ((string) $select_expr['alias'] === (string) $meta->name) {
1975 $meta->orgname = $select_expr['column'];
1976 break;
1977 } // end if
1978 } // end foreach
1982 // Do not use a table alias in a condition.
1983 // Test case is:
1984 // select * from galerie x WHERE
1985 //(select count(*) from galerie y where y.datum=x.datum)>1
1987 // But orgtable is present only with mysqli extension so the
1988 // fix is only for mysqli.
1989 // Also, do not use the original table name if we are dealing with
1990 // a view because this view might be updatable.
1991 // (The isView() verification should not be costly in most cases
1992 // because there is some caching in the function).
1993 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1994 $meta->table = $meta->orgtable;
1997 // to fix the bug where float fields (primary or not)
1998 // can't be matched because of the imprecision of
1999 // floating comparison, use CONCAT
2000 // (also, the syntax "CONCAT(field) IS NULL"
2001 // that we need on the next "if" will work)
2002 if ($meta->type == 'real') {
2003 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
2004 . PMA_backquote($meta->orgname) . ') ';
2005 } else {
2006 $condition = ' ' . PMA_backquote($meta->table) . '.'
2007 . PMA_backquote($meta->orgname) . ' ';
2008 } // end if... else...
2010 if (!isset($row[$i]) || is_null($row[$i])) {
2011 $condition .= 'IS NULL AND';
2012 } else {
2013 // timestamp is numeric on some MySQL 4.1
2014 if ($meta->numeric && $meta->type != 'timestamp') {
2015 $condition .= '= ' . $row[$i] . ' AND';
2016 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2017 // hexify only if this is a true not empty BLOB or a BINARY
2018 && stristr($field_flags, 'BINARY')
2019 && !empty($row[$i])) {
2020 // do not waste memory building a too big condition
2021 if (strlen($row[$i]) < 1000) {
2022 // use a CAST if possible, to avoid problems
2023 // if the field contains wildcard characters % or _
2024 $condition .= '= CAST(0x' . bin2hex($row[$i])
2025 . ' AS BINARY) AND';
2026 } else {
2027 // this blob won't be part of the final condition
2028 $condition = '';
2030 } elseif ($meta->type == 'bit') {
2031 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2032 } else {
2033 $condition .= '= \''
2034 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2037 if ($meta->primary_key > 0) {
2038 $primary_key .= $condition;
2039 } elseif ($meta->unique_key > 0) {
2040 $unique_key .= $condition;
2042 $nonprimary_condition .= $condition;
2043 } // end for
2045 // Correction University of Virginia 19991216:
2046 // prefer primary or unique keys for condition,
2047 // but use conjunction of all values if no primary key
2048 $clause_is_unique = true;
2049 if ($primary_key) {
2050 $preferred_condition = $primary_key;
2051 } elseif ($unique_key) {
2052 $preferred_condition = $unique_key;
2053 } elseif (! $force_unique) {
2054 $preferred_condition = $nonprimary_condition;
2055 $clause_is_unique = false;
2058 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2059 return(array($where_clause, $clause_is_unique));
2060 } // end function
2063 * Generate a button or image tag
2065 * @uses PMA_USR_BROWSER_AGENT
2066 * @uses $GLOBALS['pmaThemeImage']
2067 * @uses $GLOBALS['cfg']['PropertiesIconic']
2068 * @param string name of button element
2069 * @param string class of button element
2070 * @param string name of image element
2071 * @param string text to display
2072 * @param string image to display
2074 * @access public
2075 * @author Michal Cihar (michal@cihar.com)
2077 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2078 $image)
2080 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2081 echo ' <input type="submit" name="' . $button_name . '"'
2082 .' value="' . htmlspecialchars($text) . '"'
2083 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2084 return;
2087 /* Opera has trouble with <input type="image"> */
2088 /* IE has trouble with <button> */
2089 if (PMA_USR_BROWSER_AGENT != 'IE') {
2090 echo '<button class="' . $button_class . '" type="submit"'
2091 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2092 .' title="' . htmlspecialchars($text) . '">' . "\n"
2093 . PMA_getIcon($image, $text)
2094 .'</button>' . "\n";
2095 } else {
2096 echo '<input type="image" name="' . $image_name . '" value="'
2097 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2098 . $image . '" />'
2099 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2101 } // end function
2104 * Generate a pagination selector for browsing resultsets
2106 * @todo $url is not javascript escaped!?
2107 * @uses $GLOBALS['strPageNumber']
2108 * @uses range()
2109 * @param string URL for the JavaScript
2110 * @param string Number of rows in the pagination set
2111 * @param string current page number
2112 * @param string number of total pages
2113 * @param string If the number of pages is lower than this
2114 * variable, no pages will be omitted in
2115 * pagination
2116 * @param string How many rows at the beginning should always
2117 * be shown?
2118 * @param string How many rows at the end should always
2119 * be shown?
2120 * @param string Percentage of calculation page offsets to
2121 * hop to a next page
2122 * @param string Near the current page, how many pages should
2123 * be considered "nearby" and displayed as
2124 * well?
2125 * @param string The prompt to display (sometimes empty)
2127 * @access public
2128 * @author Garvin Hicking (pma@supergarv.de)
2130 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2131 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2132 $range = 10, $prompt = '')
2134 $increment = floor($nbTotalPage / $percent);
2135 $pageNowMinusRange = ($pageNow - $range);
2136 $pageNowPlusRange = ($pageNow + $range);
2138 $gotopage = $prompt
2139 . ' <select name="pos" onchange="goToUrl(this, \''
2140 . $url . '\');">' . "\n";
2141 if ($nbTotalPage < $showAll) {
2142 $pages = range(1, $nbTotalPage);
2143 } else {
2144 $pages = array();
2146 // Always show first X pages
2147 for ($i = 1; $i <= $sliceStart; $i++) {
2148 $pages[] = $i;
2151 // Always show last X pages
2152 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2153 $pages[] = $i;
2156 // garvin: Based on the number of results we add the specified
2157 // $percent percentage to each page number,
2158 // so that we have a representing page number every now and then to
2159 // immediately jump to specific pages.
2160 // As soon as we get near our currently chosen page ($pageNow -
2161 // $range), every page number will be shown.
2162 $i = $sliceStart;
2163 $x = $nbTotalPage - $sliceEnd;
2164 $met_boundary = false;
2165 while ($i <= $x) {
2166 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2167 // If our pageselector comes near the current page, we use 1
2168 // counter increments
2169 $i++;
2170 $met_boundary = true;
2171 } else {
2172 // We add the percentage increment to our current page to
2173 // hop to the next one in range
2174 $i += $increment;
2176 // Make sure that we do not cross our boundaries.
2177 if ($i > $pageNowMinusRange && ! $met_boundary) {
2178 $i = $pageNowMinusRange;
2182 if ($i > 0 && $i <= $x) {
2183 $pages[] = $i;
2187 // Since because of ellipsing of the current page some numbers may be double,
2188 // we unify our array:
2189 sort($pages);
2190 $pages = array_unique($pages);
2193 foreach ($pages as $i) {
2194 if ($i == $pageNow) {
2195 $selected = 'selected="selected" style="font-weight: bold"';
2196 } else {
2197 $selected = '';
2199 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2202 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2204 return $gotopage;
2205 } // end function
2209 * Generate navigation for a list
2211 * @todo use $pos from $_url_params
2212 * @uses $GLOBALS['strPageNumber']
2213 * @uses range()
2214 * @param integer number of elements in the list
2215 * @param integer current position in the list
2216 * @param array url parameters
2217 * @param string script name for form target
2218 * @param string target frame
2219 * @param integer maximum number of elements to display from the list
2221 * @access public
2223 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2225 if ($max_count < $count) {
2226 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2227 echo $GLOBALS['strPageNumber'];
2228 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2230 // Move to the beginning or to the previous page
2231 if ($pos > 0) {
2232 // loic1: patch #474210 from Gosha Sakovich - part 1
2233 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2234 $caption1 = '&lt;&lt;';
2235 $caption2 = ' &lt; ';
2236 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2237 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2238 } else {
2239 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2240 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2241 $title1 = '';
2242 $title2 = '';
2243 } // end if... else...
2244 $_url_params['pos'] = 0;
2245 echo '<a' . $title1 . ' href="' . $script
2246 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2247 . $caption1 . '</a>';
2248 $_url_params['pos'] = $pos - $max_count;
2249 echo '<a' . $title2 . ' href="' . $script
2250 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2251 . $caption2 . '</a>';
2254 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2255 echo PMA_generate_common_hidden_inputs($_url_params);
2256 echo PMA_pageselector(
2257 $script . PMA_generate_common_url($_url_params) . '&amp;',
2258 $max_count,
2259 floor(($pos + 1) / $max_count) + 1,
2260 ceil($count / $max_count));
2261 echo '</form>';
2263 if ($pos + $max_count < $count) {
2264 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2265 $caption3 = ' &gt; ';
2266 $caption4 = '&gt;&gt;';
2267 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2268 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2269 } else {
2270 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2271 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2272 $title3 = '';
2273 $title4 = '';
2274 } // end if... else...
2275 $_url_params['pos'] = $pos + $max_count;
2276 echo '<a' . $title3 . ' href="' . $script
2277 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2278 . $caption3 . '</a>';
2279 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2280 if ($_url_params['pos'] == $count) {
2281 $_url_params['pos'] = $count - $max_count;
2283 echo '<a' . $title4 . ' href="' . $script
2284 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2285 . $caption4 . '</a>';
2287 echo "\n";
2288 if ('frame_navigation' == $frame) {
2289 echo '</div>' . "\n";
2295 * replaces %u in given path with current user name
2297 * example:
2298 * <code>
2299 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2301 * </code>
2302 * @uses $cfg['Server']['user']
2303 * @uses substr()
2304 * @uses str_replace()
2305 * @param string $dir with wildcard for user
2306 * @return string per user directory
2308 function PMA_userDir($dir)
2310 // add trailing slash
2311 if (substr($dir, -1) != '/') {
2312 $dir .= '/';
2315 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2319 * returns html code for db link to default db page
2321 * @uses $cfg['DefaultTabDatabase']
2322 * @uses $GLOBALS['db']
2323 * @uses $GLOBALS['strJumpToDB']
2324 * @uses PMA_generate_common_url()
2325 * @uses PMA_unescape_mysql_wildcards()
2326 * @uses strlen()
2327 * @uses sprintf()
2328 * @uses htmlspecialchars()
2329 * @param string $database
2330 * @return string html link to default db page
2332 function PMA_getDbLink($database = null)
2334 if (!strlen($database)) {
2335 if (!strlen($GLOBALS['db'])) {
2336 return '';
2338 $database = $GLOBALS['db'];
2339 } else {
2340 $database = PMA_unescape_mysql_wildcards($database);
2343 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2344 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2345 .htmlspecialchars($database) . '</a>';
2349 * Displays a lightbulb hint explaining a known external bug
2350 * that affects a functionality
2352 * @uses PMA_MYSQL_INT_VERSION
2353 * @uses $GLOBALS['strKnownExternalBug']
2354 * @uses PMA_showHint()
2355 * @uses sprintf()
2356 * @param string $functionality localized message explaining the func.
2357 * @param string $component 'mysql' (eventually, 'php')
2358 * @param string $minimum_version of this component
2359 * @param string $bugref bug reference for this component
2361 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2363 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2364 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2369 * Generates and echoes an HTML checkbox
2371 * @param string $html_field_name the checkbox HTML field
2372 * @param string $label
2373 * @param boolean $checked is it initially checked?
2374 * @param boolean $onclick should it submit the form on click?
2376 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2378 echo '<input type="checkbox" name="' . $html_field_name . '" id="' . $html_field_name . '"' . ($checked ? ' checked="checked"' : '') . ($onclick ? ' onclick="this.form.submit();"' : '') . ' /><label for="' . $html_field_name . '">' . $label . '</label>';
2382 * Generates and echoes a set of radio HTML fields
2384 * @uses htmlspecialchars()
2385 * @param string $html_field_name the radio HTML field
2386 * @param array $choices the choices values and labels
2387 * @param string $checked_choice the choice to check by default
2388 * @param boolean $line_break whether to add an HTML line break after a choice
2389 * @param boolean $escape_label whether to use htmlspecialchars() on label
2390 * @param string $class enclose each choice with a div of this class
2392 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2393 foreach ($choices as $choice_value => $choice_label) {
2394 if (! empty($class)) {
2395 echo '<div class="' . $class . '">';
2397 $html_field_id = $html_field_name . '_' . $choice_value;
2398 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2399 if ($choice_value == $checked_choice) {
2400 echo ' checked="checked"';
2402 echo ' />' . "\n";
2403 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2404 if ($line_break) {
2405 echo '<br />';
2407 if (! empty($class)) {
2408 echo '</div>';
2410 echo "\n";
2415 * Generates and returns an HTML dropdown
2417 * @uses htmlspecialchars()
2418 * @param string $select_name
2419 * @param array $choices the choices values
2420 * @param string $active_choice the choice to select by default
2421 * @param string $id the id of the select element; can be different in case
2422 * the dropdown is present more than once on the page
2423 * @todo support titles
2425 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2427 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2428 foreach ($choices as $one_choice_value => $one_choice_label) {
2429 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2430 if ($one_choice_value == $active_choice) {
2431 $result .= ' selected="selected"';
2433 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2435 $result .= '</select>';
2436 return $result;
2440 * Generates a slider effect (Mootools)
2441 * Takes care of generating the initial <div> and the link
2442 * controlling the slider; you have to generate the </div> yourself
2443 * after the sliding section.
2445 * @uses $GLOBALS['cfg']['InitialSlidersState']
2446 * @param string $id the id of the <div> on which to apply the effect
2447 * @param string $message the message to show as a link
2449 function PMA_generate_slider_effect($id, $message)
2451 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2452 echo '<div id="' . $id . '">';
2453 return;
2456 <script type="text/javascript">
2457 // <![CDATA[
2458 window.addEvent('domready', function(){
2459 var status = {
2460 'true': '- ',
2461 'false': '+ '
2464 var anchor<?php echo $id; ?> = new Element('a', {
2465 'id': 'toggle_<?php echo $id; ?>',
2466 'href': 'javascript:void(0)',
2467 'events': {
2468 'click': function(){
2469 mySlide<?php echo $id; ?>.toggle();
2474 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2475 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2477 var slider_status<?php echo $id; ?> = new Element('span', {
2478 'id': 'slider_status_<?php echo $id; ?>'
2480 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2481 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2483 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2484 <?php
2485 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2487 mySlide<?php echo $id; ?>.hide();
2488 <?php
2491 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2492 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2495 $('<?php echo $id; ?>').style.display="block";
2497 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2498 //]]>
2499 </script>
2500 <noscript>
2501 <div id="<?php echo $id; ?>" />
2502 </noscript>
2503 <?php
2507 * Verifies if something is cached in the session
2509 * @param string $var
2510 * @param scalar $server
2511 * @return boolean
2513 function PMA_cacheExists($var, $server = 0)
2515 if (true === $server) {
2516 $server = $GLOBALS['server'];
2518 return isset($_SESSION['cache']['server_' . $server][$var]);
2522 * Gets cached information from the session
2524 * @param string $var
2525 * @param scalar $server
2526 * @return mixed
2528 function PMA_cacheGet($var, $server = 0)
2530 if (true === $server) {
2531 $server = $GLOBALS['server'];
2533 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2534 return $_SESSION['cache']['server_' . $server][$var];
2535 } else {
2536 return null;
2541 * Caches information in the session
2543 * @param string $var
2544 * @param mixed $val
2545 * @param integer $server
2546 * @return mixed
2548 function PMA_cacheSet($var, $val = null, $server = 0)
2550 if (true === $server) {
2551 $server = $GLOBALS['server'];
2553 $_SESSION['cache']['server_' . $server][$var] = $val;
2557 * Removes cached information from the session
2559 * @param string $var
2560 * @param scalar $server
2562 function PMA_cacheUnset($var, $server = 0)
2564 if (true === $server) {
2565 $server = $GLOBALS['server'];
2567 unset($_SESSION['cache']['server_' . $server][$var]);
2571 * Converts a bit value to printable format;
2572 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2573 * function because in PHP, decbin() supports only 32 bits
2575 * @uses ceil()
2576 * @uses decbin()
2577 * @uses ord()
2578 * @uses substr()
2579 * @uses sprintf()
2580 * @param numeric $value coming from a BIT field
2581 * @param integer $length
2582 * @return string the printable value
2584 function PMA_printable_bit_value($value, $length) {
2585 $printable = '';
2586 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2587 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2589 $printable = substr($printable, -$length);
2590 return $printable;
2594 * Converts a BIT type default value
2595 * for example, b'010' becomes 010
2597 * @uses strtr()
2598 * @param string $bit_default_value
2599 * @return string the converted value
2601 function PMA_convert_bit_default_value($bit_default_value) {
2602 return strtr($bit_default_value, array("b" => "", "'" => ""));
2606 * Extracts the various parts from a field type spec
2608 * @uses strpos()
2609 * @uses chop()
2610 * @uses substr()
2611 * @param string $fieldspec
2612 * @return array associative array containing type, spec_in_brackets
2613 * and possibly enum_set_values (another array)
2614 * @author Marc Delisle
2615 * @author Joshua Hogendorn
2617 function PMA_extractFieldSpec($fieldspec) {
2618 $first_bracket_pos = strpos($fieldspec, '(');
2619 if ($first_bracket_pos) {
2620 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2621 // convert to lowercase just to be sure
2622 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2623 } else {
2624 $type = $fieldspec;
2625 $spec_in_brackets = '';
2628 if ('enum' == $type || 'set' == $type) {
2629 // Define our working vars
2630 $enum_set_values = array();
2631 $working = "";
2632 $in_string = false;
2633 $index = 0;
2635 // While there is another character to process
2636 while (isset($fieldspec[$index])) {
2637 // Grab the char to look at
2638 $char = $fieldspec[$index];
2640 // If it is a single quote, needs to be handled specially
2641 if ($char == "'") {
2642 // If we are not currently in a string, begin one
2643 if (! $in_string) {
2644 $in_string = true;
2645 $working = "";
2646 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2647 } else {
2648 // Check out the next character (if possible)
2649 $has_next = isset($fieldspec[$index + 1]);
2650 $next = $has_next ? $fieldspec[$index + 1] : null;
2652 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2653 if (! $has_next || $next != "'") {
2654 $enum_set_values[] = $working;
2655 $in_string = false;
2657 // Otherwise, this is a 'double quote', and can be added to the working string
2658 } elseif ($next == "'") {
2659 $working .= "'";
2660 // Skip the next char; we already know what it is
2661 $index++;
2664 // escaping of a quote?
2665 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2666 $working .= "'";
2667 $index++;
2668 // Otherwise, add it to our working string like normal
2669 } else {
2670 $working .= $char;
2672 // Increment character index
2673 $index++;
2674 } // end while
2675 } else {
2676 $enum_set_values = array();
2679 return array(
2680 'type' => $type,
2681 'spec_in_brackets' => $spec_in_brackets,
2682 'enum_set_values' => $enum_set_values
2687 * Verifies if this table's engine supports foreign keys
2689 * @uses strtoupper()
2690 * @param string $engine
2691 * @return boolean
2693 function PMA_foreignkey_supported($engine) {
2694 $engine = strtoupper($engine);
2695 if ('INNODB' == $engine || 'PBXT' == $engine) {
2696 return true;
2697 } else {
2698 return false;
2703 * Replaces some characters by a displayable equivalent
2705 * @uses str_replace()
2706 * @param string $content
2707 * @return string the content with characters replaced
2709 function PMA_replace_binary_contents($content) {
2710 $result = str_replace("\x00", '\0', $content);
2711 $result = str_replace("\x08", '\b', $result);
2712 $result = str_replace("\x0a", '\n', $result);
2713 $result = str_replace("\x0d", '\r', $result);
2714 $result = str_replace("\x1a", '\Z', $result);
2715 return $result;
2720 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2722 * @uses strpos()
2723 * @return string with the chars replaced
2726 function PMA_duplicateFirstNewline($string){
2727 $first_occurence = strpos($string, "\r\n");
2728 if ($first_occurence === 0){
2729 $string = "\n".$string;
2731 return $string;
2735 * get the action word corresponding to a script name
2736 * in order to display it as a title in navigation panel
2738 * @uses $GLOBALS
2739 * @param string a valid value for $cfg['LeftDefaultTabTable']
2740 * or $cfg['DefaultTabTable']
2741 * or $cfg['DefaultTabDatabase']
2743 function PMA_getTitleForTarget($target) {
2744 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];
2747 /**
2748 * The function creates javascript and html code, which run given mootools/JS code when DOM is ready
2750 * @param String $code - Mootools/JS code, which will be run
2751 * @param boolena $print - If true, then the code is printed, otherwise is returned
2753 * @return String - the code
2755 function PMA_js_mootools_domready($code, $print=true)
2757 // these generated newlines are needed
2758 $out = '';
2759 $out .= '<script type="text/javascript">';
2760 $out .= "\n" . '// <![CDATA[' . "\n";
2761 $out .= 'window.addEvent(\'domready\',function() {';
2762 $out .= $code;
2763 $out .= '});';
2764 $out .= "\n" . '// ]]>' . "\n";
2765 $out .= '</script>';
2767 if ($print)
2768 echo $out;
2770 return $out;
2773 function PMA_js($code, $print=true)
2775 // these generated newlines are needed
2776 $out = '';
2777 $out .= '<script type="text/javascript">'."\n";
2778 $out .= "\n" . '// <![CDATA[' . "\n";
2779 $out .= $code;
2780 $out .= "\n" . '// ]]>' . "\n";
2781 $out .= '</script>'."\n";
2783 if ($print)
2784 echo $out;
2786 return $out;