bug #2974067 non-binary fields shown as hex
[phpmyadmin/madhuracj.git] / libraries / common.lib.php
blob2e184746d67c0325098a33ef3b4aa3f254f000b7
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(trim($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 // If there are any tab specific URL parameters, merge those with the general URL parameters
1595 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1596 $url_params = array_merge($url_params, $tab['url_params']);
1599 // build the link
1600 if (!empty($tab['link'])) {
1601 $tab['link'] = htmlentities($tab['link']);
1602 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1603 if (! empty($tab['args'])) {
1604 foreach ($tab['args'] as $param => $value) {
1605 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1606 . urlencode($value);
1611 if (! empty($tab['fragment'])) {
1612 $tab['link'] .= $tab['fragment'];
1615 // display icon, even if iconic is disabled but the link-text is missing
1616 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1617 && isset($tab['icon'])) {
1618 // avoid generating an alt tag, because it only illustrates
1619 // the text that follows and if browser does not display
1620 // images, the text is duplicated
1621 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1622 .'%1$s" width="16" height="16" alt="" />%2$s';
1623 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1625 // check to not display an empty link-text
1626 elseif (empty($tab['text'])) {
1627 $tab['text'] = '?';
1628 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1629 E_USER_NOTICE);
1632 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1634 if (!empty($tab['link'])) {
1635 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1636 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1637 . $tab['text'] . '</a>';
1638 } else {
1639 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1640 . $tab['text'] . '</span>';
1643 $out .= '</li>';
1644 return $out;
1645 } // end of the 'PMA_generate_html_tab()' function
1648 * returns html-code for a tab navigation
1650 * @uses PMA_generate_html_tab()
1651 * @uses htmlentities()
1652 * @param array $tabs one element per tab
1653 * @param string $url_params
1654 * @return string html-code for tab-navigation
1656 function PMA_generate_html_tabs($tabs, $url_params)
1658 $tag_id = 'topmenu';
1659 $tab_navigation =
1660 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1661 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1663 foreach ($tabs as $tab) {
1664 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1667 $tab_navigation .=
1668 '</ul>' . "\n"
1669 .'<div class="clearfloat"></div>'
1670 .'</div>' . "\n";
1672 return $tab_navigation;
1677 * Displays a link, or a button if the link's URL is too large, to
1678 * accommodate some browsers' limitations
1680 * @param string the URL
1681 * @param string the link message
1682 * @param mixed $tag_params string: js confirmation
1683 * array: additional tag params (f.e. style="")
1684 * @param boolean $new_form we set this to false when we are already in
1685 * a form, to avoid generating nested forms
1687 * @return string the results to be echoed or saved in an array
1689 function PMA_linkOrButton($url, $message, $tag_params = array(),
1690 $new_form = true, $strip_img = false, $target = '')
1692 if (! is_array($tag_params)) {
1693 $tmp = $tag_params;
1694 $tag_params = array();
1695 if (!empty($tmp)) {
1696 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1698 unset($tmp);
1700 if (! empty($target)) {
1701 $tag_params['target'] = htmlentities($target);
1704 $tag_params_strings = array();
1705 foreach ($tag_params as $par_name => $par_value) {
1706 // htmlspecialchars() only on non javascript
1707 $par_value = substr($par_name, 0, 2) == 'on'
1708 ? $par_value
1709 : htmlspecialchars($par_value);
1710 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1713 if (strlen($url) <= $GLOBALS['cfg']['LinkLengthLimit']) {
1714 // no whitespace within an <a> else Safari will make it part of the link
1715 $ret = "\n" . '<a href="' . $url . '" '
1716 . implode(' ', $tag_params_strings) . '>'
1717 . $message . '</a>' . "\n";
1718 } else {
1719 // no spaces (linebreaks) at all
1720 // or after the hidden fields
1721 // IE will display them all
1723 // add class=link to submit button
1724 if (empty($tag_params['class'])) {
1725 $tag_params['class'] = 'link';
1728 // decode encoded url separators
1729 $separator = PMA_get_arg_separator();
1730 // on most places separator is still hard coded ...
1731 if ($separator !== '&') {
1732 // ... so always replace & with $separator
1733 $url = str_replace(htmlentities('&'), $separator, $url);
1734 $url = str_replace('&', $separator, $url);
1736 $url = str_replace(htmlentities($separator), $separator, $url);
1737 // end decode
1739 $url_parts = parse_url($url);
1740 $query_parts = explode($separator, $url_parts['query']);
1741 if ($new_form) {
1742 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1743 . ' method="post"' . $target . ' style="display: inline;">';
1744 $subname_open = '';
1745 $subname_close = '';
1746 $submit_name = '';
1747 } else {
1748 $query_parts[] = 'redirect=' . $url_parts['path'];
1749 if (empty($GLOBALS['subform_counter'])) {
1750 $GLOBALS['subform_counter'] = 0;
1752 $GLOBALS['subform_counter']++;
1753 $ret = '';
1754 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1755 $subname_close = ']';
1756 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1758 foreach ($query_parts as $query_pair) {
1759 list($eachvar, $eachval) = explode('=', $query_pair);
1760 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1761 . $subname_close . '" value="'
1762 . htmlspecialchars(urldecode($eachval)) . '" />';
1763 } // end while
1765 if (stristr($message, '<img')) {
1766 if ($strip_img) {
1767 $message = trim(strip_tags($message));
1768 $ret .= '<input type="submit"' . $submit_name . ' '
1769 . implode(' ', $tag_params_strings)
1770 . ' value="' . htmlspecialchars($message) . '" />';
1771 } else {
1772 $displayed_message = htmlspecialchars(
1773 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1774 $message));
1775 $ret .= '<input type="image"' . $submit_name . ' '
1776 . implode(' ', $tag_params_strings)
1777 . ' src="' . preg_replace(
1778 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1779 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1781 } else {
1782 $message = trim(strip_tags($message));
1783 $ret .= '<input type="submit"' . $submit_name . ' '
1784 . implode(' ', $tag_params_strings)
1785 . ' value="' . htmlspecialchars($message) . '" />';
1787 if ($new_form) {
1788 $ret .= '</form>';
1790 } // end if... else...
1792 return $ret;
1793 } // end of the 'PMA_linkOrButton()' function
1797 * Returns a given timespan value in a readable format.
1799 * @uses $GLOBALS['timespanfmt']
1800 * @uses sprintf()
1801 * @uses floor()
1802 * @param int the timespan
1804 * @return string the formatted value
1806 function PMA_timespanFormat($seconds)
1808 $return_string = '';
1809 $days = floor($seconds / 86400);
1810 if ($days > 0) {
1811 $seconds -= $days * 86400;
1813 $hours = floor($seconds / 3600);
1814 if ($days > 0 || $hours > 0) {
1815 $seconds -= $hours * 3600;
1817 $minutes = floor($seconds / 60);
1818 if ($days > 0 || $hours > 0 || $minutes > 0) {
1819 $seconds -= $minutes * 60;
1821 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1825 * Takes a string and outputs each character on a line for itself. Used
1826 * mainly for horizontalflipped display mode.
1827 * Takes care of special html-characters.
1828 * Fulfills todo-item
1829 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1831 * @todo add a multibyte safe function PMA_STR_split()
1832 * @uses strlen
1833 * @param string The string
1834 * @param string The Separator (defaults to "<br />\n")
1836 * @access public
1837 * @author Garvin Hicking <me@supergarv.de>
1838 * @return string The flipped string
1840 function PMA_flipstring($string, $Separator = "<br />\n")
1842 $format_string = '';
1843 $charbuff = false;
1845 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1846 $char = $string{$i};
1847 $append = false;
1849 if ($char == '&') {
1850 $format_string .= $charbuff;
1851 $charbuff = $char;
1852 } elseif ($char == ';' && !empty($charbuff)) {
1853 $format_string .= $charbuff . $char;
1854 $charbuff = false;
1855 $append = true;
1856 } elseif (! empty($charbuff)) {
1857 $charbuff .= $char;
1858 } else {
1859 $format_string .= $char;
1860 $append = true;
1863 // do not add separator after the last character
1864 if ($append && ($i != $str_len - 1)) {
1865 $format_string .= $Separator;
1869 return $format_string;
1874 * Function added to avoid path disclosures.
1875 * Called by each script that needs parameters, it displays
1876 * an error message and, by default, stops the execution.
1878 * Not sure we could use a strMissingParameter message here,
1879 * would have to check if the error message file is always available
1881 * @todo localize error message
1882 * @todo use PMA_fatalError() if $die === true?
1883 * @uses PMA_getenv()
1884 * @uses header_meta_style.inc.php
1885 * @uses $GLOBALS['PMA_PHP_SELF']
1886 * basename
1887 * @param array The names of the parameters needed by the calling
1888 * script.
1889 * @param boolean Stop the execution?
1890 * (Set this manually to false in the calling script
1891 * until you know all needed parameters to check).
1892 * @param boolean Whether to include this list in checking for special params.
1893 * @global string path to current script
1894 * @global boolean flag whether any special variable was required
1896 * @access public
1897 * @author Marc Delisle (lem9@users.sourceforge.net)
1899 function PMA_checkParameters($params, $die = true, $request = true)
1901 global $checked_special;
1903 if (!isset($checked_special)) {
1904 $checked_special = false;
1907 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1908 $found_error = false;
1909 $error_message = '';
1911 foreach ($params as $param) {
1912 if ($request && $param != 'db' && $param != 'table') {
1913 $checked_special = true;
1916 if (!isset($GLOBALS[$param])) {
1917 $error_message .= $reported_script_name
1918 . ': Missing parameter: ' . $param
1919 . ' <a href="./Documentation.html#faqmissingparameters"'
1920 . ' target="documentation"> (FAQ 2.8)</a><br />';
1921 $found_error = true;
1924 if ($found_error) {
1926 * display html meta tags
1928 require_once './libraries/header_meta_style.inc.php';
1929 echo '</head><body><p>' . $error_message . '</p></body></html>';
1930 if ($die) {
1931 exit();
1934 } // end function
1937 * Function to generate unique condition for specified row.
1939 * @uses $GLOBALS['analyzed_sql'][0]
1940 * @uses PMA_DBI_field_flags()
1941 * @uses PMA_backquote()
1942 * @uses PMA_sqlAddslashes()
1943 * @uses PMA_printable_bit_value()
1944 * @uses stristr()
1945 * @uses bin2hex()
1946 * @uses preg_replace()
1947 * @param resource $handle current query result
1948 * @param integer $fields_cnt number of fields
1949 * @param array $fields_meta meta information about fields
1950 * @param array $row current row
1951 * @param boolean $force_unique generate condition only on pk or unique
1953 * @access public
1954 * @author Michal Cihar (michal@cihar.com) and others...
1955 * @return string the calculated condition and whether condition is unique
1957 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1959 $primary_key = '';
1960 $unique_key = '';
1961 $nonprimary_condition = '';
1962 $preferred_condition = '';
1964 for ($i = 0; $i < $fields_cnt; ++$i) {
1965 $condition = '';
1966 $field_flags = PMA_DBI_field_flags($handle, $i);
1967 $meta = $fields_meta[$i];
1969 // do not use a column alias in a condition
1970 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1971 $meta->orgname = $meta->name;
1973 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1974 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1975 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1976 as $select_expr) {
1977 // need (string) === (string)
1978 // '' !== 0 but '' == 0
1979 if ((string) $select_expr['alias'] === (string) $meta->name) {
1980 $meta->orgname = $select_expr['column'];
1981 break;
1982 } // end if
1983 } // end foreach
1987 // Do not use a table alias in a condition.
1988 // Test case is:
1989 // select * from galerie x WHERE
1990 //(select count(*) from galerie y where y.datum=x.datum)>1
1992 // But orgtable is present only with mysqli extension so the
1993 // fix is only for mysqli.
1994 // Also, do not use the original table name if we are dealing with
1995 // a view because this view might be updatable.
1996 // (The isView() verification should not be costly in most cases
1997 // because there is some caching in the function).
1998 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1999 $meta->table = $meta->orgtable;
2002 // to fix the bug where float fields (primary or not)
2003 // can't be matched because of the imprecision of
2004 // floating comparison, use CONCAT
2005 // (also, the syntax "CONCAT(field) IS NULL"
2006 // that we need on the next "if" will work)
2007 if ($meta->type == 'real') {
2008 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
2009 . PMA_backquote($meta->orgname) . ') ';
2010 } else {
2011 $condition = ' ' . PMA_backquote($meta->table) . '.'
2012 . PMA_backquote($meta->orgname) . ' ';
2013 } // end if... else...
2015 if (!isset($row[$i]) || is_null($row[$i])) {
2016 $condition .= 'IS NULL AND';
2017 } else {
2018 // timestamp is numeric on some MySQL 4.1
2019 if ($meta->numeric && $meta->type != 'timestamp') {
2020 $condition .= '= ' . $row[$i] . ' AND';
2021 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2022 // hexify only if this is a true not empty BLOB or a BINARY
2023 && stristr($field_flags, 'BINARY')
2024 && !empty($row[$i])) {
2025 // do not waste memory building a too big condition
2026 if (strlen($row[$i]) < 1000) {
2027 // use a CAST if possible, to avoid problems
2028 // if the field contains wildcard characters % or _
2029 $condition .= '= CAST(0x' . bin2hex($row[$i])
2030 . ' AS BINARY) AND';
2031 } else {
2032 // this blob won't be part of the final condition
2033 $condition = '';
2035 } elseif ($meta->type == 'bit') {
2036 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2037 } else {
2038 $condition .= '= \''
2039 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2042 if ($meta->primary_key > 0) {
2043 $primary_key .= $condition;
2044 } elseif ($meta->unique_key > 0) {
2045 $unique_key .= $condition;
2047 $nonprimary_condition .= $condition;
2048 } // end for
2050 // Correction University of Virginia 19991216:
2051 // prefer primary or unique keys for condition,
2052 // but use conjunction of all values if no primary key
2053 $clause_is_unique = true;
2054 if ($primary_key) {
2055 $preferred_condition = $primary_key;
2056 } elseif ($unique_key) {
2057 $preferred_condition = $unique_key;
2058 } elseif (! $force_unique) {
2059 $preferred_condition = $nonprimary_condition;
2060 $clause_is_unique = false;
2063 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2064 return(array($where_clause, $clause_is_unique));
2065 } // end function
2068 * Generate a button or image tag
2070 * @uses PMA_USR_BROWSER_AGENT
2071 * @uses $GLOBALS['pmaThemeImage']
2072 * @uses $GLOBALS['cfg']['PropertiesIconic']
2073 * @param string name of button element
2074 * @param string class of button element
2075 * @param string name of image element
2076 * @param string text to display
2077 * @param string image to display
2079 * @access public
2080 * @author Michal Cihar (michal@cihar.com)
2082 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2083 $image)
2085 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2086 echo ' <input type="submit" name="' . $button_name . '"'
2087 .' value="' . htmlspecialchars($text) . '"'
2088 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2089 return;
2092 /* Opera has trouble with <input type="image"> */
2093 /* IE has trouble with <button> */
2094 if (PMA_USR_BROWSER_AGENT != 'IE') {
2095 echo '<button class="' . $button_class . '" type="submit"'
2096 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2097 .' title="' . htmlspecialchars($text) . '">' . "\n"
2098 . PMA_getIcon($image, $text)
2099 .'</button>' . "\n";
2100 } else {
2101 echo '<input type="image" name="' . $image_name . '" value="'
2102 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2103 . $image . '" />'
2104 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2106 } // end function
2109 * Generate a pagination selector for browsing resultsets
2111 * @todo $url is not javascript escaped!?
2112 * @uses $GLOBALS['strPageNumber']
2113 * @uses range()
2114 * @param string URL for the JavaScript
2115 * @param string Number of rows in the pagination set
2116 * @param string current page number
2117 * @param string number of total pages
2118 * @param string If the number of pages is lower than this
2119 * variable, no pages will be omitted in
2120 * pagination
2121 * @param string How many rows at the beginning should always
2122 * be shown?
2123 * @param string How many rows at the end should always
2124 * be shown?
2125 * @param string Percentage of calculation page offsets to
2126 * hop to a next page
2127 * @param string Near the current page, how many pages should
2128 * be considered "nearby" and displayed as
2129 * well?
2130 * @param string The prompt to display (sometimes empty)
2132 * @access public
2133 * @author Garvin Hicking (pma@supergarv.de)
2135 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2136 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2137 $range = 10, $prompt = '')
2139 $increment = floor($nbTotalPage / $percent);
2140 $pageNowMinusRange = ($pageNow - $range);
2141 $pageNowPlusRange = ($pageNow + $range);
2143 $gotopage = $prompt
2144 . ' <select name="pos" onchange="goToUrl(this, \''
2145 . $url . '\');">' . "\n";
2146 if ($nbTotalPage < $showAll) {
2147 $pages = range(1, $nbTotalPage);
2148 } else {
2149 $pages = array();
2151 // Always show first X pages
2152 for ($i = 1; $i <= $sliceStart; $i++) {
2153 $pages[] = $i;
2156 // Always show last X pages
2157 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2158 $pages[] = $i;
2161 // garvin: Based on the number of results we add the specified
2162 // $percent percentage to each page number,
2163 // so that we have a representing page number every now and then to
2164 // immediately jump to specific pages.
2165 // As soon as we get near our currently chosen page ($pageNow -
2166 // $range), every page number will be shown.
2167 $i = $sliceStart;
2168 $x = $nbTotalPage - $sliceEnd;
2169 $met_boundary = false;
2170 while ($i <= $x) {
2171 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2172 // If our pageselector comes near the current page, we use 1
2173 // counter increments
2174 $i++;
2175 $met_boundary = true;
2176 } else {
2177 // We add the percentage increment to our current page to
2178 // hop to the next one in range
2179 $i += $increment;
2181 // Make sure that we do not cross our boundaries.
2182 if ($i > $pageNowMinusRange && ! $met_boundary) {
2183 $i = $pageNowMinusRange;
2187 if ($i > 0 && $i <= $x) {
2188 $pages[] = $i;
2192 // Since because of ellipsing of the current page some numbers may be double,
2193 // we unify our array:
2194 sort($pages);
2195 $pages = array_unique($pages);
2198 foreach ($pages as $i) {
2199 if ($i == $pageNow) {
2200 $selected = 'selected="selected" style="font-weight: bold"';
2201 } else {
2202 $selected = '';
2204 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2207 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2209 return $gotopage;
2210 } // end function
2214 * Generate navigation for a list
2216 * @todo use $pos from $_url_params
2217 * @uses $GLOBALS['strPageNumber']
2218 * @uses range()
2219 * @param integer number of elements in the list
2220 * @param integer current position in the list
2221 * @param array url parameters
2222 * @param string script name for form target
2223 * @param string target frame
2224 * @param integer maximum number of elements to display from the list
2226 * @access public
2228 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2230 if ($max_count < $count) {
2231 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2232 echo $GLOBALS['strPageNumber'];
2233 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2235 // Move to the beginning or to the previous page
2236 if ($pos > 0) {
2237 // loic1: patch #474210 from Gosha Sakovich - part 1
2238 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2239 $caption1 = '&lt;&lt;';
2240 $caption2 = ' &lt; ';
2241 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2242 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2243 } else {
2244 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2245 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2246 $title1 = '';
2247 $title2 = '';
2248 } // end if... else...
2249 $_url_params['pos'] = 0;
2250 echo '<a' . $title1 . ' href="' . $script
2251 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2252 . $caption1 . '</a>';
2253 $_url_params['pos'] = $pos - $max_count;
2254 echo '<a' . $title2 . ' href="' . $script
2255 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2256 . $caption2 . '</a>';
2259 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2260 echo PMA_generate_common_hidden_inputs($_url_params);
2261 echo PMA_pageselector(
2262 $script . PMA_generate_common_url($_url_params) . '&amp;',
2263 $max_count,
2264 floor(($pos + 1) / $max_count) + 1,
2265 ceil($count / $max_count));
2266 echo '</form>';
2268 if ($pos + $max_count < $count) {
2269 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2270 $caption3 = ' &gt; ';
2271 $caption4 = '&gt;&gt;';
2272 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2273 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2274 } else {
2275 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2276 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2277 $title3 = '';
2278 $title4 = '';
2279 } // end if... else...
2280 $_url_params['pos'] = $pos + $max_count;
2281 echo '<a' . $title3 . ' href="' . $script
2282 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2283 . $caption3 . '</a>';
2284 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2285 if ($_url_params['pos'] == $count) {
2286 $_url_params['pos'] = $count - $max_count;
2288 echo '<a' . $title4 . ' href="' . $script
2289 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2290 . $caption4 . '</a>';
2292 echo "\n";
2293 if ('frame_navigation' == $frame) {
2294 echo '</div>' . "\n";
2300 * replaces %u in given path with current user name
2302 * example:
2303 * <code>
2304 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2306 * </code>
2307 * @uses $cfg['Server']['user']
2308 * @uses substr()
2309 * @uses str_replace()
2310 * @param string $dir with wildcard for user
2311 * @return string per user directory
2313 function PMA_userDir($dir)
2315 // add trailing slash
2316 if (substr($dir, -1) != '/') {
2317 $dir .= '/';
2320 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2324 * returns html code for db link to default db page
2326 * @uses $cfg['DefaultTabDatabase']
2327 * @uses $GLOBALS['db']
2328 * @uses $GLOBALS['strJumpToDB']
2329 * @uses PMA_generate_common_url()
2330 * @uses PMA_unescape_mysql_wildcards()
2331 * @uses strlen()
2332 * @uses sprintf()
2333 * @uses htmlspecialchars()
2334 * @param string $database
2335 * @return string html link to default db page
2337 function PMA_getDbLink($database = null)
2339 if (!strlen($database)) {
2340 if (!strlen($GLOBALS['db'])) {
2341 return '';
2343 $database = $GLOBALS['db'];
2344 } else {
2345 $database = PMA_unescape_mysql_wildcards($database);
2348 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2349 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2350 .htmlspecialchars($database) . '</a>';
2354 * Displays a lightbulb hint explaining a known external bug
2355 * that affects a functionality
2357 * @uses PMA_MYSQL_INT_VERSION
2358 * @uses $GLOBALS['strKnownExternalBug']
2359 * @uses PMA_showHint()
2360 * @uses sprintf()
2361 * @param string $functionality localized message explaining the func.
2362 * @param string $component 'mysql' (eventually, 'php')
2363 * @param string $minimum_version of this component
2364 * @param string $bugref bug reference for this component
2366 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2368 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2369 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2374 * Generates and echoes an HTML checkbox
2376 * @param string $html_field_name the checkbox HTML field
2377 * @param string $label
2378 * @param boolean $checked is it initially checked?
2379 * @param boolean $onclick should it submit the form on click?
2381 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2383 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>';
2387 * Generates and echoes a set of radio HTML fields
2389 * @uses htmlspecialchars()
2390 * @param string $html_field_name the radio HTML field
2391 * @param array $choices the choices values and labels
2392 * @param string $checked_choice the choice to check by default
2393 * @param boolean $line_break whether to add an HTML line break after a choice
2394 * @param boolean $escape_label whether to use htmlspecialchars() on label
2395 * @param string $class enclose each choice with a div of this class
2397 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2398 foreach ($choices as $choice_value => $choice_label) {
2399 if (! empty($class)) {
2400 echo '<div class="' . $class . '">';
2402 $html_field_id = $html_field_name . '_' . $choice_value;
2403 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2404 if ($choice_value == $checked_choice) {
2405 echo ' checked="checked"';
2407 echo ' />' . "\n";
2408 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2409 if ($line_break) {
2410 echo '<br />';
2412 if (! empty($class)) {
2413 echo '</div>';
2415 echo "\n";
2420 * Generates and returns an HTML dropdown
2422 * @uses htmlspecialchars()
2423 * @param string $select_name
2424 * @param array $choices the choices values
2425 * @param string $active_choice the choice to select by default
2426 * @param string $id the id of the select element; can be different in case
2427 * the dropdown is present more than once on the page
2428 * @todo support titles
2430 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2432 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2433 foreach ($choices as $one_choice_value => $one_choice_label) {
2434 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2435 if ($one_choice_value == $active_choice) {
2436 $result .= ' selected="selected"';
2438 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2440 $result .= '</select>';
2441 return $result;
2445 * Generates a slider effect (Mootools)
2446 * Takes care of generating the initial <div> and the link
2447 * controlling the slider; you have to generate the </div> yourself
2448 * after the sliding section.
2450 * @uses $GLOBALS['cfg']['InitialSlidersState']
2451 * @param string $id the id of the <div> on which to apply the effect
2452 * @param string $message the message to show as a link
2454 function PMA_generate_slider_effect($id, $message)
2456 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2457 echo '<div id="' . $id . '">';
2458 return;
2461 <script type="text/javascript">
2462 // <![CDATA[
2463 window.addEvent('domready', function(){
2464 var status = {
2465 'true': '- ',
2466 'false': '+ '
2469 var anchor<?php echo $id; ?> = new Element('a', {
2470 'id': 'toggle_<?php echo $id; ?>',
2471 'href': 'javascript:void(0)',
2472 'events': {
2473 'click': function(){
2474 mySlide<?php echo $id; ?>.toggle();
2479 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2480 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2482 var slider_status<?php echo $id; ?> = new Element('span', {
2483 'id': 'slider_status_<?php echo $id; ?>'
2485 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2486 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2488 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2489 <?php
2490 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2492 mySlide<?php echo $id; ?>.hide();
2493 <?php
2496 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2497 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2500 $('<?php echo $id; ?>').style.display="block";
2502 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2503 //]]>
2504 </script>
2505 <noscript>
2506 <div id="<?php echo $id; ?>" />
2507 </noscript>
2508 <?php
2512 * Verifies if something is cached in the session
2514 * @param string $var
2515 * @param scalar $server
2516 * @return boolean
2518 function PMA_cacheExists($var, $server = 0)
2520 if (true === $server) {
2521 $server = $GLOBALS['server'];
2523 return isset($_SESSION['cache']['server_' . $server][$var]);
2527 * Gets cached information from the session
2529 * @param string $var
2530 * @param scalar $server
2531 * @return mixed
2533 function PMA_cacheGet($var, $server = 0)
2535 if (true === $server) {
2536 $server = $GLOBALS['server'];
2538 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2539 return $_SESSION['cache']['server_' . $server][$var];
2540 } else {
2541 return null;
2546 * Caches information in the session
2548 * @param string $var
2549 * @param mixed $val
2550 * @param integer $server
2551 * @return mixed
2553 function PMA_cacheSet($var, $val = null, $server = 0)
2555 if (true === $server) {
2556 $server = $GLOBALS['server'];
2558 $_SESSION['cache']['server_' . $server][$var] = $val;
2562 * Removes cached information from the session
2564 * @param string $var
2565 * @param scalar $server
2567 function PMA_cacheUnset($var, $server = 0)
2569 if (true === $server) {
2570 $server = $GLOBALS['server'];
2572 unset($_SESSION['cache']['server_' . $server][$var]);
2576 * Converts a bit value to printable format;
2577 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2578 * function because in PHP, decbin() supports only 32 bits
2580 * @uses ceil()
2581 * @uses decbin()
2582 * @uses ord()
2583 * @uses substr()
2584 * @uses sprintf()
2585 * @param numeric $value coming from a BIT field
2586 * @param integer $length
2587 * @return string the printable value
2589 function PMA_printable_bit_value($value, $length) {
2590 $printable = '';
2591 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2592 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2594 $printable = substr($printable, -$length);
2595 return $printable;
2599 * Verifies whether the value contains a non-printable character
2601 * @uses preg_match()
2602 * @param string $value
2603 * @return boolean
2605 function PMA_contains_nonprintable_ascii($value) {
2606 return preg_match('@[^[:print:]]@', $value);
2610 * Converts a BIT type default value
2611 * for example, b'010' becomes 010
2613 * @uses strtr()
2614 * @param string $bit_default_value
2615 * @return string the converted value
2617 function PMA_convert_bit_default_value($bit_default_value) {
2618 return strtr($bit_default_value, array("b" => "", "'" => ""));
2622 * Extracts the various parts from a field type spec
2624 * @uses strpos()
2625 * @uses chop()
2626 * @uses substr()
2627 * @param string $fieldspec
2628 * @return array associative array containing type, spec_in_brackets
2629 * and possibly enum_set_values (another array)
2630 * @author Marc Delisle
2631 * @author Joshua Hogendorn
2633 function PMA_extractFieldSpec($fieldspec) {
2634 $first_bracket_pos = strpos($fieldspec, '(');
2635 if ($first_bracket_pos) {
2636 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2637 // convert to lowercase just to be sure
2638 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2639 } else {
2640 $type = $fieldspec;
2641 $spec_in_brackets = '';
2644 if ('enum' == $type || 'set' == $type) {
2645 // Define our working vars
2646 $enum_set_values = array();
2647 $working = "";
2648 $in_string = false;
2649 $index = 0;
2651 // While there is another character to process
2652 while (isset($fieldspec[$index])) {
2653 // Grab the char to look at
2654 $char = $fieldspec[$index];
2656 // If it is a single quote, needs to be handled specially
2657 if ($char == "'") {
2658 // If we are not currently in a string, begin one
2659 if (! $in_string) {
2660 $in_string = true;
2661 $working = "";
2662 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2663 } else {
2664 // Check out the next character (if possible)
2665 $has_next = isset($fieldspec[$index + 1]);
2666 $next = $has_next ? $fieldspec[$index + 1] : null;
2668 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2669 if (! $has_next || $next != "'") {
2670 $enum_set_values[] = $working;
2671 $in_string = false;
2673 // Otherwise, this is a 'double quote', and can be added to the working string
2674 } elseif ($next == "'") {
2675 $working .= "'";
2676 // Skip the next char; we already know what it is
2677 $index++;
2680 // escaping of a quote?
2681 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2682 $working .= "'";
2683 $index++;
2684 // Otherwise, add it to our working string like normal
2685 } else {
2686 $working .= $char;
2688 // Increment character index
2689 $index++;
2690 } // end while
2691 } else {
2692 $enum_set_values = array();
2695 return array(
2696 'type' => $type,
2697 'spec_in_brackets' => $spec_in_brackets,
2698 'enum_set_values' => $enum_set_values
2703 * Verifies if this table's engine supports foreign keys
2705 * @uses strtoupper()
2706 * @param string $engine
2707 * @return boolean
2709 function PMA_foreignkey_supported($engine) {
2710 $engine = strtoupper($engine);
2711 if ('INNODB' == $engine || 'PBXT' == $engine) {
2712 return true;
2713 } else {
2714 return false;
2719 * Replaces some characters by a displayable equivalent
2721 * @uses str_replace()
2722 * @param string $content
2723 * @return string the content with characters replaced
2725 function PMA_replace_binary_contents($content) {
2726 $result = str_replace("\x00", '\0', $content);
2727 $result = str_replace("\x08", '\b', $result);
2728 $result = str_replace("\x0a", '\n', $result);
2729 $result = str_replace("\x0d", '\r', $result);
2730 $result = str_replace("\x1a", '\Z', $result);
2731 return $result;
2736 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2738 * @uses strpos()
2739 * @return string with the chars replaced
2742 function PMA_duplicateFirstNewline($string){
2743 $first_occurence = strpos($string, "\r\n");
2744 if ($first_occurence === 0){
2745 $string = "\n".$string;
2747 return $string;
2751 * get the action word corresponding to a script name
2752 * in order to display it as a title in navigation panel
2754 * @uses $GLOBALS
2755 * @param string a valid value for $cfg['LeftDefaultTabTable']
2756 * or $cfg['DefaultTabTable']
2757 * or $cfg['DefaultTabDatabase']
2759 function PMA_getTitleForTarget($target) {
2760 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];
2763 /**
2764 * The function creates javascript and html code, which run given mootools/JS code when DOM is ready
2766 * @param String $code - Mootools/JS code, which will be run
2767 * @param boolena $print - If true, then the code is printed, otherwise is returned
2769 * @return String - the code
2771 function PMA_js_mootools_domready($code, $print=true)
2773 // these generated newlines are needed
2774 $out = '';
2775 $out .= '<script type="text/javascript">';
2776 $out .= "\n" . '// <![CDATA[' . "\n";
2777 $out .= 'window.addEvent(\'domready\',function() {';
2778 $out .= $code;
2779 $out .= '});';
2780 $out .= "\n" . '// ]]>' . "\n";
2781 $out .= '</script>';
2783 if ($print)
2784 echo $out;
2786 return $out;
2789 function PMA_js($code, $print=true)
2791 // these generated newlines are needed
2792 $out = '';
2793 $out .= '<script type="text/javascript">'."\n";
2794 $out .= "\n" . '// <![CDATA[' . "\n";
2795 $out .= $code;
2796 $out .= "\n" . '// ]]>' . "\n";
2797 $out .= '</script>'."\n";
2799 if ($print)
2800 echo $out;
2802 return $out;