bug #2042032 Cannot detect PmaAbsoluteUri correctly on Windows
[phpmyadmin/madhuracj.git] / libraries / common.lib.php
blob743f95642831ebb8246b89e75824f0cf44184748
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
441 * returns HTML for a footnote marker and add the messsage to the footnotes
443 * @uses $GLOBALS['footnotes']
444 * @param string the error message
445 * @return string html code for a footnote marker
446 * @access public
448 function PMA_showHint($message, $bbcode = false, $type = 'notice')
450 if ($message instanceof PMA_Message) {
451 $key = $message->getHash();
452 $type = $message->getLevel();
453 } else {
454 $key = md5($message);
457 if (! isset($GLOBALS['footnotes'][$key])) {
458 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
459 $GLOBALS['footnotes'] = array();
461 $nr = count($GLOBALS['footnotes']) + 1;
462 // this is the first instance of this message
463 $instance = 1;
464 $GLOBALS['footnotes'][$key] = array(
465 'note' => $message,
466 'type' => $type,
467 'nr' => $nr,
468 'instance' => $instance
470 } else {
471 $nr = $GLOBALS['footnotes'][$key]['nr'];
472 // another instance of this message (to ensure ids are unique)
473 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
476 if ($bbcode) {
477 return '[sup]' . $nr . '[/sup]';
480 // footnotemarker used in js/tooltip.js
481 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
485 * Displays a MySQL error message in the right frame.
487 * @uses footer.inc.php
488 * @uses header.inc.php
489 * @uses $GLOBALS['sql_query']
490 * @uses $GLOBALS['strError']
491 * @uses $GLOBALS['strSQLQuery']
492 * @uses $GLOBALS['pmaThemeImage']
493 * @uses $GLOBALS['strEdit']
494 * @uses $GLOBALS['strMySQLSaid']
495 * @uses $GLOBALS['cfg']['PropertiesIconic']
496 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
497 * @uses PMA_backquote()
498 * @uses PMA_DBI_getError()
499 * @uses PMA_formatSql()
500 * @uses PMA_generate_common_hidden_inputs()
501 * @uses PMA_generate_common_url()
502 * @uses PMA_showMySQLDocu()
503 * @uses PMA_sqlAddslashes()
504 * @uses PMA_SQP_isError()
505 * @uses PMA_SQP_parse()
506 * @uses PMA_SQP_getErrorString()
507 * @uses strtolower()
508 * @uses urlencode()
509 * @uses str_replace()
510 * @uses nl2br()
511 * @uses substr()
512 * @uses preg_replace()
513 * @uses preg_match()
514 * @uses explode()
515 * @uses implode()
516 * @uses is_array()
517 * @uses function_exists()
518 * @uses htmlspecialchars()
519 * @uses trim()
520 * @uses strstr()
521 * @param string the error message
522 * @param string the sql query that failed
523 * @param boolean whether to show a "modify" link or not
524 * @param string the "back" link url (full path is not required)
525 * @param boolean EXIT the page?
527 * @global string the curent table
528 * @global string the current db
530 * @access public
532 function PMA_mysqlDie($error_message = '', $the_query = '',
533 $is_modify_link = true, $back_url = '', $exit = true)
535 global $table, $db;
538 * start http output, display html headers
540 require_once './libraries/header.inc.php';
542 $error_msg_output = '';
544 if (!$error_message) {
545 $error_message = PMA_DBI_getError();
547 if (!$the_query && !empty($GLOBALS['sql_query'])) {
548 $the_query = $GLOBALS['sql_query'];
551 // --- Added to solve bug #641765
552 // Robbat2 - 12 January 2003, 9:46PM
553 // Revised, Robbat2 - 13 January 2003, 2:59PM
554 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
555 $formatted_sql = htmlspecialchars($the_query);
556 } elseif (empty($the_query) || trim($the_query) == '') {
557 $formatted_sql = '';
558 } else {
559 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
560 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
561 } else {
562 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
565 // ---
566 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
567 $error_msg_output .= ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
568 // if the config password is wrong, or the MySQL server does not
569 // respond, do not show the query that would reveal the
570 // username/password
571 if (!empty($the_query) && !strstr($the_query, 'connect')) {
572 // --- Added to solve bug #641765
573 // Robbat2 - 12 January 2003, 9:46PM
574 // Revised, Robbat2 - 13 January 2003, 2:59PM
575 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
576 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
577 $error_msg_output .= '<br />' . "\n";
579 // ---
580 // modified to show me the help on sql errors (Michael Keck)
581 $error_msg_output .= ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
582 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
583 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
585 if ($is_modify_link) {
586 $_url_params = array(
587 'sql_query' => $the_query,
588 'show_query' => 1,
590 if (strlen($table)) {
591 $_url_params['db'] = $db;
592 $_url_params['table'] = $table;
593 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
594 } elseif (strlen($db)) {
595 $_url_params['db'] = $db;
596 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
597 } else {
598 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
601 $error_msg_output .= $doedit_goto
602 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
603 . '</a>';
604 } // end if
605 $error_msg_output .= ' </p>' . "\n"
606 .' <p>' . "\n"
607 .' ' . $formatted_sql . "\n"
608 .' </p>' . "\n";
609 } // end if
611 $tmp_mysql_error = ''; // for saving the original $error_message
612 if (!empty($error_message)) {
613 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
614 $error_message = htmlspecialchars($error_message);
615 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
617 // modified to show me the help on error-returns (Michael Keck)
618 // (now error-messages-server)
619 $error_msg_output .= '<p>' . "\n"
620 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
621 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
622 . "\n"
623 . '</p>' . "\n";
625 // The error message will be displayed within a CODE segment.
626 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
628 // Replace all non-single blanks with their HTML-counterpart
629 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
630 // Replace TAB-characters with their HTML-counterpart
631 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
632 // Replace linebreaks
633 $error_message = nl2br($error_message);
635 $error_msg_output .= '<code>' . "\n"
636 . $error_message . "\n"
637 . '</code><br />' . "\n";
638 $error_msg_output .= '</div>';
640 $_SESSION['Import_message']['message'] = $error_msg_output;
642 if ($exit) {
643 if (! empty($back_url)) {
644 if (strstr($back_url, '?')) {
645 $back_url .= '&amp;no_history=true';
646 } else {
647 $back_url .= '?no_history=true';
650 $_SESSION['Import_message']['go_back_url'] = $back_url;
652 $error_msg_output .= '<fieldset class="tblFooters">';
653 $error_msg_output .= '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
654 $error_msg_output .= '</fieldset>' . "\n\n";
657 echo $error_msg_output;
659 * display footer and exit
662 require_once './libraries/footer.inc.php';
663 } else {
664 echo $error_msg_output;
666 } // end of the 'PMA_mysqlDie()' function
669 * Send HTTP header, taking IIS limits into account (600 seems ok)
671 * @uses PMA_IS_IIS
672 * @uses PMA_COMING_FROM_COOKIE_LOGIN
673 * @uses PMA_get_arg_separator()
674 * @uses SID
675 * @uses strlen()
676 * @uses strpos()
677 * @uses header()
678 * @uses session_write_close()
679 * @uses headers_sent()
680 * @uses function_exists()
681 * @uses debug_print_backtrace()
682 * @uses trigger_error()
683 * @uses defined()
684 * @param string $uri the header to send
685 * @return boolean always true
687 function PMA_sendHeaderLocation($uri)
689 if (PMA_IS_IIS && strlen($uri) > 600) {
691 echo '<html><head><title>- - -</title>' . "\n";
692 echo '<meta http-equiv="expires" content="0">' . "\n";
693 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
694 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
695 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
696 echo '<script type="text/javascript">' . "\n";
697 echo '//<![CDATA[' . "\n";
698 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
699 echo '//]]>' . "\n";
700 echo '</script>' . "\n";
701 echo '</head>' . "\n";
702 echo '<body>' . "\n";
703 echo '<script type="text/javascript">' . "\n";
704 echo '//<![CDATA[' . "\n";
705 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
706 echo '//]]>' . "\n";
707 echo '</script></body></html>' . "\n";
709 } else {
710 if (SID) {
711 if (strpos($uri, '?') === false) {
712 header('Location: ' . $uri . '?' . SID);
713 } else {
714 $separator = PMA_get_arg_separator();
715 header('Location: ' . $uri . $separator . SID);
717 } else {
718 session_write_close();
719 if (headers_sent()) {
720 if (function_exists('debug_print_backtrace')) {
721 echo '<pre>';
722 debug_print_backtrace();
723 echo '</pre>';
725 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
727 // bug #1523784: IE6 does not like 'Refresh: 0', it
728 // results in a blank page
729 // but we need it when coming from the cookie login panel)
730 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
731 header('Refresh: 0; ' . $uri);
732 } else {
733 header('Location: ' . $uri);
740 * returns array with tables of given db with extended information and grouped
742 * @uses $cfg['LeftFrameTableSeparator']
743 * @uses $cfg['LeftFrameTableLevel']
744 * @uses $cfg['ShowTooltipAliasTB']
745 * @uses $cfg['NaturalOrder']
746 * @uses PMA_backquote()
747 * @uses count()
748 * @uses array_merge
749 * @uses uksort()
750 * @uses strstr()
751 * @uses explode()
752 * @param string $db name of db
753 * @param string $tables name of tables
754 * @param integer $limit_offset list offset
755 * @param integer $limit_count max tables to return
756 * return array (recursive) grouped table list
758 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
760 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
762 if (null === $tables) {
763 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
764 if ($GLOBALS['cfg']['NaturalOrder']) {
765 uksort($tables, 'strnatcasecmp');
769 if (count($tables) < 1) {
770 return $tables;
773 $default = array(
774 'Name' => '',
775 'Rows' => 0,
776 'Comment' => '',
777 'disp_name' => '',
780 $table_groups = array();
782 // for blobstreaming - list of blobstreaming tables - rajk
784 // load PMA configuration
785 $PMA_Config = $_SESSION['PMA_Config'];
787 // if PMA configuration exists
788 if (!empty($PMA_Config))
789 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
791 foreach ($tables as $table_name => $table) {
792 // if BS tables exist
793 if (isset($session_bs_tables))
794 // compare table name to tables in list of blobstreaming tables
795 foreach ($session_bs_tables as $table_key=>$table_val)
796 // if table is in list, skip outer foreach loop
797 if ($table_name == $table_key)
798 continue 2;
800 // check for correct row count
801 if (null === $table['Rows']) {
802 // Do not check exact row count here,
803 // if row count is invalid possibly the table is defect
804 // and this would break left frame;
805 // but we can check row count if this is a view or the
806 // information_schema database
807 // since PMA_Table::countRecords() returns a limited row count
808 // in this case.
810 // set this because PMA_Table::countRecords() can use it
811 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
813 if ($tbl_is_view || 'information_schema' == $db) {
814 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
818 // in $group we save the reference to the place in $table_groups
819 // where to store the table info
820 if ($GLOBALS['cfg']['LeftFrameDBTree']
821 && $sep && strstr($table_name, $sep))
823 $parts = explode($sep, $table_name);
825 $group =& $table_groups;
826 $i = 0;
827 $group_name_full = '';
828 $parts_cnt = count($parts) - 1;
829 while ($i < $parts_cnt
830 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
831 $group_name = $parts[$i] . $sep;
832 $group_name_full .= $group_name;
834 if (!isset($group[$group_name])) {
835 $group[$group_name] = array();
836 $group[$group_name]['is' . $sep . 'group'] = true;
837 $group[$group_name]['tab' . $sep . 'count'] = 1;
838 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
839 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
840 $table = $group[$group_name];
841 $group[$group_name] = array();
842 $group[$group_name][$group_name] = $table;
843 unset($table);
844 $group[$group_name]['is' . $sep . 'group'] = true;
845 $group[$group_name]['tab' . $sep . 'count'] = 1;
846 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
847 } else {
848 $group[$group_name]['tab' . $sep . 'count']++;
850 $group =& $group[$group_name];
851 $i++;
853 } else {
854 if (!isset($table_groups[$table_name])) {
855 $table_groups[$table_name] = array();
857 $group =& $table_groups;
861 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
862 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
863 // switch tooltip and name
864 $table['Comment'] = $table['Name'];
865 $table['disp_name'] = $table['Comment'];
866 } else {
867 $table['disp_name'] = $table['Name'];
870 $group[$table_name] = array_merge($default, $table);
873 return $table_groups;
876 /* ----------------------- Set of misc functions ----------------------- */
880 * Adds backquotes on both sides of a database, table or field name.
881 * and escapes backquotes inside the name with another backquote
883 * example:
884 * <code>
885 * echo PMA_backquote('owner`s db'); // `owner``s db`
887 * </code>
889 * @uses PMA_backquote()
890 * @uses is_array()
891 * @uses strlen()
892 * @uses str_replace()
893 * @param mixed $a_name the database, table or field name to "backquote"
894 * or array of it
895 * @param boolean $do_it a flag to bypass this function (used by dump
896 * functions)
897 * @return mixed the "backquoted" database, table or field name if the
898 * current MySQL release is >= 3.23.6, the original one
899 * else
900 * @access public
902 function PMA_backquote($a_name, $do_it = true)
904 if (is_array($a_name)) {
905 foreach ($a_name as &$data) {
906 $data = PMA_backquote($data, $do_it);
908 return $a_name;
911 if (! $do_it) {
912 global $PMA_SQPdata_forbidden_word;
913 global $PMA_SQPdata_forbidden_word_cnt;
915 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
916 return $a_name;
920 // '0' is also empty for php :-(
921 if (strlen($a_name) && $a_name !== '*') {
922 return '`' . str_replace('`', '``', $a_name) . '`';
923 } else {
924 return $a_name;
926 } // end of the 'PMA_backquote()' function
930 * Defines the <CR><LF> value depending on the user OS.
932 * @uses PMA_USR_OS
933 * @return string the <CR><LF> value to use
935 * @access public
937 function PMA_whichCrlf()
939 $the_crlf = "\n";
941 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
942 // Win case
943 if (PMA_USR_OS == 'Win') {
944 $the_crlf = "\r\n";
946 // Others
947 else {
948 $the_crlf = "\n";
951 return $the_crlf;
952 } // end of the 'PMA_whichCrlf()' function
955 * Reloads navigation if needed.
957 * @param $jsonly prints out pure JavaScript
958 * @uses $GLOBALS['reload']
959 * @uses $GLOBALS['db']
960 * @uses PMA_generate_common_url()
961 * @global array configuration
963 * @access public
965 function PMA_reloadNavigation($jsonly=false)
967 global $cfg;
969 // Reloads the navigation frame via JavaScript if required
970 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
971 // one of the reasons for a reload is when a table is dropped
972 // in this case, get rid of the table limit offset, otherwise
973 // we have a problem when dropping a table on the last page
974 // and the offset becomes greater than the total number of tables
975 unset($_SESSION['tmp_user_values']['table_limit_offset']);
976 echo "\n";
977 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
978 if (!$jsonly)
979 echo '<script type="text/javascript">' . PHP_EOL;
981 //<![CDATA[
982 if (typeof(window.parent) != 'undefined'
983 && typeof(window.parent.frame_navigation) != 'undefined'
984 && window.parent.goTo) {
985 window.parent.goTo('<?php echo $reload_url; ?>');
987 //]]>
988 <?php
989 if (!$jsonly)
990 echo '</script>' . PHP_EOL;
992 unset($GLOBALS['reload']);
997 * displays the message and the query
998 * usually the message is the result of the query executed
1000 * @param string $message the message to display
1001 * @param string $sql_query the query to display
1002 * @param string $type the type (level) of the message
1003 * @global array the configuration array
1004 * @uses $cfg
1005 * @access public
1007 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
1009 global $cfg;
1011 if (null === $sql_query) {
1012 if (! empty($GLOBALS['display_query'])) {
1013 $sql_query = $GLOBALS['display_query'];
1014 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1015 $sql_query = $GLOBALS['unparsed_sql'];
1016 } elseif (! empty($GLOBALS['sql_query'])) {
1017 $sql_query = $GLOBALS['sql_query'];
1018 } else {
1019 $sql_query = '';
1023 // Corrects the tooltip text via JS if required
1024 // @todo this is REALLY the wrong place to do this - very unexpected here
1025 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1026 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1027 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1028 echo "\n";
1029 echo '<script type="text/javascript">' . "\n";
1030 echo '//<![CDATA[' . "\n";
1031 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1032 echo '//]]>' . "\n";
1033 echo '</script>' . "\n";
1034 } // end if ... elseif
1036 // Checks if the table needs to be repaired after a TRUNCATE query.
1037 // @todo what about $GLOBALS['display_query']???
1038 // @todo this is REALLY the wrong place to do this - very unexpected here
1039 if (strlen($GLOBALS['table'])
1040 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1041 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1042 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1045 unset($tbl_status);
1047 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1049 if ($message instanceof PMA_Message) {
1050 if (isset($GLOBALS['special_message'])) {
1051 $message->addMessage($GLOBALS['special_message']);
1052 unset($GLOBALS['special_message']);
1054 $message->display();
1055 $type = $message->getLevel();
1056 } else {
1057 echo '<div class="' . $type . '">';
1058 echo PMA_sanitize($message);
1059 if (isset($GLOBALS['special_message'])) {
1060 echo PMA_sanitize($GLOBALS['special_message']);
1061 unset($GLOBALS['special_message']);
1063 echo '</div>';
1066 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1067 // Html format the query to be displayed
1068 // If we want to show some sql code it is easiest to create it here
1069 /* SQL-Parser-Analyzer */
1071 if (! empty($GLOBALS['show_as_php'])) {
1072 $new_line = '\\n"<br />' . "\n"
1073 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1074 $query_base = htmlspecialchars(addslashes($sql_query));
1075 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1076 } else {
1077 $query_base = $sql_query;
1080 $query_too_big = false;
1082 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1083 // when the query is large (for example an INSERT of binary
1084 // data), the parser chokes; so avoid parsing the query
1085 $query_too_big = true;
1086 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1087 } elseif (! empty($GLOBALS['parsed_sql'])
1088 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1089 // (here, use "! empty" because when deleting a bookmark,
1090 // $GLOBALS['parsed_sql'] is set but empty
1091 $parsed_sql = $GLOBALS['parsed_sql'];
1092 } else {
1093 // Parse SQL if needed
1094 $parsed_sql = PMA_SQP_parse($query_base);
1097 // Analyze it
1098 if (isset($parsed_sql)) {
1099 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1100 // Here we append the LIMIT added for navigation, to
1101 // enable its display. Adding it higher in the code
1102 // to $sql_query would create a problem when
1103 // using the Refresh or Edit links.
1105 // Only append it on SELECTs.
1108 * @todo what would be the best to do when someone hits Refresh:
1109 * use the current LIMITs ?
1112 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1113 && isset($GLOBALS['sql_limit_to_append'])) {
1114 $query_base = $analyzed_display_query[0]['section_before_limit']
1115 . "\n" . $GLOBALS['sql_limit_to_append']
1116 . $analyzed_display_query[0]['section_after_limit'];
1117 // Need to reparse query
1118 $parsed_sql = PMA_SQP_parse($query_base);
1122 if (! empty($GLOBALS['show_as_php'])) {
1123 $query_base = '$sql = "' . $query_base;
1124 } elseif (! empty($GLOBALS['validatequery'])) {
1125 $query_base = PMA_validateSQL($query_base);
1126 } elseif (isset($parsed_sql)) {
1127 $query_base = PMA_formatSql($parsed_sql, $query_base);
1130 // Prepares links that may be displayed to edit/explain the query
1131 // (don't go to default pages, we must go to the page
1132 // where the query box is available)
1134 // Basic url query part
1135 $url_params = array();
1136 if (strlen($GLOBALS['db'])) {
1137 $url_params['db'] = $GLOBALS['db'];
1138 if (strlen($GLOBALS['table'])) {
1139 $url_params['table'] = $GLOBALS['table'];
1140 $edit_link = 'tbl_sql.php';
1141 } else {
1142 $edit_link = 'db_sql.php';
1144 } else {
1145 $edit_link = 'server_sql.php';
1148 // Want to have the query explained (Mike Beck 2002-05-22)
1149 // but only explain a SELECT (that has not been explained)
1150 /* SQL-Parser-Analyzer */
1151 $explain_link = '';
1152 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1153 $explain_params = $url_params;
1154 // Detect if we are validating as well
1155 // To preserve the validate uRL data
1156 if (! empty($GLOBALS['validatequery'])) {
1157 $explain_params['validatequery'] = 1;
1160 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1161 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1162 $_message = $GLOBALS['strExplain'];
1163 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1164 $explain_params['sql_query'] = substr($sql_query, 8);
1165 $_message = $GLOBALS['strNoExplain'];
1167 if (isset($explain_params['sql_query'])) {
1168 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1169 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1171 } //show explain
1173 $url_params['sql_query'] = $sql_query;
1174 $url_params['show_query'] = 1;
1176 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1177 if ($cfg['EditInWindow'] == true) {
1178 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1179 } else {
1180 $onclick = '';
1183 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1184 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1185 } else {
1186 $edit_link = '';
1189 $url_qpart = PMA_generate_common_url($url_params);
1191 // Also we would like to get the SQL formed in some nice
1192 // php-code (Mike Beck 2002-05-22)
1193 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1194 $php_params = $url_params;
1196 if (! empty($GLOBALS['show_as_php'])) {
1197 $_message = $GLOBALS['strNoPhp'];
1198 } else {
1199 $php_params['show_as_php'] = 1;
1200 $_message = $GLOBALS['strPhp'];
1203 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1204 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1206 if (isset($GLOBALS['show_as_php'])) {
1207 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1208 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1210 } else {
1211 $php_link = '';
1212 } //show as php
1214 // Refresh query
1215 if (! empty($cfg['SQLQuery']['Refresh'])
1216 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1217 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1218 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1219 } else {
1220 $refresh_link = '';
1221 } //show as php
1223 if (! empty($cfg['SQLValidator']['use'])
1224 && ! empty($cfg['SQLQuery']['Validate'])) {
1225 $validate_params = $url_params;
1226 if (!empty($GLOBALS['validatequery'])) {
1227 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1228 } else {
1229 $validate_params['validatequery'] = 1;
1230 $validate_message = $GLOBALS['strValidateSQL'] ;
1233 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1234 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1235 } else {
1236 $validate_link = '';
1237 } //validator
1239 echo '<code class="sql">';
1240 if ($query_too_big) {
1241 echo $shortened_query_base;
1242 } else {
1243 echo $query_base;
1246 //Clean up the end of the PHP
1247 if (! empty($GLOBALS['show_as_php'])) {
1248 echo '";';
1250 echo '</code>';
1252 echo '<div class="tools">';
1253 // avoid displaying a Profiling checkbox that could
1254 // be checked, which would reexecute an INSERT, for example
1255 if (! empty($refresh_link)) {
1256 PMA_profilingCheckbox($sql_query);
1258 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1259 echo '</div>';
1261 echo '</div><br />' . "\n";
1262 } // end of the 'PMA_showMessage()' function
1265 * Verifies if current MySQL server supports profiling
1267 * @uses $_SESSION['profiling_supported'] for caching
1268 * @uses $GLOBALS['server']
1269 * @uses PMA_DBI_fetch_value()
1270 * @uses PMA_MYSQL_INT_VERSION
1271 * @uses defined()
1272 * @access public
1273 * @return boolean whether profiling is supported
1275 * @author Marc Delisle
1277 function PMA_profilingSupported()
1279 if (! PMA_cacheExists('profiling_supported', true)) {
1280 // 5.0.37 has profiling but for example, 5.1.20 does not
1281 // (avoid a trip to the server for MySQL before 5.0.37)
1282 // and do not set a constant as we might be switching servers
1283 if (defined('PMA_MYSQL_INT_VERSION')
1284 && PMA_MYSQL_INT_VERSION >= 50037
1285 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1286 PMA_cacheSet('profiling_supported', true, true);
1287 } else {
1288 PMA_cacheSet('profiling_supported', false, true);
1292 return PMA_cacheGet('profiling_supported', true);
1296 * Displays a form with the Profiling checkbox
1298 * @param string $sql_query
1299 * @access public
1301 * @author Marc Delisle
1303 function PMA_profilingCheckbox($sql_query)
1305 if (PMA_profilingSupported()) {
1306 echo '<form action="sql.php" method="post">' . "\n";
1307 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1308 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1309 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1310 PMA_display_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1311 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1312 echo '</form>' . "\n";
1317 * Displays the results of SHOW PROFILE
1319 * @param array the results
1320 * @access public
1322 * @author Marc Delisle
1324 function PMA_profilingResults($profiling_results)
1326 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1327 echo '<table>' . "\n";
1328 echo ' <tr>' . "\n";
1329 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1330 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1331 echo ' </tr>' . "\n";
1333 foreach($profiling_results as $one_result) {
1334 echo ' <tr>' . "\n";
1335 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1336 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1338 echo '</table>' . "\n";
1339 echo '</fieldset>' . "\n";
1343 * Formats $value to byte view
1345 * @param double the value to format
1346 * @param integer the sensitiveness
1347 * @param integer the number of decimals to retain
1349 * @return array the formatted value and its unit
1351 * @access public
1353 * @author staybyte
1354 * @version 1.2 - 18 July 2002
1356 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1358 $dh = PMA_pow(10, $comma);
1359 $li = PMA_pow(10, $limes);
1360 $return_value = $value;
1361 $unit = $GLOBALS['byteUnits'][0];
1363 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1364 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1365 // use 1024.0 to avoid integer overflow on 64-bit machines
1366 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1367 $unit = $GLOBALS['byteUnits'][$d];
1368 break 1;
1369 } // end if
1370 } // end for
1372 if ($unit != $GLOBALS['byteUnits'][0]) {
1373 // if the unit is not bytes (as represented in current language)
1374 // reformat with max length of 5
1375 // 4th parameter=true means do not reformat if value < 1
1376 $return_value = PMA_formatNumber($value, 5, $comma, true);
1377 } else {
1378 // do not reformat, just handle the locale
1379 $return_value = PMA_formatNumber($value, 0);
1382 return array($return_value, $unit);
1383 } // end of the 'PMA_formatByteDown' function
1386 * Formats $value to the given length and appends SI prefixes
1387 * $comma is not substracted from the length
1388 * with a $length of 0 no truncation occurs, number is only formated
1389 * to the current locale
1391 * examples:
1392 * <code>
1393 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1394 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1395 * echo PMA_formatNumber(-0.003, 6); // -3 m
1396 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1397 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1398 * echo PMA_formatNumber(0, 6); // 0
1400 * </code>
1401 * @param double $value the value to format
1402 * @param integer $length the max length
1403 * @param integer $comma the number of decimals to retain
1404 * @param boolean $only_down do not reformat numbers below 1
1406 * @return string the formatted value and its unit
1408 * @access public
1410 * @author staybyte, sebastian mendel
1411 * @version 1.1.0 - 2005-10-27
1413 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1415 //number_format is not multibyte safe, str_replace is safe
1416 if ($length === 0) {
1417 return str_replace(array(',', '.'),
1418 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1419 number_format($value, $comma));
1422 // this units needs no translation, ISO
1423 $units = array(
1424 -8 => 'y',
1425 -7 => 'z',
1426 -6 => 'a',
1427 -5 => 'f',
1428 -4 => 'p',
1429 -3 => 'n',
1430 -2 => '&micro;',
1431 -1 => 'm',
1432 0 => ' ',
1433 1 => 'k',
1434 2 => 'M',
1435 3 => 'G',
1436 4 => 'T',
1437 5 => 'P',
1438 6 => 'E',
1439 7 => 'Z',
1440 8 => 'Y'
1443 // we need at least 3 digits to be displayed
1444 if (3 > $length + $comma) {
1445 $length = 3 - $comma;
1448 // check for negative value to retain sign
1449 if ($value < 0) {
1450 $sign = '-';
1451 $value = abs($value);
1452 } else {
1453 $sign = '';
1456 $dh = PMA_pow(10, $comma);
1457 $li = PMA_pow(10, $length);
1458 $unit = $units[0];
1460 if ($value >= 1) {
1461 for ($d = 8; $d >= 0; $d--) {
1462 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1463 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1464 $unit = $units[$d];
1465 break 1;
1466 } // end if
1467 } // end for
1468 } elseif (!$only_down && (float) $value !== 0.0) {
1469 for ($d = -8; $d <= 8; $d++) {
1470 // force using pow() because of the negative exponent
1471 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1472 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1473 $unit = $units[$d];
1474 break 1;
1475 } // end if
1476 } // end for
1477 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1479 //number_format is not multibyte safe, str_replace is safe
1480 $value = str_replace(array(',', '.'),
1481 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1482 number_format($value, $comma));
1484 return $sign . $value . ' ' . $unit;
1485 } // end of the 'PMA_formatNumber' function
1488 * Writes localised date
1490 * @param string the current timestamp
1492 * @return string the formatted date
1494 * @access public
1496 function PMA_localisedDate($timestamp = -1, $format = '')
1498 global $datefmt, $month, $day_of_week;
1500 if ($format == '') {
1501 $format = $datefmt;
1504 if ($timestamp == -1) {
1505 $timestamp = time();
1508 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1509 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1511 return strftime($date, $timestamp);
1512 } // end of the 'PMA_localisedDate()' function
1516 * returns a tab for tabbed navigation.
1517 * If the variables $link and $args ar left empty, an inactive tab is created
1519 * @uses $GLOBALS['PMA_PHP_SELF']
1520 * @uses $GLOBALS['strEmpty']
1521 * @uses $GLOBALS['strDrop']
1522 * @uses $GLOBALS['active_page']
1523 * @uses $GLOBALS['url_query']
1524 * @uses $cfg['MainPageIconic']
1525 * @uses $GLOBALS['pmaThemeImage']
1526 * @uses PMA_generate_common_url()
1527 * @uses E_USER_NOTICE
1528 * @uses htmlentities()
1529 * @uses urlencode()
1530 * @uses sprintf()
1531 * @uses trigger_error()
1532 * @uses array_merge()
1533 * @uses basename()
1534 * @param array $tab array with all options
1535 * @param array $url_params
1536 * @return string html code for one tab, a link if valid otherwise a span
1537 * @access public
1539 function PMA_generate_html_tab($tab, $url_params = array())
1541 // default values
1542 $defaults = array(
1543 'text' => '',
1544 'class' => '',
1545 'active' => false,
1546 'link' => '',
1547 'sep' => '?',
1548 'attr' => '',
1549 'args' => '',
1550 'warning' => '',
1551 'fragment' => '',
1554 $tab = array_merge($defaults, $tab);
1556 // determine additionnal style-class
1557 if (empty($tab['class'])) {
1558 if ($tab['text'] == $GLOBALS['strEmpty']
1559 || $tab['text'] == $GLOBALS['strDrop']) {
1560 $tab['class'] = 'caution';
1561 } elseif (! empty($tab['active'])
1562 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1563 $tab['class'] = 'active';
1564 } elseif (empty($GLOBALS['active_page'])
1565 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1566 && empty($tab['warning'])) {
1567 $tab['class'] = 'active';
1571 if (!empty($tab['warning'])) {
1572 $tab['class'] .= ' warning';
1573 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1576 // build the link
1577 if (!empty($tab['link'])) {
1578 $tab['link'] = htmlentities($tab['link']);
1579 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1580 if (! empty($tab['args'])) {
1581 foreach ($tab['args'] as $param => $value) {
1582 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1583 . urlencode($value);
1588 if (! empty($tab['fragment'])) {
1589 $tab['link'] .= $tab['fragment'];
1592 // display icon, even if iconic is disabled but the link-text is missing
1593 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1594 && isset($tab['icon'])) {
1595 // avoid generating an alt tag, because it only illustrates
1596 // the text that follows and if browser does not display
1597 // images, the text is duplicated
1598 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1599 .'%1$s" width="16" height="16" alt="" />%2$s';
1600 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1602 // check to not display an empty link-text
1603 elseif (empty($tab['text'])) {
1604 $tab['text'] = '?';
1605 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1606 E_USER_NOTICE);
1609 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1611 if (!empty($tab['link'])) {
1612 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1613 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1614 . $tab['text'] . '</a>';
1615 } else {
1616 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1617 . $tab['text'] . '</span>';
1620 $out .= '</li>';
1621 return $out;
1622 } // end of the 'PMA_generate_html_tab()' function
1625 * returns html-code for a tab navigation
1627 * @uses PMA_generate_html_tab()
1628 * @uses htmlentities()
1629 * @param array $tabs one element per tab
1630 * @param string $url_params
1631 * @return string html-code for tab-navigation
1633 function PMA_generate_html_tabs($tabs, $url_params)
1635 $tag_id = 'topmenu';
1636 $tab_navigation =
1637 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1638 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1640 foreach ($tabs as $tab) {
1641 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1644 $tab_navigation .=
1645 '</ul>' . "\n"
1646 .'<div class="clearfloat"></div>'
1647 .'</div>' . "\n";
1649 return $tab_navigation;
1654 * Displays a link, or a button if the link's URL is too large, to
1655 * accommodate some browsers' limitations
1657 * @param string the URL
1658 * @param string the link message
1659 * @param mixed $tag_params string: js confirmation
1660 * array: additional tag params (f.e. style="")
1661 * @param boolean $new_form we set this to false when we are already in
1662 * a form, to avoid generating nested forms
1664 * @return string the results to be echoed or saved in an array
1666 function PMA_linkOrButton($url, $message, $tag_params = array(),
1667 $new_form = true, $strip_img = false, $target = '')
1669 if (! is_array($tag_params)) {
1670 $tmp = $tag_params;
1671 $tag_params = array();
1672 if (!empty($tmp)) {
1673 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1675 unset($tmp);
1677 if (! empty($target)) {
1678 $tag_params['target'] = htmlentities($target);
1681 $tag_params_strings = array();
1682 foreach ($tag_params as $par_name => $par_value) {
1683 // htmlspecialchars() only on non javascript
1684 $par_value = substr($par_name, 0, 2) == 'on'
1685 ? $par_value
1686 : htmlspecialchars($par_value);
1687 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1690 if (strlen($url) <= $GLOBALS['cfg']['LinkLengthLimit']) {
1691 // no whitespace within an <a> else Safari will make it part of the link
1692 $ret = "\n" . '<a href="' . $url . '" '
1693 . implode(' ', $tag_params_strings) . '>'
1694 . $message . '</a>' . "\n";
1695 } else {
1696 // no spaces (linebreaks) at all
1697 // or after the hidden fields
1698 // IE will display them all
1700 // add class=link to submit button
1701 if (empty($tag_params['class'])) {
1702 $tag_params['class'] = 'link';
1705 // decode encoded url separators
1706 $separator = PMA_get_arg_separator();
1707 // on most places separator is still hard coded ...
1708 if ($separator !== '&') {
1709 // ... so always replace & with $separator
1710 $url = str_replace(htmlentities('&'), $separator, $url);
1711 $url = str_replace('&', $separator, $url);
1713 $url = str_replace(htmlentities($separator), $separator, $url);
1714 // end decode
1716 $url_parts = parse_url($url);
1717 $query_parts = explode($separator, $url_parts['query']);
1718 if ($new_form) {
1719 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1720 . ' method="post"' . $target . ' style="display: inline;">';
1721 $subname_open = '';
1722 $subname_close = '';
1723 $submit_name = '';
1724 } else {
1725 $query_parts[] = 'redirect=' . $url_parts['path'];
1726 if (empty($GLOBALS['subform_counter'])) {
1727 $GLOBALS['subform_counter'] = 0;
1729 $GLOBALS['subform_counter']++;
1730 $ret = '';
1731 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1732 $subname_close = ']';
1733 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1735 foreach ($query_parts as $query_pair) {
1736 list($eachvar, $eachval) = explode('=', $query_pair);
1737 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1738 . $subname_close . '" value="'
1739 . htmlspecialchars(urldecode($eachval)) . '" />';
1740 } // end while
1742 if (stristr($message, '<img')) {
1743 if ($strip_img) {
1744 $message = trim(strip_tags($message));
1745 $ret .= '<input type="submit"' . $submit_name . ' '
1746 . implode(' ', $tag_params_strings)
1747 . ' value="' . htmlspecialchars($message) . '" />';
1748 } else {
1749 $ret .= '<input type="image"' . $submit_name . ' '
1750 . implode(' ', $tag_params_strings)
1751 . ' src="' . preg_replace(
1752 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1753 . ' value="' . htmlspecialchars(
1754 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1755 $message))
1756 . '" />';
1758 } else {
1759 $message = trim(strip_tags($message));
1760 $ret .= '<input type="submit"' . $submit_name . ' '
1761 . implode(' ', $tag_params_strings)
1762 . ' value="' . htmlspecialchars($message) . '" />';
1764 if ($new_form) {
1765 $ret .= '</form>';
1767 } // end if... else...
1769 return $ret;
1770 } // end of the 'PMA_linkOrButton()' function
1774 * Returns a given timespan value in a readable format.
1776 * @uses $GLOBALS['timespanfmt']
1777 * @uses sprintf()
1778 * @uses floor()
1779 * @param int the timespan
1781 * @return string the formatted value
1783 function PMA_timespanFormat($seconds)
1785 $return_string = '';
1786 $days = floor($seconds / 86400);
1787 if ($days > 0) {
1788 $seconds -= $days * 86400;
1790 $hours = floor($seconds / 3600);
1791 if ($days > 0 || $hours > 0) {
1792 $seconds -= $hours * 3600;
1794 $minutes = floor($seconds / 60);
1795 if ($days > 0 || $hours > 0 || $minutes > 0) {
1796 $seconds -= $minutes * 60;
1798 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1802 * Takes a string and outputs each character on a line for itself. Used
1803 * mainly for horizontalflipped display mode.
1804 * Takes care of special html-characters.
1805 * Fulfills todo-item
1806 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1808 * @todo add a multibyte safe function PMA_STR_split()
1809 * @uses strlen
1810 * @param string The string
1811 * @param string The Separator (defaults to "<br />\n")
1813 * @access public
1814 * @author Garvin Hicking <me@supergarv.de>
1815 * @return string The flipped string
1817 function PMA_flipstring($string, $Separator = "<br />\n")
1819 $format_string = '';
1820 $charbuff = false;
1822 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1823 $char = $string{$i};
1824 $append = false;
1826 if ($char == '&') {
1827 $format_string .= $charbuff;
1828 $charbuff = $char;
1829 } elseif ($char == ';' && !empty($charbuff)) {
1830 $format_string .= $charbuff . $char;
1831 $charbuff = false;
1832 $append = true;
1833 } elseif (! empty($charbuff)) {
1834 $charbuff .= $char;
1835 } else {
1836 $format_string .= $char;
1837 $append = true;
1840 // do not add separator after the last character
1841 if ($append && ($i != $str_len - 1)) {
1842 $format_string .= $Separator;
1846 return $format_string;
1851 * Function added to avoid path disclosures.
1852 * Called by each script that needs parameters, it displays
1853 * an error message and, by default, stops the execution.
1855 * Not sure we could use a strMissingParameter message here,
1856 * would have to check if the error message file is always available
1858 * @todo localize error message
1859 * @todo use PMA_fatalError() if $die === true?
1860 * @uses PMA_getenv()
1861 * @uses header_meta_style.inc.php
1862 * @uses $GLOBALS['PMA_PHP_SELF']
1863 * basename
1864 * @param array The names of the parameters needed by the calling
1865 * script.
1866 * @param boolean Stop the execution?
1867 * (Set this manually to false in the calling script
1868 * until you know all needed parameters to check).
1869 * @param boolean Whether to include this list in checking for special params.
1870 * @global string path to current script
1871 * @global boolean flag whether any special variable was required
1873 * @access public
1874 * @author Marc Delisle (lem9@users.sourceforge.net)
1876 function PMA_checkParameters($params, $die = true, $request = true)
1878 global $checked_special;
1880 if (!isset($checked_special)) {
1881 $checked_special = false;
1884 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1885 $found_error = false;
1886 $error_message = '';
1888 foreach ($params as $param) {
1889 if ($request && $param != 'db' && $param != 'table') {
1890 $checked_special = true;
1893 if (!isset($GLOBALS[$param])) {
1894 $error_message .= $reported_script_name
1895 . ': Missing parameter: ' . $param
1896 . ' <a href="./Documentation.html#faqmissingparameters"'
1897 . ' target="documentation"> (FAQ 2.8)</a><br />';
1898 $found_error = true;
1901 if ($found_error) {
1903 * display html meta tags
1905 require_once './libraries/header_meta_style.inc.php';
1906 echo '</head><body><p>' . $error_message . '</p></body></html>';
1907 if ($die) {
1908 exit();
1911 } // end function
1914 * Function to generate unique condition for specified row.
1916 * @uses $GLOBALS['analyzed_sql'][0]
1917 * @uses PMA_DBI_field_flags()
1918 * @uses PMA_backquote()
1919 * @uses PMA_sqlAddslashes()
1920 * @uses PMA_printable_bit_value()
1921 * @uses stristr()
1922 * @uses bin2hex()
1923 * @uses preg_replace()
1924 * @param resource $handle current query result
1925 * @param integer $fields_cnt number of fields
1926 * @param array $fields_meta meta information about fields
1927 * @param array $row current row
1928 * @param boolean $force_unique generate condition only on pk or unique
1930 * @access public
1931 * @author Michal Cihar (michal@cihar.com) and others...
1932 * @return string the calculated condition and whether condition is unique
1934 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1936 $primary_key = '';
1937 $unique_key = '';
1938 $nonprimary_condition = '';
1939 $preferred_condition = '';
1941 for ($i = 0; $i < $fields_cnt; ++$i) {
1942 $condition = '';
1943 $field_flags = PMA_DBI_field_flags($handle, $i);
1944 $meta = $fields_meta[$i];
1946 // do not use a column alias in a condition
1947 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1948 $meta->orgname = $meta->name;
1950 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1951 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1952 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1953 as $select_expr) {
1954 // need (string) === (string)
1955 // '' !== 0 but '' == 0
1956 if ((string) $select_expr['alias'] === (string) $meta->name) {
1957 $meta->orgname = $select_expr['column'];
1958 break;
1959 } // end if
1960 } // end foreach
1964 // Do not use a table alias in a condition.
1965 // Test case is:
1966 // select * from galerie x WHERE
1967 //(select count(*) from galerie y where y.datum=x.datum)>1
1969 // But orgtable is present only with mysqli extension so the
1970 // fix is only for mysqli.
1971 // Also, do not use the original table name if we are dealing with
1972 // a view because this view might be updatable.
1973 // (The isView() verification should not be costly in most cases
1974 // because there is some caching in the function).
1975 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1976 $meta->table = $meta->orgtable;
1979 // to fix the bug where float fields (primary or not)
1980 // can't be matched because of the imprecision of
1981 // floating comparison, use CONCAT
1982 // (also, the syntax "CONCAT(field) IS NULL"
1983 // that we need on the next "if" will work)
1984 if ($meta->type == 'real') {
1985 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1986 . PMA_backquote($meta->orgname) . ') ';
1987 } else {
1988 $condition = ' ' . PMA_backquote($meta->table) . '.'
1989 . PMA_backquote($meta->orgname) . ' ';
1990 } // end if... else...
1992 if (!isset($row[$i]) || is_null($row[$i])) {
1993 $condition .= 'IS NULL AND';
1994 } else {
1995 // timestamp is numeric on some MySQL 4.1
1996 if ($meta->numeric && $meta->type != 'timestamp') {
1997 $condition .= '= ' . $row[$i] . ' AND';
1998 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1999 // hexify only if this is a true not empty BLOB or a BINARY
2000 && stristr($field_flags, 'BINARY')
2001 && !empty($row[$i])) {
2002 // do not waste memory building a too big condition
2003 if (strlen($row[$i]) < 1000) {
2004 // use a CAST if possible, to avoid problems
2005 // if the field contains wildcard characters % or _
2006 $condition .= '= CAST(0x' . bin2hex($row[$i])
2007 . ' AS BINARY) AND';
2008 } else {
2009 // this blob won't be part of the final condition
2010 $condition = '';
2012 } elseif ($meta->type == 'bit') {
2013 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2014 } else {
2015 $condition .= '= \''
2016 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2019 if ($meta->primary_key > 0) {
2020 $primary_key .= $condition;
2021 } elseif ($meta->unique_key > 0) {
2022 $unique_key .= $condition;
2024 $nonprimary_condition .= $condition;
2025 } // end for
2027 // Correction University of Virginia 19991216:
2028 // prefer primary or unique keys for condition,
2029 // but use conjunction of all values if no primary key
2030 $clause_is_unique = true;
2031 if ($primary_key) {
2032 $preferred_condition = $primary_key;
2033 } elseif ($unique_key) {
2034 $preferred_condition = $unique_key;
2035 } elseif (! $force_unique) {
2036 $preferred_condition = $nonprimary_condition;
2037 $clause_is_unique = false;
2040 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2041 return(array($where_clause, $clause_is_unique));
2042 } // end function
2045 * Generate a button or image tag
2047 * @uses PMA_USR_BROWSER_AGENT
2048 * @uses $GLOBALS['pmaThemeImage']
2049 * @uses $GLOBALS['cfg']['PropertiesIconic']
2050 * @param string name of button element
2051 * @param string class of button element
2052 * @param string name of image element
2053 * @param string text to display
2054 * @param string image to display
2056 * @access public
2057 * @author Michal Cihar (michal@cihar.com)
2059 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2060 $image)
2062 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2063 echo ' <input type="submit" name="' . $button_name . '"'
2064 .' value="' . htmlspecialchars($text) . '"'
2065 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2066 return;
2069 /* Opera has trouble with <input type="image"> */
2070 /* IE has trouble with <button> */
2071 if (PMA_USR_BROWSER_AGENT != 'IE') {
2072 echo '<button class="' . $button_class . '" type="submit"'
2073 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2074 .' title="' . htmlspecialchars($text) . '">' . "\n"
2075 . PMA_getIcon($image, $text)
2076 .'</button>' . "\n";
2077 } else {
2078 echo '<input type="image" name="' . $image_name . '" value="'
2079 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2080 . $image . '" />'
2081 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2083 } // end function
2086 * Generate a pagination selector for browsing resultsets
2088 * @todo $url is not javascript escaped!?
2089 * @uses $GLOBALS['strPageNumber']
2090 * @uses range()
2091 * @param string URL for the JavaScript
2092 * @param string Number of rows in the pagination set
2093 * @param string current page number
2094 * @param string number of total pages
2095 * @param string If the number of pages is lower than this
2096 * variable, no pages will be omitted in
2097 * pagination
2098 * @param string How many rows at the beginning should always
2099 * be shown?
2100 * @param string How many rows at the end should always
2101 * be shown?
2102 * @param string Percentage of calculation page offsets to
2103 * hop to a next page
2104 * @param string Near the current page, how many pages should
2105 * be considered "nearby" and displayed as
2106 * well?
2107 * @param string The prompt to display (sometimes empty)
2109 * @access public
2110 * @author Garvin Hicking (pma@supergarv.de)
2112 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2113 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2114 $range = 10, $prompt = '')
2116 $increment = floor($nbTotalPage / $percent);
2117 $pageNowMinusRange = ($pageNow - $range);
2118 $pageNowPlusRange = ($pageNow + $range);
2120 $gotopage = $prompt
2121 . ' <select name="pos" onchange="goToUrl(this, \''
2122 . $url . '\');">' . "\n";
2123 if ($nbTotalPage < $showAll) {
2124 $pages = range(1, $nbTotalPage);
2125 } else {
2126 $pages = array();
2128 // Always show first X pages
2129 for ($i = 1; $i <= $sliceStart; $i++) {
2130 $pages[] = $i;
2133 // Always show last X pages
2134 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2135 $pages[] = $i;
2138 // garvin: Based on the number of results we add the specified
2139 // $percent percentage to each page number,
2140 // so that we have a representing page number every now and then to
2141 // immediately jump to specific pages.
2142 // As soon as we get near our currently chosen page ($pageNow -
2143 // $range), every page number will be shown.
2144 $i = $sliceStart;
2145 $x = $nbTotalPage - $sliceEnd;
2146 $met_boundary = false;
2147 while ($i <= $x) {
2148 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2149 // If our pageselector comes near the current page, we use 1
2150 // counter increments
2151 $i++;
2152 $met_boundary = true;
2153 } else {
2154 // We add the percentage increment to our current page to
2155 // hop to the next one in range
2156 $i += $increment;
2158 // Make sure that we do not cross our boundaries.
2159 if ($i > $pageNowMinusRange && ! $met_boundary) {
2160 $i = $pageNowMinusRange;
2164 if ($i > 0 && $i <= $x) {
2165 $pages[] = $i;
2169 // Since because of ellipsing of the current page some numbers may be double,
2170 // we unify our array:
2171 sort($pages);
2172 $pages = array_unique($pages);
2175 foreach ($pages as $i) {
2176 if ($i == $pageNow) {
2177 $selected = 'selected="selected" style="font-weight: bold"';
2178 } else {
2179 $selected = '';
2181 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2184 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2186 return $gotopage;
2187 } // end function
2191 * Generate navigation for a list
2193 * @todo use $pos from $_url_params
2194 * @uses $GLOBALS['strPageNumber']
2195 * @uses range()
2196 * @param integer number of elements in the list
2197 * @param integer current position in the list
2198 * @param array url parameters
2199 * @param string script name for form target
2200 * @param string target frame
2201 * @param integer maximum number of elements to display from the list
2203 * @access public
2205 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2207 if ($max_count < $count) {
2208 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2209 echo $GLOBALS['strPageNumber'];
2210 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2212 // Move to the beginning or to the previous page
2213 if ($pos > 0) {
2214 // loic1: patch #474210 from Gosha Sakovich - part 1
2215 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2216 $caption1 = '&lt;&lt;';
2217 $caption2 = ' &lt; ';
2218 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2219 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2220 } else {
2221 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2222 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2223 $title1 = '';
2224 $title2 = '';
2225 } // end if... else...
2226 $_url_params['pos'] = 0;
2227 echo '<a' . $title1 . ' href="' . $script
2228 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2229 . $caption1 . '</a>';
2230 $_url_params['pos'] = $pos - $max_count;
2231 echo '<a' . $title2 . ' href="' . $script
2232 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2233 . $caption2 . '</a>';
2236 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2237 echo PMA_generate_common_hidden_inputs($_url_params);
2238 echo PMA_pageselector(
2239 $script . PMA_generate_common_url($_url_params) . '&amp;',
2240 $max_count,
2241 floor(($pos + 1) / $max_count) + 1,
2242 ceil($count / $max_count));
2243 echo '</form>';
2245 if ($pos + $max_count < $count) {
2246 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2247 $caption3 = ' &gt; ';
2248 $caption4 = '&gt;&gt;';
2249 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2250 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2251 } else {
2252 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2253 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2254 $title3 = '';
2255 $title4 = '';
2256 } // end if... else...
2257 $_url_params['pos'] = $pos + $max_count;
2258 echo '<a' . $title3 . ' href="' . $script
2259 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2260 . $caption3 . '</a>';
2261 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2262 if ($_url_params['pos'] == $count) {
2263 $_url_params['pos'] = $count - $max_count;
2265 echo '<a' . $title4 . ' href="' . $script
2266 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2267 . $caption4 . '</a>';
2269 echo "\n";
2270 if ('frame_navigation' == $frame) {
2271 echo '</div>' . "\n";
2277 * replaces %u in given path with current user name
2279 * example:
2280 * <code>
2281 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2283 * </code>
2284 * @uses $cfg['Server']['user']
2285 * @uses substr()
2286 * @uses str_replace()
2287 * @param string $dir with wildcard for user
2288 * @return string per user directory
2290 function PMA_userDir($dir)
2292 // add trailing slash
2293 if (substr($dir, -1) != '/') {
2294 $dir .= '/';
2297 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2301 * returns html code for db link to default db page
2303 * @uses $cfg['DefaultTabDatabase']
2304 * @uses $GLOBALS['db']
2305 * @uses $GLOBALS['strJumpToDB']
2306 * @uses PMA_generate_common_url()
2307 * @uses PMA_unescape_mysql_wildcards()
2308 * @uses strlen()
2309 * @uses sprintf()
2310 * @uses htmlspecialchars()
2311 * @param string $database
2312 * @return string html link to default db page
2314 function PMA_getDbLink($database = null)
2316 if (!strlen($database)) {
2317 if (!strlen($GLOBALS['db'])) {
2318 return '';
2320 $database = $GLOBALS['db'];
2321 } else {
2322 $database = PMA_unescape_mysql_wildcards($database);
2325 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2326 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2327 .htmlspecialchars($database) . '</a>';
2331 * Displays a lightbulb hint explaining a known external bug
2332 * that affects a functionality
2334 * @uses PMA_MYSQL_INT_VERSION
2335 * @uses $GLOBALS['strKnownExternalBug']
2336 * @uses PMA_showHint()
2337 * @uses sprintf()
2338 * @param string $functionality localized message explaining the func.
2339 * @param string $component 'mysql' (eventually, 'php')
2340 * @param string $minimum_version of this component
2341 * @param string $bugref bug reference for this component
2343 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2345 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2346 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2351 * Generates and echoes an HTML checkbox
2353 * @param string $html_field_name the checkbox HTML field
2354 * @param string $label
2355 * @param boolean $checked is it initially checked?
2356 * @param boolean $onclick should it submit the form on click?
2358 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2360 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>';
2364 * Generates and echoes a set of radio HTML fields
2366 * @uses htmlspecialchars()
2367 * @param string $html_field_name the radio HTML field
2368 * @param array $choices the choices values and labels
2369 * @param string $checked_choice the choice to check by default
2370 * @param boolean $line_break whether to add an HTML line break after a choice
2371 * @param boolean $escape_label whether to use htmlspecialchars() on label
2372 * @param string $class enclose each choice with a div of this class
2374 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2375 foreach ($choices as $choice_value => $choice_label) {
2376 if (! empty($class)) {
2377 echo '<div class="' . $class . '">';
2379 $html_field_id = $html_field_name . '_' . $choice_value;
2380 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2381 if ($choice_value == $checked_choice) {
2382 echo ' checked="checked"';
2384 echo ' />' . "\n";
2385 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2386 if ($line_break) {
2387 echo '<br />';
2389 if (! empty($class)) {
2390 echo '</div>';
2392 echo "\n";
2397 * Generates and returns an HTML dropdown
2399 * @uses htmlspecialchars()
2400 * @param string $select_name
2401 * @param array $choices the choices values
2402 * @param string $active_choice the choice to select by default
2403 * @param string $id the id of the select element; can be different in case
2404 * the dropdown is present more than once on the page
2405 * @todo support titles
2407 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2409 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2410 foreach ($choices as $one_choice_value => $one_choice_label) {
2411 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2412 if ($one_choice_value == $active_choice) {
2413 $result .= ' selected="selected"';
2415 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2417 $result .= '</select>';
2418 return $result;
2422 * Generates a slider effect (Mootools)
2423 * Takes care of generating the initial <div> and the link
2424 * controlling the slider; you have to generate the </div> yourself
2425 * after the sliding section.
2427 * @uses $GLOBALS['cfg']['InitialSlidersState']
2428 * @param string $id the id of the <div> on which to apply the effect
2429 * @param string $message the message to show as a link
2431 function PMA_generate_slider_effect($id, $message)
2433 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2434 echo '<div id="' . $id . '">';
2435 return;
2438 <script type="text/javascript">
2439 // <![CDATA[
2440 window.addEvent('domready', function(){
2441 var status = {
2442 'true': '- ',
2443 'false': '+ '
2446 var anchor<?php echo $id; ?> = new Element('a', {
2447 'id': 'toggle_<?php echo $id; ?>',
2448 'href': 'javascript:void(0)',
2449 'events': {
2450 'click': function(){
2451 mySlide<?php echo $id; ?>.toggle();
2456 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2457 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2459 var slider_status<?php echo $id; ?> = new Element('span', {
2460 'id': 'slider_status_<?php echo $id; ?>'
2462 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2463 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2465 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2466 <?php
2467 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2469 mySlide<?php echo $id; ?>.hide();
2470 <?php
2473 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2474 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2477 $('<?php echo $id; ?>').style.display="block";
2479 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2480 //]]>
2481 </script>
2482 <noscript>
2483 <div id="<?php echo $id; ?>" />
2484 </noscript>
2485 <?php
2489 * Verifies if something is cached in the session
2491 * @param string $var
2492 * @param scalar $server
2493 * @return boolean
2495 function PMA_cacheExists($var, $server = 0)
2497 if (true === $server) {
2498 $server = $GLOBALS['server'];
2500 return isset($_SESSION['cache']['server_' . $server][$var]);
2504 * Gets cached information from the session
2506 * @param string $var
2507 * @param scalar $server
2508 * @return mixed
2510 function PMA_cacheGet($var, $server = 0)
2512 if (true === $server) {
2513 $server = $GLOBALS['server'];
2515 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2516 return $_SESSION['cache']['server_' . $server][$var];
2517 } else {
2518 return null;
2523 * Caches information in the session
2525 * @param string $var
2526 * @param mixed $val
2527 * @param integer $server
2528 * @return mixed
2530 function PMA_cacheSet($var, $val = null, $server = 0)
2532 if (true === $server) {
2533 $server = $GLOBALS['server'];
2535 $_SESSION['cache']['server_' . $server][$var] = $val;
2539 * Removes cached information from the session
2541 * @param string $var
2542 * @param scalar $server
2544 function PMA_cacheUnset($var, $server = 0)
2546 if (true === $server) {
2547 $server = $GLOBALS['server'];
2549 unset($_SESSION['cache']['server_' . $server][$var]);
2553 * Converts a bit value to printable format;
2554 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2555 * function because in PHP, decbin() supports only 32 bits
2557 * @uses ceil()
2558 * @uses decbin()
2559 * @uses ord()
2560 * @uses substr()
2561 * @uses sprintf()
2562 * @param numeric $value coming from a BIT field
2563 * @param integer $length
2564 * @return string the printable value
2566 function PMA_printable_bit_value($value, $length) {
2567 $printable = '';
2568 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2569 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2571 $printable = substr($printable, -$length);
2572 return $printable;
2576 * Converts a BIT type default value
2577 * for example, b'010' becomes 010
2579 * @uses strtr()
2580 * @param string $bit_default_value
2581 * @return string the converted value
2583 function PMA_convert_bit_default_value($bit_default_value) {
2584 return strtr($bit_default_value, array("b" => "", "'" => ""));
2588 * Extracts the various parts from a field type spec
2590 * @uses strpos()
2591 * @uses chop()
2592 * @uses substr()
2593 * @param string $fieldspec
2594 * @return array associative array containing type, spec_in_brackets
2595 * and possibly enum_set_values (another array)
2596 * @author Marc Delisle
2597 * @author Joshua Hogendorn
2599 function PMA_extractFieldSpec($fieldspec) {
2600 $first_bracket_pos = strpos($fieldspec, '(');
2601 if ($first_bracket_pos) {
2602 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2603 // convert to lowercase just to be sure
2604 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2605 } else {
2606 $type = $fieldspec;
2607 $spec_in_brackets = '';
2610 if ('enum' == $type || 'set' == $type) {
2611 // Define our working vars
2612 $enum_set_values = array();
2613 $working = "";
2614 $in_string = false;
2615 $index = 0;
2617 // While there is another character to process
2618 while (isset($fieldspec[$index])) {
2619 // Grab the char to look at
2620 $char = $fieldspec[$index];
2622 // If it is a single quote, needs to be handled specially
2623 if ($char == "'") {
2624 // If we are not currently in a string, begin one
2625 if (! $in_string) {
2626 $in_string = true;
2627 $working = "";
2628 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2629 } else {
2630 // Check out the next character (if possible)
2631 $has_next = isset($fieldspec[$index + 1]);
2632 $next = $has_next ? $fieldspec[$index + 1] : null;
2634 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2635 if (! $has_next || $next != "'") {
2636 $enum_set_values[] = $working;
2637 $in_string = false;
2639 // Otherwise, this is a 'double quote', and can be added to the working string
2640 } elseif ($next == "'") {
2641 $working .= "'";
2642 // Skip the next char; we already know what it is
2643 $index++;
2646 // escaping of a quote?
2647 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2648 $working .= "'";
2649 $index++;
2650 // Otherwise, add it to our working string like normal
2651 } else {
2652 $working .= $char;
2654 // Increment character index
2655 $index++;
2656 } // end while
2657 } else {
2658 $enum_set_values = array();
2661 return array(
2662 'type' => $type,
2663 'spec_in_brackets' => $spec_in_brackets,
2664 'enum_set_values' => $enum_set_values
2669 * Verifies if this table's engine supports foreign keys
2671 * @uses strtoupper()
2672 * @param string $engine
2673 * @return boolean
2675 function PMA_foreignkey_supported($engine) {
2676 $engine = strtoupper($engine);
2677 if ('INNODB' == $engine || 'PBXT' == $engine) {
2678 return true;
2679 } else {
2680 return false;
2685 * Replaces some characters by a displayable equivalent
2687 * @uses str_replace()
2688 * @param string $content
2689 * @return string the content with characters replaced
2691 function PMA_replace_binary_contents($content) {
2692 $result = str_replace("\x00", '\0', $content);
2693 $result = str_replace("\x08", '\b', $result);
2694 $result = str_replace("\x0a", '\n', $result);
2695 $result = str_replace("\x0d", '\r', $result);
2696 $result = str_replace("\x1a", '\Z', $result);
2697 return $result;
2702 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2704 * @uses strpos()
2705 * @return string with the chars replaced
2708 function PMA_duplicateFirstNewline($string){
2709 $first_occurence = strpos($string, "\r\n");
2710 if ($first_occurence === 0){
2711 $string = "\n".$string;
2713 return $string;
2717 * get the action word corresponding to a script name
2718 * in order to display it as a title in navigation panel
2720 * @uses $GLOBALS
2721 * @param string a valid value for $cfg['LeftDefaultTabTable']
2722 * or $cfg['DefaultTabTable']
2723 * or $cfg['DefaultTabDatabase']
2725 function PMA_getTitleForTarget($target) {
2726 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];
2729 /**
2730 * The function creates javascript and html code, which run given mootools/JS code when DOM is ready
2732 * @param String $code - Mootools/JS code, which will be run
2733 * @param boolena $print - If true, then the code is printed, otherwise is returned
2735 * @return String - the code
2737 function PMA_js_mootools_domready($code, $print=true)
2739 // these generated newlines are needed
2740 $out = '';
2741 $out .= '<script type="text/javascript">';
2742 $out .= "\n" . '// <![CDATA[' . "\n";
2743 $out .= 'window.addEvent(\'domready\',function() {';
2744 $out .= $code;
2745 $out .= '});';
2746 $out .= "\n" . '// ]]>' . "\n";
2747 $out .= '</script>';
2749 if ($print)
2750 echo $out;
2752 return $out;
2755 function PMA_js($code, $print=true)
2757 // these generated newlines are needed
2758 $out = '';
2759 $out .= '<script type="text/javascript">'."\n";
2760 $out .= "\n" . '// <![CDATA[' . "\n";
2761 $out .= $code;
2762 $out .= "\n" . '// ]]>' . "\n";
2763 $out .= '</script>'."\n";
2765 if ($print)
2766 echo $out;
2768 return $out;