BLOBstreaming support (Google Summer of Code 2008, Raj Kissu Rajandran) -- work in...
[phpmyadmin/crack.git] / libraries / common.lib.php
blob1f3ef0910e7def4293593c646839cc6f92658499
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)
359 * @return string the html link
361 * @access public
363 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
365 global $cfg;
367 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
368 return '';
371 // Fixup for newly used names:
372 $chapter = str_replace('_', '-', strtolower($chapter));
373 $link = str_replace('_', '-', strtolower($link));
375 switch ($cfg['MySQLManualType']) {
376 case 'chapters':
377 if (empty($chapter)) {
378 $chapter = 'index';
380 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
381 break;
382 case 'big':
383 $url = $cfg['MySQLManualBase'] . '#' . $link;
384 break;
385 case 'searchable':
386 if (empty($link)) {
387 $link = 'index';
389 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
390 break;
391 case 'viewable':
392 default:
393 if (empty($link)) {
394 $link = 'index';
396 $mysql = '5.0';
397 $lang = 'en';
398 if (defined('PMA_MYSQL_INT_VERSION')) {
399 if (PMA_MYSQL_INT_VERSION >= 50100) {
400 $mysql = '5.1';
401 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
402 $lang = $GLOBALS['mysql_5_1_doc_lang'];
404 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
405 $mysql = '5.0';
406 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
407 $lang = $GLOBALS['mysql_5_0_doc_lang'];
411 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
412 break;
415 if ($big_icon) {
416 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>';
417 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
418 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>';
419 } else {
420 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
422 } // end of the 'PMA_showMySQLDocu()' function
425 * returns HTML for a footnote marker and add the messsage to the footnotes
427 * @uses $GLOBALS['footnotes']
428 * @param string the error message
429 * @return string html code for a footnote marker
430 * @access public
432 function PMA_showHint($message, $bbcode = false, $type = 'notice')
434 if ($message instanceof PMA_Message) {
435 $key = $message->getHash();
436 $type = $message->getLevel();
437 } else {
438 $key = md5($message);
441 if (! isset($GLOBALS['footnotes'][$key])) {
442 $nr = count($GLOBALS['footnotes']) + 1;
443 // this is the first instance of this message
444 $instance = 1;
445 $GLOBALS['footnotes'][$key] = array(
446 'note' => $message,
447 'type' => $type,
448 'nr' => $nr,
449 'instance' => $instance
451 } else {
452 $nr = $GLOBALS['footnotes'][$key]['nr'];
453 // another instance of this message (to ensure ids are unique)
454 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
457 if ($bbcode) {
458 return '[sup]' . $nr . '[/sup]';
461 // footnotemarker used in js/tooltip.js
462 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
466 * Displays a MySQL error message in the right frame.
468 * @uses footer.inc.php
469 * @uses header.inc.php
470 * @uses $GLOBALS['sql_query']
471 * @uses $GLOBALS['strError']
472 * @uses $GLOBALS['strSQLQuery']
473 * @uses $GLOBALS['pmaThemeImage']
474 * @uses $GLOBALS['strEdit']
475 * @uses $GLOBALS['strMySQLSaid']
476 * @uses $GLOBALS['cfg']['PropertiesIconic']
477 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
478 * @uses PMA_backquote()
479 * @uses PMA_DBI_getError()
480 * @uses PMA_formatSql()
481 * @uses PMA_generate_common_hidden_inputs()
482 * @uses PMA_generate_common_url()
483 * @uses PMA_showMySQLDocu()
484 * @uses PMA_sqlAddslashes()
485 * @uses PMA_SQP_isError()
486 * @uses PMA_SQP_parse()
487 * @uses PMA_SQP_getErrorString()
488 * @uses strtolower()
489 * @uses urlencode()
490 * @uses str_replace()
491 * @uses nl2br()
492 * @uses substr()
493 * @uses preg_replace()
494 * @uses preg_match()
495 * @uses explode()
496 * @uses implode()
497 * @uses is_array()
498 * @uses function_exists()
499 * @uses htmlspecialchars()
500 * @uses trim()
501 * @uses strstr()
502 * @param string the error message
503 * @param string the sql query that failed
504 * @param boolean whether to show a "modify" link or not
505 * @param string the "back" link url (full path is not required)
506 * @param boolean EXIT the page?
508 * @global string the curent table
509 * @global string the current db
511 * @access public
513 function PMA_mysqlDie($error_message = '', $the_query = '',
514 $is_modify_link = true, $back_url = '', $exit = true)
516 global $table, $db;
519 * start http output, display html headers
521 require_once './libraries/header.inc.php';
523 if (!$error_message) {
524 $error_message = PMA_DBI_getError();
526 if (!$the_query && !empty($GLOBALS['sql_query'])) {
527 $the_query = $GLOBALS['sql_query'];
530 // --- Added to solve bug #641765
531 // Robbat2 - 12 January 2003, 9:46PM
532 // Revised, Robbat2 - 13 January 2003, 2:59PM
533 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
534 $formatted_sql = htmlspecialchars($the_query);
535 } elseif (empty($the_query) || trim($the_query) == '') {
536 $formatted_sql = '';
537 } else {
538 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
539 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
540 } else {
541 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
544 // ---
545 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
546 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
547 // if the config password is wrong, or the MySQL server does not
548 // respond, do not show the query that would reveal the
549 // username/password
550 if (!empty($the_query) && !strstr($the_query, 'connect')) {
551 // --- Added to solve bug #641765
552 // Robbat2 - 12 January 2003, 9:46PM
553 // Revised, Robbat2 - 13 January 2003, 2:59PM
554 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
555 echo PMA_SQP_getErrorString() . "\n";
556 echo '<br />' . "\n";
558 // ---
559 // modified to show me the help on sql errors (Michael Keck)
560 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
561 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
562 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
564 if ($is_modify_link) {
565 $_url_params = array(
566 'sql_query' => $the_query,
567 'show_query' => 1,
569 if (strlen($table)) {
570 $_url_params['db'] = $db;
571 $_url_params['table'] = $table;
572 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
573 } elseif (strlen($db)) {
574 $_url_params['db'] = $db;
575 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
576 } else {
577 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
580 echo $doedit_goto
581 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
582 . '</a>';
583 } // end if
584 echo ' </p>' . "\n"
585 .' <p>' . "\n"
586 .' ' . $formatted_sql . "\n"
587 .' </p>' . "\n";
588 } // end if
590 $tmp_mysql_error = ''; // for saving the original $error_message
591 if (!empty($error_message)) {
592 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
593 $error_message = htmlspecialchars($error_message);
594 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
596 // modified to show me the help on error-returns (Michael Keck)
597 // (now error-messages-server)
598 echo '<p>' . "\n"
599 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
600 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
601 . "\n"
602 . '</p>' . "\n";
604 // The error message will be displayed within a CODE segment.
605 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
607 // Replace all non-single blanks with their HTML-counterpart
608 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
609 // Replace TAB-characters with their HTML-counterpart
610 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
611 // Replace linebreaks
612 $error_message = nl2br($error_message);
614 echo '<code>' . "\n"
615 . $error_message . "\n"
616 . '</code><br />' . "\n";
617 echo '</div>';
619 if ($exit) {
620 if (! empty($back_url)) {
621 if (strstr($back_url, '?')) {
622 $back_url .= '&amp;no_history=true';
623 } else {
624 $back_url .= '?no_history=true';
626 echo '<fieldset class="tblFooters">';
627 echo '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
628 echo '</fieldset>' . "\n\n";
631 * display footer and exit
633 require_once './libraries/footer.inc.php';
635 } // end of the 'PMA_mysqlDie()' function
638 * Send HTTP header, taking IIS limits into account (600 seems ok)
640 * @uses PMA_IS_IIS
641 * @uses PMA_COMING_FROM_COOKIE_LOGIN
642 * @uses PMA_get_arg_separator()
643 * @uses SID
644 * @uses strlen()
645 * @uses strpos()
646 * @uses header()
647 * @uses session_write_close()
648 * @uses headers_sent()
649 * @uses function_exists()
650 * @uses debug_print_backtrace()
651 * @uses trigger_error()
652 * @uses defined()
653 * @param string $uri the header to send
654 * @return boolean always true
656 function PMA_sendHeaderLocation($uri)
658 if (PMA_IS_IIS && strlen($uri) > 600) {
660 echo '<html><head><title>- - -</title>' . "\n";
661 echo '<meta http-equiv="expires" content="0">' . "\n";
662 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
663 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
664 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
665 echo '<script type="text/javascript">' . "\n";
666 echo '//<![CDATA[' . "\n";
667 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
668 echo '//]]>' . "\n";
669 echo '</script>' . "\n";
670 echo '</head>' . "\n";
671 echo '<body>' . "\n";
672 echo '<script type="text/javascript">' . "\n";
673 echo '//<![CDATA[' . "\n";
674 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
675 echo '//]]>' . "\n";
676 echo '</script></body></html>' . "\n";
678 } else {
679 if (SID) {
680 if (strpos($uri, '?') === false) {
681 header('Location: ' . $uri . '?' . SID);
682 } else {
683 $separator = PMA_get_arg_separator();
684 header('Location: ' . $uri . $separator . SID);
686 } else {
687 session_write_close();
688 if (headers_sent()) {
689 if (function_exists('debug_print_backtrace')) {
690 echo '<pre>';
691 debug_print_backtrace();
692 echo '</pre>';
694 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
696 // bug #1523784: IE6 does not like 'Refresh: 0', it
697 // results in a blank page
698 // but we need it when coming from the cookie login panel)
699 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
700 header('Refresh: 0; ' . $uri);
701 } else {
702 header('Location: ' . $uri);
709 * returns array with tables of given db with extended information and grouped
711 * @uses $cfg['LeftFrameTableSeparator']
712 * @uses $cfg['LeftFrameTableLevel']
713 * @uses $cfg['ShowTooltipAliasTB']
714 * @uses $cfg['NaturalOrder']
715 * @uses PMA_backquote()
716 * @uses count()
717 * @uses array_merge
718 * @uses uksort()
719 * @uses strstr()
720 * @uses explode()
721 * @param string $db name of db
722 * @param string $tables name of tables
723 * @param integer $limit_offset list offset
724 * @param integer $limit_count max tables to return
725 * return array (recursive) grouped table list
727 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
729 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
731 if (null === $tables) {
732 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
733 if ($GLOBALS['cfg']['NaturalOrder']) {
734 uksort($tables, 'strnatcasecmp');
738 if (count($tables) < 1) {
739 return $tables;
742 $default = array(
743 'Name' => '',
744 'Rows' => 0,
745 'Comment' => '',
746 'disp_name' => '',
749 $table_groups = array();
751 // for blobstreaming - list of blobstreaming tables - rajk
753 // load PMA configuration
754 $PMA_Config = $_SESSION['PMA_Config'];
756 // if PMA configuration exists
757 if (!empty($PMA_Config))
758 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
760 foreach ($tables as $table_name => $table) {
761 // if BS tables exist
762 if (isset($session_bs_tables))
763 // compare table name to tables in list of blobstreaming tables
764 foreach ($session_bs_tables as $table_key=>$table_val)
765 // if table is in list, skip outer foreach loop
766 if ($table_name == $table_key)
767 continue 2;
769 // check for correct row count
770 if (null === $table['Rows']) {
771 // Do not check exact row count here,
772 // if row count is invalid possibly the table is defect
773 // and this would break left frame;
774 // but we can check row count if this is a view,
775 // since PMA_Table::countRecords() returns a limited row count
776 // in this case.
778 // set this because PMA_Table::countRecords() can use it
779 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
781 if ($tbl_is_view) {
782 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
783 $return = true);
787 // in $group we save the reference to the place in $table_groups
788 // where to store the table info
789 if ($GLOBALS['cfg']['LeftFrameDBTree']
790 && $sep && strstr($table_name, $sep))
792 $parts = explode($sep, $table_name);
794 $group =& $table_groups;
795 $i = 0;
796 $group_name_full = '';
797 while ($i < count($parts) - 1
798 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
799 $group_name = $parts[$i] . $sep;
800 $group_name_full .= $group_name;
802 if (!isset($group[$group_name])) {
803 $group[$group_name] = array();
804 $group[$group_name]['is' . $sep . 'group'] = true;
805 $group[$group_name]['tab' . $sep . 'count'] = 1;
806 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
807 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
808 $table = $group[$group_name];
809 $group[$group_name] = array();
810 $group[$group_name][$group_name] = $table;
811 unset($table);
812 $group[$group_name]['is' . $sep . 'group'] = true;
813 $group[$group_name]['tab' . $sep . 'count'] = 1;
814 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
815 } else {
816 $group[$group_name]['tab' . $sep . 'count']++;
818 $group =& $group[$group_name];
819 $i++;
821 } else {
822 if (!isset($table_groups[$table_name])) {
823 $table_groups[$table_name] = array();
825 $group =& $table_groups;
829 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
830 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
831 // switch tooltip and name
832 $table['Comment'] = $table['Name'];
833 $table['disp_name'] = $table['Comment'];
834 } else {
835 $table['disp_name'] = $table['Name'];
838 $group[$table_name] = array_merge($default, $table);
841 return $table_groups;
844 /* ----------------------- Set of misc functions ----------------------- */
848 * Adds backquotes on both sides of a database, table or field name.
849 * and escapes backquotes inside the name with another backquote
851 * example:
852 * <code>
853 * echo PMA_backquote('owner`s db'); // `owner``s db`
855 * </code>
857 * @uses PMA_backquote()
858 * @uses is_array()
859 * @uses strlen()
860 * @uses str_replace()
861 * @param mixed $a_name the database, table or field name to "backquote"
862 * or array of it
863 * @param boolean $do_it a flag to bypass this function (used by dump
864 * functions)
865 * @return mixed the "backquoted" database, table or field name if the
866 * current MySQL release is >= 3.23.6, the original one
867 * else
868 * @access public
870 function PMA_backquote($a_name, $do_it = true)
872 if (! $do_it) {
873 return $a_name;
876 if (is_array($a_name)) {
877 $result = array();
878 foreach ($a_name as $key => $val) {
879 $result[$key] = PMA_backquote($val);
881 return $result;
884 // '0' is also empty for php :-(
885 if (strlen($a_name) && $a_name !== '*') {
886 return '`' . str_replace('`', '``', $a_name) . '`';
887 } else {
888 return $a_name;
890 } // end of the 'PMA_backquote()' function
894 * Defines the <CR><LF> value depending on the user OS.
896 * @uses PMA_USR_OS
897 * @return string the <CR><LF> value to use
899 * @access public
901 function PMA_whichCrlf()
903 $the_crlf = "\n";
905 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
906 // Win case
907 if (PMA_USR_OS == 'Win') {
908 $the_crlf = "\r\n";
910 // Others
911 else {
912 $the_crlf = "\n";
915 return $the_crlf;
916 } // end of the 'PMA_whichCrlf()' function
919 * Reloads navigation if needed.
921 * @uses $GLOBALS['reload']
922 * @uses $GLOBALS['db']
923 * @uses PMA_generate_common_url()
924 * @global array configuration
926 * @access public
928 function PMA_reloadNavigation()
930 global $cfg;
932 // Reloads the navigation frame via JavaScript if required
933 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
934 // one of the reasons for a reload is when a table is dropped
935 // in this case, get rid of the table limit offset, otherwise
936 // we have a problem when dropping a table on the last page
937 // and the offset becomes greater than the total number of tables
938 unset($_SESSION['userconf']['table_limit_offset']);
939 echo "\n";
940 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
942 <script type="text/javascript">
943 //<![CDATA[
944 if (typeof(window.parent) != 'undefined'
945 && typeof(window.parent.frame_navigation) != 'undefined') {
946 window.parent.goTo('<?php echo $reload_url; ?>');
948 //]]>
949 </script>
950 <?php
951 unset($GLOBALS['reload']);
956 * displays the message and the query
957 * usually the message is the result of the query executed
959 * @param string $message the message to display
960 * @param string $sql_query the query to display
961 * @param string $type the type (level) of the message
962 * @global array the configuration array
963 * @uses $cfg
964 * @access public
966 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
968 global $cfg;
970 if (null === $sql_query) {
971 if (! empty($GLOBALS['display_query'])) {
972 $sql_query = $GLOBALS['display_query'];
973 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
974 $sql_query = $GLOBALS['unparsed_sql'];
975 } elseif (! empty($GLOBALS['sql_query'])) {
976 $sql_query = $GLOBALS['sql_query'];
977 } else {
978 $sql_query = '';
982 // Corrects the tooltip text via JS if required
983 // @todo this is REALLY the wrong place to do this - very unexpected here
984 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
985 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
986 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
987 echo "\n";
988 echo '<script type="text/javascript">' . "\n";
989 echo '//<![CDATA[' . "\n";
990 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
991 echo '//]]>' . "\n";
992 echo '</script>' . "\n";
993 } // end if ... elseif
995 // Checks if the table needs to be repaired after a TRUNCATE query.
996 // @todo what about $GLOBALS['display_query']???
997 // @todo this is REALLY the wrong place to do this - very unexpected here
998 if (strlen($GLOBALS['table'])
999 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1000 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1001 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1004 unset($tbl_status);
1006 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1008 if ($message instanceof PMA_Message) {
1009 $message->display();
1010 $type = $message->getLevel();
1011 } else {
1012 echo '<div class="' . $type . '">';
1013 echo PMA_sanitize($message);
1014 if (isset($GLOBALS['special_message'])) {
1015 echo PMA_sanitize($GLOBALS['special_message']);
1016 unset($GLOBALS['special_message']);
1018 echo '</div>';
1021 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1022 // Html format the query to be displayed
1023 // If we want to show some sql code it is easiest to create it here
1024 /* SQL-Parser-Analyzer */
1026 if (! empty($GLOBALS['show_as_php'])) {
1027 $new_line = '\\n"<br />' . "\n"
1028 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1029 $query_base = htmlspecialchars(addslashes($sql_query));
1030 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1031 } else {
1032 $query_base = $sql_query;
1035 $query_too_big = false;
1037 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1038 // when the query is large (for example an INSERT of binary
1039 // data), the parser chokes; so avoid parsing the query
1040 $query_too_big = true;
1041 $query_base = nl2br(htmlspecialchars($sql_query));
1042 } elseif (! empty($GLOBALS['parsed_sql'])
1043 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1044 // (here, use "! empty" because when deleting a bookmark,
1045 // $GLOBALS['parsed_sql'] is set but empty
1046 $parsed_sql = $GLOBALS['parsed_sql'];
1047 } else {
1048 // Parse SQL if needed
1049 $parsed_sql = PMA_SQP_parse($query_base);
1052 // Analyze it
1053 if (isset($parsed_sql)) {
1054 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1055 // Here we append the LIMIT added for navigation, to
1056 // enable its display. Adding it higher in the code
1057 // to $sql_query would create a problem when
1058 // using the Refresh or Edit links.
1060 // Only append it on SELECTs.
1063 * @todo what would be the best to do when someone hits Refresh:
1064 * use the current LIMITs ?
1067 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1068 && isset($GLOBALS['sql_limit_to_append'])) {
1069 $query_base = $analyzed_display_query[0]['section_before_limit']
1070 . "\n" . $GLOBALS['sql_limit_to_append']
1071 . $analyzed_display_query[0]['section_after_limit'];
1072 // Need to reparse query
1073 $parsed_sql = PMA_SQP_parse($query_base);
1077 if (! empty($GLOBALS['show_as_php'])) {
1078 $query_base = '$sql = "' . $query_base;
1079 } elseif (! empty($GLOBALS['validatequery'])) {
1080 $query_base = PMA_validateSQL($query_base);
1081 } elseif (isset($parsed_sql)) {
1082 $query_base = PMA_formatSql($parsed_sql, $query_base);
1085 // Prepares links that may be displayed to edit/explain the query
1086 // (don't go to default pages, we must go to the page
1087 // where the query box is available)
1089 // Basic url query part
1090 $url_params = array();
1091 if (strlen($GLOBALS['db'])) {
1092 $url_params['db'] = $GLOBALS['db'];
1093 if (strlen($GLOBALS['table'])) {
1094 $url_params['table'] = $GLOBALS['table'];
1095 $edit_link = 'tbl_sql.php';
1096 } else {
1097 $edit_link = 'db_sql.php';
1099 } else {
1100 $edit_link = 'server_sql.php';
1103 // Want to have the query explained (Mike Beck 2002-05-22)
1104 // but only explain a SELECT (that has not been explained)
1105 /* SQL-Parser-Analyzer */
1106 $explain_link = '';
1107 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1108 $explain_params = $url_params;
1109 // Detect if we are validating as well
1110 // To preserve the validate uRL data
1111 if (! empty($GLOBALS['validatequery'])) {
1112 $explain_params['validatequery'] = 1;
1115 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1116 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1117 $_message = $GLOBALS['strExplain'];
1118 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1119 $explain_params['sql_query'] = substr($sql_query, 8);
1120 $_message = $GLOBALS['strNoExplain'];
1122 if (isset($explain_params['sql_query'])) {
1123 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1124 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1126 } //show explain
1128 $url_params['sql_query'] = $sql_query;
1129 $url_params['show_query'] = 1;
1131 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1132 if ($cfg['EditInWindow'] == true) {
1133 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1134 } else {
1135 $onclick = '';
1138 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1139 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1140 } else {
1141 $edit_link = '';
1144 $url_qpart = PMA_generate_common_url($url_params);
1146 // Also we would like to get the SQL formed in some nice
1147 // php-code (Mike Beck 2002-05-22)
1148 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1149 $php_params = $url_params;
1151 if (! empty($GLOBALS['show_as_php'])) {
1152 $_message = $GLOBALS['strNoPhp'];
1153 } else {
1154 $php_params['show_as_php'] = 1;
1155 $_message = $GLOBALS['strPhp'];
1158 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1159 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1161 if (isset($GLOBALS['show_as_php'])) {
1162 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1163 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1165 } else {
1166 $php_link = '';
1167 } //show as php
1169 // Refresh query
1170 if (! empty($cfg['SQLQuery']['Refresh'])
1171 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1172 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1173 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1174 } else {
1175 $refresh_link = '';
1176 } //show as php
1178 if (! empty($cfg['SQLValidator']['use'])
1179 && ! empty($cfg['SQLQuery']['Validate'])) {
1180 $validate_params = $url_params;
1181 if (!empty($GLOBALS['validatequery'])) {
1182 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1183 } else {
1184 $validate_params['validatequery'] = 1;
1185 $validate_message = $GLOBALS['strValidateSQL'] ;
1188 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1189 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1190 } else {
1191 $validate_link = '';
1192 } //validator
1194 echo '<code class="sql">';
1195 if ($query_too_big) {
1196 echo substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1197 } else {
1198 echo $query_base;
1201 //Clean up the end of the PHP
1202 if (! empty($GLOBALS['show_as_php'])) {
1203 echo '";';
1205 echo '</code>';
1207 echo '<div class="tools">';
1208 // avoid displaying a Profiling checkbox that could
1209 // be checked, which would reexecute an INSERT, for example
1210 if (! empty($refresh_link)) {
1211 PMA_profilingCheckbox($sql_query);
1213 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1214 echo '</div>';
1216 echo '</div><br />' . "\n";
1217 } // end of the 'PMA_showMessage()' function
1220 * Verifies if current MySQL server supports profiling
1222 * @uses $_SESSION['profiling_supported'] for caching
1223 * @uses $GLOBALS['server']
1224 * @uses PMA_DBI_fetch_value()
1225 * @uses PMA_MYSQL_INT_VERSION
1226 * @uses defined()
1227 * @access public
1228 * @return boolean whether profiling is supported
1230 * @author Marc Delisle
1232 function PMA_profilingSupported()
1234 if (! PMA_cacheExists('profiling_supported', true)) {
1235 // 5.0.37 has profiling but for example, 5.1.20 does not
1236 // (avoid a trip to the server for MySQL before 5.0.37)
1237 // and do not set a constant as we might be switching servers
1238 if (defined('PMA_MYSQL_INT_VERSION')
1239 && PMA_MYSQL_INT_VERSION >= 50037
1240 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1241 PMA_cacheSet('profiling_supported', true, true);
1242 } else {
1243 PMA_cacheSet('profiling_supported', false, true);
1247 return PMA_cacheGet('profiling_supported', true);
1251 * Displays a form with the Profiling checkbox
1253 * @param string $sql_query
1254 * @access public
1256 * @author Marc Delisle
1258 function PMA_profilingCheckbox($sql_query)
1260 if (PMA_profilingSupported()) {
1261 echo '<form action="sql.php" method="post">' . "\n";
1262 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1263 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1264 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1265 PMA_generate_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1266 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1267 echo '</form>' . "\n";
1272 * Displays the results of SHOW PROFILE
1274 * @param array the results
1275 * @access public
1277 * @author Marc Delisle
1279 function PMA_profilingResults($profiling_results)
1281 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1282 echo '<table>' . "\n";
1283 echo ' <tr>' . "\n";
1284 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1285 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1286 echo ' </tr>' . "\n";
1288 foreach($profiling_results as $one_result) {
1289 echo ' <tr>' . "\n";
1290 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1291 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1293 echo '</table>' . "\n";
1294 echo '</fieldset>' . "\n";
1298 * Formats $value to byte view
1300 * @param double the value to format
1301 * @param integer the sensitiveness
1302 * @param integer the number of decimals to retain
1304 * @return array the formatted value and its unit
1306 * @access public
1308 * @author staybyte
1309 * @version 1.2 - 18 July 2002
1311 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1313 $dh = PMA_pow(10, $comma);
1314 $li = PMA_pow(10, $limes);
1315 $return_value = $value;
1316 $unit = $GLOBALS['byteUnits'][0];
1318 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1319 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1320 // use 1024.0 to avoid integer overflow on 64-bit machines
1321 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1322 $unit = $GLOBALS['byteUnits'][$d];
1323 break 1;
1324 } // end if
1325 } // end for
1327 if ($unit != $GLOBALS['byteUnits'][0]) {
1328 // if the unit is not bytes (as represented in current language)
1329 // reformat with max length of 5
1330 // 4th parameter=true means do not reformat if value < 1
1331 $return_value = PMA_formatNumber($value, 5, $comma, true);
1332 } else {
1333 // do not reformat, just handle the locale
1334 $return_value = PMA_formatNumber($value, 0);
1337 return array($return_value, $unit);
1338 } // end of the 'PMA_formatByteDown' function
1341 * Formats $value to the given length and appends SI prefixes
1342 * $comma is not substracted from the length
1343 * with a $length of 0 no truncation occurs, number is only formated
1344 * to the current locale
1346 * examples:
1347 * <code>
1348 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1349 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1350 * echo PMA_formatNumber(-0.003, 6); // -3 m
1351 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1352 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1353 * echo PMA_formatNumber(0, 6); // 0
1355 * </code>
1356 * @param double $value the value to format
1357 * @param integer $length the max length
1358 * @param integer $comma the number of decimals to retain
1359 * @param boolean $only_down do not reformat numbers below 1
1361 * @return string the formatted value and its unit
1363 * @access public
1365 * @author staybyte, sebastian mendel
1366 * @version 1.1.0 - 2005-10-27
1368 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1370 //number_format is not multibyte safe, str_replace is safe
1371 if ($length === 0) {
1372 return str_replace(array(',', '.'),
1373 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1374 number_format($value, $comma));
1377 // this units needs no translation, ISO
1378 $units = array(
1379 -8 => 'y',
1380 -7 => 'z',
1381 -6 => 'a',
1382 -5 => 'f',
1383 -4 => 'p',
1384 -3 => 'n',
1385 -2 => '&micro;',
1386 -1 => 'm',
1387 0 => ' ',
1388 1 => 'k',
1389 2 => 'M',
1390 3 => 'G',
1391 4 => 'T',
1392 5 => 'P',
1393 6 => 'E',
1394 7 => 'Z',
1395 8 => 'Y'
1398 // we need at least 3 digits to be displayed
1399 if (3 > $length + $comma) {
1400 $length = 3 - $comma;
1403 // check for negative value to retain sign
1404 if ($value < 0) {
1405 $sign = '-';
1406 $value = abs($value);
1407 } else {
1408 $sign = '';
1411 $dh = PMA_pow(10, $comma);
1412 $li = PMA_pow(10, $length);
1413 $unit = $units[0];
1415 if ($value >= 1) {
1416 for ($d = 8; $d >= 0; $d--) {
1417 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1418 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1419 $unit = $units[$d];
1420 break 1;
1421 } // end if
1422 } // end for
1423 } elseif (!$only_down && (float) $value !== 0.0) {
1424 for ($d = -8; $d <= 8; $d++) {
1425 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1426 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1427 $unit = $units[$d];
1428 break 1;
1429 } // end if
1430 } // end for
1431 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1433 //number_format is not multibyte safe, str_replace is safe
1434 $value = str_replace(array(',', '.'),
1435 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1436 number_format($value, $comma));
1438 return $sign . $value . ' ' . $unit;
1439 } // end of the 'PMA_formatNumber' function
1442 * Writes localised date
1444 * @param string the current timestamp
1446 * @return string the formatted date
1448 * @access public
1450 function PMA_localisedDate($timestamp = -1, $format = '')
1452 global $datefmt, $month, $day_of_week;
1454 if ($format == '') {
1455 $format = $datefmt;
1458 if ($timestamp == -1) {
1459 $timestamp = time();
1462 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1463 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1465 return strftime($date, $timestamp);
1466 } // end of the 'PMA_localisedDate()' function
1470 * returns a tab for tabbed navigation.
1471 * If the variables $link and $args ar left empty, an inactive tab is created
1473 * @uses $GLOBALS['PMA_PHP_SELF']
1474 * @uses $GLOBALS['strEmpty']
1475 * @uses $GLOBALS['strDrop']
1476 * @uses $GLOBALS['active_page']
1477 * @uses $GLOBALS['url_query']
1478 * @uses $cfg['MainPageIconic']
1479 * @uses $GLOBALS['pmaThemeImage']
1480 * @uses PMA_generate_common_url()
1481 * @uses E_USER_NOTICE
1482 * @uses htmlentities()
1483 * @uses urlencode()
1484 * @uses sprintf()
1485 * @uses trigger_error()
1486 * @uses array_merge()
1487 * @uses basename()
1488 * @param array $tab array with all options
1489 * @return string html code for one tab, a link if valid otherwise a span
1490 * @access public
1492 function PMA_getTab($tab)
1494 // default values
1495 $defaults = array(
1496 'text' => '',
1497 'class' => '',
1498 'active' => false,
1499 'link' => '',
1500 'sep' => '?',
1501 'attr' => '',
1502 'args' => '',
1503 'warning' => '',
1504 'fragment' => '',
1507 $tab = array_merge($defaults, $tab);
1509 // determine additionnal style-class
1510 if (empty($tab['class'])) {
1511 if ($tab['text'] == $GLOBALS['strEmpty']
1512 || $tab['text'] == $GLOBALS['strDrop']) {
1513 $tab['class'] = 'caution';
1514 } elseif (! empty($tab['active'])
1515 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1516 $tab['class'] = 'active';
1517 } elseif (empty($GLOBALS['active_page'])
1518 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1519 && empty($tab['warning'])) {
1520 $tab['class'] = 'active';
1524 if (!empty($tab['warning'])) {
1525 $tab['class'] .= ' warning';
1526 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1529 // build the link
1530 if (!empty($tab['link'])) {
1531 $tab['link'] = htmlentities($tab['link']);
1532 $tab['link'] = $tab['link'] . $tab['sep']
1533 .(empty($GLOBALS['url_query']) ?
1534 PMA_generate_common_url() : $GLOBALS['url_query']);
1535 if (! empty($tab['args'])) {
1536 foreach ($tab['args'] as $param => $value) {
1537 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1538 . urlencode($value);
1543 if (! empty($tab['fragment'])) {
1544 $tab['link'] .= $tab['fragment'];
1547 // display icon, even if iconic is disabled but the link-text is missing
1548 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1549 && isset($tab['icon'])) {
1550 // avoid generating an alt tag, because it only illustrates
1551 // the text that follows and if browser does not display
1552 // images, the text is duplicated
1553 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1554 .'%1$s" width="16" height="16" alt="" />%2$s';
1555 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1557 // check to not display an empty link-text
1558 elseif (empty($tab['text'])) {
1559 $tab['text'] = '?';
1560 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1561 E_USER_NOTICE);
1564 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1566 if (!empty($tab['link'])) {
1567 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1568 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1569 . $tab['text'] . '</a>';
1570 } else {
1571 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1572 . $tab['text'] . '</span>';
1575 $out .= '</li>';
1576 return $out;
1577 } // end of the 'PMA_getTab()' function
1580 * returns html-code for a tab navigation
1582 * @uses PMA_getTab()
1583 * @uses htmlentities()
1584 * @param array $tabs one element per tab
1585 * @param string $tag_id id used for the html-tag
1586 * @return string html-code for tab-navigation
1588 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1590 $tab_navigation =
1591 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1592 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1594 foreach ($tabs as $tab) {
1595 $tab_navigation .= PMA_getTab($tab) . "\n";
1598 $tab_navigation .=
1599 '</ul>' . "\n"
1600 .'<div class="clearfloat"></div>'
1601 .'</div>' . "\n";
1603 return $tab_navigation;
1608 * Displays a link, or a button if the link's URL is too large, to
1609 * accommodate some browsers' limitations
1611 * @param string the URL
1612 * @param string the link message
1613 * @param mixed $tag_params string: js confirmation
1614 * array: additional tag params (f.e. style="")
1615 * @param boolean $new_form we set this to false when we are already in
1616 * a form, to avoid generating nested forms
1618 * @return string the results to be echoed or saved in an array
1620 function PMA_linkOrButton($url, $message, $tag_params = array(),
1621 $new_form = true, $strip_img = false, $target = '')
1623 if (! is_array($tag_params)) {
1624 $tmp = $tag_params;
1625 $tag_params = array();
1626 if (!empty($tmp)) {
1627 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1629 unset($tmp);
1631 if (! empty($target)) {
1632 $tag_params['target'] = htmlentities($target);
1635 $tag_params_strings = array();
1636 foreach ($tag_params as $par_name => $par_value) {
1637 // htmlspecialchars() only on non javascript
1638 $par_value = substr($par_name, 0, 2) == 'on'
1639 ? $par_value
1640 : htmlspecialchars($par_value);
1641 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1644 // previously the limit was set to 2047, it seems 1000 is better
1645 if (strlen($url) <= 1000) {
1646 // no whitespace within an <a> else Safari will make it part of the link
1647 $ret = "\n" . '<a href="' . $url . '" '
1648 . implode(' ', $tag_params_strings) . '>'
1649 . $message . '</a>' . "\n";
1650 } else {
1651 // no spaces (linebreaks) at all
1652 // or after the hidden fields
1653 // IE will display them all
1655 // add class=link to submit button
1656 if (empty($tag_params['class'])) {
1657 $tag_params['class'] = 'link';
1660 // decode encoded url separators
1661 $separator = PMA_get_arg_separator();
1662 // on most places separator is still hard coded ...
1663 if ($separator !== '&') {
1664 // ... so always replace & with $separator
1665 $url = str_replace(htmlentities('&'), $separator, $url);
1666 $url = str_replace('&', $separator, $url);
1668 $url = str_replace(htmlentities($separator), $separator, $url);
1669 // end decode
1671 $url_parts = parse_url($url);
1672 $query_parts = explode($separator, $url_parts['query']);
1673 if ($new_form) {
1674 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1675 . ' method="post"' . $target . ' style="display: inline;">';
1676 $subname_open = '';
1677 $subname_close = '';
1678 $submit_name = '';
1679 } else {
1680 $query_parts[] = 'redirect=' . $url_parts['path'];
1681 if (empty($GLOBALS['subform_counter'])) {
1682 $GLOBALS['subform_counter'] = 0;
1684 $GLOBALS['subform_counter']++;
1685 $ret = '';
1686 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1687 $subname_close = ']';
1688 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1690 foreach ($query_parts as $query_pair) {
1691 list($eachvar, $eachval) = explode('=', $query_pair);
1692 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1693 . $subname_close . '" value="'
1694 . htmlspecialchars(urldecode($eachval)) . '" />';
1695 } // end while
1697 if (stristr($message, '<img')) {
1698 if ($strip_img) {
1699 $message = trim(strip_tags($message));
1700 $ret .= '<input type="submit"' . $submit_name . ' '
1701 . implode(' ', $tag_params_strings)
1702 . ' value="' . htmlspecialchars($message) . '" />';
1703 } else {
1704 $ret .= '<input type="image"' . $submit_name . ' '
1705 . implode(' ', $tag_params_strings)
1706 . ' src="' . preg_replace(
1707 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1708 . ' value="' . htmlspecialchars(
1709 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1710 $message))
1711 . '" />';
1713 } else {
1714 $message = trim(strip_tags($message));
1715 $ret .= '<input type="submit"' . $submit_name . ' '
1716 . implode(' ', $tag_params_strings)
1717 . ' value="' . htmlspecialchars($message) . '" />';
1719 if ($new_form) {
1720 $ret .= '</form>';
1722 } // end if... else...
1724 return $ret;
1725 } // end of the 'PMA_linkOrButton()' function
1729 * Returns a given timespan value in a readable format.
1731 * @uses $GLOBALS['timespanfmt']
1732 * @uses sprintf()
1733 * @uses floor()
1734 * @param int the timespan
1736 * @return string the formatted value
1738 function PMA_timespanFormat($seconds)
1740 $return_string = '';
1741 $days = floor($seconds / 86400);
1742 if ($days > 0) {
1743 $seconds -= $days * 86400;
1745 $hours = floor($seconds / 3600);
1746 if ($days > 0 || $hours > 0) {
1747 $seconds -= $hours * 3600;
1749 $minutes = floor($seconds / 60);
1750 if ($days > 0 || $hours > 0 || $minutes > 0) {
1751 $seconds -= $minutes * 60;
1753 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1757 * Takes a string and outputs each character on a line for itself. Used
1758 * mainly for horizontalflipped display mode.
1759 * Takes care of special html-characters.
1760 * Fulfills todo-item
1761 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1763 * @todo add a multibyte safe function PMA_STR_split()
1764 * @uses strlen
1765 * @param string The string
1766 * @param string The Separator (defaults to "<br />\n")
1768 * @access public
1769 * @author Garvin Hicking <me@supergarv.de>
1770 * @return string The flipped string
1772 function PMA_flipstring($string, $Separator = "<br />\n")
1774 $format_string = '';
1775 $charbuff = false;
1777 for ($i = 0; $i < strlen($string); $i++) {
1778 $char = $string{$i};
1779 $append = false;
1781 if ($char == '&') {
1782 $format_string .= $charbuff;
1783 $charbuff = $char;
1784 $append = true;
1785 } elseif (!empty($charbuff)) {
1786 $charbuff .= $char;
1787 } elseif ($char == ';' && !empty($charbuff)) {
1788 $format_string .= $charbuff;
1789 $charbuff = false;
1790 $append = true;
1791 } else {
1792 $format_string .= $char;
1793 $append = true;
1796 if ($append && ($i != strlen($string))) {
1797 $format_string .= $Separator;
1801 return $format_string;
1806 * Function added to avoid path disclosures.
1807 * Called by each script that needs parameters, it displays
1808 * an error message and, by default, stops the execution.
1810 * Not sure we could use a strMissingParameter message here,
1811 * would have to check if the error message file is always available
1813 * @todo localize error message
1814 * @todo use PMA_fatalError() if $die === true?
1815 * @uses PMA_getenv()
1816 * @uses header_meta_style.inc.php
1817 * @uses $GLOBALS['PMA_PHP_SELF']
1818 * basename
1819 * @param array The names of the parameters needed by the calling
1820 * script.
1821 * @param boolean Stop the execution?
1822 * (Set this manually to false in the calling script
1823 * until you know all needed parameters to check).
1824 * @param boolean Whether to include this list in checking for special params.
1825 * @global string path to current script
1826 * @global boolean flag whether any special variable was required
1828 * @access public
1829 * @author Marc Delisle (lem9@users.sourceforge.net)
1831 function PMA_checkParameters($params, $die = true, $request = true)
1833 global $checked_special;
1835 if (!isset($checked_special)) {
1836 $checked_special = false;
1839 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1840 $found_error = false;
1841 $error_message = '';
1843 foreach ($params as $param) {
1844 if ($request && $param != 'db' && $param != 'table') {
1845 $checked_special = true;
1848 if (!isset($GLOBALS[$param])) {
1849 $error_message .= $reported_script_name
1850 . ': Missing parameter: ' . $param
1851 . ' <a href="./Documentation.html#faqmissingparameters"'
1852 . ' target="documentation"> (FAQ 2.8)</a><br />';
1853 $found_error = true;
1856 if ($found_error) {
1858 * display html meta tags
1860 require_once './libraries/header_meta_style.inc.php';
1861 echo '</head><body><p>' . $error_message . '</p></body></html>';
1862 if ($die) {
1863 exit();
1866 } // end function
1869 * Function to generate unique condition for specified row.
1871 * @uses $GLOBALS['analyzed_sql'][0]
1872 * @uses PMA_DBI_field_flags()
1873 * @uses PMA_backquote()
1874 * @uses PMA_sqlAddslashes()
1875 * @uses stristr()
1876 * @uses bin2hex()
1877 * @uses preg_replace()
1878 * @param resource $handle current query result
1879 * @param integer $fields_cnt number of fields
1880 * @param array $fields_meta meta information about fields
1881 * @param array $row current row
1882 * @param boolean $force_unique generate condition only on pk or unique
1884 * @access public
1885 * @author Michal Cihar (michal@cihar.com) and others...
1886 * @return string calculated condition
1888 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1890 $primary_key = '';
1891 $unique_key = '';
1892 $nonprimary_condition = '';
1893 $preferred_condition = '';
1895 for ($i = 0; $i < $fields_cnt; ++$i) {
1896 $condition = '';
1897 $field_flags = PMA_DBI_field_flags($handle, $i);
1898 $meta = $fields_meta[$i];
1900 // do not use a column alias in a condition
1901 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1902 $meta->orgname = $meta->name;
1904 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1905 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1906 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1907 as $select_expr) {
1908 // need (string) === (string)
1909 // '' !== 0 but '' == 0
1910 if ((string) $select_expr['alias'] === (string) $meta->name) {
1911 $meta->orgname = $select_expr['column'];
1912 break;
1913 } // end if
1914 } // end foreach
1918 // Do not use a table alias in a condition.
1919 // Test case is:
1920 // select * from galerie x WHERE
1921 //(select count(*) from galerie y where y.datum=x.datum)>1
1923 // But orgtable is present only with mysqli extension so the
1924 // fix is only for mysqli.
1925 if (isset($meta->orgtable) && $meta->table != $meta->orgtable) {
1926 $meta->table = $meta->orgtable;
1929 // to fix the bug where float fields (primary or not)
1930 // can't be matched because of the imprecision of
1931 // floating comparison, use CONCAT
1932 // (also, the syntax "CONCAT(field) IS NULL"
1933 // that we need on the next "if" will work)
1934 if ($meta->type == 'real') {
1935 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1936 . PMA_backquote($meta->orgname) . ') ';
1937 } else {
1938 $condition = ' ' . PMA_backquote($meta->table) . '.'
1939 . PMA_backquote($meta->orgname) . ' ';
1940 } // end if... else...
1942 if (!isset($row[$i]) || is_null($row[$i])) {
1943 $condition .= 'IS NULL AND';
1944 } else {
1945 // timestamp is numeric on some MySQL 4.1
1946 if ($meta->numeric && $meta->type != 'timestamp') {
1947 $condition .= '= ' . $row[$i] . ' AND';
1948 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1949 // hexify only if this is a true not empty BLOB or a BINARY
1950 && stristr($field_flags, 'BINARY')
1951 && !empty($row[$i])) {
1952 // do not waste memory building a too big condition
1953 if (strlen($row[$i]) < 1000) {
1954 // use a CAST if possible, to avoid problems
1955 // if the field contains wildcard characters % or _
1956 $condition .= '= CAST(0x' . bin2hex($row[$i])
1957 . ' AS BINARY) AND';
1958 } else {
1959 // this blob won't be part of the final condition
1960 $condition = '';
1962 } else {
1963 $condition .= '= \''
1964 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
1967 if ($meta->primary_key > 0) {
1968 $primary_key .= $condition;
1969 } elseif ($meta->unique_key > 0) {
1970 $unique_key .= $condition;
1972 $nonprimary_condition .= $condition;
1973 } // end for
1975 // Correction University of Virginia 19991216:
1976 // prefer primary or unique keys for condition,
1977 // but use conjunction of all values if no primary key
1978 if ($primary_key) {
1979 $preferred_condition = $primary_key;
1980 } elseif ($unique_key) {
1981 $preferred_condition = $unique_key;
1982 } elseif (! $force_unique) {
1983 $preferred_condition = $nonprimary_condition;
1986 return preg_replace('|\s?AND$|', '', $preferred_condition);
1987 } // end function
1990 * Generate a button or image tag
1992 * @uses PMA_USR_BROWSER_AGENT
1993 * @uses $GLOBALS['pmaThemeImage']
1994 * @uses $GLOBALS['cfg']['PropertiesIconic']
1995 * @param string name of button element
1996 * @param string class of button element
1997 * @param string name of image element
1998 * @param string text to display
1999 * @param string image to display
2001 * @access public
2002 * @author Michal Cihar (michal@cihar.com)
2004 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2005 $image)
2007 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2008 echo ' <input type="submit" name="' . $button_name . '"'
2009 .' value="' . htmlspecialchars($text) . '"'
2010 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2011 return;
2014 /* Opera has trouble with <input type="image"> */
2015 /* IE has trouble with <button> */
2016 if (PMA_USR_BROWSER_AGENT != 'IE') {
2017 echo '<button class="' . $button_class . '" type="submit"'
2018 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2019 .' title="' . htmlspecialchars($text) . '">' . "\n"
2020 . PMA_getIcon($image, $text)
2021 .'</button>' . "\n";
2022 } else {
2023 echo '<input type="image" name="' . $image_name . '" value="'
2024 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2025 . $image . '" />'
2026 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2028 } // end function
2031 * Generate a pagination selector for browsing resultsets
2033 * @todo $url is not javascript escaped!?
2034 * @uses $GLOBALS['strPageNumber']
2035 * @uses range()
2036 * @param string URL for the JavaScript
2037 * @param string Number of rows in the pagination set
2038 * @param string current page number
2039 * @param string number of total pages
2040 * @param string If the number of pages is lower than this
2041 * variable, no pages will be omitted in
2042 * pagination
2043 * @param string How many rows at the beginning should always
2044 * be shown?
2045 * @param string How many rows at the end should always
2046 * be shown?
2047 * @param string Percentage of calculation page offsets to
2048 * hop to a next page
2049 * @param string Near the current page, how many pages should
2050 * be considered "nearby" and displayed as
2051 * well?
2052 * @param string The prompt to display (sometimes empty)
2054 * @access public
2055 * @author Garvin Hicking (pma@supergarv.de)
2057 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2058 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2059 $range = 10, $prompt = '')
2061 $increment = floor($nbTotalPage / $percent);
2062 $pageNowMinusRange = ($pageNow - $range);
2063 $pageNowPlusRange = ($pageNow + $range);
2065 $gotopage = $prompt
2066 . ' <select name="pos" onchange="goToUrl(this, \''
2067 . $url . '\');">' . "\n";
2068 if ($nbTotalPage < $showAll) {
2069 $pages = range(1, $nbTotalPage);
2070 } else {
2071 $pages = array();
2073 // Always show first X pages
2074 for ($i = 1; $i <= $sliceStart; $i++) {
2075 $pages[] = $i;
2078 // Always show last X pages
2079 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2080 $pages[] = $i;
2083 // garvin: Based on the number of results we add the specified
2084 // $percent percentage to each page number,
2085 // so that we have a representing page number every now and then to
2086 // immediately jump to specific pages.
2087 // As soon as we get near our currently chosen page ($pageNow -
2088 // $range), every page number will be shown.
2089 $i = $sliceStart;
2090 $x = $nbTotalPage - $sliceEnd;
2091 $met_boundary = false;
2092 while ($i <= $x) {
2093 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2094 // If our pageselector comes near the current page, we use 1
2095 // counter increments
2096 $i++;
2097 $met_boundary = true;
2098 } else {
2099 // We add the percentage increment to our current page to
2100 // hop to the next one in range
2101 $i += $increment;
2103 // Make sure that we do not cross our boundaries.
2104 if ($i > $pageNowMinusRange && ! $met_boundary) {
2105 $i = $pageNowMinusRange;
2109 if ($i > 0 && $i <= $x) {
2110 $pages[] = $i;
2114 // Since because of ellipsing of the current page some numbers may be double,
2115 // we unify our array:
2116 sort($pages);
2117 $pages = array_unique($pages);
2120 foreach ($pages as $i) {
2121 if ($i == $pageNow) {
2122 $selected = 'selected="selected" style="font-weight: bold"';
2123 } else {
2124 $selected = '';
2126 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2129 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2131 return $gotopage;
2132 } // end function
2136 * Generate navigation for a list
2138 * @todo use $pos from $_url_params
2139 * @uses $GLOBALS['strPageNumber']
2140 * @uses range()
2141 * @param integer number of elements in the list
2142 * @param integer current position in the list
2143 * @param array url parameters
2144 * @param string script name for form target
2145 * @param string target frame
2146 * @param integer maximum number of elements to display from the list
2148 * @access public
2150 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2152 if ($max_count < $count) {
2153 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2154 echo $GLOBALS['strPageNumber'];
2155 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2157 // Move to the beginning or to the previous page
2158 if ($pos > 0) {
2159 // loic1: patch #474210 from Gosha Sakovich - part 1
2160 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2161 $caption1 = '&lt;&lt;';
2162 $caption2 = ' &lt; ';
2163 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2164 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2165 } else {
2166 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2167 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2168 $title1 = '';
2169 $title2 = '';
2170 } // end if... else...
2171 $_url_params['pos'] = 0;
2172 echo '<a' . $title1 . ' href="' . $script
2173 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2174 . $caption1 . '</a>';
2175 $_url_params['pos'] = $pos - $max_count;
2176 echo '<a' . $title2 . ' href="' . $script
2177 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2178 . $caption2 . '</a>';
2181 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2182 echo PMA_generate_common_hidden_inputs($_url_params);
2183 echo PMA_pageselector(
2184 $script . PMA_generate_common_url($_url_params) . '&',
2185 $max_count,
2186 floor(($pos + 1) / $max_count) + 1,
2187 ceil($count / $max_count));
2188 echo '</form>';
2190 if ($pos + $max_count < $count) {
2191 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2192 $caption3 = ' &gt; ';
2193 $caption4 = '&gt;&gt;';
2194 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2195 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2196 } else {
2197 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2198 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2199 $title3 = '';
2200 $title4 = '';
2201 } // end if... else...
2202 $_url_params['pos'] = $pos + $max_count;
2203 echo '<a' . $title3 . ' href="' . $script
2204 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2205 . $caption3 . '</a>';
2206 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2207 if ($_url_params['pos'] == $count) {
2208 $_url_params['pos'] = $count - $max_count;
2210 echo '<a' . $title4 . ' href="' . $script
2211 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2212 . $caption4 . '</a>';
2214 echo "\n";
2215 if ('frame_navigation' == $frame) {
2216 echo '</div>' . "\n";
2222 * replaces %u in given path with current user name
2224 * example:
2225 * <code>
2226 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2228 * </code>
2229 * @uses $cfg['Server']['user']
2230 * @uses substr()
2231 * @uses str_replace()
2232 * @param string $dir with wildcard for user
2233 * @return string per user directory
2235 function PMA_userDir($dir)
2237 // add trailing slash
2238 if (substr($dir, -1) != '/') {
2239 $dir .= '/';
2242 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2246 * returns html code for db link to default db page
2248 * @uses $cfg['DefaultTabDatabase']
2249 * @uses $GLOBALS['db']
2250 * @uses $GLOBALS['strJumpToDB']
2251 * @uses PMA_generate_common_url()
2252 * @uses PMA_unescape_mysql_wildcards()
2253 * @uses strlen()
2254 * @uses sprintf()
2255 * @uses htmlspecialchars()
2256 * @param string $database
2257 * @return string html link to default db page
2259 function PMA_getDbLink($database = null)
2261 if (!strlen($database)) {
2262 if (!strlen($GLOBALS['db'])) {
2263 return '';
2265 $database = $GLOBALS['db'];
2266 } else {
2267 $database = PMA_unescape_mysql_wildcards($database);
2270 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2271 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2272 .htmlspecialchars($database) . '</a>';
2276 * Displays a lightbulb hint explaining a known external bug
2277 * that affects a functionality
2279 * @uses PMA_MYSQL_INT_VERSION
2280 * @uses $GLOBALS['strKnownExternalBug']
2281 * @uses PMA_showHint()
2282 * @uses sprintf()
2283 * @param string $functionality localized message explaining the func.
2284 * @param string $component 'mysql' (eventually, 'php')
2285 * @param string $minimum_version of this component
2286 * @param string $bugref bug reference for this component
2288 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2290 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2291 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2296 * Generates and echoes an HTML checkbox
2298 * @param string $html_field_name the checkbox HTML field
2299 * @param string $label
2300 * @param boolean $checked is it initially checked?
2301 * @param boolean $onclick should it submit the form on click?
2303 function PMA_generate_html_checkbox($html_field_name, $label, $checked, $onclick) {
2305 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>';
2309 * Generates and echoes a set of radio HTML fields
2311 * @uses htmlspecialchars()
2312 * @param string $html_field_name the radio HTML field
2313 * @param array $choices the choices values and labels
2314 * @param string $checked_choice the choice to check by default
2315 * @param boolean $line_break whether to add an HTML line break after a choice
2316 * @param boolean $escape_label whether to use htmlspecialchars() on label
2317 * @param string $class enclose each choice with a div of this class
2319 function PMA_generate_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2320 foreach ($choices as $choice_value => $choice_label) {
2321 if (! empty($class)) {
2322 echo '<div class="' . $class . '">';
2324 $html_field_id = $html_field_name . '_' . $choice_value;
2325 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2326 if ($choice_value == $checked_choice) {
2327 echo ' checked="checked"';
2329 echo ' />' . "\n";
2330 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2331 if ($line_break) {
2332 echo '<br />';
2334 if (! empty($class)) {
2335 echo '</div>';
2337 echo "\n";
2342 * Generates and echoes an HTML dropdown
2344 * @uses htmlspecialchars()
2345 * @param string $select_name
2346 * @param array $choices the choices values
2347 * @param string $active_choice the choice to select by default
2348 * @todo support titles
2350 function PMA_generate_html_dropdown($select_name, $choices, $active_choice)
2352 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($select_name) . '">"' . "\n";
2353 foreach ($choices as $one_choice) {
2354 $result .= '<option value="' . htmlspecialchars($one_choice) . '"';
2355 if ($one_choice == $active_choice) {
2356 $result .= ' selected="selected"';
2358 $result .= '>' . htmlspecialchars($one_choice) . '</option>' . "\n";
2360 $result .= '</select>' . "\n";
2361 echo $result;
2365 * Generates a slider effect (Mootools)
2366 * Takes care of generating the initial <div> and the link
2367 * controlling the slider; you have to generate the </div> yourself
2368 * after the sliding section.
2370 * @uses $GLOBALS['cfg']['InitialSlidersState']
2371 * @param string $id the id of the <div> on which to apply the effect
2372 * @param string $message the message to show as a link
2374 function PMA_generate_slider_effect($id, $message)
2377 <script type="text/javascript">
2378 // <![CDATA[
2379 window.addEvent('domready', function(){
2380 var status = {
2381 'true': '- ',
2382 'false': '+ '
2385 var anchor<?php echo $id; ?> = new Element('a', {
2386 'id': 'toggle_<?php echo $id; ?>',
2387 'href': '#',
2388 'events': {
2389 'click': function(){
2390 mySlide<?php echo $id; ?>.toggle();
2395 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2396 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2398 var slider_status<?php echo $id; ?> = new Element('span', {
2399 'id': 'slider_status_<?php echo $id; ?>'
2401 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2402 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2404 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2405 <?php
2406 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2408 mySlide<?php echo $id; ?>.hide();
2409 <?php
2412 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2413 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2416 $('<?php echo $id; ?>').style.display="block";
2418 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2419 //]]>
2420 </script>
2421 <noscript>
2422 <div id="<?php echo $id; ?>">
2423 </noscript>
2424 <?php
2428 * Cache information in the session
2430 * @param unknown_type $var
2431 * @param unknown_type $val
2432 * @param unknown_type $server
2433 * @return mixed
2435 function PMA_cacheExists($var, $server = 0)
2437 if (true === $server) {
2438 $server = $GLOBALS['server'];
2440 return isset($_SESSION['cache']['server_' . $server][$var]);
2444 * Cache information in the session
2446 * @param unknown_type $var
2447 * @param unknown_type $val
2448 * @param unknown_type $server
2449 * @return mixed
2451 function PMA_cacheGet($var, $server = 0)
2453 if (true === $server) {
2454 $server = $GLOBALS['server'];
2456 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2457 return $_SESSION['cache']['server_' . $server][$var];
2458 } else {
2459 return null;
2464 * Cache information in the session
2466 * @param unknown_type $var
2467 * @param unknown_type $val
2468 * @param unknown_type $server
2469 * @return mixed
2471 function PMA_cacheSet($var, $val = null, $server = 0)
2473 if (true === $server) {
2474 $server = $GLOBALS['server'];
2476 $_SESSION['cache']['server_' . $server][$var] = $val;
2480 * Converts a bit value to printable format;
2481 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2482 * function because in PHP, decbin() supports only 32 bits
2484 * @uses ceil()
2485 * @uses decbin()
2486 * @uses ord()
2487 * @uses substr()
2488 * @uses sprintf()
2489 * @param numeric $value coming from a BIT field
2490 * @param integer $length
2491 * @return string the printable value
2493 function PMA_printable_bit_value($value, $length) {
2494 $printable = '';
2495 for ($i = 0; $i < ceil($length / 8); $i++) {
2496 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2498 $printable = substr($printable, -$length);
2499 return $printable;
2503 * Extracts the various parts from a field type spec
2505 * @uses strpos()
2506 * @uses chop()
2507 * @uses substr()
2508 * @param string $fieldspec
2509 * @return array associative array containing type, spec_in_brackets
2510 * and possibly enum_set_values (another array)
2511 * @author Marc Delisle
2512 * @author Joshua Hogendorn
2514 function PMA_extractFieldSpec($fieldspec) {
2515 $first_bracket_pos = strpos($fieldspec, '(');
2516 if ($first_bracket_pos) {
2517 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strpos($fieldspec, ')') - $first_bracket_pos - 1)));
2518 // convert to lowercase just to be sure
2519 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2520 } else {
2521 $type = $fieldspec;
2522 $spec_in_brackets = '';
2525 if ('enum' == $type || 'set' == $type) {
2526 // Define our working vars
2527 $enum_set_values = array();
2528 $working = "";
2529 $in_string = false;
2530 $index = 0;
2532 // While there is another character to process
2533 while (isset($fieldspec[$index])) {
2534 // Grab the char to look at
2535 $char = $fieldspec[$index];
2537 // If it is a single quote, needs to be handled specially
2538 if ($char == "'") {
2539 // If we are not currently in a string, begin one
2540 if (! $in_string) {
2541 $in_string = true;
2542 $working = "";
2543 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2544 } else {
2545 // Check out the next character (if possible)
2546 $has_next = isset($fieldspec[$index + 1]);
2547 $next = $has_next ? $fieldspec[$index + 1] : null;
2549 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2550 if (! $has_next || $next != "'") {
2551 $enum_set_values[] = $working;
2552 $in_string = false;
2554 // Otherwise, this is a 'double quote', and can be added to the working string
2555 } elseif ($next == "'") {
2556 $working .= "'";
2557 // Skip the next char; we already know what it is
2558 $index++;
2561 // escaping of a quote?
2562 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2563 $working .= "'";
2564 $index++;
2565 // Otherwise, add it to our working string like normal
2566 } else {
2567 $working .= $char;
2569 // Increment character index
2570 $index++;
2571 } // end while
2572 } else {
2573 $enum_set_values = array();
2576 return array(
2577 'type' => $type,
2578 'spec_in_brackets' => $spec_in_brackets,
2579 'enum_set_values' => $enum_set_values
2584 * Verifies if this table's engine supports foreign keys
2586 * @uses strtoupper()
2587 * @param string $engine
2588 * @return boolean
2590 function PMA_foreignkey_supported($engine) {
2591 $engine = strtoupper($engine);
2592 if ('INNODB' == $engine || 'PBXT' == $engine) {
2593 return true;
2594 } else {
2595 return false;
2600 * Replaces some characters by a displayable equivalent
2602 * @uses str_replace()
2603 * @param string $content
2604 * @return string the content with characters replaced
2606 function PMA_replace_binary_contents($content) {
2607 $result = str_replace("\x00", '\0', $content);
2608 $result = str_replace("\x08", '\b', $result);
2609 $result = str_replace("\x0a", '\n', $result);
2610 $result = str_replace("\x0d", '\r', $result);
2611 $result = str_replace("\x1a", '\Z', $result);
2612 return $result;