Merge branch 'QA_3_3'
[phpmyadmin/dkf.git] / libraries / common.lib.php
blob76ebb060099ccd89887a8a24dc8b2e5c180d36a5
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
298 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
300 global $cfg;
302 // Check that we actually have a valid set of parsed data
303 // well, not quite
304 // first check for the SQL parser having hit an error
305 if (PMA_SQP_isError()) {
306 return htmlspecialchars($parsed_sql['raw']);
308 // then check for an array
309 if (!is_array($parsed_sql)) {
310 // We don't so just return the input directly
311 // This is intended to be used for when the SQL Parser is turned off
312 $formatted_sql = '<pre>' . "\n"
313 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
314 . '</pre>';
315 return $formatted_sql;
318 $formatted_sql = '';
320 switch ($cfg['SQP']['fmtType']) {
321 case 'none':
322 if ($unparsed_sql != '') {
323 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
324 } else {
325 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
327 break;
328 case 'html':
329 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
330 break;
331 case 'text':
332 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
333 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
334 break;
335 default:
336 break;
337 } // end switch
339 return $formatted_sql;
340 } // end of the "PMA_formatSql()" function
344 * Displays a link to the official MySQL documentation
346 * @uses $cfg['MySQLManualType']
347 * @uses $cfg['MySQLManualBase']
348 * @uses $cfg['ReplaceHelpImg']
349 * @uses $GLOBALS['strDocu']
350 * @uses $GLOBALS['pmaThemeImage']
351 * @uses PMA_MYSQL_INT_VERSION
352 * @uses strtolower()
353 * @uses str_replace()
354 * @param string chapter of "HTML, one page per chapter" documentation
355 * @param string contains name of page/anchor that is being linked
356 * @param bool whether to use big icon (like in left frame)
357 * @param string anchor to page part
359 * @return string the html link
361 * @access public
363 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
365 global $cfg;
367 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
368 return '';
371 // Fixup for newly used names:
372 $chapter = str_replace('_', '-', strtolower($chapter));
373 $link = str_replace('_', '-', strtolower($link));
375 switch ($cfg['MySQLManualType']) {
376 case 'chapters':
377 if (empty($chapter)) {
378 $chapter = 'index';
380 if (empty($anchor)) {
381 $anchor = $link;
383 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
384 break;
385 case 'big':
386 if (empty($anchor)) {
387 $anchor = $link;
389 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
390 break;
391 case 'searchable':
392 if (empty($link)) {
393 $link = 'index';
395 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
396 if (!empty($anchor)) {
397 $url .= '#' . $anchor;
399 break;
400 case 'viewable':
401 default:
402 if (empty($link)) {
403 $link = 'index';
405 $mysql = '5.0';
406 $lang = 'en';
407 if (defined('PMA_MYSQL_INT_VERSION')) {
408 if (PMA_MYSQL_INT_VERSION >= 50100) {
409 $mysql = '5.1';
410 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
411 $lang = _pgettext('$mysql_5_1_doc_lang', 'en');
412 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
413 $mysql = '5.0';
414 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
415 $lang = _pgettext('$mysql_5_0_doc_lang', 'en');
418 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
419 if (!empty($anchor)) {
420 $url .= '#' . $anchor;
422 break;
425 if ($just_open) {
426 return '<a href="' . $url . '" target="mysql_doc">';
427 } elseif ($big_icon) {
428 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>';
429 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
430 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>';
431 } else {
432 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
434 } // end of the 'PMA_showMySQLDocu()' function
438 * Displays a link to the phpMyAdmin documentation
440 * @param string anchor in documentation
442 * @return string the html link
444 * @access public
446 function PMA_showDocu($anchor) {
447 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
448 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>';
449 } else {
450 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . $GLOBALS['strDocu'] . '</a>]';
452 } // end of the 'PMA_showDocu()' function
455 * returns HTML for a footnote marker and add the messsage to the footnotes
457 * @uses $GLOBALS['footnotes']
458 * @param string the error message
459 * @return string html code for a footnote marker
460 * @access public
462 function PMA_showHint($message, $bbcode = false, $type = 'notice')
464 if ($message instanceof PMA_Message) {
465 $key = $message->getHash();
466 $type = $message->getLevel();
467 } else {
468 $key = md5($message);
471 if (! isset($GLOBALS['footnotes'][$key])) {
472 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
473 $GLOBALS['footnotes'] = array();
475 $nr = count($GLOBALS['footnotes']) + 1;
476 // this is the first instance of this message
477 $instance = 1;
478 $GLOBALS['footnotes'][$key] = array(
479 'note' => $message,
480 'type' => $type,
481 'nr' => $nr,
482 'instance' => $instance
484 } else {
485 $nr = $GLOBALS['footnotes'][$key]['nr'];
486 // another instance of this message (to ensure ids are unique)
487 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
490 if ($bbcode) {
491 return '[sup]' . $nr . '[/sup]';
494 // footnotemarker used in js/tooltip.js
495 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
499 * Displays a MySQL error message in the right frame.
501 * @uses footer.inc.php
502 * @uses header.inc.php
503 * @uses $GLOBALS['sql_query']
504 * @uses $GLOBALS['strError']
505 * @uses $GLOBALS['strSQLQuery']
506 * @uses $GLOBALS['pmaThemeImage']
507 * @uses $GLOBALS['strEdit']
508 * @uses $GLOBALS['strMySQLSaid']
509 * @uses $GLOBALS['cfg']['PropertiesIconic']
510 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
511 * @uses PMA_backquote()
512 * @uses PMA_DBI_getError()
513 * @uses PMA_formatSql()
514 * @uses PMA_generate_common_hidden_inputs()
515 * @uses PMA_generate_common_url()
516 * @uses PMA_showMySQLDocu()
517 * @uses PMA_sqlAddslashes()
518 * @uses PMA_SQP_isError()
519 * @uses PMA_SQP_parse()
520 * @uses PMA_SQP_getErrorString()
521 * @uses strtolower()
522 * @uses urlencode()
523 * @uses str_replace()
524 * @uses nl2br()
525 * @uses substr()
526 * @uses preg_replace()
527 * @uses preg_match()
528 * @uses explode()
529 * @uses implode()
530 * @uses is_array()
531 * @uses function_exists()
532 * @uses htmlspecialchars()
533 * @uses trim()
534 * @uses strstr()
535 * @param string the error message
536 * @param string the sql query that failed
537 * @param boolean whether to show a "modify" link or not
538 * @param string the "back" link url (full path is not required)
539 * @param boolean EXIT the page?
541 * @global string the curent table
542 * @global string the current db
544 * @access public
546 function PMA_mysqlDie($error_message = '', $the_query = '',
547 $is_modify_link = true, $back_url = '', $exit = true)
549 global $table, $db;
552 * start http output, display html headers
554 require_once './libraries/header.inc.php';
556 $error_msg_output = '';
558 if (!$error_message) {
559 $error_message = PMA_DBI_getError();
561 if (!$the_query && !empty($GLOBALS['sql_query'])) {
562 $the_query = $GLOBALS['sql_query'];
565 // --- Added to solve bug #641765
566 // Robbat2 - 12 January 2003, 9:46PM
567 // Revised, Robbat2 - 13 January 2003, 2:59PM
568 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
569 $formatted_sql = htmlspecialchars($the_query);
570 } elseif (empty($the_query) || trim($the_query) == '') {
571 $formatted_sql = '';
572 } else {
573 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
574 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
575 } else {
576 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
579 // ---
580 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
581 $error_msg_output .= ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
582 // if the config password is wrong, or the MySQL server does not
583 // respond, do not show the query that would reveal the
584 // username/password
585 if (!empty($the_query) && !strstr($the_query, 'connect')) {
586 // --- Added to solve bug #641765
587 // Robbat2 - 12 January 2003, 9:46PM
588 // Revised, Robbat2 - 13 January 2003, 2:59PM
589 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
590 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
591 $error_msg_output .= '<br />' . "\n";
593 // ---
594 // modified to show the help on sql errors
595 $error_msg_output .= ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
596 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
597 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
599 if ($is_modify_link) {
600 $_url_params = array(
601 'sql_query' => $the_query,
602 'show_query' => 1,
604 if (strlen($table)) {
605 $_url_params['db'] = $db;
606 $_url_params['table'] = $table;
607 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
608 } elseif (strlen($db)) {
609 $_url_params['db'] = $db;
610 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
611 } else {
612 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
615 $error_msg_output .= $doedit_goto
616 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
617 . '</a>';
618 } // end if
619 $error_msg_output .= ' </p>' . "\n"
620 .' <p>' . "\n"
621 .' ' . $formatted_sql . "\n"
622 .' </p>' . "\n";
623 } // end if
625 $tmp_mysql_error = ''; // for saving the original $error_message
626 if (!empty($error_message)) {
627 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
628 $error_message = htmlspecialchars($error_message);
629 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
631 // modified to show the help on error-returns
632 // (now error-messages-server)
633 $error_msg_output .= '<p>' . "\n"
634 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
635 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
636 . "\n"
637 . '</p>' . "\n";
639 // The error message will be displayed within a CODE segment.
640 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
642 // Replace all non-single blanks with their HTML-counterpart
643 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
644 // Replace TAB-characters with their HTML-counterpart
645 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
646 // Replace linebreaks
647 $error_message = nl2br($error_message);
649 $error_msg_output .= '<code>' . "\n"
650 . $error_message . "\n"
651 . '</code><br />' . "\n";
652 $error_msg_output .= '</div>';
654 $_SESSION['Import_message']['message'] = $error_msg_output;
656 if ($exit) {
657 if (! empty($back_url)) {
658 if (strstr($back_url, '?')) {
659 $back_url .= '&amp;no_history=true';
660 } else {
661 $back_url .= '?no_history=true';
664 $_SESSION['Import_message']['go_back_url'] = $back_url;
666 $error_msg_output .= '<fieldset class="tblFooters">';
667 $error_msg_output .= '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
668 $error_msg_output .= '</fieldset>' . "\n\n";
671 echo $error_msg_output;
673 * display footer and exit
676 require_once './libraries/footer.inc.php';
677 } else {
678 echo $error_msg_output;
680 } // end of the 'PMA_mysqlDie()' function
683 * Send HTTP header, taking IIS limits into account (600 seems ok)
685 * @uses PMA_IS_IIS
686 * @uses PMA_COMING_FROM_COOKIE_LOGIN
687 * @uses PMA_get_arg_separator()
688 * @uses SID
689 * @uses strlen()
690 * @uses strpos()
691 * @uses header()
692 * @uses session_write_close()
693 * @uses headers_sent()
694 * @uses function_exists()
695 * @uses debug_print_backtrace()
696 * @uses trigger_error()
697 * @uses defined()
698 * @param string $uri the header to send
699 * @return boolean always true
701 function PMA_sendHeaderLocation($uri)
703 if (PMA_IS_IIS && strlen($uri) > 600) {
705 echo '<html><head><title>- - -</title>' . "\n";
706 echo '<meta http-equiv="expires" content="0">' . "\n";
707 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
708 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
709 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
710 echo '<script type="text/javascript">' . "\n";
711 echo '//<![CDATA[' . "\n";
712 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
713 echo '//]]>' . "\n";
714 echo '</script>' . "\n";
715 echo '</head>' . "\n";
716 echo '<body>' . "\n";
717 echo '<script type="text/javascript">' . "\n";
718 echo '//<![CDATA[' . "\n";
719 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
720 echo '//]]>' . "\n";
721 echo '</script></body></html>' . "\n";
723 } else {
724 if (SID) {
725 if (strpos($uri, '?') === false) {
726 header('Location: ' . $uri . '?' . SID);
727 } else {
728 $separator = PMA_get_arg_separator();
729 header('Location: ' . $uri . $separator . SID);
731 } else {
732 session_write_close();
733 if (headers_sent()) {
734 if (function_exists('debug_print_backtrace')) {
735 echo '<pre>';
736 debug_print_backtrace();
737 echo '</pre>';
739 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
741 // bug #1523784: IE6 does not like 'Refresh: 0', it
742 // results in a blank page
743 // but we need it when coming from the cookie login panel)
744 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
745 header('Refresh: 0; ' . $uri);
746 } else {
747 header('Location: ' . $uri);
754 * returns array with tables of given db with extended information and grouped
756 * @uses $cfg['LeftFrameTableSeparator']
757 * @uses $cfg['LeftFrameTableLevel']
758 * @uses $cfg['ShowTooltipAliasTB']
759 * @uses $cfg['NaturalOrder']
760 * @uses PMA_backquote()
761 * @uses count()
762 * @uses array_merge
763 * @uses uksort()
764 * @uses strstr()
765 * @uses explode()
766 * @param string $db name of db
767 * @param string $tables name of tables
768 * @param integer $limit_offset list offset
769 * @param integer $limit_count max tables to return
770 * return array (recursive) grouped table list
772 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
774 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
776 if (null === $tables) {
777 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
778 if ($GLOBALS['cfg']['NaturalOrder']) {
779 uksort($tables, 'strnatcasecmp');
783 if (count($tables) < 1) {
784 return $tables;
787 $default = array(
788 'Name' => '',
789 'Rows' => 0,
790 'Comment' => '',
791 'disp_name' => '',
794 $table_groups = array();
796 // for blobstreaming - list of blobstreaming tables
798 // load PMA configuration
799 $PMA_Config = $GLOBALS['PMA_Config'];
801 // if PMA configuration exists
802 if (!empty($PMA_Config))
803 $session_bs_tables = $GLOBALS['PMA_Config']->get('BLOBSTREAMING_TABLES');
805 foreach ($tables as $table_name => $table) {
806 // if BS tables exist
807 if (isset($session_bs_tables))
808 // compare table name to tables in list of blobstreaming tables
809 foreach ($session_bs_tables as $table_key=>$table_val)
810 // if table is in list, skip outer foreach loop
811 if ($table_name == $table_key)
812 continue 2;
814 // check for correct row count
815 if (null === $table['Rows']) {
816 // Do not check exact row count here,
817 // if row count is invalid possibly the table is defect
818 // and this would break left frame;
819 // but we can check row count if this is a view or the
820 // information_schema database
821 // since PMA_Table::countRecords() returns a limited row count
822 // in this case.
824 // set this because PMA_Table::countRecords() can use it
825 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
827 if ($tbl_is_view || 'information_schema' == $db) {
828 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
832 // in $group we save the reference to the place in $table_groups
833 // where to store the table info
834 if ($GLOBALS['cfg']['LeftFrameDBTree']
835 && $sep && strstr($table_name, $sep))
837 $parts = explode($sep, $table_name);
839 $group =& $table_groups;
840 $i = 0;
841 $group_name_full = '';
842 $parts_cnt = count($parts) - 1;
843 while ($i < $parts_cnt
844 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
845 $group_name = $parts[$i] . $sep;
846 $group_name_full .= $group_name;
848 if (!isset($group[$group_name])) {
849 $group[$group_name] = array();
850 $group[$group_name]['is' . $sep . 'group'] = true;
851 $group[$group_name]['tab' . $sep . 'count'] = 1;
852 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
853 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
854 $table = $group[$group_name];
855 $group[$group_name] = array();
856 $group[$group_name][$group_name] = $table;
857 unset($table);
858 $group[$group_name]['is' . $sep . 'group'] = true;
859 $group[$group_name]['tab' . $sep . 'count'] = 1;
860 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
861 } else {
862 $group[$group_name]['tab' . $sep . 'count']++;
864 $group =& $group[$group_name];
865 $i++;
867 } else {
868 if (!isset($table_groups[$table_name])) {
869 $table_groups[$table_name] = array();
871 $group =& $table_groups;
875 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
876 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
877 // switch tooltip and name
878 $table['Comment'] = $table['Name'];
879 $table['disp_name'] = $table['Comment'];
880 } else {
881 $table['disp_name'] = $table['Name'];
884 $group[$table_name] = array_merge($default, $table);
887 return $table_groups;
890 /* ----------------------- Set of misc functions ----------------------- */
894 * Adds backquotes on both sides of a database, table or field name.
895 * and escapes backquotes inside the name with another backquote
897 * example:
898 * <code>
899 * echo PMA_backquote('owner`s db'); // `owner``s db`
901 * </code>
903 * @uses PMA_backquote()
904 * @uses is_array()
905 * @uses strlen()
906 * @uses str_replace()
907 * @param mixed $a_name the database, table or field name to "backquote"
908 * or array of it
909 * @param boolean $do_it a flag to bypass this function (used by dump
910 * functions)
911 * @return mixed the "backquoted" database, table or field name if the
912 * current MySQL release is >= 3.23.6, the original one
913 * else
914 * @access public
916 function PMA_backquote($a_name, $do_it = true)
918 if (is_array($a_name)) {
919 foreach ($a_name as &$data) {
920 $data = PMA_backquote($data, $do_it);
922 return $a_name;
925 if (! $do_it) {
926 global $PMA_SQPdata_forbidden_word;
927 global $PMA_SQPdata_forbidden_word_cnt;
929 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
930 return $a_name;
934 // '0' is also empty for php :-(
935 if (strlen($a_name) && $a_name !== '*') {
936 return '`' . str_replace('`', '``', $a_name) . '`';
937 } else {
938 return $a_name;
940 } // end of the 'PMA_backquote()' function
944 * Defines the <CR><LF> value depending on the user OS.
946 * @uses PMA_USR_OS
947 * @return string the <CR><LF> value to use
949 * @access public
951 function PMA_whichCrlf()
953 $the_crlf = "\n";
955 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
956 // Win case
957 if (PMA_USR_OS == 'Win') {
958 $the_crlf = "\r\n";
960 // Others
961 else {
962 $the_crlf = "\n";
965 return $the_crlf;
966 } // end of the 'PMA_whichCrlf()' function
969 * Reloads navigation if needed.
971 * @param $jsonly prints out pure JavaScript
972 * @uses $GLOBALS['reload']
973 * @uses $GLOBALS['db']
974 * @uses PMA_generate_common_url()
975 * @global array configuration
977 * @access public
979 function PMA_reloadNavigation($jsonly=false)
981 global $cfg;
983 // Reloads the navigation frame via JavaScript if required
984 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
985 // one of the reasons for a reload is when a table is dropped
986 // in this case, get rid of the table limit offset, otherwise
987 // we have a problem when dropping a table on the last page
988 // and the offset becomes greater than the total number of tables
989 unset($_SESSION['tmp_user_values']['table_limit_offset']);
990 echo "\n";
991 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
992 if (!$jsonly)
993 echo '<script type="text/javascript">' . PHP_EOL;
995 //<![CDATA[
996 if (typeof(window.parent) != 'undefined'
997 && typeof(window.parent.frame_navigation) != 'undefined'
998 && window.parent.goTo) {
999 window.parent.goTo('<?php echo $reload_url; ?>');
1001 //]]>
1002 <?php
1003 if (!$jsonly)
1004 echo '</script>' . PHP_EOL;
1006 unset($GLOBALS['reload']);
1011 * displays the message and the query
1012 * usually the message is the result of the query executed
1014 * @param string $message the message to display
1015 * @param string $sql_query the query to display
1016 * @param string $type the type (level) of the message
1017 * @param boolean $is_view is this a message after a VIEW operation?
1018 * @global array the configuration array
1019 * @uses $cfg
1020 * @access public
1022 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
1024 global $cfg;
1026 if (null === $sql_query) {
1027 if (! empty($GLOBALS['display_query'])) {
1028 $sql_query = $GLOBALS['display_query'];
1029 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1030 $sql_query = $GLOBALS['unparsed_sql'];
1031 } elseif (! empty($GLOBALS['sql_query'])) {
1032 $sql_query = $GLOBALS['sql_query'];
1033 } else {
1034 $sql_query = '';
1038 // Corrects the tooltip text via JS if required
1039 // @todo this is REALLY the wrong place to do this - very unexpected here
1040 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1041 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1042 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1043 echo "\n";
1044 echo '<script type="text/javascript">' . "\n";
1045 echo '//<![CDATA[' . "\n";
1046 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1047 echo '//]]>' . "\n";
1048 echo '</script>' . "\n";
1049 } // end if ... elseif
1051 // Checks if the table needs to be repaired after a TRUNCATE query.
1052 // @todo what about $GLOBALS['display_query']???
1053 // @todo this is REALLY the wrong place to do this - very unexpected here
1054 if (strlen($GLOBALS['table'])
1055 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1056 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1057 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1060 unset($tbl_status);
1062 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1064 if ($message instanceof PMA_Message) {
1065 if (isset($GLOBALS['special_message'])) {
1066 $message->addMessage($GLOBALS['special_message']);
1067 unset($GLOBALS['special_message']);
1069 $message->display();
1070 $type = $message->getLevel();
1071 } else {
1072 echo '<div class="' . $type . '">';
1073 echo PMA_sanitize($message);
1074 if (isset($GLOBALS['special_message'])) {
1075 echo PMA_sanitize($GLOBALS['special_message']);
1076 unset($GLOBALS['special_message']);
1078 echo '</div>';
1081 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1082 // Html format the query to be displayed
1083 // If we want to show some sql code it is easiest to create it here
1084 /* SQL-Parser-Analyzer */
1086 if (! empty($GLOBALS['show_as_php'])) {
1087 $new_line = '\\n"<br />' . "\n"
1088 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1089 $query_base = htmlspecialchars(addslashes($sql_query));
1090 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1091 } else {
1092 $query_base = $sql_query;
1095 $query_too_big = false;
1097 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1098 // when the query is large (for example an INSERT of binary
1099 // data), the parser chokes; so avoid parsing the query
1100 $query_too_big = true;
1101 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1102 } elseif (! empty($GLOBALS['parsed_sql'])
1103 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1104 // (here, use "! empty" because when deleting a bookmark,
1105 // $GLOBALS['parsed_sql'] is set but empty
1106 $parsed_sql = $GLOBALS['parsed_sql'];
1107 } else {
1108 // Parse SQL if needed
1109 $parsed_sql = PMA_SQP_parse($query_base);
1112 // Analyze it
1113 if (isset($parsed_sql)) {
1114 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1115 // Here we append the LIMIT added for navigation, to
1116 // enable its display. Adding it higher in the code
1117 // to $sql_query would create a problem when
1118 // using the Refresh or Edit links.
1120 // Only append it on SELECTs.
1123 * @todo what would be the best to do when someone hits Refresh:
1124 * use the current LIMITs ?
1127 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1128 && isset($GLOBALS['sql_limit_to_append'])) {
1129 $query_base = $analyzed_display_query[0]['section_before_limit']
1130 . "\n" . $GLOBALS['sql_limit_to_append']
1131 . $analyzed_display_query[0]['section_after_limit'];
1132 // Need to reparse query
1133 $parsed_sql = PMA_SQP_parse($query_base);
1137 if (! empty($GLOBALS['show_as_php'])) {
1138 $query_base = '$sql = "' . $query_base;
1139 } elseif (! empty($GLOBALS['validatequery'])) {
1140 $query_base = PMA_validateSQL($query_base);
1141 } elseif (isset($parsed_sql)) {
1142 $query_base = PMA_formatSql($parsed_sql, $query_base);
1145 // Prepares links that may be displayed to edit/explain the query
1146 // (don't go to default pages, we must go to the page
1147 // where the query box is available)
1149 // Basic url query part
1150 $url_params = array();
1151 if (strlen($GLOBALS['db'])) {
1152 $url_params['db'] = $GLOBALS['db'];
1153 if (strlen($GLOBALS['table'])) {
1154 $url_params['table'] = $GLOBALS['table'];
1155 $edit_link = 'tbl_sql.php';
1156 } else {
1157 $edit_link = 'db_sql.php';
1159 } else {
1160 $edit_link = 'server_sql.php';
1163 // Want to have the query explained (Mike Beck 2002-05-22)
1164 // but only explain a SELECT (that has not been explained)
1165 /* SQL-Parser-Analyzer */
1166 $explain_link = '';
1167 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1168 $explain_params = $url_params;
1169 // Detect if we are validating as well
1170 // To preserve the validate uRL data
1171 if (! empty($GLOBALS['validatequery'])) {
1172 $explain_params['validatequery'] = 1;
1175 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1176 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1177 $_message = $GLOBALS['strExplain'];
1178 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1179 $explain_params['sql_query'] = substr($sql_query, 8);
1180 $_message = $GLOBALS['strNoExplain'];
1182 if (isset($explain_params['sql_query'])) {
1183 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1184 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1186 } //show explain
1188 $url_params['sql_query'] = $sql_query;
1189 $url_params['show_query'] = 1;
1191 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1192 if ($cfg['EditInWindow'] == true) {
1193 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1194 } else {
1195 $onclick = '';
1198 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1199 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1200 } else {
1201 $edit_link = '';
1204 $url_qpart = PMA_generate_common_url($url_params);
1206 // Also we would like to get the SQL formed in some nice
1207 // php-code (Mike Beck 2002-05-22)
1208 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1209 $php_params = $url_params;
1211 if (! empty($GLOBALS['show_as_php'])) {
1212 $_message = $GLOBALS['strNoPhp'];
1213 } else {
1214 $php_params['show_as_php'] = 1;
1215 $_message = $GLOBALS['strPhp'];
1218 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1219 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1221 if (isset($GLOBALS['show_as_php'])) {
1222 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1223 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1225 } else {
1226 $php_link = '';
1227 } //show as php
1229 // Refresh query
1230 if (! empty($cfg['SQLQuery']['Refresh'])
1231 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1232 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1233 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1234 } else {
1235 $refresh_link = '';
1236 } //show as php
1238 if (! empty($cfg['SQLValidator']['use'])
1239 && ! empty($cfg['SQLQuery']['Validate'])) {
1240 $validate_params = $url_params;
1241 if (!empty($GLOBALS['validatequery'])) {
1242 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1243 } else {
1244 $validate_params['validatequery'] = 1;
1245 $validate_message = $GLOBALS['strValidateSQL'] ;
1248 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1249 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1250 } else {
1251 $validate_link = '';
1252 } //validator
1254 echo '<code class="sql">';
1255 if ($query_too_big) {
1256 echo $shortened_query_base;
1257 } else {
1258 echo $query_base;
1261 //Clean up the end of the PHP
1262 if (! empty($GLOBALS['show_as_php'])) {
1263 echo '";';
1265 echo '</code>';
1267 echo '<div class="tools">';
1268 // avoid displaying a Profiling checkbox that could
1269 // be checked, which would reexecute an INSERT, for example
1270 if (! empty($refresh_link)) {
1271 PMA_profilingCheckbox($sql_query);
1273 $inline_edit = "<script type=\"text/javascript\">\n" .
1274 "//<![CDATA[\n" .
1275 "document.write('[<a href=\"#\" title=\"" .
1276 PMA_escapeJsString(__('Inline edit of this query')) .
1277 "\" id=\"inline_edit\">" .
1278 PMA_escapeJsString(__('Inline')) .
1279 "</a>]');\n" .
1280 "//]]>\n" .
1281 "</script>";
1282 echo $inline_edit . $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1283 echo '</div>';
1285 echo '</div><br />' . "\n";
1286 } // end of the 'PMA_showMessage()' function
1289 * Verifies if current MySQL server supports profiling
1291 * @uses $_SESSION['profiling_supported'] for caching
1292 * @uses $GLOBALS['server']
1293 * @uses PMA_DBI_fetch_value()
1294 * @uses PMA_MYSQL_INT_VERSION
1295 * @uses defined()
1296 * @access public
1297 * @return boolean whether profiling is supported
1300 function PMA_profilingSupported()
1302 if (! PMA_cacheExists('profiling_supported', true)) {
1303 // 5.0.37 has profiling but for example, 5.1.20 does not
1304 // (avoid a trip to the server for MySQL before 5.0.37)
1305 // and do not set a constant as we might be switching servers
1306 if (defined('PMA_MYSQL_INT_VERSION')
1307 && PMA_MYSQL_INT_VERSION >= 50037
1308 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1309 PMA_cacheSet('profiling_supported', true, true);
1310 } else {
1311 PMA_cacheSet('profiling_supported', false, true);
1315 return PMA_cacheGet('profiling_supported', true);
1319 * Displays a form with the Profiling checkbox
1321 * @param string $sql_query
1322 * @access public
1325 function PMA_profilingCheckbox($sql_query)
1327 if (PMA_profilingSupported()) {
1328 echo '<form action="sql.php" method="post">' . "\n";
1329 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1330 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1331 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1332 PMA_display_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1333 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1334 echo '</form>' . "\n";
1339 * Displays the results of SHOW PROFILE
1341 * @param array the results
1342 * @access public
1345 function PMA_profilingResults($profiling_results)
1347 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1348 echo '<table>' . "\n";
1349 echo ' <tr>' . "\n";
1350 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1351 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1352 echo ' </tr>' . "\n";
1354 foreach($profiling_results as $one_result) {
1355 echo ' <tr>' . "\n";
1356 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1357 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1359 echo '</table>' . "\n";
1360 echo '</fieldset>' . "\n";
1364 * Formats $value to byte view
1366 * @param double the value to format
1367 * @param integer the sensitiveness
1368 * @param integer the number of decimals to retain
1370 * @return array the formatted value and its unit
1372 * @access public
1374 * @version 1.2 - 18 July 2002
1376 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1378 $dh = PMA_pow(10, $comma);
1379 $li = PMA_pow(10, $limes);
1380 $return_value = $value;
1381 $unit = $GLOBALS['byteUnits'][0];
1383 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1384 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1385 // use 1024.0 to avoid integer overflow on 64-bit machines
1386 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1387 $unit = $GLOBALS['byteUnits'][$d];
1388 break 1;
1389 } // end if
1390 } // end for
1392 if ($unit != $GLOBALS['byteUnits'][0]) {
1393 // if the unit is not bytes (as represented in current language)
1394 // reformat with max length of 5
1395 // 4th parameter=true means do not reformat if value < 1
1396 $return_value = PMA_formatNumber($value, 5, $comma, true);
1397 } else {
1398 // do not reformat, just handle the locale
1399 $return_value = PMA_formatNumber($value, 0);
1402 return array(trim($return_value), $unit);
1403 } // end of the 'PMA_formatByteDown' function
1406 * Formats $value to the given length and appends SI prefixes
1407 * $comma is not substracted from the length
1408 * with a $length of 0 no truncation occurs, number is only formated
1409 * to the current locale
1411 * examples:
1412 * <code>
1413 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1414 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1415 * echo PMA_formatNumber(-0.003, 6); // -3 m
1416 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1417 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1418 * echo PMA_formatNumber(0, 6); // 0
1420 * </code>
1421 * @param double $value the value to format
1422 * @param integer $length the max length
1423 * @param integer $comma the number of decimals to retain
1424 * @param boolean $only_down do not reformat numbers below 1
1426 * @return string the formatted value and its unit
1428 * @access public
1430 * @version 1.1.0 - 2005-10-27
1432 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1434 //number_format is not multibyte safe, str_replace is safe
1435 if ($length === 0) {
1436 return str_replace(array(',', '.'),
1437 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1438 number_format($value, $comma));
1441 // this units needs no translation, ISO
1442 $units = array(
1443 -8 => 'y',
1444 -7 => 'z',
1445 -6 => 'a',
1446 -5 => 'f',
1447 -4 => 'p',
1448 -3 => 'n',
1449 -2 => '&micro;',
1450 -1 => 'm',
1451 0 => ' ',
1452 1 => 'k',
1453 2 => 'M',
1454 3 => 'G',
1455 4 => 'T',
1456 5 => 'P',
1457 6 => 'E',
1458 7 => 'Z',
1459 8 => 'Y'
1462 // we need at least 3 digits to be displayed
1463 if (3 > $length + $comma) {
1464 $length = 3 - $comma;
1467 // check for negative value to retain sign
1468 if ($value < 0) {
1469 $sign = '-';
1470 $value = abs($value);
1471 } else {
1472 $sign = '';
1475 $dh = PMA_pow(10, $comma);
1476 $li = PMA_pow(10, $length);
1477 $unit = $units[0];
1479 if ($value >= 1) {
1480 for ($d = 8; $d >= 0; $d--) {
1481 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1482 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1483 $unit = $units[$d];
1484 break 1;
1485 } // end if
1486 } // end for
1487 } elseif (!$only_down && (float) $value !== 0.0) {
1488 for ($d = -8; $d <= 8; $d++) {
1489 // force using pow() because of the negative exponent
1490 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1491 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1492 $unit = $units[$d];
1493 break 1;
1494 } // end if
1495 } // end for
1496 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1498 //number_format is not multibyte safe, str_replace is safe
1499 $value = str_replace(array(',', '.'),
1500 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1501 number_format($value, $comma));
1503 return $sign . $value . ' ' . $unit;
1504 } // end of the 'PMA_formatNumber' function
1507 * Returns the number of bytes when a formatted size is given
1509 * @param string $size the size expression (for example 8MB)
1510 * @uses PMA_pow()
1511 * @return integer The numerical part of the expression (for example 8)
1513 function PMA_extractValueFromFormattedSize($formatted_size)
1515 $return_value = -1;
1517 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1518 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1519 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1520 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1521 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1522 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1524 return $return_value;
1525 }// end of the 'PMA_extractValueFromFormattedSize' function
1528 * Writes localised date
1530 * @param string the current timestamp
1532 * @return string the formatted date
1534 * @access public
1536 function PMA_localisedDate($timestamp = -1, $format = '')
1538 global $datefmt, $month, $day_of_week;
1540 if ($format == '') {
1541 $format = $datefmt;
1544 if ($timestamp == -1) {
1545 $timestamp = time();
1548 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1549 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1551 return strftime($date, $timestamp);
1552 } // end of the 'PMA_localisedDate()' function
1556 * returns a tab for tabbed navigation.
1557 * If the variables $link and $args ar left empty, an inactive tab is created
1559 * @uses $GLOBALS['PMA_PHP_SELF']
1560 * @uses $GLOBALS['strEmpty']
1561 * @uses $GLOBALS['strDrop']
1562 * @uses $GLOBALS['active_page']
1563 * @uses $GLOBALS['url_query']
1564 * @uses $cfg['MainPageIconic']
1565 * @uses $GLOBALS['pmaThemeImage']
1566 * @uses PMA_generate_common_url()
1567 * @uses E_USER_NOTICE
1568 * @uses htmlentities()
1569 * @uses urlencode()
1570 * @uses sprintf()
1571 * @uses trigger_error()
1572 * @uses array_merge()
1573 * @uses basename()
1574 * @param array $tab array with all options
1575 * @param array $url_params
1576 * @return string html code for one tab, a link if valid otherwise a span
1577 * @access public
1579 function PMA_generate_html_tab($tab, $url_params = array())
1581 // default values
1582 $defaults = array(
1583 'text' => '',
1584 'class' => '',
1585 'active' => false,
1586 'link' => '',
1587 'sep' => '?',
1588 'attr' => '',
1589 'args' => '',
1590 'warning' => '',
1591 'fragment' => '',
1594 $tab = array_merge($defaults, $tab);
1596 // determine additionnal style-class
1597 if (empty($tab['class'])) {
1598 if ($tab['text'] == $GLOBALS['strEmpty']
1599 || $tab['text'] == $GLOBALS['strDrop']) {
1600 $tab['class'] = 'caution';
1601 } elseif (! empty($tab['active'])
1602 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1603 $tab['class'] = 'active';
1604 } elseif (empty($GLOBALS['active_page'])
1605 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1606 && empty($tab['warning'])) {
1607 $tab['class'] = 'active';
1611 if (!empty($tab['warning'])) {
1612 $tab['class'] .= ' warning';
1613 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1616 // If there are any tab specific URL parameters, merge those with the general URL parameters
1617 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1618 $url_params = array_merge($url_params, $tab['url_params']);
1621 // build the link
1622 if (!empty($tab['link'])) {
1623 $tab['link'] = htmlentities($tab['link']);
1624 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1625 if (! empty($tab['args'])) {
1626 foreach ($tab['args'] as $param => $value) {
1627 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1628 . urlencode($value);
1633 if (! empty($tab['fragment'])) {
1634 $tab['link'] .= $tab['fragment'];
1637 // display icon, even if iconic is disabled but the link-text is missing
1638 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1639 && isset($tab['icon'])) {
1640 // avoid generating an alt tag, because it only illustrates
1641 // the text that follows and if browser does not display
1642 // images, the text is duplicated
1643 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1644 .'%1$s" width="16" height="16" alt="" />%2$s';
1645 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1647 // check to not display an empty link-text
1648 elseif (empty($tab['text'])) {
1649 $tab['text'] = '?';
1650 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1651 E_USER_NOTICE);
1654 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1656 if (!empty($tab['link'])) {
1657 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1658 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1659 . $tab['text'] . '</a>';
1660 } else {
1661 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1662 . $tab['text'] . '</span>';
1665 $out .= '</li>';
1666 return $out;
1667 } // end of the 'PMA_generate_html_tab()' function
1670 * returns html-code for a tab navigation
1672 * @uses PMA_generate_html_tab()
1673 * @uses htmlentities()
1674 * @param array $tabs one element per tab
1675 * @param string $url_params
1676 * @return string html-code for tab-navigation
1678 function PMA_generate_html_tabs($tabs, $url_params)
1680 $tag_id = 'topmenu';
1681 $tab_navigation =
1682 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1683 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1685 foreach ($tabs as $tab) {
1686 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1689 $tab_navigation .=
1690 '</ul>' . "\n"
1691 .'<div class="clearfloat"></div>'
1692 .'</div>' . "\n";
1694 return $tab_navigation;
1699 * Displays a link, or a button if the link's URL is too large, to
1700 * accommodate some browsers' limitations
1702 * @param string the URL
1703 * @param string the link message
1704 * @param mixed $tag_params string: js confirmation
1705 * array: additional tag params (f.e. style="")
1706 * @param boolean $new_form we set this to false when we are already in
1707 * a form, to avoid generating nested forms
1709 * @return string the results to be echoed or saved in an array
1711 function PMA_linkOrButton($url, $message, $tag_params = array(),
1712 $new_form = true, $strip_img = false, $target = '')
1714 if (! is_array($tag_params)) {
1715 $tmp = $tag_params;
1716 $tag_params = array();
1717 if (!empty($tmp)) {
1718 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1720 unset($tmp);
1722 if (! empty($target)) {
1723 $tag_params['target'] = htmlentities($target);
1726 $tag_params_strings = array();
1727 foreach ($tag_params as $par_name => $par_value) {
1728 // htmlspecialchars() only on non javascript
1729 $par_value = substr($par_name, 0, 2) == 'on'
1730 ? $par_value
1731 : htmlspecialchars($par_value);
1732 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1735 if (strlen($url) <= $GLOBALS['cfg']['LinkLengthLimit']) {
1736 // no whitespace within an <a> else Safari will make it part of the link
1737 $ret = "\n" . '<a href="' . $url . '" '
1738 . implode(' ', $tag_params_strings) . '>'
1739 . $message . '</a>' . "\n";
1740 } else {
1741 // no spaces (linebreaks) at all
1742 // or after the hidden fields
1743 // IE will display them all
1745 // add class=link to submit button
1746 if (empty($tag_params['class'])) {
1747 $tag_params['class'] = 'link';
1750 // decode encoded url separators
1751 $separator = PMA_get_arg_separator();
1752 // on most places separator is still hard coded ...
1753 if ($separator !== '&') {
1754 // ... so always replace & with $separator
1755 $url = str_replace(htmlentities('&'), $separator, $url);
1756 $url = str_replace('&', $separator, $url);
1758 $url = str_replace(htmlentities($separator), $separator, $url);
1759 // end decode
1761 $url_parts = parse_url($url);
1762 $query_parts = explode($separator, $url_parts['query']);
1763 if ($new_form) {
1764 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1765 . ' method="post"' . $target . ' style="display: inline;">';
1766 $subname_open = '';
1767 $subname_close = '';
1768 $submit_name = '';
1769 } else {
1770 $query_parts[] = 'redirect=' . $url_parts['path'];
1771 if (empty($GLOBALS['subform_counter'])) {
1772 $GLOBALS['subform_counter'] = 0;
1774 $GLOBALS['subform_counter']++;
1775 $ret = '';
1776 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1777 $subname_close = ']';
1778 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1780 foreach ($query_parts as $query_pair) {
1781 list($eachvar, $eachval) = explode('=', $query_pair);
1782 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1783 . $subname_close . '" value="'
1784 . htmlspecialchars(urldecode($eachval)) . '" />';
1785 } // end while
1787 if (stristr($message, '<img')) {
1788 if ($strip_img) {
1789 $message = trim(strip_tags($message));
1790 $ret .= '<input type="submit"' . $submit_name . ' '
1791 . implode(' ', $tag_params_strings)
1792 . ' value="' . htmlspecialchars($message) . '" />';
1793 } else {
1794 $displayed_message = htmlspecialchars(
1795 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1796 $message));
1797 $ret .= '<input type="image"' . $submit_name . ' '
1798 . implode(' ', $tag_params_strings)
1799 . ' src="' . preg_replace(
1800 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1801 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1803 } else {
1804 $message = trim(strip_tags($message));
1805 $ret .= '<input type="submit"' . $submit_name . ' '
1806 . implode(' ', $tag_params_strings)
1807 . ' value="' . htmlspecialchars($message) . '" />';
1809 if ($new_form) {
1810 $ret .= '</form>';
1812 } // end if... else...
1814 return $ret;
1815 } // end of the 'PMA_linkOrButton()' function
1819 * Returns a given timespan value in a readable format.
1821 * @uses $GLOBALS['timespanfmt']
1822 * @uses sprintf()
1823 * @uses floor()
1824 * @param int the timespan
1826 * @return string the formatted value
1828 function PMA_timespanFormat($seconds)
1830 $return_string = '';
1831 $days = floor($seconds / 86400);
1832 if ($days > 0) {
1833 $seconds -= $days * 86400;
1835 $hours = floor($seconds / 3600);
1836 if ($days > 0 || $hours > 0) {
1837 $seconds -= $hours * 3600;
1839 $minutes = floor($seconds / 60);
1840 if ($days > 0 || $hours > 0 || $minutes > 0) {
1841 $seconds -= $minutes * 60;
1843 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1847 * Takes a string and outputs each character on a line for itself. Used
1848 * mainly for horizontalflipped display mode.
1849 * Takes care of special html-characters.
1850 * Fulfills todo-item
1851 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1853 * @todo add a multibyte safe function PMA_STR_split()
1854 * @uses strlen
1855 * @param string The string
1856 * @param string The Separator (defaults to "<br />\n")
1858 * @access public
1859 * @return string The flipped string
1861 function PMA_flipstring($string, $Separator = "<br />\n")
1863 $format_string = '';
1864 $charbuff = false;
1866 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1867 $char = $string{$i};
1868 $append = false;
1870 if ($char == '&') {
1871 $format_string .= $charbuff;
1872 $charbuff = $char;
1873 } elseif ($char == ';' && !empty($charbuff)) {
1874 $format_string .= $charbuff . $char;
1875 $charbuff = false;
1876 $append = true;
1877 } elseif (! empty($charbuff)) {
1878 $charbuff .= $char;
1879 } else {
1880 $format_string .= $char;
1881 $append = true;
1884 // do not add separator after the last character
1885 if ($append && ($i != $str_len - 1)) {
1886 $format_string .= $Separator;
1890 return $format_string;
1895 * Function added to avoid path disclosures.
1896 * Called by each script that needs parameters, it displays
1897 * an error message and, by default, stops the execution.
1899 * Not sure we could use a strMissingParameter message here,
1900 * would have to check if the error message file is always available
1902 * @todo localize error message
1903 * @todo use PMA_fatalError() if $die === true?
1904 * @uses PMA_getenv()
1905 * @uses header_meta_style.inc.php
1906 * @uses $GLOBALS['PMA_PHP_SELF']
1907 * basename
1908 * @param array The names of the parameters needed by the calling
1909 * script.
1910 * @param boolean Stop the execution?
1911 * (Set this manually to false in the calling script
1912 * until you know all needed parameters to check).
1913 * @param boolean Whether to include this list in checking for special params.
1914 * @global string path to current script
1915 * @global boolean flag whether any special variable was required
1917 * @access public
1919 function PMA_checkParameters($params, $die = true, $request = true)
1921 global $checked_special;
1923 if (!isset($checked_special)) {
1924 $checked_special = false;
1927 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1928 $found_error = false;
1929 $error_message = '';
1931 foreach ($params as $param) {
1932 if ($request && $param != 'db' && $param != 'table') {
1933 $checked_special = true;
1936 if (!isset($GLOBALS[$param])) {
1937 $error_message .= $reported_script_name
1938 . ': Missing parameter: ' . $param
1939 . ' <a href="./Documentation.html#faqmissingparameters"'
1940 . ' target="documentation"> (FAQ 2.8)</a><br />';
1941 $found_error = true;
1944 if ($found_error) {
1946 * display html meta tags
1948 require_once './libraries/header_meta_style.inc.php';
1949 echo '</head><body><p>' . $error_message . '</p></body></html>';
1950 if ($die) {
1951 exit();
1954 } // end function
1957 * Function to generate unique condition for specified row.
1959 * @uses $GLOBALS['analyzed_sql'][0]
1960 * @uses PMA_DBI_field_flags()
1961 * @uses PMA_backquote()
1962 * @uses PMA_sqlAddslashes()
1963 * @uses PMA_printable_bit_value()
1964 * @uses stristr()
1965 * @uses bin2hex()
1966 * @uses preg_replace()
1967 * @param resource $handle current query result
1968 * @param integer $fields_cnt number of fields
1969 * @param array $fields_meta meta information about fields
1970 * @param array $row current row
1971 * @param boolean $force_unique generate condition only on pk or unique
1973 * @access public
1974 * @return string the calculated condition and whether condition is unique
1976 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1978 $primary_key = '';
1979 $unique_key = '';
1980 $nonprimary_condition = '';
1981 $preferred_condition = '';
1983 for ($i = 0; $i < $fields_cnt; ++$i) {
1984 $condition = '';
1985 $field_flags = PMA_DBI_field_flags($handle, $i);
1986 $meta = $fields_meta[$i];
1988 // do not use a column alias in a condition
1989 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1990 $meta->orgname = $meta->name;
1992 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1993 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1994 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1995 as $select_expr) {
1996 // need (string) === (string)
1997 // '' !== 0 but '' == 0
1998 if ((string) $select_expr['alias'] === (string) $meta->name) {
1999 $meta->orgname = $select_expr['column'];
2000 break;
2001 } // end if
2002 } // end foreach
2006 // Do not use a table alias in a condition.
2007 // Test case is:
2008 // select * from galerie x WHERE
2009 //(select count(*) from galerie y where y.datum=x.datum)>1
2011 // But orgtable is present only with mysqli extension so the
2012 // fix is only for mysqli.
2013 // Also, do not use the original table name if we are dealing with
2014 // a view because this view might be updatable.
2015 // (The isView() verification should not be costly in most cases
2016 // because there is some caching in the function).
2017 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
2018 $meta->table = $meta->orgtable;
2021 // to fix the bug where float fields (primary or not)
2022 // can't be matched because of the imprecision of
2023 // floating comparison, use CONCAT
2024 // (also, the syntax "CONCAT(field) IS NULL"
2025 // that we need on the next "if" will work)
2026 if ($meta->type == 'real') {
2027 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
2028 . PMA_backquote($meta->orgname) . ') ';
2029 } else {
2030 $condition = ' ' . PMA_backquote($meta->table) . '.'
2031 . PMA_backquote($meta->orgname) . ' ';
2032 } // end if... else...
2034 if (!isset($row[$i]) || is_null($row[$i])) {
2035 $condition .= 'IS NULL AND';
2036 } else {
2037 // timestamp is numeric on some MySQL 4.1
2038 if ($meta->numeric && $meta->type != 'timestamp') {
2039 $condition .= '= ' . $row[$i] . ' AND';
2040 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2041 // hexify only if this is a true not empty BLOB or a BINARY
2042 && stristr($field_flags, 'BINARY')
2043 && !empty($row[$i])) {
2044 // do not waste memory building a too big condition
2045 if (strlen($row[$i]) < 1000) {
2046 // use a CAST if possible, to avoid problems
2047 // if the field contains wildcard characters % or _
2048 $condition .= '= CAST(0x' . bin2hex($row[$i])
2049 . ' AS BINARY) AND';
2050 } else {
2051 // this blob won't be part of the final condition
2052 $condition = '';
2054 } elseif ($meta->type == 'bit') {
2055 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2056 } else {
2057 $condition .= '= \''
2058 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2061 if ($meta->primary_key > 0) {
2062 $primary_key .= $condition;
2063 } elseif ($meta->unique_key > 0) {
2064 $unique_key .= $condition;
2066 $nonprimary_condition .= $condition;
2067 } // end for
2069 // Correction University of Virginia 19991216:
2070 // prefer primary or unique keys for condition,
2071 // but use conjunction of all values if no primary key
2072 $clause_is_unique = true;
2073 if ($primary_key) {
2074 $preferred_condition = $primary_key;
2075 } elseif ($unique_key) {
2076 $preferred_condition = $unique_key;
2077 } elseif (! $force_unique) {
2078 $preferred_condition = $nonprimary_condition;
2079 $clause_is_unique = false;
2082 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2083 return(array($where_clause, $clause_is_unique));
2084 } // end function
2087 * Generate a button or image tag
2089 * @uses PMA_USR_BROWSER_AGENT
2090 * @uses $GLOBALS['pmaThemeImage']
2091 * @uses $GLOBALS['cfg']['PropertiesIconic']
2092 * @param string name of button element
2093 * @param string class of button element
2094 * @param string name of image element
2095 * @param string text to display
2096 * @param string image to display
2098 * @access public
2100 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2101 $image)
2103 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2104 echo ' <input type="submit" name="' . $button_name . '"'
2105 .' value="' . htmlspecialchars($text) . '"'
2106 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2107 return;
2110 /* Opera has trouble with <input type="image"> */
2111 /* IE has trouble with <button> */
2112 if (PMA_USR_BROWSER_AGENT != 'IE') {
2113 echo '<button class="' . $button_class . '" type="submit"'
2114 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2115 .' title="' . htmlspecialchars($text) . '">' . "\n"
2116 . PMA_getIcon($image, $text)
2117 .'</button>' . "\n";
2118 } else {
2119 echo '<input type="image" name="' . $image_name . '" value="'
2120 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2121 . $image . '" />'
2122 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2124 } // end function
2127 * Generate a pagination selector for browsing resultsets
2129 * @todo $url is not javascript escaped!?
2130 * @uses $GLOBALS['strPageNumber']
2131 * @uses range()
2132 * @param string URL for the JavaScript
2133 * @param string Number of rows in the pagination set
2134 * @param string current page number
2135 * @param string number of total pages
2136 * @param string If the number of pages is lower than this
2137 * variable, no pages will be omitted in
2138 * pagination
2139 * @param string How many rows at the beginning should always
2140 * be shown?
2141 * @param string How many rows at the end should always
2142 * be shown?
2143 * @param string Percentage of calculation page offsets to
2144 * hop to a next page
2145 * @param string Near the current page, how many pages should
2146 * be considered "nearby" and displayed as
2147 * well?
2148 * @param string The prompt to display (sometimes empty)
2150 * @access public
2152 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2153 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2154 $range = 10, $prompt = '')
2156 $increment = floor($nbTotalPage / $percent);
2157 $pageNowMinusRange = ($pageNow - $range);
2158 $pageNowPlusRange = ($pageNow + $range);
2160 $gotopage = $prompt
2161 . ' <select name="pos" onchange="goToUrl(this, \''
2162 . $url . '\');">' . "\n";
2163 if ($nbTotalPage < $showAll) {
2164 $pages = range(1, $nbTotalPage);
2165 } else {
2166 $pages = array();
2168 // Always show first X pages
2169 for ($i = 1; $i <= $sliceStart; $i++) {
2170 $pages[] = $i;
2173 // Always show last X pages
2174 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2175 $pages[] = $i;
2178 // Based on the number of results we add the specified
2179 // $percent percentage to each page number,
2180 // so that we have a representing page number every now and then to
2181 // immediately jump to specific pages.
2182 // As soon as we get near our currently chosen page ($pageNow -
2183 // $range), every page number will be shown.
2184 $i = $sliceStart;
2185 $x = $nbTotalPage - $sliceEnd;
2186 $met_boundary = false;
2187 while ($i <= $x) {
2188 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2189 // If our pageselector comes near the current page, we use 1
2190 // counter increments
2191 $i++;
2192 $met_boundary = true;
2193 } else {
2194 // We add the percentage increment to our current page to
2195 // hop to the next one in range
2196 $i += $increment;
2198 // Make sure that we do not cross our boundaries.
2199 if ($i > $pageNowMinusRange && ! $met_boundary) {
2200 $i = $pageNowMinusRange;
2204 if ($i > 0 && $i <= $x) {
2205 $pages[] = $i;
2209 // Since because of ellipsing of the current page some numbers may be double,
2210 // we unify our array:
2211 sort($pages);
2212 $pages = array_unique($pages);
2215 foreach ($pages as $i) {
2216 if ($i == $pageNow) {
2217 $selected = 'selected="selected" style="font-weight: bold"';
2218 } else {
2219 $selected = '';
2221 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2224 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2226 return $gotopage;
2227 } // end function
2231 * Generate navigation for a list
2233 * @todo use $pos from $_url_params
2234 * @uses $GLOBALS['strPageNumber']
2235 * @uses range()
2236 * @param integer number of elements in the list
2237 * @param integer current position in the list
2238 * @param array url parameters
2239 * @param string script name for form target
2240 * @param string target frame
2241 * @param integer maximum number of elements to display from the list
2243 * @access public
2245 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2247 if ($max_count < $count) {
2248 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2249 echo $GLOBALS['strPageNumber'];
2250 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2252 // Move to the beginning or to the previous page
2253 if ($pos > 0) {
2254 // patch #474210 - part 1
2255 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2256 $caption1 = '&lt;&lt;';
2257 $caption2 = ' &lt; ';
2258 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2259 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2260 } else {
2261 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2262 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2263 $title1 = '';
2264 $title2 = '';
2265 } // end if... else...
2266 $_url_params['pos'] = 0;
2267 echo '<a' . $title1 . ' href="' . $script
2268 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2269 . $caption1 . '</a>';
2270 $_url_params['pos'] = $pos - $max_count;
2271 echo '<a' . $title2 . ' href="' . $script
2272 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2273 . $caption2 . '</a>';
2276 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2277 echo PMA_generate_common_hidden_inputs($_url_params);
2278 echo PMA_pageselector(
2279 $script . PMA_generate_common_url($_url_params) . '&amp;',
2280 $max_count,
2281 floor(($pos + 1) / $max_count) + 1,
2282 ceil($count / $max_count));
2283 echo '</form>';
2285 if ($pos + $max_count < $count) {
2286 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2287 $caption3 = ' &gt; ';
2288 $caption4 = '&gt;&gt;';
2289 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2290 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2291 } else {
2292 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2293 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2294 $title3 = '';
2295 $title4 = '';
2296 } // end if... else...
2297 $_url_params['pos'] = $pos + $max_count;
2298 echo '<a' . $title3 . ' href="' . $script
2299 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2300 . $caption3 . '</a>';
2301 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2302 if ($_url_params['pos'] == $count) {
2303 $_url_params['pos'] = $count - $max_count;
2305 echo '<a' . $title4 . ' href="' . $script
2306 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2307 . $caption4 . '</a>';
2309 echo "\n";
2310 if ('frame_navigation' == $frame) {
2311 echo '</div>' . "\n";
2317 * replaces %u in given path with current user name
2319 * example:
2320 * <code>
2321 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2323 * </code>
2324 * @uses $cfg['Server']['user']
2325 * @uses substr()
2326 * @uses str_replace()
2327 * @param string $dir with wildcard for user
2328 * @return string per user directory
2330 function PMA_userDir($dir)
2332 // add trailing slash
2333 if (substr($dir, -1) != '/') {
2334 $dir .= '/';
2337 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2341 * returns html code for db link to default db page
2343 * @uses $cfg['DefaultTabDatabase']
2344 * @uses $GLOBALS['db']
2345 * @uses $GLOBALS['strJumpToDB']
2346 * @uses PMA_generate_common_url()
2347 * @uses PMA_unescape_mysql_wildcards()
2348 * @uses strlen()
2349 * @uses sprintf()
2350 * @uses htmlspecialchars()
2351 * @param string $database
2352 * @return string html link to default db page
2354 function PMA_getDbLink($database = null)
2356 if (!strlen($database)) {
2357 if (!strlen($GLOBALS['db'])) {
2358 return '';
2360 $database = $GLOBALS['db'];
2361 } else {
2362 $database = PMA_unescape_mysql_wildcards($database);
2365 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2366 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2367 .htmlspecialchars($database) . '</a>';
2371 * Displays a lightbulb hint explaining a known external bug
2372 * that affects a functionality
2374 * @uses PMA_MYSQL_INT_VERSION
2375 * @uses $GLOBALS['strKnownExternalBug']
2376 * @uses PMA_showHint()
2377 * @uses sprintf()
2378 * @param string $functionality localized message explaining the func.
2379 * @param string $component 'mysql' (eventually, 'php')
2380 * @param string $minimum_version of this component
2381 * @param string $bugref bug reference for this component
2383 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2385 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2386 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2391 * Generates and echoes an HTML checkbox
2393 * @param string $html_field_name the checkbox HTML field
2394 * @param string $label
2395 * @param boolean $checked is it initially checked?
2396 * @param boolean $onclick should it submit the form on click?
2398 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2400 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>';
2404 * Generates and echoes a set of radio HTML fields
2406 * @uses htmlspecialchars()
2407 * @param string $html_field_name the radio HTML field
2408 * @param array $choices the choices values and labels
2409 * @param string $checked_choice the choice to check by default
2410 * @param boolean $line_break whether to add an HTML line break after a choice
2411 * @param boolean $escape_label whether to use htmlspecialchars() on label
2412 * @param string $class enclose each choice with a div of this class
2414 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2415 foreach ($choices as $choice_value => $choice_label) {
2416 if (! empty($class)) {
2417 echo '<div class="' . $class . '">';
2419 $html_field_id = $html_field_name . '_' . $choice_value;
2420 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2421 if ($choice_value == $checked_choice) {
2422 echo ' checked="checked"';
2424 echo ' />' . "\n";
2425 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2426 if ($line_break) {
2427 echo '<br />';
2429 if (! empty($class)) {
2430 echo '</div>';
2432 echo "\n";
2437 * Generates and returns an HTML dropdown
2439 * @uses htmlspecialchars()
2440 * @param string $select_name
2441 * @param array $choices the choices values
2442 * @param string $active_choice the choice to select by default
2443 * @param string $id the id of the select element; can be different in case
2444 * the dropdown is present more than once on the page
2445 * @todo support titles
2447 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2449 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2450 foreach ($choices as $one_choice_value => $one_choice_label) {
2451 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2452 if ($one_choice_value == $active_choice) {
2453 $result .= ' selected="selected"';
2455 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2457 $result .= '</select>';
2458 return $result;
2462 * Generates a slider effect (jQjuery)
2463 * Takes care of generating the initial <div> and the link
2464 * controlling the slider; you have to generate the </div> yourself
2465 * after the sliding section.
2467 * @uses $GLOBALS['cfg']['InitialSlidersState']
2468 * @param string $id the id of the <div> on which to apply the effect
2469 * @param string $message the message to show as a link
2471 function PMA_generate_slider_effect($id, $message)
2473 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2474 echo '<div id="' . $id . '">';
2475 return;
2478 <script type="text/javascript">
2479 // <![CDATA[
2480 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none; overflow:auto;"' : ''; ?>>');
2482 function PMA_set_status_label_<?php echo $id; ?>() {
2483 if ($('#<?php echo $id; ?>').css('display') == 'none') {
2484 $('#anchor_status_<?php echo $id; ?>').text('+ ');
2485 } else {
2486 $('#anchor_status_<?php echo $id; ?>').text('- ');
2490 $(document).ready(function() {
2492 $('<span id="anchor_status_<?php echo $id; ?>"><span>')
2493 .insertBefore('#<?php echo $id; ?>')
2495 PMA_set_status_label_<?php echo $id; ?>();
2497 $('<a href="#<?php echo $id; ?>" id="anchor_<?php echo $id; ?>"><?php echo htmlspecialchars($message); ?></a>')
2498 .insertBefore('#<?php echo $id; ?>')
2499 .click(function() {
2500 // the callback should be the 4th parameter but
2501 // it only works as the second parameter
2502 $('#<?php echo $id; ?>').toggle('drop', function() {
2503 PMA_set_status_label_<?php echo $id; ?>();
2507 //]]>
2508 </script>
2509 <noscript>
2510 <div id="<?php echo $id; ?>">
2511 </noscript>
2512 <?php
2516 * Verifies if something is cached in the session
2518 * @param string $var
2519 * @param scalar $server
2520 * @return boolean
2522 function PMA_cacheExists($var, $server = 0)
2524 if (true === $server) {
2525 $server = $GLOBALS['server'];
2527 return isset($_SESSION['cache']['server_' . $server][$var]);
2531 * Gets cached information from the session
2533 * @param string $var
2534 * @param scalar $server
2535 * @return mixed
2537 function PMA_cacheGet($var, $server = 0)
2539 if (true === $server) {
2540 $server = $GLOBALS['server'];
2542 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2543 return $_SESSION['cache']['server_' . $server][$var];
2544 } else {
2545 return null;
2550 * Caches information in the session
2552 * @param string $var
2553 * @param mixed $val
2554 * @param integer $server
2555 * @return mixed
2557 function PMA_cacheSet($var, $val = null, $server = 0)
2559 if (true === $server) {
2560 $server = $GLOBALS['server'];
2562 $_SESSION['cache']['server_' . $server][$var] = $val;
2566 * Removes cached information from the session
2568 * @param string $var
2569 * @param scalar $server
2571 function PMA_cacheUnset($var, $server = 0)
2573 if (true === $server) {
2574 $server = $GLOBALS['server'];
2576 unset($_SESSION['cache']['server_' . $server][$var]);
2580 * Converts a bit value to printable format;
2581 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2582 * function because in PHP, decbin() supports only 32 bits
2584 * @uses ceil()
2585 * @uses decbin()
2586 * @uses ord()
2587 * @uses substr()
2588 * @uses sprintf()
2589 * @param numeric $value coming from a BIT field
2590 * @param integer $length
2591 * @return string the printable value
2593 function PMA_printable_bit_value($value, $length) {
2594 $printable = '';
2595 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2596 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2598 $printable = substr($printable, -$length);
2599 return $printable;
2603 * Verifies whether the value contains a non-printable character
2605 * @uses preg_match()
2606 * @param string $value
2607 * @return boolean
2609 function PMA_contains_nonprintable_ascii($value) {
2610 return preg_match('@[^[:print:]]@', $value);
2614 * Converts a BIT type default value
2615 * for example, b'010' becomes 010
2617 * @uses strtr()
2618 * @param string $bit_default_value
2619 * @return string the converted value
2621 function PMA_convert_bit_default_value($bit_default_value) {
2622 return strtr($bit_default_value, array("b" => "", "'" => ""));
2626 * Extracts the various parts from a field type spec
2628 * @uses strpos()
2629 * @uses chop()
2630 * @uses substr()
2631 * @param string $fieldspec
2632 * @return array associative array containing type, spec_in_brackets
2633 * and possibly enum_set_values (another array)
2635 function PMA_extractFieldSpec($fieldspec) {
2636 $first_bracket_pos = strpos($fieldspec, '(');
2637 if ($first_bracket_pos) {
2638 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2639 // convert to lowercase just to be sure
2640 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2641 } else {
2642 $type = $fieldspec;
2643 $spec_in_brackets = '';
2646 if ('enum' == $type || 'set' == $type) {
2647 // Define our working vars
2648 $enum_set_values = array();
2649 $working = "";
2650 $in_string = false;
2651 $index = 0;
2653 // While there is another character to process
2654 while (isset($fieldspec[$index])) {
2655 // Grab the char to look at
2656 $char = $fieldspec[$index];
2658 // If it is a single quote, needs to be handled specially
2659 if ($char == "'") {
2660 // If we are not currently in a string, begin one
2661 if (! $in_string) {
2662 $in_string = true;
2663 $working = "";
2664 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2665 } else {
2666 // Check out the next character (if possible)
2667 $has_next = isset($fieldspec[$index + 1]);
2668 $next = $has_next ? $fieldspec[$index + 1] : null;
2670 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2671 if (! $has_next || $next != "'") {
2672 $enum_set_values[] = $working;
2673 $in_string = false;
2675 // Otherwise, this is a 'double quote', and can be added to the working string
2676 } elseif ($next == "'") {
2677 $working .= "'";
2678 // Skip the next char; we already know what it is
2679 $index++;
2682 // escaping of a quote?
2683 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2684 $working .= "'";
2685 $index++;
2686 // Otherwise, add it to our working string like normal
2687 } else {
2688 $working .= $char;
2690 // Increment character index
2691 $index++;
2692 } // end while
2693 } else {
2694 $enum_set_values = array();
2697 return array(
2698 'type' => $type,
2699 'spec_in_brackets' => $spec_in_brackets,
2700 'enum_set_values' => $enum_set_values
2705 * Verifies if this table's engine supports foreign keys
2707 * @uses strtoupper()
2708 * @param string $engine
2709 * @return boolean
2711 function PMA_foreignkey_supported($engine) {
2712 $engine = strtoupper($engine);
2713 if ('INNODB' == $engine || 'PBXT' == $engine) {
2714 return true;
2715 } else {
2716 return false;
2721 * Replaces some characters by a displayable equivalent
2723 * @uses str_replace()
2724 * @param string $content
2725 * @return string the content with characters replaced
2727 function PMA_replace_binary_contents($content) {
2728 $result = str_replace("\x00", '\0', $content);
2729 $result = str_replace("\x08", '\b', $result);
2730 $result = str_replace("\x0a", '\n', $result);
2731 $result = str_replace("\x0d", '\r', $result);
2732 $result = str_replace("\x1a", '\Z', $result);
2733 return $result;
2738 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2740 * @uses strpos()
2741 * @return string with the chars replaced
2744 function PMA_duplicateFirstNewline($string){
2745 $first_occurence = strpos($string, "\r\n");
2746 if ($first_occurence === 0){
2747 $string = "\n".$string;
2749 return $string;
2753 * get the action word corresponding to a script name
2754 * in order to display it as a title in navigation panel
2756 * @uses $GLOBALS
2757 * @param string a valid value for $cfg['LeftDefaultTabTable']
2758 * or $cfg['DefaultTabTable']
2759 * or $cfg['DefaultTabDatabase']
2761 function PMA_getTitleForTarget($target) {
2762 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];
2765 function PMA_js($code, $print=true)
2767 // these generated newlines are needed
2768 $out = '';
2769 $out .= '<script type="text/javascript">'."\n";
2770 $out .= "\n" . '// <![CDATA[' . "\n";
2771 $out .= $code;
2772 $out .= "\n" . '// ]]>' . "\n";
2773 $out .= '</script>'."\n";
2775 if ($print)
2776 echo $out;
2778 return $out;