Italian update
[phpmyadmin/sankalp_k.git] / libraries / common.lib.php
blobe2363b3330be0cc4aaf23d485d10b1f31291df9d
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 $cfg['PropertiesIconic']
414 * @uses PMA_backquote()
415 * @uses PMA_DBI_getError()
416 * @uses PMA_formatSql()
417 * @uses PMA_generate_common_hidden_inputs()
418 * @uses PMA_generate_common_url()
419 * @uses PMA_showMySQLDocu()
420 * @uses PMA_sqlAddslashes()
421 * @uses PMA_SQP_isError()
422 * @uses PMA_SQP_parse()
423 * @uses PMA_SQP_getErrorString()
424 * @uses strtolower()
425 * @uses urlencode()
426 * @uses str_replace()
427 * @uses nl2br()
428 * @uses substr()
429 * @uses preg_replace()
430 * @uses preg_match()
431 * @uses explode()
432 * @uses implode()
433 * @uses is_array()
434 * @uses function_exists()
435 * @uses htmlspecialchars()
436 * @uses trim()
437 * @uses strstr()
438 * @param string the error message
439 * @param string the sql query that failed
440 * @param boolean whether to show a "modify" link or not
441 * @param string the "back" link url (full path is not required)
442 * @param boolean EXIT the page?
444 * @global string the curent table
445 * @global string the current db
447 * @access public
449 function PMA_mysqlDie($error_message = '', $the_query = '',
450 $is_modify_link = true, $back_url = '', $exit = true)
452 global $table, $db;
455 * start http output, display html headers
457 require_once './libraries/header.inc.php';
459 if (!$error_message) {
460 $error_message = PMA_DBI_getError();
462 if (!$the_query && !empty($GLOBALS['sql_query'])) {
463 $the_query = $GLOBALS['sql_query'];
466 // --- Added to solve bug #641765
467 // Robbat2 - 12 January 2003, 9:46PM
468 // Revised, Robbat2 - 13 January 2003, 2:59PM
469 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
470 $formatted_sql = htmlspecialchars($the_query);
471 } elseif (empty($the_query) || trim($the_query) == '') {
472 $formatted_sql = '';
473 } else {
474 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
476 // ---
477 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
478 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
479 // if the config password is wrong, or the MySQL server does not
480 // respond, do not show the query that would reveal the
481 // username/password
482 if (!empty($the_query) && !strstr($the_query, 'connect')) {
483 // --- Added to solve bug #641765
484 // Robbat2 - 12 January 2003, 9:46PM
485 // Revised, Robbat2 - 13 January 2003, 2:59PM
486 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
487 echo PMA_SQP_getErrorString() . "\n";
488 echo '<br />' . "\n";
490 // ---
491 // modified to show me the help on sql errors (Michael Keck)
492 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
493 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
494 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
496 if ($is_modify_link && strlen($db)) {
497 if (strlen($table)) {
498 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($db, $table) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
499 } else {
500 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($db) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
502 if ($GLOBALS['cfg']['PropertiesIconic']) {
503 echo $doedit_goto
504 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
505 . '</a>';
506 } else {
507 echo ' ['
508 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
509 . ']' . "\n";
511 } // end if
512 echo ' </p>' . "\n"
513 .' <p>' . "\n"
514 .' ' . $formatted_sql . "\n"
515 .' </p>' . "\n";
516 } // end if
518 $tmp_mysql_error = ''; // for saving the original $error_message
519 if (!empty($error_message)) {
520 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
521 $error_message = htmlspecialchars($error_message);
522 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
524 // modified to show me the help on error-returns (Michael Keck)
525 // (now error-messages-server)
526 echo '<p>' . "\n"
527 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
528 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
529 . "\n"
530 . '</p>' . "\n";
532 // The error message will be displayed within a CODE segment.
533 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
535 // Replace all non-single blanks with their HTML-counterpart
536 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
537 // Replace TAB-characters with their HTML-counterpart
538 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
539 // Replace linebreaks
540 $error_message = nl2br($error_message);
542 echo '<code>' . "\n"
543 . $error_message . "\n"
544 . '</code><br />' . "\n";
545 echo '</div>';
546 echo '<fieldset class="tblFooters">';
548 if (!empty($back_url) && $exit) {
549 $goto_back_url='<a href="' . (strstr($back_url, '?') ? $back_url . '&amp;no_history=true' : $back_url . '?no_history=true') . '">';
550 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
552 echo ' </fieldset>' . "\n\n";
553 if ($exit) {
555 * display footer and exit
557 require_once './libraries/footer.inc.php';
559 } // end of the 'PMA_mysqlDie()' function
562 * Returns a string formatted with CONVERT ... USING
563 * if MySQL supports it
565 * @uses PMA_MYSQL_INT_VERSION
566 * @uses $GLOBALS['collation_connection']
567 * @uses explode()
568 * @param string the string itself
569 * @param string the mode: quoted or unquoted (this one by default)
571 * @return the formatted string
573 * @access private
575 function PMA_convert_using($string, $mode='unquoted', $force_utf8 = false)
577 if ($mode == 'quoted') {
578 $possible_quote = "'";
579 } else {
580 $possible_quote = "";
583 if (PMA_MYSQL_INT_VERSION >= 40100) {
584 if ($force_utf8) {
585 $charset = 'utf8';
586 $collate = ' COLLATE utf8_bin';
587 } else {
588 list($charset) = explode('_', $GLOBALS['collation_connection']);
589 $collate = '';
591 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $charset . ")" . $collate;
592 } else {
593 $converted_string = $possible_quote . $string . $possible_quote;
595 return $converted_string;
596 } // end function
599 * Send HTTP header, taking IIS limits into account (600 seems ok)
601 * @uses PMA_IS_IIS
602 * @uses PMA_COMING_FROM_COOKIE_LOGIN
603 * @uses PMA_get_arg_separator()
604 * @uses SID
605 * @uses strlen()
606 * @uses strpos()
607 * @uses header()
608 * @uses session_write_close()
609 * @uses headers_sent()
610 * @uses function_exists()
611 * @uses debug_print_backtrace()
612 * @uses trigger_error()
613 * @uses defined()
614 * @param string $uri the header to send
615 * @return boolean always true
617 function PMA_sendHeaderLocation($uri)
619 if (PMA_IS_IIS && strlen($uri) > 600) {
621 echo '<html><head><title>- - -</title>' . "\n";
622 echo '<meta http-equiv="expires" content="0">' . "\n";
623 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
624 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
625 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
626 echo '<script type="text/javascript">' . "\n";
627 echo '//<![CDATA[' . "\n";
628 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
629 echo '//]]>' . "\n";
630 echo '</script>' . "\n";
631 echo '</head>' . "\n";
632 echo '<body>' . "\n";
633 echo '<script type="text/javascript">' . "\n";
634 echo '//<![CDATA[' . "\n";
635 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
636 echo '//]]>' . "\n";
637 echo '</script></body></html>' . "\n";
639 } else {
640 if (SID) {
641 if (strpos($uri, '?') === false) {
642 header('Location: ' . $uri . '?' . SID);
643 } else {
644 $separator = PMA_get_arg_separator();
645 header('Location: ' . $uri . $separator . SID);
647 } else {
648 session_write_close();
649 if (headers_sent()) {
650 if (function_exists('debug_print_backtrace')) {
651 echo '<pre>';
652 debug_print_backtrace();
653 echo '</pre>';
655 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
657 // bug #1523784: IE6 does not like 'Refresh: 0', it
658 // results in a blank page
659 // but we need it when coming from the cookie login panel)
660 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
661 header('Refresh: 0; ' . $uri);
662 } else {
663 header('Location: ' . $uri);
670 * returns array with tables of given db with extended information and grouped
672 * @uses $cfg['LeftFrameTableSeparator']
673 * @uses $cfg['LeftFrameTableLevel']
674 * @uses $cfg['ShowTooltipAliasTB']
675 * @uses $cfg['NaturalOrder']
676 * @uses PMA_backquote()
677 * @uses count()
678 * @uses array_merge
679 * @uses uksort()
680 * @uses strstr()
681 * @uses explode()
682 * @param string $db name of db
683 * @param string $tables name of tables
684 * return array (recursive) grouped table list
686 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
688 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
690 if (null === $tables) {
691 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
692 if ($GLOBALS['cfg']['NaturalOrder']) {
693 uksort($tables, 'strnatcasecmp');
697 if (count($tables) < 1) {
698 return $tables;
701 $default = array(
702 'Name' => '',
703 'Rows' => 0,
704 'Comment' => '',
705 'disp_name' => '',
708 $table_groups = array();
710 foreach ($tables as $table_name => $table) {
712 // check for correct row count
713 if (null === $table['Rows']) {
714 // Do not check exact row count here,
715 // if row count is invalid possibly the table is defect
716 // and this would break left frame;
717 // but we can check row count if this is a view,
718 // since PMA_Table::countRecords() returns a limited row count
719 // in this case.
721 // set this because PMA_Table::countRecords() can use it
722 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
724 if ($tbl_is_view) {
725 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
726 $return = true);
730 // in $group we save the reference to the place in $table_groups
731 // where to store the table info
732 if ($GLOBALS['cfg']['LeftFrameDBTree']
733 && $sep && strstr($table_name, $sep))
735 $parts = explode($sep, $table_name);
737 $group =& $table_groups;
738 $i = 0;
739 $group_name_full = '';
740 while ($i < count($parts) - 1
741 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
742 $group_name = $parts[$i] . $sep;
743 $group_name_full .= $group_name;
745 if (!isset($group[$group_name])) {
746 $group[$group_name] = array();
747 $group[$group_name]['is' . $sep . 'group'] = true;
748 $group[$group_name]['tab' . $sep . 'count'] = 1;
749 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
750 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
751 $table = $group[$group_name];
752 $group[$group_name] = array();
753 $group[$group_name][$group_name] = $table;
754 unset($table);
755 $group[$group_name]['is' . $sep . 'group'] = true;
756 $group[$group_name]['tab' . $sep . 'count'] = 1;
757 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
758 } else {
759 $group[$group_name]['tab' . $sep . 'count']++;
761 $group =& $group[$group_name];
762 $i++;
764 } else {
765 if (!isset($table_groups[$table_name])) {
766 $table_groups[$table_name] = array();
768 $group =& $table_groups;
772 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
773 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
774 // switch tooltip and name
775 $table['Comment'] = $table['Name'];
776 $table['disp_name'] = $table['Comment'];
777 } else {
778 $table['disp_name'] = $table['Name'];
781 $group[$table_name] = array_merge($default, $table);
784 return $table_groups;
787 /* ----------------------- Set of misc functions ----------------------- */
791 * Adds backquotes on both sides of a database, table or field name.
792 * and escapes backquotes inside the name with another backquote
794 * example:
795 * <code>
796 * echo PMA_backquote('owner`s db'); // `owner``s db`
798 * </code>
800 * @uses PMA_backquote()
801 * @uses is_array()
802 * @uses strlen()
803 * @uses str_replace()
804 * @param mixed $a_name the database, table or field name to "backquote"
805 * or array of it
806 * @param boolean $do_it a flag to bypass this function (used by dump
807 * functions)
808 * @return mixed the "backquoted" database, table or field name if the
809 * current MySQL release is >= 3.23.6, the original one
810 * else
811 * @access public
813 function PMA_backquote($a_name, $do_it = true)
815 if (! $do_it) {
816 return $a_name;
819 if (is_array($a_name)) {
820 $result = array();
821 foreach ($a_name as $key => $val) {
822 $result[$key] = PMA_backquote($val);
824 return $result;
827 // '0' is also empty for php :-(
828 if (strlen($a_name) && $a_name !== '*') {
829 return '`' . str_replace('`', '``', $a_name) . '`';
830 } else {
831 return $a_name;
833 } // end of the 'PMA_backquote()' function
837 * Defines the <CR><LF> value depending on the user OS.
839 * @uses PMA_USR_OS
840 * @return string the <CR><LF> value to use
842 * @access public
844 function PMA_whichCrlf()
846 $the_crlf = "\n";
848 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
849 // Win case
850 if (PMA_USR_OS == 'Win') {
851 $the_crlf = "\r\n";
853 // Others
854 else {
855 $the_crlf = "\n";
858 return $the_crlf;
859 } // end of the 'PMA_whichCrlf()' function
862 * Reloads navigation if needed.
864 * @uses $GLOBALS['reload']
865 * @uses $GLOBALS['db']
866 * @uses PMA_generate_common_url()
867 * @global array configuration
869 * @access public
871 function PMA_reloadNavigation()
873 global $cfg;
875 // Reloads the navigation frame via JavaScript if required
876 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
877 // one of the reasons for a reload is when a table is dropped
878 // in this case, get rid of the table limit offset, otherwise
879 // we have a problem when dropping a table on the last page
880 // and the offset becomes greater than the total number of tables
881 unset($_SESSION['userconf']['table_limit_offset']);
882 echo "\n";
883 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
885 <script type="text/javascript">
886 //<![CDATA[
887 if (typeof(window.parent) != 'undefined'
888 && typeof(window.parent.frame_navigation) != 'undefined') {
889 window.parent.goTo('<?php echo $reload_url; ?>');
891 //]]>
892 </script>
893 <?php
894 unset($GLOBALS['reload']);
899 * displays the message and the query
900 * usually the message is the result of the query executed
902 * @param string $message the message to display
903 * @param string $sql_query the query to display
904 * @global array the configuration array
905 * @uses $cfg
906 * @access public
908 function PMA_showMessage($message, $sql_query = null)
910 global $cfg;
911 $query_too_big = false;
913 if (null === $sql_query) {
914 if (! empty($GLOBALS['display_query'])) {
915 $sql_query = $GLOBALS['display_query'];
916 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
917 $sql_query = $GLOBALS['unparsed_sql'];
918 } elseif (! empty($GLOBALS['sql_query'])) {
919 $sql_query = $GLOBALS['sql_query'];
920 } else {
921 $sql_query = '';
925 // Corrects the tooltip text via JS if required
926 // @todo this is REALLY the wrong place to do this - very unexpected here
927 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
928 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
929 if ($result) {
930 $tbl_status = PMA_DBI_fetch_assoc($result);
931 $tooltip = (empty($tbl_status['Comment']))
932 ? ''
933 : $tbl_status['Comment'] . ' ';
934 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
935 PMA_DBI_free_result($result);
936 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
937 echo "\n";
938 echo '<script type="text/javascript">' . "\n";
939 echo '//<![CDATA[' . "\n";
940 echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
941 echo '//]]>' . "\n";
942 echo '</script>' . "\n";
943 } // end if
944 } // end if ... elseif
946 // Checks if the table needs to be repaired after a TRUNCATE query.
947 // @todo what about $GLOBALS['display_query']???
948 // @todo this is REALLY the wrong place to do this - very unexpected here
949 if (strlen($GLOBALS['table'])
950 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
951 if (!isset($tbl_status)) {
952 $result = @PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
953 if ($result) {
954 $tbl_status = PMA_DBI_fetch_assoc($result);
955 PMA_DBI_free_result($result);
958 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
959 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
962 unset($tbl_status);
963 echo '<br />' . "\n";
965 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
966 if (!empty($GLOBALS['show_error_header'])) {
967 echo '<div class="error">' . "\n";
968 echo '<h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
971 echo '<div class="notice">';
972 echo PMA_sanitize($message);
973 if (isset($GLOBALS['special_message'])) {
974 echo PMA_sanitize($GLOBALS['special_message']);
975 unset($GLOBALS['special_message']);
977 echo '</div>';
979 if (!empty($GLOBALS['show_error_header'])) {
980 echo '</div>';
983 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
984 // Basic url query part
985 $url_qpart = '?' . PMA_generate_common_url($GLOBALS['db'], $GLOBALS['table']);
987 // Html format the query to be displayed
988 // The nl2br function isn't used because its result isn't a valid
989 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
990 // If we want to show some sql code it is easiest to create it here
991 /* SQL-Parser-Analyzer */
993 if (!empty($GLOBALS['show_as_php'])) {
994 $new_line = '\'<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
996 if (isset($new_line)) {
997 /* SQL-Parser-Analyzer */
998 $query_base = PMA_sqlAddslashes(htmlspecialchars($sql_query), false, false, true);
999 /* SQL-Parser-Analyzer */
1000 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
1001 } else {
1002 $query_base = $sql_query;
1005 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1006 $query_too_big = true;
1007 $query_base = nl2br(htmlspecialchars($sql_query));
1008 unset($GLOBALS['parsed_sql']);
1011 // Parse SQL if needed
1012 // (here, use "! empty" because when deleting a bookmark,
1013 // $GLOBALS['parsed_sql'] is set but empty
1014 if (! empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1015 $parsed_sql = $GLOBALS['parsed_sql'];
1016 } else {
1017 // when the query is large (for example an INSERT of binary
1018 // data), the parser chokes; so avoid parsing the query
1019 if (! $query_too_big) {
1020 $parsed_sql = PMA_SQP_parse($query_base);
1024 // Analyze it
1025 if (isset($parsed_sql)) {
1026 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1029 // Here we append the LIMIT added for navigation, to
1030 // enable its display. Adding it higher in the code
1031 // to $sql_query would create a problem when
1032 // using the Refresh or Edit links.
1034 // Only append it on SELECTs.
1037 * @todo what would be the best to do when someone hits Refresh:
1038 * use the current LIMITs ?
1041 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1042 && isset($GLOBALS['sql_limit_to_append'])) {
1043 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1044 // Need to reparse query
1045 $parsed_sql = PMA_SQP_parse($query_base);
1048 if (!empty($GLOBALS['show_as_php'])) {
1049 $query_base = '$sql = \'' . $query_base;
1050 } elseif (!empty($GLOBALS['validatequery'])) {
1051 $query_base = PMA_validateSQL($query_base);
1052 } else {
1053 if (isset($parsed_sql)) {
1054 $query_base = PMA_formatSql($parsed_sql, $query_base);
1058 // Prepares links that may be displayed to edit/explain the query
1059 // (don't go to default pages, we must go to the page
1060 // where the query box is available)
1062 $edit_target = strlen($GLOBALS['db']) ? (strlen($GLOBALS['table']) ? 'tbl_sql.php' : 'db_sql.php') : 'server_sql.php';
1064 if (isset($cfg['SQLQuery']['Edit'])
1065 && ($cfg['SQLQuery']['Edit'] == true)
1066 && (!empty($edit_target))
1067 && ! $query_too_big) {
1069 if ($cfg['EditInWindow'] == true) {
1070 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1071 } else {
1072 $onclick = '';
1075 $edit_link = $edit_target
1076 . $url_qpart
1077 . '&amp;sql_query=' . urlencode($sql_query)
1078 . '&amp;show_query=1#querybox';
1079 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1080 } else {
1081 $edit_link = '';
1084 // Want to have the query explained (Mike Beck 2002-05-22)
1085 // but only explain a SELECT (that has not been explained)
1086 /* SQL-Parser-Analyzer */
1087 if (isset($cfg['SQLQuery']['Explain'])
1088 && $cfg['SQLQuery']['Explain'] == true
1089 && ! $query_too_big) {
1091 // Detect if we are validating as well
1092 // To preserve the validate uRL data
1093 if (!empty($GLOBALS['validatequery'])) {
1094 $explain_link_validate = '&amp;validatequery=1';
1095 } else {
1096 $explain_link_validate = '';
1099 $explain_link = 'import.php'
1100 . $url_qpart
1101 . $explain_link_validate
1102 . '&amp;sql_query=';
1104 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1105 $explain_link .= urlencode('EXPLAIN ' . $sql_query);
1106 $message = $GLOBALS['strExplain'];
1107 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1108 $explain_link .= urlencode(substr($sql_query, 8));
1109 $message = $GLOBALS['strNoExplain'];
1110 } else {
1111 $explain_link = '';
1113 if (!empty($explain_link)) {
1114 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1116 } else {
1117 $explain_link = '';
1118 } //show explain
1120 // Also we would like to get the SQL formed in some nice
1121 // php-code (Mike Beck 2002-05-22)
1122 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1123 && $cfg['SQLQuery']['ShowAsPHP'] == true
1124 && ! $query_too_big) {
1125 $php_link = 'import.php'
1126 . $url_qpart
1127 . '&amp;show_query=1'
1128 . '&amp;sql_query=' . urlencode($sql_query)
1129 . '&amp;show_as_php=';
1131 if (!empty($GLOBALS['show_as_php'])) {
1132 $php_link .= '0';
1133 $message = $GLOBALS['strNoPhp'];
1134 } else {
1135 $php_link .= '1';
1136 $message = $GLOBALS['strPhp'];
1138 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1140 if (isset($GLOBALS['show_as_php'])) {
1141 $runquery_link
1142 = 'import.php'
1143 . $url_qpart
1144 . '&amp;show_query=1'
1145 . '&amp;sql_query=' . urlencode($sql_query);
1146 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1149 } else {
1150 $php_link = '';
1151 } //show as php
1153 // Refresh query
1154 if (isset($cfg['SQLQuery']['Refresh'])
1155 && $cfg['SQLQuery']['Refresh']
1156 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1158 $refresh_link = 'import.php'
1159 . $url_qpart
1160 . '&amp;show_query=1'
1161 . '&amp;sql_query=' . urlencode($sql_query);
1162 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1163 } else {
1164 $refresh_link = '';
1165 } //show as php
1167 if (isset($cfg['SQLValidator']['use'])
1168 && $cfg['SQLValidator']['use'] == true
1169 && isset($cfg['SQLQuery']['Validate'])
1170 && $cfg['SQLQuery']['Validate'] == true) {
1171 $validate_link = 'import.php'
1172 . $url_qpart
1173 . '&amp;show_query=1'
1174 . '&amp;sql_query=' . urlencode($sql_query)
1175 . '&amp;validatequery=';
1176 if (!empty($GLOBALS['validatequery'])) {
1177 $validate_link .= '0';
1178 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1179 } else {
1180 $validate_link .= '1';
1181 $validate_message = $GLOBALS['strValidateSQL'] ;
1183 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1184 } else {
1185 $validate_link = '';
1186 } //validator
1188 // why this?
1189 //unset($sql_query);
1191 // Displays the message
1192 echo '<fieldset class="">' . "\n";
1193 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1194 echo ' <div>';
1195 // when uploading a 700 Kio binary file into a LONGBLOB,
1196 // I get a white page, strlen($query_base) is 2 x 700 Kio
1197 // so put a hard limit here (let's say 1000)
1198 if ($query_too_big) {
1199 echo ' ' . substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
1200 } else {
1201 echo ' ' . $query_base;
1204 //Clean up the end of the PHP
1205 if (!empty($GLOBALS['show_as_php'])) {
1206 echo '\';';
1208 echo ' </div>';
1209 echo '</fieldset>' . "\n";
1211 if (!empty($edit_target)) {
1212 echo '<fieldset class="tblFooters">';
1213 PMA_profilingCheckbox($sql_query);
1214 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1215 echo '</fieldset>';
1218 echo '</div><br />' . "\n";
1219 } // end of the 'PMA_showMessage()' function
1223 * Verifies if current MySQL server supports profiling
1225 * @access public
1226 * @return boolean whether profiling is supported
1228 * @author Marc Delisle
1230 function PMA_profilingSupported() {
1231 // 5.0.37 has profiling but for example, 5.1.20 does not
1232 // (avoid a trip to the server for MySQL before 5.0.37)
1233 // and do not set a constant as we might be switching servers
1234 if (defined('PMA_MYSQL_INT_VERSION') && PMA_MYSQL_INT_VERSION >= 50037 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1235 return true;
1236 } else {
1237 return false;
1242 * Displays a form with the Profiling checkbox
1244 * @param string $sql_query
1245 * @access public
1247 * @author Marc Delisle
1249 function PMA_profilingCheckbox($sql_query) {
1250 if (PMA_profilingSupported()) {
1251 echo '<form action="sql.php" method="post">' . "\n";
1252 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1253 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1254 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1255 echo '<input type="checkbox" name="profiling" id="profiling"' . (isset($_SESSION['profiling']) ? ' checked="checked"' : '') . ' onclick="this.form.submit();" /><label for="profiling">' . $GLOBALS['strProfiling'] . '</label>' . "\n";
1256 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1257 echo '</form>' . "\n";
1262 * Displays the results of SHOW PROFILE
1264 * @param array the results
1265 * @access public
1267 * @author Marc Delisle
1269 function PMA_profilingResults($profiling_results) {
1270 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1271 echo '<table>' . "\n";
1272 echo ' <tr>' . "\n";
1273 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1274 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1275 echo ' </tr>' . "\n";
1277 foreach($profiling_results as $one_result) {
1278 echo ' <tr>' . "\n";
1279 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1280 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1282 echo '</table>' . "\n";
1283 echo '</fieldset>' . "\n";
1287 * Formats $value to byte view
1289 * @param double the value to format
1290 * @param integer the sensitiveness
1291 * @param integer the number of decimals to retain
1293 * @return array the formatted value and its unit
1295 * @access public
1297 * @author staybyte
1298 * @version 1.2 - 18 July 2002
1300 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1302 $dh = PMA_pow(10, $comma);
1303 $li = PMA_pow(10, $limes);
1304 $return_value = $value;
1305 $unit = $GLOBALS['byteUnits'][0];
1307 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1308 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1309 // use 1024.0 to avoid integer overflow on 64-bit machines
1310 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1311 $unit = $GLOBALS['byteUnits'][$d];
1312 break 1;
1313 } // end if
1314 } // end for
1316 if ($unit != $GLOBALS['byteUnits'][0]) {
1317 // if the unit is not bytes (as represented in current language)
1318 // reformat with max length of 5
1319 // 4th parameter=true means do not reformat if value < 1
1320 $return_value = PMA_formatNumber($value, 5, $comma, true);
1321 } else {
1322 // do not reformat, just handle the locale
1323 $return_value = PMA_formatNumber($value, 0);
1326 return array($return_value, $unit);
1327 } // end of the 'PMA_formatByteDown' function
1330 * Formats $value to the given length and appends SI prefixes
1331 * $comma is not substracted from the length
1332 * with a $length of 0 no truncation occurs, number is only formated
1333 * to the current locale
1335 * examples:
1336 * <code>
1337 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1338 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1339 * echo PMA_formatNumber(-0.003, 6); // -3 m
1340 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1341 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1342 * echo PMA_formatNumber(0, 6); // 0
1344 * </code>
1345 * @param double $value the value to format
1346 * @param integer $length the max length
1347 * @param integer $comma the number of decimals to retain
1348 * @param boolean $only_down do not reformat numbers below 1
1350 * @return string the formatted value and its unit
1352 * @access public
1354 * @author staybyte, sebastian mendel
1355 * @version 1.1.0 - 2005-10-27
1357 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1359 //number_format is not multibyte safe, str_replace is safe
1360 if ($length === 0) {
1361 return str_replace(array(',', '.'),
1362 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1363 number_format($value, $comma));
1366 // this units needs no translation, ISO
1367 $units = array(
1368 -8 => 'y',
1369 -7 => 'z',
1370 -6 => 'a',
1371 -5 => 'f',
1372 -4 => 'p',
1373 -3 => 'n',
1374 -2 => '&micro;',
1375 -1 => 'm',
1376 0 => ' ',
1377 1 => 'k',
1378 2 => 'M',
1379 3 => 'G',
1380 4 => 'T',
1381 5 => 'P',
1382 6 => 'E',
1383 7 => 'Z',
1384 8 => 'Y'
1387 // we need at least 3 digits to be displayed
1388 if (3 > $length + $comma) {
1389 $length = 3 - $comma;
1392 // check for negative value to retain sign
1393 if ($value < 0) {
1394 $sign = '-';
1395 $value = abs($value);
1396 } else {
1397 $sign = '';
1400 $dh = PMA_pow(10, $comma);
1401 $li = PMA_pow(10, $length);
1402 $unit = $units[0];
1404 if ($value >= 1) {
1405 for ($d = 8; $d >= 0; $d--) {
1406 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1407 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1408 $unit = $units[$d];
1409 break 1;
1410 } // end if
1411 } // end for
1412 } elseif (!$only_down && (float) $value !== 0.0) {
1413 for ($d = -8; $d <= 8; $d++) {
1414 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1415 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1416 $unit = $units[$d];
1417 break 1;
1418 } // end if
1419 } // end for
1420 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1422 //number_format is not multibyte safe, str_replace is safe
1423 $value = str_replace(array(',', '.'),
1424 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1425 number_format($value, $comma));
1427 return $sign . $value . ' ' . $unit;
1428 } // end of the 'PMA_formatNumber' function
1431 * Extracts ENUM / SET options from a type definition string
1433 * @param string The column type definition
1435 * @return array The options or
1436 * boolean false in case of an error.
1438 * @author rabus
1440 function PMA_getEnumSetOptions($type_def)
1442 $open = strpos($type_def, '(');
1443 $close = strrpos($type_def, ')');
1444 if (!$open || !$close) {
1445 return false;
1447 $options = substr($type_def, $open + 2, $close - $open - 3);
1448 $options = explode('\',\'', $options);
1449 return $options;
1450 } // end of the 'PMA_getEnumSetOptions' function
1453 * Writes localised date
1455 * @param string the current timestamp
1457 * @return string the formatted date
1459 * @access public
1461 function PMA_localisedDate($timestamp = -1, $format = '')
1463 global $datefmt, $month, $day_of_week;
1465 if ($format == '') {
1466 $format = $datefmt;
1469 if ($timestamp == -1) {
1470 $timestamp = time();
1473 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1474 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1476 return strftime($date, $timestamp);
1477 } // end of the 'PMA_localisedDate()' function
1481 * returns a tab for tabbed navigation.
1482 * If the variables $link and $args ar left empty, an inactive tab is created
1484 * @uses $GLOBALS['PMA_PHP_SELF']
1485 * @uses $GLOBALS['strEmpty']
1486 * @uses $GLOBALS['strDrop']
1487 * @uses $GLOBALS['active_page']
1488 * @uses $GLOBALS['url_query']
1489 * @uses $cfg['MainPageIconic']
1490 * @uses $GLOBALS['pmaThemeImage']
1491 * @uses PMA_generate_common_url()
1492 * @uses E_USER_NOTICE
1493 * @uses htmlentities()
1494 * @uses urlencode()
1495 * @uses sprintf()
1496 * @uses trigger_error()
1497 * @uses array_merge()
1498 * @uses basename()
1499 * @param array $tab array with all options
1500 * @return string html code for one tab, a link if valid otherwise a span
1501 * @access public
1503 function PMA_getTab($tab)
1505 // default values
1506 $defaults = array(
1507 'text' => '',
1508 'class' => '',
1509 'active' => false,
1510 'link' => '',
1511 'sep' => '?',
1512 'attr' => '',
1513 'args' => '',
1514 'warning' => '',
1515 'fragment' => '',
1518 $tab = array_merge($defaults, $tab);
1520 // determine additionnal style-class
1521 if (empty($tab['class'])) {
1522 if ($tab['text'] == $GLOBALS['strEmpty']
1523 || $tab['text'] == $GLOBALS['strDrop']) {
1524 $tab['class'] = 'caution';
1525 } elseif (!empty($tab['active'])
1526 || (isset($GLOBALS['active_page'])
1527 && $GLOBALS['active_page'] == $tab['link'])
1528 || (basename($GLOBALS['PMA_PHP_SELF']) == $tab['link'] && empty($tab['warning'])))
1530 $tab['class'] = 'active';
1534 if (!empty($tab['warning'])) {
1535 $tab['class'] .= ' warning';
1536 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1539 // build the link
1540 if (!empty($tab['link'])) {
1541 $tab['link'] = htmlentities($tab['link']);
1542 $tab['link'] = $tab['link'] . $tab['sep']
1543 .(empty($GLOBALS['url_query']) ?
1544 PMA_generate_common_url() : $GLOBALS['url_query']);
1545 if (!empty($tab['args'])) {
1546 foreach ($tab['args'] as $param => $value) {
1547 $tab['link'] .= '&amp;' . urlencode($param) . '='
1548 . urlencode($value);
1553 if (! empty($tab['fragment'])) {
1554 $tab['link'] .= $tab['fragment'];
1557 // display icon, even if iconic is disabled but the link-text is missing
1558 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1559 && isset($tab['icon'])) {
1560 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1561 .'%1$s" width="16" height="16" alt="%2$s" />%2$s';
1562 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1564 // check to not display an empty link-text
1565 elseif (empty($tab['text'])) {
1566 $tab['text'] = '?';
1567 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1568 E_USER_NOTICE);
1571 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1573 if (!empty($tab['link'])) {
1574 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1575 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1576 . $tab['text'] . '</a>';
1577 } else {
1578 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1579 . $tab['text'] . '</span>';
1582 $out .= '</li>';
1583 return $out;
1584 } // end of the 'PMA_getTab()' function
1587 * returns html-code for a tab navigation
1589 * @uses PMA_getTab()
1590 * @uses htmlentities()
1591 * @param array $tabs one element per tab
1592 * @param string $tag_id id used for the html-tag
1593 * @return string html-code for tab-navigation
1595 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1597 $tab_navigation =
1598 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1599 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1601 foreach ($tabs as $tab) {
1602 $tab_navigation .= PMA_getTab($tab) . "\n";
1605 $tab_navigation .=
1606 '</ul>' . "\n"
1607 .'<div class="clearfloat"></div>'
1608 .'</div>' . "\n";
1610 return $tab_navigation;
1615 * Displays a link, or a button if the link's URL is too large, to
1616 * accommodate some browsers' limitations
1618 * @param string the URL
1619 * @param string the link message
1620 * @param mixed $tag_params string: js confirmation
1621 * array: additional tag params (f.e. style="")
1622 * @param boolean $new_form we set this to false when we are already in
1623 * a form, to avoid generating nested forms
1625 * @return string the results to be echoed or saved in an array
1627 function PMA_linkOrButton($url, $message, $tag_params = array(),
1628 $new_form = true, $strip_img = false, $target = '')
1630 if (! is_array($tag_params)) {
1631 $tmp = $tag_params;
1632 $tag_params = array();
1633 if (!empty($tmp)) {
1634 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1636 unset($tmp);
1638 if (! empty($target)) {
1639 $tag_params['target'] = htmlentities($target);
1642 $tag_params_strings = array();
1643 foreach ($tag_params as $par_name => $par_value) {
1644 // htmlspecialchars() only on non javascript
1645 $par_value = substr($par_name, 0, 2) == 'on'
1646 ? $par_value
1647 : htmlspecialchars($par_value);
1648 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1651 // previously the limit was set to 2047, it seems 1000 is better
1652 if (strlen($url) <= 1000) {
1653 // no whitespace within an <a> else Safari will make it part of the link
1654 $ret = "\n" . '<a href="' . $url . '" '
1655 . implode(' ', $tag_params_strings) . '>'
1656 . $message . '</a>' . "\n";
1657 } else {
1658 // no spaces (linebreaks) at all
1659 // or after the hidden fields
1660 // IE will display them all
1662 // add class=link to submit button
1663 if (empty($tag_params['class'])) {
1664 $tag_params['class'] = 'link';
1667 // decode encoded url separators
1668 $separator = PMA_get_arg_separator();
1669 // on most places separator is still hard coded ...
1670 if ($separator !== '&') {
1671 // ... so always replace & with $separator
1672 $url = str_replace(htmlentities('&'), $separator, $url);
1673 $url = str_replace('&', $separator, $url);
1675 $url = str_replace(htmlentities($separator), $separator, $url);
1676 // end decode
1678 $url_parts = parse_url($url);
1679 $query_parts = explode($separator, $url_parts['query']);
1680 if ($new_form) {
1681 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1682 . ' method="post"' . $target . ' style="display: inline;">';
1683 $subname_open = '';
1684 $subname_close = '';
1685 $submit_name = '';
1686 } else {
1687 $query_parts[] = 'redirect=' . $url_parts['path'];
1688 if (empty($GLOBALS['subform_counter'])) {
1689 $GLOBALS['subform_counter'] = 0;
1691 $GLOBALS['subform_counter']++;
1692 $ret = '';
1693 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1694 $subname_close = ']';
1695 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1697 foreach ($query_parts as $query_pair) {
1698 list($eachvar, $eachval) = explode('=', $query_pair);
1699 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1700 . $subname_close . '" value="'
1701 . htmlspecialchars(urldecode($eachval)) . '" />';
1702 } // end while
1704 if (stristr($message, '<img')) {
1705 if ($strip_img) {
1706 $message = trim(strip_tags($message));
1707 $ret .= '<input type="submit"' . $submit_name . ' '
1708 . implode(' ', $tag_params_strings)
1709 . ' value="' . htmlspecialchars($message) . '" />';
1710 } else {
1711 $ret .= '<input type="image"' . $submit_name . ' '
1712 . implode(' ', $tag_params_strings)
1713 . ' src="' . preg_replace(
1714 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1715 . ' value="' . htmlspecialchars(
1716 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1717 $message))
1718 . '" />';
1720 } else {
1721 $message = trim(strip_tags($message));
1722 $ret .= '<input type="submit"' . $submit_name . ' '
1723 . implode(' ', $tag_params_strings)
1724 . ' value="' . htmlspecialchars($message) . '" />';
1726 if ($new_form) {
1727 $ret .= '</form>';
1729 } // end if... else...
1731 return $ret;
1732 } // end of the 'PMA_linkOrButton()' function
1736 * Returns a given timespan value in a readable format.
1738 * @uses $GLOBALS['timespanfmt']
1739 * @uses sprintf()
1740 * @uses floor()
1741 * @param int the timespan
1743 * @return string the formatted value
1745 function PMA_timespanFormat($seconds)
1747 $return_string = '';
1748 $days = floor($seconds / 86400);
1749 if ($days > 0) {
1750 $seconds -= $days * 86400;
1752 $hours = floor($seconds / 3600);
1753 if ($days > 0 || $hours > 0) {
1754 $seconds -= $hours * 3600;
1756 $minutes = floor($seconds / 60);
1757 if ($days > 0 || $hours > 0 || $minutes > 0) {
1758 $seconds -= $minutes * 60;
1760 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1764 * Takes a string and outputs each character on a line for itself. Used
1765 * mainly for horizontalflipped display mode.
1766 * Takes care of special html-characters.
1767 * Fulfills todo-item
1768 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1770 * @todo add a multibyte safe function PMA_STR_split()
1771 * @uses strlen
1772 * @param string The string
1773 * @param string The Separator (defaults to "<br />\n")
1775 * @access public
1776 * @author Garvin Hicking <me@supergarv.de>
1777 * @return string The flipped string
1779 function PMA_flipstring($string, $Separator = "<br />\n")
1781 $format_string = '';
1782 $charbuff = false;
1784 for ($i = 0; $i < strlen($string); $i++) {
1785 $char = $string{$i};
1786 $append = false;
1788 if ($char == '&') {
1789 $format_string .= $charbuff;
1790 $charbuff = $char;
1791 $append = true;
1792 } elseif (!empty($charbuff)) {
1793 $charbuff .= $char;
1794 } elseif ($char == ';' && !empty($charbuff)) {
1795 $format_string .= $charbuff;
1796 $charbuff = false;
1797 $append = true;
1798 } else {
1799 $format_string .= $char;
1800 $append = true;
1803 if ($append && ($i != strlen($string))) {
1804 $format_string .= $Separator;
1808 return $format_string;
1813 * Function added to avoid path disclosures.
1814 * Called by each script that needs parameters, it displays
1815 * an error message and, by default, stops the execution.
1817 * Not sure we could use a strMissingParameter message here,
1818 * would have to check if the error message file is always available
1820 * @todo localize error message
1821 * @todo use PMA_fatalError() if $die === true?
1822 * @uses PMA_getenv()
1823 * @uses header_meta_style.inc.php
1824 * @uses $GLOBALS['PMA_PHP_SELF']
1825 * basename
1826 * @param array The names of the parameters needed by the calling
1827 * script.
1828 * @param boolean Stop the execution?
1829 * (Set this manually to false in the calling script
1830 * until you know all needed parameters to check).
1831 * @param boolean Whether to include this list in checking for special params.
1832 * @global string path to current script
1833 * @global boolean flag whether any special variable was required
1835 * @access public
1836 * @author Marc Delisle (lem9@users.sourceforge.net)
1838 function PMA_checkParameters($params, $die = true, $request = true)
1840 global $checked_special;
1842 if (!isset($checked_special)) {
1843 $checked_special = false;
1846 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1847 $found_error = false;
1848 $error_message = '';
1850 foreach ($params as $param) {
1851 if ($request && $param != 'db' && $param != 'table') {
1852 $checked_special = true;
1855 if (!isset($GLOBALS[$param])) {
1856 $error_message .= $reported_script_name
1857 . ': Missing parameter: ' . $param
1858 . ' <a href="./Documentation.html#faqmissingparameters"'
1859 . ' target="documentation"> (FAQ 2.8)</a><br />';
1860 $found_error = true;
1863 if ($found_error) {
1865 * display html meta tags
1867 require_once './libraries/header_meta_style.inc.php';
1868 echo '</head><body><p>' . $error_message . '</p></body></html>';
1869 if ($die) {
1870 exit();
1873 } // end function
1876 * Function to generate unique condition for specified row.
1878 * @uses PMA_MYSQL_INT_VERSION
1879 * @uses $GLOBALS['analyzed_sql'][0]
1880 * @uses PMA_DBI_field_flags()
1881 * @uses PMA_backquote()
1882 * @uses PMA_sqlAddslashes()
1883 * @uses stristr()
1884 * @uses bin2hex()
1885 * @uses preg_replace()
1886 * @param resource $handle current query result
1887 * @param integer $fields_cnt number of fields
1888 * @param array $fields_meta meta information about fields
1889 * @param array $row current row
1890 * @param boolean $force_unique generate condition only on pk or unique
1892 * @access public
1893 * @author Michal Cihar (michal@cihar.com) and others...
1894 * @return string calculated condition
1896 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1898 $primary_key = '';
1899 $unique_key = '';
1900 $nonprimary_condition = '';
1901 $preferred_condition = '';
1903 for ($i = 0; $i < $fields_cnt; ++$i) {
1904 $condition = '';
1905 $field_flags = PMA_DBI_field_flags($handle, $i);
1906 $meta = $fields_meta[$i];
1908 // do not use a column alias in a condition
1909 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1910 $meta->orgname = $meta->name;
1912 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1913 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1914 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1915 as $select_expr) {
1916 // need (string) === (string)
1917 // '' !== 0 but '' == 0
1918 if ((string) $select_expr['alias'] === (string) $meta->name) {
1919 $meta->orgname = $select_expr['column'];
1920 break;
1921 } // end if
1922 } // end foreach
1926 // Do not use a table alias in a condition.
1927 // Test case is:
1928 // select * from galerie x WHERE
1929 //(select count(*) from galerie y where y.datum=x.datum)>1
1931 // But orgtable is present only with mysqli extension so the
1932 // fix is only for mysqli.
1933 if (isset($meta->orgtable) && $meta->table != $meta->orgtable) {
1934 $meta->table = $meta->orgtable;
1937 // to fix the bug where float fields (primary or not)
1938 // can't be matched because of the imprecision of
1939 // floating comparison, use CONCAT
1940 // (also, the syntax "CONCAT(field) IS NULL"
1941 // that we need on the next "if" will work)
1942 if ($meta->type == 'real') {
1943 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1944 . PMA_backquote($meta->orgname) . ') ';
1945 } else {
1946 // string and blob fields have to be converted using
1947 // the system character set (always utf8) since
1948 // mysql4.1 can use different charset for fields.
1949 if (PMA_MYSQL_INT_VERSION >= 40100
1950 && ($meta->type == 'string' || $meta->type == 'blob')) {
1951 $condition = ' CONVERT(' . PMA_backquote($meta->table) . '.'
1952 . PMA_backquote($meta->orgname) . ' USING utf8) ';
1953 } else {
1954 $condition = ' ' . PMA_backquote($meta->table) . '.'
1955 . PMA_backquote($meta->orgname) . ' ';
1957 } // end if... else...
1959 if (!isset($row[$i]) || is_null($row[$i])) {
1960 $condition .= 'IS NULL AND';
1961 } else {
1962 // timestamp is numeric on some MySQL 4.1
1963 if ($meta->numeric && $meta->type != 'timestamp') {
1964 $condition .= '= ' . $row[$i] . ' AND';
1965 } elseif ($meta->type == 'blob'
1966 // hexify only if this is a true not empty BLOB
1967 && stristr($field_flags, 'BINARY')
1968 && !empty($row[$i])) {
1969 // do not waste memory building a too big condition
1970 if (strlen($row[$i]) < 1000) {
1971 if (PMA_MYSQL_INT_VERSION < 40002) {
1972 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
1973 } else {
1974 // use a CAST if possible, to avoid problems
1975 // if the field contains wildcard characters % or _
1976 $condition .= '= CAST(0x' . bin2hex($row[$i])
1977 . ' AS BINARY) AND';
1979 } else {
1980 // this blob won't be part of the final condition
1981 $condition = '';
1983 } else {
1984 $condition .= '= \''
1985 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
1988 if ($meta->primary_key > 0) {
1989 $primary_key .= $condition;
1990 } elseif ($meta->unique_key > 0) {
1991 $unique_key .= $condition;
1993 $nonprimary_condition .= $condition;
1994 } // end for
1996 // Correction University of Virginia 19991216:
1997 // prefer primary or unique keys for condition,
1998 // but use conjunction of all values if no primary key
1999 if ($primary_key) {
2000 $preferred_condition = $primary_key;
2001 } elseif ($unique_key) {
2002 $preferred_condition = $unique_key;
2003 } elseif (! $force_unique) {
2004 $preferred_condition = $nonprimary_condition;
2007 return preg_replace('|\s?AND$|', '', $preferred_condition);
2008 } // end function
2011 * Generate a button or image tag
2013 * @uses PMA_USR_BROWSER_AGENT
2014 * @uses $GLOBALS['pmaThemeImage']
2015 * @uses $GLOBALS['cfg']['PropertiesIconic']
2016 * @param string name of button element
2017 * @param string class of button element
2018 * @param string name of image element
2019 * @param string text to display
2020 * @param string image to display
2022 * @access public
2023 * @author Michal Cihar (michal@cihar.com)
2025 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2026 $image)
2028 /* Opera has trouble with <input type="image"> */
2029 /* IE has trouble with <button> */
2030 if (PMA_USR_BROWSER_AGENT != 'IE') {
2031 echo '<button class="' . $button_class . '" type="submit"'
2032 .' name="' . $button_name . '" value="' . $text . '"'
2033 .' title="' . $text . '">' . "\n"
2034 .'<img class="icon" src="' . $GLOBALS['pmaThemeImage'] . $image . '"'
2035 .' title="' . $text . '" alt="' . $text . '" width="16"'
2036 .' height="16" />'
2037 .($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n"
2038 .'</button>' . "\n";
2039 } else {
2040 echo '<input type="image" name="' . $image_name . '" value="'
2041 . $text . '" title="' . $text . '" src="' . $GLOBALS['pmaThemeImage']
2042 . $image . '" />'
2043 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . $text : '') . "\n";
2045 } // end function
2048 * Generate a pagination selector for browsing resultsets
2050 * @uses $GLOBALS['strPageNumber']
2051 * @uses range()
2052 * @param string URL for the JavaScript
2053 * @param string Number of rows in the pagination set
2054 * @param string current page number
2055 * @param string number of total pages
2056 * @param string If the number of pages is lower than this
2057 * variable, no pages will be ommitted in
2058 * pagination
2059 * @param string How many rows at the beginning should always
2060 * be shown?
2061 * @param string How many rows at the end should always
2062 * be shown?
2063 * @param string Percentage of calculation page offsets to
2064 * hop to a next page
2065 * @param string Near the current page, how many pages should
2066 * be considered "nearby" and displayed as
2067 * well?
2068 * @param string The prompt to display (sometimes empty)
2070 * @access public
2071 * @author Garvin Hicking (pma@supergarv.de)
2073 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2074 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2075 $range = 10, $prompt = '')
2077 $gotopage = $prompt
2078 . ' <select name="pos" onchange="goToUrl(this, \''
2079 . $url . '\');">' . "\n";
2080 if ($nbTotalPage < $showAll) {
2081 $pages = range(1, $nbTotalPage);
2082 } else {
2083 $pages = array();
2085 // Always show first X pages
2086 for ($i = 1; $i <= $sliceStart; $i++) {
2087 $pages[] = $i;
2090 // Always show last X pages
2091 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2092 $pages[] = $i;
2095 // garvin: Based on the number of results we add the specified
2096 // $percent percentate to each page number,
2097 // so that we have a representing page number every now and then to
2098 // immideately jump to specific pages.
2099 // As soon as we get near our currently chosen page ($pageNow -
2100 // $range), every page number will be
2101 // shown.
2102 $i = $sliceStart;
2103 $x = $nbTotalPage - $sliceEnd;
2104 $met_boundary = false;
2105 while ($i <= $x) {
2106 if ($i >= ($pageNow - $range) && $i <= ($pageNow + $range)) {
2107 // If our pageselector comes near the current page, we use 1
2108 // counter increments
2109 $i++;
2110 $met_boundary = true;
2111 } else {
2112 // We add the percentate increment to our current page to
2113 // hop to the next one in range
2114 $i = $i + floor($nbTotalPage / $percent);
2116 // Make sure that we do not cross our boundaries.
2117 if ($i > ($pageNow - $range) && !$met_boundary) {
2118 $i = $pageNow - $range;
2122 if ($i > 0 && $i <= $x) {
2123 $pages[] = $i;
2127 // Since because of ellipsing of the current page some numbers may be double,
2128 // we unify our array:
2129 sort($pages);
2130 $pages = array_unique($pages);
2133 foreach ($pages as $i) {
2134 if ($i == $pageNow) {
2135 $selected = 'selected="selected" style="font-weight: bold"';
2136 } else {
2137 $selected = '';
2139 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2142 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2145 return $gotopage;
2146 } // end function
2150 * Generate navigation for a list
2152 * @todo use $pos from $_url_params
2153 * @uses $GLOBALS['strPageNumber']
2154 * @uses range()
2155 * @param integer number of elements in the list
2156 * @param integer current position in the list
2157 * @param array url parameters
2158 * @param string script name for form target
2159 * @param string target frame
2160 * @param integer maximum number of elements to display from the list
2162 * @access public
2164 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2166 if ($max_count < $count) {
2167 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2168 echo $GLOBALS['strPageNumber'];
2169 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2171 // Move to the beginning or to the previous page
2172 if ($pos > 0) {
2173 // loic1: patch #474210 from Gosha Sakovich - part 1
2174 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2175 $caption1 = '&lt;&lt;';
2176 $caption2 = ' &lt; ';
2177 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2178 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2179 } else {
2180 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2181 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2182 $title1 = '';
2183 $title2 = '';
2184 } // end if... else...
2185 $_url_params['pos'] = 0;
2186 echo '<a' . $title1 . ' href="' . $script
2187 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2188 . $caption1 . '</a>';
2189 $_url_params['pos'] = $pos - $max_count;
2190 echo '<a' . $title2 . ' href="' . $script
2191 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2192 . $caption2 . '</a>';
2195 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2196 echo PMA_generate_common_hidden_inputs($_url_params);
2197 echo PMA_pageselector(
2198 $script . PMA_generate_common_url($_url_params) . '&',
2199 $max_count,
2200 floor(($pos + 1) / $max_count) + 1,
2201 ceil($count / $max_count));
2202 echo '</form>';
2204 if ($pos + $max_count < $count) {
2205 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2206 $caption3 = ' &gt; ';
2207 $caption4 = '&gt;&gt;';
2208 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2209 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2210 } else {
2211 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2212 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2213 $title3 = '';
2214 $title4 = '';
2215 } // end if... else...
2216 $_url_params['pos'] = $pos + $max_count;
2217 echo '<a' . $title3 . ' href="' . $script
2218 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2219 . $caption3 . '</a>';
2220 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2221 if ($_url_params['pos'] == $count) {
2222 $_url_params['pos'] = $count - $max_count;
2224 echo '<a' . $title4 . ' href="' . $script
2225 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2226 . $caption4 . '</a>';
2228 echo "\n";
2229 if ('frame_navigation' == $frame) {
2230 echo '</div>' . "\n";
2236 * replaces %u in given path with current user name
2238 * example:
2239 * <code>
2240 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2242 * </code>
2243 * @uses $cfg['Server']['user']
2244 * @uses substr()
2245 * @uses str_replace()
2246 * @param string $dir with wildcard for user
2247 * @return string per user directory
2249 function PMA_userDir($dir)
2251 // add trailing slash
2252 if (substr($dir, -1) != '/') {
2253 $dir .= '/';
2256 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2260 * returns html code for db link to default db page
2262 * @uses $cfg['DefaultTabDatabase']
2263 * @uses $GLOBALS['db']
2264 * @uses $GLOBALS['strJumpToDB']
2265 * @uses PMA_generate_common_url()
2266 * @uses PMA_unescape_mysql_wildcards()
2267 * @uses strlen()
2268 * @uses sprintf()
2269 * @uses htmlspecialchars()
2270 * @param string $database
2271 * @return string html link to default db page
2273 function PMA_getDbLink($database = null)
2275 if (!strlen($database)) {
2276 if (!strlen($GLOBALS['db'])) {
2277 return '';
2279 $database = $GLOBALS['db'];
2280 } else {
2281 $database = PMA_unescape_mysql_wildcards($database);
2284 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2285 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2286 .htmlspecialchars($database) . '</a>';
2290 * Displays a lightbulb hint explaining a known external bug
2291 * that affects a functionality
2293 * @uses PMA_MYSQL_INT_VERSION
2294 * @uses $GLOBALS['strKnownExternalBug']
2295 * @uses PMA_showHint()
2296 * @uses sprintf()
2297 * @param string $functionality localized message explaining the func.
2298 * @param string $component 'mysql' (eventually, 'php')
2299 * @param string $minimum_version of this component
2300 * @param string $bugref bug reference for this component
2302 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2304 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2305 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));