remove deprecated parameter of PMA_Table::countRecords()
[phpmyadmin/madhuracj.git] / libraries / common.lib.php
blob94d7d8240b471baabb62d1bac169555876ac3657
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 (! $do_it) {
905 return $a_name;
908 if (is_array($a_name)) {
909 $result = array();
910 foreach ($a_name as $key => $val) {
911 $result[$key] = PMA_backquote($val);
913 return $result;
916 // '0' is also empty for php :-(
917 if (strlen($a_name) && $a_name !== '*') {
918 return '`' . str_replace('`', '``', $a_name) . '`';
919 } else {
920 return $a_name;
922 } // end of the 'PMA_backquote()' function
926 * Defines the <CR><LF> value depending on the user OS.
928 * @uses PMA_USR_OS
929 * @return string the <CR><LF> value to use
931 * @access public
933 function PMA_whichCrlf()
935 $the_crlf = "\n";
937 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
938 // Win case
939 if (PMA_USR_OS == 'Win') {
940 $the_crlf = "\r\n";
942 // Others
943 else {
944 $the_crlf = "\n";
947 return $the_crlf;
948 } // end of the 'PMA_whichCrlf()' function
951 * Reloads navigation if needed.
953 * @param $jsonly prints out pure JavaScript
954 * @uses $GLOBALS['reload']
955 * @uses $GLOBALS['db']
956 * @uses PMA_generate_common_url()
957 * @global array configuration
959 * @access public
961 function PMA_reloadNavigation($jsonly=false)
963 global $cfg;
965 // Reloads the navigation frame via JavaScript if required
966 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
967 // one of the reasons for a reload is when a table is dropped
968 // in this case, get rid of the table limit offset, otherwise
969 // we have a problem when dropping a table on the last page
970 // and the offset becomes greater than the total number of tables
971 unset($_SESSION['tmp_user_values']['table_limit_offset']);
972 echo "\n";
973 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
974 if (!$jsonly)
975 echo '<script type="text/javascript">' . PHP_EOL;
977 //<![CDATA[
978 if (typeof(window.parent) != 'undefined'
979 && typeof(window.parent.frame_navigation) != 'undefined'
980 && window.parent.goTo) {
981 window.parent.goTo('<?php echo $reload_url; ?>');
983 //]]>
984 <?php
985 if (!$jsonly)
986 echo '</script>' . PHP_EOL;
988 unset($GLOBALS['reload']);
993 * displays the message and the query
994 * usually the message is the result of the query executed
996 * @param string $message the message to display
997 * @param string $sql_query the query to display
998 * @param string $type the type (level) of the message
999 * @global array the configuration array
1000 * @uses $cfg
1001 * @access public
1003 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
1005 global $cfg;
1007 if (null === $sql_query) {
1008 if (! empty($GLOBALS['display_query'])) {
1009 $sql_query = $GLOBALS['display_query'];
1010 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
1011 $sql_query = $GLOBALS['unparsed_sql'];
1012 } elseif (! empty($GLOBALS['sql_query'])) {
1013 $sql_query = $GLOBALS['sql_query'];
1014 } else {
1015 $sql_query = '';
1019 // Corrects the tooltip text via JS if required
1020 // @todo this is REALLY the wrong place to do this - very unexpected here
1021 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1022 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1023 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1024 echo "\n";
1025 echo '<script type="text/javascript">' . "\n";
1026 echo '//<![CDATA[' . "\n";
1027 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1028 echo '//]]>' . "\n";
1029 echo '</script>' . "\n";
1030 } // end if ... elseif
1032 // Checks if the table needs to be repaired after a TRUNCATE query.
1033 // @todo what about $GLOBALS['display_query']???
1034 // @todo this is REALLY the wrong place to do this - very unexpected here
1035 if (strlen($GLOBALS['table'])
1036 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1037 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1038 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1041 unset($tbl_status);
1043 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1045 if ($message instanceof PMA_Message) {
1046 if (isset($GLOBALS['special_message'])) {
1047 $message->addMessage($GLOBALS['special_message']);
1048 unset($GLOBALS['special_message']);
1050 $message->display();
1051 $type = $message->getLevel();
1052 } else {
1053 echo '<div class="' . $type . '">';
1054 echo PMA_sanitize($message);
1055 if (isset($GLOBALS['special_message'])) {
1056 echo PMA_sanitize($GLOBALS['special_message']);
1057 unset($GLOBALS['special_message']);
1059 echo '</div>';
1062 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1063 // Html format the query to be displayed
1064 // If we want to show some sql code it is easiest to create it here
1065 /* SQL-Parser-Analyzer */
1067 if (! empty($GLOBALS['show_as_php'])) {
1068 $new_line = '\\n"<br />' . "\n"
1069 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1070 $query_base = htmlspecialchars(addslashes($sql_query));
1071 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1072 } else {
1073 $query_base = $sql_query;
1076 $query_too_big = false;
1078 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1079 // when the query is large (for example an INSERT of binary
1080 // data), the parser chokes; so avoid parsing the query
1081 $query_too_big = true;
1082 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1083 } elseif (! empty($GLOBALS['parsed_sql'])
1084 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1085 // (here, use "! empty" because when deleting a bookmark,
1086 // $GLOBALS['parsed_sql'] is set but empty
1087 $parsed_sql = $GLOBALS['parsed_sql'];
1088 } else {
1089 // Parse SQL if needed
1090 $parsed_sql = PMA_SQP_parse($query_base);
1093 // Analyze it
1094 if (isset($parsed_sql)) {
1095 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1096 // Here we append the LIMIT added for navigation, to
1097 // enable its display. Adding it higher in the code
1098 // to $sql_query would create a problem when
1099 // using the Refresh or Edit links.
1101 // Only append it on SELECTs.
1104 * @todo what would be the best to do when someone hits Refresh:
1105 * use the current LIMITs ?
1108 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1109 && isset($GLOBALS['sql_limit_to_append'])) {
1110 $query_base = $analyzed_display_query[0]['section_before_limit']
1111 . "\n" . $GLOBALS['sql_limit_to_append']
1112 . $analyzed_display_query[0]['section_after_limit'];
1113 // Need to reparse query
1114 $parsed_sql = PMA_SQP_parse($query_base);
1118 if (! empty($GLOBALS['show_as_php'])) {
1119 $query_base = '$sql = "' . $query_base;
1120 } elseif (! empty($GLOBALS['validatequery'])) {
1121 $query_base = PMA_validateSQL($query_base);
1122 } elseif (isset($parsed_sql)) {
1123 $query_base = PMA_formatSql($parsed_sql, $query_base);
1126 // Prepares links that may be displayed to edit/explain the query
1127 // (don't go to default pages, we must go to the page
1128 // where the query box is available)
1130 // Basic url query part
1131 $url_params = array();
1132 if (strlen($GLOBALS['db'])) {
1133 $url_params['db'] = $GLOBALS['db'];
1134 if (strlen($GLOBALS['table'])) {
1135 $url_params['table'] = $GLOBALS['table'];
1136 $edit_link = 'tbl_sql.php';
1137 } else {
1138 $edit_link = 'db_sql.php';
1140 } else {
1141 $edit_link = 'server_sql.php';
1144 // Want to have the query explained (Mike Beck 2002-05-22)
1145 // but only explain a SELECT (that has not been explained)
1146 /* SQL-Parser-Analyzer */
1147 $explain_link = '';
1148 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1149 $explain_params = $url_params;
1150 // Detect if we are validating as well
1151 // To preserve the validate uRL data
1152 if (! empty($GLOBALS['validatequery'])) {
1153 $explain_params['validatequery'] = 1;
1156 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1157 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1158 $_message = $GLOBALS['strExplain'];
1159 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1160 $explain_params['sql_query'] = substr($sql_query, 8);
1161 $_message = $GLOBALS['strNoExplain'];
1163 if (isset($explain_params['sql_query'])) {
1164 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1165 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1167 } //show explain
1169 $url_params['sql_query'] = $sql_query;
1170 $url_params['show_query'] = 1;
1172 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1173 if ($cfg['EditInWindow'] == true) {
1174 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1175 } else {
1176 $onclick = '';
1179 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1180 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1181 } else {
1182 $edit_link = '';
1185 $url_qpart = PMA_generate_common_url($url_params);
1187 // Also we would like to get the SQL formed in some nice
1188 // php-code (Mike Beck 2002-05-22)
1189 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1190 $php_params = $url_params;
1192 if (! empty($GLOBALS['show_as_php'])) {
1193 $_message = $GLOBALS['strNoPhp'];
1194 } else {
1195 $php_params['show_as_php'] = 1;
1196 $_message = $GLOBALS['strPhp'];
1199 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1200 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1202 if (isset($GLOBALS['show_as_php'])) {
1203 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1204 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1206 } else {
1207 $php_link = '';
1208 } //show as php
1210 // Refresh query
1211 if (! empty($cfg['SQLQuery']['Refresh'])
1212 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1213 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1214 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1215 } else {
1216 $refresh_link = '';
1217 } //show as php
1219 if (! empty($cfg['SQLValidator']['use'])
1220 && ! empty($cfg['SQLQuery']['Validate'])) {
1221 $validate_params = $url_params;
1222 if (!empty($GLOBALS['validatequery'])) {
1223 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1224 } else {
1225 $validate_params['validatequery'] = 1;
1226 $validate_message = $GLOBALS['strValidateSQL'] ;
1229 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1230 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1231 } else {
1232 $validate_link = '';
1233 } //validator
1235 echo '<code class="sql">';
1236 if ($query_too_big) {
1237 echo $shortened_query_base;
1238 } else {
1239 echo $query_base;
1242 //Clean up the end of the PHP
1243 if (! empty($GLOBALS['show_as_php'])) {
1244 echo '";';
1246 echo '</code>';
1248 echo '<div class="tools">';
1249 // avoid displaying a Profiling checkbox that could
1250 // be checked, which would reexecute an INSERT, for example
1251 if (! empty($refresh_link)) {
1252 PMA_profilingCheckbox($sql_query);
1254 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1255 echo '</div>';
1257 echo '</div><br />' . "\n";
1258 } // end of the 'PMA_showMessage()' function
1261 * Verifies if current MySQL server supports profiling
1263 * @uses $_SESSION['profiling_supported'] for caching
1264 * @uses $GLOBALS['server']
1265 * @uses PMA_DBI_fetch_value()
1266 * @uses PMA_MYSQL_INT_VERSION
1267 * @uses defined()
1268 * @access public
1269 * @return boolean whether profiling is supported
1271 * @author Marc Delisle
1273 function PMA_profilingSupported()
1275 if (! PMA_cacheExists('profiling_supported', true)) {
1276 // 5.0.37 has profiling but for example, 5.1.20 does not
1277 // (avoid a trip to the server for MySQL before 5.0.37)
1278 // and do not set a constant as we might be switching servers
1279 if (defined('PMA_MYSQL_INT_VERSION')
1280 && PMA_MYSQL_INT_VERSION >= 50037
1281 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1282 PMA_cacheSet('profiling_supported', true, true);
1283 } else {
1284 PMA_cacheSet('profiling_supported', false, true);
1288 return PMA_cacheGet('profiling_supported', true);
1292 * Displays a form with the Profiling checkbox
1294 * @param string $sql_query
1295 * @access public
1297 * @author Marc Delisle
1299 function PMA_profilingCheckbox($sql_query)
1301 if (PMA_profilingSupported()) {
1302 echo '<form action="sql.php" method="post">' . "\n";
1303 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1304 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1305 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1306 PMA_display_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1307 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1308 echo '</form>' . "\n";
1313 * Displays the results of SHOW PROFILE
1315 * @param array the results
1316 * @access public
1318 * @author Marc Delisle
1320 function PMA_profilingResults($profiling_results)
1322 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1323 echo '<table>' . "\n";
1324 echo ' <tr>' . "\n";
1325 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1326 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1327 echo ' </tr>' . "\n";
1329 foreach($profiling_results as $one_result) {
1330 echo ' <tr>' . "\n";
1331 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1332 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1334 echo '</table>' . "\n";
1335 echo '</fieldset>' . "\n";
1339 * Formats $value to byte view
1341 * @param double the value to format
1342 * @param integer the sensitiveness
1343 * @param integer the number of decimals to retain
1345 * @return array the formatted value and its unit
1347 * @access public
1349 * @author staybyte
1350 * @version 1.2 - 18 July 2002
1352 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1354 $dh = PMA_pow(10, $comma);
1355 $li = PMA_pow(10, $limes);
1356 $return_value = $value;
1357 $unit = $GLOBALS['byteUnits'][0];
1359 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1360 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1361 // use 1024.0 to avoid integer overflow on 64-bit machines
1362 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1363 $unit = $GLOBALS['byteUnits'][$d];
1364 break 1;
1365 } // end if
1366 } // end for
1368 if ($unit != $GLOBALS['byteUnits'][0]) {
1369 // if the unit is not bytes (as represented in current language)
1370 // reformat with max length of 5
1371 // 4th parameter=true means do not reformat if value < 1
1372 $return_value = PMA_formatNumber($value, 5, $comma, true);
1373 } else {
1374 // do not reformat, just handle the locale
1375 $return_value = PMA_formatNumber($value, 0);
1378 return array($return_value, $unit);
1379 } // end of the 'PMA_formatByteDown' function
1382 * Formats $value to the given length and appends SI prefixes
1383 * $comma is not substracted from the length
1384 * with a $length of 0 no truncation occurs, number is only formated
1385 * to the current locale
1387 * examples:
1388 * <code>
1389 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1390 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1391 * echo PMA_formatNumber(-0.003, 6); // -3 m
1392 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1393 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1394 * echo PMA_formatNumber(0, 6); // 0
1396 * </code>
1397 * @param double $value the value to format
1398 * @param integer $length the max length
1399 * @param integer $comma the number of decimals to retain
1400 * @param boolean $only_down do not reformat numbers below 1
1402 * @return string the formatted value and its unit
1404 * @access public
1406 * @author staybyte, sebastian mendel
1407 * @version 1.1.0 - 2005-10-27
1409 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1411 //number_format is not multibyte safe, str_replace is safe
1412 if ($length === 0) {
1413 return str_replace(array(',', '.'),
1414 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1415 number_format($value, $comma));
1418 // this units needs no translation, ISO
1419 $units = array(
1420 -8 => 'y',
1421 -7 => 'z',
1422 -6 => 'a',
1423 -5 => 'f',
1424 -4 => 'p',
1425 -3 => 'n',
1426 -2 => '&micro;',
1427 -1 => 'm',
1428 0 => ' ',
1429 1 => 'k',
1430 2 => 'M',
1431 3 => 'G',
1432 4 => 'T',
1433 5 => 'P',
1434 6 => 'E',
1435 7 => 'Z',
1436 8 => 'Y'
1439 // we need at least 3 digits to be displayed
1440 if (3 > $length + $comma) {
1441 $length = 3 - $comma;
1444 // check for negative value to retain sign
1445 if ($value < 0) {
1446 $sign = '-';
1447 $value = abs($value);
1448 } else {
1449 $sign = '';
1452 $dh = PMA_pow(10, $comma);
1453 $li = PMA_pow(10, $length);
1454 $unit = $units[0];
1456 if ($value >= 1) {
1457 for ($d = 8; $d >= 0; $d--) {
1458 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1459 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1460 $unit = $units[$d];
1461 break 1;
1462 } // end if
1463 } // end for
1464 } elseif (!$only_down && (float) $value !== 0.0) {
1465 for ($d = -8; $d <= 8; $d++) {
1466 // force using pow() because of the negative exponent
1467 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1468 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1469 $unit = $units[$d];
1470 break 1;
1471 } // end if
1472 } // end for
1473 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1475 //number_format is not multibyte safe, str_replace is safe
1476 $value = str_replace(array(',', '.'),
1477 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1478 number_format($value, $comma));
1480 return $sign . $value . ' ' . $unit;
1481 } // end of the 'PMA_formatNumber' function
1484 * Writes localised date
1486 * @param string the current timestamp
1488 * @return string the formatted date
1490 * @access public
1492 function PMA_localisedDate($timestamp = -1, $format = '')
1494 global $datefmt, $month, $day_of_week;
1496 if ($format == '') {
1497 $format = $datefmt;
1500 if ($timestamp == -1) {
1501 $timestamp = time();
1504 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1505 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1507 return strftime($date, $timestamp);
1508 } // end of the 'PMA_localisedDate()' function
1512 * returns a tab for tabbed navigation.
1513 * If the variables $link and $args ar left empty, an inactive tab is created
1515 * @uses $GLOBALS['PMA_PHP_SELF']
1516 * @uses $GLOBALS['strEmpty']
1517 * @uses $GLOBALS['strDrop']
1518 * @uses $GLOBALS['active_page']
1519 * @uses $GLOBALS['url_query']
1520 * @uses $cfg['MainPageIconic']
1521 * @uses $GLOBALS['pmaThemeImage']
1522 * @uses PMA_generate_common_url()
1523 * @uses E_USER_NOTICE
1524 * @uses htmlentities()
1525 * @uses urlencode()
1526 * @uses sprintf()
1527 * @uses trigger_error()
1528 * @uses array_merge()
1529 * @uses basename()
1530 * @param array $tab array with all options
1531 * @param array $url_params
1532 * @return string html code for one tab, a link if valid otherwise a span
1533 * @access public
1535 function PMA_generate_html_tab($tab, $url_params = array())
1537 // default values
1538 $defaults = array(
1539 'text' => '',
1540 'class' => '',
1541 'active' => false,
1542 'link' => '',
1543 'sep' => '?',
1544 'attr' => '',
1545 'args' => '',
1546 'warning' => '',
1547 'fragment' => '',
1550 $tab = array_merge($defaults, $tab);
1552 // determine additionnal style-class
1553 if (empty($tab['class'])) {
1554 if ($tab['text'] == $GLOBALS['strEmpty']
1555 || $tab['text'] == $GLOBALS['strDrop']) {
1556 $tab['class'] = 'caution';
1557 } elseif (! empty($tab['active'])
1558 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1559 $tab['class'] = 'active';
1560 } elseif (empty($GLOBALS['active_page'])
1561 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1562 && empty($tab['warning'])) {
1563 $tab['class'] = 'active';
1567 if (!empty($tab['warning'])) {
1568 $tab['class'] .= ' warning';
1569 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1572 // build the link
1573 if (!empty($tab['link'])) {
1574 $tab['link'] = htmlentities($tab['link']);
1575 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1576 if (! empty($tab['args'])) {
1577 foreach ($tab['args'] as $param => $value) {
1578 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1579 . urlencode($value);
1584 if (! empty($tab['fragment'])) {
1585 $tab['link'] .= $tab['fragment'];
1588 // display icon, even if iconic is disabled but the link-text is missing
1589 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1590 && isset($tab['icon'])) {
1591 // avoid generating an alt tag, because it only illustrates
1592 // the text that follows and if browser does not display
1593 // images, the text is duplicated
1594 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1595 .'%1$s" width="16" height="16" alt="" />%2$s';
1596 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1598 // check to not display an empty link-text
1599 elseif (empty($tab['text'])) {
1600 $tab['text'] = '?';
1601 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1602 E_USER_NOTICE);
1605 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1607 if (!empty($tab['link'])) {
1608 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1609 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1610 . $tab['text'] . '</a>';
1611 } else {
1612 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1613 . $tab['text'] . '</span>';
1616 $out .= '</li>';
1617 return $out;
1618 } // end of the 'PMA_generate_html_tab()' function
1621 * returns html-code for a tab navigation
1623 * @uses PMA_generate_html_tab()
1624 * @uses htmlentities()
1625 * @param array $tabs one element per tab
1626 * @param string $url_params
1627 * @return string html-code for tab-navigation
1629 function PMA_generate_html_tabs($tabs, $url_params)
1631 $tag_id = 'topmenu';
1632 $tab_navigation =
1633 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1634 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1636 foreach ($tabs as $tab) {
1637 $tab_navigation .= PMA_generate_html_tab($tab, $url_params) . "\n";
1640 $tab_navigation .=
1641 '</ul>' . "\n"
1642 .'<div class="clearfloat"></div>'
1643 .'</div>' . "\n";
1645 return $tab_navigation;
1650 * Displays a link, or a button if the link's URL is too large, to
1651 * accommodate some browsers' limitations
1653 * @param string the URL
1654 * @param string the link message
1655 * @param mixed $tag_params string: js confirmation
1656 * array: additional tag params (f.e. style="")
1657 * @param boolean $new_form we set this to false when we are already in
1658 * a form, to avoid generating nested forms
1660 * @return string the results to be echoed or saved in an array
1662 function PMA_linkOrButton($url, $message, $tag_params = array(),
1663 $new_form = true, $strip_img = false, $target = '')
1665 if (! is_array($tag_params)) {
1666 $tmp = $tag_params;
1667 $tag_params = array();
1668 if (!empty($tmp)) {
1669 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1671 unset($tmp);
1673 if (! empty($target)) {
1674 $tag_params['target'] = htmlentities($target);
1677 $tag_params_strings = array();
1678 foreach ($tag_params as $par_name => $par_value) {
1679 // htmlspecialchars() only on non javascript
1680 $par_value = substr($par_name, 0, 2) == 'on'
1681 ? $par_value
1682 : htmlspecialchars($par_value);
1683 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1686 if (strlen($url) <= $GLOBALS['cfg']['LinkLengthLimit']) {
1687 // no whitespace within an <a> else Safari will make it part of the link
1688 $ret = "\n" . '<a href="' . $url . '" '
1689 . implode(' ', $tag_params_strings) . '>'
1690 . $message . '</a>' . "\n";
1691 } else {
1692 // no spaces (linebreaks) at all
1693 // or after the hidden fields
1694 // IE will display them all
1696 // add class=link to submit button
1697 if (empty($tag_params['class'])) {
1698 $tag_params['class'] = 'link';
1701 // decode encoded url separators
1702 $separator = PMA_get_arg_separator();
1703 // on most places separator is still hard coded ...
1704 if ($separator !== '&') {
1705 // ... so always replace & with $separator
1706 $url = str_replace(htmlentities('&'), $separator, $url);
1707 $url = str_replace('&', $separator, $url);
1709 $url = str_replace(htmlentities($separator), $separator, $url);
1710 // end decode
1712 $url_parts = parse_url($url);
1713 $query_parts = explode($separator, $url_parts['query']);
1714 if ($new_form) {
1715 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1716 . ' method="post"' . $target . ' style="display: inline;">';
1717 $subname_open = '';
1718 $subname_close = '';
1719 $submit_name = '';
1720 } else {
1721 $query_parts[] = 'redirect=' . $url_parts['path'];
1722 if (empty($GLOBALS['subform_counter'])) {
1723 $GLOBALS['subform_counter'] = 0;
1725 $GLOBALS['subform_counter']++;
1726 $ret = '';
1727 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1728 $subname_close = ']';
1729 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1731 foreach ($query_parts as $query_pair) {
1732 list($eachvar, $eachval) = explode('=', $query_pair);
1733 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1734 . $subname_close . '" value="'
1735 . htmlspecialchars(urldecode($eachval)) . '" />';
1736 } // end while
1738 if (stristr($message, '<img')) {
1739 if ($strip_img) {
1740 $message = trim(strip_tags($message));
1741 $ret .= '<input type="submit"' . $submit_name . ' '
1742 . implode(' ', $tag_params_strings)
1743 . ' value="' . htmlspecialchars($message) . '" />';
1744 } else {
1745 $ret .= '<input type="image"' . $submit_name . ' '
1746 . implode(' ', $tag_params_strings)
1747 . ' src="' . preg_replace(
1748 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1749 . ' value="' . htmlspecialchars(
1750 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1751 $message))
1752 . '" />';
1754 } else {
1755 $message = trim(strip_tags($message));
1756 $ret .= '<input type="submit"' . $submit_name . ' '
1757 . implode(' ', $tag_params_strings)
1758 . ' value="' . htmlspecialchars($message) . '" />';
1760 if ($new_form) {
1761 $ret .= '</form>';
1763 } // end if... else...
1765 return $ret;
1766 } // end of the 'PMA_linkOrButton()' function
1770 * Returns a given timespan value in a readable format.
1772 * @uses $GLOBALS['timespanfmt']
1773 * @uses sprintf()
1774 * @uses floor()
1775 * @param int the timespan
1777 * @return string the formatted value
1779 function PMA_timespanFormat($seconds)
1781 $return_string = '';
1782 $days = floor($seconds / 86400);
1783 if ($days > 0) {
1784 $seconds -= $days * 86400;
1786 $hours = floor($seconds / 3600);
1787 if ($days > 0 || $hours > 0) {
1788 $seconds -= $hours * 3600;
1790 $minutes = floor($seconds / 60);
1791 if ($days > 0 || $hours > 0 || $minutes > 0) {
1792 $seconds -= $minutes * 60;
1794 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1798 * Takes a string and outputs each character on a line for itself. Used
1799 * mainly for horizontalflipped display mode.
1800 * Takes care of special html-characters.
1801 * Fulfills todo-item
1802 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1804 * @todo add a multibyte safe function PMA_STR_split()
1805 * @uses strlen
1806 * @param string The string
1807 * @param string The Separator (defaults to "<br />\n")
1809 * @access public
1810 * @author Garvin Hicking <me@supergarv.de>
1811 * @return string The flipped string
1813 function PMA_flipstring($string, $Separator = "<br />\n")
1815 $format_string = '';
1816 $charbuff = false;
1818 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1819 $char = $string{$i};
1820 $append = false;
1822 if ($char == '&') {
1823 $format_string .= $charbuff;
1824 $charbuff = $char;
1825 } elseif ($char == ';' && !empty($charbuff)) {
1826 $format_string .= $charbuff . $char;
1827 $charbuff = false;
1828 $append = true;
1829 } elseif (! empty($charbuff)) {
1830 $charbuff .= $char;
1831 } else {
1832 $format_string .= $char;
1833 $append = true;
1836 // do not add separator after the last character
1837 if ($append && ($i != $str_len - 1)) {
1838 $format_string .= $Separator;
1842 return $format_string;
1847 * Function added to avoid path disclosures.
1848 * Called by each script that needs parameters, it displays
1849 * an error message and, by default, stops the execution.
1851 * Not sure we could use a strMissingParameter message here,
1852 * would have to check if the error message file is always available
1854 * @todo localize error message
1855 * @todo use PMA_fatalError() if $die === true?
1856 * @uses PMA_getenv()
1857 * @uses header_meta_style.inc.php
1858 * @uses $GLOBALS['PMA_PHP_SELF']
1859 * basename
1860 * @param array The names of the parameters needed by the calling
1861 * script.
1862 * @param boolean Stop the execution?
1863 * (Set this manually to false in the calling script
1864 * until you know all needed parameters to check).
1865 * @param boolean Whether to include this list in checking for special params.
1866 * @global string path to current script
1867 * @global boolean flag whether any special variable was required
1869 * @access public
1870 * @author Marc Delisle (lem9@users.sourceforge.net)
1872 function PMA_checkParameters($params, $die = true, $request = true)
1874 global $checked_special;
1876 if (!isset($checked_special)) {
1877 $checked_special = false;
1880 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1881 $found_error = false;
1882 $error_message = '';
1884 foreach ($params as $param) {
1885 if ($request && $param != 'db' && $param != 'table') {
1886 $checked_special = true;
1889 if (!isset($GLOBALS[$param])) {
1890 $error_message .= $reported_script_name
1891 . ': Missing parameter: ' . $param
1892 . ' <a href="./Documentation.html#faqmissingparameters"'
1893 . ' target="documentation"> (FAQ 2.8)</a><br />';
1894 $found_error = true;
1897 if ($found_error) {
1899 * display html meta tags
1901 require_once './libraries/header_meta_style.inc.php';
1902 echo '</head><body><p>' . $error_message . '</p></body></html>';
1903 if ($die) {
1904 exit();
1907 } // end function
1910 * Function to generate unique condition for specified row.
1912 * @uses $GLOBALS['analyzed_sql'][0]
1913 * @uses PMA_DBI_field_flags()
1914 * @uses PMA_backquote()
1915 * @uses PMA_sqlAddslashes()
1916 * @uses PMA_printable_bit_value()
1917 * @uses stristr()
1918 * @uses bin2hex()
1919 * @uses preg_replace()
1920 * @param resource $handle current query result
1921 * @param integer $fields_cnt number of fields
1922 * @param array $fields_meta meta information about fields
1923 * @param array $row current row
1924 * @param boolean $force_unique generate condition only on pk or unique
1926 * @access public
1927 * @author Michal Cihar (michal@cihar.com) and others...
1928 * @return string calculated condition
1930 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1932 $primary_key = '';
1933 $unique_key = '';
1934 $nonprimary_condition = '';
1935 $preferred_condition = '';
1937 for ($i = 0; $i < $fields_cnt; ++$i) {
1938 $condition = '';
1939 $field_flags = PMA_DBI_field_flags($handle, $i);
1940 $meta = $fields_meta[$i];
1942 // do not use a column alias in a condition
1943 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1944 $meta->orgname = $meta->name;
1946 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1947 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1948 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1949 as $select_expr) {
1950 // need (string) === (string)
1951 // '' !== 0 but '' == 0
1952 if ((string) $select_expr['alias'] === (string) $meta->name) {
1953 $meta->orgname = $select_expr['column'];
1954 break;
1955 } // end if
1956 } // end foreach
1960 // Do not use a table alias in a condition.
1961 // Test case is:
1962 // select * from galerie x WHERE
1963 //(select count(*) from galerie y where y.datum=x.datum)>1
1965 // But orgtable is present only with mysqli extension so the
1966 // fix is only for mysqli.
1967 // Also, do not use the original table name if we are dealing with
1968 // a view because this view might be updatable.
1969 // (The isView() verification should not be costly in most cases
1970 // because there is some caching in the function).
1971 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1972 $meta->table = $meta->orgtable;
1975 // to fix the bug where float fields (primary or not)
1976 // can't be matched because of the imprecision of
1977 // floating comparison, use CONCAT
1978 // (also, the syntax "CONCAT(field) IS NULL"
1979 // that we need on the next "if" will work)
1980 if ($meta->type == 'real') {
1981 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1982 . PMA_backquote($meta->orgname) . ') ';
1983 } else {
1984 $condition = ' ' . PMA_backquote($meta->table) . '.'
1985 . PMA_backquote($meta->orgname) . ' ';
1986 } // end if... else...
1988 if (!isset($row[$i]) || is_null($row[$i])) {
1989 $condition .= 'IS NULL AND';
1990 } else {
1991 // timestamp is numeric on some MySQL 4.1
1992 if ($meta->numeric && $meta->type != 'timestamp') {
1993 $condition .= '= ' . $row[$i] . ' AND';
1994 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1995 // hexify only if this is a true not empty BLOB or a BINARY
1996 && stristr($field_flags, 'BINARY')
1997 && !empty($row[$i])) {
1998 // do not waste memory building a too big condition
1999 if (strlen($row[$i]) < 1000) {
2000 // use a CAST if possible, to avoid problems
2001 // if the field contains wildcard characters % or _
2002 $condition .= '= CAST(0x' . bin2hex($row[$i])
2003 . ' AS BINARY) AND';
2004 } else {
2005 // this blob won't be part of the final condition
2006 $condition = '';
2008 } elseif ($meta->type == 'bit') {
2009 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2010 } else {
2011 $condition .= '= \''
2012 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2015 if ($meta->primary_key > 0) {
2016 $primary_key .= $condition;
2017 } elseif ($meta->unique_key > 0) {
2018 $unique_key .= $condition;
2020 $nonprimary_condition .= $condition;
2021 } // end for
2023 // Correction University of Virginia 19991216:
2024 // prefer primary or unique keys for condition,
2025 // but use conjunction of all values if no primary key
2026 if ($primary_key) {
2027 $preferred_condition = $primary_key;
2028 } elseif ($unique_key) {
2029 $preferred_condition = $unique_key;
2030 } elseif (! $force_unique) {
2031 $preferred_condition = $nonprimary_condition;
2034 return trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2035 } // end function
2038 * Generate a button or image tag
2040 * @uses PMA_USR_BROWSER_AGENT
2041 * @uses $GLOBALS['pmaThemeImage']
2042 * @uses $GLOBALS['cfg']['PropertiesIconic']
2043 * @param string name of button element
2044 * @param string class of button element
2045 * @param string name of image element
2046 * @param string text to display
2047 * @param string image to display
2049 * @access public
2050 * @author Michal Cihar (michal@cihar.com)
2052 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2053 $image)
2055 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2056 echo ' <input type="submit" name="' . $button_name . '"'
2057 .' value="' . htmlspecialchars($text) . '"'
2058 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2059 return;
2062 /* Opera has trouble with <input type="image"> */
2063 /* IE has trouble with <button> */
2064 if (PMA_USR_BROWSER_AGENT != 'IE') {
2065 echo '<button class="' . $button_class . '" type="submit"'
2066 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2067 .' title="' . htmlspecialchars($text) . '">' . "\n"
2068 . PMA_getIcon($image, $text)
2069 .'</button>' . "\n";
2070 } else {
2071 echo '<input type="image" name="' . $image_name . '" value="'
2072 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2073 . $image . '" />'
2074 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2076 } // end function
2079 * Generate a pagination selector for browsing resultsets
2081 * @todo $url is not javascript escaped!?
2082 * @uses $GLOBALS['strPageNumber']
2083 * @uses range()
2084 * @param string URL for the JavaScript
2085 * @param string Number of rows in the pagination set
2086 * @param string current page number
2087 * @param string number of total pages
2088 * @param string If the number of pages is lower than this
2089 * variable, no pages will be omitted in
2090 * pagination
2091 * @param string How many rows at the beginning should always
2092 * be shown?
2093 * @param string How many rows at the end should always
2094 * be shown?
2095 * @param string Percentage of calculation page offsets to
2096 * hop to a next page
2097 * @param string Near the current page, how many pages should
2098 * be considered "nearby" and displayed as
2099 * well?
2100 * @param string The prompt to display (sometimes empty)
2102 * @access public
2103 * @author Garvin Hicking (pma@supergarv.de)
2105 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2106 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2107 $range = 10, $prompt = '')
2109 $increment = floor($nbTotalPage / $percent);
2110 $pageNowMinusRange = ($pageNow - $range);
2111 $pageNowPlusRange = ($pageNow + $range);
2113 $gotopage = $prompt
2114 . ' <select name="pos" onchange="goToUrl(this, \''
2115 . $url . '\');">' . "\n";
2116 if ($nbTotalPage < $showAll) {
2117 $pages = range(1, $nbTotalPage);
2118 } else {
2119 $pages = array();
2121 // Always show first X pages
2122 for ($i = 1; $i <= $sliceStart; $i++) {
2123 $pages[] = $i;
2126 // Always show last X pages
2127 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2128 $pages[] = $i;
2131 // garvin: Based on the number of results we add the specified
2132 // $percent percentage to each page number,
2133 // so that we have a representing page number every now and then to
2134 // immediately jump to specific pages.
2135 // As soon as we get near our currently chosen page ($pageNow -
2136 // $range), every page number will be shown.
2137 $i = $sliceStart;
2138 $x = $nbTotalPage - $sliceEnd;
2139 $met_boundary = false;
2140 while ($i <= $x) {
2141 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2142 // If our pageselector comes near the current page, we use 1
2143 // counter increments
2144 $i++;
2145 $met_boundary = true;
2146 } else {
2147 // We add the percentage increment to our current page to
2148 // hop to the next one in range
2149 $i += $increment;
2151 // Make sure that we do not cross our boundaries.
2152 if ($i > $pageNowMinusRange && ! $met_boundary) {
2153 $i = $pageNowMinusRange;
2157 if ($i > 0 && $i <= $x) {
2158 $pages[] = $i;
2162 // Since because of ellipsing of the current page some numbers may be double,
2163 // we unify our array:
2164 sort($pages);
2165 $pages = array_unique($pages);
2168 foreach ($pages as $i) {
2169 if ($i == $pageNow) {
2170 $selected = 'selected="selected" style="font-weight: bold"';
2171 } else {
2172 $selected = '';
2174 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2177 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2179 return $gotopage;
2180 } // end function
2184 * Generate navigation for a list
2186 * @todo use $pos from $_url_params
2187 * @uses $GLOBALS['strPageNumber']
2188 * @uses range()
2189 * @param integer number of elements in the list
2190 * @param integer current position in the list
2191 * @param array url parameters
2192 * @param string script name for form target
2193 * @param string target frame
2194 * @param integer maximum number of elements to display from the list
2196 * @access public
2198 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2200 if ($max_count < $count) {
2201 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2202 echo $GLOBALS['strPageNumber'];
2203 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2205 // Move to the beginning or to the previous page
2206 if ($pos > 0) {
2207 // loic1: patch #474210 from Gosha Sakovich - part 1
2208 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2209 $caption1 = '&lt;&lt;';
2210 $caption2 = ' &lt; ';
2211 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2212 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2213 } else {
2214 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2215 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2216 $title1 = '';
2217 $title2 = '';
2218 } // end if... else...
2219 $_url_params['pos'] = 0;
2220 echo '<a' . $title1 . ' href="' . $script
2221 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2222 . $caption1 . '</a>';
2223 $_url_params['pos'] = $pos - $max_count;
2224 echo '<a' . $title2 . ' href="' . $script
2225 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2226 . $caption2 . '</a>';
2229 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2230 echo PMA_generate_common_hidden_inputs($_url_params);
2231 echo PMA_pageselector(
2232 $script . PMA_generate_common_url($_url_params) . '&amp;',
2233 $max_count,
2234 floor(($pos + 1) / $max_count) + 1,
2235 ceil($count / $max_count));
2236 echo '</form>';
2238 if ($pos + $max_count < $count) {
2239 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2240 $caption3 = ' &gt; ';
2241 $caption4 = '&gt;&gt;';
2242 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2243 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2244 } else {
2245 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2246 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2247 $title3 = '';
2248 $title4 = '';
2249 } // end if... else...
2250 $_url_params['pos'] = $pos + $max_count;
2251 echo '<a' . $title3 . ' href="' . $script
2252 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2253 . $caption3 . '</a>';
2254 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2255 if ($_url_params['pos'] == $count) {
2256 $_url_params['pos'] = $count - $max_count;
2258 echo '<a' . $title4 . ' href="' . $script
2259 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2260 . $caption4 . '</a>';
2262 echo "\n";
2263 if ('frame_navigation' == $frame) {
2264 echo '</div>' . "\n";
2270 * replaces %u in given path with current user name
2272 * example:
2273 * <code>
2274 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2276 * </code>
2277 * @uses $cfg['Server']['user']
2278 * @uses substr()
2279 * @uses str_replace()
2280 * @param string $dir with wildcard for user
2281 * @return string per user directory
2283 function PMA_userDir($dir)
2285 // add trailing slash
2286 if (substr($dir, -1) != '/') {
2287 $dir .= '/';
2290 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2294 * returns html code for db link to default db page
2296 * @uses $cfg['DefaultTabDatabase']
2297 * @uses $GLOBALS['db']
2298 * @uses $GLOBALS['strJumpToDB']
2299 * @uses PMA_generate_common_url()
2300 * @uses PMA_unescape_mysql_wildcards()
2301 * @uses strlen()
2302 * @uses sprintf()
2303 * @uses htmlspecialchars()
2304 * @param string $database
2305 * @return string html link to default db page
2307 function PMA_getDbLink($database = null)
2309 if (!strlen($database)) {
2310 if (!strlen($GLOBALS['db'])) {
2311 return '';
2313 $database = $GLOBALS['db'];
2314 } else {
2315 $database = PMA_unescape_mysql_wildcards($database);
2318 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2319 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2320 .htmlspecialchars($database) . '</a>';
2324 * Displays a lightbulb hint explaining a known external bug
2325 * that affects a functionality
2327 * @uses PMA_MYSQL_INT_VERSION
2328 * @uses $GLOBALS['strKnownExternalBug']
2329 * @uses PMA_showHint()
2330 * @uses sprintf()
2331 * @param string $functionality localized message explaining the func.
2332 * @param string $component 'mysql' (eventually, 'php')
2333 * @param string $minimum_version of this component
2334 * @param string $bugref bug reference for this component
2336 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2338 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2339 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2344 * Generates and echoes an HTML checkbox
2346 * @param string $html_field_name the checkbox HTML field
2347 * @param string $label
2348 * @param boolean $checked is it initially checked?
2349 * @param boolean $onclick should it submit the form on click?
2351 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2353 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>';
2357 * Generates and echoes a set of radio HTML fields
2359 * @uses htmlspecialchars()
2360 * @param string $html_field_name the radio HTML field
2361 * @param array $choices the choices values and labels
2362 * @param string $checked_choice the choice to check by default
2363 * @param boolean $line_break whether to add an HTML line break after a choice
2364 * @param boolean $escape_label whether to use htmlspecialchars() on label
2365 * @param string $class enclose each choice with a div of this class
2367 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2368 foreach ($choices as $choice_value => $choice_label) {
2369 if (! empty($class)) {
2370 echo '<div class="' . $class . '">';
2372 $html_field_id = $html_field_name . '_' . $choice_value;
2373 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2374 if ($choice_value == $checked_choice) {
2375 echo ' checked="checked"';
2377 echo ' />' . "\n";
2378 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2379 if ($line_break) {
2380 echo '<br />';
2382 if (! empty($class)) {
2383 echo '</div>';
2385 echo "\n";
2390 * Generates and returns an HTML dropdown
2392 * @uses htmlspecialchars()
2393 * @param string $select_name
2394 * @param array $choices the choices values
2395 * @param string $active_choice the choice to select by default
2396 * @param string $id the id of the select element; can be different in case
2397 * the dropdown is present more than once on the page
2398 * @todo support titles
2400 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2402 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2403 foreach ($choices as $one_choice_value => $one_choice_label) {
2404 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2405 if ($one_choice_value == $active_choice) {
2406 $result .= ' selected="selected"';
2408 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2410 $result .= '</select>';
2411 return $result;
2415 * Generates a slider effect (Mootools)
2416 * Takes care of generating the initial <div> and the link
2417 * controlling the slider; you have to generate the </div> yourself
2418 * after the sliding section.
2420 * @uses $GLOBALS['cfg']['InitialSlidersState']
2421 * @param string $id the id of the <div> on which to apply the effect
2422 * @param string $message the message to show as a link
2424 function PMA_generate_slider_effect($id, $message)
2426 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2427 echo '<div id="' . $id . '">';
2428 return;
2431 <script type="text/javascript">
2432 // <![CDATA[
2433 window.addEvent('domready', function(){
2434 var status = {
2435 'true': '- ',
2436 'false': '+ '
2439 var anchor<?php echo $id; ?> = new Element('a', {
2440 'id': 'toggle_<?php echo $id; ?>',
2441 'href': 'javascript:void(0)',
2442 'events': {
2443 'click': function(){
2444 mySlide<?php echo $id; ?>.toggle();
2449 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2450 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2452 var slider_status<?php echo $id; ?> = new Element('span', {
2453 'id': 'slider_status_<?php echo $id; ?>'
2455 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2456 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2458 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2459 <?php
2460 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2462 mySlide<?php echo $id; ?>.hide();
2463 <?php
2466 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2467 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2470 $('<?php echo $id; ?>').style.display="block";
2472 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2473 //]]>
2474 </script>
2475 <noscript>
2476 <div id="<?php echo $id; ?>" />
2477 </noscript>
2478 <?php
2482 * Verifies if something is cached in the session
2484 * @param string $var
2485 * @param scalar $server
2486 * @return boolean
2488 function PMA_cacheExists($var, $server = 0)
2490 if (true === $server) {
2491 $server = $GLOBALS['server'];
2493 return isset($_SESSION['cache']['server_' . $server][$var]);
2497 * Gets cached information from the session
2499 * @param string $var
2500 * @param scalar $server
2501 * @return mixed
2503 function PMA_cacheGet($var, $server = 0)
2505 if (true === $server) {
2506 $server = $GLOBALS['server'];
2508 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2509 return $_SESSION['cache']['server_' . $server][$var];
2510 } else {
2511 return null;
2516 * Caches information in the session
2518 * @param string $var
2519 * @param mixed $val
2520 * @param integer $server
2521 * @return mixed
2523 function PMA_cacheSet($var, $val = null, $server = 0)
2525 if (true === $server) {
2526 $server = $GLOBALS['server'];
2528 $_SESSION['cache']['server_' . $server][$var] = $val;
2532 * Removes cached information from the session
2534 * @param string $var
2535 * @param scalar $server
2537 function PMA_cacheUnset($var, $server = 0)
2539 if (true === $server) {
2540 $server = $GLOBALS['server'];
2542 unset($_SESSION['cache']['server_' . $server][$var]);
2546 * Converts a bit value to printable format;
2547 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2548 * function because in PHP, decbin() supports only 32 bits
2550 * @uses ceil()
2551 * @uses decbin()
2552 * @uses ord()
2553 * @uses substr()
2554 * @uses sprintf()
2555 * @param numeric $value coming from a BIT field
2556 * @param integer $length
2557 * @return string the printable value
2559 function PMA_printable_bit_value($value, $length) {
2560 $printable = '';
2561 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2562 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2564 $printable = substr($printable, -$length);
2565 return $printable;
2569 * Converts a BIT type default value
2570 * for example, b'010' becomes 010
2572 * @uses strtr()
2573 * @param string $bit_default_value
2574 * @return string the converted value
2576 function PMA_convert_bit_default_value($bit_default_value) {
2577 return strtr($bit_default_value, array("b" => "", "'" => ""));
2581 * Extracts the various parts from a field type spec
2583 * @uses strpos()
2584 * @uses chop()
2585 * @uses substr()
2586 * @param string $fieldspec
2587 * @return array associative array containing type, spec_in_brackets
2588 * and possibly enum_set_values (another array)
2589 * @author Marc Delisle
2590 * @author Joshua Hogendorn
2592 function PMA_extractFieldSpec($fieldspec) {
2593 $first_bracket_pos = strpos($fieldspec, '(');
2594 if ($first_bracket_pos) {
2595 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2596 // convert to lowercase just to be sure
2597 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2598 } else {
2599 $type = $fieldspec;
2600 $spec_in_brackets = '';
2603 if ('enum' == $type || 'set' == $type) {
2604 // Define our working vars
2605 $enum_set_values = array();
2606 $working = "";
2607 $in_string = false;
2608 $index = 0;
2610 // While there is another character to process
2611 while (isset($fieldspec[$index])) {
2612 // Grab the char to look at
2613 $char = $fieldspec[$index];
2615 // If it is a single quote, needs to be handled specially
2616 if ($char == "'") {
2617 // If we are not currently in a string, begin one
2618 if (! $in_string) {
2619 $in_string = true;
2620 $working = "";
2621 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2622 } else {
2623 // Check out the next character (if possible)
2624 $has_next = isset($fieldspec[$index + 1]);
2625 $next = $has_next ? $fieldspec[$index + 1] : null;
2627 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2628 if (! $has_next || $next != "'") {
2629 $enum_set_values[] = $working;
2630 $in_string = false;
2632 // Otherwise, this is a 'double quote', and can be added to the working string
2633 } elseif ($next == "'") {
2634 $working .= "'";
2635 // Skip the next char; we already know what it is
2636 $index++;
2639 // escaping of a quote?
2640 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2641 $working .= "'";
2642 $index++;
2643 // Otherwise, add it to our working string like normal
2644 } else {
2645 $working .= $char;
2647 // Increment character index
2648 $index++;
2649 } // end while
2650 } else {
2651 $enum_set_values = array();
2654 return array(
2655 'type' => $type,
2656 'spec_in_brackets' => $spec_in_brackets,
2657 'enum_set_values' => $enum_set_values
2662 * Verifies if this table's engine supports foreign keys
2664 * @uses strtoupper()
2665 * @param string $engine
2666 * @return boolean
2668 function PMA_foreignkey_supported($engine) {
2669 $engine = strtoupper($engine);
2670 if ('INNODB' == $engine || 'PBXT' == $engine) {
2671 return true;
2672 } else {
2673 return false;
2678 * Replaces some characters by a displayable equivalent
2680 * @uses str_replace()
2681 * @param string $content
2682 * @return string the content with characters replaced
2684 function PMA_replace_binary_contents($content) {
2685 $result = str_replace("\x00", '\0', $content);
2686 $result = str_replace("\x08", '\b', $result);
2687 $result = str_replace("\x0a", '\n', $result);
2688 $result = str_replace("\x0d", '\r', $result);
2689 $result = str_replace("\x1a", '\Z', $result);
2690 return $result;
2695 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2697 * @uses strpos()
2698 * @return string with the chars replaced
2701 function PMA_duplicateFirstNewline($string){
2702 $first_occurence = strpos($string, "\r\n");
2703 if ($first_occurence === 0){
2704 $string = "\n".$string;
2706 return $string;
2710 * get the action word corresponding to a script name
2711 * in order to display it as a title in navigation panel
2713 * @uses $GLOBALS
2714 * @param string a valid value for $cfg['LeftDefaultTabTable']
2715 * or $cfg['DefaultTabTable']
2716 * or $cfg['DefaultTabDatabase']
2718 function PMA_getTitleForTarget($target) {
2719 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];
2722 /**
2723 * The function creates javascript and html code, which run given mootools/JS code when DOM is ready
2725 * @param String $code - Mootools/JS code, which will be run
2726 * @param boolena $print - If true, then the code is printed, otherwise is returned
2728 * @return String - the code
2730 function PMA_js_mootools_domready($code, $print=true)
2732 $out = '';
2733 $out .= '<script type="text/javascript">'."\n";
2734 $out .= 'window.addEvent(\'domready\',function() {'."\n";
2735 $out .= $code;
2736 $out .= '});'."\n";
2737 $out .= '</script>'."\n";
2739 if ($print)
2740 echo $out;
2742 return $out;
2745 function PMA_js($code, $print=true)
2747 $out = '';
2748 $out .= '<script type="text/javascript">'."\n";
2749 $out .= $code;
2750 $out .= '</script>'."\n";
2752 if ($print)
2753 echo $out;
2755 return $out;