User_Schema class : removed tabs + commented code + organized structure, Delete listi...
[phpmyadmin-themes.git] / libraries / common.lib.php
blob6591715ec4c5a7eab277c4492ee59652f04d241f
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 __('Max: %s%s')
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(__('Max: %s%s'), $max_size, $max_unit) . ')';
151 * Generates a hidden field which should indicate to the browser
152 * the maximum size for upload
154 * @param integer the size
156 * @return string the INPUT field
158 * @access public
160 function PMA_generateHiddenMaxFileSize($max_size)
162 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
166 * Add slashes before "'" and "\" characters so a value containing them can
167 * be used in a sql comparison.
169 * @uses str_replace()
170 * @param string the string to slash
171 * @param boolean whether the string will be used in a 'LIKE' clause
172 * (it then requires two more escaped sequences) or not
173 * @param boolean whether to treat cr/lfs as escape-worthy entities
174 * (converts \n to \\n, \r to \\r)
176 * @param boolean whether this function is used as part of the
177 * "Create PHP code" dialog
179 * @return string the slashed string
181 * @access public
183 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
185 if ($is_like) {
186 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
187 } else {
188 $a_string = str_replace('\\', '\\\\', $a_string);
191 if ($crlf) {
192 $a_string = str_replace("\n", '\n', $a_string);
193 $a_string = str_replace("\r", '\r', $a_string);
194 $a_string = str_replace("\t", '\t', $a_string);
197 if ($php_code) {
198 $a_string = str_replace('\'', '\\\'', $a_string);
199 } else {
200 $a_string = str_replace('\'', '\'\'', $a_string);
203 return $a_string;
204 } // end of the 'PMA_sqlAddslashes()' function
208 * Add slashes before "_" and "%" characters for using them in MySQL
209 * database, table and field names.
210 * Note: This function does not escape backslashes!
212 * @uses str_replace()
213 * @param string the string to escape
215 * @return string the escaped string
217 * @access public
219 function PMA_escape_mysql_wildcards($name)
221 $name = str_replace('_', '\\_', $name);
222 $name = str_replace('%', '\\%', $name);
224 return $name;
225 } // end of the 'PMA_escape_mysql_wildcards()' function
228 * removes slashes before "_" and "%" characters
229 * Note: This function does not unescape backslashes!
231 * @uses str_replace()
232 * @param string $name the string to escape
233 * @return string the escaped string
234 * @access public
236 function PMA_unescape_mysql_wildcards($name)
238 $name = str_replace('\\_', '_', $name);
239 $name = str_replace('\\%', '%', $name);
241 return $name;
242 } // end of the 'PMA_unescape_mysql_wildcards()' function
245 * removes quotes (',",`) from a quoted string
247 * checks if the sting is quoted and removes this quotes
249 * @uses str_replace()
250 * @uses substr()
251 * @param string $quoted_string string to remove quotes from
252 * @param string $quote type of quote to remove
253 * @return string unqoted string
255 function PMA_unQuote($quoted_string, $quote = null)
257 $quotes = array();
259 if (null === $quote) {
260 $quotes[] = '`';
261 $quotes[] = '"';
262 $quotes[] = "'";
263 } else {
264 $quotes[] = $quote;
267 foreach ($quotes as $quote) {
268 if (substr($quoted_string, 0, 1) === $quote
269 && substr($quoted_string, -1, 1) === $quote) {
270 $unquoted_string = substr($quoted_string, 1, -1);
271 // replace escaped quotes
272 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
273 return $unquoted_string;
277 return $quoted_string;
281 * format sql strings
283 * @todo move into PMA_Sql
284 * @uses PMA_SQP_isError()
285 * @uses PMA_SQP_formatHtml()
286 * @uses PMA_SQP_formatNone()
287 * @uses is_array()
288 * @param mixed pre-parsed SQL structure
290 * @return string the formatted sql
292 * @global array the configuration array
293 * @global boolean whether the current statement is a multiple one or not
295 * @access public
298 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
300 global $cfg;
302 // Check that we actually have a valid set of parsed data
303 // well, not quite
304 // first check for the SQL parser having hit an error
305 if (PMA_SQP_isError()) {
306 return htmlspecialchars($parsed_sql['raw']);
308 // then check for an array
309 if (!is_array($parsed_sql)) {
310 // We don't so just return the input directly
311 // This is intended to be used for when the SQL Parser is turned off
312 $formatted_sql = '<pre>' . "\n"
313 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
314 . '</pre>';
315 return $formatted_sql;
318 $formatted_sql = '';
320 switch ($cfg['SQP']['fmtType']) {
321 case 'none':
322 if ($unparsed_sql != '') {
323 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
324 } else {
325 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
327 break;
328 case 'html':
329 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
330 break;
331 case 'text':
332 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
333 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
334 break;
335 default:
336 break;
337 } // end switch
339 return $formatted_sql;
340 } // end of the "PMA_formatSql()" function
344 * Displays a link to the official MySQL documentation
346 * @uses $cfg['MySQLManualType']
347 * @uses $cfg['MySQLManualBase']
348 * @uses $cfg['ReplaceHelpImg']
349 * @uses __('Documentation')
350 * @uses $GLOBALS['pmaThemeImage']
351 * @uses PMA_MYSQL_INT_VERSION
352 * @uses strtolower()
353 * @uses str_replace()
354 * @param string chapter of "HTML, one page per chapter" documentation
355 * @param string contains name of page/anchor that is being linked
356 * @param bool whether to use big icon (like in left frame)
357 * @param string anchor to page part
359 * @return string the html link
361 * @access public
363 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
365 global $cfg;
367 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
368 return '';
371 // Fixup for newly used names:
372 $chapter = str_replace('_', '-', strtolower($chapter));
373 $link = str_replace('_', '-', strtolower($link));
375 switch ($cfg['MySQLManualType']) {
376 case 'chapters':
377 if (empty($chapter)) {
378 $chapter = 'index';
380 if (empty($anchor)) {
381 $anchor = $link;
383 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
384 break;
385 case 'big':
386 if (empty($anchor)) {
387 $anchor = $link;
389 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
390 break;
391 case 'searchable':
392 if (empty($link)) {
393 $link = 'index';
395 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
396 if (!empty($anchor)) {
397 $url .= '#' . $anchor;
399 break;
400 case 'viewable':
401 default:
402 if (empty($link)) {
403 $link = 'index';
405 $mysql = '5.0';
406 $lang = 'en';
407 if (defined('PMA_MYSQL_INT_VERSION')) {
408 if (PMA_MYSQL_INT_VERSION >= 50100) {
409 $mysql = '5.1';
410 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
411 $lang = _pgettext('$mysql_5_1_doc_lang', 'en');
412 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
413 $mysql = '5.0';
414 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
415 $lang = _pgettext('$mysql_5_0_doc_lang', 'en');
418 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
419 if (!empty($anchor)) {
420 $url .= '#' . $anchor;
422 break;
425 if ($just_open) {
426 return '<a href="' . $url . '" target="mysql_doc">';
427 } elseif ($big_icon) {
428 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
429 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
430 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
431 } else {
432 return '[<a href="' . $url . '" target="mysql_doc">' . __('Documentation') . '</a>]';
434 } // end of the 'PMA_showMySQLDocu()' function
438 * Displays a link to the phpMyAdmin documentation
440 * @param string anchor in documentation
442 * @return string the html link
444 * @access public
446 function PMA_showDocu($anchor) {
447 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
448 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
449 } else {
450 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
452 } // end of the 'PMA_showDocu()' function
455 * returns HTML for a footnote marker and add the messsage to the footnotes
457 * @uses $GLOBALS['footnotes']
458 * @param string the error message
459 * @return string html code for a footnote marker
460 * @access public
462 function PMA_showHint($message, $bbcode = false, $type = 'notice')
464 if ($message instanceof PMA_Message) {
465 $key = $message->getHash();
466 $type = $message->getLevel();
467 } else {
468 $key = md5($message);
471 if (! isset($GLOBALS['footnotes'][$key])) {
472 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
473 $GLOBALS['footnotes'] = array();
475 $nr = count($GLOBALS['footnotes']) + 1;
476 // this is the first instance of this message
477 $instance = 1;
478 $GLOBALS['footnotes'][$key] = array(
479 'note' => $message,
480 'type' => $type,
481 'nr' => $nr,
482 'instance' => $instance
484 } else {
485 $nr = $GLOBALS['footnotes'][$key]['nr'];
486 // another instance of this message (to ensure ids are unique)
487 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
490 if ($bbcode) {
491 return '[sup]' . $nr . '[/sup]';
494 // footnotemarker used in js/tooltip.js
495 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
499 * Displays a MySQL error message in the right frame.
501 * @uses footer.inc.php
502 * @uses header.inc.php
503 * @uses $GLOBALS['sql_query']
504 * @uses __('Error')
505 * @uses __('SQL query')
506 * @uses $GLOBALS['pmaThemeImage']
507 * @uses __('Edit')
508 * @uses __('MySQL said: ')
509 * @uses $GLOBALS['cfg']['PropertiesIconic']
510 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
511 * @uses PMA_backquote()
512 * @uses PMA_DBI_getError()
513 * @uses PMA_formatSql()
514 * @uses PMA_generate_common_hidden_inputs()
515 * @uses PMA_generate_common_url()
516 * @uses PMA_showMySQLDocu()
517 * @uses PMA_sqlAddslashes()
518 * @uses PMA_SQP_isError()
519 * @uses PMA_SQP_parse()
520 * @uses PMA_SQP_getErrorString()
521 * @uses strtolower()
522 * @uses urlencode()
523 * @uses str_replace()
524 * @uses nl2br()
525 * @uses substr()
526 * @uses preg_replace()
527 * @uses preg_match()
528 * @uses explode()
529 * @uses implode()
530 * @uses is_array()
531 * @uses function_exists()
532 * @uses htmlspecialchars()
533 * @uses trim()
534 * @uses strstr()
535 * @param string the error message
536 * @param string the sql query that failed
537 * @param boolean whether to show a "modify" link or not
538 * @param string the "back" link url (full path is not required)
539 * @param boolean EXIT the page?
541 * @global string the curent table
542 * @global string the current db
544 * @access public
546 function PMA_mysqlDie($error_message = '', $the_query = '',
547 $is_modify_link = true, $back_url = '', $exit = true)
549 global $table, $db;
552 * start http output, display html headers
554 require_once './libraries/header.inc.php';
556 $error_msg_output = '';
558 if (!$error_message) {
559 $error_message = PMA_DBI_getError();
561 if (!$the_query && !empty($GLOBALS['sql_query'])) {
562 $the_query = $GLOBALS['sql_query'];
565 // --- Added to solve bug #641765
566 // Robbat2 - 12 January 2003, 9:46PM
567 // Revised, Robbat2 - 13 January 2003, 2:59PM
568 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
569 $formatted_sql = htmlspecialchars($the_query);
570 } elseif (empty($the_query) || trim($the_query) == '') {
571 $formatted_sql = '';
572 } else {
573 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
574 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
575 } else {
576 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
579 // ---
580 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
581 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
582 // if the config password is wrong, or the MySQL server does not
583 // respond, do not show the query that would reveal the
584 // username/password
585 if (!empty($the_query) && !strstr($the_query, 'connect')) {
586 // --- Added to solve bug #641765
587 // Robbat2 - 12 January 2003, 9:46PM
588 // Revised, Robbat2 - 13 January 2003, 2:59PM
589 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
590 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
591 $error_msg_output .= '<br />' . "\n";
593 // ---
594 // modified to show the help on sql errors
595 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
596 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
597 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
599 if ($is_modify_link) {
600 $_url_params = array(
601 'sql_query' => $the_query,
602 'show_query' => 1,
604 if (strlen($table)) {
605 $_url_params['db'] = $db;
606 $_url_params['table'] = $table;
607 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
608 } elseif (strlen($db)) {
609 $_url_params['db'] = $db;
610 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
611 } else {
612 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
615 $error_msg_output .= $doedit_goto
616 . PMA_getIcon('b_edit.png', __('Edit'))
617 . '</a>';
618 } // end if
619 $error_msg_output .= ' </p>' . "\n"
620 .' <p>' . "\n"
621 .' ' . $formatted_sql . "\n"
622 .' </p>' . "\n";
623 } // end if
625 $tmp_mysql_error = ''; // for saving the original $error_message
626 if (!empty($error_message)) {
627 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
628 $error_message = htmlspecialchars($error_message);
629 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
631 // modified to show the help on error-returns
632 // (now error-messages-server)
633 $error_msg_output .= '<p>' . "\n"
634 . ' <strong>' . __('MySQL said: ') . '</strong>'
635 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
636 . "\n"
637 . '</p>' . "\n";
639 // The error message will be displayed within a CODE segment.
640 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
642 // Replace all non-single blanks with their HTML-counterpart
643 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
644 // Replace TAB-characters with their HTML-counterpart
645 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
646 // Replace linebreaks
647 $error_message = nl2br($error_message);
649 $error_msg_output .= '<code>' . "\n"
650 . $error_message . "\n"
651 . '</code><br />' . "\n";
652 $error_msg_output .= '</div>';
654 $_SESSION['Import_message']['message'] = $error_msg_output;
656 if ($exit) {
657 if (! empty($back_url)) {
658 if (strstr($back_url, '?')) {
659 $back_url .= '&amp;no_history=true';
660 } else {
661 $back_url .= '?no_history=true';
664 $_SESSION['Import_message']['go_back_url'] = $back_url;
666 $error_msg_output .= '<fieldset class="tblFooters">';
667 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
668 $error_msg_output .= '</fieldset>' . "\n\n";
671 echo $error_msg_output;
673 * display footer and exit
676 require_once './libraries/footer.inc.php';
677 } else {
678 echo $error_msg_output;
680 } // end of the 'PMA_mysqlDie()' function
683 * Send HTTP header, taking IIS limits into account (600 seems ok)
685 * @uses PMA_IS_IIS
686 * @uses PMA_COMING_FROM_COOKIE_LOGIN
687 * @uses PMA_get_arg_separator()
688 * @uses SID
689 * @uses strlen()
690 * @uses strpos()
691 * @uses header()
692 * @uses session_write_close()
693 * @uses headers_sent()
694 * @uses function_exists()
695 * @uses debug_print_backtrace()
696 * @uses trigger_error()
697 * @uses defined()
698 * @param string $uri the header to send
699 * @return boolean always true
701 function PMA_sendHeaderLocation($uri)
703 if (PMA_IS_IIS && strlen($uri) > 600) {
705 echo '<html><head><title>- - -</title>' . "\n";
706 echo '<meta http-equiv="expires" content="0">' . "\n";
707 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
708 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
709 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
710 echo '<script type="text/javascript">' . "\n";
711 echo '//<![CDATA[' . "\n";
712 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
713 echo '//]]>' . "\n";
714 echo '</script>' . "\n";
715 echo '</head>' . "\n";
716 echo '<body>' . "\n";
717 echo '<script type="text/javascript">' . "\n";
718 echo '//<![CDATA[' . "\n";
719 echo 'document.write(\'<p><a href="' . $uri . '">' . __('Go') . '</a></p>\');' . "\n";
720 echo '//]]>' . "\n";
721 echo '</script></body></html>' . "\n";
723 } else {
724 if (SID) {
725 if (strpos($uri, '?') === false) {
726 header('Location: ' . $uri . '?' . SID);
727 } else {
728 $separator = PMA_get_arg_separator();
729 header('Location: ' . $uri . $separator . SID);
731 } else {
732 session_write_close();
733 if (headers_sent()) {
734 if (function_exists('debug_print_backtrace')) {
735 echo '<pre>';
736 debug_print_backtrace();
737 echo '</pre>';
739 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
741 // bug #1523784: IE6 does not like 'Refresh: 0', it
742 // results in a blank page
743 // but we need it when coming from the cookie login panel)
744 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
745 header('Refresh: 0; ' . $uri);
746 } else {
747 header('Location: ' . $uri);
754 * returns array with tables of given db with extended information and grouped
756 * @uses $cfg['LeftFrameTableSeparator']
757 * @uses $cfg['LeftFrameTableLevel']
758 * @uses $cfg['ShowTooltipAliasTB']
759 * @uses $cfg['NaturalOrder']
760 * @uses PMA_backquote()
761 * @uses count()
762 * @uses array_merge
763 * @uses uksort()
764 * @uses strstr()
765 * @uses explode()
766 * @param string $db name of db
767 * @param string $tables name of tables
768 * @param integer $limit_offset list offset
769 * @param integer $limit_count max tables to return
770 * return array (recursive) grouped table list
772 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
774 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
776 if (null === $tables) {
777 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
778 if ($GLOBALS['cfg']['NaturalOrder']) {
779 uksort($tables, 'strnatcasecmp');
783 if (count($tables) < 1) {
784 return $tables;
787 $default = array(
788 'Name' => '',
789 'Rows' => 0,
790 'Comment' => '',
791 'disp_name' => '',
794 $table_groups = array();
796 // for blobstreaming - list of blobstreaming tables
798 // load PMA configuration
799 $PMA_Config = $GLOBALS['PMA_Config'];
801 // if PMA configuration exists
802 if (!empty($PMA_Config))
803 $session_bs_tables = $GLOBALS['PMA_Config']->get('BLOBSTREAMING_TABLES');
805 foreach ($tables as $table_name => $table) {
806 // if BS tables exist
807 if (isset($session_bs_tables))
808 // compare table name to tables in list of blobstreaming tables
809 foreach ($session_bs_tables as $table_key=>$table_val)
810 // if table is in list, skip outer foreach loop
811 if ($table_name == $table_key)
812 continue 2;
814 // check for correct row count
815 if (null === $table['Rows']) {
816 // Do not check exact row count here,
817 // if row count is invalid possibly the table is defect
818 // and this would break left frame;
819 // but we can check row count if this is a view or the
820 // information_schema database
821 // since PMA_Table::countRecords() returns a limited row count
822 // in this case.
824 // set this because PMA_Table::countRecords() can use it
825 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
827 if ($tbl_is_view || 'information_schema' == $db) {
828 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
832 // in $group we save the reference to the place in $table_groups
833 // where to store the table info
834 if ($GLOBALS['cfg']['LeftFrameDBTree']
835 && $sep && strstr($table_name, $sep))
837 $parts = explode($sep, $table_name);
839 $group =& $table_groups;
840 $i = 0;
841 $group_name_full = '';
842 $parts_cnt = count($parts) - 1;
843 while ($i < $parts_cnt
844 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
845 $group_name = $parts[$i] . $sep;
846 $group_name_full .= $group_name;
848 if (!isset($group[$group_name])) {
849 $group[$group_name] = array();
850 $group[$group_name]['is' . $sep . 'group'] = true;
851 $group[$group_name]['tab' . $sep . 'count'] = 1;
852 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
853 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
854 $table = $group[$group_name];
855 $group[$group_name] = array();
856 $group[$group_name][$group_name] = $table;
857 unset($table);
858 $group[$group_name]['is' . $sep . 'group'] = true;
859 $group[$group_name]['tab' . $sep . 'count'] = 1;
860 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
861 } else {
862 $group[$group_name]['tab' . $sep . 'count']++;
864 $group =& $group[$group_name];
865 $i++;
867 } else {
868 if (!isset($table_groups[$table_name])) {
869 $table_groups[$table_name] = array();
871 $group =& $table_groups;
875 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
876 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
877 // switch tooltip and name
878 $table['Comment'] = $table['Name'];
879 $table['disp_name'] = $table['Comment'];
880 } else {
881 $table['disp_name'] = $table['Name'];
884 $group[$table_name] = array_merge($default, $table);
887 return $table_groups;
890 /* ----------------------- Set of misc functions ----------------------- */
894 * Adds backquotes on both sides of a database, table or field name.
895 * and escapes backquotes inside the name with another backquote
897 * example:
898 * <code>
899 * echo PMA_backquote('owner`s db'); // `owner``s db`
901 * </code>
903 * @uses PMA_backquote()
904 * @uses is_array()
905 * @uses strlen()
906 * @uses str_replace()
907 * @param mixed $a_name the database, table or field name to "backquote"
908 * or array of it
909 * @param boolean $do_it a flag to bypass this function (used by dump
910 * functions)
911 * @return mixed the "backquoted" database, table or field name if the
912 * current MySQL release is >= 3.23.6, the original one
913 * else
914 * @access public
916 function PMA_backquote($a_name, $do_it = true)
918 if (is_array($a_name)) {
919 foreach ($a_name as &$data) {
920 $data = PMA_backquote($data, $do_it);
922 return $a_name;
925 if (! $do_it) {
926 global $PMA_SQPdata_forbidden_word;
927 global $PMA_SQPdata_forbidden_word_cnt;
929 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
930 return $a_name;
934 // '0' is also empty for php :-(
935 if (strlen($a_name) && $a_name !== '*') {
936 return '`' . str_replace('`', '``', $a_name) . '`';
937 } else {
938 return $a_name;
940 } // end of the 'PMA_backquote()' function
944 * Defines the <CR><LF> value depending on the user OS.
946 * @uses PMA_USR_OS
947 * @return string the <CR><LF> value to use
949 * @access public
951 function PMA_whichCrlf()
953 $the_crlf = "\n";
955 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
956 // Win case
957 if (PMA_USR_OS == 'Win') {
958 $the_crlf = "\r\n";
960 // Others
961 else {
962 $the_crlf = "\n";
965 return $the_crlf;
966 } // end of the 'PMA_whichCrlf()' function
969 * Reloads navigation if needed.
971 * @param $jsonly prints out pure JavaScript
972 * @uses $GLOBALS['reload']
973 * @uses $GLOBALS['db']
974 * @uses PMA_generate_common_url()
975 * @global array configuration
977 * @access public
979 function PMA_reloadNavigation($jsonly=false)
981 global $cfg;
983 // Reloads the navigation frame via JavaScript if required
984 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
985 // one of the reasons for a reload is when a table is dropped
986 // in this case, get rid of the table limit offset, otherwise
987 // we have a problem when dropping a table on the last page
988 // and the offset becomes greater than the total number of tables
989 unset($_SESSION['tmp_user_values']['table_limit_offset']);
990 echo "\n";
991 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
992 if (!$jsonly)
993 echo '<script type="text/javascript">' . PHP_EOL;
995 //<![CDATA[
996 if (typeof(window.parent) != 'undefined'
997 && typeof(window.parent.frame_navigation) != 'undefined'
998 && window.parent.goTo) {
999 window.parent.goTo('<?php echo $reload_url; ?>');
1001 //]]>
1002 <?php
1003 if (!$jsonly)
1004 echo '</script>' . PHP_EOL;
1006 unset($GLOBALS['reload']);
1011 * displays the message and the query
1012 * usually the message is the result of the query executed
1014 * @param string $message the message to display
1015 * @param string $sql_query the query to display
1016 * @param string $type the type (level) of the message
1017 * @param boolean $is_view is this a message after a VIEW operation?
1018 * @global array the configuration array
1019 * @uses $cfg
1020 * @access public
1022 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
1024 global $cfg;
1026 if (null === $sql_query) {
1027 if (! empty($GLOBALS['display_query'])) {
1028 $sql_query = $GLOBALS['display_query'];
1029 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1030 $sql_query = $GLOBALS['unparsed_sql'];
1031 } elseif (! empty($GLOBALS['sql_query'])) {
1032 $sql_query = $GLOBALS['sql_query'];
1033 } else {
1034 $sql_query = '';
1038 // Corrects the tooltip text via JS if required
1039 // @todo this is REALLY the wrong place to do this - very unexpected here
1040 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1041 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1042 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1043 echo "\n";
1044 echo '<script type="text/javascript">' . "\n";
1045 echo '//<![CDATA[' . "\n";
1046 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1047 echo '//]]>' . "\n";
1048 echo '</script>' . "\n";
1049 } // end if ... elseif
1051 // Checks if the table needs to be repaired after a TRUNCATE query.
1052 // @todo what about $GLOBALS['display_query']???
1053 // @todo this is REALLY the wrong place to do this - very unexpected here
1054 if (strlen($GLOBALS['table'])
1055 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1056 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1057 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1060 unset($tbl_status);
1062 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1064 if ($message instanceof PMA_Message) {
1065 if (isset($GLOBALS['special_message'])) {
1066 $message->addMessage($GLOBALS['special_message']);
1067 unset($GLOBALS['special_message']);
1069 $message->display();
1070 $type = $message->getLevel();
1071 } else {
1072 echo '<div class="' . $type . '">';
1073 echo PMA_sanitize($message);
1074 if (isset($GLOBALS['special_message'])) {
1075 echo PMA_sanitize($GLOBALS['special_message']);
1076 unset($GLOBALS['special_message']);
1078 echo '</div>';
1081 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1082 // Html format the query to be displayed
1083 // If we want to show some sql code it is easiest to create it here
1084 /* SQL-Parser-Analyzer */
1086 if (! empty($GLOBALS['show_as_php'])) {
1087 $new_line = '\\n"<br />' . "\n"
1088 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1089 $query_base = htmlspecialchars(addslashes($sql_query));
1090 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1091 } else {
1092 $query_base = $sql_query;
1095 $query_too_big = false;
1097 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1098 // when the query is large (for example an INSERT of binary
1099 // data), the parser chokes; so avoid parsing the query
1100 $query_too_big = true;
1101 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1102 } elseif (! empty($GLOBALS['parsed_sql'])
1103 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1104 // (here, use "! empty" because when deleting a bookmark,
1105 // $GLOBALS['parsed_sql'] is set but empty
1106 $parsed_sql = $GLOBALS['parsed_sql'];
1107 } else {
1108 // Parse SQL if needed
1109 $parsed_sql = PMA_SQP_parse($query_base);
1112 // Analyze it
1113 if (isset($parsed_sql)) {
1114 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1115 // Here we append the LIMIT added for navigation, to
1116 // enable its display. Adding it higher in the code
1117 // to $sql_query would create a problem when
1118 // using the Refresh or Edit links.
1120 // Only append it on SELECTs.
1123 * @todo what would be the best to do when someone hits Refresh:
1124 * use the current LIMITs ?
1127 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1128 && isset($GLOBALS['sql_limit_to_append'])) {
1129 $query_base = $analyzed_display_query[0]['section_before_limit']
1130 . "\n" . $GLOBALS['sql_limit_to_append']
1131 . $analyzed_display_query[0]['section_after_limit'];
1132 // Need to reparse query
1133 $parsed_sql = PMA_SQP_parse($query_base);
1137 if (! empty($GLOBALS['show_as_php'])) {
1138 $query_base = '$sql = "' . $query_base;
1139 } elseif (! empty($GLOBALS['validatequery'])) {
1140 $query_base = PMA_validateSQL($query_base);
1141 } elseif (isset($parsed_sql)) {
1142 $query_base = PMA_formatSql($parsed_sql, $query_base);
1145 // Prepares links that may be displayed to edit/explain the query
1146 // (don't go to default pages, we must go to the page
1147 // where the query box is available)
1149 // Basic url query part
1150 $url_params = array();
1151 if (strlen($GLOBALS['db'])) {
1152 $url_params['db'] = $GLOBALS['db'];
1153 if (strlen($GLOBALS['table'])) {
1154 $url_params['table'] = $GLOBALS['table'];
1155 $edit_link = 'tbl_sql.php';
1156 } else {
1157 $edit_link = 'db_sql.php';
1159 } else {
1160 $edit_link = 'server_sql.php';
1163 // Want to have the query explained (Mike Beck 2002-05-22)
1164 // but only explain a SELECT (that has not been explained)
1165 /* SQL-Parser-Analyzer */
1166 $explain_link = '';
1167 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1168 $explain_params = $url_params;
1169 // Detect if we are validating as well
1170 // To preserve the validate uRL data
1171 if (! empty($GLOBALS['validatequery'])) {
1172 $explain_params['validatequery'] = 1;
1175 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1176 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1177 $_message = __('Explain SQL');
1178 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1179 $explain_params['sql_query'] = substr($sql_query, 8);
1180 $_message = __('Skip Explain SQL');
1182 if (isset($explain_params['sql_query'])) {
1183 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1184 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1186 } //show explain
1188 $url_params['sql_query'] = $sql_query;
1189 $url_params['show_query'] = 1;
1191 // even if the query is big and was truncated, offer the chance
1192 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1193 if (! empty($cfg['SQLQuery']['Edit'])) {
1194 if ($cfg['EditInWindow'] == true) {
1195 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1196 } else {
1197 $onclick = '';
1200 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1201 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1202 } else {
1203 $edit_link = '';
1206 $url_qpart = PMA_generate_common_url($url_params);
1208 // Also we would like to get the SQL formed in some nice
1209 // php-code (Mike Beck 2002-05-22)
1210 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1211 $php_params = $url_params;
1213 if (! empty($GLOBALS['show_as_php'])) {
1214 $_message = __('Without PHP Code');
1215 } else {
1216 $php_params['show_as_php'] = 1;
1217 $_message = __('Create PHP Code');
1220 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1221 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1223 if (isset($GLOBALS['show_as_php'])) {
1224 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1225 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1227 } else {
1228 $php_link = '';
1229 } //show as php
1231 // Refresh query
1232 if (! empty($cfg['SQLQuery']['Refresh'])
1233 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1234 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1235 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1236 } else {
1237 $refresh_link = '';
1238 } //show as php
1240 if (! empty($cfg['SQLValidator']['use'])
1241 && ! empty($cfg['SQLQuery']['Validate'])) {
1242 $validate_params = $url_params;
1243 if (!empty($GLOBALS['validatequery'])) {
1244 $validate_message = __('Skip Validate SQL') ;
1245 } else {
1246 $validate_params['validatequery'] = 1;
1247 $validate_message = __('Validate SQL') ;
1250 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1251 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1252 } else {
1253 $validate_link = '';
1254 } //validator
1256 echo '<code class="sql">';
1257 if ($query_too_big) {
1258 echo $shortened_query_base;
1259 } else {
1260 echo $query_base;
1263 //Clean up the end of the PHP
1264 if (! empty($GLOBALS['show_as_php'])) {
1265 echo '";';
1267 echo '</code>';
1269 echo '<div class="tools">';
1270 // avoid displaying a Profiling checkbox that could
1271 // be checked, which would reexecute an INSERT, for example
1272 if (! empty($refresh_link)) {
1273 PMA_profilingCheckbox($sql_query);
1275 $inline_edit = "<script type=\"text/javascript\">\n" .
1276 "//<![CDATA[\n" .
1277 "document.write('[<a href=\"#\" title=\"" .
1278 PMA_escapeJsString(__('Inline edit of this query')) .
1279 "\" id=\"inline_edit\">" .
1280 PMA_escapeJsString(__('Inline')) .
1281 "</a>]');\n" .
1282 "//]]>\n" .
1283 "</script>";
1284 echo $inline_edit . $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1285 echo '</div>';
1287 echo '</div><br />' . "\n";
1288 } // end of the 'PMA_showMessage()' function
1291 * Verifies if current MySQL server supports profiling
1293 * @uses $_SESSION['profiling_supported'] for caching
1294 * @uses $GLOBALS['server']
1295 * @uses PMA_DBI_fetch_value()
1296 * @uses PMA_MYSQL_INT_VERSION
1297 * @uses defined()
1298 * @access public
1299 * @return boolean whether profiling is supported
1302 function PMA_profilingSupported()
1304 if (! PMA_cacheExists('profiling_supported', true)) {
1305 // 5.0.37 has profiling but for example, 5.1.20 does not
1306 // (avoid a trip to the server for MySQL before 5.0.37)
1307 // and do not set a constant as we might be switching servers
1308 if (defined('PMA_MYSQL_INT_VERSION')
1309 && PMA_MYSQL_INT_VERSION >= 50037
1310 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1311 PMA_cacheSet('profiling_supported', true, true);
1312 } else {
1313 PMA_cacheSet('profiling_supported', false, true);
1317 return PMA_cacheGet('profiling_supported', true);
1321 * Displays a form with the Profiling checkbox
1323 * @param string $sql_query
1324 * @access public
1327 function PMA_profilingCheckbox($sql_query)
1329 if (PMA_profilingSupported()) {
1330 echo '<form action="sql.php" method="post">' . "\n";
1331 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1332 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1333 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1334 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1335 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1336 echo '</form>' . "\n";
1341 * Displays the results of SHOW PROFILE
1343 * @param array the results
1344 * @access public
1347 function PMA_profilingResults($profiling_results)
1349 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1350 echo '<table>' . "\n";
1351 echo ' <tr>' . "\n";
1352 echo ' <th>' . __('Status') . '</th>' . "\n";
1353 echo ' <th>' . __('Time') . '</th>' . "\n";
1354 echo ' </tr>' . "\n";
1356 foreach($profiling_results as $one_result) {
1357 echo ' <tr>' . "\n";
1358 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1359 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1361 echo '</table>' . "\n";
1362 echo '</fieldset>' . "\n";
1366 * Formats $value to byte view
1368 * @param double the value to format
1369 * @param integer the sensitiveness
1370 * @param integer the number of decimals to retain
1372 * @return array the formatted value and its unit
1374 * @access public
1376 * @version 1.2 - 18 July 2002
1378 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1380 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1381 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1383 $dh = PMA_pow(10, $comma);
1384 $li = PMA_pow(10, $limes);
1385 $return_value = $value;
1386 $unit = $byteUnits[0];
1388 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1389 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1390 // use 1024.0 to avoid integer overflow on 64-bit machines
1391 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1392 $unit = $byteUnits[$d];
1393 break 1;
1394 } // end if
1395 } // end for
1397 if ($unit != $byteUnits[0]) {
1398 // if the unit is not bytes (as represented in current language)
1399 // reformat with max length of 5
1400 // 4th parameter=true means do not reformat if value < 1
1401 $return_value = PMA_formatNumber($value, 5, $comma, true);
1402 } else {
1403 // do not reformat, just handle the locale
1404 $return_value = PMA_formatNumber($value, 0);
1407 return array(trim($return_value), $unit);
1408 } // end of the 'PMA_formatByteDown' function
1411 * Changes thousands and decimal separators to locale specific values.
1413 function PMA_localizeNumber($value)
1415 return str_replace(
1416 array(',', '.'),
1417 array(
1418 /* l10n: Thousands separator */
1419 __(','),
1420 /* l10n: Decimal separator */
1421 __('.'),
1423 $value);
1427 * Formats $value to the given length and appends SI prefixes
1428 * $comma is not substracted from the length
1429 * with a $length of 0 no truncation occurs, number is only formated
1430 * to the current locale
1432 * examples:
1433 * <code>
1434 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1435 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1436 * echo PMA_formatNumber(-0.003, 6); // -3 m
1437 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1438 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1439 * echo PMA_formatNumber(0, 6); // 0
1441 * </code>
1442 * @param double $value the value to format
1443 * @param integer $length the max length
1444 * @param integer $comma the number of decimals to retain
1445 * @param boolean $only_down do not reformat numbers below 1
1447 * @return string the formatted value and its unit
1449 * @access public
1451 * @version 1.1.0 - 2005-10-27
1453 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1455 //number_format is not multibyte safe, str_replace is safe
1456 if ($length === 0) {
1457 return PMA_localizeNumber(number_format($value, $comma));
1460 // this units needs no translation, ISO
1461 $units = array(
1462 -8 => 'y',
1463 -7 => 'z',
1464 -6 => 'a',
1465 -5 => 'f',
1466 -4 => 'p',
1467 -3 => 'n',
1468 -2 => '&micro;',
1469 -1 => 'm',
1470 0 => ' ',
1471 1 => 'k',
1472 2 => 'M',
1473 3 => 'G',
1474 4 => 'T',
1475 5 => 'P',
1476 6 => 'E',
1477 7 => 'Z',
1478 8 => 'Y'
1481 // we need at least 3 digits to be displayed
1482 if (3 > $length + $comma) {
1483 $length = 3 - $comma;
1486 // check for negative value to retain sign
1487 if ($value < 0) {
1488 $sign = '-';
1489 $value = abs($value);
1490 } else {
1491 $sign = '';
1494 $dh = PMA_pow(10, $comma);
1495 $li = PMA_pow(10, $length);
1496 $unit = $units[0];
1498 if ($value >= 1) {
1499 for ($d = 8; $d >= 0; $d--) {
1500 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1501 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1502 $unit = $units[$d];
1503 break 1;
1504 } // end if
1505 } // end for
1506 } elseif (!$only_down && (float) $value !== 0.0) {
1507 for ($d = -8; $d <= 8; $d++) {
1508 // force using pow() because of the negative exponent
1509 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1510 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1511 $unit = $units[$d];
1512 break 1;
1513 } // end if
1514 } // end for
1515 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1517 //number_format is not multibyte safe, str_replace is safe
1518 $value = PMA_localizeNumber(number_format($value, $comma));
1520 return $sign . $value . ' ' . $unit;
1521 } // end of the 'PMA_formatNumber' function
1524 * Returns the number of bytes when a formatted size is given
1526 * @param string $size the size expression (for example 8MB)
1527 * @uses PMA_pow()
1528 * @return integer The numerical part of the expression (for example 8)
1530 function PMA_extractValueFromFormattedSize($formatted_size)
1532 $return_value = -1;
1534 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1535 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1536 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1537 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1538 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1539 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1541 return $return_value;
1542 }// end of the 'PMA_extractValueFromFormattedSize' function
1545 * Writes localised date
1547 * @param string the current timestamp
1549 * @return string the formatted date
1551 * @access public
1553 function PMA_localisedDate($timestamp = -1, $format = '')
1555 $month = array(
1556 /* l10n: Short month name */
1557 __('Jan'),
1558 /* l10n: Short month name */
1559 __('Feb'),
1560 /* l10n: Short month name */
1561 __('Mar'),
1562 /* l10n: Short month name */
1563 __('Apr'),
1564 /* l10n: Short month name */
1565 _pgettext('Short month name', 'May'),
1566 /* l10n: Short month name */
1567 __('Jun'),
1568 /* l10n: Short month name */
1569 __('Jul'),
1570 /* l10n: Short month name */
1571 __('Aug'),
1572 /* l10n: Short month name */
1573 __('Sep'),
1574 /* l10n: Short month name */
1575 __('Oct'),
1576 /* l10n: Short month name */
1577 __('Nov'),
1578 /* l10n: Short month name */
1579 __('Dec'));
1580 $day_of_week = array(
1581 /* l10n: Short week day name */
1582 __('Sun'),
1583 /* l10n: Short week day name */
1584 __('Mon'),
1585 /* l10n: Short week day name */
1586 __('Tue'),
1587 /* l10n: Short week day name */
1588 __('Wed'),
1589 /* l10n: Short week day name */
1590 __('Thu'),
1591 /* l10n: Short week day name */
1592 __('Fri'),
1593 /* l10n: Short week day name */
1594 __('Sat'));
1596 if ($format == '') {
1597 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1598 $format = __('%B %d, %Y at %I:%M %p');
1601 if ($timestamp == -1) {
1602 $timestamp = time();
1605 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1606 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1608 return strftime($date, $timestamp);
1609 } // end of the 'PMA_localisedDate()' function
1613 * returns a tab for tabbed navigation.
1614 * If the variables $link and $args ar left empty, an inactive tab is created
1616 * @uses $GLOBALS['PMA_PHP_SELF']
1617 * @uses __('Empty')
1618 * @uses __('Drop')
1619 * @uses $GLOBALS['active_page']
1620 * @uses $GLOBALS['url_query']
1621 * @uses $cfg['MainPageIconic']
1622 * @uses $GLOBALS['pmaThemeImage']
1623 * @uses PMA_generate_common_url()
1624 * @uses E_USER_NOTICE
1625 * @uses htmlentities()
1626 * @uses urlencode()
1627 * @uses sprintf()
1628 * @uses trigger_error()
1629 * @uses array_merge()
1630 * @uses basename()
1631 * @param array $tab array with all options
1632 * @param array $url_params
1633 * @return string html code for one tab, a link if valid otherwise a span
1634 * @access public
1636 function PMA_generate_html_tab($tab, $url_params = array())
1638 // default values
1639 $defaults = array(
1640 'text' => '',
1641 'class' => '',
1642 'active' => false,
1643 'link' => '',
1644 'sep' => '?',
1645 'attr' => '',
1646 'args' => '',
1647 'warning' => '',
1648 'fragment' => '',
1651 $tab = array_merge($defaults, $tab);
1653 // determine additionnal style-class
1654 if (empty($tab['class'])) {
1655 if ($tab['text'] == __('Empty')
1656 || $tab['text'] == __('Drop')) {
1657 $tab['class'] = 'caution';
1658 } elseif (! empty($tab['active'])
1659 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1660 $tab['class'] = 'active';
1661 } elseif (empty($GLOBALS['active_page'])
1662 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1663 && empty($tab['warning'])) {
1664 $tab['class'] = 'active';
1668 if (!empty($tab['warning'])) {
1669 $tab['class'] .= ' warning';
1670 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1673 // If there are any tab specific URL parameters, merge those with the general URL parameters
1674 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1675 $url_params = array_merge($url_params, $tab['url_params']);
1678 // build the link
1679 if (!empty($tab['link'])) {
1680 $tab['link'] = htmlentities($tab['link']);
1681 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1682 if (! empty($tab['args'])) {
1683 foreach ($tab['args'] as $param => $value) {
1684 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1685 . urlencode($value);
1690 if (! empty($tab['fragment'])) {
1691 $tab['link'] .= $tab['fragment'];
1694 // display icon, even if iconic is disabled but the link-text is missing
1695 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1696 && isset($tab['icon'])) {
1697 // avoid generating an alt tag, because it only illustrates
1698 // the text that follows and if browser does not display
1699 // images, the text is duplicated
1700 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1701 .'%1$s" width="16" height="16" alt="" />%2$s';
1702 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1704 // check to not display an empty link-text
1705 elseif (empty($tab['text'])) {
1706 $tab['text'] = '?';
1707 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1708 E_USER_NOTICE);
1711 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1713 if (!empty($tab['link'])) {
1714 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1715 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1716 . $tab['text'] . '</a>';
1717 } else {
1718 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1719 . $tab['text'] . '</span>';
1722 $out .= '</li>';
1723 return $out;
1724 } // end of the 'PMA_generate_html_tab()' function
1727 * returns html-code for a tab navigation
1729 * @uses PMA_generate_html_tab()
1730 * @uses htmlentities()
1731 * @param array $tabs one element per tab
1732 * @param string $url_params
1733 * @return string html-code for tab-navigation
1735 function PMA_generate_html_tabs($tabs, $url_params)
1737 $tag_id = 'topmenu';
1738 $tab_navigation =
1739 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1740 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1742 foreach ($tabs as $tab) {
1743 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1746 $tab_navigation .=
1747 '</ul>' . "\n"
1748 .'<div class="clearfloat"></div>'
1749 .'</div>' . "\n";
1751 return $tab_navigation;
1756 * Displays a link, or a button if the link's URL is too large, to
1757 * accommodate some browsers' limitations
1759 * @param string the URL
1760 * @param string the link message
1761 * @param mixed $tag_params string: js confirmation
1762 * array: additional tag params (f.e. style="")
1763 * @param boolean $new_form we set this to false when we are already in
1764 * a form, to avoid generating nested forms
1766 * @return string the results to be echoed or saved in an array
1768 function PMA_linkOrButton($url, $message, $tag_params = array(),
1769 $new_form = true, $strip_img = false, $target = '')
1771 $url_length = strlen($url);
1772 // with this we should be able to catch case of image upload
1773 // into a (MEDIUM) BLOB; not worth generating even a form for these
1774 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1775 return '';
1778 if (! is_array($tag_params)) {
1779 $tmp = $tag_params;
1780 $tag_params = array();
1781 if (!empty($tmp)) {
1782 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1784 unset($tmp);
1786 if (! empty($target)) {
1787 $tag_params['target'] = htmlentities($target);
1790 $tag_params_strings = array();
1791 foreach ($tag_params as $par_name => $par_value) {
1792 // htmlspecialchars() only on non javascript
1793 $par_value = substr($par_name, 0, 2) == 'on'
1794 ? $par_value
1795 : htmlspecialchars($par_value);
1796 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1799 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1800 // no whitespace within an <a> else Safari will make it part of the link
1801 $ret = "\n" . '<a href="' . $url . '" '
1802 . implode(' ', $tag_params_strings) . '>'
1803 . $message . '</a>' . "\n";
1804 } else {
1805 // no spaces (linebreaks) at all
1806 // or after the hidden fields
1807 // IE will display them all
1809 // add class=link to submit button
1810 if (empty($tag_params['class'])) {
1811 $tag_params['class'] = 'link';
1814 // decode encoded url separators
1815 $separator = PMA_get_arg_separator();
1816 // on most places separator is still hard coded ...
1817 if ($separator !== '&') {
1818 // ... so always replace & with $separator
1819 $url = str_replace(htmlentities('&'), $separator, $url);
1820 $url = str_replace('&', $separator, $url);
1822 $url = str_replace(htmlentities($separator), $separator, $url);
1823 // end decode
1825 $url_parts = parse_url($url);
1826 $query_parts = explode($separator, $url_parts['query']);
1827 if ($new_form) {
1828 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1829 . ' method="post"' . $target . ' style="display: inline;">';
1830 $subname_open = '';
1831 $subname_close = '';
1832 $submit_name = '';
1833 } else {
1834 $query_parts[] = 'redirect=' . $url_parts['path'];
1835 if (empty($GLOBALS['subform_counter'])) {
1836 $GLOBALS['subform_counter'] = 0;
1838 $GLOBALS['subform_counter']++;
1839 $ret = '';
1840 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1841 $subname_close = ']';
1842 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1844 foreach ($query_parts as $query_pair) {
1845 list($eachvar, $eachval) = explode('=', $query_pair);
1846 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1847 . $subname_close . '" value="'
1848 . htmlspecialchars(urldecode($eachval)) . '" />';
1849 } // end while
1851 if (stristr($message, '<img')) {
1852 if ($strip_img) {
1853 $message = trim(strip_tags($message));
1854 $ret .= '<input type="submit"' . $submit_name . ' '
1855 . implode(' ', $tag_params_strings)
1856 . ' value="' . htmlspecialchars($message) . '" />';
1857 } else {
1858 $displayed_message = htmlspecialchars(
1859 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1860 $message));
1861 $ret .= '<input type="image"' . $submit_name . ' '
1862 . implode(' ', $tag_params_strings)
1863 . ' src="' . preg_replace(
1864 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1865 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1867 } else {
1868 $message = trim(strip_tags($message));
1869 $ret .= '<input type="submit"' . $submit_name . ' '
1870 . implode(' ', $tag_params_strings)
1871 . ' value="' . htmlspecialchars($message) . '" />';
1873 if ($new_form) {
1874 $ret .= '</form>';
1876 } // end if... else...
1878 return $ret;
1879 } // end of the 'PMA_linkOrButton()' function
1883 * Returns a given timespan value in a readable format.
1885 * @uses __('%s days, %s hours, %s minutes and %s seconds')
1886 * @uses sprintf()
1887 * @uses floor()
1888 * @param int the timespan
1890 * @return string the formatted value
1892 function PMA_timespanFormat($seconds)
1894 $return_string = '';
1895 $days = floor($seconds / 86400);
1896 if ($days > 0) {
1897 $seconds -= $days * 86400;
1899 $hours = floor($seconds / 3600);
1900 if ($days > 0 || $hours > 0) {
1901 $seconds -= $hours * 3600;
1903 $minutes = floor($seconds / 60);
1904 if ($days > 0 || $hours > 0 || $minutes > 0) {
1905 $seconds -= $minutes * 60;
1907 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1911 * Takes a string and outputs each character on a line for itself. Used
1912 * mainly for horizontalflipped display mode.
1913 * Takes care of special html-characters.
1914 * Fulfills todo-item
1915 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1917 * @todo add a multibyte safe function PMA_STR_split()
1918 * @uses strlen
1919 * @param string The string
1920 * @param string The Separator (defaults to "<br />\n")
1922 * @access public
1923 * @return string The flipped string
1925 function PMA_flipstring($string, $Separator = "<br />\n")
1927 $format_string = '';
1928 $charbuff = false;
1930 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1931 $char = $string{$i};
1932 $append = false;
1934 if ($char == '&') {
1935 $format_string .= $charbuff;
1936 $charbuff = $char;
1937 } elseif ($char == ';' && !empty($charbuff)) {
1938 $format_string .= $charbuff . $char;
1939 $charbuff = false;
1940 $append = true;
1941 } elseif (! empty($charbuff)) {
1942 $charbuff .= $char;
1943 } else {
1944 $format_string .= $char;
1945 $append = true;
1948 // do not add separator after the last character
1949 if ($append && ($i != $str_len - 1)) {
1950 $format_string .= $Separator;
1954 return $format_string;
1959 * Function added to avoid path disclosures.
1960 * Called by each script that needs parameters, it displays
1961 * an error message and, by default, stops the execution.
1963 * Not sure we could use a strMissingParameter message here,
1964 * would have to check if the error message file is always available
1966 * @todo localize error message
1967 * @todo use PMA_fatalError() if $die === true?
1968 * @uses PMA_getenv()
1969 * @uses header_meta_style.inc.php
1970 * @uses $GLOBALS['PMA_PHP_SELF']
1971 * basename
1972 * @param array The names of the parameters needed by the calling
1973 * script.
1974 * @param boolean Stop the execution?
1975 * (Set this manually to false in the calling script
1976 * until you know all needed parameters to check).
1977 * @param boolean Whether to include this list in checking for special params.
1978 * @global string path to current script
1979 * @global boolean flag whether any special variable was required
1981 * @access public
1983 function PMA_checkParameters($params, $die = true, $request = true)
1985 global $checked_special;
1987 if (!isset($checked_special)) {
1988 $checked_special = false;
1991 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1992 $found_error = false;
1993 $error_message = '';
1995 foreach ($params as $param) {
1996 if ($request && $param != 'db' && $param != 'table') {
1997 $checked_special = true;
2000 if (!isset($GLOBALS[$param])) {
2001 $error_message .= $reported_script_name
2002 . ': Missing parameter: ' . $param
2003 . PMA_showDocu('faqmissingparameters')
2004 . '<br />';
2005 $found_error = true;
2008 if ($found_error) {
2010 * display html meta tags
2012 require_once './libraries/header_meta_style.inc.php';
2013 echo '</head><body><p>' . $error_message . '</p></body></html>';
2014 if ($die) {
2015 exit();
2018 } // end function
2021 * Function to generate unique condition for specified row.
2023 * @uses $GLOBALS['analyzed_sql'][0]
2024 * @uses PMA_DBI_field_flags()
2025 * @uses PMA_backquote()
2026 * @uses PMA_sqlAddslashes()
2027 * @uses PMA_printable_bit_value()
2028 * @uses stristr()
2029 * @uses bin2hex()
2030 * @uses preg_replace()
2031 * @param resource $handle current query result
2032 * @param integer $fields_cnt number of fields
2033 * @param array $fields_meta meta information about fields
2034 * @param array $row current row
2035 * @param boolean $force_unique generate condition only on pk or unique
2037 * @access public
2038 * @return string the calculated condition and whether condition is unique
2040 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
2042 $primary_key = '';
2043 $unique_key = '';
2044 $nonprimary_condition = '';
2045 $preferred_condition = '';
2047 for ($i = 0; $i < $fields_cnt; ++$i) {
2048 $condition = '';
2049 $field_flags = PMA_DBI_field_flags($handle, $i);
2050 $meta = $fields_meta[$i];
2052 // do not use a column alias in a condition
2053 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2054 $meta->orgname = $meta->name;
2056 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2057 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2058 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2059 as $select_expr) {
2060 // need (string) === (string)
2061 // '' !== 0 but '' == 0
2062 if ((string) $select_expr['alias'] === (string) $meta->name) {
2063 $meta->orgname = $select_expr['column'];
2064 break;
2065 } // end if
2066 } // end foreach
2070 // Do not use a table alias in a condition.
2071 // Test case is:
2072 // select * from galerie x WHERE
2073 //(select count(*) from galerie y where y.datum=x.datum)>1
2075 // But orgtable is present only with mysqli extension so the
2076 // fix is only for mysqli.
2077 // Also, do not use the original table name if we are dealing with
2078 // a view because this view might be updatable.
2079 // (The isView() verification should not be costly in most cases
2080 // because there is some caching in the function).
2081 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
2082 $meta->table = $meta->orgtable;
2085 // to fix the bug where float fields (primary or not)
2086 // can't be matched because of the imprecision of
2087 // floating comparison, use CONCAT
2088 // (also, the syntax "CONCAT(field) IS NULL"
2089 // that we need on the next "if" will work)
2090 if ($meta->type == 'real') {
2091 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
2092 . PMA_backquote($meta->orgname) . ') ';
2093 } else {
2094 $condition = ' ' . PMA_backquote($meta->table) . '.'
2095 . PMA_backquote($meta->orgname) . ' ';
2096 } // end if... else...
2098 if (!isset($row[$i]) || is_null($row[$i])) {
2099 $condition .= 'IS NULL AND';
2100 } else {
2101 // timestamp is numeric on some MySQL 4.1
2102 if ($meta->numeric && $meta->type != 'timestamp') {
2103 $condition .= '= ' . $row[$i] . ' AND';
2104 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2105 // hexify only if this is a true not empty BLOB or a BINARY
2106 && stristr($field_flags, 'BINARY')
2107 && !empty($row[$i])) {
2108 // do not waste memory building a too big condition
2109 if (strlen($row[$i]) < 1000) {
2110 // use a CAST if possible, to avoid problems
2111 // if the field contains wildcard characters % or _
2112 $condition .= '= CAST(0x' . bin2hex($row[$i])
2113 . ' AS BINARY) AND';
2114 } else {
2115 // this blob won't be part of the final condition
2116 $condition = '';
2118 } elseif ($meta->type == 'bit') {
2119 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2120 } else {
2121 $condition .= '= \''
2122 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2125 if ($meta->primary_key > 0) {
2126 $primary_key .= $condition;
2127 } elseif ($meta->unique_key > 0) {
2128 $unique_key .= $condition;
2130 $nonprimary_condition .= $condition;
2131 } // end for
2133 // Correction University of Virginia 19991216:
2134 // prefer primary or unique keys for condition,
2135 // but use conjunction of all values if no primary key
2136 $clause_is_unique = true;
2137 if ($primary_key) {
2138 $preferred_condition = $primary_key;
2139 } elseif ($unique_key) {
2140 $preferred_condition = $unique_key;
2141 } elseif (! $force_unique) {
2142 $preferred_condition = $nonprimary_condition;
2143 $clause_is_unique = false;
2146 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2147 return(array($where_clause, $clause_is_unique));
2148 } // end function
2151 * Generate a button or image tag
2153 * @uses PMA_USR_BROWSER_AGENT
2154 * @uses $GLOBALS['pmaThemeImage']
2155 * @uses $GLOBALS['cfg']['PropertiesIconic']
2156 * @param string name of button element
2157 * @param string class of button element
2158 * @param string name of image element
2159 * @param string text to display
2160 * @param string image to display
2162 * @access public
2164 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2165 $image)
2167 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2168 echo ' <input type="submit" name="' . $button_name . '"'
2169 .' value="' . htmlspecialchars($text) . '"'
2170 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2171 return;
2174 /* Opera has trouble with <input type="image"> */
2175 /* IE has trouble with <button> */
2176 if (PMA_USR_BROWSER_AGENT != 'IE') {
2177 echo '<button class="' . $button_class . '" type="submit"'
2178 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2179 .' title="' . htmlspecialchars($text) . '">' . "\n"
2180 . PMA_getIcon($image, $text)
2181 .'</button>' . "\n";
2182 } else {
2183 echo '<input type="image" name="' . $image_name . '" value="'
2184 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2185 . $image . '" />'
2186 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2188 } // end function
2191 * Generate a pagination selector for browsing resultsets
2193 * @todo $url is not javascript escaped!?
2194 * @uses __('Page number:')
2195 * @uses range()
2196 * @param string URL for the JavaScript
2197 * @param string Number of rows in the pagination set
2198 * @param string current page number
2199 * @param string number of total pages
2200 * @param string If the number of pages is lower than this
2201 * variable, no pages will be omitted in
2202 * pagination
2203 * @param string How many rows at the beginning should always
2204 * be shown?
2205 * @param string How many rows at the end should always
2206 * be shown?
2207 * @param string Percentage of calculation page offsets to
2208 * hop to a next page
2209 * @param string Near the current page, how many pages should
2210 * be considered "nearby" and displayed as
2211 * well?
2212 * @param string The prompt to display (sometimes empty)
2214 * @access public
2216 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2217 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2218 $range = 10, $prompt = '')
2220 $increment = floor($nbTotalPage / $percent);
2221 $pageNowMinusRange = ($pageNow - $range);
2222 $pageNowPlusRange = ($pageNow + $range);
2224 $gotopage = $prompt
2225 . ' <select name="pos" onchange="goToUrl(this, \''
2226 . $url . '\');">' . "\n";
2227 if ($nbTotalPage < $showAll) {
2228 $pages = range(1, $nbTotalPage);
2229 } else {
2230 $pages = array();
2232 // Always show first X pages
2233 for ($i = 1; $i <= $sliceStart; $i++) {
2234 $pages[] = $i;
2237 // Always show last X pages
2238 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2239 $pages[] = $i;
2242 // Based on the number of results we add the specified
2243 // $percent percentage to each page number,
2244 // so that we have a representing page number every now and then to
2245 // immediately jump to specific pages.
2246 // As soon as we get near our currently chosen page ($pageNow -
2247 // $range), every page number will be shown.
2248 $i = $sliceStart;
2249 $x = $nbTotalPage - $sliceEnd;
2250 $met_boundary = false;
2251 while ($i <= $x) {
2252 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2253 // If our pageselector comes near the current page, we use 1
2254 // counter increments
2255 $i++;
2256 $met_boundary = true;
2257 } else {
2258 // We add the percentage increment to our current page to
2259 // hop to the next one in range
2260 $i += $increment;
2262 // Make sure that we do not cross our boundaries.
2263 if ($i > $pageNowMinusRange && ! $met_boundary) {
2264 $i = $pageNowMinusRange;
2268 if ($i > 0 && $i <= $x) {
2269 $pages[] = $i;
2273 // Since because of ellipsing of the current page some numbers may be double,
2274 // we unify our array:
2275 sort($pages);
2276 $pages = array_unique($pages);
2279 foreach ($pages as $i) {
2280 if ($i == $pageNow) {
2281 $selected = 'selected="selected" style="font-weight: bold"';
2282 } else {
2283 $selected = '';
2285 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2288 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2290 return $gotopage;
2291 } // end function
2295 * Generate navigation for a list
2297 * @todo use $pos from $_url_params
2298 * @uses __('Page number:')
2299 * @uses range()
2300 * @param integer number of elements in the list
2301 * @param integer current position in the list
2302 * @param array url parameters
2303 * @param string script name for form target
2304 * @param string target frame
2305 * @param integer maximum number of elements to display from the list
2307 * @access public
2309 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2311 if ($max_count < $count) {
2312 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2313 echo __('Page number:');
2314 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2316 // Move to the beginning or to the previous page
2317 if ($pos > 0) {
2318 // patch #474210 - part 1
2319 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2320 $caption1 = '&lt;&lt;';
2321 $caption2 = ' &lt; ';
2322 $title1 = ' title="' . __('Begin') . '"';
2323 $title2 = ' title="' . __('Previous') . '"';
2324 } else {
2325 $caption1 = __('Begin') . ' &lt;&lt;';
2326 $caption2 = __('Previous') . ' &lt;';
2327 $title1 = '';
2328 $title2 = '';
2329 } // end if... else...
2330 $_url_params['pos'] = 0;
2331 echo '<a' . $title1 . ' href="' . $script
2332 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2333 . $caption1 . '</a>';
2334 $_url_params['pos'] = $pos - $max_count;
2335 echo '<a' . $title2 . ' href="' . $script
2336 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2337 . $caption2 . '</a>';
2340 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2341 echo PMA_generate_common_hidden_inputs($_url_params);
2342 echo PMA_pageselector(
2343 $script . PMA_generate_common_url($_url_params) . '&amp;',
2344 $max_count,
2345 floor(($pos + 1) / $max_count) + 1,
2346 ceil($count / $max_count));
2347 echo '</form>';
2349 if ($pos + $max_count < $count) {
2350 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2351 $caption3 = ' &gt; ';
2352 $caption4 = '&gt;&gt;';
2353 $title3 = ' title="' . __('Next') . '"';
2354 $title4 = ' title="' . __('End') . '"';
2355 } else {
2356 $caption3 = '&gt; ' . __('Next');
2357 $caption4 = '&gt;&gt; ' . __('End');
2358 $title3 = '';
2359 $title4 = '';
2360 } // end if... else...
2361 $_url_params['pos'] = $pos + $max_count;
2362 echo '<a' . $title3 . ' href="' . $script
2363 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2364 . $caption3 . '</a>';
2365 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2366 if ($_url_params['pos'] == $count) {
2367 $_url_params['pos'] = $count - $max_count;
2369 echo '<a' . $title4 . ' href="' . $script
2370 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2371 . $caption4 . '</a>';
2373 echo "\n";
2374 if ('frame_navigation' == $frame) {
2375 echo '</div>' . "\n";
2381 * replaces %u in given path with current user name
2383 * example:
2384 * <code>
2385 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2387 * </code>
2388 * @uses $cfg['Server']['user']
2389 * @uses substr()
2390 * @uses str_replace()
2391 * @param string $dir with wildcard for user
2392 * @return string per user directory
2394 function PMA_userDir($dir)
2396 // add trailing slash
2397 if (substr($dir, -1) != '/') {
2398 $dir .= '/';
2401 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2405 * returns html code for db link to default db page
2407 * @uses $cfg['DefaultTabDatabase']
2408 * @uses $GLOBALS['db']
2409 * @uses __('Jump to database &quot;%s&quot;.')
2410 * @uses PMA_generate_common_url()
2411 * @uses PMA_unescape_mysql_wildcards()
2412 * @uses strlen()
2413 * @uses sprintf()
2414 * @uses htmlspecialchars()
2415 * @param string $database
2416 * @return string html link to default db page
2418 function PMA_getDbLink($database = null)
2420 if (!strlen($database)) {
2421 if (!strlen($GLOBALS['db'])) {
2422 return '';
2424 $database = $GLOBALS['db'];
2425 } else {
2426 $database = PMA_unescape_mysql_wildcards($database);
2429 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2430 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2431 .htmlspecialchars($database) . '</a>';
2435 * Displays a lightbulb hint explaining a known external bug
2436 * that affects a functionality
2438 * @uses PMA_MYSQL_INT_VERSION
2439 * @uses __('The %s functionality is affected by a known bug, see %s')
2440 * @uses PMA_showHint()
2441 * @uses sprintf()
2442 * @param string $functionality localized message explaining the func.
2443 * @param string $component 'mysql' (eventually, 'php')
2444 * @param string $minimum_version of this component
2445 * @param string $bugref bug reference for this component
2447 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2449 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2450 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, 'http://bugs.mysql.com/' . $bugref));
2455 * Generates and echoes an HTML checkbox
2457 * @param string $html_field_name the checkbox HTML field
2458 * @param string $label
2459 * @param boolean $checked is it initially checked?
2460 * @param boolean $onclick should it submit the form on click?
2462 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2464 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>';
2468 * Generates and echoes a set of radio HTML fields
2470 * @uses htmlspecialchars()
2471 * @param string $html_field_name the radio HTML field
2472 * @param array $choices the choices values and labels
2473 * @param string $checked_choice the choice to check by default
2474 * @param boolean $line_break whether to add an HTML line break after a choice
2475 * @param boolean $escape_label whether to use htmlspecialchars() on label
2476 * @param string $class enclose each choice with a div of this class
2478 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2479 foreach ($choices as $choice_value => $choice_label) {
2480 if (! empty($class)) {
2481 echo '<div class="' . $class . '">';
2483 $html_field_id = $html_field_name . '_' . $choice_value;
2484 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2485 if ($choice_value == $checked_choice) {
2486 echo ' checked="checked"';
2488 echo ' />' . "\n";
2489 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2490 if ($line_break) {
2491 echo '<br />';
2493 if (! empty($class)) {
2494 echo '</div>';
2496 echo "\n";
2501 * Generates and returns an HTML dropdown
2503 * @uses htmlspecialchars()
2504 * @param string $select_name
2505 * @param array $choices the choices values
2506 * @param string $active_choice the choice to select by default
2507 * @param string $id the id of the select element; can be different in case
2508 * the dropdown is present more than once on the page
2509 * @todo support titles
2511 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2513 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2514 foreach ($choices as $one_choice_value => $one_choice_label) {
2515 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2516 if ($one_choice_value == $active_choice) {
2517 $result .= ' selected="selected"';
2519 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2521 $result .= '</select>';
2522 return $result;
2526 * Generates a slider effect (jQjuery)
2527 * Takes care of generating the initial <div> and the link
2528 * controlling the slider; you have to generate the </div> yourself
2529 * after the sliding section.
2531 * @uses $GLOBALS['cfg']['InitialSlidersState']
2532 * @param string $id the id of the <div> on which to apply the effect
2533 * @param string $message the message to show as a link
2535 function PMA_generate_slider_effect($id, $message)
2537 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2538 echo '<div id="' . $id . '">';
2539 return;
2542 <script type="text/javascript">
2543 // <![CDATA[
2544 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none; overflow:auto;"' : ''; ?>>');
2546 function PMA_set_status_label_<?php echo $id; ?>() {
2547 if ($('#<?php echo $id; ?>').css('display') == 'none') {
2548 $('#anchor_status_<?php echo $id; ?>').text('+ ');
2549 } else {
2550 $('#anchor_status_<?php echo $id; ?>').text('- ');
2554 $(document).ready(function() {
2556 $('<span id="anchor_status_<?php echo $id; ?>"><span>')
2557 .insertBefore('#<?php echo $id; ?>')
2559 PMA_set_status_label_<?php echo $id; ?>();
2561 $('<a href="#<?php echo $id; ?>" id="anchor_<?php echo $id; ?>"><?php echo htmlspecialchars($message); ?></a>')
2562 .insertBefore('#<?php echo $id; ?>')
2563 .click(function() {
2564 // the callback should be the 4th parameter but
2565 // it only works as the second parameter
2566 $('#<?php echo $id; ?>').toggle('drop', function() {
2567 PMA_set_status_label_<?php echo $id; ?>();
2571 //]]>
2572 </script>
2573 <noscript>
2574 <div id="<?php echo $id; ?>">
2575 </noscript>
2576 <?php
2580 * Verifies if something is cached in the session
2582 * @param string $var
2583 * @param scalar $server
2584 * @return boolean
2586 function PMA_cacheExists($var, $server = 0)
2588 if (true === $server) {
2589 $server = $GLOBALS['server'];
2591 return isset($_SESSION['cache']['server_' . $server][$var]);
2595 * Gets cached information from the session
2597 * @param string $var
2598 * @param scalar $server
2599 * @return mixed
2601 function PMA_cacheGet($var, $server = 0)
2603 if (true === $server) {
2604 $server = $GLOBALS['server'];
2606 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2607 return $_SESSION['cache']['server_' . $server][$var];
2608 } else {
2609 return null;
2614 * Caches information in the session
2616 * @param string $var
2617 * @param mixed $val
2618 * @param integer $server
2619 * @return mixed
2621 function PMA_cacheSet($var, $val = null, $server = 0)
2623 if (true === $server) {
2624 $server = $GLOBALS['server'];
2626 $_SESSION['cache']['server_' . $server][$var] = $val;
2630 * Removes cached information from the session
2632 * @param string $var
2633 * @param scalar $server
2635 function PMA_cacheUnset($var, $server = 0)
2637 if (true === $server) {
2638 $server = $GLOBALS['server'];
2640 unset($_SESSION['cache']['server_' . $server][$var]);
2644 * Converts a bit value to printable format;
2645 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2646 * function because in PHP, decbin() supports only 32 bits
2648 * @uses ceil()
2649 * @uses decbin()
2650 * @uses ord()
2651 * @uses substr()
2652 * @uses sprintf()
2653 * @param numeric $value coming from a BIT field
2654 * @param integer $length
2655 * @return string the printable value
2657 function PMA_printable_bit_value($value, $length) {
2658 $printable = '';
2659 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2660 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2662 $printable = substr($printable, -$length);
2663 return $printable;
2667 * Verifies whether the value contains a non-printable character
2669 * @uses preg_match()
2670 * @param string $value
2671 * @return boolean
2673 function PMA_contains_nonprintable_ascii($value) {
2674 return preg_match('@[^[:print:]]@', $value);
2678 * Converts a BIT type default value
2679 * for example, b'010' becomes 010
2681 * @uses strtr()
2682 * @param string $bit_default_value
2683 * @return string the converted value
2685 function PMA_convert_bit_default_value($bit_default_value) {
2686 return strtr($bit_default_value, array("b" => "", "'" => ""));
2690 * Extracts the various parts from a field type spec
2692 * @uses strpos()
2693 * @uses chop()
2694 * @uses substr()
2695 * @param string $fieldspec
2696 * @return array associative array containing type, spec_in_brackets
2697 * and possibly enum_set_values (another array)
2699 function PMA_extractFieldSpec($fieldspec) {
2700 $first_bracket_pos = strpos($fieldspec, '(');
2701 if ($first_bracket_pos) {
2702 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2703 // convert to lowercase just to be sure
2704 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2705 } else {
2706 $type = $fieldspec;
2707 $spec_in_brackets = '';
2710 if ('enum' == $type || 'set' == $type) {
2711 // Define our working vars
2712 $enum_set_values = array();
2713 $working = "";
2714 $in_string = false;
2715 $index = 0;
2717 // While there is another character to process
2718 while (isset($fieldspec[$index])) {
2719 // Grab the char to look at
2720 $char = $fieldspec[$index];
2722 // If it is a single quote, needs to be handled specially
2723 if ($char == "'") {
2724 // If we are not currently in a string, begin one
2725 if (! $in_string) {
2726 $in_string = true;
2727 $working = "";
2728 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2729 } else {
2730 // Check out the next character (if possible)
2731 $has_next = isset($fieldspec[$index + 1]);
2732 $next = $has_next ? $fieldspec[$index + 1] : null;
2734 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2735 if (! $has_next || $next != "'") {
2736 $enum_set_values[] = $working;
2737 $in_string = false;
2739 // Otherwise, this is a 'double quote', and can be added to the working string
2740 } elseif ($next == "'") {
2741 $working .= "'";
2742 // Skip the next char; we already know what it is
2743 $index++;
2746 // escaping of a quote?
2747 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2748 $working .= "'";
2749 $index++;
2750 // Otherwise, add it to our working string like normal
2751 } else {
2752 $working .= $char;
2754 // Increment character index
2755 $index++;
2756 } // end while
2757 } else {
2758 $enum_set_values = array();
2761 return array(
2762 'type' => $type,
2763 'spec_in_brackets' => $spec_in_brackets,
2764 'enum_set_values' => $enum_set_values
2769 * Verifies if this table's engine supports foreign keys
2771 * @uses strtoupper()
2772 * @param string $engine
2773 * @return boolean
2775 function PMA_foreignkey_supported($engine) {
2776 $engine = strtoupper($engine);
2777 if ('INNODB' == $engine || 'PBXT' == $engine) {
2778 return true;
2779 } else {
2780 return false;
2785 * Replaces some characters by a displayable equivalent
2787 * @uses str_replace()
2788 * @param string $content
2789 * @return string the content with characters replaced
2791 function PMA_replace_binary_contents($content) {
2792 $result = str_replace("\x00", '\0', $content);
2793 $result = str_replace("\x08", '\b', $result);
2794 $result = str_replace("\x0a", '\n', $result);
2795 $result = str_replace("\x0d", '\r', $result);
2796 $result = str_replace("\x1a", '\Z', $result);
2797 return $result;
2802 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2804 * @uses strpos()
2805 * @return string with the chars replaced
2808 function PMA_duplicateFirstNewline($string){
2809 $first_occurence = strpos($string, "\r\n");
2810 if ($first_occurence === 0){
2811 $string = "\n".$string;
2813 return $string;
2817 * get the action word corresponding to a script name
2818 * in order to display it as a title in navigation panel
2820 * @uses $GLOBALS
2821 * @param string a valid value for $cfg['LeftDefaultTabTable']
2822 * or $cfg['DefaultTabTable']
2823 * or $cfg['DefaultTabDatabase']
2825 function PMA_getTitleForTarget($target) {
2827 $mapping = array(
2828 // Values for $cfg['DefaultTabTable']
2829 'tbl_structure.php' => __('Structure'),
2830 'tbl_sql.php' => __('SQL'),
2831 'tbl_select.php' =>__('Search'),
2832 'tbl_change.php' =>__('Insert'),
2833 'sql.php' => __('Browse'),
2835 // Values for $cfg['DefaultTabDatabase']
2836 'db_structure.php' => __('Structure'),
2837 'db_sql.php' => __('SQL'),
2838 'db_search.php' => __('Search'),
2839 'db_operations.php' => __('Operations'),
2841 return $mapping[$target];
2844 function PMA_js($code, $print=true)
2846 // these generated newlines are needed
2847 $out = '';
2848 $out .= '<script type="text/javascript">'."\n";
2849 $out .= "\n" . '// <![CDATA[' . "\n";
2850 $out .= $code;
2851 $out .= "\n" . '// ]]>' . "\n";
2852 $out .= '</script>'."\n";
2854 if ($print)
2855 echo $out;
2857 return $out;