new language: uzbek (cyrillic and latin)
[phpmyadmin/crack.git] / libraries / common.lib.php
blob25c6f00521b6f575a05a702b2e9c6705e78655a7
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 * @package phpMyAdmin
8 */
10 /**
11 * Exponential expression / raise number into power
13 * @uses function_exists()
14 * @uses bcpow()
15 * @uses gmp_pow()
16 * @uses gmp_strval()
17 * @uses pow()
18 * @param number $base
19 * @param number $exp
20 * @param string pow function use, or false for auto-detect
21 * @return mixed string or float
23 function PMA_pow($base, $exp, $use_function = false)
25 static $pow_function = null;
27 if ($exp < 0) {
28 return false;
31 if (null == $pow_function) {
32 if (function_exists('bcpow')) {
33 // BCMath Arbitrary Precision Mathematics Function
34 $pow_function = 'bcpow';
35 } elseif (function_exists('gmp_pow')) {
36 // GMP Function
37 $pow_function = 'gmp_pow';
38 } else {
39 // PHP function
40 $pow_function = 'pow';
44 if (! $use_function) {
45 $use_function = $pow_function;
48 switch ($use_function) {
49 case 'bcpow' :
50 // bcscale() needed for testing PMA_pow() with base values < 1
51 bcscale(10);
52 $pow = bcpow($base, $exp);
53 break;
54 case 'gmp_pow' :
55 $pow = gmp_strval(gmp_pow($base, $exp));
56 break;
57 case 'pow' :
58 $base = (float) $base;
59 $exp = (int) $exp;
60 $pow = pow($base, $exp);
61 break;
62 default:
63 $pow = $use_function($base, $exp);
66 return $pow;
69 /**
70 * string PMA_getIcon(string $icon)
72 * @uses $GLOBALS['pmaThemeImage']
73 * @uses $GLOBALS['cfg']['PropertiesIconic']
74 * @uses htmlspecialchars()
75 * @param string $icon name of icon file
76 * @param string $alternate alternate text
77 * @param boolean $container include in container
78 * @param boolean $$force_text whether to force alternate text to be displayed
79 * @return html img tag
81 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
83 $include_icon = false;
84 $include_text = false;
85 $include_box = false;
86 $alternate = htmlspecialchars($alternate);
87 $button = '';
89 if ($GLOBALS['cfg']['PropertiesIconic']) {
90 $include_icon = true;
93 if ($force_text
94 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
95 || ! $include_icon) {
96 // $cfg['PropertiesIconic'] is false or both
97 // OR we have no $include_icon
98 $include_text = true;
101 if ($include_text && $include_icon && $container) {
102 // we have icon, text and request for container
103 $include_box = true;
106 if ($include_box) {
107 $button .= '<div class="nowrap">';
110 if ($include_icon) {
111 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
112 . ' title="' . $alternate . '" alt="' . $alternate . '"'
113 . ' class="icon" width="16" height="16" />';
116 if ($include_icon && $include_text) {
117 $button .= ' ';
120 if ($include_text) {
121 $button .= $alternate;
124 if ($include_box) {
125 $button .= '</div>';
128 return $button;
132 * Displays the maximum size for an upload
134 * @uses $GLOBALS['strMaximumSize']
135 * @uses PMA_formatByteDown()
136 * @uses sprintf()
137 * @param integer the size
139 * @return string the message
141 * @access public
143 function PMA_displayMaximumUploadSize($max_upload_size)
145 // I have to reduce the second parameter (sensitiveness) from 6 to 4
146 // to avoid weird results like 512 kKib
147 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
148 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
152 * Generates a hidden field which should indicate to the browser
153 * the maximum size for upload
155 * @param integer the size
157 * @return string the INPUT field
159 * @access public
161 function PMA_generateHiddenMaxFileSize($max_size)
163 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
167 * Add slashes before "'" and "\" characters so a value containing them can
168 * be used in a sql comparison.
170 * @uses str_replace()
171 * @param string the string to slash
172 * @param boolean whether the string will be used in a 'LIKE' clause
173 * (it then requires two more escaped sequences) or not
174 * @param boolean whether to treat cr/lfs as escape-worthy entities
175 * (converts \n to \\n, \r to \\r)
177 * @param boolean whether this function is used as part of the
178 * "Create PHP code" dialog
180 * @return string the slashed string
182 * @access public
184 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
186 if ($is_like) {
187 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
188 } else {
189 $a_string = str_replace('\\', '\\\\', $a_string);
192 if ($crlf) {
193 $a_string = str_replace("\n", '\n', $a_string);
194 $a_string = str_replace("\r", '\r', $a_string);
195 $a_string = str_replace("\t", '\t', $a_string);
198 if ($php_code) {
199 $a_string = str_replace('\'', '\\\'', $a_string);
200 } else {
201 $a_string = str_replace('\'', '\'\'', $a_string);
204 return $a_string;
205 } // end of the 'PMA_sqlAddslashes()' function
209 * Add slashes before "_" and "%" characters for using them in MySQL
210 * database, table and field names.
211 * Note: This function does not escape backslashes!
213 * @uses str_replace()
214 * @param string the string to escape
216 * @return string the escaped string
218 * @access public
220 function PMA_escape_mysql_wildcards($name)
222 $name = str_replace('_', '\\_', $name);
223 $name = str_replace('%', '\\%', $name);
225 return $name;
226 } // end of the 'PMA_escape_mysql_wildcards()' function
229 * removes slashes before "_" and "%" characters
230 * Note: This function does not unescape backslashes!
232 * @uses str_replace()
233 * @param string $name the string to escape
234 * @return string the escaped string
235 * @access public
237 function PMA_unescape_mysql_wildcards($name)
239 $name = str_replace('\\_', '_', $name);
240 $name = str_replace('\\%', '%', $name);
242 return $name;
243 } // end of the 'PMA_unescape_mysql_wildcards()' function
246 * removes quotes (',",`) from a quoted string
248 * checks if the sting is quoted and removes this quotes
250 * @uses str_replace()
251 * @uses substr()
252 * @param string $quoted_string string to remove quotes from
253 * @param string $quote type of quote to remove
254 * @return string unqoted string
256 function PMA_unQuote($quoted_string, $quote = null)
258 $quotes = array();
260 if (null === $quote) {
261 $quotes[] = '`';
262 $quotes[] = '"';
263 $quotes[] = "'";
264 } else {
265 $quotes[] = $quote;
268 foreach ($quotes as $quote) {
269 if (substr($quoted_string, 0, 1) === $quote
270 && substr($quoted_string, -1, 1) === $quote) {
271 $unquoted_string = substr($quoted_string, 1, -1);
272 // replace escaped quotes
273 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
274 return $unquoted_string;
278 return $quoted_string;
282 * format sql strings
284 * @todo move into PMA_Sql
285 * @uses PMA_SQP_isError()
286 * @uses PMA_SQP_formatHtml()
287 * @uses PMA_SQP_formatNone()
288 * @uses is_array()
289 * @param mixed pre-parsed SQL structure
291 * @return string the formatted sql
293 * @global array the configuration array
294 * @global boolean whether the current statement is a multiple one or not
296 * @access public
298 * @author Robin Johnson <robbat2@users.sourceforge.net>
300 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
302 global $cfg;
304 // Check that we actually have a valid set of parsed data
305 // well, not quite
306 // first check for the SQL parser having hit an error
307 if (PMA_SQP_isError()) {
308 return htmlspecialchars($parsed_sql['raw']);
310 // then check for an array
311 if (!is_array($parsed_sql)) {
312 // We don't so just return the input directly
313 // This is intended to be used for when the SQL Parser is turned off
314 $formatted_sql = '<pre>' . "\n"
315 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
316 . '</pre>';
317 return $formatted_sql;
320 $formatted_sql = '';
322 switch ($cfg['SQP']['fmtType']) {
323 case 'none':
324 if ($unparsed_sql != '') {
325 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
326 } else {
327 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
329 break;
330 case 'html':
331 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
332 break;
333 case 'text':
334 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
335 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
336 break;
337 default:
338 break;
339 } // end switch
341 return $formatted_sql;
342 } // end of the "PMA_formatSql()" function
346 * Displays a link to the official MySQL documentation
348 * @uses $cfg['MySQLManualType']
349 * @uses $cfg['MySQLManualBase']
350 * @uses $cfg['ReplaceHelpImg']
351 * @uses $GLOBALS['mysql_4_1_doc_lang']
352 * @uses $GLOBALS['mysql_5_1_doc_lang']
353 * @uses $GLOBALS['mysql_5_0_doc_lang']
354 * @uses $GLOBALS['strDocu']
355 * @uses $GLOBALS['pmaThemeImage']
356 * @uses PMA_MYSQL_INT_VERSION
357 * @uses strtolower()
358 * @uses str_replace()
359 * @param string chapter of "HTML, one page per chapter" documentation
360 * @param string contains name of page/anchor that is being linked
361 * @param bool whether to use big icon (like in left frame)
362 * @param string anchor to page part
364 * @return string the html link
366 * @access public
368 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '')
370 global $cfg;
372 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
373 return '';
376 // Fixup for newly used names:
377 $chapter = str_replace('_', '-', strtolower($chapter));
378 $link = str_replace('_', '-', strtolower($link));
380 switch ($cfg['MySQLManualType']) {
381 case 'chapters':
382 if (empty($chapter)) {
383 $chapter = 'index';
385 if (empty($anchor)) {
386 $anchor = $link;
388 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
389 break;
390 case 'big':
391 if (empty($anchor)) {
392 $anchor = $link;
394 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
395 break;
396 case 'searchable':
397 if (empty($link)) {
398 $link = 'index';
400 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
401 if (!empty($anchor)) {
402 $url .= '#' . $anchor;
404 break;
405 case 'viewable':
406 default:
407 if (empty($link)) {
408 $link = 'index';
410 $mysql = '5.0';
411 $lang = 'en';
412 if (defined('PMA_MYSQL_INT_VERSION')) {
413 if (PMA_MYSQL_INT_VERSION >= 50100) {
414 $mysql = '5.1';
415 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
416 $lang = $GLOBALS['mysql_5_1_doc_lang'];
418 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
419 $mysql = '5.0';
420 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
421 $lang = $GLOBALS['mysql_5_0_doc_lang'];
425 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
426 if (!empty($anchor)) {
427 $url .= '#' . $anchor;
429 break;
432 if ($big_icon) {
433 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>';
434 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
435 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>';
436 } else {
437 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
439 } // end of the 'PMA_showMySQLDocu()' function
442 * returns HTML for a footnote marker and add the messsage to the footnotes
444 * @uses $GLOBALS['footnotes']
445 * @param string the error message
446 * @return string html code for a footnote marker
447 * @access public
449 function PMA_showHint($message, $bbcode = false, $type = 'notice')
451 if ($message instanceof PMA_Message) {
452 $key = $message->getHash();
453 $type = $message->getLevel();
454 } else {
455 $key = md5($message);
458 if (! isset($GLOBALS['footnotes'][$key])) {
459 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
460 $GLOBALS['footnotes'] = array();
462 $nr = count($GLOBALS['footnotes']) + 1;
463 // this is the first instance of this message
464 $instance = 1;
465 $GLOBALS['footnotes'][$key] = array(
466 'note' => $message,
467 'type' => $type,
468 'nr' => $nr,
469 'instance' => $instance
471 } else {
472 $nr = $GLOBALS['footnotes'][$key]['nr'];
473 // another instance of this message (to ensure ids are unique)
474 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
477 if ($bbcode) {
478 return '[sup]' . $nr . '[/sup]';
481 // footnotemarker used in js/tooltip.js
482 return '<sup class="footnotemarker" id="footnote_sup_' . $nr . '_' . $instance . '">' . $nr . '</sup>';
486 * Displays a MySQL error message in the right frame.
488 * @uses footer.inc.php
489 * @uses header.inc.php
490 * @uses $GLOBALS['sql_query']
491 * @uses $GLOBALS['strError']
492 * @uses $GLOBALS['strSQLQuery']
493 * @uses $GLOBALS['pmaThemeImage']
494 * @uses $GLOBALS['strEdit']
495 * @uses $GLOBALS['strMySQLSaid']
496 * @uses $GLOBALS['cfg']['PropertiesIconic']
497 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
498 * @uses PMA_backquote()
499 * @uses PMA_DBI_getError()
500 * @uses PMA_formatSql()
501 * @uses PMA_generate_common_hidden_inputs()
502 * @uses PMA_generate_common_url()
503 * @uses PMA_showMySQLDocu()
504 * @uses PMA_sqlAddslashes()
505 * @uses PMA_SQP_isError()
506 * @uses PMA_SQP_parse()
507 * @uses PMA_SQP_getErrorString()
508 * @uses strtolower()
509 * @uses urlencode()
510 * @uses str_replace()
511 * @uses nl2br()
512 * @uses substr()
513 * @uses preg_replace()
514 * @uses preg_match()
515 * @uses explode()
516 * @uses implode()
517 * @uses is_array()
518 * @uses function_exists()
519 * @uses htmlspecialchars()
520 * @uses trim()
521 * @uses strstr()
522 * @param string the error message
523 * @param string the sql query that failed
524 * @param boolean whether to show a "modify" link or not
525 * @param string the "back" link url (full path is not required)
526 * @param boolean EXIT the page?
528 * @global string the curent table
529 * @global string the current db
531 * @access public
533 function PMA_mysqlDie($error_message = '', $the_query = '',
534 $is_modify_link = true, $back_url = '', $exit = true)
536 global $table, $db;
539 * start http output, display html headers
541 require_once './libraries/header.inc.php';
543 if (!$error_message) {
544 $error_message = PMA_DBI_getError();
546 if (!$the_query && !empty($GLOBALS['sql_query'])) {
547 $the_query = $GLOBALS['sql_query'];
550 // --- Added to solve bug #641765
551 // Robbat2 - 12 January 2003, 9:46PM
552 // Revised, Robbat2 - 13 January 2003, 2:59PM
553 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
554 $formatted_sql = htmlspecialchars($the_query);
555 } elseif (empty($the_query) || trim($the_query) == '') {
556 $formatted_sql = '';
557 } else {
558 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
559 $formatted_sql = substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]';
560 } else {
561 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
564 // ---
565 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
566 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
567 // if the config password is wrong, or the MySQL server does not
568 // respond, do not show the query that would reveal the
569 // username/password
570 if (!empty($the_query) && !strstr($the_query, 'connect')) {
571 // --- Added to solve bug #641765
572 // Robbat2 - 12 January 2003, 9:46PM
573 // Revised, Robbat2 - 13 January 2003, 2:59PM
574 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
575 echo PMA_SQP_getErrorString() . "\n";
576 echo '<br />' . "\n";
578 // ---
579 // modified to show me the help on sql errors (Michael Keck)
580 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
581 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
582 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
584 if ($is_modify_link) {
585 $_url_params = array(
586 'sql_query' => $the_query,
587 'show_query' => 1,
589 if (strlen($table)) {
590 $_url_params['db'] = $db;
591 $_url_params['table'] = $table;
592 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
593 } elseif (strlen($db)) {
594 $_url_params['db'] = $db;
595 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
596 } else {
597 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
600 echo $doedit_goto
601 . PMA_getIcon('b_edit.png', $GLOBALS['strEdit'])
602 . '</a>';
603 } // end if
604 echo ' </p>' . "\n"
605 .' <p>' . "\n"
606 .' ' . $formatted_sql . "\n"
607 .' </p>' . "\n";
608 } // end if
610 $tmp_mysql_error = ''; // for saving the original $error_message
611 if (!empty($error_message)) {
612 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
613 $error_message = htmlspecialchars($error_message);
614 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
616 // modified to show me the help on error-returns (Michael Keck)
617 // (now error-messages-server)
618 echo '<p>' . "\n"
619 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
620 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
621 . "\n"
622 . '</p>' . "\n";
624 // The error message will be displayed within a CODE segment.
625 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
627 // Replace all non-single blanks with their HTML-counterpart
628 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
629 // Replace TAB-characters with their HTML-counterpart
630 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
631 // Replace linebreaks
632 $error_message = nl2br($error_message);
634 echo '<code>' . "\n"
635 . $error_message . "\n"
636 . '</code><br />' . "\n";
637 echo '</div>';
639 if ($exit) {
640 if (! empty($back_url)) {
641 if (strstr($back_url, '?')) {
642 $back_url .= '&amp;no_history=true';
643 } else {
644 $back_url .= '?no_history=true';
646 echo '<fieldset class="tblFooters">';
647 echo '[ <a href="' . $back_url . '">' . $GLOBALS['strBack'] . '</a> ]';
648 echo '</fieldset>' . "\n\n";
651 * display footer and exit
653 require_once './libraries/footer.inc.php';
655 } // end of the 'PMA_mysqlDie()' function
658 * Send HTTP header, taking IIS limits into account (600 seems ok)
660 * @uses PMA_IS_IIS
661 * @uses PMA_COMING_FROM_COOKIE_LOGIN
662 * @uses PMA_get_arg_separator()
663 * @uses SID
664 * @uses strlen()
665 * @uses strpos()
666 * @uses header()
667 * @uses session_write_close()
668 * @uses headers_sent()
669 * @uses function_exists()
670 * @uses debug_print_backtrace()
671 * @uses trigger_error()
672 * @uses defined()
673 * @param string $uri the header to send
674 * @return boolean always true
676 function PMA_sendHeaderLocation($uri)
678 if (PMA_IS_IIS && strlen($uri) > 600) {
680 echo '<html><head><title>- - -</title>' . "\n";
681 echo '<meta http-equiv="expires" content="0">' . "\n";
682 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
683 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
684 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
685 echo '<script type="text/javascript">' . "\n";
686 echo '//<![CDATA[' . "\n";
687 echo 'setTimeout("window.location = unescape(\'"' . $uri . '"\')", 2000);' . "\n";
688 echo '//]]>' . "\n";
689 echo '</script>' . "\n";
690 echo '</head>' . "\n";
691 echo '<body>' . "\n";
692 echo '<script type="text/javascript">' . "\n";
693 echo '//<![CDATA[' . "\n";
694 echo 'document.write(\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
695 echo '//]]>' . "\n";
696 echo '</script></body></html>' . "\n";
698 } else {
699 if (SID) {
700 if (strpos($uri, '?') === false) {
701 header('Location: ' . $uri . '?' . SID);
702 } else {
703 $separator = PMA_get_arg_separator();
704 header('Location: ' . $uri . $separator . SID);
706 } else {
707 session_write_close();
708 if (headers_sent()) {
709 if (function_exists('debug_print_backtrace')) {
710 echo '<pre>';
711 debug_print_backtrace();
712 echo '</pre>';
714 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
716 // bug #1523784: IE6 does not like 'Refresh: 0', it
717 // results in a blank page
718 // but we need it when coming from the cookie login panel)
719 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
720 header('Refresh: 0; ' . $uri);
721 } else {
722 header('Location: ' . $uri);
729 * returns array with tables of given db with extended information and grouped
731 * @uses $cfg['LeftFrameTableSeparator']
732 * @uses $cfg['LeftFrameTableLevel']
733 * @uses $cfg['ShowTooltipAliasTB']
734 * @uses $cfg['NaturalOrder']
735 * @uses PMA_backquote()
736 * @uses count()
737 * @uses array_merge
738 * @uses uksort()
739 * @uses strstr()
740 * @uses explode()
741 * @param string $db name of db
742 * @param string $tables name of tables
743 * @param integer $limit_offset list offset
744 * @param integer $limit_count max tables to return
745 * return array (recursive) grouped table list
747 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
749 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
751 if (null === $tables) {
752 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
753 if ($GLOBALS['cfg']['NaturalOrder']) {
754 uksort($tables, 'strnatcasecmp');
758 if (count($tables) < 1) {
759 return $tables;
762 $default = array(
763 'Name' => '',
764 'Rows' => 0,
765 'Comment' => '',
766 'disp_name' => '',
769 $table_groups = array();
771 // for blobstreaming - list of blobstreaming tables - rajk
773 // load PMA configuration
774 $PMA_Config = $_SESSION['PMA_Config'];
776 // if PMA configuration exists
777 if (!empty($PMA_Config))
778 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
780 foreach ($tables as $table_name => $table) {
781 // if BS tables exist
782 if (isset($session_bs_tables))
783 // compare table name to tables in list of blobstreaming tables
784 foreach ($session_bs_tables as $table_key=>$table_val)
785 // if table is in list, skip outer foreach loop
786 if ($table_name == $table_key)
787 continue 2;
789 // check for correct row count
790 if (null === $table['Rows']) {
791 // Do not check exact row count here,
792 // if row count is invalid possibly the table is defect
793 // and this would break left frame;
794 // but we can check row count if this is a view or the
795 // information_schema database
796 // since PMA_Table::countRecords() returns a limited row count
797 // in this case.
799 // set this because PMA_Table::countRecords() can use it
800 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
802 if ($tbl_is_view || 'information_schema' == $db) {
803 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
804 $return = true);
808 // in $group we save the reference to the place in $table_groups
809 // where to store the table info
810 if ($GLOBALS['cfg']['LeftFrameDBTree']
811 && $sep && strstr($table_name, $sep))
813 $parts = explode($sep, $table_name);
815 $group =& $table_groups;
816 $i = 0;
817 $group_name_full = '';
818 $parts_cnt = count($parts) - 1;
819 while ($i < $parts_cnt
820 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
821 $group_name = $parts[$i] . $sep;
822 $group_name_full .= $group_name;
824 if (!isset($group[$group_name])) {
825 $group[$group_name] = array();
826 $group[$group_name]['is' . $sep . 'group'] = true;
827 $group[$group_name]['tab' . $sep . 'count'] = 1;
828 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
829 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
830 $table = $group[$group_name];
831 $group[$group_name] = array();
832 $group[$group_name][$group_name] = $table;
833 unset($table);
834 $group[$group_name]['is' . $sep . 'group'] = true;
835 $group[$group_name]['tab' . $sep . 'count'] = 1;
836 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
837 } else {
838 $group[$group_name]['tab' . $sep . 'count']++;
840 $group =& $group[$group_name];
841 $i++;
843 } else {
844 if (!isset($table_groups[$table_name])) {
845 $table_groups[$table_name] = array();
847 $group =& $table_groups;
851 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
852 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
853 // switch tooltip and name
854 $table['Comment'] = $table['Name'];
855 $table['disp_name'] = $table['Comment'];
856 } else {
857 $table['disp_name'] = $table['Name'];
860 $group[$table_name] = array_merge($default, $table);
863 return $table_groups;
866 /* ----------------------- Set of misc functions ----------------------- */
870 * Adds backquotes on both sides of a database, table or field name.
871 * and escapes backquotes inside the name with another backquote
873 * example:
874 * <code>
875 * echo PMA_backquote('owner`s db'); // `owner``s db`
877 * </code>
879 * @uses PMA_backquote()
880 * @uses is_array()
881 * @uses strlen()
882 * @uses str_replace()
883 * @param mixed $a_name the database, table or field name to "backquote"
884 * or array of it
885 * @param boolean $do_it a flag to bypass this function (used by dump
886 * functions)
887 * @return mixed the "backquoted" database, table or field name if the
888 * current MySQL release is >= 3.23.6, the original one
889 * else
890 * @access public
892 function PMA_backquote($a_name, $do_it = true)
894 if (! $do_it) {
895 return $a_name;
898 if (is_array($a_name)) {
899 $result = array();
900 foreach ($a_name as $key => $val) {
901 $result[$key] = PMA_backquote($val);
903 return $result;
906 // '0' is also empty for php :-(
907 if (strlen($a_name) && $a_name !== '*') {
908 return '`' . str_replace('`', '``', $a_name) . '`';
909 } else {
910 return $a_name;
912 } // end of the 'PMA_backquote()' function
916 * Defines the <CR><LF> value depending on the user OS.
918 * @uses PMA_USR_OS
919 * @return string the <CR><LF> value to use
921 * @access public
923 function PMA_whichCrlf()
925 $the_crlf = "\n";
927 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
928 // Win case
929 if (PMA_USR_OS == 'Win') {
930 $the_crlf = "\r\n";
932 // Others
933 else {
934 $the_crlf = "\n";
937 return $the_crlf;
938 } // end of the 'PMA_whichCrlf()' function
941 * Reloads navigation if needed.
943 * @uses $GLOBALS['reload']
944 * @uses $GLOBALS['db']
945 * @uses PMA_generate_common_url()
946 * @global array configuration
948 * @access public
950 function PMA_reloadNavigation()
952 global $cfg;
954 // Reloads the navigation frame via JavaScript if required
955 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
956 // one of the reasons for a reload is when a table is dropped
957 // in this case, get rid of the table limit offset, otherwise
958 // we have a problem when dropping a table on the last page
959 // and the offset becomes greater than the total number of tables
960 unset($_SESSION['userconf']['table_limit_offset']);
961 echo "\n";
962 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
964 <script type="text/javascript">
965 //<![CDATA[
966 if (typeof(window.parent) != 'undefined'
967 && typeof(window.parent.frame_navigation) != 'undefined'
968 && window.parent.goTo) {
969 window.parent.goTo('<?php echo $reload_url; ?>');
971 //]]>
972 </script>
973 <?php
974 unset($GLOBALS['reload']);
979 * displays the message and the query
980 * usually the message is the result of the query executed
982 * @param string $message the message to display
983 * @param string $sql_query the query to display
984 * @param string $type the type (level) of the message
985 * @global array the configuration array
986 * @uses $cfg
987 * @access public
989 function PMA_showMessage($message, $sql_query = null, $type = 'notice')
991 global $cfg;
993 if (null === $sql_query) {
994 if (! empty($GLOBALS['display_query'])) {
995 $sql_query = $GLOBALS['display_query'];
996 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
997 $sql_query = $GLOBALS['unparsed_sql'];
998 } elseif (! empty($GLOBALS['sql_query'])) {
999 $sql_query = $GLOBALS['sql_query'];
1000 } else {
1001 $sql_query = '';
1005 // Corrects the tooltip text via JS if required
1006 // @todo this is REALLY the wrong place to do this - very unexpected here
1007 if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1008 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
1009 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1010 echo "\n";
1011 echo '<script type="text/javascript">' . "\n";
1012 echo '//<![CDATA[' . "\n";
1013 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
1014 echo '//]]>' . "\n";
1015 echo '</script>' . "\n";
1016 } // end if ... elseif
1018 // Checks if the table needs to be repaired after a TRUNCATE query.
1019 // @todo what about $GLOBALS['display_query']???
1020 // @todo this is REALLY the wrong place to do this - very unexpected here
1021 if (strlen($GLOBALS['table'])
1022 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1023 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1024 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1027 unset($tbl_status);
1029 echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
1031 if ($message instanceof PMA_Message) {
1032 if (isset($GLOBALS['special_message'])) {
1033 $message->addMessage($GLOBALS['special_message']);
1034 unset($GLOBALS['special_message']);
1036 $message->display();
1037 $type = $message->getLevel();
1038 } else {
1039 echo '<div class="' . $type . '">';
1040 echo PMA_sanitize($message);
1041 if (isset($GLOBALS['special_message'])) {
1042 echo PMA_sanitize($GLOBALS['special_message']);
1043 unset($GLOBALS['special_message']);
1045 echo '</div>';
1048 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1049 // Html format the query to be displayed
1050 // If we want to show some sql code it is easiest to create it here
1051 /* SQL-Parser-Analyzer */
1053 if (! empty($GLOBALS['show_as_php'])) {
1054 $new_line = '\\n"<br />' . "\n"
1055 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1056 $query_base = htmlspecialchars(addslashes($sql_query));
1057 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1058 } else {
1059 $query_base = $sql_query;
1062 $query_too_big = false;
1064 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1065 // when the query is large (for example an INSERT of binary
1066 // data), the parser chokes; so avoid parsing the query
1067 $query_too_big = true;
1068 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1069 } elseif (! empty($GLOBALS['parsed_sql'])
1070 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1071 // (here, use "! empty" because when deleting a bookmark,
1072 // $GLOBALS['parsed_sql'] is set but empty
1073 $parsed_sql = $GLOBALS['parsed_sql'];
1074 } else {
1075 // Parse SQL if needed
1076 $parsed_sql = PMA_SQP_parse($query_base);
1079 // Analyze it
1080 if (isset($parsed_sql)) {
1081 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1082 // Here we append the LIMIT added for navigation, to
1083 // enable its display. Adding it higher in the code
1084 // to $sql_query would create a problem when
1085 // using the Refresh or Edit links.
1087 // Only append it on SELECTs.
1090 * @todo what would be the best to do when someone hits Refresh:
1091 * use the current LIMITs ?
1094 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1095 && isset($GLOBALS['sql_limit_to_append'])) {
1096 $query_base = $analyzed_display_query[0]['section_before_limit']
1097 . "\n" . $GLOBALS['sql_limit_to_append']
1098 . $analyzed_display_query[0]['section_after_limit'];
1099 // Need to reparse query
1100 $parsed_sql = PMA_SQP_parse($query_base);
1104 if (! empty($GLOBALS['show_as_php'])) {
1105 $query_base = '$sql = "' . $query_base;
1106 } elseif (! empty($GLOBALS['validatequery'])) {
1107 $query_base = PMA_validateSQL($query_base);
1108 } elseif (isset($parsed_sql)) {
1109 $query_base = PMA_formatSql($parsed_sql, $query_base);
1112 // Prepares links that may be displayed to edit/explain the query
1113 // (don't go to default pages, we must go to the page
1114 // where the query box is available)
1116 // Basic url query part
1117 $url_params = array();
1118 if (strlen($GLOBALS['db'])) {
1119 $url_params['db'] = $GLOBALS['db'];
1120 if (strlen($GLOBALS['table'])) {
1121 $url_params['table'] = $GLOBALS['table'];
1122 $edit_link = 'tbl_sql.php';
1123 } else {
1124 $edit_link = 'db_sql.php';
1126 } else {
1127 $edit_link = 'server_sql.php';
1130 // Want to have the query explained (Mike Beck 2002-05-22)
1131 // but only explain a SELECT (that has not been explained)
1132 /* SQL-Parser-Analyzer */
1133 $explain_link = '';
1134 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1135 $explain_params = $url_params;
1136 // Detect if we are validating as well
1137 // To preserve the validate uRL data
1138 if (! empty($GLOBALS['validatequery'])) {
1139 $explain_params['validatequery'] = 1;
1142 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1143 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1144 $_message = $GLOBALS['strExplain'];
1145 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1146 $explain_params['sql_query'] = substr($sql_query, 8);
1147 $_message = $GLOBALS['strNoExplain'];
1149 if (isset($explain_params['sql_query'])) {
1150 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1151 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1153 } //show explain
1155 $url_params['sql_query'] = $sql_query;
1156 $url_params['show_query'] = 1;
1158 if (! empty($cfg['SQLQuery']['Edit']) && ! $query_too_big) {
1159 if ($cfg['EditInWindow'] == true) {
1160 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1161 } else {
1162 $onclick = '';
1165 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1166 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1167 } else {
1168 $edit_link = '';
1171 $url_qpart = PMA_generate_common_url($url_params);
1173 // Also we would like to get the SQL formed in some nice
1174 // php-code (Mike Beck 2002-05-22)
1175 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1176 $php_params = $url_params;
1178 if (! empty($GLOBALS['show_as_php'])) {
1179 $_message = $GLOBALS['strNoPhp'];
1180 } else {
1181 $php_params['show_as_php'] = 1;
1182 $_message = $GLOBALS['strPhp'];
1185 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1186 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1188 if (isset($GLOBALS['show_as_php'])) {
1189 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1190 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1192 } else {
1193 $php_link = '';
1194 } //show as php
1196 // Refresh query
1197 if (! empty($cfg['SQLQuery']['Refresh'])
1198 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1199 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1200 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1201 } else {
1202 $refresh_link = '';
1203 } //show as php
1205 if (! empty($cfg['SQLValidator']['use'])
1206 && ! empty($cfg['SQLQuery']['Validate'])) {
1207 $validate_params = $url_params;
1208 if (!empty($GLOBALS['validatequery'])) {
1209 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1210 } else {
1211 $validate_params['validatequery'] = 1;
1212 $validate_message = $GLOBALS['strValidateSQL'] ;
1215 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1216 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1217 } else {
1218 $validate_link = '';
1219 } //validator
1221 echo '<code class="sql">';
1222 if ($query_too_big) {
1223 echo $shortened_query_base;
1224 } else {
1225 echo $query_base;
1228 //Clean up the end of the PHP
1229 if (! empty($GLOBALS['show_as_php'])) {
1230 echo '";';
1232 echo '</code>';
1234 echo '<div class="tools">';
1235 // avoid displaying a Profiling checkbox that could
1236 // be checked, which would reexecute an INSERT, for example
1237 if (! empty($refresh_link)) {
1238 PMA_profilingCheckbox($sql_query);
1240 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1241 echo '</div>';
1243 echo '</div><br />' . "\n";
1244 } // end of the 'PMA_showMessage()' function
1247 * Verifies if current MySQL server supports profiling
1249 * @uses $_SESSION['profiling_supported'] for caching
1250 * @uses $GLOBALS['server']
1251 * @uses PMA_DBI_fetch_value()
1252 * @uses PMA_MYSQL_INT_VERSION
1253 * @uses defined()
1254 * @access public
1255 * @return boolean whether profiling is supported
1257 * @author Marc Delisle
1259 function PMA_profilingSupported()
1261 if (! PMA_cacheExists('profiling_supported', true)) {
1262 // 5.0.37 has profiling but for example, 5.1.20 does not
1263 // (avoid a trip to the server for MySQL before 5.0.37)
1264 // and do not set a constant as we might be switching servers
1265 if (defined('PMA_MYSQL_INT_VERSION')
1266 && PMA_MYSQL_INT_VERSION >= 50037
1267 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1268 PMA_cacheSet('profiling_supported', true, true);
1269 } else {
1270 PMA_cacheSet('profiling_supported', false, true);
1274 return PMA_cacheGet('profiling_supported', true);
1278 * Displays a form with the Profiling checkbox
1280 * @param string $sql_query
1281 * @access public
1283 * @author Marc Delisle
1285 function PMA_profilingCheckbox($sql_query)
1287 if (PMA_profilingSupported()) {
1288 echo '<form action="sql.php" method="post">' . "\n";
1289 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1290 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1291 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1292 PMA_generate_html_checkbox('profiling', $GLOBALS['strProfiling'], isset($_SESSION['profiling']), true);
1293 echo '<noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>' . "\n";
1294 echo '</form>' . "\n";
1299 * Displays the results of SHOW PROFILE
1301 * @param array the results
1302 * @access public
1304 * @author Marc Delisle
1306 function PMA_profilingResults($profiling_results)
1308 echo '<fieldset><legend>' . $GLOBALS['strProfiling'] . '</legend>' . "\n";
1309 echo '<table>' . "\n";
1310 echo ' <tr>' . "\n";
1311 echo ' <th>' . $GLOBALS['strStatus'] . '</th>' . "\n";
1312 echo ' <th>' . $GLOBALS['strTime'] . '</th>' . "\n";
1313 echo ' </tr>' . "\n";
1315 foreach($profiling_results as $one_result) {
1316 echo ' <tr>' . "\n";
1317 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1318 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1320 echo '</table>' . "\n";
1321 echo '</fieldset>' . "\n";
1325 * Formats $value to byte view
1327 * @param double the value to format
1328 * @param integer the sensitiveness
1329 * @param integer the number of decimals to retain
1331 * @return array the formatted value and its unit
1333 * @access public
1335 * @author staybyte
1336 * @version 1.2 - 18 July 2002
1338 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1340 $dh = PMA_pow(10, $comma);
1341 $li = PMA_pow(10, $limes);
1342 $return_value = $value;
1343 $unit = $GLOBALS['byteUnits'][0];
1345 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1346 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * PMA_pow(10, $ex)) {
1347 // use 1024.0 to avoid integer overflow on 64-bit machines
1348 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1349 $unit = $GLOBALS['byteUnits'][$d];
1350 break 1;
1351 } // end if
1352 } // end for
1354 if ($unit != $GLOBALS['byteUnits'][0]) {
1355 // if the unit is not bytes (as represented in current language)
1356 // reformat with max length of 5
1357 // 4th parameter=true means do not reformat if value < 1
1358 $return_value = PMA_formatNumber($value, 5, $comma, true);
1359 } else {
1360 // do not reformat, just handle the locale
1361 $return_value = PMA_formatNumber($value, 0);
1364 return array($return_value, $unit);
1365 } // end of the 'PMA_formatByteDown' function
1368 * Formats $value to the given length and appends SI prefixes
1369 * $comma is not substracted from the length
1370 * with a $length of 0 no truncation occurs, number is only formated
1371 * to the current locale
1373 * examples:
1374 * <code>
1375 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1376 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1377 * echo PMA_formatNumber(-0.003, 6); // -3 m
1378 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1379 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1380 * echo PMA_formatNumber(0, 6); // 0
1382 * </code>
1383 * @param double $value the value to format
1384 * @param integer $length the max length
1385 * @param integer $comma the number of decimals to retain
1386 * @param boolean $only_down do not reformat numbers below 1
1388 * @return string the formatted value and its unit
1390 * @access public
1392 * @author staybyte, sebastian mendel
1393 * @version 1.1.0 - 2005-10-27
1395 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1397 //number_format is not multibyte safe, str_replace is safe
1398 if ($length === 0) {
1399 return str_replace(array(',', '.'),
1400 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1401 number_format($value, $comma));
1404 // this units needs no translation, ISO
1405 $units = array(
1406 -8 => 'y',
1407 -7 => 'z',
1408 -6 => 'a',
1409 -5 => 'f',
1410 -4 => 'p',
1411 -3 => 'n',
1412 -2 => '&micro;',
1413 -1 => 'm',
1414 0 => ' ',
1415 1 => 'k',
1416 2 => 'M',
1417 3 => 'G',
1418 4 => 'T',
1419 5 => 'P',
1420 6 => 'E',
1421 7 => 'Z',
1422 8 => 'Y'
1425 // we need at least 3 digits to be displayed
1426 if (3 > $length + $comma) {
1427 $length = 3 - $comma;
1430 // check for negative value to retain sign
1431 if ($value < 0) {
1432 $sign = '-';
1433 $value = abs($value);
1434 } else {
1435 $sign = '';
1438 $dh = PMA_pow(10, $comma);
1439 $li = PMA_pow(10, $length);
1440 $unit = $units[0];
1442 if ($value >= 1) {
1443 for ($d = 8; $d >= 0; $d--) {
1444 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1445 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1446 $unit = $units[$d];
1447 break 1;
1448 } // end if
1449 } // end for
1450 } elseif (!$only_down && (float) $value !== 0.0) {
1451 for ($d = -8; $d <= 8; $d++) {
1452 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1)) {
1453 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1454 $unit = $units[$d];
1455 break 1;
1456 } // end if
1457 } // end for
1458 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1460 //number_format is not multibyte safe, str_replace is safe
1461 $value = str_replace(array(',', '.'),
1462 array($GLOBALS['number_thousands_separator'], $GLOBALS['number_decimal_separator']),
1463 number_format($value, $comma));
1465 return $sign . $value . ' ' . $unit;
1466 } // end of the 'PMA_formatNumber' function
1469 * Writes localised date
1471 * @param string the current timestamp
1473 * @return string the formatted date
1475 * @access public
1477 function PMA_localisedDate($timestamp = -1, $format = '')
1479 global $datefmt, $month, $day_of_week;
1481 if ($format == '') {
1482 $format = $datefmt;
1485 if ($timestamp == -1) {
1486 $timestamp = time();
1489 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1490 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1492 return strftime($date, $timestamp);
1493 } // end of the 'PMA_localisedDate()' function
1497 * returns a tab for tabbed navigation.
1498 * If the variables $link and $args ar left empty, an inactive tab is created
1500 * @uses $GLOBALS['PMA_PHP_SELF']
1501 * @uses $GLOBALS['strEmpty']
1502 * @uses $GLOBALS['strDrop']
1503 * @uses $GLOBALS['active_page']
1504 * @uses $GLOBALS['url_query']
1505 * @uses $cfg['MainPageIconic']
1506 * @uses $GLOBALS['pmaThemeImage']
1507 * @uses PMA_generate_common_url()
1508 * @uses E_USER_NOTICE
1509 * @uses htmlentities()
1510 * @uses urlencode()
1511 * @uses sprintf()
1512 * @uses trigger_error()
1513 * @uses array_merge()
1514 * @uses basename()
1515 * @param array $tab array with all options
1516 * @param array $url_params
1517 * @return string html code for one tab, a link if valid otherwise a span
1518 * @access public
1520 function PMA_getTab($tab, $url_params = array())
1522 // default values
1523 $defaults = array(
1524 'text' => '',
1525 'class' => '',
1526 'active' => false,
1527 'link' => '',
1528 'sep' => '?',
1529 'attr' => '',
1530 'args' => '',
1531 'warning' => '',
1532 'fragment' => '',
1535 $tab = array_merge($defaults, $tab);
1537 // determine additionnal style-class
1538 if (empty($tab['class'])) {
1539 if ($tab['text'] == $GLOBALS['strEmpty']
1540 || $tab['text'] == $GLOBALS['strDrop']) {
1541 $tab['class'] = 'caution';
1542 } elseif (! empty($tab['active'])
1543 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1544 $tab['class'] = 'active';
1545 } elseif (empty($GLOBALS['active_page'])
1546 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1547 && empty($tab['warning'])) {
1548 $tab['class'] = 'active';
1552 if (!empty($tab['warning'])) {
1553 $tab['class'] .= ' warning';
1554 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1557 // build the link
1558 if (!empty($tab['link'])) {
1559 $tab['link'] = htmlentities($tab['link']);
1560 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1561 if (! empty($tab['args'])) {
1562 foreach ($tab['args'] as $param => $value) {
1563 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1564 . urlencode($value);
1569 if (! empty($tab['fragment'])) {
1570 $tab['link'] .= $tab['fragment'];
1573 // display icon, even if iconic is disabled but the link-text is missing
1574 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1575 && isset($tab['icon'])) {
1576 // avoid generating an alt tag, because it only illustrates
1577 // the text that follows and if browser does not display
1578 // images, the text is duplicated
1579 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1580 .'%1$s" width="16" height="16" alt="" />%2$s';
1581 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1583 // check to not display an empty link-text
1584 elseif (empty($tab['text'])) {
1585 $tab['text'] = '?';
1586 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1587 E_USER_NOTICE);
1590 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1592 if (!empty($tab['link'])) {
1593 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1594 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1595 . $tab['text'] . '</a>';
1596 } else {
1597 $out .= '<span class="tab' . htmlentities($tab['class']) . '">'
1598 . $tab['text'] . '</span>';
1601 $out .= '</li>';
1602 return $out;
1603 } // end of the 'PMA_getTab()' function
1606 * returns html-code for a tab navigation
1608 * @uses PMA_getTab()
1609 * @uses htmlentities()
1610 * @param array $tabs one element per tab
1611 * @param string $url_params
1612 * @return string html-code for tab-navigation
1614 function PMA_getTabs($tabs, $url_params)
1616 $tag_id = 'topmenu';
1617 $tab_navigation =
1618 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1619 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1621 foreach ($tabs as $tab) {
1622 $tab_navigation .= PMA_getTab($tab, $url_params) . "\n";
1625 $tab_navigation .=
1626 '</ul>' . "\n"
1627 .'<div class="clearfloat"></div>'
1628 .'</div>' . "\n";
1630 return $tab_navigation;
1635 * Displays a link, or a button if the link's URL is too large, to
1636 * accommodate some browsers' limitations
1638 * @param string the URL
1639 * @param string the link message
1640 * @param mixed $tag_params string: js confirmation
1641 * array: additional tag params (f.e. style="")
1642 * @param boolean $new_form we set this to false when we are already in
1643 * a form, to avoid generating nested forms
1645 * @return string the results to be echoed or saved in an array
1647 function PMA_linkOrButton($url, $message, $tag_params = array(),
1648 $new_form = true, $strip_img = false, $target = '')
1650 if (! is_array($tag_params)) {
1651 $tmp = $tag_params;
1652 $tag_params = array();
1653 if (!empty($tmp)) {
1654 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1656 unset($tmp);
1658 if (! empty($target)) {
1659 $tag_params['target'] = htmlentities($target);
1662 $tag_params_strings = array();
1663 foreach ($tag_params as $par_name => $par_value) {
1664 // htmlspecialchars() only on non javascript
1665 $par_value = substr($par_name, 0, 2) == 'on'
1666 ? $par_value
1667 : htmlspecialchars($par_value);
1668 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1671 // previously the limit was set to 2047, it seems 1000 is better
1672 if (strlen($url) <= 1000) {
1673 // no whitespace within an <a> else Safari will make it part of the link
1674 $ret = "\n" . '<a href="' . $url . '" '
1675 . implode(' ', $tag_params_strings) . '>'
1676 . $message . '</a>' . "\n";
1677 } else {
1678 // no spaces (linebreaks) at all
1679 // or after the hidden fields
1680 // IE will display them all
1682 // add class=link to submit button
1683 if (empty($tag_params['class'])) {
1684 $tag_params['class'] = 'link';
1687 // decode encoded url separators
1688 $separator = PMA_get_arg_separator();
1689 // on most places separator is still hard coded ...
1690 if ($separator !== '&') {
1691 // ... so always replace & with $separator
1692 $url = str_replace(htmlentities('&'), $separator, $url);
1693 $url = str_replace('&', $separator, $url);
1695 $url = str_replace(htmlentities($separator), $separator, $url);
1696 // end decode
1698 $url_parts = parse_url($url);
1699 $query_parts = explode($separator, $url_parts['query']);
1700 if ($new_form) {
1701 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1702 . ' method="post"' . $target . ' style="display: inline;">';
1703 $subname_open = '';
1704 $subname_close = '';
1705 $submit_name = '';
1706 } else {
1707 $query_parts[] = 'redirect=' . $url_parts['path'];
1708 if (empty($GLOBALS['subform_counter'])) {
1709 $GLOBALS['subform_counter'] = 0;
1711 $GLOBALS['subform_counter']++;
1712 $ret = '';
1713 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1714 $subname_close = ']';
1715 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1717 foreach ($query_parts as $query_pair) {
1718 list($eachvar, $eachval) = explode('=', $query_pair);
1719 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1720 . $subname_close . '" value="'
1721 . htmlspecialchars(urldecode($eachval)) . '" />';
1722 } // end while
1724 if (stristr($message, '<img')) {
1725 if ($strip_img) {
1726 $message = trim(strip_tags($message));
1727 $ret .= '<input type="submit"' . $submit_name . ' '
1728 . implode(' ', $tag_params_strings)
1729 . ' value="' . htmlspecialchars($message) . '" />';
1730 } else {
1731 $ret .= '<input type="image"' . $submit_name . ' '
1732 . implode(' ', $tag_params_strings)
1733 . ' src="' . preg_replace(
1734 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1735 . ' value="' . htmlspecialchars(
1736 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1737 $message))
1738 . '" />';
1740 } else {
1741 $message = trim(strip_tags($message));
1742 $ret .= '<input type="submit"' . $submit_name . ' '
1743 . implode(' ', $tag_params_strings)
1744 . ' value="' . htmlspecialchars($message) . '" />';
1746 if ($new_form) {
1747 $ret .= '</form>';
1749 } // end if... else...
1751 return $ret;
1752 } // end of the 'PMA_linkOrButton()' function
1756 * Returns a given timespan value in a readable format.
1758 * @uses $GLOBALS['timespanfmt']
1759 * @uses sprintf()
1760 * @uses floor()
1761 * @param int the timespan
1763 * @return string the formatted value
1765 function PMA_timespanFormat($seconds)
1767 $return_string = '';
1768 $days = floor($seconds / 86400);
1769 if ($days > 0) {
1770 $seconds -= $days * 86400;
1772 $hours = floor($seconds / 3600);
1773 if ($days > 0 || $hours > 0) {
1774 $seconds -= $hours * 3600;
1776 $minutes = floor($seconds / 60);
1777 if ($days > 0 || $hours > 0 || $minutes > 0) {
1778 $seconds -= $minutes * 60;
1780 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1784 * Takes a string and outputs each character on a line for itself. Used
1785 * mainly for horizontalflipped display mode.
1786 * Takes care of special html-characters.
1787 * Fulfills todo-item
1788 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1790 * @todo add a multibyte safe function PMA_STR_split()
1791 * @uses strlen
1792 * @param string The string
1793 * @param string The Separator (defaults to "<br />\n")
1795 * @access public
1796 * @author Garvin Hicking <me@supergarv.de>
1797 * @return string The flipped string
1799 function PMA_flipstring($string, $Separator = "<br />\n")
1801 $format_string = '';
1802 $charbuff = false;
1804 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1805 $char = $string{$i};
1806 $append = false;
1808 if ($char == '&') {
1809 $format_string .= $charbuff;
1810 $charbuff = $char;
1811 } elseif ($char == ';' && !empty($charbuff)) {
1812 $format_string .= $charbuff . $char;
1813 $charbuff = false;
1814 $append = true;
1815 } elseif (! empty($charbuff)) {
1816 $charbuff .= $char;
1817 } else {
1818 $format_string .= $char;
1819 $append = true;
1822 // do not add separator after the last character
1823 if ($append && ($i != $str_len - 1)) {
1824 $format_string .= $Separator;
1828 return $format_string;
1833 * Function added to avoid path disclosures.
1834 * Called by each script that needs parameters, it displays
1835 * an error message and, by default, stops the execution.
1837 * Not sure we could use a strMissingParameter message here,
1838 * would have to check if the error message file is always available
1840 * @todo localize error message
1841 * @todo use PMA_fatalError() if $die === true?
1842 * @uses PMA_getenv()
1843 * @uses header_meta_style.inc.php
1844 * @uses $GLOBALS['PMA_PHP_SELF']
1845 * basename
1846 * @param array The names of the parameters needed by the calling
1847 * script.
1848 * @param boolean Stop the execution?
1849 * (Set this manually to false in the calling script
1850 * until you know all needed parameters to check).
1851 * @param boolean Whether to include this list in checking for special params.
1852 * @global string path to current script
1853 * @global boolean flag whether any special variable was required
1855 * @access public
1856 * @author Marc Delisle (lem9@users.sourceforge.net)
1858 function PMA_checkParameters($params, $die = true, $request = true)
1860 global $checked_special;
1862 if (!isset($checked_special)) {
1863 $checked_special = false;
1866 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1867 $found_error = false;
1868 $error_message = '';
1870 foreach ($params as $param) {
1871 if ($request && $param != 'db' && $param != 'table') {
1872 $checked_special = true;
1875 if (!isset($GLOBALS[$param])) {
1876 $error_message .= $reported_script_name
1877 . ': Missing parameter: ' . $param
1878 . ' <a href="./Documentation.html#faqmissingparameters"'
1879 . ' target="documentation"> (FAQ 2.8)</a><br />';
1880 $found_error = true;
1883 if ($found_error) {
1885 * display html meta tags
1887 require_once './libraries/header_meta_style.inc.php';
1888 echo '</head><body><p>' . $error_message . '</p></body></html>';
1889 if ($die) {
1890 exit();
1893 } // end function
1896 * Function to generate unique condition for specified row.
1898 * @uses $GLOBALS['analyzed_sql'][0]
1899 * @uses PMA_DBI_field_flags()
1900 * @uses PMA_backquote()
1901 * @uses PMA_sqlAddslashes()
1902 * @uses stristr()
1903 * @uses bin2hex()
1904 * @uses preg_replace()
1905 * @param resource $handle current query result
1906 * @param integer $fields_cnt number of fields
1907 * @param array $fields_meta meta information about fields
1908 * @param array $row current row
1909 * @param boolean $force_unique generate condition only on pk or unique
1911 * @access public
1912 * @author Michal Cihar (michal@cihar.com) and others...
1913 * @return string calculated condition
1915 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1917 $primary_key = '';
1918 $unique_key = '';
1919 $nonprimary_condition = '';
1920 $preferred_condition = '';
1922 for ($i = 0; $i < $fields_cnt; ++$i) {
1923 $condition = '';
1924 $field_flags = PMA_DBI_field_flags($handle, $i);
1925 $meta = $fields_meta[$i];
1927 // do not use a column alias in a condition
1928 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1929 $meta->orgname = $meta->name;
1931 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1932 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1933 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
1934 as $select_expr) {
1935 // need (string) === (string)
1936 // '' !== 0 but '' == 0
1937 if ((string) $select_expr['alias'] === (string) $meta->name) {
1938 $meta->orgname = $select_expr['column'];
1939 break;
1940 } // end if
1941 } // end foreach
1945 // Do not use a table alias in a condition.
1946 // Test case is:
1947 // select * from galerie x WHERE
1948 //(select count(*) from galerie y where y.datum=x.datum)>1
1950 // But orgtable is present only with mysqli extension so the
1951 // fix is only for mysqli.
1952 // Also, do not use the original table name if we are dealing with
1953 // a view because this view might be updatable.
1954 // (The isView() verification should not be costly in most cases
1955 // because there is some caching in the function).
1956 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1957 $meta->table = $meta->orgtable;
1960 // to fix the bug where float fields (primary or not)
1961 // can't be matched because of the imprecision of
1962 // floating comparison, use CONCAT
1963 // (also, the syntax "CONCAT(field) IS NULL"
1964 // that we need on the next "if" will work)
1965 if ($meta->type == 'real') {
1966 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1967 . PMA_backquote($meta->orgname) . ') ';
1968 } else {
1969 $condition = ' ' . PMA_backquote($meta->table) . '.'
1970 . PMA_backquote($meta->orgname) . ' ';
1971 } // end if... else...
1973 if (!isset($row[$i]) || is_null($row[$i])) {
1974 $condition .= 'IS NULL AND';
1975 } else {
1976 // timestamp is numeric on some MySQL 4.1
1977 if ($meta->numeric && $meta->type != 'timestamp') {
1978 $condition .= '= ' . $row[$i] . ' AND';
1979 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1980 // hexify only if this is a true not empty BLOB or a BINARY
1981 && stristr($field_flags, 'BINARY')
1982 && !empty($row[$i])) {
1983 // do not waste memory building a too big condition
1984 if (strlen($row[$i]) < 1000) {
1985 // use a CAST if possible, to avoid problems
1986 // if the field contains wildcard characters % or _
1987 $condition .= '= CAST(0x' . bin2hex($row[$i])
1988 . ' AS BINARY) AND';
1989 } else {
1990 // this blob won't be part of the final condition
1991 $condition = '';
1993 } else {
1994 $condition .= '= \''
1995 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
1998 if ($meta->primary_key > 0) {
1999 $primary_key .= $condition;
2000 } elseif ($meta->unique_key > 0) {
2001 $unique_key .= $condition;
2003 $nonprimary_condition .= $condition;
2004 } // end for
2006 // Correction University of Virginia 19991216:
2007 // prefer primary or unique keys for condition,
2008 // but use conjunction of all values if no primary key
2009 if ($primary_key) {
2010 $preferred_condition = $primary_key;
2011 } elseif ($unique_key) {
2012 $preferred_condition = $unique_key;
2013 } elseif (! $force_unique) {
2014 $preferred_condition = $nonprimary_condition;
2017 return trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2018 } // end function
2021 * Generate a button or image tag
2023 * @uses PMA_USR_BROWSER_AGENT
2024 * @uses $GLOBALS['pmaThemeImage']
2025 * @uses $GLOBALS['cfg']['PropertiesIconic']
2026 * @param string name of button element
2027 * @param string class of button element
2028 * @param string name of image element
2029 * @param string text to display
2030 * @param string image to display
2032 * @access public
2033 * @author Michal Cihar (michal@cihar.com)
2035 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2036 $image)
2038 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2039 echo ' <input type="submit" name="' . $button_name . '"'
2040 .' value="' . htmlspecialchars($text) . '"'
2041 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2042 return;
2045 /* Opera has trouble with <input type="image"> */
2046 /* IE has trouble with <button> */
2047 if (PMA_USR_BROWSER_AGENT != 'IE') {
2048 echo '<button class="' . $button_class . '" type="submit"'
2049 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2050 .' title="' . htmlspecialchars($text) . '">' . "\n"
2051 . PMA_getIcon($image, $text)
2052 .'</button>' . "\n";
2053 } else {
2054 echo '<input type="image" name="' . $image_name . '" value="'
2055 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2056 . $image . '" />'
2057 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2059 } // end function
2062 * Generate a pagination selector for browsing resultsets
2064 * @todo $url is not javascript escaped!?
2065 * @uses $GLOBALS['strPageNumber']
2066 * @uses range()
2067 * @param string URL for the JavaScript
2068 * @param string Number of rows in the pagination set
2069 * @param string current page number
2070 * @param string number of total pages
2071 * @param string If the number of pages is lower than this
2072 * variable, no pages will be omitted in
2073 * pagination
2074 * @param string How many rows at the beginning should always
2075 * be shown?
2076 * @param string How many rows at the end should always
2077 * be shown?
2078 * @param string Percentage of calculation page offsets to
2079 * hop to a next page
2080 * @param string Near the current page, how many pages should
2081 * be considered "nearby" and displayed as
2082 * well?
2083 * @param string The prompt to display (sometimes empty)
2085 * @access public
2086 * @author Garvin Hicking (pma@supergarv.de)
2088 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2089 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2090 $range = 10, $prompt = '')
2092 $increment = floor($nbTotalPage / $percent);
2093 $pageNowMinusRange = ($pageNow - $range);
2094 $pageNowPlusRange = ($pageNow + $range);
2096 $gotopage = $prompt
2097 . ' <select name="pos" onchange="goToUrl(this, \''
2098 . $url . '\');">' . "\n";
2099 if ($nbTotalPage < $showAll) {
2100 $pages = range(1, $nbTotalPage);
2101 } else {
2102 $pages = array();
2104 // Always show first X pages
2105 for ($i = 1; $i <= $sliceStart; $i++) {
2106 $pages[] = $i;
2109 // Always show last X pages
2110 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2111 $pages[] = $i;
2114 // garvin: Based on the number of results we add the specified
2115 // $percent percentage to each page number,
2116 // so that we have a representing page number every now and then to
2117 // immediately jump to specific pages.
2118 // As soon as we get near our currently chosen page ($pageNow -
2119 // $range), every page number will be shown.
2120 $i = $sliceStart;
2121 $x = $nbTotalPage - $sliceEnd;
2122 $met_boundary = false;
2123 while ($i <= $x) {
2124 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2125 // If our pageselector comes near the current page, we use 1
2126 // counter increments
2127 $i++;
2128 $met_boundary = true;
2129 } else {
2130 // We add the percentage increment to our current page to
2131 // hop to the next one in range
2132 $i += $increment;
2134 // Make sure that we do not cross our boundaries.
2135 if ($i > $pageNowMinusRange && ! $met_boundary) {
2136 $i = $pageNowMinusRange;
2140 if ($i > 0 && $i <= $x) {
2141 $pages[] = $i;
2145 // Since because of ellipsing of the current page some numbers may be double,
2146 // we unify our array:
2147 sort($pages);
2148 $pages = array_unique($pages);
2151 foreach ($pages as $i) {
2152 if ($i == $pageNow) {
2153 $selected = 'selected="selected" style="font-weight: bold"';
2154 } else {
2155 $selected = '';
2157 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2160 $gotopage .= ' </select><noscript><input type="submit" value="' . $GLOBALS['strGo'] . '" /></noscript>';
2162 return $gotopage;
2163 } // end function
2167 * Generate navigation for a list
2169 * @todo use $pos from $_url_params
2170 * @uses $GLOBALS['strPageNumber']
2171 * @uses range()
2172 * @param integer number of elements in the list
2173 * @param integer current position in the list
2174 * @param array url parameters
2175 * @param string script name for form target
2176 * @param string target frame
2177 * @param integer maximum number of elements to display from the list
2179 * @access public
2181 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2183 if ($max_count < $count) {
2184 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2185 echo $GLOBALS['strPageNumber'];
2186 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2188 // Move to the beginning or to the previous page
2189 if ($pos > 0) {
2190 // loic1: patch #474210 from Gosha Sakovich - part 1
2191 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2192 $caption1 = '&lt;&lt;';
2193 $caption2 = ' &lt; ';
2194 $title1 = ' title="' . $GLOBALS['strPos1'] . '"';
2195 $title2 = ' title="' . $GLOBALS['strPrevious'] . '"';
2196 } else {
2197 $caption1 = $GLOBALS['strPos1'] . ' &lt;&lt;';
2198 $caption2 = $GLOBALS['strPrevious'] . ' &lt;';
2199 $title1 = '';
2200 $title2 = '';
2201 } // end if... else...
2202 $_url_params['pos'] = 0;
2203 echo '<a' . $title1 . ' href="' . $script
2204 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2205 . $caption1 . '</a>';
2206 $_url_params['pos'] = $pos - $max_count;
2207 echo '<a' . $title2 . ' href="' . $script
2208 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2209 . $caption2 . '</a>';
2212 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2213 echo PMA_generate_common_hidden_inputs($_url_params);
2214 echo PMA_pageselector(
2215 $script . PMA_generate_common_url($_url_params) . '&amp;',
2216 $max_count,
2217 floor(($pos + 1) / $max_count) + 1,
2218 ceil($count / $max_count));
2219 echo '</form>';
2221 if ($pos + $max_count < $count) {
2222 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2223 $caption3 = ' &gt; ';
2224 $caption4 = '&gt;&gt;';
2225 $title3 = ' title="' . $GLOBALS['strNext'] . '"';
2226 $title4 = ' title="' . $GLOBALS['strEnd'] . '"';
2227 } else {
2228 $caption3 = '&gt; ' . $GLOBALS['strNext'];
2229 $caption4 = '&gt;&gt; ' . $GLOBALS['strEnd'];
2230 $title3 = '';
2231 $title4 = '';
2232 } // end if... else...
2233 $_url_params['pos'] = $pos + $max_count;
2234 echo '<a' . $title3 . ' href="' . $script
2235 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2236 . $caption3 . '</a>';
2237 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2238 if ($_url_params['pos'] == $count) {
2239 $_url_params['pos'] = $count - $max_count;
2241 echo '<a' . $title4 . ' href="' . $script
2242 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2243 . $caption4 . '</a>';
2245 echo "\n";
2246 if ('frame_navigation' == $frame) {
2247 echo '</div>' . "\n";
2253 * replaces %u in given path with current user name
2255 * example:
2256 * <code>
2257 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2259 * </code>
2260 * @uses $cfg['Server']['user']
2261 * @uses substr()
2262 * @uses str_replace()
2263 * @param string $dir with wildcard for user
2264 * @return string per user directory
2266 function PMA_userDir($dir)
2268 // add trailing slash
2269 if (substr($dir, -1) != '/') {
2270 $dir .= '/';
2273 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2277 * returns html code for db link to default db page
2279 * @uses $cfg['DefaultTabDatabase']
2280 * @uses $GLOBALS['db']
2281 * @uses $GLOBALS['strJumpToDB']
2282 * @uses PMA_generate_common_url()
2283 * @uses PMA_unescape_mysql_wildcards()
2284 * @uses strlen()
2285 * @uses sprintf()
2286 * @uses htmlspecialchars()
2287 * @param string $database
2288 * @return string html link to default db page
2290 function PMA_getDbLink($database = null)
2292 if (!strlen($database)) {
2293 if (!strlen($GLOBALS['db'])) {
2294 return '';
2296 $database = $GLOBALS['db'];
2297 } else {
2298 $database = PMA_unescape_mysql_wildcards($database);
2301 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2302 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2303 .htmlspecialchars($database) . '</a>';
2307 * Displays a lightbulb hint explaining a known external bug
2308 * that affects a functionality
2310 * @uses PMA_MYSQL_INT_VERSION
2311 * @uses $GLOBALS['strKnownExternalBug']
2312 * @uses PMA_showHint()
2313 * @uses sprintf()
2314 * @param string $functionality localized message explaining the func.
2315 * @param string $component 'mysql' (eventually, 'php')
2316 * @param string $minimum_version of this component
2317 * @param string $bugref bug reference for this component
2319 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2321 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2322 echo PMA_showHint(sprintf($GLOBALS['strKnownExternalBug'], $functionality, 'http://bugs.mysql.com/' . $bugref));
2327 * Generates and echoes an HTML checkbox
2329 * @param string $html_field_name the checkbox HTML field
2330 * @param string $label
2331 * @param boolean $checked is it initially checked?
2332 * @param boolean $onclick should it submit the form on click?
2334 function PMA_generate_html_checkbox($html_field_name, $label, $checked, $onclick) {
2336 echo '<input type="checkbox" name="' . $html_field_name . '" id="' . $html_field_name . '"' . ($checked ? ' checked="checked"' : '') . ($onclick ? ' onclick="this.form.submit();"' : '') . ' /><label for="' . $html_field_name . '">' . $label . '</label>';
2340 * Generates and echoes a set of radio HTML fields
2342 * @uses htmlspecialchars()
2343 * @param string $html_field_name the radio HTML field
2344 * @param array $choices the choices values and labels
2345 * @param string $checked_choice the choice to check by default
2346 * @param boolean $line_break whether to add an HTML line break after a choice
2347 * @param boolean $escape_label whether to use htmlspecialchars() on label
2348 * @param string $class enclose each choice with a div of this class
2350 function PMA_generate_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2351 foreach ($choices as $choice_value => $choice_label) {
2352 if (! empty($class)) {
2353 echo '<div class="' . $class . '">';
2355 $html_field_id = $html_field_name . '_' . $choice_value;
2356 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2357 if ($choice_value == $checked_choice) {
2358 echo ' checked="checked"';
2360 echo ' />' . "\n";
2361 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2362 if ($line_break) {
2363 echo '<br />';
2365 if (! empty($class)) {
2366 echo '</div>';
2368 echo "\n";
2373 * Generates and echoes an HTML dropdown
2375 * @uses htmlspecialchars()
2376 * @param string $select_name
2377 * @param array $choices the choices values
2378 * @param string $active_choice the choice to select by default
2379 * @todo support titles
2381 function PMA_generate_html_dropdown($select_name, $choices, $active_choice)
2383 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($select_name) . '">"' . "\n";
2384 foreach ($choices as $one_choice) {
2385 $result .= '<option value="' . htmlspecialchars($one_choice) . '"';
2386 if ($one_choice == $active_choice) {
2387 $result .= ' selected="selected"';
2389 $result .= '>' . htmlspecialchars($one_choice) . '</option>' . "\n";
2391 $result .= '</select>' . "\n";
2392 echo $result;
2396 * Generates a slider effect (Mootools)
2397 * Takes care of generating the initial <div> and the link
2398 * controlling the slider; you have to generate the </div> yourself
2399 * after the sliding section.
2401 * @uses $GLOBALS['cfg']['InitialSlidersState']
2402 * @param string $id the id of the <div> on which to apply the effect
2403 * @param string $message the message to show as a link
2405 function PMA_generate_slider_effect($id, $message)
2407 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2408 echo '<div id="' . $id . '">';
2409 return;
2412 <script type="text/javascript">
2413 // <![CDATA[
2414 window.addEvent('domready', function(){
2415 var status = {
2416 'true': '- ',
2417 'false': '+ '
2420 var anchor<?php echo $id; ?> = new Element('a', {
2421 'id': 'toggle_<?php echo $id; ?>',
2422 'href': '#',
2423 'events': {
2424 'click': function(){
2425 mySlide<?php echo $id; ?>.toggle();
2430 anchor<?php echo $id; ?>.appendText('<?php echo $message; ?>');
2431 anchor<?php echo $id; ?>.injectBefore('<?php echo $id; ?>');
2433 var slider_status<?php echo $id; ?> = new Element('span', {
2434 'id': 'slider_status_<?php echo $id; ?>'
2436 slider_status<?php echo $id; ?>.appendText('<?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? '+' : '-';?> ');
2437 slider_status<?php echo $id; ?>.injectBefore('toggle_<?php echo $id; ?>');
2439 var mySlide<?php echo $id; ?> = new Fx.Slide('<?php echo $id; ?>');
2440 <?php
2441 if ($GLOBALS['cfg']['InitialSlidersState'] == 'closed') {
2443 mySlide<?php echo $id; ?>.hide();
2444 <?php
2447 mySlide<?php echo $id; ?>.addEvent('complete', function() {
2448 $('slider_status_<?php echo $id; ?>').set('html', status[mySlide<?php echo $id; ?>.open]);
2451 $('<?php echo $id; ?>').style.display="block";
2453 document.write('<div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none;"' : ''; ?>>');
2454 //]]>
2455 </script>
2456 <noscript>
2457 <div id="<?php echo $id; ?>" />
2458 </noscript>
2459 <?php
2463 * Verifies if something is cached in the session
2465 * @param string $var
2466 * @param scalar $server
2467 * @return boolean
2469 function PMA_cacheExists($var, $server = 0)
2471 if (true === $server) {
2472 $server = $GLOBALS['server'];
2474 return isset($_SESSION['cache']['server_' . $server][$var]);
2478 * Gets cached information from the session
2480 * @param string $var
2481 * @param scalar $server
2482 * @return mixed
2484 function PMA_cacheGet($var, $server = 0)
2486 if (true === $server) {
2487 $server = $GLOBALS['server'];
2489 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2490 return $_SESSION['cache']['server_' . $server][$var];
2491 } else {
2492 return null;
2497 * Caches information in the session
2499 * @param string $var
2500 * @param mixed $val
2501 * @param integer $server
2502 * @return mixed
2504 function PMA_cacheSet($var, $val = null, $server = 0)
2506 if (true === $server) {
2507 $server = $GLOBALS['server'];
2509 $_SESSION['cache']['server_' . $server][$var] = $val;
2513 * Removes cached information from the session
2515 * @param string $var
2516 * @param scalar $server
2518 function PMA_cacheUnset($var, $server = 0)
2520 if (true === $server) {
2521 $server = $GLOBALS['server'];
2523 unset($_SESSION['cache']['server_' . $server][$var]);
2527 * Converts a bit value to printable format;
2528 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2529 * function because in PHP, decbin() supports only 32 bits
2531 * @uses ceil()
2532 * @uses decbin()
2533 * @uses ord()
2534 * @uses substr()
2535 * @uses sprintf()
2536 * @param numeric $value coming from a BIT field
2537 * @param integer $length
2538 * @return string the printable value
2540 function PMA_printable_bit_value($value, $length) {
2541 $printable = '';
2542 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2543 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2545 $printable = substr($printable, -$length);
2546 return $printable;
2550 * Extracts the various parts from a field type spec
2552 * @uses strpos()
2553 * @uses chop()
2554 * @uses substr()
2555 * @param string $fieldspec
2556 * @return array associative array containing type, spec_in_brackets
2557 * and possibly enum_set_values (another array)
2558 * @author Marc Delisle
2559 * @author Joshua Hogendorn
2561 function PMA_extractFieldSpec($fieldspec) {
2562 $first_bracket_pos = strpos($fieldspec, '(');
2563 if ($first_bracket_pos) {
2564 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2565 // convert to lowercase just to be sure
2566 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2567 } else {
2568 $type = $fieldspec;
2569 $spec_in_brackets = '';
2572 if ('enum' == $type || 'set' == $type) {
2573 // Define our working vars
2574 $enum_set_values = array();
2575 $working = "";
2576 $in_string = false;
2577 $index = 0;
2579 // While there is another character to process
2580 while (isset($fieldspec[$index])) {
2581 // Grab the char to look at
2582 $char = $fieldspec[$index];
2584 // If it is a single quote, needs to be handled specially
2585 if ($char == "'") {
2586 // If we are not currently in a string, begin one
2587 if (! $in_string) {
2588 $in_string = true;
2589 $working = "";
2590 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2591 } else {
2592 // Check out the next character (if possible)
2593 $has_next = isset($fieldspec[$index + 1]);
2594 $next = $has_next ? $fieldspec[$index + 1] : null;
2596 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2597 if (! $has_next || $next != "'") {
2598 $enum_set_values[] = $working;
2599 $in_string = false;
2601 // Otherwise, this is a 'double quote', and can be added to the working string
2602 } elseif ($next == "'") {
2603 $working .= "'";
2604 // Skip the next char; we already know what it is
2605 $index++;
2608 // escaping of a quote?
2609 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2610 $working .= "'";
2611 $index++;
2612 // Otherwise, add it to our working string like normal
2613 } else {
2614 $working .= $char;
2616 // Increment character index
2617 $index++;
2618 } // end while
2619 } else {
2620 $enum_set_values = array();
2623 return array(
2624 'type' => $type,
2625 'spec_in_brackets' => $spec_in_brackets,
2626 'enum_set_values' => $enum_set_values
2631 * Verifies if this table's engine supports foreign keys
2633 * @uses strtoupper()
2634 * @param string $engine
2635 * @return boolean
2637 function PMA_foreignkey_supported($engine) {
2638 $engine = strtoupper($engine);
2639 if ('INNODB' == $engine || 'PBXT' == $engine) {
2640 return true;
2641 } else {
2642 return false;
2647 * Replaces some characters by a displayable equivalent
2649 * @uses str_replace()
2650 * @param string $content
2651 * @return string the content with characters replaced
2653 function PMA_replace_binary_contents($content) {
2654 $result = str_replace("\x00", '\0', $content);
2655 $result = str_replace("\x08", '\b', $result);
2656 $result = str_replace("\x0a", '\n', $result);
2657 $result = str_replace("\x0d", '\r', $result);
2658 $result = str_replace("\x1a", '\Z', $result);
2659 return $result;
2664 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2666 * @uses strpos()
2667 * @return string with the chars replaced
2670 function PMA_duplicateFirstNewline($string){
2671 $first_occurence = strpos($string, "\r\n");
2672 if ($first_occurence === 0){
2673 $string = "\n".$string;
2675 return $string;
2679 * get the action word corresponding to a script name
2680 * in order to display it as a title in navigation panel
2682 * @uses $GLOBALS
2683 * @param string a valid value for $cfg['LeftDefaultTabTable']
2684 * or $cfg['DefaultTabTable']
2685 * or $cfg['DefaultTabDatabase']
2687 function PMA_getTitleForTarget($target) {
2688 return $GLOBALS[$GLOBALS['cfg']['DefaultTabTranslationMapping'][$target]];