typos and rephrasing
[phpmyadmin/crack.git] / libraries / common.lib.php
blob9cb76a4e4b2e0704472d348f2e008fcae0d2212a
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('<?php echo $reload_url; ?>');
961 //]]>
962 </script>
963 <?php
964 unset($GLOBALS['reload']);
969 * displays the message and the query
970 * usually the message is the result of the query executed
972 * @param string $message the message to display
973 * @param string $sql_query the query to display
974 * @param string $type the type (level) of the message
975 * @global array the configuration array
976 * @uses $cfg
977 * @access public
979 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
981 global $cfg;
983 if (null === $sql_query) {
984 if (! empty($GLOBALS['display_query'])) {
985 $sql_query = $GLOBALS['display_query'];
986 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
987 $sql_query = $GLOBALS['unparsed_sql'];
988 } elseif (! empty($GLOBALS['sql_query'])) {
989 $sql_query = $GLOBALS['sql_query'];
990 } else {
991 $sql_query = '';
995 // Corrects the tooltip text via JS if required
996 // @todo this is REALLY the wrong place to do this - very unexpected here
997 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
998 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
999 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1000 echo "\n";
1001 echo '<script type="text/javascript">' . "\n";
1002 echo '//<![CDATA[' . "\n";
1003 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1004 echo '//]]>' . "\n";
1005 echo '</script>' . "\n";
1006 } // end if ... elseif
1008 // Checks if the table needs to be repaired after a TRUNCATE query.
1009 // @todo what about $GLOBALS['display_query']???
1010 // @todo this is REALLY the wrong place to do this - very unexpected here
1011 if (strlen($GLOBALS['table'])
1012 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1013 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1014 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1017 unset($tbl_status);
1019 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1021 if ($message instanceof PMA_Message) {
1022 $message->display();
1023 $type = $message->getLevel();
1024 } else {
1025 echo '<div class="' . $type . '">';
1026 echo PMA_sanitize($message);
1027 if (isset($GLOBALS['special_message'])) {
1028 echo PMA_sanitize($GLOBALS['special_message']);
1029 unset($GLOBALS['special_message']);
1031 echo '</div>';
1034 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1035 // Html format the query to be displayed
1036 // If we want to show some sql code it is easiest to create it here
1037 /* SQL-Parser-Analyzer */
1039 if (! empty($GLOBALS['show_as_php'])) {
1040 $new_line = '\\n"<br />' . "\n"
1041 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1042 $query_base = htmlspecialchars(addslashes($sql_query));
1043 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1044 } else {
1045 $query_base = $sql_query;
1048 $query_too_big = false;
1050 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1051 // when the query is large (for example an INSERT of binary
1052 // data), the parser chokes; so avoid parsing the query
1053 $query_too_big = true;
1054 $query_base = nl2br(htmlspecialchars($sql_query));
1055 } elseif (! empty($GLOBALS['parsed_sql'])
1056 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1057 // (here, use "! empty" because when deleting a bookmark,
1058 // $GLOBALS['parsed_sql'] is set but empty
1059 $parsed_sql = $GLOBALS['parsed_sql'];
1060 } else {
1061 // Parse SQL if needed
1062 $parsed_sql = PMA_SQP_parse($query_base);
1065 // Analyze it
1066 if (isset($parsed_sql)) {
1067 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1068 // Here we append the LIMIT added for navigation, to
1069 // enable its display. Adding it higher in the code
1070 // to $sql_query would create a problem when
1071 // using the Refresh or Edit links.
1073 // Only append it on SELECTs.
1076 * @todo what would be the best to do when someone hits Refresh:
1077 * use the current LIMITs ?
1080 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1081 && isset($GLOBALS['sql_limit_to_append'])) {
1082 $query_base = $analyzed_display_query[0]['section_before_limit']
1083 . "\n" . $GLOBALS['sql_limit_to_append']
1084 . $analyzed_display_query[0]['section_after_limit'];
1085 // Need to reparse query
1086 $parsed_sql = PMA_SQP_parse($query_base);
1090 if (! empty($GLOBALS['show_as_php'])) {
1091 $query_base = '$sql = "' . $query_base;
1092 } elseif (! empty($GLOBALS['validatequery'])) {
1093 $query_base = PMA_validateSQL($query_base);
1094 } elseif (isset($parsed_sql)) {
1095 $query_base = PMA_formatSql($parsed_sql, $query_base);
1098 // Prepares links that may be displayed to edit/explain the query
1099 // (don't go to default pages, we must go to the page
1100 // where the query box is available)
1102 // Basic url query part
1103 $url_params = array();
1104 if (strlen($GLOBALS['db'])) {
1105 $url_params['db'] = $GLOBALS['db'];
1106 if (strlen($GLOBALS['table'])) {
1107 $url_params['table'] = $GLOBALS['table'];
1108 $edit_link = 'tbl_sql.php';
1109 } else {
1110 $edit_link = 'db_sql.php';
1112 } else {
1113 $edit_link = 'server_sql.php';
1116 // Want to have the query explained (Mike Beck 2002-05-22)
1117 // but only explain a SELECT (that has not been explained)
1118 /* SQL-Parser-Analyzer */
1119 $explain_link = '';
1120 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1121 $explain_params = $url_params;
1122 // Detect if we are validating as well
1123 // To preserve the validate uRL data
1124 if (! empty($GLOBALS['validatequery'])) {
1125 $explain_params['validatequery'] = 1;
1128 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1129 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1130 $_message = $GLOBALS['strExplain'];
1131 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1132 $explain_params['sql_query'] = substr($sql_query, 8);
1133 $_message = $GLOBALS['strNoExplain'];
1135 if (isset($explain_params['sql_query'])) {
1136 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1137 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1139 } //show explain
1141 $url_params['sql_query'] = $sql_query;
1142 $url_params['show_query'] = 1;
1144 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1145 if ($cfg['EditInWindow'] == true) {
1146 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1147 } else {
1148 $onclick = '';
1151 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1152 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1153 } else {
1154 $edit_link = '';
1157 $url_qpart = PMA_generate_common_url($url_params);
1159 // Also we would like to get the SQL formed in some nice
1160 // php-code (Mike Beck 2002-05-22)
1161 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1162 $php_params = $url_params;
1164 if (! empty($GLOBALS['show_as_php'])) {
1165 $_message = $GLOBALS['strNoPhp'];
1166 } else {
1167 $php_params['show_as_php'] = 1;
1168 $_message = $GLOBALS['strPhp'];
1171 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1172 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1174 if (isset($GLOBALS['show_as_php'])) {
1175 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1176 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1178 } else {
1179 $php_link = '';
1180 } //show as php
1182 // Refresh query
1183 if (! empty($cfg['SQLQuery']['Refresh'])
1184 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1185 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1186 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1187 } else {
1188 $refresh_link = '';
1189 } //show as php
1191 if (! empty($cfg['SQLValidator']['use'])
1192 && ! empty($cfg['SQLQuery']['Validate'])) {
1193 $validate_params = $url_params;
1194 if (!empty($GLOBALS['validatequery'])) {
1195 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1196 } else {
1197 $validate_params['validatequery'] = 1;
1198 $validate_message = $GLOBALS['strValidateSQL'] ;
1201 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1202 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1203 } else {
1204 $validate_link = '';
1205 } //validator
1207 echo '<code class="sql">';
1208 if ($query_too_big) {
1209 echo substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1210 } else {
1211 echo $query_base;
1214 //Clean up the end of the PHP
1215 if (! empty($GLOBALS['show_as_php'])) {
1216 echo '";';
1218 echo '</code>';
1220 echo '<div class="tools">';
1221 // avoid displaying a Profiling checkbox that could
1222 // be checked, which would reexecute an INSERT, for example
1223 if (! empty($refresh_link)) {
1224 PMA_profilingCheckbox($sql_query);
1226 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1227 echo '</div>';
1229 echo '</div><br />' . "\n";
1230 } // end of the 'PMA_showMessage()' function
1233 * Verifies if current MySQL server supports profiling
1235 * @uses $_SESSION['profiling_supported'] for caching
1236 * @uses $GLOBALS['server']
1237 * @uses PMA_DBI_fetch_value()
1238 * @uses PMA_MYSQL_INT_VERSION
1239 * @uses defined()
1240 * @access public
1241 * @return boolean whether profiling is supported
1243 * @author Marc Delisle
1245 function PMA_profilingSupported()
1247 if (! PMA_cacheExists('profiling_supported', true)) {
1248 // 5.0.37 has profiling but for example, 5.1.20 does not
1249 // (avoid a trip to the server for MySQL before 5.0.37)
1250 // and do not set a constant as we might be switching servers
1251 if (defined('PMA_MYSQL_INT_VERSION')
1252 && PMA_MYSQL_INT_VERSION >= 50037
1253 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1254 PMA_cacheSet('profiling_supported', true, true);
1255 } else {
1256 PMA_cacheSet('profiling_supported', false, true);
1260 return PMA_cacheGet('profiling_supported', true);
1264 * Displays a form with the Profiling checkbox
1266 * @param string $sql_query
1267 * @access public
1269 * @author Marc Delisle
1271 function PMA_profilingCheckbox($sql_query)
1273 if (PMA_profilingSupported()) {
1274 echo '<form action="sql.php" method="post">' . "\n";
1275 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1276 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1277 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1278 PMA_generate_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1279 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1280 echo '</form>' . "\n";
1285 * Displays the results of SHOW PROFILE
1287 * @param array the results
1288 * @access public
1290 * @author Marc Delisle
1292 function PMA_profilingResults($profiling_results)
1294 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1295 echo '<table>' . "\n";
1296 echo ' <tr>' . "\n";
1297 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1298 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1299 echo ' </tr>' . "\n";
1301 foreach($profiling_results as $one_result) {
1302 echo ' <tr>' . "\n";
1303 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1304 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1306 echo '</table>' . "\n";
1307 echo '</fieldset>' . "\n";
1311 * Formats $value to byte view
1313 * @param double the value to format
1314 * @param integer the sensitiveness
1315 * @param integer the number of decimals to retain
1317 * @return array the formatted value and its unit
1319 * @access public
1321 * @author staybyte
1322 * @version 1.2 - 18 July 2002
1324 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1326 $dh = PMA_pow(10, $comma);
1327 $li = PMA_pow(10, $limes);
1328 $return_value = $value;
1329 $unit = $GLOBALS['byteUnits'][0];
1331 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1332 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1333 // use 1024.0 to avoid integer overflow on 64-bit machines
1334 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1335 $unit = $GLOBALS['byteUnits'][$d];
1336 break 1;
1337 } // end if
1338 } // end for
1340 if ($unit != $GLOBALS['byteUnits'][0]) {
1341 // if the unit is not bytes (as represented in current language)
1342 // reformat with max length of 5
1343 // 4th parameter=true means do not reformat if value < 1
1344 $return_value = PMA_formatNumber($value, 5, $comma, true);
1345 } else {
1346 // do not reformat, just handle the locale
1347 $return_value = PMA_formatNumber($value, 0);
1350 return array($return_value, $unit);
1351 } // end of the 'PMA_formatByteDown' function
1354 * Formats $value to the given length and appends SI prefixes
1355 * $comma is not substracted from the length
1356 * with a $length of 0 no truncation occurs, number is only formated
1357 * to the current locale
1359 * examples:
1360 * <code>
1361 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1362 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1363 * echo PMA_formatNumber(-0.003, 6); // -3 m
1364 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1365 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1366 * echo PMA_formatNumber(0, 6); // 0
1368 * </code>
1369 * @param double $value the value to format
1370 * @param integer $length the max length
1371 * @param integer $comma the number of decimals to retain
1372 * @param boolean $only_down do not reformat numbers below 1
1374 * @return string the formatted value and its unit
1376 * @access public
1378 * @author staybyte, sebastian mendel
1379 * @version 1.1.0 - 2005-10-27
1381 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1383 //number_format is not multibyte safe, str_replace is safe
1384 if ($length === 0) {
1385 return str_replace(array(',', '.'),
1386 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1387 number_format($value, $comma));
1390 // this units needs no translation, ISO
1391 $units = array(
1392 -8 => 'y',
1393 -7 => 'z',
1394 -6 => 'a',
1395 -5 => 'f',
1396 -4 => 'p',
1397 -3 => 'n',
1398 -2 => '&micro;',
1399 -1 => 'm',
1400 0 => ' ',
1401 1 => 'k',
1402 2 => 'M',
1403 3 => 'G',
1404 4 => 'T',
1405 5 => 'P',
1406 6 => 'E',
1407 7 => 'Z',
1408 8 => 'Y'
1411 // we need at least 3 digits to be displayed
1412 if (3 > $length + $comma) {
1413 $length = 3 - $comma;
1416 // check for negative value to retain sign
1417 if ($value < 0) {
1418 $sign = '-';
1419 $value = abs($value);
1420 } else {
1421 $sign = '';
1424 $dh = PMA_pow(10, $comma);
1425 $li = PMA_pow(10, $length);
1426 $unit = $units[0];
1428 if ($value >= 1) {
1429 for ($d = 8; $d >= 0; $d--) {
1430 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1431 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1432 $unit = $units[$d];
1433 break 1;
1434 } // end if
1435 } // end for
1436 } elseif (!$only_down && (float) $value !== 0.0) {
1437 for ($d = -8; $d <= 8; $d++) {
1438 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1439 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1440 $unit = $units[$d];
1441 break 1;
1442 } // end if
1443 } // end for
1444 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1446 //number_format is not multibyte safe, str_replace is safe
1447 $value = str_replace(array(',', '.'),
1448 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1449 number_format($value, $comma));
1451 return $sign . $value . ' ' . $unit;
1452 } // end of the 'PMA_formatNumber' function
1455 * Writes localised date
1457 * @param string the current timestamp
1459 * @return string the formatted date
1461 * @access public
1463 function PMA_localisedDate($timestamp = -1, $format = '')
1465 global $datefmt, $month, $day_of_week;
1467 if ($format == '') {
1468 $format = $datefmt;
1471 if ($timestamp == -1) {
1472 $timestamp = time();
1475 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1476 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1478 return strftime($date, $timestamp);
1479 } // end of the 'PMA_localisedDate()' function
1483 * returns a tab for tabbed navigation.
1484 * If the variables $link and $args ar left empty, an inactive tab is created
1486 * @uses $GLOBALS['PMA_PHP_SELF']
1487 * @uses $GLOBALS['strEmpty']
1488 * @uses $GLOBALS['strDrop']
1489 * @uses $GLOBALS['active_page']
1490 * @uses $GLOBALS['url_query']
1491 * @uses $cfg['MainPageIconic']
1492 * @uses $GLOBALS['pmaThemeImage']
1493 * @uses PMA_generate_common_url()
1494 * @uses E_USER_NOTICE
1495 * @uses htmlentities()
1496 * @uses urlencode()
1497 * @uses sprintf()
1498 * @uses trigger_error()
1499 * @uses array_merge()
1500 * @uses basename()
1501 * @param array $tab array with all options
1502 * @return string html code for one tab, a link if valid otherwise a span
1503 * @access public
1505 function PMA_getTab($tab)
1507 // default values
1508 $defaults = array(
1509 'text' => '',
1510 'class' => '',
1511 'active' => false,
1512 'link' => '',
1513 'sep' => '?',
1514 'attr' => '',
1515 'args' => '',
1516 'warning' => '',
1517 'fragment' => '',
1520 $tab = array_merge($defaults, $tab);
1522 // determine additionnal style-class
1523 if (empty($tab['class'])) {
1524 if ($tab['text'] == $GLOBALS['strEmpty']
1525 || $tab['text'] == $GLOBALS['strDrop']) {
1526 $tab['class'] = 'caution';
1527 } elseif (! empty($tab['active'])
1528 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1529 $tab['class'] = 'active';
1530 } elseif (empty($GLOBALS['active_page'])
1531 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1532 && empty($tab['warning'])) {
1533 $tab['class'] = 'active';
1537 if (!empty($tab['warning'])) {
1538 $tab['class'] .= ' warning';
1539 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1542 // build the link
1543 if (!empty($tab['link'])) {
1544 $tab['link'] = htmlentities($tab['link']);
1545 $tab['link'] = $tab['link'] . $tab['sep']
1546 .(empty($GLOBALS['url_query']) ?
1547 PMA_generate_common_url() : $GLOBALS['url_query']);
1548 if (! empty($tab['args'])) {
1549 foreach ($tab['args'] as $param => $value) {
1550 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1551 . urlencode($value);
1556 if (! empty($tab['fragment'])) {
1557 $tab['link'] .= $tab['fragment'];
1560 // display icon, even if iconic is disabled but the link-text is missing
1561 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1562 && isset($tab['icon'])) {
1563 // avoid generating an alt tag, because it only illustrates
1564 // the text that follows and if browser does not display
1565 // images, the text is duplicated
1566 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1567 .'%1$s" width="16" height="16" alt="" />%2$s';
1568 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1570 // check to not display an empty link-text
1571 elseif (empty($tab['text'])) {
1572 $tab['text'] = '?';
1573 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1574 E_USER_NOTICE);
1577 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1579 if (!empty($tab['link'])) {
1580 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1581 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1582 . $tab['text'] . '</a>';
1583 } else {
1584 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1585 . $tab['text'] . '</span>';
1588 $out .= '</li>';
1589 return $out;
1590 } // end of the 'PMA_getTab()' function
1593 * returns html-code for a tab navigation
1595 * @uses PMA_getTab()
1596 * @uses htmlentities()
1597 * @param array $tabs one element per tab
1598 * @param string $tag_id id used for the html-tag
1599 * @return string html-code for tab-navigation
1601 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1603 $tab_navigation =
1604 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1605 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1607 foreach ($tabs as $tab) {
1608 $tab_navigation .= PMA_getTab($tab) . "\n";
1611 $tab_navigation .=
1612 '</ul>' . "\n"
1613 .'<div class="clearfloat"></div>'
1614 .'</div>' . "\n";
1616 return $tab_navigation;
1621 * Displays a link, or a button if the link's URL is too large, to
1622 * accommodate some browsers' limitations
1624 * @param string the URL
1625 * @param string the link message
1626 * @param mixed $tag_params string: js confirmation
1627 * array: additional tag params (f.e. style="")
1628 * @param boolean $new_form we set this to false when we are already in
1629 * a form, to avoid generating nested forms
1631 * @return string the results to be echoed or saved in an array
1633 function PMA_linkOrButton($url, $message, $tag_params = array(),
1634 $new_form = true, $strip_img = false, $target = '')
1636 if (! is_array($tag_params)) {
1637 $tmp = $tag_params;
1638 $tag_params = array();
1639 if (!empty($tmp)) {
1640 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1642 unset($tmp);
1644 if (! empty($target)) {
1645 $tag_params['target'] = htmlentities($target);
1648 $tag_params_strings = array();
1649 foreach ($tag_params as $par_name => $par_value) {
1650 // htmlspecialchars() only on non javascript
1651 $par_value = substr($par_name, 0, 2) == 'on'
1652 ? $par_value
1653 : htmlspecialchars($par_value);
1654 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1657 // previously the limit was set to 2047, it seems 1000 is better
1658 if (strlen($url) <= 1000) {
1659 // no whitespace within an <a> else Safari will make it part of the link
1660 $ret = "\n" . '<a href="' . $url . '" '
1661 . implode(' ', $tag_params_strings) . '>'
1662 . $message . '</a>' . "\n";
1663 } else {
1664 // no spaces (linebreaks) at all
1665 // or after the hidden fields
1666 // IE will display them all
1668 // add class=link to submit button
1669 if (empty($tag_params['class'])) {
1670 $tag_params['class'] = 'link';
1673 // decode encoded url separators
1674 $separator = PMA_get_arg_separator();
1675 // on most places separator is still hard coded ...
1676 if ($separator !== '&') {
1677 // ... so always replace & with $separator
1678 $url = str_replace(htmlentities('&'), $separator, $url);
1679 $url = str_replace('&', $separator, $url);
1681 $url = str_replace(htmlentities($separator), $separator, $url);
1682 // end decode
1684 $url_parts = parse_url($url);
1685 $query_parts = explode($separator, $url_parts['query']);
1686 if ($new_form) {
1687 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1688 . ' method="post"' . $target . ' style="display: inline;">';
1689 $subname_open = '';
1690 $subname_close = '';
1691 $submit_name = '';
1692 } else {
1693 $query_parts[] = 'redirect=' . $url_parts['path'];
1694 if (empty($GLOBALS['subform_counter'])) {
1695 $GLOBALS['subform_counter'] = 0;
1697 $GLOBALS['subform_counter']++;
1698 $ret = '';
1699 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1700 $subname_close = ']';
1701 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1703 foreach ($query_parts as $query_pair) {
1704 list($eachvar, $eachval) = explode('=', $query_pair);
1705 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1706 . $subname_close . '" value="'
1707 . htmlspecialchars(urldecode($eachval)) . '" />';
1708 } // end while
1710 if (stristr($message, '<img')) {
1711 if ($strip_img) {
1712 $message = trim(strip_tags($message));
1713 $ret .= '<input type="submit"' . $submit_name . ' '
1714 . implode(' ', $tag_params_strings)
1715 . ' value="' . htmlspecialchars($message) . '" />';
1716 } else {
1717 $ret .= '<input type="image"' . $submit_name . ' '
1718 . implode(' ', $tag_params_strings)
1719 . ' src="' . preg_replace(
1720 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1721 . ' value="' . htmlspecialchars(
1722 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1723 $message))
1724 . '" />';
1726 } else {
1727 $message = trim(strip_tags($message));
1728 $ret .= '<input type="submit"' . $submit_name . ' '
1729 . implode(' ', $tag_params_strings)
1730 . ' value="' . htmlspecialchars($message) . '" />';
1732 if ($new_form) {
1733 $ret .= '</form>';
1735 } // end if... else...
1737 return $ret;
1738 } // end of the 'PMA_linkOrButton()' function
1742 * Returns a given timespan value in a readable format.
1744 * @uses $GLOBALS['timespanfmt']
1745 * @uses sprintf()
1746 * @uses floor()
1747 * @param int the timespan
1749 * @return string the formatted value
1751 function PMA_timespanFormat($seconds)
1753 $return_string = '';
1754 $days = floor($seconds / 86400);
1755 if ($days > 0) {
1756 $seconds -= $days * 86400;
1758 $hours = floor($seconds / 3600);
1759 if ($days > 0 || $hours > 0) {
1760 $seconds -= $hours * 3600;
1762 $minutes = floor($seconds / 60);
1763 if ($days > 0 || $hours > 0 || $minutes > 0) {
1764 $seconds -= $minutes * 60;
1766 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1770 * Takes a string and outputs each character on a line for itself. Used
1771 * mainly for horizontalflipped display mode.
1772 * Takes care of special html-characters.
1773 * Fulfills todo-item
1774 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1776 * @todo add a multibyte safe function PMA_STR_split()
1777 * @uses strlen
1778 * @param string The string
1779 * @param string The Separator (defaults to "<br />\n")
1781 * @access public
1782 * @author Garvin Hicking <me@supergarv.de>
1783 * @return string The flipped string
1785 function PMA_flipstring($string, $Separator = "<br />\n")
1787 $format_string = '';
1788 $charbuff = false;
1790 for ($i = 0; $i < strlen($string); $i++) {
1791 $char = $string{$i};
1792 $append = false;
1794 if ($char == '&') {
1795 $format_string .= $charbuff;
1796 $charbuff = $char;
1797 $append = true;
1798 } elseif (!empty($charbuff)) {
1799 $charbuff .= $char;
1800 } elseif ($char == ';' && !empty($charbuff)) {
1801 $format_string .= $charbuff;
1802 $charbuff = false;
1803 $append = true;
1804 } else {
1805 $format_string .= $char;
1806 $append = true;
1809 if ($append && ($i != strlen($string))) {
1810 $format_string .= $Separator;
1814 return $format_string;
1819 * Function added to avoid path disclosures.
1820 * Called by each script that needs parameters, it displays
1821 * an error message and, by default, stops the execution.
1823 * Not sure we could use a strMissingParameter message here,
1824 * would have to check if the error message file is always available
1826 * @todo localize error message
1827 * @todo use PMA_fatalError() if $die === true?
1828 * @uses PMA_getenv()
1829 * @uses header_meta_style.inc.php
1830 * @uses $GLOBALS['PMA_PHP_SELF']
1831 * basename
1832 * @param array The names of the parameters needed by the calling
1833 * script.
1834 * @param boolean Stop the execution?
1835 * (Set this manually to false in the calling script
1836 * until you know all needed parameters to check).
1837 * @param boolean Whether to include this list in checking for special params.
1838 * @global string path to current script
1839 * @global boolean flag whether any special variable was required
1841 * @access public
1842 * @author Marc Delisle (lem9@users.sourceforge.net)
1844 function PMA_checkParameters($params, $die = true, $request = true)
1846 global $checked_special;
1848 if (!isset($checked_special)) {
1849 $checked_special = false;
1852 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1853 $found_error = false;
1854 $error_message = '';
1856 foreach ($params as $param) {
1857 if ($request && $param != 'db' && $param != 'table') {
1858 $checked_special = true;
1861 if (!isset($GLOBALS[$param])) {
1862 $error_message .= $reported_script_name
1863 . ': Missing parameter: ' . $param
1864 . ' <a href="./Documentation.html#faqmissingparameters"'
1865 . ' target="documentation"> (FAQ 2.8)</a><br />';
1866 $found_error = true;
1869 if ($found_error) {
1871 * display html meta tags
1873 require_once './libraries/header_meta_style.inc.php';
1874 echo '</head><body><p>' . $error_message . '</p></body></html>';
1875 if ($die) {
1876 exit();
1879 } // end function
1882 * Function to generate unique condition for specified row.
1884 * @uses $GLOBALS['analyzed_sql'][0]
1885 * @uses PMA_DBI_field_flags()
1886 * @uses PMA_backquote()
1887 * @uses PMA_sqlAddslashes()
1888 * @uses stristr()
1889 * @uses bin2hex()
1890 * @uses preg_replace()
1891 * @param resource $handle current query result
1892 * @param integer $fields_cnt number of fields
1893 * @param array $fields_meta meta information about fields
1894 * @param array $row current row
1895 * @param boolean $force_unique generate condition only on pk or unique
1897 * @access public
1898 * @author Michal Cihar (michal@cihar.com) and others...
1899 * @return string calculated condition
1901 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1903 $primary_key = '';
1904 $unique_key = '';
1905 $nonprimary_condition = '';
1906 $preferred_condition = '';
1908 for ($i = 0; $i < $fields_cnt; ++$i) {
1909 $condition = '';
1910 $field_flags = PMA_DBI_field_flags($handle, $i);
1911 $meta = $fields_meta[$i];
1913 // do not use a column alias in a condition
1914 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1915 $meta->orgname = $meta->name;
1917 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1918 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1919 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1920 as $select_expr) {
1921 // need (string) === (string)
1922 // '' !== 0 but '' == 0
1923 if ((string) $select_expr['alias'] === (string) $meta->name) {
1924 $meta->orgname = $select_expr['column'];
1925 break;
1926 } // end if
1927 } // end foreach
1931 // Do not use a table alias in a condition.
1932 // Test case is:
1933 // select * from galerie x WHERE
1934 //(select count(*) from galerie y where y.datum=x.datum)>1
1936 // But orgtable is present only with mysqli extension so the
1937 // fix is only for mysqli.
1938 if (isset($meta->orgtable) && $meta->table != $meta->orgtable) {
1939 $meta->table = $meta->orgtable;
1942 // to fix the bug where float fields (primary or not)
1943 // can't be matched because of the imprecision of
1944 // floating comparison, use CONCAT
1945 // (also, the syntax "CONCAT(field) IS NULL"
1946 // that we need on the next "if" will work)
1947 if ($meta->type == 'real') {
1948 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1949 . PMA_backquote($meta->orgname) . ') ';
1950 } else {
1951 $condition = ' ' . PMA_backquote($meta->table) . '.'
1952 . PMA_backquote($meta->orgname) . ' ';
1953 } // end if... else...
1955 if (!isset($row[$i]) || is_null($row[$i])) {
1956 $condition .= 'IS NULL AND';
1957 } else {
1958 // timestamp is numeric on some MySQL 4.1
1959 if ($meta->numeric && $meta->type != 'timestamp') {
1960 $condition .= '= ' . $row[$i] . ' AND';
1961 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1962 // hexify only if this is a true not empty BLOB or a BINARY
1963 && stristr($field_flags, 'BINARY')
1964 && !empty($row[$i])) {
1965 // do not waste memory building a too big condition
1966 if (strlen($row[$i]) < 1000) {
1967 // use a CAST if possible, to avoid problems
1968 // if the field contains wildcard characters % or _
1969 $condition .= '= CAST(0x' . bin2hex($row[$i])
1970 . ' AS BINARY) AND';
1971 } else {
1972 // this blob won't be part of the final condition
1973 $condition = '';
1975 } else {
1976 $condition .= '= \''
1977 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
1980 if ($meta->primary_key > 0) {
1981 $primary_key .= $condition;
1982 } elseif ($meta->unique_key > 0) {
1983 $unique_key .= $condition;
1985 $nonprimary_condition .= $condition;
1986 } // end for
1988 // Correction University of Virginia 19991216:
1989 // prefer primary or unique keys for condition,
1990 // but use conjunction of all values if no primary key
1991 if ($primary_key) {
1992 $preferred_condition = $primary_key;
1993 } elseif ($unique_key) {
1994 $preferred_condition = $unique_key;
1995 } elseif (! $force_unique) {
1996 $preferred_condition = $nonprimary_condition;
1999 return preg_replace('|\s?AND$|', '', $preferred_condition);
2000 } // end function
2003 * Generate a button or image tag
2005 * @uses PMA_USR_BROWSER_AGENT
2006 * @uses $GLOBALS['pmaThemeImage']
2007 * @uses $GLOBALS['cfg']['PropertiesIconic']
2008 * @param string name of button element
2009 * @param string class of button element
2010 * @param string name of image element
2011 * @param string text to display
2012 * @param string image to display
2014 * @access public
2015 * @author Michal Cihar (michal@cihar.com)
2017 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2018 $image)
2020 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2021 echo ' <input type="submit" name="' . $button_name . '"'
2022 .' value="' . htmlspecialchars($text) . '"'
2023 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2024 return;
2027 /* Opera has trouble with <input type="image"> */
2028 /* IE has trouble with <button> */
2029 if (PMA_USR_BROWSER_AGENT != 'IE') {
2030 echo '<button class="' . $button_class . '" type="submit"'
2031 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2032 .' title="' . htmlspecialchars($text) . '">' . "\n"
2033 . PMA_getIcon($image, $text)
2034 .'</button>' . "\n";
2035 } else {
2036 echo '<input type="image" name="' . $image_name . '" value="'
2037 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2038 . $image . '" />'
2039 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2041 } // end function
2044 * Generate a pagination selector for browsing resultsets
2046 * @todo $url is not javascript escaped!?
2047 * @uses $GLOBALS['strPageNumber']
2048 * @uses range()
2049 * @param string URL for the JavaScript
2050 * @param string Number of rows in the pagination set
2051 * @param string current page number
2052 * @param string number of total pages
2053 * @param string If the number of pages is lower than this
2054 * variable, no pages will be omitted in
2055 * pagination
2056 * @param string How many rows at the beginning should always
2057 * be shown?
2058 * @param string How many rows at the end should always
2059 * be shown?
2060 * @param string Percentage of calculation page offsets to
2061 * hop to a next page
2062 * @param string Near the current page, how many pages should
2063 * be considered "nearby" and displayed as
2064 * well?
2065 * @param string The prompt to display (sometimes empty)
2067 * @access public
2068 * @author Garvin Hicking (pma@supergarv.de)
2070 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2071 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2072 $range = 10, $prompt = '')
2074 $increment = floor($nbTotalPage / $percent);
2075 $pageNowMinusRange = ($pageNow - $range);
2076 $pageNowPlusRange = ($pageNow + $range);
2078 $gotopage = $prompt
2079 . ' <select name="pos" onchange="goToUrl(this, \''
2080 . $url . '\');">' . "\n";
2081 if ($nbTotalPage < $showAll) {
2082 $pages = range(1, $nbTotalPage);
2083 } else {
2084 $pages = array();
2086 // Always show first X pages
2087 for ($i = 1; $i <= $sliceStart; $i++) {
2088 $pages[] = $i;
2091 // Always show last X pages
2092 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2093 $pages[] = $i;
2096 // garvin: Based on the number of results we add the specified
2097 // $percent percentage to each page number,
2098 // so that we have a representing page number every now and then to
2099 // immediately jump to specific pages.
2100 // As soon as we get near our currently chosen page ($pageNow -
2101 // $range), every page number will be shown.
2102 $i = $sliceStart;
2103 $x = $nbTotalPage - $sliceEnd;
2104 $met_boundary = false;
2105 while ($i <= $x) {
2106 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2107 // If our pageselector comes near the current page, we use 1
2108 // counter increments
2109 $i++;
2110 $met_boundary = true;
2111 } else {
2112 // We add the percentage increment to our current page to
2113 // hop to the next one in range
2114 $i += $increment;
2116 // Make sure that we do not cross our boundaries.
2117 if ($i > $pageNowMinusRange && ! $met_boundary) {
2118 $i = $pageNowMinusRange;
2122 if ($i > 0 && $i <= $x) {
2123 $pages[] = $i;
2127 // Since because of ellipsing of the current page some numbers may be double,
2128 // we unify our array:
2129 sort($pages);
2130 $pages = array_unique($pages);
2133 foreach ($pages as $i) {
2134 if ($i == $pageNow) {
2135 $selected = 'selected="selected" style="font-weight: bold"';
2136 } else {
2137 $selected = '';
2139 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2142 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2144 return $gotopage;
2145 } // end function
2149 * Generate navigation for a list
2151 * @todo use $pos from $_url_params
2152 * @uses $GLOBALS['strPageNumber']
2153 * @uses range()
2154 * @param integer number of elements in the list
2155 * @param integer current position in the list
2156 * @param array url parameters
2157 * @param string script name for form target
2158 * @param string target frame
2159 * @param integer maximum number of elements to display from the list
2161 * @access public
2163 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2165 if ($max_count < $count) {
2166 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2167 echo $GLOBALS['strPageNumber'];
2168 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2170 // Move to the beginning or to the previous page
2171 if ($pos > 0) {
2172 // loic1: patch #474210 from Gosha Sakovich - part 1
2173 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2174 $caption1 = '&lt;&lt;';
2175 $caption2 = ' &lt; ';
2176 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2177 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2178 } else {
2179 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2180 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2181 $title1 = '';
2182 $title2 = '';
2183 } // end if... else...
2184 $_url_params['pos'] = 0;
2185 echo '<a' . $title1 . ' href="' . $script
2186 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2187 . $caption1 . '</a>';
2188 $_url_params['pos'] = $pos - $max_count;
2189 echo '<a' . $title2 . ' href="' . $script
2190 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2191 . $caption2 . '</a>';
2194 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2195 echo PMA_generate_common_hidden_inputs($_url_params);
2196 echo PMA_pageselector(
2197 $script . PMA_generate_common_url($_url_params) . '&',
2198 $max_count,
2199 floor(($pos + 1) / $max_count) + 1,
2200 ceil($count / $max_count));
2201 echo '</form>';
2203 if ($pos + $max_count < $count) {
2204 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2205 $caption3 = ' &gt; ';
2206 $caption4 = '&gt;&gt;';
2207 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2208 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2209 } else {
2210 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2211 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2212 $title3 = '';
2213 $title4 = '';
2214 } // end if... else...
2215 $_url_params['pos'] = $pos + $max_count;
2216 echo '<a' . $title3 . ' href="' . $script
2217 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2218 . $caption3 . '</a>';
2219 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2220 if ($_url_params['pos'] == $count) {
2221 $_url_params['pos'] = $count - $max_count;
2223 echo '<a' . $title4 . ' href="' . $script
2224 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2225 . $caption4 . '</a>';
2227 echo "\n";
2228 if ('frame_navigation' == $frame) {
2229 echo '</div>' . "\n";
2235 * replaces %u in given path with current user name
2237 * example:
2238 * <code>
2239 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2241 * </code>
2242 * @uses $cfg['Server']['user']
2243 * @uses substr()
2244 * @uses str_replace()
2245 * @param string $dir with wildcard for user
2246 * @return string per user directory
2248 function PMA_userDir($dir)
2250 // add trailing slash
2251 if (substr($dir, -1) != '/') {
2252 $dir .= '/';
2255 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2259 * returns html code for db link to default db page
2261 * @uses $cfg['DefaultTabDatabase']
2262 * @uses $GLOBALS['db']
2263 * @uses $GLOBALS['strJumpToDB']
2264 * @uses PMA_generate_common_url()
2265 * @uses PMA_unescape_mysql_wildcards()
2266 * @uses strlen()
2267 * @uses sprintf()
2268 * @uses htmlspecialchars()
2269 * @param string $database
2270 * @return string html link to default db page
2272 function PMA_getDbLink($database = null)
2274 if (!strlen($database)) {
2275 if (!strlen($GLOBALS['db'])) {
2276 return '';
2278 $database = $GLOBALS['db'];
2279 } else {
2280 $database = PMA_unescape_mysql_wildcards($database);
2283 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2284 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2285 .htmlspecialchars($database) . '</a>';
2289 * Displays a lightbulb hint explaining a known external bug
2290 * that affects a functionality
2292 * @uses PMA_MYSQL_INT_VERSION
2293 * @uses $GLOBALS['strKnownExternalBug']
2294 * @uses PMA_showHint()
2295 * @uses sprintf()
2296 * @param string $functionality localized message explaining the func.
2297 * @param string $component 'mysql' (eventually, 'php')
2298 * @param string $minimum_version of this component
2299 * @param string $bugref bug reference for this component
2301 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2303 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2304 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2309 * Generates and echoes an HTML checkbox
2311 * @param string $html_field_name the checkbox HTML field
2312 * @param string $label
2313 * @param boolean $checked is it initially checked?
2314 * @param boolean $onclick should it submit the form on click?
2316 function PMA_generate_html_checkbox($html_field_name, $label, $checked, $onclick) {
2318 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>';
2322 * Generates and echoes a set of radio HTML fields
2324 * @uses htmlspecialchars()
2325 * @param string $html_field_name the radio HTML field
2326 * @param array $choices the choices values and labels
2327 * @param string $checked_choice the choice to check by default
2328 * @param boolean $line_break whether to add an HTML line break after a choice
2329 * @param boolean $escape_label whether to use htmlspecialchars() on label
2330 * @param string $class enclose each choice with a div of this class
2332 function PMA_generate_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2333 foreach ($choices as $choice_value => $choice_label) {
2334 if (! empty($class)) {
2335 echo '<div class="' . $class . '">';
2337 $html_field_id = $html_field_name . '_' . $choice_value;
2338 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2339 if ($choice_value == $checked_choice) {
2340 echo ' checked="checked"';
2342 echo ' />' . "\n";
2343 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2344 if ($line_break) {
2345 echo '<br />';
2347 if (! empty($class)) {
2348 echo '</div>';
2350 echo "\n";
2355 * Generates and echoes an HTML dropdown
2357 * @uses htmlspecialchars()
2358 * @param string $select_name
2359 * @param array $choices the choices values
2360 * @param string $active_choice the choice to select by default
2361 * @todo support titles
2363 function PMA_generate_html_dropdown($select_name, $choices, $active_choice)
2365 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($select_name) . '">"' . "\n";
2366 foreach ($choices as $one_choice) {
2367 $result .= '<option value="' . htmlspecialchars($one_choice) . '"';
2368 if ($one_choice == $active_choice) {
2369 $result .= ' selected="selected"';
2371 $result .= '>' . htmlspecialchars($one_choice) . '</option>' . "\n";
2373 $result .= '</select>' . "\n";
2374 echo $result;
2378 * Generates a slider effect (Mootools)
2379 * Takes care of generating the initial <div> and the link
2380 * controlling the slider; you have to generate the </div> yourself
2381 * after the sliding section.
2383 * @uses $GLOBALS['cfg']['InitialSlidersState']
2384 * @param string $id the id of the <div> on which to apply the effect
2385 * @param string $message the message to show as a link
2387 function PMA_generate_slider_effect($id, $message)
2390 <script type="text/javascript">
2391 // <![CDATA[
2392 window.addEvent('domready', function(){
2393 var status = {
2394 'true': '- ',
2395 'false': '+ '
2398 var anchor<?php echo $id; ?> = new Element('a', {
2399 'id': 'toggle_<?php echo $id; ?>',
2400 'href': '#',
2401 'events': {
2402 'click': function(){
2403 mySlide<?php echo $id; ?>.toggle();
2408 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2409 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2411 var slider_status<?php echo $id; ?> = new Element('span', {
2412 'id': 'slider_status_<?php echo $id; ?>'
2414 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2415 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2417 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2418 <?php
2419 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2421 mySlide<?php echo $id; ?>.hide();
2422 <?php
2425 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2426 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2429 $('<?php echo $id; ?>').style.display="block";
2431 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2432 //]]>
2433 </script>
2434 <noscript>
2435 <div id="<?php echo $id; ?>">
2436 </noscript>
2437 <?php
2441 * Cache information in the session
2443 * @param unknown_type $var
2444 * @param unknown_type $val
2445 * @param unknown_type $server
2446 * @return mixed
2448 function PMA_cacheExists($var, $server = 0)
2450 if (true === $server) {
2451 $server = $GLOBALS['server'];
2453 return isset($_SESSION['cache']['server_' . $server][$var]);
2457 * Cache information in the session
2459 * @param unknown_type $var
2460 * @param unknown_type $val
2461 * @param unknown_type $server
2462 * @return mixed
2464 function PMA_cacheGet($var, $server = 0)
2466 if (true === $server) {
2467 $server = $GLOBALS['server'];
2469 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2470 return $_SESSION['cache']['server_' . $server][$var];
2471 } else {
2472 return null;
2477 * Cache information in the session
2479 * @param unknown_type $var
2480 * @param unknown_type $val
2481 * @param unknown_type $server
2482 * @return mixed
2484 function PMA_cacheSet($var, $val = null, $server = 0)
2486 if (true === $server) {
2487 $server = $GLOBALS['server'];
2489 $_SESSION['cache']['server_' . $server][$var] = $val;
2493 * Converts a bit value to printable format;
2494 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2495 * function because in PHP, decbin() supports only 32 bits
2497 * @uses ceil()
2498 * @uses decbin()
2499 * @uses ord()
2500 * @uses substr()
2501 * @uses sprintf()
2502 * @param numeric $value coming from a BIT field
2503 * @param integer $length
2504 * @return string the printable value
2506 function PMA_printable_bit_value($value, $length) {
2507 $printable = '';
2508 for ($i = 0; $i < ceil($length / 8); $i++) {
2509 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2511 $printable = substr($printable, -$length);
2512 return $printable;
2516 * Extracts the various parts from a field type spec
2518 * @uses strpos()
2519 * @uses chop()
2520 * @uses substr()
2521 * @param string $fieldspec
2522 * @return array associative array containing type, spec_in_brackets
2523 * and possibly enum_set_values (another array)
2524 * @author Marc Delisle
2525 * @author Joshua Hogendorn
2527 function PMA_extractFieldSpec($fieldspec) {
2528 $first_bracket_pos = strpos($fieldspec, '(');
2529 if ($first_bracket_pos) {
2530 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strpos($fieldspec, ')') - $first_bracket_pos - 1)));
2531 // convert to lowercase just to be sure
2532 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2533 } else {
2534 $type = $fieldspec;
2535 $spec_in_brackets = '';
2538 if ('enum' == $type || 'set' == $type) {
2539 // Define our working vars
2540 $enum_set_values = array();
2541 $working = "";
2542 $in_string = false;
2543 $index = 0;
2545 // While there is another character to process
2546 while (isset($fieldspec[$index])) {
2547 // Grab the char to look at
2548 $char = $fieldspec[$index];
2550 // If it is a single quote, needs to be handled specially
2551 if ($char == "'") {
2552 // If we are not currently in a string, begin one
2553 if (! $in_string) {
2554 $in_string = true;
2555 $working = "";
2556 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2557 } else {
2558 // Check out the next character (if possible)
2559 $has_next = isset($fieldspec[$index + 1]);
2560 $next = $has_next ? $fieldspec[$index + 1] : null;
2562 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2563 if (! $has_next || $next != "'") {
2564 $enum_set_values[] = $working;
2565 $in_string = false;
2567 // Otherwise, this is a 'double quote', and can be added to the working string
2568 } elseif ($next == "'") {
2569 $working .= "'";
2570 // Skip the next char; we already know what it is
2571 $index++;
2574 // escaping of a quote?
2575 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2576 $working .= "'";
2577 $index++;
2578 // Otherwise, add it to our working string like normal
2579 } else {
2580 $working .= $char;
2582 // Increment character index
2583 $index++;
2584 } // end while
2585 } else {
2586 $enum_set_values = array();
2589 return array(
2590 'type' => $type,
2591 'spec_in_brackets' => $spec_in_brackets,
2592 'enum_set_values' => $enum_set_values
2597 * Verifies if this table's engine supports foreign keys
2599 * @uses strtoupper()
2600 * @param string $engine
2601 * @return boolean
2603 function PMA_foreignkey_supported($engine) {
2604 $engine = strtoupper($engine);
2605 if ('INNODB' == $engine || 'PBXT' == $engine) {
2606 return true;
2607 } else {
2608 return false;
2613 * Replaces some characters by a displayable equivalent
2615 * @uses str_replace()
2616 * @param string $content
2617 * @return string the content with characters replaced
2619 function PMA_replace_binary_contents($content) {
2620 $result = str_replace("\x00", '\0', $content);
2621 $result = str_replace("\x08", '\b', $result);
2622 $result = str_replace("\x0a", '\n', $result);
2623 $result = str_replace("\x0d", '\r', $result);
2624 $result = str_replace("\x1a", '\Z', $result);
2625 return $result;