Fix for the Open in New Window in Patient/Client->Patients search gui, take 2.
[openemr.git] / phpmyadmin / libraries / common.lib.php
blob626bbe386ed0b8ea88c69b3860c8c42092d8fe07
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 * @param $icon name of icon
72 * @return html img tag
74 function PMA_getIcon($icon, $alternate = '')
76 if ($GLOBALS['cfg']['PropertiesIconic']) {
77 return '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
78 . ' title="' . $alternate . '" alt="' . $alternate . '"'
79 . ' class="icon" width="16" height="16" />';
80 } else {
81 return $alternate;
85 /**
86 * Displays the maximum size for an upload
88 * @uses $GLOBALS['strMaximumSize']
89 * @uses PMA_formatByteDown()
90 * @uses sprintf()
91 * @param integer the size
93 * @return string the message
95 * @access public
97 function PMA_displayMaximumUploadSize($max_upload_size)
99 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size);
100 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
104 * Generates a hidden field which should indicate to the browser
105 * the maximum size for upload
107 * @param integer the size
109 * @return string the INPUT field
111 * @access public
113 function PMA_generateHiddenMaxFileSize($max_size)
115 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
119 * Add slashes before "'" and "\" characters so a value containing them can
120 * be used in a sql comparison.
122 * @uses str_replace()
123 * @param string the string to slash
124 * @param boolean whether the string will be used in a 'LIKE' clause
125 * (it then requires two more escaped sequences) or not
126 * @param boolean whether to treat cr/lfs as escape-worthy entities
127 * (converts \n to \\n, \r to \\r)
129 * @param boolean whether this function is used as part of the
130 * "Create PHP code" dialog
132 * @return string the slashed string
134 * @access public
136 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
138 if ($is_like) {
139 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
140 } else {
141 $a_string = str_replace('\\', '\\\\', $a_string);
144 if ($crlf) {
145 $a_string = str_replace("\n", '\n', $a_string);
146 $a_string = str_replace("\r", '\r', $a_string);
147 $a_string = str_replace("\t", '\t', $a_string);
150 if ($php_code) {
151 $a_string = str_replace('\'', '\\\'', $a_string);
152 } else {
153 $a_string = str_replace('\'', '\'\'', $a_string);
156 return $a_string;
157 } // end of the 'PMA_sqlAddslashes()' function
161 * Add slashes before "_" and "%" characters for using them in MySQL
162 * database, table and field names.
163 * Note: This function does not escape backslashes!
165 * @uses str_replace()
166 * @param string the string to escape
168 * @return string the escaped string
170 * @access public
172 function PMA_escape_mysql_wildcards($name)
174 $name = str_replace('_', '\\_', $name);
175 $name = str_replace('%', '\\%', $name);
177 return $name;
178 } // end of the 'PMA_escape_mysql_wildcards()' function
181 * removes slashes before "_" and "%" characters
182 * Note: This function does not unescape backslashes!
184 * @uses str_replace()
185 * @param string $name the string to escape
186 * @return string the escaped string
187 * @access public
189 function PMA_unescape_mysql_wildcards($name)
191 $name = str_replace('\\_', '_', $name);
192 $name = str_replace('\\%', '%', $name);
194 return $name;
195 } // end of the 'PMA_unescape_mysql_wildcards()' function
198 * removes quotes (',",`) from a quoted string
200 * checks if the sting is quoted and removes this quotes
202 * @uses str_replace()
203 * @uses substr()
204 * @param string $quoted_string string to remove quotes from
205 * @param string $quote type of quote to remove
206 * @return string unqoted string
208 function PMA_unQuote($quoted_string, $quote = null)
210 $quotes = array();
212 if (null === $quote) {
213 $quotes[] = '`';
214 $quotes[] = '"';
215 $quotes[] = "'";
216 } else {
217 $quotes[] = $quote;
220 foreach ($quotes as $quote) {
221 if (substr($quoted_string, 0, 1) === $quote
222 && substr($quoted_string, -1, 1) === $quote) {
223 $unquoted_string = substr($quoted_string, 1, -1);
224 // replace escaped quotes
225 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
226 return $unquoted_string;
230 return $quoted_string;
234 * format sql strings
236 * @todo move into PMA_Sql
237 * @uses PMA_SQP_isError()
238 * @uses PMA_SQP_formatHtml()
239 * @uses PMA_SQP_formatNone()
240 * @uses is_array()
241 * @param mixed pre-parsed SQL structure
243 * @return string the formatted sql
245 * @global array the configuration array
246 * @global boolean whether the current statement is a multiple one or not
248 * @access public
250 * @author Robin Johnson <robbat2@users.sourceforge.net>
252 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
254 global $cfg;
256 // Check that we actually have a valid set of parsed data
257 // well, not quite
258 // first check for the SQL parser having hit an error
259 if (PMA_SQP_isError()) {
260 return $parsed_sql;
262 // then check for an array
263 if (!is_array($parsed_sql)) {
264 // We don't so just return the input directly
265 // This is intended to be used for when the SQL Parser is turned off
266 $formatted_sql = '<pre>' . "\n"
267 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
268 . '</pre>';
269 return $formatted_sql;
272 $formatted_sql = '';
274 switch ($cfg['SQP']['fmtType']) {
275 case 'none':
276 if ($unparsed_sql != '') {
277 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
278 } else {
279 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
281 break;
282 case 'html':
283 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
284 break;
285 case 'text':
286 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
287 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
288 break;
289 default:
290 break;
291 } // end switch
293 return $formatted_sql;
294 } // end of the "PMA_formatSql()" function
298 * Displays a link to the official MySQL documentation
300 * @uses $cfg['MySQLManualType']
301 * @uses $cfg['MySQLManualBase']
302 * @uses $cfg['ReplaceHelpImg']
303 * @uses $GLOBALS['mysql_4_1_doc_lang']
304 * @uses $GLOBALS['mysql_5_1_doc_lang']
305 * @uses $GLOBALS['mysql_5_0_doc_lang']
306 * @uses $GLOBALS['strDocu']
307 * @uses $GLOBALS['pmaThemeImage']
308 * @uses PMA_MYSQL_INT_VERSION
309 * @uses strtolower()
310 * @uses str_replace()
311 * @param string chapter of "HTML, one page per chapter" documentation
312 * @param string contains name of page/anchor that is being linked
313 * @param bool whether to use big icon (like in left frame)
315 * @return string the html link
317 * @access public
319 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
321 global $cfg;
323 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
324 return '';
327 // Fixup for newly used names:
328 $chapter = str_replace('_', '-', strtolower($chapter));
329 $link = str_replace('_', '-', strtolower($link));
331 switch ($cfg['MySQLManualType']) {
332 case 'chapters':
333 if (empty($chapter)) {
334 $chapter = 'index';
336 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
337 break;
338 case 'big':
339 $url = $cfg['MySQLManualBase'] . '#' . $link;
340 break;
341 case 'searchable':
342 if (empty($link)) {
343 $link = 'index';
345 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
346 break;
347 case 'viewable':
348 default:
349 if (empty($link)) {
350 $link = 'index';
352 $mysql = '5.0';
353 $lang = 'en';
354 if (defined('PMA_MYSQL_INT_VERSION')) {
355 if (PMA_MYSQL_INT_VERSION < 50000) {
356 $mysql = '4.1';
357 if (!empty($GLOBALS['mysql_4_1_doc_lang'])) {
358 $lang = $GLOBALS['mysql_4_1_doc_lang'];
360 } elseif (PMA_MYSQL_INT_VERSION >= 50100) {
361 $mysql = '5.1';
362 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
363 $lang = $GLOBALS['mysql_5_1_doc_lang'];
365 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
366 $mysql = '5.0';
367 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
368 $lang = $GLOBALS['mysql_5_0_doc_lang'];
372 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
373 break;
376 if ($big_icon) {
377 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>';
378 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
379 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>';
380 } else {
381 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
383 } // end of the 'PMA_showMySQLDocu()' function
386 * Displays a hint icon, on mouse over show the hint
388 * @uses $GLOBALS['pmaThemeImage']
389 * @uses PMA_jsFormat()
390 * @param string the error message
392 * @access public
394 function PMA_showHint($hint_message)
396 //return '<img class="lightbulb" src="' . $GLOBALS['pmaThemeImage'] . 'b_tipp.png" width="16" height="16" border="0" alt="' . $hint_message . '" title="' . $hint_message . '" align="middle" onclick="alert(\'' . PMA_jsFormat($hint_message, false) . '\');" />';
397 return '<img class="lightbulb" src="' . $GLOBALS['pmaThemeImage']
398 . 'b_tipp.png" width="16" height="16" alt="Tip" title="Tip" onmouseover="pmaTooltip(\''
399 . PMA_jsFormat($hint_message, false) . '\'); return false;" onmouseout="swapTooltip(\'default\'); return false;" />';
403 * Displays a MySQL error message in the right frame.
405 * @uses footer.inc.php
406 * @uses header.inc.php
407 * @uses $GLOBALS['sql_query']
408 * @uses $GLOBALS['strError']
409 * @uses $GLOBALS['strSQLQuery']
410 * @uses $GLOBALS['pmaThemeImage']
411 * @uses $GLOBALS['strEdit']
412 * @uses $GLOBALS['strMySQLSaid']
413 * @uses $GLOBALS['cfg']['PropertiesIconic']
414 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
415 * @uses PMA_backquote()
416 * @uses PMA_DBI_getError()
417 * @uses PMA_formatSql()
418 * @uses PMA_generate_common_hidden_inputs()
419 * @uses PMA_generate_common_url()
420 * @uses PMA_showMySQLDocu()
421 * @uses PMA_sqlAddslashes()
422 * @uses PMA_SQP_isError()
423 * @uses PMA_SQP_parse()
424 * @uses PMA_SQP_getErrorString()
425 * @uses strtolower()
426 * @uses urlencode()
427 * @uses str_replace()
428 * @uses nl2br()
429 * @uses substr()
430 * @uses preg_replace()
431 * @uses preg_match()
432 * @uses explode()
433 * @uses implode()
434 * @uses is_array()
435 * @uses function_exists()
436 * @uses htmlspecialchars()
437 * @uses trim()
438 * @uses strstr()
439 * @param string the error message
440 * @param string the sql query that failed
441 * @param boolean whether to show a "modify" link or not
442 * @param string the "back" link url (full path is not required)
443 * @param boolean EXIT the page?
445 * @global string the curent table
446 * @global string the current db
448 * @access public
450 function PMA_mysqlDie($error_message = '', $the_query = '',
451 $is_modify_link = true, $back_url = '', $exit = true)
453 global $table, $db;
456 * start http output, display html headers
458 require_once './libraries/header.inc.php';
460 if (!$error_message) {
461 $error_message = PMA_DBI_getError();
463 if (!$the_query && !empty($GLOBALS['sql_query'])) {
464 $the_query = $GLOBALS['sql_query'];
467 // --- Added to solve bug #641765
468 // Robbat2 - 12 January 2003, 9:46PM
469 // Revised, Robbat2 - 13 January 2003, 2:59PM
470 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
471 $formatted_sql = htmlspecialchars($the_query);
472 } elseif (empty($the_query) || trim($the_query) == '') {
473 $formatted_sql = '';
474 } else {
475 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
476 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
477 } else {
478 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
481 // ---
482 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
483 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
484 // if the config password is wrong, or the MySQL server does not
485 // respond, do not show the query that would reveal the
486 // username/password
487 if (!empty($the_query) && !strstr($the_query, 'connect')) {
488 // --- Added to solve bug #641765
489 // Robbat2 - 12 January 2003, 9:46PM
490 // Revised, Robbat2 - 13 January 2003, 2:59PM
491 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
492 echo PMA_SQP_getErrorString() . "\n";
493 echo '<br />' . "\n";
495 // ---
496 // modified to show me the help on sql errors (Michael Keck)
497 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
498 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
499 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
501 if ($is_modify_link && strlen($db)) {
502 if (strlen($table)) {
503 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($db, $table) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
504 } else {
505 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($db) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
507 if ($GLOBALS['cfg']['PropertiesIconic']) {
508 echo $doedit_goto
509 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
510 . '</a>';
511 } else {
512 echo ' ['
513 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
514 . ']' . "\n";
516 } // end if
517 echo ' </p>' . "\n"
518 .' <p>' . "\n"
519 .' ' . $formatted_sql . "\n"
520 .' </p>' . "\n";
521 } // end if
523 $tmp_mysql_error = ''; // for saving the original $error_message
524 if (!empty($error_message)) {
525 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
526 $error_message = htmlspecialchars($error_message);
527 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
529 // modified to show me the help on error-returns (Michael Keck)
530 // (now error-messages-server)
531 echo '<p>' . "\n"
532 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
533 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
534 . "\n"
535 . '</p>' . "\n";
537 // The error message will be displayed within a CODE segment.
538 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
540 // Replace all non-single blanks with their HTML-counterpart
541 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
542 // Replace TAB-characters with their HTML-counterpart
543 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
544 // Replace linebreaks
545 $error_message = nl2br($error_message);
547 echo '<code>' . "\n"
548 . $error_message . "\n"
549 . '</code><br />' . "\n";
550 echo '</div>';
551 echo '<fieldset class="tblFooters">';
553 if (!empty($back_url) && $exit) {
554 $goto_back_url='<a href="' . (strstr($back_url, '?') ? $back_url . '&amp;no_history=true' : $back_url . '?no_history=true') . '">';
555 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
557 echo ' </fieldset>' . "\n\n";
558 if ($exit) {
560 * display footer and exit
562 require_once './libraries/footer.inc.php';
564 } // end of the 'PMA_mysqlDie()' function
567 * Returns a string formatted with CONVERT ... USING
568 * if MySQL supports it
570 * @uses PMA_MYSQL_INT_VERSION
571 * @uses $GLOBALS['collation_connection']
572 * @uses explode()
573 * @param string the string itself
574 * @param string the mode: quoted or unquoted (this one by default)
576 * @return the formatted string
578 * @access private
580 function PMA_convert_using($string, $mode='unquoted', $force_utf8 = false)
582 if ($mode == 'quoted') {
583 $possible_quote = "'";
584 } else {
585 $possible_quote = "";
588 if (PMA_MYSQL_INT_VERSION >= 40100) {
589 if ($force_utf8) {
590 $charset = 'utf8';
591 $collate = ' COLLATE utf8_bin';
592 } else {
593 list($charset) = explode('_', $GLOBALS['collation_connection']);
594 $collate = '';
596 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $charset . ")" . $collate;
597 } else {
598 $converted_string = $possible_quote . $string . $possible_quote;
600 return $converted_string;
601 } // end function
604 * Send HTTP header, taking IIS limits into account (600 seems ok)
606 * @uses PMA_IS_IIS
607 * @uses PMA_COMING_FROM_COOKIE_LOGIN
608 * @uses PMA_get_arg_separator()
609 * @uses SID
610 * @uses strlen()
611 * @uses strpos()
612 * @uses header()
613 * @uses session_write_close()
614 * @uses headers_sent()
615 * @uses function_exists()
616 * @uses debug_print_backtrace()
617 * @uses trigger_error()
618 * @uses defined()
619 * @param string $uri the header to send
620 * @return boolean always true
622 function PMA_sendHeaderLocation($uri)
624 if (PMA_IS_IIS && strlen($uri) > 600) {
626 echo '<html><head><title>- - -</title>' . "\n";
627 echo '<meta http-equiv="expires" content="0">' . "\n";
628 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
629 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
630 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
631 echo '<script type="text/javascript">' . "\n";
632 echo '//<![CDATA[' . "\n";
633 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
634 echo '//]]>' . "\n";
635 echo '</script>' . "\n";
636 echo '</head>' . "\n";
637 echo '<body>' . "\n";
638 echo '<script type="text/javascript">' . "\n";
639 echo '//<![CDATA[' . "\n";
640 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
641 echo '//]]>' . "\n";
642 echo '</script></body></html>' . "\n";
644 } else {
645 if (SID) {
646 if (strpos($uri, '?') === false) {
647 header('Location: ' . $uri . '?' . SID);
648 } else {
649 $separator = PMA_get_arg_separator();
650 header('Location: ' . $uri . $separator . SID);
652 } else {
653 session_write_close();
654 if (headers_sent()) {
655 if (function_exists('debug_print_backtrace')) {
656 echo '<pre>';
657 debug_print_backtrace();
658 echo '</pre>';
660 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
662 // bug #1523784: IE6 does not like 'Refresh: 0', it
663 // results in a blank page
664 // but we need it when coming from the cookie login panel)
665 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
666 header('Refresh: 0; ' . $uri);
667 } else {
668 header('Location: ' . $uri);
675 * returns array with tables of given db with extended information and grouped
677 * @uses $cfg['LeftFrameTableSeparator']
678 * @uses $cfg['LeftFrameTableLevel']
679 * @uses $cfg['ShowTooltipAliasTB']
680 * @uses $cfg['NaturalOrder']
681 * @uses PMA_backquote()
682 * @uses count()
683 * @uses array_merge
684 * @uses uksort()
685 * @uses strstr()
686 * @uses explode()
687 * @param string $db name of db
688 * @param string $tables name of tables
689 * return array (recursive) grouped table list
691 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
693 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
695 if (null === $tables) {
696 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
697 if ($GLOBALS['cfg']['NaturalOrder']) {
698 uksort($tables, 'strnatcasecmp');
702 if (count($tables) < 1) {
703 return $tables;
706 $default = array(
707 'Name' => '',
708 'Rows' => 0,
709 'Comment' => '',
710 'disp_name' => '',
713 $table_groups = array();
715 foreach ($tables as $table_name => $table) {
717 // check for correct row count
718 if (null === $table['Rows']) {
719 // Do not check exact row count here,
720 // if row count is invalid possibly the table is defect
721 // and this would break left frame;
722 // but we can check row count if this is a view,
723 // since PMA_Table::countRecords() returns a limited row count
724 // in this case.
726 // set this because PMA_Table::countRecords() can use it
727 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
729 if ($tbl_is_view) {
730 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
731 $return = true);
735 // in $group we save the reference to the place in $table_groups
736 // where to store the table info
737 if ($GLOBALS['cfg']['LeftFrameDBTree']
738 && $sep && strstr($table_name, $sep))
740 $parts = explode($sep, $table_name);
742 $group =& $table_groups;
743 $i = 0;
744 $group_name_full = '';
745 while ($i < count($parts) - 1
746 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
747 $group_name = $parts[$i] . $sep;
748 $group_name_full .= $group_name;
750 if (!isset($group[$group_name])) {
751 $group[$group_name] = array();
752 $group[$group_name]['is' . $sep . 'group'] = true;
753 $group[$group_name]['tab' . $sep . 'count'] = 1;
754 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
755 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
756 $table = $group[$group_name];
757 $group[$group_name] = array();
758 $group[$group_name][$group_name] = $table;
759 unset($table);
760 $group[$group_name]['is' . $sep . 'group'] = true;
761 $group[$group_name]['tab' . $sep . 'count'] = 1;
762 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
763 } else {
764 $group[$group_name]['tab' . $sep . 'count']++;
766 $group =& $group[$group_name];
767 $i++;
769 } else {
770 if (!isset($table_groups[$table_name])) {
771 $table_groups[$table_name] = array();
773 $group =& $table_groups;
777 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
778 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
779 // switch tooltip and name
780 $table['Comment'] = $table['Name'];
781 $table['disp_name'] = $table['Comment'];
782 } else {
783 $table['disp_name'] = $table['Name'];
786 $group[$table_name] = array_merge($default, $table);
789 return $table_groups;
792 /* ----------------------- Set of misc functions ----------------------- */
796 * Adds backquotes on both sides of a database, table or field name.
797 * and escapes backquotes inside the name with another backquote
799 * example:
800 * <code>
801 * echo PMA_backquote('owner`s db'); // `owner``s db`
803 * </code>
805 * @uses PMA_backquote()
806 * @uses is_array()
807 * @uses strlen()
808 * @uses str_replace()
809 * @param mixed $a_name the database, table or field name to "backquote"
810 * or array of it
811 * @param boolean $do_it a flag to bypass this function (used by dump
812 * functions)
813 * @return mixed the "backquoted" database, table or field name if the
814 * current MySQL release is >= 3.23.6, the original one
815 * else
816 * @access public
818 function PMA_backquote($a_name, $do_it = true)
820 if (! $do_it) {
821 return $a_name;
824 if (is_array($a_name)) {
825 $result = array();
826 foreach ($a_name as $key => $val) {
827 $result[$key] = PMA_backquote($val);
829 return $result;
832 // '0' is also empty for php :-(
833 if (strlen($a_name) && $a_name !== '*') {
834 return '`' . str_replace('`', '``', $a_name) . '`';
835 } else {
836 return $a_name;
838 } // end of the 'PMA_backquote()' function
842 * Defines the <CR><LF> value depending on the user OS.
844 * @uses PMA_USR_OS
845 * @return string the <CR><LF> value to use
847 * @access public
849 function PMA_whichCrlf()
851 $the_crlf = "\n";
853 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
854 // Win case
855 if (PMA_USR_OS == 'Win') {
856 $the_crlf = "\r\n";
858 // Others
859 else {
860 $the_crlf = "\n";
863 return $the_crlf;
864 } // end of the 'PMA_whichCrlf()' function
867 * Reloads navigation if needed.
869 * @uses $GLOBALS['reload']
870 * @uses $GLOBALS['db']
871 * @uses PMA_generate_common_url()
872 * @global array configuration
874 * @access public
876 function PMA_reloadNavigation()
878 global $cfg;
880 // Reloads the navigation frame via JavaScript if required
881 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
882 // one of the reasons for a reload is when a table is dropped
883 // in this case, get rid of the table limit offset, otherwise
884 // we have a problem when dropping a table on the last page
885 // and the offset becomes greater than the total number of tables
886 unset($_SESSION['userconf']['table_limit_offset']);
887 echo "\n";
888 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
890 <script type="text/javascript">
891 //<![CDATA[
892 if (typeof(window.parent) != 'undefined'
893 && typeof(window.parent.frame_navigation) != 'undefined') {
894 window.parent.goTo('<?php echo $reload_url; ?>');
896 //]]>
897 </script>
898 <?php
899 unset($GLOBALS['reload']);
904 * displays the message and the query
905 * usually the message is the result of the query executed
907 * @param string $message the message to display
908 * @param string $sql_query the query to display
909 * @global array the configuration array
910 * @uses $cfg
911 * @access public
913 function PMA_showMessage($message, $sql_query = null)
915 global $cfg;
916 $query_too_big = false;
918 if (null === $sql_query) {
919 if (! empty($GLOBALS['display_query'])) {
920 $sql_query = $GLOBALS['display_query'];
921 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
922 $sql_query = $GLOBALS['unparsed_sql'];
923 } elseif (! empty($GLOBALS['sql_query'])) {
924 $sql_query = $GLOBALS['sql_query'];
925 } else {
926 $sql_query = '';
930 // Corrects the tooltip text via JS if required
931 // @todo this is REALLY the wrong place to do this - very unexpected here
932 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
933 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
934 if ($result) {
935 $tbl_status = PMA_DBI_fetch_assoc($result);
936 $tooltip = (empty($tbl_status['Comment']))
937 ? ''
938 : $tbl_status['Comment'] . ' ';
939 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
940 PMA_DBI_free_result($result);
941 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
942 echo "\n";
943 echo '<script type="text/javascript">' . "\n";
944 echo '//<![CDATA[' . "\n";
945 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
946 echo '//]]>' . "\n";
947 echo '</script>' . "\n";
948 } // end if
949 } // end if ... elseif
951 // Checks if the table needs to be repaired after a TRUNCATE query.
952 // @todo what about $GLOBALS['display_query']???
953 // @todo this is REALLY the wrong place to do this - very unexpected here
954 if (strlen($GLOBALS['table'])
955 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
956 if (!isset($tbl_status)) {
957 $result = @PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
958 if ($result) {
959 $tbl_status = PMA_DBI_fetch_assoc($result);
960 PMA_DBI_free_result($result);
963 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
964 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
967 unset($tbl_status);
968 echo '<br />' . "\n";
970 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
971 if (!empty($GLOBALS['show_error_header'])) {
972 echo '<div class="error">' . "\n";
973 echo '<h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
976 echo '<div class="notice">';
977 echo PMA_sanitize($message);
978 if (isset($GLOBALS['special_message'])) {
979 echo PMA_sanitize($GLOBALS['special_message']);
980 unset($GLOBALS['special_message']);
982 echo '</div>';
984 if (!empty($GLOBALS['show_error_header'])) {
985 echo '</div>';
988 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
989 // Basic url query part
990 $url_qpart = '?' . PMA_generate_common_url($GLOBALS['db'], $GLOBALS['table']);
992 // Html format the query to be displayed
993 // The nl2br function isn't used because its result isn't a valid
994 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
995 // If we want to show some sql code it is easiest to create it here
996 /* SQL-Parser-Analyzer */
998 if (!empty($GLOBALS['show_as_php'])) {
999 $new_line = '\'<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
1001 if (isset($new_line)) {
1002 /* SQL-Parser-Analyzer */
1003 $query_base = PMA_sqlAddslashes(htmlspecialchars($sql_query), false, false, true);
1004 /* SQL-Parser-Analyzer */
1005 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
1006 } else {
1007 $query_base = $sql_query;
1010 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1011 $query_too_big = true;
1012 $query_base = nl2br(htmlspecialchars($sql_query));
1013 unset($GLOBALS['parsed_sql']);
1016 // Parse SQL if needed
1017 // (here, use "! empty" because when deleting a bookmark,
1018 // $GLOBALS['parsed_sql'] is set but empty
1019 if (! empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1020 $parsed_sql = $GLOBALS['parsed_sql'];
1021 } else {
1022 // when the query is large (for example an INSERT of binary
1023 // data), the parser chokes; so avoid parsing the query
1024 if (! $query_too_big) {
1025 $parsed_sql = PMA_SQP_parse($query_base);
1029 // Analyze it
1030 if (isset($parsed_sql)) {
1031 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1034 // Here we append the LIMIT added for navigation, to
1035 // enable its display. Adding it higher in the code
1036 // to $sql_query would create a problem when
1037 // using the Refresh or Edit links.
1039 // Only append it on SELECTs.
1042 * @todo what would be the best to do when someone hits Refresh:
1043 * use the current LIMITs ?
1046 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1047 && isset($GLOBALS['sql_limit_to_append'])) {
1048 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1049 // Need to reparse query
1050 $parsed_sql = PMA_SQP_parse($query_base);
1053 if (!empty($GLOBALS['show_as_php'])) {
1054 $query_base = '$sql = \'' . $query_base;
1055 } elseif (!empty($GLOBALS['validatequery'])) {
1056 $query_base = PMA_validateSQL($query_base);
1057 } else {
1058 if (isset($parsed_sql)) {
1059 $query_base = PMA_formatSql($parsed_sql, $query_base);
1063 // Prepares links that may be displayed to edit/explain the query
1064 // (don't go to default pages, we must go to the page
1065 // where the query box is available)
1067 $edit_target = strlen($GLOBALS['db']) ? (strlen($GLOBALS['table']) ? 'tbl_sql.php' : 'db_sql.php') : 'server_sql.php';
1069 if (isset($cfg['SQLQuery']['Edit'])
1070 && ($cfg['SQLQuery']['Edit'] == true)
1071 && (!empty($edit_target))
1072 && ! $query_too_big) {
1074 if ($cfg['EditInWindow'] == true) {
1075 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1076 } else {
1077 $onclick = '';
1080 $edit_link = $edit_target
1081 . $url_qpart
1082 . '&amp;sql_query=' . urlencode($sql_query)
1083 . '&amp;show_query=1#querybox';
1084 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1085 } else {
1086 $edit_link = '';
1089 // Want to have the query explained (Mike Beck 2002-05-22)
1090 // but only explain a SELECT (that has not been explained)
1091 /* SQL-Parser-Analyzer */
1092 if (isset($cfg['SQLQuery']['Explain'])
1093 && $cfg['SQLQuery']['Explain'] == true
1094 && ! $query_too_big) {
1096 // Detect if we are validating as well
1097 // To preserve the validate uRL data
1098 if (!empty($GLOBALS['validatequery'])) {
1099 $explain_link_validate = '&amp;validatequery=1';
1100 } else {
1101 $explain_link_validate = '';
1104 $explain_link = 'import.php'
1105 . $url_qpart
1106 . $explain_link_validate
1107 . '&amp;sql_query=';
1109 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1110 $explain_link .= urlencode('EXPLAIN ' . $sql_query);
1111 $message = $GLOBALS['strExplain'];
1112 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1113 $explain_link .= urlencode(substr($sql_query, 8));
1114 $message = $GLOBALS['strNoExplain'];
1115 } else {
1116 $explain_link = '';
1118 if (!empty($explain_link)) {
1119 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1121 } else {
1122 $explain_link = '';
1123 } //show explain
1125 // Also we would like to get the SQL formed in some nice
1126 // php-code (Mike Beck 2002-05-22)
1127 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1128 && $cfg['SQLQuery']['ShowAsPHP'] == true
1129 && ! $query_too_big) {
1130 $php_link = 'import.php'
1131 . $url_qpart
1132 . '&amp;show_query=1'
1133 . '&amp;sql_query=' . urlencode($sql_query)
1134 . '&amp;show_as_php=';
1136 if (!empty($GLOBALS['show_as_php'])) {
1137 $php_link .= '0';
1138 $message = $GLOBALS['strNoPhp'];
1139 } else {
1140 $php_link .= '1';
1141 $message = $GLOBALS['strPhp'];
1143 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1145 if (isset($GLOBALS['show_as_php'])) {
1146 $runquery_link
1147 = 'import.php'
1148 . $url_qpart
1149 . '&amp;show_query=1'
1150 . '&amp;sql_query=' . urlencode($sql_query);
1151 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1154 } else {
1155 $php_link = '';
1156 } //show as php
1158 // Refresh query
1159 if (isset($cfg['SQLQuery']['Refresh'])
1160 && $cfg['SQLQuery']['Refresh']
1161 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1163 $refresh_link = 'import.php'
1164 . $url_qpart
1165 . '&amp;show_query=1'
1166 . '&amp;sql_query=' . urlencode($sql_query);
1167 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1168 } else {
1169 $refresh_link = '';
1170 } //show as php
1172 if (isset($cfg['SQLValidator']['use'])
1173 && $cfg['SQLValidator']['use'] == true
1174 && isset($cfg['SQLQuery']['Validate'])
1175 && $cfg['SQLQuery']['Validate'] == true) {
1176 $validate_link = 'import.php'
1177 . $url_qpart
1178 . '&amp;show_query=1'
1179 . '&amp;sql_query=' . urlencode($sql_query)
1180 . '&amp;validatequery=';
1181 if (!empty($GLOBALS['validatequery'])) {
1182 $validate_link .= '0';
1183 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1184 } else {
1185 $validate_link .= '1';
1186 $validate_message = $GLOBALS['strValidateSQL'] ;
1188 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1189 } else {
1190 $validate_link = '';
1191 } //validator
1193 // why this?
1194 //unset($sql_query);
1196 // Displays the message
1197 echo '<fieldset class="">' . "\n";
1198 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1199 echo ' <div>';
1200 // when uploading a 700 Kio binary file into a LONGBLOB,
1201 // I get a white page, strlen($query_base) is 2 x 700 Kio
1202 // so put a hard limit here (let's say 1000)
1203 if ($query_too_big) {
1204 echo ' ' . substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1205 } else {
1206 echo ' ' . $query_base;
1209 //Clean up the end of the PHP
1210 if (!empty($GLOBALS['show_as_php'])) {
1211 echo '\';';
1213 echo ' </div>';
1214 echo '</fieldset>' . "\n";
1216 if (!empty($edit_target)) {
1217 echo '<fieldset class="tblFooters">';
1218 // avoid displaying a Profiling checkbox that could
1219 // be checked, which would reexecute an INSERT, for example
1220 if (! empty($refresh_link)) {
1221 PMA_profilingCheckbox($sql_query);
1223 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1224 echo '</fieldset>';
1227 echo '</div><br />' . "\n";
1228 } // end of the 'PMA_showMessage()' function
1232 * Verifies if current MySQL server supports profiling
1234 * @access public
1235 * @return boolean whether profiling is supported
1237 * @author Marc Delisle
1239 function PMA_profilingSupported() {
1240 // 5.0.37 has profiling but for example, 5.1.20 does not
1241 // (avoid a trip to the server for MySQL before 5.0.37)
1242 // and do not set a constant as we might be switching servers
1243 if (defined('PMA_MYSQL_INT_VERSION') && PMA_MYSQL_INT_VERSION >= 50037 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1244 return true;
1245 } else {
1246 return false;
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) {
1259 if (PMA_profilingSupported()) {
1260 echo '<form action="sql.php" method="post">' . "\n";
1261 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1262 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1263 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1264 echo '<input type="checkbox" name="profiling" id="profiling"' . (isset($_SESSION['profiling']) ? ' checked="checked"' : '') . ' onclick="this.form.submit();" /><label for="profiling">' . $GLOBALS['strProfiling'] . '</label>' . "\n";
1265 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1266 echo '</form>' . "\n";
1271 * Displays the results of SHOW PROFILE
1273 * @param array the results
1274 * @access public
1276 * @author Marc Delisle
1278 function PMA_profilingResults($profiling_results) {
1279 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1280 echo '<table>' . "\n";
1281 echo ' <tr>' . "\n";
1282 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1283 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1284 echo ' </tr>' . "\n";
1286 foreach($profiling_results as $one_result) {
1287 echo ' <tr>' . "\n";
1288 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1289 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1291 echo '</table>' . "\n";
1292 echo '</fieldset>' . "\n";
1296 * Formats $value to byte view
1298 * @param double the value to format
1299 * @param integer the sensitiveness
1300 * @param integer the number of decimals to retain
1302 * @return array the formatted value and its unit
1304 * @access public
1306 * @author staybyte
1307 * @version 1.2 - 18 July 2002
1309 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1311 $dh = PMA_pow(10, $comma);
1312 $li = PMA_pow(10, $limes);
1313 $return_value = $value;
1314 $unit = $GLOBALS['byteUnits'][0];
1316 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1317 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1318 // use 1024.0 to avoid integer overflow on 64-bit machines
1319 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1320 $unit = $GLOBALS['byteUnits'][$d];
1321 break 1;
1322 } // end if
1323 } // end for
1325 if ($unit != $GLOBALS['byteUnits'][0]) {
1326 // if the unit is not bytes (as represented in current language)
1327 // reformat with max length of 5
1328 // 4th parameter=true means do not reformat if value < 1
1329 $return_value = PMA_formatNumber($value, 5, $comma, true);
1330 } else {
1331 // do not reformat, just handle the locale
1332 $return_value = PMA_formatNumber($value, 0);
1335 return array($return_value, $unit);
1336 } // end of the 'PMA_formatByteDown' function
1339 * Formats $value to the given length and appends SI prefixes
1340 * $comma is not substracted from the length
1341 * with a $length of 0 no truncation occurs, number is only formated
1342 * to the current locale
1344 * examples:
1345 * <code>
1346 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1347 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1348 * echo PMA_formatNumber(-0.003, 6); // -3 m
1349 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1350 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1351 * echo PMA_formatNumber(0, 6); // 0
1353 * </code>
1354 * @param double $value the value to format
1355 * @param integer $length the max length
1356 * @param integer $comma the number of decimals to retain
1357 * @param boolean $only_down do not reformat numbers below 1
1359 * @return string the formatted value and its unit
1361 * @access public
1363 * @author staybyte, sebastian mendel
1364 * @version 1.1.0 - 2005-10-27
1366 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1368 //number_format is not multibyte safe, str_replace is safe
1369 if ($length === 0) {
1370 return str_replace(array(',', '.'),
1371 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1372 number_format($value, $comma));
1375 // this units needs no translation, ISO
1376 $units = array(
1377 -8 => 'y',
1378 -7 => 'z',
1379 -6 => 'a',
1380 -5 => 'f',
1381 -4 => 'p',
1382 -3 => 'n',
1383 -2 => '&micro;',
1384 -1 => 'm',
1385 0 => ' ',
1386 1 => 'k',
1387 2 => 'M',
1388 3 => 'G',
1389 4 => 'T',
1390 5 => 'P',
1391 6 => 'E',
1392 7 => 'Z',
1393 8 => 'Y'
1396 // we need at least 3 digits to be displayed
1397 if (3 > $length + $comma) {
1398 $length = 3 - $comma;
1401 // check for negative value to retain sign
1402 if ($value < 0) {
1403 $sign = '-';
1404 $value = abs($value);
1405 } else {
1406 $sign = '';
1409 $dh = PMA_pow(10, $comma);
1410 $li = PMA_pow(10, $length);
1411 $unit = $units[0];
1413 if ($value >= 1) {
1414 for ($d = 8; $d >= 0; $d--) {
1415 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1416 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1417 $unit = $units[$d];
1418 break 1;
1419 } // end if
1420 } // end for
1421 } elseif (!$only_down && (float) $value !== 0.0) {
1422 for ($d = -8; $d <= 8; $d++) {
1423 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1424 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1425 $unit = $units[$d];
1426 break 1;
1427 } // end if
1428 } // end for
1429 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1431 //number_format is not multibyte safe, str_replace is safe
1432 $value = str_replace(array(',', '.'),
1433 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1434 number_format($value, $comma));
1436 return $sign . $value . ' ' . $unit;
1437 } // end of the 'PMA_formatNumber' function
1440 * Extracts ENUM / SET options from a type definition string
1442 * @param string The column type definition
1444 * @return array The options or
1445 * boolean false in case of an error.
1447 * @author rabus
1449 function PMA_getEnumSetOptions($type_def)
1451 $open = strpos($type_def, '(');
1452 $close = strrpos($type_def, ')');
1453 if (!$open || !$close) {
1454 return false;
1456 $options = substr($type_def, $open + 2, $close - $open - 3);
1457 $options = explode('\',\'', $options);
1458 return $options;
1459 } // end of the 'PMA_getEnumSetOptions' function
1462 * Writes localised date
1464 * @param string the current timestamp
1466 * @return string the formatted date
1468 * @access public
1470 function PMA_localisedDate($timestamp = -1, $format = '')
1472 global $datefmt, $month, $day_of_week;
1474 if ($format == '') {
1475 $format = $datefmt;
1478 if ($timestamp == -1) {
1479 $timestamp = time();
1482 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1483 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1485 return strftime($date, $timestamp);
1486 } // end of the 'PMA_localisedDate()' function
1490 * returns a tab for tabbed navigation.
1491 * If the variables $link and $args ar left empty, an inactive tab is created
1493 * @uses $GLOBALS['PMA_PHP_SELF']
1494 * @uses $GLOBALS['strEmpty']
1495 * @uses $GLOBALS['strDrop']
1496 * @uses $GLOBALS['active_page']
1497 * @uses $GLOBALS['url_query']
1498 * @uses $cfg['MainPageIconic']
1499 * @uses $GLOBALS['pmaThemeImage']
1500 * @uses PMA_generate_common_url()
1501 * @uses E_USER_NOTICE
1502 * @uses htmlentities()
1503 * @uses urlencode()
1504 * @uses sprintf()
1505 * @uses trigger_error()
1506 * @uses array_merge()
1507 * @uses basename()
1508 * @param array $tab array with all options
1509 * @return string html code for one tab, a link if valid otherwise a span
1510 * @access public
1512 function PMA_getTab($tab)
1514 // default values
1515 $defaults = array(
1516 'text' => '',
1517 'class' => '',
1518 'active' => false,
1519 'link' => '',
1520 'sep' => '?',
1521 'attr' => '',
1522 'args' => '',
1523 'warning' => '',
1524 'fragment' => '',
1527 $tab = array_merge($defaults, $tab);
1529 // determine additionnal style-class
1530 if (empty($tab['class'])) {
1531 if ($tab['text'] == $GLOBALS['strEmpty']
1532 || $tab['text'] == $GLOBALS['strDrop']) {
1533 $tab['class'] = 'caution';
1534 } elseif (!empty($tab['active'])
1535 || (isset($GLOBALS['active_page'])
1536 && $GLOBALS['active_page'] == $tab['link'])
1537 || (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'] && empty($tab['warning'])))
1539 $tab['class'] = 'active';
1543 if (!empty($tab['warning'])) {
1544 $tab['class'] .= ' warning';
1545 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1548 // build the link
1549 if (!empty($tab['link'])) {
1550 $tab['link'] = htmlentities($tab['link']);
1551 $tab['link'] = $tab['link'] . $tab['sep']
1552 .(empty($GLOBALS['url_query']) ?
1553 PMA_generate_common_url() : $GLOBALS['url_query']);
1554 if (!empty($tab['args'])) {
1555 foreach ($tab['args'] as $param => $value) {
1556 $tab['link'] .= '&amp;' . urlencode($param) . '='
1557 . urlencode($value);
1562 if (! empty($tab['fragment'])) {
1563 $tab['link'] .= $tab['fragment'];
1566 // display icon, even if iconic is disabled but the link-text is missing
1567 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1568 && isset($tab['icon'])) {
1569 // avoid generating an alt tag, because it only illustrates
1570 // the text that follows and if browser does not display
1571 // images, the text is duplicated
1572 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1573 .'%1$s" width="16" height="16" alt="" />%2$s';
1574 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1576 // check to not display an empty link-text
1577 elseif (empty($tab['text'])) {
1578 $tab['text'] = '?';
1579 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1580 E_USER_NOTICE);
1583 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1585 if (!empty($tab['link'])) {
1586 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1587 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1588 . $tab['text'] . '</a>';
1589 } else {
1590 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1591 . $tab['text'] . '</span>';
1594 $out .= '</li>';
1595 return $out;
1596 } // end of the 'PMA_getTab()' function
1599 * returns html-code for a tab navigation
1601 * @uses PMA_getTab()
1602 * @uses htmlentities()
1603 * @param array $tabs one element per tab
1604 * @param string $tag_id id used for the html-tag
1605 * @return string html-code for tab-navigation
1607 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1609 $tab_navigation =
1610 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1611 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1613 foreach ($tabs as $tab) {
1614 $tab_navigation .= PMA_getTab($tab) . "\n";
1617 $tab_navigation .=
1618 '</ul>' . "\n"
1619 .'<div class="clearfloat"></div>'
1620 .'</div>' . "\n";
1622 return $tab_navigation;
1627 * Displays a link, or a button if the link's URL is too large, to
1628 * accommodate some browsers' limitations
1630 * @param string the URL
1631 * @param string the link message
1632 * @param mixed $tag_params string: js confirmation
1633 * array: additional tag params (f.e. style="")
1634 * @param boolean $new_form we set this to false when we are already in
1635 * a form, to avoid generating nested forms
1637 * @return string the results to be echoed or saved in an array
1639 function PMA_linkOrButton($url, $message, $tag_params = array(),
1640 $new_form = true, $strip_img = false, $target = '')
1642 if (! is_array($tag_params)) {
1643 $tmp = $tag_params;
1644 $tag_params = array();
1645 if (!empty($tmp)) {
1646 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1648 unset($tmp);
1650 if (! empty($target)) {
1651 $tag_params['target'] = htmlentities($target);
1654 $tag_params_strings = array();
1655 foreach ($tag_params as $par_name => $par_value) {
1656 // htmlspecialchars() only on non javascript
1657 $par_value = substr($par_name, 0, 2) == 'on'
1658 ? $par_value
1659 : htmlspecialchars($par_value);
1660 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1663 // previously the limit was set to 2047, it seems 1000 is better
1664 if (strlen($url) <= 1000) {
1665 // no whitespace within an <a> else Safari will make it part of the link
1666 $ret = "\n" . '<a href="' . $url . '" '
1667 . implode(' ', $tag_params_strings) . '>'
1668 . $message . '</a>' . "\n";
1669 } else {
1670 // no spaces (linebreaks) at all
1671 // or after the hidden fields
1672 // IE will display them all
1674 // add class=link to submit button
1675 if (empty($tag_params['class'])) {
1676 $tag_params['class'] = 'link';
1679 // decode encoded url separators
1680 $separator = PMA_get_arg_separator();
1681 // on most places separator is still hard coded ...
1682 if ($separator !== '&') {
1683 // ... so always replace & with $separator
1684 $url = str_replace(htmlentities('&'), $separator, $url);
1685 $url = str_replace('&', $separator, $url);
1687 $url = str_replace(htmlentities($separator), $separator, $url);
1688 // end decode
1690 $url_parts = parse_url($url);
1691 $query_parts = explode($separator, $url_parts['query']);
1692 if ($new_form) {
1693 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1694 . ' method="post"' . $target . ' style="display: inline;">';
1695 $subname_open = '';
1696 $subname_close = '';
1697 $submit_name = '';
1698 } else {
1699 $query_parts[] = 'redirect=' . $url_parts['path'];
1700 if (empty($GLOBALS['subform_counter'])) {
1701 $GLOBALS['subform_counter'] = 0;
1703 $GLOBALS['subform_counter']++;
1704 $ret = '';
1705 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1706 $subname_close = ']';
1707 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1709 foreach ($query_parts as $query_pair) {
1710 list($eachvar, $eachval) = explode('=', $query_pair);
1711 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1712 . $subname_close . '" value="'
1713 . htmlspecialchars(urldecode($eachval)) . '" />';
1714 } // end while
1716 if (stristr($message, '<img')) {
1717 if ($strip_img) {
1718 $message = trim(strip_tags($message));
1719 $ret .= '<input type="submit"' . $submit_name . ' '
1720 . implode(' ', $tag_params_strings)
1721 . ' value="' . htmlspecialchars($message) . '" />';
1722 } else {
1723 $ret .= '<input type="image"' . $submit_name . ' '
1724 . implode(' ', $tag_params_strings)
1725 . ' src="' . preg_replace(
1726 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1727 . ' value="' . htmlspecialchars(
1728 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1729 $message))
1730 . '" />';
1732 } else {
1733 $message = trim(strip_tags($message));
1734 $ret .= '<input type="submit"' . $submit_name . ' '
1735 . implode(' ', $tag_params_strings)
1736 . ' value="' . htmlspecialchars($message) . '" />';
1738 if ($new_form) {
1739 $ret .= '</form>';
1741 } // end if... else...
1743 return $ret;
1744 } // end of the 'PMA_linkOrButton()' function
1748 * Returns a given timespan value in a readable format.
1750 * @uses $GLOBALS['timespanfmt']
1751 * @uses sprintf()
1752 * @uses floor()
1753 * @param int the timespan
1755 * @return string the formatted value
1757 function PMA_timespanFormat($seconds)
1759 $return_string = '';
1760 $days = floor($seconds / 86400);
1761 if ($days > 0) {
1762 $seconds -= $days * 86400;
1764 $hours = floor($seconds / 3600);
1765 if ($days > 0 || $hours > 0) {
1766 $seconds -= $hours * 3600;
1768 $minutes = floor($seconds / 60);
1769 if ($days > 0 || $hours > 0 || $minutes > 0) {
1770 $seconds -= $minutes * 60;
1772 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1776 * Takes a string and outputs each character on a line for itself. Used
1777 * mainly for horizontalflipped display mode.
1778 * Takes care of special html-characters.
1779 * Fulfills todo-item
1780 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1782 * @todo add a multibyte safe function PMA_STR_split()
1783 * @uses strlen
1784 * @param string The string
1785 * @param string The Separator (defaults to "<br />\n")
1787 * @access public
1788 * @author Garvin Hicking <me@supergarv.de>
1789 * @return string The flipped string
1791 function PMA_flipstring($string, $Separator = "<br />\n")
1793 $format_string = '';
1794 $charbuff = false;
1796 for ($i = 0; $i < strlen($string); $i++) {
1797 $char = $string{$i};
1798 $append = false;
1800 if ($char == '&') {
1801 $format_string .= $charbuff;
1802 $charbuff = $char;
1803 $append = true;
1804 } elseif (!empty($charbuff)) {
1805 $charbuff .= $char;
1806 } elseif ($char == ';' && !empty($charbuff)) {
1807 $format_string .= $charbuff;
1808 $charbuff = false;
1809 $append = true;
1810 } else {
1811 $format_string .= $char;
1812 $append = true;
1815 if ($append && ($i != strlen($string))) {
1816 $format_string .= $Separator;
1820 return $format_string;
1825 * Function added to avoid path disclosures.
1826 * Called by each script that needs parameters, it displays
1827 * an error message and, by default, stops the execution.
1829 * Not sure we could use a strMissingParameter message here,
1830 * would have to check if the error message file is always available
1832 * @todo localize error message
1833 * @todo use PMA_fatalError() if $die === true?
1834 * @uses PMA_getenv()
1835 * @uses header_meta_style.inc.php
1836 * @uses $GLOBALS['PMA_PHP_SELF']
1837 * basename
1838 * @param array The names of the parameters needed by the calling
1839 * script.
1840 * @param boolean Stop the execution?
1841 * (Set this manually to false in the calling script
1842 * until you know all needed parameters to check).
1843 * @param boolean Whether to include this list in checking for special params.
1844 * @global string path to current script
1845 * @global boolean flag whether any special variable was required
1847 * @access public
1848 * @author Marc Delisle (lem9@users.sourceforge.net)
1850 function PMA_checkParameters($params, $die = true, $request = true)
1852 global $checked_special;
1854 if (!isset($checked_special)) {
1855 $checked_special = false;
1858 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1859 $found_error = false;
1860 $error_message = '';
1862 foreach ($params as $param) {
1863 if ($request && $param != 'db' && $param != 'table') {
1864 $checked_special = true;
1867 if (!isset($GLOBALS[$param])) {
1868 $error_message .= $reported_script_name
1869 . ': Missing parameter: ' . $param
1870 . ' <a href="./Documentation.html#faqmissingparameters"'
1871 . ' target="documentation"> (FAQ 2.8)</a><br />';
1872 $found_error = true;
1875 if ($found_error) {
1877 * display html meta tags
1879 require_once './libraries/header_meta_style.inc.php';
1880 echo '</head><body><p>' . $error_message . '</p></body></html>';
1881 if ($die) {
1882 exit();
1885 } // end function
1888 * Function to generate unique condition for specified row.
1890 * @uses PMA_MYSQL_INT_VERSION
1891 * @uses $GLOBALS['analyzed_sql'][0]
1892 * @uses PMA_DBI_field_flags()
1893 * @uses PMA_backquote()
1894 * @uses PMA_sqlAddslashes()
1895 * @uses stristr()
1896 * @uses bin2hex()
1897 * @uses preg_replace()
1898 * @param resource $handle current query result
1899 * @param integer $fields_cnt number of fields
1900 * @param array $fields_meta meta information about fields
1901 * @param array $row current row
1902 * @param boolean $force_unique generate condition only on pk or unique
1904 * @access public
1905 * @author Michal Cihar (michal@cihar.com) and others...
1906 * @return string calculated condition
1908 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1910 $primary_key = '';
1911 $unique_key = '';
1912 $nonprimary_condition = '';
1913 $preferred_condition = '';
1915 for ($i = 0; $i < $fields_cnt; ++$i) {
1916 $condition = '';
1917 $field_flags = PMA_DBI_field_flags($handle, $i);
1918 $meta = $fields_meta[$i];
1920 // do not use a column alias in a condition
1921 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1922 $meta->orgname = $meta->name;
1924 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1925 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1926 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1927 as $select_expr) {
1928 // need (string) === (string)
1929 // '' !== 0 but '' == 0
1930 if ((string) $select_expr['alias'] === (string) $meta->name) {
1931 $meta->orgname = $select_expr['column'];
1932 break;
1933 } // end if
1934 } // end foreach
1938 // Do not use a table alias in a condition.
1939 // Test case is:
1940 // select * from galerie x WHERE
1941 //(select count(*) from galerie y where y.datum=x.datum)>1
1943 // But orgtable is present only with mysqli extension so the
1944 // fix is only for mysqli.
1945 if (isset($meta->orgtable) && $meta->table != $meta->orgtable) {
1946 $meta->table = $meta->orgtable;
1949 // to fix the bug where float fields (primary or not)
1950 // can't be matched because of the imprecision of
1951 // floating comparison, use CONCAT
1952 // (also, the syntax "CONCAT(field) IS NULL"
1953 // that we need on the next "if" will work)
1954 if ($meta->type == 'real') {
1955 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1956 . PMA_backquote($meta->orgname) . ') ';
1957 } else {
1958 // string and blob fields have to be converted using
1959 // the system character set (always utf8) since
1960 // mysql4.1 can use different charset for fields.
1961 if (PMA_MYSQL_INT_VERSION >= 40100
1962 && ($meta->type == 'string' || $meta->type == 'blob')) {
1963 $condition = ' CONVERT(' . PMA_backquote($meta->table) . '.'
1964 . PMA_backquote($meta->orgname) . ' USING utf8) ';
1965 } else {
1966 $condition = ' ' . PMA_backquote($meta->table) . '.'
1967 . PMA_backquote($meta->orgname) . ' ';
1969 } // end if... else...
1971 if (!isset($row[$i]) || is_null($row[$i])) {
1972 $condition .= 'IS NULL AND';
1973 } else {
1974 // timestamp is numeric on some MySQL 4.1
1975 if ($meta->numeric && $meta->type != 'timestamp') {
1976 $condition .= '= ' . $row[$i] . ' AND';
1977 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1978 // hexify only if this is a true not empty BLOB or a BINARY
1979 && stristr($field_flags, 'BINARY')
1980 && !empty($row[$i])) {
1981 // do not waste memory building a too big condition
1982 if (strlen($row[$i]) < 1000) {
1983 if (PMA_MYSQL_INT_VERSION < 40002) {
1984 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
1985 } else {
1986 // use a CAST if possible, to avoid problems
1987 // if the field contains wildcard characters % or _
1988 $condition .= '= CAST(0x' . bin2hex($row[$i])
1989 . ' AS BINARY) AND';
1991 } else {
1992 // this blob won't be part of the final condition
1993 $condition = '';
1995 } else {
1996 $condition .= '= \''
1997 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2000 if ($meta->primary_key > 0) {
2001 $primary_key .= $condition;
2002 } elseif ($meta->unique_key > 0) {
2003 $unique_key .= $condition;
2005 $nonprimary_condition .= $condition;
2006 } // end for
2008 // Correction University of Virginia 19991216:
2009 // prefer primary or unique keys for condition,
2010 // but use conjunction of all values if no primary key
2011 if ($primary_key) {
2012 $preferred_condition = $primary_key;
2013 } elseif ($unique_key) {
2014 $preferred_condition = $unique_key;
2015 } elseif (! $force_unique) {
2016 $preferred_condition = $nonprimary_condition;
2019 return preg_replace('|\s?AND$|', '', $preferred_condition);
2020 } // end function
2023 * Generate a button or image tag
2025 * @uses PMA_USR_BROWSER_AGENT
2026 * @uses $GLOBALS['pmaThemeImage']
2027 * @uses $GLOBALS['cfg']['PropertiesIconic']
2028 * @param string name of button element
2029 * @param string class of button element
2030 * @param string name of image element
2031 * @param string text to display
2032 * @param string image to display
2034 * @access public
2035 * @author Michal Cihar (michal@cihar.com)
2037 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2038 $image)
2040 /* Opera has trouble with <input type="image"> */
2041 /* IE has trouble with <button> */
2042 if (PMA_USR_BROWSER_AGENT != 'IE') {
2043 echo '<button class="' . $button_class . '" type="submit"'
2044 .' name="' . $button_name . '" value="' . $text . '"'
2045 .' title="' . $text . '">' . "\n"
2046 .'<img class="icon" src="' . $GLOBALS['pmaThemeImage'] . $image . '"'
2047 .' title="' . $text . '" alt="' . $text . '" width="16"'
2048 .' height="16" />'
2049 .($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n"
2050 .'</button>' . "\n";
2051 } else {
2052 echo '<input type="image" name="' . $image_name . '" value="'
2053 . $text . '" title="' . $text . '" src="' . $GLOBALS['pmaThemeImage']
2054 . $image . '" />'
2055 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n";
2057 } // end function
2060 * Generate a pagination selector for browsing resultsets
2062 * @uses $GLOBALS['strPageNumber']
2063 * @uses range()
2064 * @param string URL for the JavaScript
2065 * @param string Number of rows in the pagination set
2066 * @param string current page number
2067 * @param string number of total pages
2068 * @param string If the number of pages is lower than this
2069 * variable, no pages will be ommitted in
2070 * pagination
2071 * @param string How many rows at the beginning should always
2072 * be shown?
2073 * @param string How many rows at the end should always
2074 * be shown?
2075 * @param string Percentage of calculation page offsets to
2076 * hop to a next page
2077 * @param string Near the current page, how many pages should
2078 * be considered "nearby" and displayed as
2079 * well?
2080 * @param string The prompt to display (sometimes empty)
2082 * @access public
2083 * @author Garvin Hicking (pma@supergarv.de)
2085 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2086 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2087 $range = 10, $prompt = '')
2089 $gotopage = $prompt
2090 . ' <select name="pos" onchange="goToUrl(this, \''
2091 . $url . '\');">' . "\n";
2092 if ($nbTotalPage < $showAll) {
2093 $pages = range(1, $nbTotalPage);
2094 } else {
2095 $pages = array();
2097 // Always show first X pages
2098 for ($i = 1; $i <= $sliceStart; $i++) {
2099 $pages[] = $i;
2102 // Always show last X pages
2103 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2104 $pages[] = $i;
2107 // garvin: Based on the number of results we add the specified
2108 // $percent percentate to each page number,
2109 // so that we have a representing page number every now and then to
2110 // immideately jump to specific pages.
2111 // As soon as we get near our currently chosen page ($pageNow -
2112 // $range), every page number will be
2113 // shown.
2114 $i = $sliceStart;
2115 $x = $nbTotalPage - $sliceEnd;
2116 $met_boundary = false;
2117 while ($i <= $x) {
2118 if ($i >= ($pageNow - $range) && $i <= ($pageNow + $range)) {
2119 // If our pageselector comes near the current page, we use 1
2120 // counter increments
2121 $i++;
2122 $met_boundary = true;
2123 } else {
2124 // We add the percentate increment to our current page to
2125 // hop to the next one in range
2126 $i = $i + floor($nbTotalPage / $percent);
2128 // Make sure that we do not cross our boundaries.
2129 if ($i > ($pageNow - $range) && !$met_boundary) {
2130 $i = $pageNow - $range;
2134 if ($i > 0 && $i <= $x) {
2135 $pages[] = $i;
2139 // Since because of ellipsing of the current page some numbers may be double,
2140 // we unify our array:
2141 sort($pages);
2142 $pages = array_unique($pages);
2145 foreach ($pages as $i) {
2146 if ($i == $pageNow) {
2147 $selected = 'selected="selected" style="font-weight: bold"';
2148 } else {
2149 $selected = '';
2151 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2154 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2157 return $gotopage;
2158 } // end function
2162 * Generate navigation for a list
2164 * @todo use $pos from $_url_params
2165 * @uses $GLOBALS['strPageNumber']
2166 * @uses range()
2167 * @param integer number of elements in the list
2168 * @param integer current position in the list
2169 * @param array url parameters
2170 * @param string script name for form target
2171 * @param string target frame
2172 * @param integer maximum number of elements to display from the list
2174 * @access public
2176 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2178 if ($max_count < $count) {
2179 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2180 echo $GLOBALS['strPageNumber'];
2181 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2183 // Move to the beginning or to the previous page
2184 if ($pos > 0) {
2185 // loic1: patch #474210 from Gosha Sakovich - part 1
2186 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2187 $caption1 = '&lt;&lt;';
2188 $caption2 = ' &lt; ';
2189 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2190 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2191 } else {
2192 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2193 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2194 $title1 = '';
2195 $title2 = '';
2196 } // end if... else...
2197 $_url_params['pos'] = 0;
2198 echo '<a' . $title1 . ' href="' . $script
2199 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2200 . $caption1 . '</a>';
2201 $_url_params['pos'] = $pos - $max_count;
2202 echo '<a' . $title2 . ' href="' . $script
2203 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2204 . $caption2 . '</a>';
2207 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2208 echo PMA_generate_common_hidden_inputs($_url_params);
2209 echo PMA_pageselector(
2210 $script . PMA_generate_common_url($_url_params) . '&',
2211 $max_count,
2212 floor(($pos + 1) / $max_count) + 1,
2213 ceil($count / $max_count));
2214 echo '</form>';
2216 if ($pos + $max_count < $count) {
2217 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2218 $caption3 = ' &gt; ';
2219 $caption4 = '&gt;&gt;';
2220 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2221 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2222 } else {
2223 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2224 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2225 $title3 = '';
2226 $title4 = '';
2227 } // end if... else...
2228 $_url_params['pos'] = $pos + $max_count;
2229 echo '<a' . $title3 . ' href="' . $script
2230 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2231 . $caption3 . '</a>';
2232 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2233 if ($_url_params['pos'] == $count) {
2234 $_url_params['pos'] = $count - $max_count;
2236 echo '<a' . $title4 . ' href="' . $script
2237 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2238 . $caption4 . '</a>';
2240 echo "\n";
2241 if ('frame_navigation' == $frame) {
2242 echo '</div>' . "\n";
2248 * replaces %u in given path with current user name
2250 * example:
2251 * <code>
2252 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2254 * </code>
2255 * @uses $cfg['Server']['user']
2256 * @uses substr()
2257 * @uses str_replace()
2258 * @param string $dir with wildcard for user
2259 * @return string per user directory
2261 function PMA_userDir($dir)
2263 // add trailing slash
2264 if (substr($dir, -1) != '/') {
2265 $dir .= '/';
2268 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2272 * returns html code for db link to default db page
2274 * @uses $cfg['DefaultTabDatabase']
2275 * @uses $GLOBALS['db']
2276 * @uses $GLOBALS['strJumpToDB']
2277 * @uses PMA_generate_common_url()
2278 * @uses PMA_unescape_mysql_wildcards()
2279 * @uses strlen()
2280 * @uses sprintf()
2281 * @uses htmlspecialchars()
2282 * @param string $database
2283 * @return string html link to default db page
2285 function PMA_getDbLink($database = null)
2287 if (!strlen($database)) {
2288 if (!strlen($GLOBALS['db'])) {
2289 return '';
2291 $database = $GLOBALS['db'];
2292 } else {
2293 $database = PMA_unescape_mysql_wildcards($database);
2296 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2297 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2298 .htmlspecialchars($database) . '</a>';
2302 * Displays a lightbulb hint explaining a known external bug
2303 * that affects a functionality
2305 * @uses PMA_MYSQL_INT_VERSION
2306 * @uses $GLOBALS['strKnownExternalBug']
2307 * @uses PMA_showHint()
2308 * @uses sprintf()
2309 * @param string $functionality localized message explaining the func.
2310 * @param string $component 'mysql' (eventually, 'php')
2311 * @param string $minimum_version of this component
2312 * @param string $bugref bug reference for this component
2314 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2316 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2317 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2322 * Converts a bit value to printable format;
2323 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2324 * function because in PHP, decbin() supports only 32 bits
2326 * @uses ceil()
2327 * @uses decbin()
2328 * @uses ord()
2329 * @uses substr()
2330 * @uses sprintf()
2331 * @param numeric $value coming from a BIT field
2332 * @param integer $length
2333 * @return string the printable value
2335 function PMA_printable_bit_value($value, $length) {
2336 $printable = '';
2337 for ($i = 0; $i < ceil($length / 8); $i++) {
2338 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2340 $printable = substr($printable, -$length);
2341 return $printable;
2345 * Extracts the true field type and length from a field type spec
2347 * @uses strpos()
2348 * @uses chop()
2349 * @uses substr()
2350 * @param string $fieldspec
2351 * @return array associative array containing the type and length
2353 function PMA_extract_type_length($fieldspec) {
2354 $first_bracket_pos = strpos($fieldspec, '(');
2355 if ($first_bracket_pos) {
2356 $length = chop(substr($fieldspec, $first_bracket_pos + 1, (strpos($fieldspec, ')') - $first_bracket_pos - 1)));
2357 $type = chop(substr($fieldspec, 0, $first_bracket_pos));
2358 } else {
2359 $type = $fieldspec;
2360 $length = '';
2362 return array(
2363 'type' => $type,
2364 'length' => $length