new
[phpmyadmin/crack.git] / libraries / common.lib.php
blobfe67a9f94d335e1671823fadb5a97675b31efc82
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 */
9 /**
10 * Exponential expression / raise number into power
12 * @uses function_exists()
13 * @uses bcpow()
14 * @uses gmp_pow()
15 * @uses gmp_strval()
16 * @uses pow()
17 * @param number $base
18 * @param number $exp
19 * @param string pow function use, or false for auto-detect
20 * @return mixed string or float
22 function PMA_pow($base, $exp, $use_function = false)
24 static $pow_function = null;
26 if ($exp < 0) {
27 return false;
30 if (null == $pow_function) {
31 if (function_exists('bcpow')) {
32 // BCMath Arbitrary Precision Mathematics Function
33 $pow_function = 'bcpow';
34 } elseif (function_exists('gmp_pow')) {
35 // GMP Function
36 $pow_function = 'gmp_pow';
37 } else {
38 // PHP function
39 $pow_function = 'pow';
43 if (! $use_function) {
44 $use_function = $pow_function;
47 switch ($use_function) {
48 case 'bcpow' :
49 //bcscale(10);
50 $pow = bcpow($base, $exp);
51 break;
52 case 'gmp_pow' :
53 $pow = gmp_strval(gmp_pow($base, $exp));
54 break;
55 case 'pow' :
56 $base = (float) $base;
57 $exp = (int) $exp;
58 $pow = pow($base, $exp);
59 break;
60 default:
61 $pow = $use_function($base, $exp);
64 return $pow;
67 /**
68 * string PMA_getIcon(string $icon)
70 * @uses $GLOBALS['pmaThemeImage']
71 * @uses $GLOBALS['cfg']['PropertiesIconic']
72 * @uses htmlspecialchars()
73 * @param string $icon name of icon file
74 * @param string $alternate alternate text
75 * @param boolean $container include in container
76 * @param boolean $$force_text whether to force alternate text to be displayed
77 * @return html img tag
79 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
81 $include_icon = false;
82 $include_text = false;
83 $include_box = false;
84 $alternate = htmlspecialchars($alternate);
85 $button = '';
87 if ($GLOBALS['cfg']['PropertiesIconic']) {
88 $include_icon = true;
91 if ($force_text
92 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
93 || ! $include_icon) {
94 // $cfg['PropertiesIconic'] is false or both
95 // OR we have no $include_icon
96 $include_text = true;
99 if ($include_text && $include_icon && $container) {
100 // we have icon, text and request for container
101 $include_box = true;
104 if ($include_box) {
105 $button .= '<div class="nowrap">';
108 if ($include_icon) {
109 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
110 . ' title="' . $alternate . '" alt="' . $alternate . '"'
111 . ' class="icon" width="16" height="16" />';
114 if ($include_icon && $include_text) {
115 $button .= ' ';
118 if ($include_text) {
119 $button .= $alternate;
122 if ($include_box) {
123 $button .= '</div>';
126 return $button;
130 * Displays the maximum size for an upload
132 * @uses $GLOBALS['strMaximumSize']
133 * @uses PMA_formatByteDown()
134 * @uses sprintf()
135 * @param integer the size
137 * @return string the message
139 * @access public
141 function PMA_displayMaximumUploadSize($max_upload_size)
143 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size);
144 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
148 * Generates a hidden field which should indicate to the browser
149 * the maximum size for upload
151 * @param integer the size
153 * @return string the INPUT field
155 * @access public
157 function PMA_generateHiddenMaxFileSize($max_size)
159 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
163 * Add slashes before "'" and "\" characters so a value containing them can
164 * be used in a sql comparison.
166 * @uses str_replace()
167 * @param string the string to slash
168 * @param boolean whether the string will be used in a 'LIKE' clause
169 * (it then requires two more escaped sequences) or not
170 * @param boolean whether to treat cr/lfs as escape-worthy entities
171 * (converts \n to \\n, \r to \\r)
173 * @param boolean whether this function is used as part of the
174 * "Create PHP code" dialog
176 * @return string the slashed string
178 * @access public
180 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
182 if ($is_like) {
183 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
184 } else {
185 $a_string = str_replace('\\', '\\\\', $a_string);
188 if ($crlf) {
189 $a_string = str_replace("\n", '\n', $a_string);
190 $a_string = str_replace("\r", '\r', $a_string);
191 $a_string = str_replace("\t", '\t', $a_string);
194 if ($php_code) {
195 $a_string = str_replace('\'', '\\\'', $a_string);
196 } else {
197 $a_string = str_replace('\'', '\'\'', $a_string);
200 return $a_string;
201 } // end of the 'PMA_sqlAddslashes()' function
205 * Add slashes before "_" and "%" characters for using them in MySQL
206 * database, table and field names.
207 * Note: This function does not escape backslashes!
209 * @uses str_replace()
210 * @param string the string to escape
212 * @return string the escaped string
214 * @access public
216 function PMA_escape_mysql_wildcards($name)
218 $name = str_replace('_', '\\_', $name);
219 $name = str_replace('%', '\\%', $name);
221 return $name;
222 } // end of the 'PMA_escape_mysql_wildcards()' function
225 * removes slashes before "_" and "%" characters
226 * Note: This function does not unescape backslashes!
228 * @uses str_replace()
229 * @param string $name the string to escape
230 * @return string the escaped string
231 * @access public
233 function PMA_unescape_mysql_wildcards($name)
235 $name = str_replace('\\_', '_', $name);
236 $name = str_replace('\\%', '%', $name);
238 return $name;
239 } // end of the 'PMA_unescape_mysql_wildcards()' function
242 * removes quotes (',",`) from a quoted string
244 * checks if the sting is quoted and removes this quotes
246 * @uses str_replace()
247 * @uses substr()
248 * @param string $quoted_string string to remove quotes from
249 * @param string $quote type of quote to remove
250 * @return string unqoted string
252 function PMA_unQuote($quoted_string, $quote = null)
254 $quotes = array();
256 if (null === $quote) {
257 $quotes[] = '`';
258 $quotes[] = '"';
259 $quotes[] = "'";
260 } else {
261 $quotes[] = $quote;
264 foreach ($quotes as $quote) {
265 if (substr($quoted_string, 0, 1) === $quote
266 && substr($quoted_string, -1, 1) === $quote) {
267 $unquoted_string = substr($quoted_string, 1, -1);
268 // replace escaped quotes
269 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
270 return $unquoted_string;
274 return $quoted_string;
278 * format sql strings
280 * @todo move into PMA_Sql
281 * @uses PMA_SQP_isError()
282 * @uses PMA_SQP_formatHtml()
283 * @uses PMA_SQP_formatNone()
284 * @uses is_array()
285 * @param mixed pre-parsed SQL structure
287 * @return string the formatted sql
289 * @global array the configuration array
290 * @global boolean whether the current statement is a multiple one or not
292 * @access public
294 * @author Robin Johnson <robbat2@users.sourceforge.net>
296 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
298 global $cfg;
300 // Check that we actually have a valid set of parsed data
301 // well, not quite
302 // first check for the SQL parser having hit an error
303 if (PMA_SQP_isError()) {
304 return $parsed_sql;
306 // then check for an array
307 if (!is_array($parsed_sql)) {
308 // We don't so just return the input directly
309 // This is intended to be used for when the SQL Parser is turned off
310 $formatted_sql = '<pre>' . "\n"
311 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
312 . '</pre>';
313 return $formatted_sql;
316 $formatted_sql = '';
318 switch ($cfg['SQP']['fmtType']) {
319 case 'none':
320 if ($unparsed_sql != '') {
321 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
322 } else {
323 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
325 break;
326 case 'html':
327 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
328 break;
329 case 'text':
330 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
331 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
332 break;
333 default:
334 break;
335 } // end switch
337 return $formatted_sql;
338 } // end of the "PMA_formatSql()" function
342 * Displays a link to the official MySQL documentation
344 * @uses $cfg['MySQLManualType']
345 * @uses $cfg['MySQLManualBase']
346 * @uses $cfg['ReplaceHelpImg']
347 * @uses $GLOBALS['mysql_4_1_doc_lang']
348 * @uses $GLOBALS['mysql_5_1_doc_lang']
349 * @uses $GLOBALS['mysql_5_0_doc_lang']
350 * @uses $GLOBALS['strDocu']
351 * @uses $GLOBALS['pmaThemeImage']
352 * @uses PMA_MYSQL_INT_VERSION
353 * @uses strtolower()
354 * @uses str_replace()
355 * @param string chapter of "HTML, one page per chapter" documentation
356 * @param string contains name of page/anchor that is being linked
357 * @param bool whether to use big icon (like in left frame)
358 * @param string anchor to page part
360 * @return string the html link
362 * @access public
364 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '')
366 global $cfg;
368 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
369 return '';
372 // Fixup for newly used names:
373 $chapter = str_replace('_', '-', strtolower($chapter));
374 $link = str_replace('_', '-', strtolower($link));
376 switch ($cfg['MySQLManualType']) {
377 case 'chapters':
378 if (empty($chapter)) {
379 $chapter = 'index';
381 if (empty($anchor)) {
382 $anchor = $link;
384 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
385 break;
386 case 'big':
387 if (empty($anchor)) {
388 $anchor = $link;
390 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
391 break;
392 case 'searchable':
393 if (empty($link)) {
394 $link = 'index';
396 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
397 if (!empty($anchor)) {
398 $url .= '#' . $anchor;
400 break;
401 case 'viewable':
402 default:
403 if (empty($link)) {
404 $link = 'index';
406 $mysql = '5.0';
407 $lang = 'en';
408 if (defined('PMA_MYSQL_INT_VERSION')) {
409 if (PMA_MYSQL_INT_VERSION >= 50100) {
410 $mysql = '5.1';
411 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
412 $lang = $GLOBALS['mysql_5_1_doc_lang'];
414 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
415 $mysql = '5.0';
416 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
417 $lang = $GLOBALS['mysql_5_0_doc_lang'];
421 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
422 if (!empty($anchor)) {
423 $url .= '#' . $anchor;
425 break;
428 if ($big_icon) {
429 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>';
430 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
431 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>';
432 } else {
433 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
435 } // end of the 'PMA_showMySQLDocu()' function
438 * returns HTML for a footnote marker and add the messsage to the footnotes
440 * @uses $GLOBALS['footnotes']
441 * @param string the error message
442 * @return string html code for a footnote marker
443 * @access public
445 function PMA_showHint($message, $bbcode = false, $type = 'notice')
447 if ($message instanceof PMA_Message) {
448 $key = $message->getHash();
449 $type = $message->getLevel();
450 } else {
451 $key = md5($message);
454 if (! isset($GLOBALS['footnotes'][$key])) {
455 $nr = count($GLOBALS['footnotes']) + 1;
456 // this is the first instance of this message
457 $instance = 1;
458 $GLOBALS['footnotes'][$key] = array(
459 'note' => $message,
460 'type' => $type,
461 'nr' => $nr,
462 'instance' => $instance
464 } else {
465 $nr = $GLOBALS['footnotes'][$key]['nr'];
466 // another instance of this message (to ensure ids are unique)
467 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
470 if ($bbcode) {
471 return '[sup]' . $nr . '[/sup]';
474 // footnotemarker used in js/tooltip.js
475 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
479 * Displays a MySQL error message in the right frame.
481 * @uses footer.inc.php
482 * @uses header.inc.php
483 * @uses $GLOBALS['sql_query']
484 * @uses $GLOBALS['strError']
485 * @uses $GLOBALS['strSQLQuery']
486 * @uses $GLOBALS['pmaThemeImage']
487 * @uses $GLOBALS['strEdit']
488 * @uses $GLOBALS['strMySQLSaid']
489 * @uses $GLOBALS['cfg']['PropertiesIconic']
490 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
491 * @uses PMA_backquote()
492 * @uses PMA_DBI_getError()
493 * @uses PMA_formatSql()
494 * @uses PMA_generate_common_hidden_inputs()
495 * @uses PMA_generate_common_url()
496 * @uses PMA_showMySQLDocu()
497 * @uses PMA_sqlAddslashes()
498 * @uses PMA_SQP_isError()
499 * @uses PMA_SQP_parse()
500 * @uses PMA_SQP_getErrorString()
501 * @uses strtolower()
502 * @uses urlencode()
503 * @uses str_replace()
504 * @uses nl2br()
505 * @uses substr()
506 * @uses preg_replace()
507 * @uses preg_match()
508 * @uses explode()
509 * @uses implode()
510 * @uses is_array()
511 * @uses function_exists()
512 * @uses htmlspecialchars()
513 * @uses trim()
514 * @uses strstr()
515 * @param string the error message
516 * @param string the sql query that failed
517 * @param boolean whether to show a "modify" link or not
518 * @param string the "back" link url (full path is not required)
519 * @param boolean EXIT the page?
521 * @global string the curent table
522 * @global string the current db
524 * @access public
526 function PMA_mysqlDie($error_message = '', $the_query = '',
527 $is_modify_link = true, $back_url = '', $exit = true)
529 global $table, $db;
532 * start http output, display html headers
534 require_once './libraries/header.inc.php';
536 if (!$error_message) {
537 $error_message = PMA_DBI_getError();
539 if (!$the_query && !empty($GLOBALS['sql_query'])) {
540 $the_query = $GLOBALS['sql_query'];
543 // --- Added to solve bug #641765
544 // Robbat2 - 12 January 2003, 9:46PM
545 // Revised, Robbat2 - 13 January 2003, 2:59PM
546 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
547 $formatted_sql = htmlspecialchars($the_query);
548 } elseif (empty($the_query) || trim($the_query) == '') {
549 $formatted_sql = '';
550 } else {
551 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
552 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
553 } else {
554 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
557 // ---
558 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
559 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
560 // if the config password is wrong, or the MySQL server does not
561 // respond, do not show the query that would reveal the
562 // username/password
563 if (!empty($the_query) && !strstr($the_query, 'connect')) {
564 // --- Added to solve bug #641765
565 // Robbat2 - 12 January 2003, 9:46PM
566 // Revised, Robbat2 - 13 January 2003, 2:59PM
567 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
568 echo PMA_SQP_getErrorString() . "\n";
569 echo '<br />' . "\n";
571 // ---
572 // modified to show me the help on sql errors (Michael Keck)
573 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
574 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
575 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
577 if ($is_modify_link) {
578 $_url_params = array(
579 'sql_query' => $the_query,
580 'show_query' => 1,
582 if (strlen($table)) {
583 $_url_params['db'] = $db;
584 $_url_params['table'] = $table;
585 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
586 } elseif (strlen($db)) {
587 $_url_params['db'] = $db;
588 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
589 } else {
590 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
593 echo $doedit_goto
594 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
595 . '</a>';
596 } // end if
597 echo ' </p>' . "\n"
598 .' <p>' . "\n"
599 .' ' . $formatted_sql . "\n"
600 .' </p>' . "\n";
601 } // end if
603 $tmp_mysql_error = ''; // for saving the original $error_message
604 if (!empty($error_message)) {
605 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
606 $error_message = htmlspecialchars($error_message);
607 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
609 // modified to show me the help on error-returns (Michael Keck)
610 // (now error-messages-server)
611 echo '<p>' . "\n"
612 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
613 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
614 . "\n"
615 . '</p>' . "\n";
617 // The error message will be displayed within a CODE segment.
618 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
620 // Replace all non-single blanks with their HTML-counterpart
621 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
622 // Replace TAB-characters with their HTML-counterpart
623 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
624 // Replace linebreaks
625 $error_message = nl2br($error_message);
627 echo '<code>' . "\n"
628 . $error_message . "\n"
629 . '</code><br />' . "\n";
630 echo '</div>';
632 if ($exit) {
633 if (! empty($back_url)) {
634 if (strstr($back_url, '?')) {
635 $back_url .= '&amp;no_history=true';
636 } else {
637 $back_url .= '?no_history=true';
639 echo '<fieldset class="tblFooters">';
640 echo '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
641 echo '</fieldset>' . "\n\n";
644 * display footer and exit
646 require_once './libraries/footer.inc.php';
648 } // end of the 'PMA_mysqlDie()' function
651 * Send HTTP header, taking IIS limits into account (600 seems ok)
653 * @uses PMA_IS_IIS
654 * @uses PMA_COMING_FROM_COOKIE_LOGIN
655 * @uses PMA_get_arg_separator()
656 * @uses SID
657 * @uses strlen()
658 * @uses strpos()
659 * @uses header()
660 * @uses session_write_close()
661 * @uses headers_sent()
662 * @uses function_exists()
663 * @uses debug_print_backtrace()
664 * @uses trigger_error()
665 * @uses defined()
666 * @param string $uri the header to send
667 * @return boolean always true
669 function PMA_sendHeaderLocation($uri)
671 if (PMA_IS_IIS && strlen($uri) > 600) {
673 echo '<html><head><title>- - -</title>' . "\n";
674 echo '<meta http-equiv="expires" content="0">' . "\n";
675 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
676 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
677 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
678 echo '<script type="text/javascript">' . "\n";
679 echo '//<![CDATA[' . "\n";
680 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
681 echo '//]]>' . "\n";
682 echo '</script>' . "\n";
683 echo '</head>' . "\n";
684 echo '<body>' . "\n";
685 echo '<script type="text/javascript">' . "\n";
686 echo '//<![CDATA[' . "\n";
687 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
688 echo '//]]>' . "\n";
689 echo '</script></body></html>' . "\n";
691 } else {
692 if (SID) {
693 if (strpos($uri, '?') === false) {
694 header('Location: ' . $uri . '?' . SID);
695 } else {
696 $separator = PMA_get_arg_separator();
697 header('Location: ' . $uri . $separator . SID);
699 } else {
700 session_write_close();
701 if (headers_sent()) {
702 if (function_exists('debug_print_backtrace')) {
703 echo '<pre>';
704 debug_print_backtrace();
705 echo '</pre>';
707 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
709 // bug #1523784: IE6 does not like 'Refresh: 0', it
710 // results in a blank page
711 // but we need it when coming from the cookie login panel)
712 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
713 header('Refresh: 0; ' . $uri);
714 } else {
715 header('Location: ' . $uri);
722 * returns array with tables of given db with extended information and grouped
724 * @uses $cfg['LeftFrameTableSeparator']
725 * @uses $cfg['LeftFrameTableLevel']
726 * @uses $cfg['ShowTooltipAliasTB']
727 * @uses $cfg['NaturalOrder']
728 * @uses PMA_backquote()
729 * @uses count()
730 * @uses array_merge
731 * @uses uksort()
732 * @uses strstr()
733 * @uses explode()
734 * @param string $db name of db
735 * @param string $tables name of tables
736 * @param integer $limit_offset list offset
737 * @param integer $limit_count max tables to return
738 * return array (recursive) grouped table list
740 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
742 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
744 if (null === $tables) {
745 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
746 if ($GLOBALS['cfg']['NaturalOrder']) {
747 uksort($tables, 'strnatcasecmp');
751 if (count($tables) < 1) {
752 return $tables;
755 $default = array(
756 'Name' => '',
757 'Rows' => 0,
758 'Comment' => '',
759 'disp_name' => '',
762 $table_groups = array();
764 // for blobstreaming - list of blobstreaming tables - rajk
766 // load PMA configuration
767 $PMA_Config = $_SESSION['PMA_Config'];
769 // if PMA configuration exists
770 if (!empty($PMA_Config))
771 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
773 foreach ($tables as $table_name => $table) {
774 // if BS tables exist
775 if (isset($session_bs_tables))
776 // compare table name to tables in list of blobstreaming tables
777 foreach ($session_bs_tables as $table_key=>$table_val)
778 // if table is in list, skip outer foreach loop
779 if ($table_name == $table_key)
780 continue 2;
782 // check for correct row count
783 if (null === $table['Rows']) {
784 // Do not check exact row count here,
785 // if row count is invalid possibly the table is defect
786 // and this would break left frame;
787 // but we can check row count if this is a view,
788 // since PMA_Table::countRecords() returns a limited row count
789 // in this case.
791 // set this because PMA_Table::countRecords() can use it
792 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
794 if ($tbl_is_view) {
795 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
796 $return = true);
800 // in $group we save the reference to the place in $table_groups
801 // where to store the table info
802 if ($GLOBALS['cfg']['LeftFrameDBTree']
803 && $sep && strstr($table_name, $sep))
805 $parts = explode($sep, $table_name);
807 $group =& $table_groups;
808 $i = 0;
809 $group_name_full = '';
810 while ($i < count($parts) - 1
811 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
812 $group_name = $parts[$i] . $sep;
813 $group_name_full .= $group_name;
815 if (!isset($group[$group_name])) {
816 $group[$group_name] = array();
817 $group[$group_name]['is' . $sep . 'group'] = true;
818 $group[$group_name]['tab' . $sep . 'count'] = 1;
819 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
820 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
821 $table = $group[$group_name];
822 $group[$group_name] = array();
823 $group[$group_name][$group_name] = $table;
824 unset($table);
825 $group[$group_name]['is' . $sep . 'group'] = true;
826 $group[$group_name]['tab' . $sep . 'count'] = 1;
827 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
828 } else {
829 $group[$group_name]['tab' . $sep . 'count']++;
831 $group =& $group[$group_name];
832 $i++;
834 } else {
835 if (!isset($table_groups[$table_name])) {
836 $table_groups[$table_name] = array();
838 $group =& $table_groups;
842 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
843 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
844 // switch tooltip and name
845 $table['Comment'] = $table['Name'];
846 $table['disp_name'] = $table['Comment'];
847 } else {
848 $table['disp_name'] = $table['Name'];
851 $group[$table_name] = array_merge($default, $table);
854 return $table_groups;
857 /* ----------------------- Set of misc functions ----------------------- */
861 * Adds backquotes on both sides of a database, table or field name.
862 * and escapes backquotes inside the name with another backquote
864 * example:
865 * <code>
866 * echo PMA_backquote('owner`s db'); // `owner``s db`
868 * </code>
870 * @uses PMA_backquote()
871 * @uses is_array()
872 * @uses strlen()
873 * @uses str_replace()
874 * @param mixed $a_name the database, table or field name to "backquote"
875 * or array of it
876 * @param boolean $do_it a flag to bypass this function (used by dump
877 * functions)
878 * @return mixed the "backquoted" database, table or field name if the
879 * current MySQL release is >= 3.23.6, the original one
880 * else
881 * @access public
883 function PMA_backquote($a_name, $do_it = true)
885 if (! $do_it) {
886 return $a_name;
889 if (is_array($a_name)) {
890 $result = array();
891 foreach ($a_name as $key => $val) {
892 $result[$key] = PMA_backquote($val);
894 return $result;
897 // '0' is also empty for php :-(
898 if (strlen($a_name) && $a_name !== '*') {
899 return '`' . str_replace('`', '``', $a_name) . '`';
900 } else {
901 return $a_name;
903 } // end of the 'PMA_backquote()' function
907 * Defines the <CR><LF> value depending on the user OS.
909 * @uses PMA_USR_OS
910 * @return string the <CR><LF> value to use
912 * @access public
914 function PMA_whichCrlf()
916 $the_crlf = "\n";
918 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
919 // Win case
920 if (PMA_USR_OS == 'Win') {
921 $the_crlf = "\r\n";
923 // Others
924 else {
925 $the_crlf = "\n";
928 return $the_crlf;
929 } // end of the 'PMA_whichCrlf()' function
932 * Reloads navigation if needed.
934 * @uses $GLOBALS['reload']
935 * @uses $GLOBALS['db']
936 * @uses PMA_generate_common_url()
937 * @global array configuration
939 * @access public
941 function PMA_reloadNavigation()
943 global $cfg;
945 // Reloads the navigation frame via JavaScript if required
946 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
947 // one of the reasons for a reload is when a table is dropped
948 // in this case, get rid of the table limit offset, otherwise
949 // we have a problem when dropping a table on the last page
950 // and the offset becomes greater than the total number of tables
951 unset($_SESSION['userconf']['table_limit_offset']);
952 echo "\n";
953 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
955 <script type="text/javascript">
956 //<![CDATA[
957 if (typeof(window.parent) != 'undefined'
958 && typeof(window.parent.frame_navigation) != 'undefined'
959 && window.parent.goTo) {
960 window.parent.goTo('<?php echo $reload_url; ?>');
962 //]]>
963 </script>
964 <?php
965 unset($GLOBALS['reload']);
970 * displays the message and the query
971 * usually the message is the result of the query executed
973 * @param string $message the message to display
974 * @param string $sql_query the query to display
975 * @param string $type the type (level) of the message
976 * @global array the configuration array
977 * @uses $cfg
978 * @access public
980 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
982 global $cfg;
984 if (null === $sql_query) {
985 if (! empty($GLOBALS['display_query'])) {
986 $sql_query = $GLOBALS['display_query'];
987 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
988 $sql_query = $GLOBALS['unparsed_sql'];
989 } elseif (! empty($GLOBALS['sql_query'])) {
990 $sql_query = $GLOBALS['sql_query'];
991 } else {
992 $sql_query = '';
996 // Corrects the tooltip text via JS if required
997 // @todo this is REALLY the wrong place to do this - very unexpected here
998 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
999 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1000 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1001 echo "\n";
1002 echo '<script type="text/javascript">' . "\n";
1003 echo '//<![CDATA[' . "\n";
1004 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1005 echo '//]]>' . "\n";
1006 echo '</script>' . "\n";
1007 } // end if ... elseif
1009 // Checks if the table needs to be repaired after a TRUNCATE query.
1010 // @todo what about $GLOBALS['display_query']???
1011 // @todo this is REALLY the wrong place to do this - very unexpected here
1012 if (strlen($GLOBALS['table'])
1013 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1014 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1015 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1018 unset($tbl_status);
1020 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1022 if ($message instanceof PMA_Message) {
1023 $message->display();
1024 $type = $message->getLevel();
1025 } else {
1026 echo '<div class="' . $type . '">';
1027 echo PMA_sanitize($message);
1028 if (isset($GLOBALS['special_message'])) {
1029 echo PMA_sanitize($GLOBALS['special_message']);
1030 unset($GLOBALS['special_message']);
1032 echo '</div>';
1035 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1036 // Html format the query to be displayed
1037 // If we want to show some sql code it is easiest to create it here
1038 /* SQL-Parser-Analyzer */
1040 if (! empty($GLOBALS['show_as_php'])) {
1041 $new_line = '\\n"<br />' . "\n"
1042 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1043 $query_base = htmlspecialchars(addslashes($sql_query));
1044 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1045 } else {
1046 $query_base = $sql_query;
1049 $query_too_big = false;
1051 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1052 // when the query is large (for example an INSERT of binary
1053 // data), the parser chokes; so avoid parsing the query
1054 $query_too_big = true;
1055 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1056 } elseif (! empty($GLOBALS['parsed_sql'])
1057 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1058 // (here, use "! empty" because when deleting a bookmark,
1059 // $GLOBALS['parsed_sql'] is set but empty
1060 $parsed_sql = $GLOBALS['parsed_sql'];
1061 } else {
1062 // Parse SQL if needed
1063 $parsed_sql = PMA_SQP_parse($query_base);
1066 // Analyze it
1067 if (isset($parsed_sql)) {
1068 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1069 // Here we append the LIMIT added for navigation, to
1070 // enable its display. Adding it higher in the code
1071 // to $sql_query would create a problem when
1072 // using the Refresh or Edit links.
1074 // Only append it on SELECTs.
1077 * @todo what would be the best to do when someone hits Refresh:
1078 * use the current LIMITs ?
1081 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1082 && isset($GLOBALS['sql_limit_to_append'])) {
1083 $query_base = $analyzed_display_query[0]['section_before_limit']
1084 . "\n" . $GLOBALS['sql_limit_to_append']
1085 . $analyzed_display_query[0]['section_after_limit'];
1086 // Need to reparse query
1087 $parsed_sql = PMA_SQP_parse($query_base);
1091 if (! empty($GLOBALS['show_as_php'])) {
1092 $query_base = '$sql = "' . $query_base;
1093 } elseif (! empty($GLOBALS['validatequery'])) {
1094 $query_base = PMA_validateSQL($query_base);
1095 } elseif (isset($parsed_sql)) {
1096 $query_base = PMA_formatSql($parsed_sql, $query_base);
1099 // Prepares links that may be displayed to edit/explain the query
1100 // (don't go to default pages, we must go to the page
1101 // where the query box is available)
1103 // Basic url query part
1104 $url_params = array();
1105 if (strlen($GLOBALS['db'])) {
1106 $url_params['db'] = $GLOBALS['db'];
1107 if (strlen($GLOBALS['table'])) {
1108 $url_params['table'] = $GLOBALS['table'];
1109 $edit_link = 'tbl_sql.php';
1110 } else {
1111 $edit_link = 'db_sql.php';
1113 } else {
1114 $edit_link = 'server_sql.php';
1117 // Want to have the query explained (Mike Beck 2002-05-22)
1118 // but only explain a SELECT (that has not been explained)
1119 /* SQL-Parser-Analyzer */
1120 $explain_link = '';
1121 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1122 $explain_params = $url_params;
1123 // Detect if we are validating as well
1124 // To preserve the validate uRL data
1125 if (! empty($GLOBALS['validatequery'])) {
1126 $explain_params['validatequery'] = 1;
1129 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1130 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1131 $_message = $GLOBALS['strExplain'];
1132 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1133 $explain_params['sql_query'] = substr($sql_query, 8);
1134 $_message = $GLOBALS['strNoExplain'];
1136 if (isset($explain_params['sql_query'])) {
1137 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1138 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1140 } //show explain
1142 $url_params['sql_query'] = $sql_query;
1143 $url_params['show_query'] = 1;
1145 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1146 if ($cfg['EditInWindow'] == true) {
1147 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1148 } else {
1149 $onclick = '';
1152 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1153 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1154 } else {
1155 $edit_link = '';
1158 $url_qpart = PMA_generate_common_url($url_params);
1160 // Also we would like to get the SQL formed in some nice
1161 // php-code (Mike Beck 2002-05-22)
1162 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1163 $php_params = $url_params;
1165 if (! empty($GLOBALS['show_as_php'])) {
1166 $_message = $GLOBALS['strNoPhp'];
1167 } else {
1168 $php_params['show_as_php'] = 1;
1169 $_message = $GLOBALS['strPhp'];
1172 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1173 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1175 if (isset($GLOBALS['show_as_php'])) {
1176 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1177 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1179 } else {
1180 $php_link = '';
1181 } //show as php
1183 // Refresh query
1184 if (! empty($cfg['SQLQuery']['Refresh'])
1185 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1186 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1187 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1188 } else {
1189 $refresh_link = '';
1190 } //show as php
1192 if (! empty($cfg['SQLValidator']['use'])
1193 && ! empty($cfg['SQLQuery']['Validate'])) {
1194 $validate_params = $url_params;
1195 if (!empty($GLOBALS['validatequery'])) {
1196 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1197 } else {
1198 $validate_params['validatequery'] = 1;
1199 $validate_message = $GLOBALS['strValidateSQL'] ;
1202 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1203 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1204 } else {
1205 $validate_link = '';
1206 } //validator
1208 echo '<code class="sql">';
1209 if ($query_too_big) {
1210 echo $shortened_query_base;
1211 } else {
1212 echo $query_base;
1215 //Clean up the end of the PHP
1216 if (! empty($GLOBALS['show_as_php'])) {
1217 echo '";';
1219 echo '</code>';
1221 echo '<div class="tools">';
1222 // avoid displaying a Profiling checkbox that could
1223 // be checked, which would reexecute an INSERT, for example
1224 if (! empty($refresh_link)) {
1225 PMA_profilingCheckbox($sql_query);
1227 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1228 echo '</div>';
1230 echo '</div><br />' . "\n";
1231 } // end of the 'PMA_showMessage()' function
1234 * Verifies if current MySQL server supports profiling
1236 * @uses $_SESSION['profiling_supported'] for caching
1237 * @uses $GLOBALS['server']
1238 * @uses PMA_DBI_fetch_value()
1239 * @uses PMA_MYSQL_INT_VERSION
1240 * @uses defined()
1241 * @access public
1242 * @return boolean whether profiling is supported
1244 * @author Marc Delisle
1246 function PMA_profilingSupported()
1248 if (! PMA_cacheExists('profiling_supported', true)) {
1249 // 5.0.37 has profiling but for example, 5.1.20 does not
1250 // (avoid a trip to the server for MySQL before 5.0.37)
1251 // and do not set a constant as we might be switching servers
1252 if (defined('PMA_MYSQL_INT_VERSION')
1253 && PMA_MYSQL_INT_VERSION >= 50037
1254 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1255 PMA_cacheSet('profiling_supported', true, true);
1256 } else {
1257 PMA_cacheSet('profiling_supported', false, true);
1261 return PMA_cacheGet('profiling_supported', true);
1265 * Displays a form with the Profiling checkbox
1267 * @param string $sql_query
1268 * @access public
1270 * @author Marc Delisle
1272 function PMA_profilingCheckbox($sql_query)
1274 if (PMA_profilingSupported()) {
1275 echo '<form action="sql.php" method="post">' . "\n";
1276 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1277 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1278 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1279 PMA_generate_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1280 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1281 echo '</form>' . "\n";
1286 * Displays the results of SHOW PROFILE
1288 * @param array the results
1289 * @access public
1291 * @author Marc Delisle
1293 function PMA_profilingResults($profiling_results)
1295 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1296 echo '<table>' . "\n";
1297 echo ' <tr>' . "\n";
1298 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1299 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1300 echo ' </tr>' . "\n";
1302 foreach($profiling_results as $one_result) {
1303 echo ' <tr>' . "\n";
1304 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1305 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1307 echo '</table>' . "\n";
1308 echo '</fieldset>' . "\n";
1312 * Formats $value to byte view
1314 * @param double the value to format
1315 * @param integer the sensitiveness
1316 * @param integer the number of decimals to retain
1318 * @return array the formatted value and its unit
1320 * @access public
1322 * @author staybyte
1323 * @version 1.2 - 18 July 2002
1325 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1327 $dh = PMA_pow(10, $comma);
1328 $li = PMA_pow(10, $limes);
1329 $return_value = $value;
1330 $unit = $GLOBALS['byteUnits'][0];
1332 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1333 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1334 // use 1024.0 to avoid integer overflow on 64-bit machines
1335 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1336 $unit = $GLOBALS['byteUnits'][$d];
1337 break 1;
1338 } // end if
1339 } // end for
1341 if ($unit != $GLOBALS['byteUnits'][0]) {
1342 // if the unit is not bytes (as represented in current language)
1343 // reformat with max length of 5
1344 // 4th parameter=true means do not reformat if value < 1
1345 $return_value = PMA_formatNumber($value, 5, $comma, true);
1346 } else {
1347 // do not reformat, just handle the locale
1348 $return_value = PMA_formatNumber($value, 0);
1351 return array($return_value, $unit);
1352 } // end of the 'PMA_formatByteDown' function
1355 * Formats $value to the given length and appends SI prefixes
1356 * $comma is not substracted from the length
1357 * with a $length of 0 no truncation occurs, number is only formated
1358 * to the current locale
1360 * examples:
1361 * <code>
1362 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1363 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1364 * echo PMA_formatNumber(-0.003, 6); // -3 m
1365 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1366 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1367 * echo PMA_formatNumber(0, 6); // 0
1369 * </code>
1370 * @param double $value the value to format
1371 * @param integer $length the max length
1372 * @param integer $comma the number of decimals to retain
1373 * @param boolean $only_down do not reformat numbers below 1
1375 * @return string the formatted value and its unit
1377 * @access public
1379 * @author staybyte, sebastian mendel
1380 * @version 1.1.0 - 2005-10-27
1382 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1384 //number_format is not multibyte safe, str_replace is safe
1385 if ($length === 0) {
1386 return str_replace(array(',', '.'),
1387 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1388 number_format($value, $comma));
1391 // this units needs no translation, ISO
1392 $units = array(
1393 -8 => 'y',
1394 -7 => 'z',
1395 -6 => 'a',
1396 -5 => 'f',
1397 -4 => 'p',
1398 -3 => 'n',
1399 -2 => '&micro;',
1400 -1 => 'm',
1401 0 => ' ',
1402 1 => 'k',
1403 2 => 'M',
1404 3 => 'G',
1405 4 => 'T',
1406 5 => 'P',
1407 6 => 'E',
1408 7 => 'Z',
1409 8 => 'Y'
1412 // we need at least 3 digits to be displayed
1413 if (3 > $length + $comma) {
1414 $length = 3 - $comma;
1417 // check for negative value to retain sign
1418 if ($value < 0) {
1419 $sign = '-';
1420 $value = abs($value);
1421 } else {
1422 $sign = '';
1425 $dh = PMA_pow(10, $comma);
1426 $li = PMA_pow(10, $length);
1427 $unit = $units[0];
1429 if ($value >= 1) {
1430 for ($d = 8; $d >= 0; $d--) {
1431 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1432 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1433 $unit = $units[$d];
1434 break 1;
1435 } // end if
1436 } // end for
1437 } elseif (!$only_down && (float) $value !== 0.0) {
1438 for ($d = -8; $d <= 8; $d++) {
1439 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1440 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1441 $unit = $units[$d];
1442 break 1;
1443 } // end if
1444 } // end for
1445 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1447 //number_format is not multibyte safe, str_replace is safe
1448 $value = str_replace(array(',', '.'),
1449 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1450 number_format($value, $comma));
1452 return $sign . $value . ' ' . $unit;
1453 } // end of the 'PMA_formatNumber' function
1456 * Writes localised date
1458 * @param string the current timestamp
1460 * @return string the formatted date
1462 * @access public
1464 function PMA_localisedDate($timestamp = -1, $format = '')
1466 global $datefmt, $month, $day_of_week;
1468 if ($format == '') {
1469 $format = $datefmt;
1472 if ($timestamp == -1) {
1473 $timestamp = time();
1476 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1477 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1479 return strftime($date, $timestamp);
1480 } // end of the 'PMA_localisedDate()' function
1484 * returns a tab for tabbed navigation.
1485 * If the variables $link and $args ar left empty, an inactive tab is created
1487 * @uses $GLOBALS['PMA_PHP_SELF']
1488 * @uses $GLOBALS['strEmpty']
1489 * @uses $GLOBALS['strDrop']
1490 * @uses $GLOBALS['active_page']
1491 * @uses $GLOBALS['url_query']
1492 * @uses $cfg['MainPageIconic']
1493 * @uses $GLOBALS['pmaThemeImage']
1494 * @uses PMA_generate_common_url()
1495 * @uses E_USER_NOTICE
1496 * @uses htmlentities()
1497 * @uses urlencode()
1498 * @uses sprintf()
1499 * @uses trigger_error()
1500 * @uses array_merge()
1501 * @uses basename()
1502 * @param array $tab array with all options
1503 * @return string html code for one tab, a link if valid otherwise a span
1504 * @access public
1506 function PMA_getTab($tab)
1508 // default values
1509 $defaults = array(
1510 'text' => '',
1511 'class' => '',
1512 'active' => false,
1513 'link' => '',
1514 'sep' => '?',
1515 'attr' => '',
1516 'args' => '',
1517 'warning' => '',
1518 'fragment' => '',
1521 $tab = array_merge($defaults, $tab);
1523 // determine additionnal style-class
1524 if (empty($tab['class'])) {
1525 if ($tab['text'] == $GLOBALS['strEmpty']
1526 || $tab['text'] == $GLOBALS['strDrop']) {
1527 $tab['class'] = 'caution';
1528 } elseif (! empty($tab['active'])
1529 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1530 $tab['class'] = 'active';
1531 } elseif (empty($GLOBALS['active_page'])
1532 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1533 && empty($tab['warning'])) {
1534 $tab['class'] = 'active';
1538 if (!empty($tab['warning'])) {
1539 $tab['class'] .= ' warning';
1540 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1543 // build the link
1544 if (!empty($tab['link'])) {
1545 $tab['link'] = htmlentities($tab['link']);
1546 $tab['link'] = $tab['link'] . $tab['sep']
1547 .(empty($GLOBALS['url_query']) ?
1548 PMA_generate_common_url() : $GLOBALS['url_query']);
1549 if (! empty($tab['args'])) {
1550 foreach ($tab['args'] as $param => $value) {
1551 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1552 . urlencode($value);
1557 if (! empty($tab['fragment'])) {
1558 $tab['link'] .= $tab['fragment'];
1561 // display icon, even if iconic is disabled but the link-text is missing
1562 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1563 && isset($tab['icon'])) {
1564 // avoid generating an alt tag, because it only illustrates
1565 // the text that follows and if browser does not display
1566 // images, the text is duplicated
1567 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1568 .'%1$s" width="16" height="16" alt="" />%2$s';
1569 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1571 // check to not display an empty link-text
1572 elseif (empty($tab['text'])) {
1573 $tab['text'] = '?';
1574 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1575 E_USER_NOTICE);
1578 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1580 if (!empty($tab['link'])) {
1581 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1582 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1583 . $tab['text'] . '</a>';
1584 } else {
1585 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1586 . $tab['text'] . '</span>';
1589 $out .= '</li>';
1590 return $out;
1591 } // end of the 'PMA_getTab()' function
1594 * returns html-code for a tab navigation
1596 * @uses PMA_getTab()
1597 * @uses htmlentities()
1598 * @param array $tabs one element per tab
1599 * @param string $tag_id id used for the html-tag
1600 * @return string html-code for tab-navigation
1602 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1604 $tab_navigation =
1605 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1606 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1608 foreach ($tabs as $tab) {
1609 $tab_navigation .= PMA_getTab($tab) . "\n";
1612 $tab_navigation .=
1613 '</ul>' . "\n"
1614 .'<div class="clearfloat"></div>'
1615 .'</div>' . "\n";
1617 return $tab_navigation;
1622 * Displays a link, or a button if the link's URL is too large, to
1623 * accommodate some browsers' limitations
1625 * @param string the URL
1626 * @param string the link message
1627 * @param mixed $tag_params string: js confirmation
1628 * array: additional tag params (f.e. style="")
1629 * @param boolean $new_form we set this to false when we are already in
1630 * a form, to avoid generating nested forms
1632 * @return string the results to be echoed or saved in an array
1634 function PMA_linkOrButton($url, $message, $tag_params = array(),
1635 $new_form = true, $strip_img = false, $target = '')
1637 if (! is_array($tag_params)) {
1638 $tmp = $tag_params;
1639 $tag_params = array();
1640 if (!empty($tmp)) {
1641 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1643 unset($tmp);
1645 if (! empty($target)) {
1646 $tag_params['target'] = htmlentities($target);
1649 $tag_params_strings = array();
1650 foreach ($tag_params as $par_name => $par_value) {
1651 // htmlspecialchars() only on non javascript
1652 $par_value = substr($par_name, 0, 2) == 'on'
1653 ? $par_value
1654 : htmlspecialchars($par_value);
1655 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1658 // previously the limit was set to 2047, it seems 1000 is better
1659 if (strlen($url) <= 1000) {
1660 // no whitespace within an <a> else Safari will make it part of the link
1661 $ret = "\n" . '<a href="' . $url . '" '
1662 . implode(' ', $tag_params_strings) . '>'
1663 . $message . '</a>' . "\n";
1664 } else {
1665 // no spaces (linebreaks) at all
1666 // or after the hidden fields
1667 // IE will display them all
1669 // add class=link to submit button
1670 if (empty($tag_params['class'])) {
1671 $tag_params['class'] = 'link';
1674 // decode encoded url separators
1675 $separator = PMA_get_arg_separator();
1676 // on most places separator is still hard coded ...
1677 if ($separator !== '&') {
1678 // ... so always replace & with $separator
1679 $url = str_replace(htmlentities('&'), $separator, $url);
1680 $url = str_replace('&', $separator, $url);
1682 $url = str_replace(htmlentities($separator), $separator, $url);
1683 // end decode
1685 $url_parts = parse_url($url);
1686 $query_parts = explode($separator, $url_parts['query']);
1687 if ($new_form) {
1688 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1689 . ' method="post"' . $target . ' style="display: inline;">';
1690 $subname_open = '';
1691 $subname_close = '';
1692 $submit_name = '';
1693 } else {
1694 $query_parts[] = 'redirect=' . $url_parts['path'];
1695 if (empty($GLOBALS['subform_counter'])) {
1696 $GLOBALS['subform_counter'] = 0;
1698 $GLOBALS['subform_counter']++;
1699 $ret = '';
1700 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1701 $subname_close = ']';
1702 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1704 foreach ($query_parts as $query_pair) {
1705 list($eachvar, $eachval) = explode('=', $query_pair);
1706 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1707 . $subname_close . '" value="'
1708 . htmlspecialchars(urldecode($eachval)) . '" />';
1709 } // end while
1711 if (stristr($message, '<img')) {
1712 if ($strip_img) {
1713 $message = trim(strip_tags($message));
1714 $ret .= '<input type="submit"' . $submit_name . ' '
1715 . implode(' ', $tag_params_strings)
1716 . ' value="' . htmlspecialchars($message) . '" />';
1717 } else {
1718 $ret .= '<input type="image"' . $submit_name . ' '
1719 . implode(' ', $tag_params_strings)
1720 . ' src="' . preg_replace(
1721 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1722 . ' value="' . htmlspecialchars(
1723 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1724 $message))
1725 . '" />';
1727 } else {
1728 $message = trim(strip_tags($message));
1729 $ret .= '<input type="submit"' . $submit_name . ' '
1730 . implode(' ', $tag_params_strings)
1731 . ' value="' . htmlspecialchars($message) . '" />';
1733 if ($new_form) {
1734 $ret .= '</form>';
1736 } // end if... else...
1738 return $ret;
1739 } // end of the 'PMA_linkOrButton()' function
1743 * Returns a given timespan value in a readable format.
1745 * @uses $GLOBALS['timespanfmt']
1746 * @uses sprintf()
1747 * @uses floor()
1748 * @param int the timespan
1750 * @return string the formatted value
1752 function PMA_timespanFormat($seconds)
1754 $return_string = '';
1755 $days = floor($seconds / 86400);
1756 if ($days > 0) {
1757 $seconds -= $days * 86400;
1759 $hours = floor($seconds / 3600);
1760 if ($days > 0 || $hours > 0) {
1761 $seconds -= $hours * 3600;
1763 $minutes = floor($seconds / 60);
1764 if ($days > 0 || $hours > 0 || $minutes > 0) {
1765 $seconds -= $minutes * 60;
1767 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1771 * Takes a string and outputs each character on a line for itself. Used
1772 * mainly for horizontalflipped display mode.
1773 * Takes care of special html-characters.
1774 * Fulfills todo-item
1775 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1777 * @todo add a multibyte safe function PMA_STR_split()
1778 * @uses strlen
1779 * @param string The string
1780 * @param string The Separator (defaults to "<br />\n")
1782 * @access public
1783 * @author Garvin Hicking <me@supergarv.de>
1784 * @return string The flipped string
1786 function PMA_flipstring($string, $Separator = "<br />\n")
1788 $format_string = '';
1789 $charbuff = false;
1791 for ($i = 0; $i < strlen($string); $i++) {
1792 $char = $string{$i};
1793 $append = false;
1795 if ($char == '&') {
1796 $format_string .= $charbuff;
1797 $charbuff = $char;
1798 $append = true;
1799 } elseif (!empty($charbuff)) {
1800 $charbuff .= $char;
1801 } elseif ($char == ';' && !empty($charbuff)) {
1802 $format_string .= $charbuff;
1803 $charbuff = false;
1804 $append = true;
1805 } else {
1806 $format_string .= $char;
1807 $append = true;
1810 if ($append && ($i != strlen($string))) {
1811 $format_string .= $Separator;
1815 return $format_string;
1820 * Function added to avoid path disclosures.
1821 * Called by each script that needs parameters, it displays
1822 * an error message and, by default, stops the execution.
1824 * Not sure we could use a strMissingParameter message here,
1825 * would have to check if the error message file is always available
1827 * @todo localize error message
1828 * @todo use PMA_fatalError() if $die === true?
1829 * @uses PMA_getenv()
1830 * @uses header_meta_style.inc.php
1831 * @uses $GLOBALS['PMA_PHP_SELF']
1832 * basename
1833 * @param array The names of the parameters needed by the calling
1834 * script.
1835 * @param boolean Stop the execution?
1836 * (Set this manually to false in the calling script
1837 * until you know all needed parameters to check).
1838 * @param boolean Whether to include this list in checking for special params.
1839 * @global string path to current script
1840 * @global boolean flag whether any special variable was required
1842 * @access public
1843 * @author Marc Delisle (lem9@users.sourceforge.net)
1845 function PMA_checkParameters($params, $die = true, $request = true)
1847 global $checked_special;
1849 if (!isset($checked_special)) {
1850 $checked_special = false;
1853 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1854 $found_error = false;
1855 $error_message = '';
1857 foreach ($params as $param) {
1858 if ($request && $param != 'db' && $param != 'table') {
1859 $checked_special = true;
1862 if (!isset($GLOBALS[$param])) {
1863 $error_message .= $reported_script_name
1864 . ': Missing parameter: ' . $param
1865 . ' <a href="./Documentation.html#faqmissingparameters"'
1866 . ' target="documentation"> (FAQ 2.8)</a><br />';
1867 $found_error = true;
1870 if ($found_error) {
1872 * display html meta tags
1874 require_once './libraries/header_meta_style.inc.php';
1875 echo '</head><body><p>' . $error_message . '</p></body></html>';
1876 if ($die) {
1877 exit();
1880 } // end function
1883 * Function to generate unique condition for specified row.
1885 * @uses $GLOBALS['analyzed_sql'][0]
1886 * @uses PMA_DBI_field_flags()
1887 * @uses PMA_backquote()
1888 * @uses PMA_sqlAddslashes()
1889 * @uses stristr()
1890 * @uses bin2hex()
1891 * @uses preg_replace()
1892 * @param resource $handle current query result
1893 * @param integer $fields_cnt number of fields
1894 * @param array $fields_meta meta information about fields
1895 * @param array $row current row
1896 * @param boolean $force_unique generate condition only on pk or unique
1898 * @access public
1899 * @author Michal Cihar (michal@cihar.com) and others...
1900 * @return string calculated condition
1902 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1904 $primary_key = '';
1905 $unique_key = '';
1906 $nonprimary_condition = '';
1907 $preferred_condition = '';
1909 for ($i = 0; $i < $fields_cnt; ++$i) {
1910 $condition = '';
1911 $field_flags = PMA_DBI_field_flags($handle, $i);
1912 $meta = $fields_meta[$i];
1914 // do not use a column alias in a condition
1915 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1916 $meta->orgname = $meta->name;
1918 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1919 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1920 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1921 as $select_expr) {
1922 // need (string) === (string)
1923 // '' !== 0 but '' == 0
1924 if ((string) $select_expr['alias'] === (string) $meta->name) {
1925 $meta->orgname = $select_expr['column'];
1926 break;
1927 } // end if
1928 } // end foreach
1932 // Do not use a table alias in a condition.
1933 // Test case is:
1934 // select * from galerie x WHERE
1935 //(select count(*) from galerie y where y.datum=x.datum)>1
1937 // But orgtable is present only with mysqli extension so the
1938 // fix is only for mysqli.
1939 // Also, do not use the original table name if we are dealing with
1940 // a view because this view might be updatable.
1941 // (The isView() verification should not be costly in most cases
1942 // because there is some caching in the function).
1943 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1944 $meta->table = $meta->orgtable;
1947 // to fix the bug where float fields (primary or not)
1948 // can't be matched because of the imprecision of
1949 // floating comparison, use CONCAT
1950 // (also, the syntax "CONCAT(field) IS NULL"
1951 // that we need on the next "if" will work)
1952 if ($meta->type == 'real') {
1953 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1954 . PMA_backquote($meta->orgname) . ') ';
1955 } else {
1956 $condition = ' ' . PMA_backquote($meta->table) . '.'
1957 . PMA_backquote($meta->orgname) . ' ';
1958 } // end if... else...
1960 if (!isset($row[$i]) || is_null($row[$i])) {
1961 $condition .= 'IS NULL AND';
1962 } else {
1963 // timestamp is numeric on some MySQL 4.1
1964 if ($meta->numeric && $meta->type != 'timestamp') {
1965 $condition .= '= ' . $row[$i] . ' AND';
1966 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1967 // hexify only if this is a true not empty BLOB or a BINARY
1968 && stristr($field_flags, 'BINARY')
1969 && !empty($row[$i])) {
1970 // do not waste memory building a too big condition
1971 if (strlen($row[$i]) < 1000) {
1972 // use a CAST if possible, to avoid problems
1973 // if the field contains wildcard characters % or _
1974 $condition .= '= CAST(0x' . bin2hex($row[$i])
1975 . ' AS BINARY) AND';
1976 } else {
1977 // this blob won't be part of the final condition
1978 $condition = '';
1980 } else {
1981 $condition .= '= \''
1982 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
1985 if ($meta->primary_key > 0) {
1986 $primary_key .= $condition;
1987 } elseif ($meta->unique_key > 0) {
1988 $unique_key .= $condition;
1990 $nonprimary_condition .= $condition;
1991 } // end for
1993 // Correction University of Virginia 19991216:
1994 // prefer primary or unique keys for condition,
1995 // but use conjunction of all values if no primary key
1996 if ($primary_key) {
1997 $preferred_condition = $primary_key;
1998 } elseif ($unique_key) {
1999 $preferred_condition = $unique_key;
2000 } elseif (! $force_unique) {
2001 $preferred_condition = $nonprimary_condition;
2004 return preg_replace('|\s?AND$|', '', $preferred_condition);
2005 } // end function
2008 * Generate a button or image tag
2010 * @uses PMA_USR_BROWSER_AGENT
2011 * @uses $GLOBALS['pmaThemeImage']
2012 * @uses $GLOBALS['cfg']['PropertiesIconic']
2013 * @param string name of button element
2014 * @param string class of button element
2015 * @param string name of image element
2016 * @param string text to display
2017 * @param string image to display
2019 * @access public
2020 * @author Michal Cihar (michal@cihar.com)
2022 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2023 $image)
2025 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2026 echo ' <input type="submit" name="' . $button_name . '"'
2027 .' value="' . htmlspecialchars($text) . '"'
2028 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2029 return;
2032 /* Opera has trouble with <input type="image"> */
2033 /* IE has trouble with <button> */
2034 if (PMA_USR_BROWSER_AGENT != 'IE') {
2035 echo '<button class="' . $button_class . '" type="submit"'
2036 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2037 .' title="' . htmlspecialchars($text) . '">' . "\n"
2038 . PMA_getIcon($image, $text)
2039 .'</button>' . "\n";
2040 } else {
2041 echo '<input type="image" name="' . $image_name . '" value="'
2042 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2043 . $image . '" />'
2044 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2046 } // end function
2049 * Generate a pagination selector for browsing resultsets
2051 * @todo $url is not javascript escaped!?
2052 * @uses $GLOBALS['strPageNumber']
2053 * @uses range()
2054 * @param string URL for the JavaScript
2055 * @param string Number of rows in the pagination set
2056 * @param string current page number
2057 * @param string number of total pages
2058 * @param string If the number of pages is lower than this
2059 * variable, no pages will be omitted in
2060 * pagination
2061 * @param string How many rows at the beginning should always
2062 * be shown?
2063 * @param string How many rows at the end should always
2064 * be shown?
2065 * @param string Percentage of calculation page offsets to
2066 * hop to a next page
2067 * @param string Near the current page, how many pages should
2068 * be considered "nearby" and displayed as
2069 * well?
2070 * @param string The prompt to display (sometimes empty)
2072 * @access public
2073 * @author Garvin Hicking (pma@supergarv.de)
2075 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2076 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2077 $range = 10, $prompt = '')
2079 $increment = floor($nbTotalPage / $percent);
2080 $pageNowMinusRange = ($pageNow - $range);
2081 $pageNowPlusRange = ($pageNow + $range);
2083 $gotopage = $prompt
2084 . ' <select name="pos" onchange="goToUrl(this, \''
2085 . $url . '\');">' . "\n";
2086 if ($nbTotalPage < $showAll) {
2087 $pages = range(1, $nbTotalPage);
2088 } else {
2089 $pages = array();
2091 // Always show first X pages
2092 for ($i = 1; $i <= $sliceStart; $i++) {
2093 $pages[] = $i;
2096 // Always show last X pages
2097 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2098 $pages[] = $i;
2101 // garvin: Based on the number of results we add the specified
2102 // $percent percentage to each page number,
2103 // so that we have a representing page number every now and then to
2104 // immediately jump to specific pages.
2105 // As soon as we get near our currently chosen page ($pageNow -
2106 // $range), every page number will be shown.
2107 $i = $sliceStart;
2108 $x = $nbTotalPage - $sliceEnd;
2109 $met_boundary = false;
2110 while ($i <= $x) {
2111 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2112 // If our pageselector comes near the current page, we use 1
2113 // counter increments
2114 $i++;
2115 $met_boundary = true;
2116 } else {
2117 // We add the percentage increment to our current page to
2118 // hop to the next one in range
2119 $i += $increment;
2121 // Make sure that we do not cross our boundaries.
2122 if ($i > $pageNowMinusRange && ! $met_boundary) {
2123 $i = $pageNowMinusRange;
2127 if ($i > 0 && $i <= $x) {
2128 $pages[] = $i;
2132 // Since because of ellipsing of the current page some numbers may be double,
2133 // we unify our array:
2134 sort($pages);
2135 $pages = array_unique($pages);
2138 foreach ($pages as $i) {
2139 if ($i == $pageNow) {
2140 $selected = 'selected="selected" style="font-weight: bold"';
2141 } else {
2142 $selected = '';
2144 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2147 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2149 return $gotopage;
2150 } // end function
2154 * Generate navigation for a list
2156 * @todo use $pos from $_url_params
2157 * @uses $GLOBALS['strPageNumber']
2158 * @uses range()
2159 * @param integer number of elements in the list
2160 * @param integer current position in the list
2161 * @param array url parameters
2162 * @param string script name for form target
2163 * @param string target frame
2164 * @param integer maximum number of elements to display from the list
2166 * @access public
2168 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2170 if ($max_count < $count) {
2171 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2172 echo $GLOBALS['strPageNumber'];
2173 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2175 // Move to the beginning or to the previous page
2176 if ($pos > 0) {
2177 // loic1: patch #474210 from Gosha Sakovich - part 1
2178 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2179 $caption1 = '&lt;&lt;';
2180 $caption2 = ' &lt; ';
2181 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2182 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2183 } else {
2184 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2185 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2186 $title1 = '';
2187 $title2 = '';
2188 } // end if... else...
2189 $_url_params['pos'] = 0;
2190 echo '<a' . $title1 . ' href="' . $script
2191 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2192 . $caption1 . '</a>';
2193 $_url_params['pos'] = $pos - $max_count;
2194 echo '<a' . $title2 . ' href="' . $script
2195 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2196 . $caption2 . '</a>';
2199 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2200 echo PMA_generate_common_hidden_inputs($_url_params);
2201 echo PMA_pageselector(
2202 $script . PMA_generate_common_url($_url_params) . '&',
2203 $max_count,
2204 floor(($pos + 1) / $max_count) + 1,
2205 ceil($count / $max_count));
2206 echo '</form>';
2208 if ($pos + $max_count < $count) {
2209 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2210 $caption3 = ' &gt; ';
2211 $caption4 = '&gt;&gt;';
2212 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2213 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2214 } else {
2215 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2216 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2217 $title3 = '';
2218 $title4 = '';
2219 } // end if... else...
2220 $_url_params['pos'] = $pos + $max_count;
2221 echo '<a' . $title3 . ' href="' . $script
2222 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2223 . $caption3 . '</a>';
2224 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2225 if ($_url_params['pos'] == $count) {
2226 $_url_params['pos'] = $count - $max_count;
2228 echo '<a' . $title4 . ' href="' . $script
2229 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2230 . $caption4 . '</a>';
2232 echo "\n";
2233 if ('frame_navigation' == $frame) {
2234 echo '</div>' . "\n";
2240 * replaces %u in given path with current user name
2242 * example:
2243 * <code>
2244 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2246 * </code>
2247 * @uses $cfg['Server']['user']
2248 * @uses substr()
2249 * @uses str_replace()
2250 * @param string $dir with wildcard for user
2251 * @return string per user directory
2253 function PMA_userDir($dir)
2255 // add trailing slash
2256 if (substr($dir, -1) != '/') {
2257 $dir .= '/';
2260 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2264 * returns html code for db link to default db page
2266 * @uses $cfg['DefaultTabDatabase']
2267 * @uses $GLOBALS['db']
2268 * @uses $GLOBALS['strJumpToDB']
2269 * @uses PMA_generate_common_url()
2270 * @uses PMA_unescape_mysql_wildcards()
2271 * @uses strlen()
2272 * @uses sprintf()
2273 * @uses htmlspecialchars()
2274 * @param string $database
2275 * @return string html link to default db page
2277 function PMA_getDbLink($database = null)
2279 if (!strlen($database)) {
2280 if (!strlen($GLOBALS['db'])) {
2281 return '';
2283 $database = $GLOBALS['db'];
2284 } else {
2285 $database = PMA_unescape_mysql_wildcards($database);
2288 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2289 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2290 .htmlspecialchars($database) . '</a>';
2294 * Displays a lightbulb hint explaining a known external bug
2295 * that affects a functionality
2297 * @uses PMA_MYSQL_INT_VERSION
2298 * @uses $GLOBALS['strKnownExternalBug']
2299 * @uses PMA_showHint()
2300 * @uses sprintf()
2301 * @param string $functionality localized message explaining the func.
2302 * @param string $component 'mysql' (eventually, 'php')
2303 * @param string $minimum_version of this component
2304 * @param string $bugref bug reference for this component
2306 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2308 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2309 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2314 * Generates and echoes an HTML checkbox
2316 * @param string $html_field_name the checkbox HTML field
2317 * @param string $label
2318 * @param boolean $checked is it initially checked?
2319 * @param boolean $onclick should it submit the form on click?
2321 function PMA_generate_html_checkbox($html_field_name, $label, $checked, $onclick) {
2323 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>';
2327 * Generates and echoes a set of radio HTML fields
2329 * @uses htmlspecialchars()
2330 * @param string $html_field_name the radio HTML field
2331 * @param array $choices the choices values and labels
2332 * @param string $checked_choice the choice to check by default
2333 * @param boolean $line_break whether to add an HTML line break after a choice
2334 * @param boolean $escape_label whether to use htmlspecialchars() on label
2335 * @param string $class enclose each choice with a div of this class
2337 function PMA_generate_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2338 foreach ($choices as $choice_value => $choice_label) {
2339 if (! empty($class)) {
2340 echo '<div class="' . $class . '">';
2342 $html_field_id = $html_field_name . '_' . $choice_value;
2343 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2344 if ($choice_value == $checked_choice) {
2345 echo ' checked="checked"';
2347 echo ' />' . "\n";
2348 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2349 if ($line_break) {
2350 echo '<br />';
2352 if (! empty($class)) {
2353 echo '</div>';
2355 echo "\n";
2360 * Generates and echoes an HTML dropdown
2362 * @uses htmlspecialchars()
2363 * @param string $select_name
2364 * @param array $choices the choices values
2365 * @param string $active_choice the choice to select by default
2366 * @todo support titles
2368 function PMA_generate_html_dropdown($select_name, $choices, $active_choice)
2370 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($select_name) . '">"' . "\n";
2371 foreach ($choices as $one_choice) {
2372 $result .= '<option value="' . htmlspecialchars($one_choice) . '"';
2373 if ($one_choice == $active_choice) {
2374 $result .= ' selected="selected"';
2376 $result .= '>' . htmlspecialchars($one_choice) . '</option>' . "\n";
2378 $result .= '</select>' . "\n";
2379 echo $result;
2383 * Generates a slider effect (Mootools)
2384 * Takes care of generating the initial <div> and the link
2385 * controlling the slider; you have to generate the </div> yourself
2386 * after the sliding section.
2388 * @uses $GLOBALS['cfg']['InitialSlidersState']
2389 * @param string $id the id of the <div> on which to apply the effect
2390 * @param string $message the message to show as a link
2392 function PMA_generate_slider_effect($id, $message)
2395 <script type="text/javascript">
2396 // <![CDATA[
2397 window.addEvent('domready', function(){
2398 var status = {
2399 'true': '- ',
2400 'false': '+ '
2403 var anchor<?php echo $id; ?> = new Element('a', {
2404 'id': 'toggle_<?php echo $id; ?>',
2405 'href': '#',
2406 'events': {
2407 'click': function(){
2408 mySlide<?php echo $id; ?>.toggle();
2413 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2414 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2416 var slider_status<?php echo $id; ?> = new Element('span', {
2417 'id': 'slider_status_<?php echo $id; ?>'
2419 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2420 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2422 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2423 <?php
2424 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2426 mySlide<?php echo $id; ?>.hide();
2427 <?php
2430 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2431 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2434 $('<?php echo $id; ?>').style.display="block";
2436 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2437 //]]>
2438 </script>
2439 <noscript>
2440 <div id="<?php echo $id; ?>">
2441 </noscript>
2442 <?php
2446 * Verifies if something is cached in the session
2448 * @param unknown_type $var
2449 * @param unknown_type $val
2450 * @param unknown_type $server
2451 * @return mixed
2453 function PMA_cacheExists($var, $server = 0)
2455 if (true === $server) {
2456 $server = $GLOBALS['server'];
2458 return isset($_SESSION['cache']['server_' . $server][$var]);
2462 * Gets cached information from the session
2464 * @param unknown_type $var
2465 * @param unknown_type $val
2466 * @param unknown_type $server
2467 * @return mixed
2469 function PMA_cacheGet($var, $server = 0)
2471 if (true === $server) {
2472 $server = $GLOBALS['server'];
2474 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2475 return $_SESSION['cache']['server_' . $server][$var];
2476 } else {
2477 return null;
2482 * Caches information in the session
2484 * @param unknown_type $var
2485 * @param unknown_type $val
2486 * @param unknown_type $server
2487 * @return mixed
2489 function PMA_cacheSet($var, $val = null, $server = 0)
2491 if (true === $server) {
2492 $server = $GLOBALS['server'];
2494 $_SESSION['cache']['server_' . $server][$var] = $val;
2498 * Removes cached information from the session
2500 * @param unknown_type $var
2501 * @param unknown_type $server
2502 * @return mixed
2504 function PMA_cacheUnset($var, $server = 0)
2506 if (true === $server) {
2507 $server = $GLOBALS['server'];
2509 unset($_SESSION['cache']['server_' . $server][$var]);
2513 * Converts a bit value to printable format;
2514 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2515 * function because in PHP, decbin() supports only 32 bits
2517 * @uses ceil()
2518 * @uses decbin()
2519 * @uses ord()
2520 * @uses substr()
2521 * @uses sprintf()
2522 * @param numeric $value coming from a BIT field
2523 * @param integer $length
2524 * @return string the printable value
2526 function PMA_printable_bit_value($value, $length) {
2527 $printable = '';
2528 for ($i = 0; $i < ceil($length / 8); $i++) {
2529 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2531 $printable = substr($printable, -$length);
2532 return $printable;
2536 * Extracts the various parts from a field type spec
2538 * @uses strpos()
2539 * @uses chop()
2540 * @uses substr()
2541 * @param string $fieldspec
2542 * @return array associative array containing type, spec_in_brackets
2543 * and possibly enum_set_values (another array)
2544 * @author Marc Delisle
2545 * @author Joshua Hogendorn
2547 function PMA_extractFieldSpec($fieldspec) {
2548 $first_bracket_pos = strpos($fieldspec, '(');
2549 if ($first_bracket_pos) {
2550 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strpos($fieldspec, ')') - $first_bracket_pos - 1)));
2551 // convert to lowercase just to be sure
2552 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2553 } else {
2554 $type = $fieldspec;
2555 $spec_in_brackets = '';
2558 if ('enum' == $type || 'set' == $type) {
2559 // Define our working vars
2560 $enum_set_values = array();
2561 $working = "";
2562 $in_string = false;
2563 $index = 0;
2565 // While there is another character to process
2566 while (isset($fieldspec[$index])) {
2567 // Grab the char to look at
2568 $char = $fieldspec[$index];
2570 // If it is a single quote, needs to be handled specially
2571 if ($char == "'") {
2572 // If we are not currently in a string, begin one
2573 if (! $in_string) {
2574 $in_string = true;
2575 $working = "";
2576 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2577 } else {
2578 // Check out the next character (if possible)
2579 $has_next = isset($fieldspec[$index + 1]);
2580 $next = $has_next ? $fieldspec[$index + 1] : null;
2582 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2583 if (! $has_next || $next != "'") {
2584 $enum_set_values[] = $working;
2585 $in_string = false;
2587 // Otherwise, this is a 'double quote', and can be added to the working string
2588 } elseif ($next == "'") {
2589 $working .= "'";
2590 // Skip the next char; we already know what it is
2591 $index++;
2594 // escaping of a quote?
2595 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2596 $working .= "'";
2597 $index++;
2598 // Otherwise, add it to our working string like normal
2599 } else {
2600 $working .= $char;
2602 // Increment character index
2603 $index++;
2604 } // end while
2605 } else {
2606 $enum_set_values = array();
2609 return array(
2610 'type' => $type,
2611 'spec_in_brackets' => $spec_in_brackets,
2612 'enum_set_values' => $enum_set_values
2617 * Verifies if this table's engine supports foreign keys
2619 * @uses strtoupper()
2620 * @param string $engine
2621 * @return boolean
2623 function PMA_foreignkey_supported($engine) {
2624 $engine = strtoupper($engine);
2625 if ('INNODB' == $engine || 'PBXT' == $engine) {
2626 return true;
2627 } else {
2628 return false;
2633 * Replaces some characters by a displayable equivalent
2635 * @uses str_replace()
2636 * @param string $content
2637 * @return string the content with characters replaced
2639 function PMA_replace_binary_contents($content) {
2640 $result = str_replace("\x00", '\0', $content);
2641 $result = str_replace("\x08", '\b', $result);
2642 $result = str_replace("\x0a", '\n', $result);
2643 $result = str_replace("\x0d", '\r', $result);
2644 $result = str_replace("\x1a", '\Z', $result);
2645 return $result;
2650 * If the first character given is \n (CR) we will add an extra \n
2652 * @uses strpos()
2653 * @return string with the chars replaced
2656 function PMA_duplicateFirstNewline($string){
2657 $first_occurence = strpos($string, "\n");
2658 if($first_occurence == 1){
2659 $string = "\n".$string;
2661 return $string;