Refresh .po files
[phpmyadmin/madhuracj.git] / libraries / common.lib.php
blobe64c75161ac6c96248a09f658fcad56e2d27f7bd
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Misc functions used all over the scripts.
6 * @package phpMyAdmin
7 */
9 /**
10 * Exponential expression / raise number into power
12 * @param string $base
13 * @param string $exp
14 * @param mixed $use_function pow function to use, or false for auto-detect
15 * @return mixed string or float
17 function PMA_pow($base, $exp, $use_function = false)
19 static $pow_function = null;
21 if (null == $pow_function) {
22 if (function_exists('bcpow')) {
23 // BCMath Arbitrary Precision Mathematics Function
24 $pow_function = 'bcpow';
25 } elseif (function_exists('gmp_pow')) {
26 // GMP Function
27 $pow_function = 'gmp_pow';
28 } else {
29 // PHP function
30 $pow_function = 'pow';
34 if (! $use_function) {
35 $use_function = $pow_function;
38 if ($exp < 0 && 'pow' != $use_function) {
39 return false;
41 switch ($use_function) {
42 case 'bcpow' :
43 // bcscale() needed for testing PMA_pow() with base values < 1
44 bcscale(10);
45 $pow = bcpow($base, $exp);
46 break;
47 case 'gmp_pow' :
48 $pow = gmp_strval(gmp_pow($base, $exp));
49 break;
50 case 'pow' :
51 $base = (float) $base;
52 $exp = (int) $exp;
53 $pow = pow($base, $exp);
54 break;
55 default:
56 $pow = $use_function($base, $exp);
59 return $pow;
62 /**
63 * string PMA_getIcon(string $icon)
65 * @param string $icon name of icon file
66 * @param string $alternate alternate text
67 * @param boolean $container include in container
68 * @param boolean $force_text whether to force alternate text to be displayed
69 * @return html img tag
71 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
73 $include_icon = false;
74 $include_text = false;
75 $include_box = false;
76 $alternate = htmlspecialchars($alternate);
77 $button = '';
79 if ($GLOBALS['cfg']['PropertiesIconic']) {
80 $include_icon = true;
83 if ($force_text
84 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
85 || ! $include_icon) {
86 // $cfg['PropertiesIconic'] is false or both
87 // OR we have no $include_icon
88 $include_text = true;
91 if ($include_text && $include_icon && $container) {
92 // we have icon, text and request for container
93 $include_box = true;
96 // Always use a span (we rely on this in js/sql.js)
97 $button .= '<span class="nowrap">';
99 if ($include_icon) {
100 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
101 . ' title="' . $alternate . '" alt="' . $alternate . '"'
102 . ' class="icon" width="16" height="16" />';
105 if ($include_icon && $include_text) {
106 $button .= ' ';
109 if ($include_text) {
110 $button .= $alternate;
113 $button .= '</span>';
115 return $button;
119 * Displays the maximum size for an upload
121 * @param integer $max_upload_size the size
122 * @return string the message
124 * @access public
126 function PMA_displayMaximumUploadSize($max_upload_size)
128 // I have to reduce the second parameter (sensitiveness) from 6 to 4
129 // to avoid weird results like 512 kKib
130 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
131 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
135 * Generates a hidden field which should indicate to the browser
136 * the maximum size for upload
138 * @param integer $max_size the size
139 * @return string the INPUT field
141 * @access public
143 function PMA_generateHiddenMaxFileSize($max_size)
145 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
149 * Add slashes before "'" and "\" characters so a value containing them can
150 * be used in a sql comparison.
152 * @param string $a_string the string to slash
153 * @param bool $is_like whether the string will be used in a 'LIKE' clause
154 * (it then requires two more escaped sequences) or not
155 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
156 * (converts \n to \\n, \r to \\r)
157 * @param bool $php_code whether this function is used as part of the
158 * "Create PHP code" dialog
160 * @return string the slashed string
162 * @access public
164 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
166 if ($is_like) {
167 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
168 } else {
169 $a_string = str_replace('\\', '\\\\', $a_string);
172 if ($crlf) {
173 $a_string = str_replace("\n", '\n', $a_string);
174 $a_string = str_replace("\r", '\r', $a_string);
175 $a_string = str_replace("\t", '\t', $a_string);
178 if ($php_code) {
179 $a_string = str_replace('\'', '\\\'', $a_string);
180 } else {
181 $a_string = str_replace('\'', '\'\'', $a_string);
184 return $a_string;
185 } // end of the 'PMA_sqlAddSlashes()' function
189 * Add slashes before "_" and "%" characters for using them in MySQL
190 * database, table and field names.
191 * Note: This function does not escape backslashes!
193 * @param string $name the string to escape
194 * @return string the escaped string
196 * @access public
198 function PMA_escape_mysql_wildcards($name)
200 $name = str_replace('_', '\\_', $name);
201 $name = str_replace('%', '\\%', $name);
203 return $name;
204 } // end of the 'PMA_escape_mysql_wildcards()' function
207 * removes slashes before "_" and "%" characters
208 * Note: This function does not unescape backslashes!
210 * @param string $name the string to escape
211 * @return string the escaped string
212 * @access public
214 function PMA_unescape_mysql_wildcards($name)
216 $name = str_replace('\\_', '_', $name);
217 $name = str_replace('\\%', '%', $name);
219 return $name;
220 } // end of the 'PMA_unescape_mysql_wildcards()' function
223 * removes quotes (',",`) from a quoted string
225 * checks if the sting is quoted and removes this quotes
227 * @param string $quoted_string string to remove quotes from
228 * @param string $quote type of quote to remove
229 * @return string unqoted string
231 function PMA_unQuote($quoted_string, $quote = null)
233 $quotes = array();
235 if (null === $quote) {
236 $quotes[] = '`';
237 $quotes[] = '"';
238 $quotes[] = "'";
239 } else {
240 $quotes[] = $quote;
243 foreach ($quotes as $quote) {
244 if (substr($quoted_string, 0, 1) === $quote
245 && substr($quoted_string, -1, 1) === $quote) {
246 $unquoted_string = substr($quoted_string, 1, -1);
247 // replace escaped quotes
248 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
249 return $unquoted_string;
253 return $quoted_string;
257 * format sql strings
259 * @todo move into PMA_Sql
260 * @param mixed $parsed_sql pre-parsed SQL structure
261 * @param string $unparsed_sql
262 * @return string the formatted sql
264 * @global array the configuration array
265 * @global boolean whether the current statement is a multiple one or not
267 * @access public
270 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
272 global $cfg;
274 // Check that we actually have a valid set of parsed data
275 // well, not quite
276 // first check for the SQL parser having hit an error
277 if (PMA_SQP_isError()) {
278 return htmlspecialchars($parsed_sql['raw']);
280 // then check for an array
281 if (! is_array($parsed_sql)) {
282 // We don't so just return the input directly
283 // This is intended to be used for when the SQL Parser is turned off
284 $formatted_sql = '<pre>' . "\n"
285 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
286 . '</pre>';
287 return $formatted_sql;
290 $formatted_sql = '';
292 switch ($cfg['SQP']['fmtType']) {
293 case 'none':
294 if ($unparsed_sql != '') {
295 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
296 } else {
297 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
299 break;
300 case 'html':
301 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
302 break;
303 case 'text':
304 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
305 break;
306 default:
307 break;
308 } // end switch
310 return $formatted_sql;
311 } // end of the "PMA_formatSql()" function
315 * Displays a link to the official MySQL documentation
317 * @param string $chapter chapter of "HTML, one page per chapter" documentation
318 * @param string $link contains name of page/anchor that is being linked
319 * @param bool $big_icon whether to use big icon (like in left frame)
320 * @param string $anchor anchor to page part
321 * @param bool $just_open whether only the opening <a> tag should be returned
323 * @return string the html link
325 * @access public
327 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
329 global $cfg;
331 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
332 return '';
335 // Fixup for newly used names:
336 $chapter = str_replace('_', '-', strtolower($chapter));
337 $link = str_replace('_', '-', strtolower($link));
339 switch ($cfg['MySQLManualType']) {
340 case 'chapters':
341 if (empty($chapter)) {
342 $chapter = 'index';
344 if (empty($anchor)) {
345 $anchor = $link;
347 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
348 break;
349 case 'big':
350 if (empty($anchor)) {
351 $anchor = $link;
353 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
354 break;
355 case 'searchable':
356 if (empty($link)) {
357 $link = 'index';
359 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
360 if (!empty($anchor)) {
361 $url .= '#' . $anchor;
363 break;
364 case 'viewable':
365 default:
366 if (empty($link)) {
367 $link = 'index';
369 $mysql = '5.0';
370 $lang = 'en';
371 if (defined('PMA_MYSQL_INT_VERSION')) {
372 if (PMA_MYSQL_INT_VERSION >= 50500) {
373 $mysql = '5.5';
374 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
375 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
376 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
377 $mysql = '5.1';
378 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
379 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
380 } else {
381 $mysql = '5.0';
382 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
383 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
386 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
387 if (!empty($anchor)) {
388 $url .= '#' . $anchor;
390 break;
393 if ($just_open) {
394 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
395 } elseif ($big_icon) {
396 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
397 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
398 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
399 } else {
400 return '[<a href="' . PMA_linkURL($url) . '" target="mysql_doc">' . __('Documentation') . '</a>]';
402 } // end of the 'PMA_showMySQLDocu()' function
406 * Displays a link to the phpMyAdmin documentation
408 * @param string $anchor anchor in documentation
409 * @return string the html link
411 * @access public
413 function PMA_showDocu($anchor) {
414 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
415 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
416 } else {
417 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
419 } // end of the 'PMA_showDocu()' function
422 * Displays a link to the PHP documentation
424 * @param string $target anchor in documentation
425 * @return string the html link
427 * @access public
429 function PMA_showPHPDocu($target) {
430 $url = PMA_getPHPDocLink($target);
432 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
433 return '<a href="' . $url . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
434 } else {
435 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
437 } // end of the 'PMA_showPHPDocu()' function
440 * returns HTML for a footnote marker and add the messsage to the footnotes
442 * @param string $message the error message
443 * @param bool $bbcode
444 * @param string $type
445 * @return string html code for a footnote marker
446 * @access public
448 function PMA_showHint($message, $bbcode = false, $type = 'notice')
450 if ($message instanceof PMA_Message) {
451 $key = $message->getHash();
452 $type = $message->getLevel();
453 } else {
454 $key = md5($message);
457 if (! isset($GLOBALS['footnotes'][$key])) {
458 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
459 $GLOBALS['footnotes'] = array();
461 $nr = count($GLOBALS['footnotes']) + 1;
462 // this is the first instance of this message
463 $instance = 1;
464 $GLOBALS['footnotes'][$key] = array(
465 'note' => $message,
466 'type' => $type,
467 'nr' => $nr,
468 'instance' => $instance
470 } else {
471 $nr = $GLOBALS['footnotes'][$key]['nr'];
472 // another instance of this message (to ensure ids are unique)
473 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
476 if ($bbcode) {
477 return '[sup]' . $nr . '[/sup]';
480 // footnotemarker used in js/tooltip.js
481 return '<sup class="footnotemarker">' . $nr . '</sup>' .
482 '<img class="footnotemarker" id="footnote_' . $nr . '_' . $instance . '" src="' .
483 $GLOBALS['pmaThemeImage'] . 'b_help.png" alt="" />';
487 * Displays a MySQL error message in the right frame.
489 * @param string $error_message the error message
490 * @param string $the_query the sql query that failed
491 * @param bool $is_modify_link whether to show a "modify" link or not
492 * @param string $back_url the "back" link url (full path is not required)
493 * @param bool $exit EXIT the page?
495 * @global string the curent table
496 * @global string the current db
498 * @access public
500 function PMA_mysqlDie($error_message = '', $the_query = '',
501 $is_modify_link = true, $back_url = '', $exit = true)
503 global $table, $db;
506 * start http output, display html headers
508 require_once './libraries/header.inc.php';
510 $error_msg_output = '';
512 if (!$error_message) {
513 $error_message = PMA_DBI_getError();
515 if (!$the_query && !empty($GLOBALS['sql_query'])) {
516 $the_query = $GLOBALS['sql_query'];
519 // --- Added to solve bug #641765
520 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
521 $formatted_sql = htmlspecialchars($the_query);
522 } elseif (empty($the_query) || trim($the_query) == '') {
523 $formatted_sql = '';
524 } else {
525 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
526 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
527 } else {
528 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
531 // ---
532 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
533 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
534 // if the config password is wrong, or the MySQL server does not
535 // respond, do not show the query that would reveal the
536 // username/password
537 if (!empty($the_query) && !strstr($the_query, 'connect')) {
538 // --- Added to solve bug #641765
539 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
540 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
541 $error_msg_output .= '<br />' . "\n";
543 // ---
544 // modified to show the help on sql errors
545 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
546 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
547 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
549 if ($is_modify_link) {
550 $_url_params = array(
551 'sql_query' => $the_query,
552 'show_query' => 1,
554 if (strlen($table)) {
555 $_url_params['db'] = $db;
556 $_url_params['table'] = $table;
557 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
558 } elseif (strlen($db)) {
559 $_url_params['db'] = $db;
560 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
561 } else {
562 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
565 $error_msg_output .= $doedit_goto
566 . PMA_getIcon('b_edit.png', __('Edit'))
567 . '</a>';
568 } // end if
569 $error_msg_output .= ' </p>' . "\n"
570 .' <p>' . "\n"
571 .' ' . $formatted_sql . "\n"
572 .' </p>' . "\n";
573 } // end if
575 if (!empty($error_message)) {
576 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
578 // modified to show the help on error-returns
579 // (now error-messages-server)
580 $error_msg_output .= '<p>' . "\n"
581 . ' <strong>' . __('MySQL said: ') . '</strong>'
582 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
583 . "\n"
584 . '</p>' . "\n";
586 // The error message will be displayed within a CODE segment.
587 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
589 // Replace all non-single blanks with their HTML-counterpart
590 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
591 // Replace TAB-characters with their HTML-counterpart
592 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
593 // Replace linebreaks
594 $error_message = nl2br($error_message);
596 $error_msg_output .= '<code>' . "\n"
597 . $error_message . "\n"
598 . '</code><br />' . "\n";
599 $error_msg_output .= '</div>';
601 $_SESSION['Import_message']['message'] = $error_msg_output;
603 if ($exit) {
605 * If in an Ajax request
606 * - avoid displaying a Back link
607 * - use PMA_ajaxResponse() to transmit the message and exit
609 if($GLOBALS['is_ajax_request'] == true) {
610 PMA_ajaxResponse($error_msg_output, false);
612 if (! empty($back_url)) {
613 if (strstr($back_url, '?')) {
614 $back_url .= '&amp;no_history=true';
615 } else {
616 $back_url .= '?no_history=true';
619 $_SESSION['Import_message']['go_back_url'] = $back_url;
621 $error_msg_output .= '<fieldset class="tblFooters">';
622 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
623 $error_msg_output .= '</fieldset>' . "\n\n";
626 echo $error_msg_output;
628 * display footer and exit
630 require './libraries/footer.inc.php';
631 } else {
632 echo $error_msg_output;
634 } // end of the 'PMA_mysqlDie()' function
637 * returns array with tables of given db with extended information and grouped
639 * @param string $db name of db
640 * @param string $tables name of tables
641 * @param integer $limit_offset list offset
642 * @param int|bool $limit_count max tables to return
643 * @return array (recursive) grouped table list
645 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
647 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
649 if (null === $tables) {
650 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
651 if ($GLOBALS['cfg']['NaturalOrder']) {
652 uksort($tables, 'strnatcasecmp');
656 if (count($tables) < 1) {
657 return $tables;
660 $default = array(
661 'Name' => '',
662 'Rows' => 0,
663 'Comment' => '',
664 'disp_name' => '',
667 $table_groups = array();
669 // for blobstreaming - list of blobstreaming tables
671 // load PMA configuration
672 $PMA_Config = $GLOBALS['PMA_Config'];
674 foreach ($tables as $table_name => $table) {
675 // if BS tables exist
676 if (PMA_BS_IsHiddenTable($table_name)) {
677 continue;
680 // check for correct row count
681 if (null === $table['Rows']) {
682 // Do not check exact row count here,
683 // if row count is invalid possibly the table is defect
684 // and this would break left frame;
685 // but we can check row count if this is a view or the
686 // information_schema database
687 // since PMA_Table::countRecords() returns a limited row count
688 // in this case.
690 // set this because PMA_Table::countRecords() can use it
691 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
693 if ($tbl_is_view || 'information_schema' == $db) {
694 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
698 // in $group we save the reference to the place in $table_groups
699 // where to store the table info
700 if ($GLOBALS['cfg']['LeftFrameDBTree']
701 && $sep && strstr($table_name, $sep))
703 $parts = explode($sep, $table_name);
705 $group =& $table_groups;
706 $i = 0;
707 $group_name_full = '';
708 $parts_cnt = count($parts) - 1;
709 while ($i < $parts_cnt
710 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
711 $group_name = $parts[$i] . $sep;
712 $group_name_full .= $group_name;
714 if (! isset($group[$group_name])) {
715 $group[$group_name] = array();
716 $group[$group_name]['is' . $sep . 'group'] = true;
717 $group[$group_name]['tab' . $sep . 'count'] = 1;
718 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
719 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
720 $table = $group[$group_name];
721 $group[$group_name] = array();
722 $group[$group_name][$group_name] = $table;
723 unset($table);
724 $group[$group_name]['is' . $sep . 'group'] = true;
725 $group[$group_name]['tab' . $sep . 'count'] = 1;
726 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
727 } else {
728 $group[$group_name]['tab' . $sep . 'count']++;
730 $group =& $group[$group_name];
731 $i++;
733 } else {
734 if (! isset($table_groups[$table_name])) {
735 $table_groups[$table_name] = array();
737 $group =& $table_groups;
741 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
742 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
743 // switch tooltip and name
744 $table['Comment'] = $table['Name'];
745 $table['disp_name'] = $table['Comment'];
746 } else {
747 $table['disp_name'] = $table['Name'];
750 $group[$table_name] = array_merge($default, $table);
753 return $table_groups;
756 /* ----------------------- Set of misc functions ----------------------- */
760 * Adds backquotes on both sides of a database, table or field name.
761 * and escapes backquotes inside the name with another backquote
763 * example:
764 * <code>
765 * echo PMA_backquote('owner`s db'); // `owner``s db`
767 * </code>
769 * @param mixed $a_name the database, table or field name to "backquote"
770 * or array of it
771 * @param boolean $do_it a flag to bypass this function (used by dump
772 * functions)
773 * @return mixed the "backquoted" database, table or field name
774 * @access public
776 function PMA_backquote($a_name, $do_it = true)
778 if (is_array($a_name)) {
779 foreach ($a_name as &$data) {
780 $data = PMA_backquote($data, $do_it);
782 return $a_name;
785 if (! $do_it) {
786 global $PMA_SQPdata_forbidden_word;
788 if(! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
789 return $a_name;
793 // '0' is also empty for php :-(
794 if (strlen($a_name) && $a_name !== '*') {
795 return '`' . str_replace('`', '``', $a_name) . '`';
796 } else {
797 return $a_name;
799 } // end of the 'PMA_backquote()' function
802 * Defines the <CR><LF> value depending on the user OS.
804 * @return string the <CR><LF> value to use
806 * @access public
808 function PMA_whichCrlf()
810 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
811 // Win case
812 if (PMA_USR_OS == 'Win') {
813 $the_crlf = "\r\n";
815 // Others
816 else {
817 $the_crlf = "\n";
820 return $the_crlf;
821 } // end of the 'PMA_whichCrlf()' function
824 * Reloads navigation if needed.
826 * @param bool $jsonly prints out pure JavaScript
828 * @access public
830 function PMA_reloadNavigation($jsonly=false)
832 // Reloads the navigation frame via JavaScript if required
833 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
834 // one of the reasons for a reload is when a table is dropped
835 // in this case, get rid of the table limit offset, otherwise
836 // we have a problem when dropping a table on the last page
837 // and the offset becomes greater than the total number of tables
838 unset($_SESSION['tmp_user_values']['table_limit_offset']);
839 echo "\n";
840 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
841 if (!$jsonly)
842 echo '<script type="text/javascript">' . PHP_EOL;
844 //<![CDATA[
845 if (typeof(window.parent) != 'undefined'
846 && typeof(window.parent.frame_navigation) != 'undefined'
847 && window.parent.goTo) {
848 window.parent.goTo('<?php echo $reload_url; ?>');
850 //]]>
851 <?php
852 if (!$jsonly)
853 echo '</script>' . PHP_EOL;
855 unset($GLOBALS['reload']);
860 * displays the message and the query
861 * usually the message is the result of the query executed
863 * @param string $message the message to display
864 * @param string $sql_query the query to display
865 * @param string $type the type (level) of the message
866 * @param boolean $is_view is this a message after a VIEW operation?
867 * @return string
868 * @access public
870 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
873 * PMA_ajaxResponse uses this function to collect the string of HTML generated
874 * for showing the message. Use output buffering to collect it and return it
875 * in a string. In some special cases on sql.php, buffering has to be disabled
876 * and hence we check with $GLOBALS['buffer_message']
878 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
879 ob_start();
881 global $cfg;
883 if (null === $sql_query) {
884 if (! empty($GLOBALS['display_query'])) {
885 $sql_query = $GLOBALS['display_query'];
886 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
887 $sql_query = $GLOBALS['unparsed_sql'];
888 } elseif (! empty($GLOBALS['sql_query'])) {
889 $sql_query = $GLOBALS['sql_query'];
890 } else {
891 $sql_query = '';
895 if (isset($GLOBALS['using_bookmark_message'])) {
896 $GLOBALS['using_bookmark_message']->display();
897 unset($GLOBALS['using_bookmark_message']);
900 // Corrects the tooltip text via JS if required
901 // @todo this is REALLY the wrong place to do this - very unexpected here
902 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
903 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
904 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
905 echo "\n";
906 echo '<script type="text/javascript">' . "\n";
907 echo '//<![CDATA[' . "\n";
908 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
909 echo '//]]>' . "\n";
910 echo '</script>' . "\n";
911 } // end if ... elseif
913 // Checks if the table needs to be repaired after a TRUNCATE query.
914 // @todo what about $GLOBALS['display_query']???
915 // @todo this is REALLY the wrong place to do this - very unexpected here
916 if (strlen($GLOBALS['table'])
917 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
918 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
919 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
922 unset($tbl_status);
924 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
925 // check for it's presence before using it
926 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
928 if ($message instanceof PMA_Message) {
929 if (isset($GLOBALS['special_message'])) {
930 $message->addMessage($GLOBALS['special_message']);
931 unset($GLOBALS['special_message']);
933 $message->display();
934 $type = $message->getLevel();
935 } else {
936 echo '<div class="' . $type . '">';
937 echo PMA_sanitize($message);
938 if (isset($GLOBALS['special_message'])) {
939 echo PMA_sanitize($GLOBALS['special_message']);
940 unset($GLOBALS['special_message']);
942 echo '</div>';
945 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
946 // Html format the query to be displayed
947 // If we want to show some sql code it is easiest to create it here
948 /* SQL-Parser-Analyzer */
950 if (! empty($GLOBALS['show_as_php'])) {
951 $new_line = '\\n"<br />' . "\n"
952 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
953 $query_base = htmlspecialchars(addslashes($sql_query));
954 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
955 } else {
956 $query_base = $sql_query;
959 $query_too_big = false;
961 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
962 // when the query is large (for example an INSERT of binary
963 // data), the parser chokes; so avoid parsing the query
964 $query_too_big = true;
965 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
966 } elseif (! empty($GLOBALS['parsed_sql'])
967 && $query_base == $GLOBALS['parsed_sql']['raw']) {
968 // (here, use "! empty" because when deleting a bookmark,
969 // $GLOBALS['parsed_sql'] is set but empty
970 $parsed_sql = $GLOBALS['parsed_sql'];
971 } else {
972 // Parse SQL if needed
973 $parsed_sql = PMA_SQP_parse($query_base);
974 if (PMA_SQP_isError()) {
975 unset($parsed_sql);
979 // Analyze it
980 if (isset($parsed_sql)) {
981 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
983 // Same as below (append LIMIT), append the remembered ORDER BY
984 if ($GLOBALS['cfg']['RememberSorting']
985 && isset($analyzed_display_query[0]['queryflags']['select_from'])
986 && isset($GLOBALS['sql_order_to_append'])) {
987 $query_base = $analyzed_display_query[0]['section_before_limit']
988 . "\n" . $GLOBALS['sql_order_to_append']
989 . $analyzed_display_query[0]['section_after_limit'];
991 // Need to reparse query
992 $parsed_sql = PMA_SQP_parse($query_base);
993 // update the $analyzed_display_query
994 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
995 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
998 // Here we append the LIMIT added for navigation, to
999 // enable its display. Adding it higher in the code
1000 // to $sql_query would create a problem when
1001 // using the Refresh or Edit links.
1003 // Only append it on SELECTs.
1006 * @todo what would be the best to do when someone hits Refresh:
1007 * use the current LIMITs ?
1010 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1011 && isset($GLOBALS['sql_limit_to_append'])) {
1012 $query_base = $analyzed_display_query[0]['section_before_limit']
1013 . "\n" . $GLOBALS['sql_limit_to_append']
1014 . $analyzed_display_query[0]['section_after_limit'];
1015 // Need to reparse query
1016 $parsed_sql = PMA_SQP_parse($query_base);
1020 if (! empty($GLOBALS['show_as_php'])) {
1021 $query_base = '$sql = "' . $query_base;
1022 } elseif (! empty($GLOBALS['validatequery'])) {
1023 try {
1024 $query_base = PMA_validateSQL($query_base);
1025 } catch (Exception $e) {
1026 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1028 } elseif (isset($parsed_sql)) {
1029 $query_base = PMA_formatSql($parsed_sql, $query_base);
1032 // Prepares links that may be displayed to edit/explain the query
1033 // (don't go to default pages, we must go to the page
1034 // where the query box is available)
1036 // Basic url query part
1037 $url_params = array();
1038 if (! isset($GLOBALS['db'])) {
1039 $GLOBALS['db'] = '';
1041 if (strlen($GLOBALS['db'])) {
1042 $url_params['db'] = $GLOBALS['db'];
1043 if (strlen($GLOBALS['table'])) {
1044 $url_params['table'] = $GLOBALS['table'];
1045 $edit_link = 'tbl_sql.php';
1046 } else {
1047 $edit_link = 'db_sql.php';
1049 } else {
1050 $edit_link = 'server_sql.php';
1053 // Want to have the query explained
1054 // but only explain a SELECT (that has not been explained)
1055 /* SQL-Parser-Analyzer */
1056 $explain_link = '';
1057 $is_select = false;
1058 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1059 $explain_params = $url_params;
1060 // Detect if we are validating as well
1061 // To preserve the validate uRL data
1062 if (! empty($GLOBALS['validatequery'])) {
1063 $explain_params['validatequery'] = 1;
1065 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1066 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1067 $_message = __('Explain SQL');
1068 $is_select = true;
1069 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1070 $explain_params['sql_query'] = substr($sql_query, 8);
1071 $_message = __('Skip Explain SQL');
1073 if (isset($explain_params['sql_query'])) {
1074 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1075 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1077 } //show explain
1079 $url_params['sql_query'] = $sql_query;
1080 $url_params['show_query'] = 1;
1082 // even if the query is big and was truncated, offer the chance
1083 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1084 if (! empty($cfg['SQLQuery']['Edit'])) {
1085 if ($cfg['EditInWindow'] == true) {
1086 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1087 } else {
1088 $onclick = '';
1091 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1092 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1093 } else {
1094 $edit_link = '';
1097 $url_qpart = PMA_generate_common_url($url_params);
1099 // Also we would like to get the SQL formed in some nice
1100 // php-code
1101 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1102 $php_params = $url_params;
1104 if (! empty($GLOBALS['show_as_php'])) {
1105 $_message = __('Without PHP Code');
1106 } else {
1107 $php_params['show_as_php'] = 1;
1108 $_message = __('Create PHP Code');
1111 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1112 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1114 if (isset($GLOBALS['show_as_php'])) {
1115 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1116 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1118 } else {
1119 $php_link = '';
1120 } //show as php
1122 // Refresh query
1123 if (! empty($cfg['SQLQuery']['Refresh'])
1124 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1125 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1126 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1127 } else {
1128 $refresh_link = '';
1129 } //show as php
1131 if (! empty($cfg['SQLValidator']['use'])
1132 && ! empty($cfg['SQLQuery']['Validate'])) {
1133 $validate_params = $url_params;
1134 if (!empty($GLOBALS['validatequery'])) {
1135 $validate_message = __('Skip Validate SQL') ;
1136 } else {
1137 $validate_params['validatequery'] = 1;
1138 $validate_message = __('Validate SQL') ;
1141 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1142 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1143 } else {
1144 $validate_link = '';
1145 } //validator
1147 if (!empty($GLOBALS['validatequery'])) {
1148 echo '<div class="sqlvalidate">';
1149 } else {
1150 echo '<code class="sql">';
1152 if ($query_too_big) {
1153 echo $shortened_query_base;
1154 } else {
1155 echo $query_base;
1158 //Clean up the end of the PHP
1159 if (! empty($GLOBALS['show_as_php'])) {
1160 echo '";';
1162 if (!empty($GLOBALS['validatequery'])) {
1163 echo '</div>';
1164 } else {
1165 echo '</code>';
1168 echo '<div class="tools">';
1169 // avoid displaying a Profiling checkbox that could
1170 // be checked, which would reexecute an INSERT, for example
1171 if (! empty($refresh_link)) {
1172 PMA_profilingCheckbox($sql_query);
1174 // if needed, generate an invisible form that contains controls for the
1175 // Inline link; this way, the behavior of the Inline link does not
1176 // depend on the profiling support or on the refresh link
1177 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1178 echo '<form action="sql.php" method="post">';
1179 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1180 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1181 echo '</form>';
1184 // in the tools div, only display the Inline link when not in ajax
1185 // mode because 1) it currently does not work and 2) we would
1186 // have two similar mechanisms on the page for the same goal
1187 if ($is_select || $GLOBALS['is_ajax_request'] === false) {
1188 // see in js/functions.js the jQuery code attached to id inline_edit
1189 // document.write conflicts with jQuery, hence used $().append()
1190 echo "<script type=\"text/javascript\">\n" .
1191 "//<![CDATA[\n" .
1192 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1193 PMA_escapeJsString(__('Inline edit of this query')) .
1194 "\" class=\"inline_edit_sql\">" .
1195 PMA_escapeJsString(__('Inline')) .
1196 "</a>]');\n" .
1197 "//]]>\n" .
1198 "</script>";
1200 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1201 echo '</div>';
1203 echo '</div>';
1204 if ($GLOBALS['is_ajax_request'] === false) {
1205 echo '<br class="clearfloat" />';
1208 // If we are in an Ajax request, we have most probably been called in
1209 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1210 // to PMA_ajaxResponse(), which will encode it for JSON.
1211 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1212 $buffer_contents = ob_get_contents();
1213 ob_end_clean();
1214 return $buffer_contents;
1216 return null;
1217 } // end of the 'PMA_showMessage()' function
1220 * Verifies if current MySQL server supports profiling
1222 * @access public
1223 * @return boolean whether profiling is supported
1225 function PMA_profilingSupported()
1227 if (! PMA_cacheExists('profiling_supported', true)) {
1228 // 5.0.37 has profiling but for example, 5.1.20 does not
1229 // (avoid a trip to the server for MySQL before 5.0.37)
1230 // and do not set a constant as we might be switching servers
1231 if (defined('PMA_MYSQL_INT_VERSION')
1232 && PMA_MYSQL_INT_VERSION >= 50037
1233 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1234 PMA_cacheSet('profiling_supported', true, true);
1235 } else {
1236 PMA_cacheSet('profiling_supported', false, true);
1240 return PMA_cacheGet('profiling_supported', true);
1244 * Displays a form with the Profiling checkbox
1246 * @param string $sql_query
1247 * @access public
1249 function PMA_profilingCheckbox($sql_query)
1251 if (PMA_profilingSupported()) {
1252 echo '<form action="sql.php" method="post">' . "\n";
1253 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1254 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1255 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1256 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1257 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1258 echo '</form>' . "\n";
1263 * Formats $value to byte view
1265 * @param double $value the value to format
1266 * @param int $limes the sensitiveness
1267 * @param int $comma the number of decimals to retain
1269 * @return array the formatted value and its unit
1271 * @access public
1273 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1275 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1276 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1278 $dh = PMA_pow(10, $comma);
1279 $li = PMA_pow(10, $limes);
1280 $unit = $byteUnits[0];
1282 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1283 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1284 // use 1024.0 to avoid integer overflow on 64-bit machines
1285 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1286 $unit = $byteUnits[$d];
1287 break 1;
1288 } // end if
1289 } // end for
1291 if ($unit != $byteUnits[0]) {
1292 // if the unit is not bytes (as represented in current language)
1293 // reformat with max length of 5
1294 // 4th parameter=true means do not reformat if value < 1
1295 $return_value = PMA_formatNumber($value, 5, $comma, true);
1296 } else {
1297 // do not reformat, just handle the locale
1298 $return_value = PMA_formatNumber($value, 0);
1301 return array(trim($return_value), $unit);
1302 } // end of the 'PMA_formatByteDown' function
1305 * Changes thousands and decimal separators to locale specific values.
1307 * @param $value
1308 * @return string
1310 function PMA_localizeNumber($value)
1312 return str_replace(
1313 array(',', '.'),
1314 array(
1315 /* l10n: Thousands separator */
1316 __(','),
1317 /* l10n: Decimal separator */
1318 __('.'),
1320 $value);
1324 * Formats $value to the given length and appends SI prefixes
1325 * with a $length of 0 no truncation occurs, number is only formated
1326 * to the current locale
1328 * examples:
1329 * <code>
1330 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1331 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1332 * echo PMA_formatNumber(-0.003, 6); // -3 m
1333 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1334 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1335 * echo PMA_formatNumber(0, 6); // 0
1337 * </code>
1338 * @param double $value the value to format
1339 * @param integer $digits_left number of digits left of the comma
1340 * @param integer $digits_right number of digits right of the comma
1341 * @param boolean $only_down do not reformat numbers below 1
1342 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1344 * @return string the formatted value and its unit
1346 * @access public
1348 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1350 if($value==0) return '0';
1352 $originalValue = $value;
1353 //number_format is not multibyte safe, str_replace is safe
1354 if ($digits_left === 0) {
1355 $value = number_format($value, $digits_right);
1356 if($originalValue!=0 && floatval($value) == 0) $value = ' <'.(1/PMA_pow(10,$digits_right));
1358 return PMA_localizeNumber($value);
1361 // this units needs no translation, ISO
1362 $units = array(
1363 -8 => 'y',
1364 -7 => 'z',
1365 -6 => 'a',
1366 -5 => 'f',
1367 -4 => 'p',
1368 -3 => 'n',
1369 -2 => '&micro;',
1370 -1 => 'm',
1371 0 => ' ',
1372 1 => 'k',
1373 2 => 'M',
1374 3 => 'G',
1375 4 => 'T',
1376 5 => 'P',
1377 6 => 'E',
1378 7 => 'Z',
1379 8 => 'Y'
1382 // check for negative value to retain sign
1383 if ($value < 0) {
1384 $sign = '-';
1385 $value = abs($value);
1386 } else {
1387 $sign = '';
1390 $dh = PMA_pow(10, $digits_right);
1392 // This gives us the right SI prefix already, but $digits_left parameter not incorporated
1393 $d = floor(log10($value) / 3);
1394 // Lowering the SI prefix by 1 gives us an additional 3 zeros
1395 // So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits) to use, then lower the SI prefix
1396 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1397 if($digits_left > $cur_digits) {
1398 $d-= floor(($digits_left - $cur_digits)/3);
1401 if($d<0 && $only_down) $d=0;
1403 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1404 $unit = $units[$d];
1406 // If we dont want any zeros after the comma just add the thousand seperator
1407 if($noTrailingZero)
1408 $value = PMA_localizeNumber(preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$value));
1409 else
1410 $value = PMA_localizeNumber(number_format($value, $digits_right)); //number_format is not multibyte safe, str_replace is safe
1412 if($originalValue!=0 && floatval($value) == 0) return ' <'.(1/PMA_pow(10,$digits_right)).' '.$unit;
1414 return $sign . $value . ' ' . $unit;
1415 } // end of the 'PMA_formatNumber' function
1418 * Returns the number of bytes when a formatted size is given
1420 * @param string $formatted_size the size expression (for example 8MB)
1421 * @return integer The numerical part of the expression (for example 8)
1423 function PMA_extractValueFromFormattedSize($formatted_size)
1425 $return_value = -1;
1427 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1428 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1429 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1430 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1431 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1432 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1434 return $return_value;
1435 }// end of the 'PMA_extractValueFromFormattedSize' function
1438 * Writes localised date
1440 * @param string $timestamp the current timestamp
1441 * @param string $format format
1442 * @return string the formatted date
1444 * @access public
1446 function PMA_localisedDate($timestamp = -1, $format = '')
1448 $month = array(
1449 /* l10n: Short month name */
1450 __('Jan'),
1451 /* l10n: Short month name */
1452 __('Feb'),
1453 /* l10n: Short month name */
1454 __('Mar'),
1455 /* l10n: Short month name */
1456 __('Apr'),
1457 /* l10n: Short month name */
1458 _pgettext('Short month name', 'May'),
1459 /* l10n: Short month name */
1460 __('Jun'),
1461 /* l10n: Short month name */
1462 __('Jul'),
1463 /* l10n: Short month name */
1464 __('Aug'),
1465 /* l10n: Short month name */
1466 __('Sep'),
1467 /* l10n: Short month name */
1468 __('Oct'),
1469 /* l10n: Short month name */
1470 __('Nov'),
1471 /* l10n: Short month name */
1472 __('Dec'));
1473 $day_of_week = array(
1474 /* l10n: Short week day name */
1475 __('Sun'),
1476 /* l10n: Short week day name */
1477 __('Mon'),
1478 /* l10n: Short week day name */
1479 __('Tue'),
1480 /* l10n: Short week day name */
1481 __('Wed'),
1482 /* l10n: Short week day name */
1483 __('Thu'),
1484 /* l10n: Short week day name */
1485 __('Fri'),
1486 /* l10n: Short week day name */
1487 __('Sat'));
1489 if ($format == '') {
1490 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1491 $format = __('%B %d, %Y at %I:%M %p');
1494 if ($timestamp == -1) {
1495 $timestamp = time();
1498 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1499 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1501 return strftime($date, $timestamp);
1502 } // end of the 'PMA_localisedDate()' function
1506 * returns a tab for tabbed navigation.
1507 * If the variables $link and $args ar left empty, an inactive tab is created
1509 * @param array $tab array with all options
1510 * @param array $url_params
1511 * @return string html code for one tab, a link if valid otherwise a span
1512 * @access public
1514 function PMA_generate_html_tab($tab, $url_params = array())
1516 // default values
1517 $defaults = array(
1518 'text' => '',
1519 'class' => '',
1520 'active' => null,
1521 'link' => '',
1522 'sep' => '?',
1523 'attr' => '',
1524 'args' => '',
1525 'warning' => '',
1526 'fragment' => '',
1527 'id' => '',
1530 $tab = array_merge($defaults, $tab);
1532 // determine additionnal style-class
1533 if (empty($tab['class'])) {
1534 if (! empty($tab['active'])
1535 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1536 $tab['class'] = 'active';
1537 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1538 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1539 && empty($tab['warning'])) {
1540 $tab['class'] = 'active';
1544 if (!empty($tab['warning'])) {
1545 $tab['class'] .= ' error';
1546 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1549 // If there are any tab specific URL parameters, merge those with the general URL parameters
1550 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1551 $url_params = array_merge($url_params, $tab['url_params']);
1554 // build the link
1555 if (!empty($tab['link'])) {
1556 $tab['link'] = htmlentities($tab['link']);
1557 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1558 if (! empty($tab['args'])) {
1559 foreach ($tab['args'] as $param => $value) {
1560 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1561 . urlencode($value);
1566 if (! empty($tab['fragment'])) {
1567 $tab['link'] .= $tab['fragment'];
1570 // display icon, even if iconic is disabled but the link-text is missing
1571 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1572 && isset($tab['icon'])) {
1573 // avoid generating an alt tag, because it only illustrates
1574 // the text that follows and if browser does not display
1575 // images, the text is duplicated
1576 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1577 .'%1$s" width="16" height="16" alt="" />%2$s';
1578 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1580 // check to not display an empty link-text
1581 elseif (empty($tab['text'])) {
1582 $tab['text'] = '?';
1583 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1584 E_USER_NOTICE);
1587 //Set the id for the tab, if set in the params
1588 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1589 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1591 if (!empty($tab['link'])) {
1592 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1593 .$id_string
1594 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1595 . $tab['text'] . '</a>';
1596 } else {
1597 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1598 . $tab['text'] . '</span>';
1601 $out .= '</li>';
1602 return $out;
1603 } // end of the 'PMA_generate_html_tab()' function
1606 * returns html-code for a tab navigation
1608 * @param array $tabs one element per tab
1609 * @param string $url_params
1610 * @return string html-code for tab-navigation
1612 function PMA_generate_html_tabs($tabs, $url_params)
1614 $tag_id = 'topmenu';
1615 $tab_navigation =
1616 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1617 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1619 foreach ($tabs as $tab) {
1620 $tab_navigation .= PMA_generate_html_tab($tab, $url_params);
1623 $tab_navigation .=
1624 '</ul>' . "\n"
1625 .'<div class="clearfloat"></div>'
1626 .'</div>' . "\n";
1628 return $tab_navigation;
1633 * Displays a link, or a button if the link's URL is too large, to
1634 * accommodate some browsers' limitations
1636 * @param string $url the URL
1637 * @param string $message the link message
1638 * @param mixed $tag_params string: js confirmation
1639 * array: additional tag params (f.e. style="")
1640 * @param boolean $new_form we set this to false when we are already in
1641 * a form, to avoid generating nested forms
1642 * @param boolean $strip_img
1643 * @param string $target
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 $url_length = strlen($url);
1651 // with this we should be able to catch case of image upload
1652 // into a (MEDIUM) BLOB; not worth generating even a form for these
1653 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1654 return '';
1657 if (! is_array($tag_params)) {
1658 $tmp = $tag_params;
1659 $tag_params = array();
1660 if (!empty($tmp)) {
1661 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1663 unset($tmp);
1665 if (! empty($target)) {
1666 $tag_params['target'] = htmlentities($target);
1669 $tag_params_strings = array();
1670 foreach ($tag_params as $par_name => $par_value) {
1671 // htmlspecialchars() only on non javascript
1672 $par_value = substr($par_name, 0, 2) == 'on'
1673 ? $par_value
1674 : htmlspecialchars($par_value);
1675 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1678 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1679 // no whitespace within an <a> else Safari will make it part of the link
1680 $ret = "\n" . '<a href="' . $url . '" '
1681 . implode(' ', $tag_params_strings) . '>'
1682 . $message . '</a>' . "\n";
1683 } else {
1684 // no spaces (linebreaks) at all
1685 // or after the hidden fields
1686 // IE will display them all
1688 // add class=link to submit button
1689 if (empty($tag_params['class'])) {
1690 $tag_params['class'] = 'link';
1693 // decode encoded url separators
1694 $separator = PMA_get_arg_separator();
1695 // on most places separator is still hard coded ...
1696 if ($separator !== '&') {
1697 // ... so always replace & with $separator
1698 $url = str_replace(htmlentities('&'), $separator, $url);
1699 $url = str_replace('&', $separator, $url);
1701 $url = str_replace(htmlentities($separator), $separator, $url);
1702 // end decode
1704 $url_parts = parse_url($url);
1705 $query_parts = explode($separator, $url_parts['query']);
1706 if ($new_form) {
1707 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1708 . ' method="post"' . $target . ' style="display: inline;">';
1709 $subname_open = '';
1710 $subname_close = '';
1711 $submit_name = '';
1712 } else {
1713 $query_parts[] = 'redirect=' . $url_parts['path'];
1714 if (empty($GLOBALS['subform_counter'])) {
1715 $GLOBALS['subform_counter'] = 0;
1717 $GLOBALS['subform_counter']++;
1718 $ret = '';
1719 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1720 $subname_close = ']';
1721 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1723 foreach ($query_parts as $query_pair) {
1724 list($eachvar, $eachval) = explode('=', $query_pair);
1725 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1726 . $subname_close . '" value="'
1727 . htmlspecialchars(urldecode($eachval)) . '" />';
1728 } // end while
1730 if (stristr($message, '<img')) {
1731 if ($strip_img) {
1732 $message = trim(strip_tags($message));
1733 $ret .= '<input type="submit"' . $submit_name . ' '
1734 . implode(' ', $tag_params_strings)
1735 . ' value="' . htmlspecialchars($message) . '" />';
1736 } else {
1737 $displayed_message = htmlspecialchars(
1738 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1739 $message));
1740 $ret .= '<input type="image"' . $submit_name . ' '
1741 . implode(' ', $tag_params_strings)
1742 . ' src="' . preg_replace(
1743 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1744 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1745 // Here we cannot obey PropertiesIconic completely as a
1746 // generated link would have a length over LinkLengthLimit
1747 // but we can at least show the message.
1748 // If PropertiesIconic is false or 'both'
1749 if ($GLOBALS['cfg']['PropertiesIconic'] !== true) {
1750 $ret .= ' <span class="clickprevimage">' . $displayed_message . '</span>';
1753 } else {
1754 $message = trim(strip_tags($message));
1755 $ret .= '<input type="submit"' . $submit_name . ' '
1756 . implode(' ', $tag_params_strings)
1757 . ' value="' . htmlspecialchars($message) . '" />';
1759 if ($new_form) {
1760 $ret .= '</form>';
1762 } // end if... else...
1764 return $ret;
1765 } // end of the 'PMA_linkOrButton()' function
1769 * Returns a given timespan value in a readable format.
1771 * @param int $seconds the timespan
1773 * @return string the formatted value
1775 function PMA_timespanFormat($seconds)
1777 $days = floor($seconds / 86400);
1778 if ($days > 0) {
1779 $seconds -= $days * 86400;
1781 $hours = floor($seconds / 3600);
1782 if ($days > 0 || $hours > 0) {
1783 $seconds -= $hours * 3600;
1785 $minutes = floor($seconds / 60);
1786 if ($days > 0 || $hours > 0 || $minutes > 0) {
1787 $seconds -= $minutes * 60;
1789 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1793 * Takes a string and outputs each character on a line for itself. Used
1794 * mainly for horizontalflipped display mode.
1795 * Takes care of special html-characters.
1796 * Fulfills todo-item
1797 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1799 * @todo add a multibyte safe function PMA_STR_split()
1800 * @param string $string The string
1801 * @param string $Separator The Separator (defaults to "<br />\n")
1803 * @access public
1804 * @return string The flipped string
1806 function PMA_flipstring($string, $Separator = "<br />\n")
1808 $format_string = '';
1809 $charbuff = false;
1811 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1812 $char = $string{$i};
1813 $append = false;
1815 if ($char == '&') {
1816 $format_string .= $charbuff;
1817 $charbuff = $char;
1818 } elseif ($char == ';' && !empty($charbuff)) {
1819 $format_string .= $charbuff . $char;
1820 $charbuff = false;
1821 $append = true;
1822 } elseif (! empty($charbuff)) {
1823 $charbuff .= $char;
1824 } else {
1825 $format_string .= $char;
1826 $append = true;
1829 // do not add separator after the last character
1830 if ($append && ($i != $str_len - 1)) {
1831 $format_string .= $Separator;
1835 return $format_string;
1839 * Function added to avoid path disclosures.
1840 * Called by each script that needs parameters, it displays
1841 * an error message and, by default, stops the execution.
1843 * Not sure we could use a strMissingParameter message here,
1844 * would have to check if the error message file is always available
1846 * @todo localize error message
1847 * @todo use PMA_fatalError() if $die === true?
1848 * @param array $params The names of the parameters needed by the calling script.
1849 * @param bool $die Stop the execution?
1850 * (Set this manually to false in the calling script
1851 * until you know all needed parameters to check).
1852 * @param bool $request Whether to include this list in checking for special params.
1853 * @global string path to current script
1854 * @global boolean flag whether any special variable was required
1856 * @access public
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 . PMA_showDocu('faqmissingparameters')
1879 . '<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 * @param resource $handle current query result
1899 * @param integer $fields_cnt number of fields
1900 * @param array $fields_meta meta information about fields
1901 * @param array $row current row
1902 * @param boolean $force_unique generate condition only on pk or unique
1904 * @access public
1905 * @return array the calculated condition and whether condition is unique
1907 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1909 $primary_key = '';
1910 $unique_key = '';
1911 $nonprimary_condition = '';
1912 $preferred_condition = '';
1914 for ($i = 0; $i < $fields_cnt; ++$i) {
1915 $condition = '';
1916 $field_flags = PMA_DBI_field_flags($handle, $i);
1917 $meta = $fields_meta[$i];
1919 // do not use a column alias in a condition
1920 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1921 $meta->orgname = $meta->name;
1923 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1924 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1925 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
1926 // need (string) === (string)
1927 // '' !== 0 but '' == 0
1928 if ((string) $select_expr['alias'] === (string) $meta->name) {
1929 $meta->orgname = $select_expr['column'];
1930 break;
1931 } // end if
1932 } // end foreach
1936 // Do not use a table alias in a condition.
1937 // Test case is:
1938 // select * from galerie x WHERE
1939 //(select count(*) from galerie y where y.datum=x.datum)>1
1941 // But orgtable is present only with mysqli extension so the
1942 // fix is only for mysqli.
1943 // Also, do not use the original table name if we are dealing with
1944 // a view because this view might be updatable.
1945 // (The isView() verification should not be costly in most cases
1946 // because there is some caching in the function).
1947 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1948 $meta->table = $meta->orgtable;
1951 // to fix the bug where float fields (primary or not)
1952 // can't be matched because of the imprecision of
1953 // floating comparison, use CONCAT
1954 // (also, the syntax "CONCAT(field) IS NULL"
1955 // that we need on the next "if" will work)
1956 if ($meta->type == 'real') {
1957 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1958 . PMA_backquote($meta->orgname) . ') ';
1959 } else {
1960 $condition = ' ' . PMA_backquote($meta->table) . '.'
1961 . PMA_backquote($meta->orgname) . ' ';
1962 } // end if... else...
1964 if (! isset($row[$i]) || is_null($row[$i])) {
1965 $condition .= 'IS NULL AND';
1966 } else {
1967 // timestamp is numeric on some MySQL 4.1
1968 // for real we use CONCAT above and it should compare to string
1969 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
1970 $condition .= '= ' . $row[$i] . ' AND';
1971 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1972 // hexify only if this is a true not empty BLOB or a BINARY
1973 && stristr($field_flags, 'BINARY')
1974 && !empty($row[$i])) {
1975 // do not waste memory building a too big condition
1976 if (strlen($row[$i]) < 1000) {
1977 // use a CAST if possible, to avoid problems
1978 // if the field contains wildcard characters % or _
1979 $condition .= '= CAST(0x' . bin2hex($row[$i])
1980 . ' AS BINARY) AND';
1981 } else {
1982 // this blob won't be part of the final condition
1983 $condition = '';
1985 } elseif ($meta->type == 'bit') {
1986 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
1987 } else {
1988 $condition .= '= \''
1989 . PMA_sqlAddSlashes($row[$i], false, true) . '\' AND';
1992 if ($meta->primary_key > 0) {
1993 $primary_key .= $condition;
1994 } elseif ($meta->unique_key > 0) {
1995 $unique_key .= $condition;
1997 $nonprimary_condition .= $condition;
1998 } // end for
2000 // Correction University of Virginia 19991216:
2001 // prefer primary or unique keys for condition,
2002 // but use conjunction of all values if no primary key
2003 $clause_is_unique = true;
2004 if ($primary_key) {
2005 $preferred_condition = $primary_key;
2006 } elseif ($unique_key) {
2007 $preferred_condition = $unique_key;
2008 } elseif (! $force_unique) {
2009 $preferred_condition = $nonprimary_condition;
2010 $clause_is_unique = false;
2013 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2014 return(array($where_clause, $clause_is_unique));
2015 } // end function
2018 * Generate a button or image tag
2020 * @param string $button_name name of button element
2021 * @param string $button_class class of button element
2022 * @param string $image_name name of image element
2023 * @param string $text text to display
2024 * @param string $image image to display
2025 * @param string $value
2027 * @access public
2029 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2030 $image, $value = '')
2032 if ($value == '') {
2033 $value = $text;
2035 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2036 echo ' <input type="submit" name="' . $button_name . '"'
2037 .' value="' . htmlspecialchars($value) . '"'
2038 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2039 return;
2042 /* Opera has trouble with <input type="image"> */
2043 /* IE has trouble with <button> */
2044 if (PMA_USR_BROWSER_AGENT != 'IE') {
2045 echo '<button class="' . $button_class . '" type="submit"'
2046 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2047 .' title="' . htmlspecialchars($text) . '">' . "\n"
2048 . PMA_getIcon($image, $text)
2049 .'</button>' . "\n";
2050 } else {
2051 echo '<input type="image" name="' . $image_name . '" value="'
2052 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2053 . $image . '" />'
2054 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2056 } // end function
2059 * Generate a pagination selector for browsing resultsets
2061 * @param int $rows Number of rows in the pagination set
2062 * @param int $pageNow current page number
2063 * @param int $nbTotalPage number of total pages
2064 * @param int $showAll If the number of pages is lower than this
2065 * variable, no pages will be omitted in pagination
2066 * @param int $sliceStart How many rows at the beginning should always be shown?
2067 * @param int $sliceEnd How many rows at the end should always be shown?
2068 * @param int $percent Percentage of calculation page offsets to hop to a next page
2069 * @param int $range Near the current page, how many pages should
2070 * be considered "nearby" and displayed as well?
2071 * @param string $prompt The prompt to display (sometimes empty)
2073 * @return string
2074 * @access public
2076 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2077 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2078 $range = 10, $prompt = '')
2080 $increment = floor($nbTotalPage / $percent);
2081 $pageNowMinusRange = ($pageNow - $range);
2082 $pageNowPlusRange = ($pageNow + $range);
2084 $gotopage = $prompt . ' <select id="pageselector" ';
2085 if ($GLOBALS['cfg']['AjaxEnable']) {
2086 $gotopage .= ' class="ajax"';
2088 $gotopage .= ' name="pos" >' . "\n";
2089 if ($nbTotalPage < $showAll) {
2090 $pages = range(1, $nbTotalPage);
2091 } else {
2092 $pages = array();
2094 // Always show first X pages
2095 for ($i = 1; $i <= $sliceStart; $i++) {
2096 $pages[] = $i;
2099 // Always show last X pages
2100 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2101 $pages[] = $i;
2104 // Based on the number of results we add the specified
2105 // $percent percentage to each page number,
2106 // so that we have a representing page number every now and then to
2107 // immediately jump to specific pages.
2108 // As soon as we get near our currently chosen page ($pageNow -
2109 // $range), every page number will be shown.
2110 $i = $sliceStart;
2111 $x = $nbTotalPage - $sliceEnd;
2112 $met_boundary = false;
2113 while ($i <= $x) {
2114 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2115 // If our pageselector comes near the current page, we use 1
2116 // counter increments
2117 $i++;
2118 $met_boundary = true;
2119 } else {
2120 // We add the percentage increment to our current page to
2121 // hop to the next one in range
2122 $i += $increment;
2124 // Make sure that we do not cross our boundaries.
2125 if ($i > $pageNowMinusRange && ! $met_boundary) {
2126 $i = $pageNowMinusRange;
2130 if ($i > 0 && $i <= $x) {
2131 $pages[] = $i;
2135 // Since because of ellipsing of the current page some numbers may be double,
2136 // we unify our array:
2137 sort($pages);
2138 $pages = array_unique($pages);
2141 foreach ($pages as $i) {
2142 if ($i == $pageNow) {
2143 $selected = 'selected="selected" style="font-weight: bold"';
2144 } else {
2145 $selected = '';
2147 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2150 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2152 return $gotopage;
2153 } // end function
2157 * Generate navigation for a list
2159 * @todo use $pos from $_url_params
2160 * @param int $count number of elements in the list
2161 * @param int $pos current position in the list
2162 * @param array $_url_params url parameters
2163 * @param string $script script name for form target
2164 * @param string $frame target frame
2165 * @param int $max_count maximum number of elements to display from the list
2167 * @access public
2169 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2171 if ($max_count < $count) {
2172 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2173 echo __('Page number:');
2174 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2176 // Move to the beginning or to the previous page
2177 if ($pos > 0) {
2178 // patch #474210 - part 1
2179 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2180 $caption1 = '&lt;&lt;';
2181 $caption2 = ' &lt; ';
2182 $title1 = ' title="' . __('Begin') . '"';
2183 $title2 = ' title="' . __('Previous') . '"';
2184 } else {
2185 $caption1 = __('Begin') . ' &lt;&lt;';
2186 $caption2 = __('Previous') . ' &lt;';
2187 $title1 = '';
2188 $title2 = '';
2189 } // end if... else...
2190 $_url_params['pos'] = 0;
2191 echo '<a' . $title1 . ' href="' . $script
2192 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2193 . $caption1 . '</a>';
2194 $_url_params['pos'] = $pos - $max_count;
2195 echo '<a' . $title2 . ' href="' . $script
2196 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2197 . $caption2 . '</a>';
2200 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2201 echo PMA_generate_common_hidden_inputs($_url_params);
2202 echo PMA_pageselector(
2203 $max_count,
2204 floor(($pos + 1) / $max_count) + 1,
2205 ceil($count / $max_count));
2206 echo '</form>';
2208 if ($pos + $max_count < $count) {
2209 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2210 $caption3 = ' &gt; ';
2211 $caption4 = '&gt;&gt;';
2212 $title3 = ' title="' . __('Next') . '"';
2213 $title4 = ' title="' . __('End') . '"';
2214 } else {
2215 $caption3 = '&gt; ' . __('Next');
2216 $caption4 = '&gt;&gt; ' . __('End');
2217 $title3 = '';
2218 $title4 = '';
2219 } // end if... else...
2220 $_url_params['pos'] = $pos + $max_count;
2221 echo '<a' . $title3 . ' href="' . $script
2222 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2223 . $caption3 . '</a>';
2224 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2225 if ($_url_params['pos'] == $count) {
2226 $_url_params['pos'] = $count - $max_count;
2228 echo '<a' . $title4 . ' href="' . $script
2229 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2230 . $caption4 . '</a>';
2232 echo "\n";
2233 if ('frame_navigation' == $frame) {
2234 echo '</div>' . "\n";
2240 * replaces %u in given path with current user name
2242 * example:
2243 * <code>
2244 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2246 * </code>
2247 * @param string $dir with wildcard for user
2248 * @return string per user directory
2250 function PMA_userDir($dir)
2252 // add trailing slash
2253 if (substr($dir, -1) != '/') {
2254 $dir .= '/';
2257 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2261 * returns html code for db link to default db page
2263 * @param string $database
2264 * @return string html link to default db page
2266 function PMA_getDbLink($database = null)
2268 if (! strlen($database)) {
2269 if (! strlen($GLOBALS['db'])) {
2270 return '';
2272 $database = $GLOBALS['db'];
2273 } else {
2274 $database = PMA_unescape_mysql_wildcards($database);
2277 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2278 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2279 .htmlspecialchars($database) . '</a>';
2283 * Displays a lightbulb hint explaining a known external bug
2284 * that affects a functionality
2286 * @param string $functionality localized message explaining the func.
2287 * @param string $component 'mysql' (eventually, 'php')
2288 * @param string $minimum_version of this component
2289 * @param string $bugref bug reference for this component
2291 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2293 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2294 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2299 * Generates and echoes an HTML checkbox
2301 * @param string $html_field_name the checkbox HTML field
2302 * @param string $label
2303 * @param boolean $checked is it initially checked?
2304 * @param boolean $onclick should it submit the form on click?
2306 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2308 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>';
2312 * Generates and echoes a set of radio HTML fields
2314 * @param string $html_field_name the radio HTML field
2315 * @param array $choices the choices values and labels
2316 * @param string $checked_choice the choice to check by default
2317 * @param boolean $line_break whether to add an HTML line break after a choice
2318 * @param boolean $escape_label whether to use htmlspecialchars() on label
2319 * @param string $class enclose each choice with a div of this class
2321 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2322 foreach ($choices as $choice_value => $choice_label) {
2323 if (! empty($class)) {
2324 echo '<div class="' . $class . '">';
2326 $html_field_id = $html_field_name . '_' . $choice_value;
2327 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2328 if ($choice_value == $checked_choice) {
2329 echo ' checked="checked"';
2331 echo ' />' . "\n";
2332 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2333 if ($line_break) {
2334 echo '<br />';
2336 if (! empty($class)) {
2337 echo '</div>';
2339 echo "\n";
2344 * Generates and returns an HTML dropdown
2346 * @param string $select_name
2347 * @param array $choices choices values
2348 * @param string $active_choice the choice to select by default
2349 * @param string $id id of the select element; can be different in case
2350 * the dropdown is present more than once on the page
2351 * @return string
2352 * @todo support titles
2354 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2356 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2357 foreach ($choices as $one_choice_value => $one_choice_label) {
2358 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2359 if ($one_choice_value == $active_choice) {
2360 $result .= ' selected="selected"';
2362 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2364 $result .= '</select>';
2365 return $result;
2369 * Generates a slider effect (jQjuery)
2370 * Takes care of generating the initial <div> and the link
2371 * controlling the slider; you have to generate the </div> yourself
2372 * after the sliding section.
2374 * @param string $id the id of the <div> on which to apply the effect
2375 * @param string $message the message to show as a link
2377 function PMA_generate_slider_effect($id, $message)
2379 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2380 echo '<div id="' . $id . '">';
2381 return;
2384 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2385 * opening the <div> with PHP itself instead of JavaScript.
2387 * @todo find a better solution that uses $.append(), the recommended method
2388 * maybe by using an additional param, the id of the div to append to
2391 <div id="<?php echo $id; ?>" <?php echo $GLOBALS['cfg']['InitialSlidersState'] == 'closed' ? ' style="display: none; overflow:auto;"' : ''; ?> class="pma_auto_slider" title="<?php echo htmlspecialchars($message); ?>">
2392 <?php
2396 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2398 * @param string $action The URL for the request to be executed
2399 * @param string $select_name The name for the dropdown box
2400 * @param array $options An array of options (see rte_footer.lib.php)
2401 * @param string $callback A JS snippet to execute when the request is
2402 * successfully processed
2404 * @return string HTML code for the toggle button
2406 function PMA_toggleButton($action, $select_name, $options, $callback)
2408 // Do the logic first
2409 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2410 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2411 if ($options[1]['selected'] == true) {
2412 $state = 'on';
2413 } else if ($options[0]['selected'] == true) {
2414 $state = 'off';
2415 } else {
2416 $state = 'on';
2418 $selected1 = '';
2419 $selected0 = '';
2420 if ($options[1]['selected'] == true) {
2421 $selected1 = " selected='selected'";
2422 } else if ($options[0]['selected'] == true) {
2423 $selected0 = " selected='selected'";
2425 // Generate output
2426 $retval = "<!-- TOGGLE START -->\n";
2427 if ($GLOBALS['cfg']['AjaxEnable']) {
2428 $retval .= "<noscript>\n";
2430 $retval .= "<div class='wrapper'>\n";
2431 $retval .= " <form action='$action' method='post'>\n";
2432 $retval .= " <select name='$select_name'>\n";
2433 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2434 $retval .= " {$options[1]['label']}\n";
2435 $retval .= " </option>\n";
2436 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2437 $retval .= " {$options[0]['label']}\n";
2438 $retval .= " </option>\n";
2439 $retval .= " </select>\n";
2440 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2441 $retval .= " </form>\n";
2442 $retval .= "</div>\n";
2443 if ($GLOBALS['cfg']['AjaxEnable']) {
2444 $retval .= "</noscript>\n";
2445 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2446 $retval .= " <div class='toggleButton'>\n";
2447 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2448 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2449 $retval .= " alt='' />\n";
2450 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2451 $retval .= " <tbody>\n";
2452 $retval .= " <td class='toggleOn'>\n";
2453 $retval .= " <span class='hide'>$link_on</span>\n";
2454 $retval .= " <div>";
2455 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2456 $retval .= " </td>\n";
2457 $retval .= " <td><div>&nbsp;</div></td>\n";
2458 $retval .= " <td class='toggleOff'>\n";
2459 $retval .= " <span class='hide'>$link_off</span>\n";
2460 $retval .= " <div>";
2461 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2462 $retval .= " </div>\n";
2463 $retval .= " </tbody>\n";
2464 $retval .= " </tr></table>\n";
2465 $retval .= " <span class='hide callback'>$callback</span>\n";
2466 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2467 $retval .= " </div>\n";
2468 $retval .= " </div>\n";
2469 $retval .= "</div>\n";
2471 $retval .= "<!-- TOGGLE END -->";
2473 return $retval;
2474 } // end PMA_toggleButton()
2477 * Clears cache content which needs to be refreshed on user change.
2479 function PMA_clearUserCache() {
2480 PMA_cacheUnset('is_superuser', true);
2484 * Verifies if something is cached in the session
2486 * @param string $var
2487 * @param int|true $server
2488 * @return boolean
2490 function PMA_cacheExists($var, $server = 0)
2492 if (true === $server) {
2493 $server = $GLOBALS['server'];
2495 return isset($_SESSION['cache']['server_' . $server][$var]);
2499 * Gets cached information from the session
2501 * @param string $var
2502 * @param int|true $server
2503 * @return mixed
2505 function PMA_cacheGet($var, $server = 0)
2507 if (true === $server) {
2508 $server = $GLOBALS['server'];
2510 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2511 return $_SESSION['cache']['server_' . $server][$var];
2512 } else {
2513 return null;
2518 * Caches information in the session
2520 * @param string $var
2521 * @param mixed $val
2522 * @param int|true $server
2523 * @return mixed
2525 function PMA_cacheSet($var, $val = null, $server = 0)
2527 if (true === $server) {
2528 $server = $GLOBALS['server'];
2530 $_SESSION['cache']['server_' . $server][$var] = $val;
2534 * Removes cached information from the session
2536 * @param string $var
2537 * @param int|true $server
2539 function PMA_cacheUnset($var, $server = 0)
2541 if (true === $server) {
2542 $server = $GLOBALS['server'];
2544 unset($_SESSION['cache']['server_' . $server][$var]);
2548 * Converts a bit value to printable format;
2549 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2550 * function because in PHP, decbin() supports only 32 bits
2552 * @param numeric $value coming from a BIT field
2553 * @param integer $length
2554 * @return string the printable value
2556 function PMA_printable_bit_value($value, $length) {
2557 $printable = '';
2558 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2559 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2561 $printable = substr($printable, -$length);
2562 return $printable;
2566 * Verifies whether the value contains a non-printable character
2568 * @param string $value
2569 * @return boolean
2571 function PMA_contains_nonprintable_ascii($value) {
2572 return preg_match('@[^[:print:]]@', $value);
2576 * Converts a BIT type default value
2577 * for example, b'010' becomes 010
2579 * @param string $bit_default_value
2580 * @return string the converted value
2582 function PMA_convert_bit_default_value($bit_default_value) {
2583 return strtr($bit_default_value, array("b" => "", "'" => ""));
2587 * Extracts the various parts from a field type spec
2589 * @param string $fieldspec
2590 * @return array associative array containing type, spec_in_brackets
2591 * and possibly enum_set_values (another array)
2593 function PMA_extractFieldSpec($fieldspec) {
2594 $first_bracket_pos = strpos($fieldspec, '(');
2595 if ($first_bracket_pos) {
2596 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2597 // convert to lowercase just to be sure
2598 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2599 } else {
2600 $type = $fieldspec;
2601 $spec_in_brackets = '';
2604 if ('enum' == $type || 'set' == $type) {
2605 // Define our working vars
2606 $enum_set_values = array();
2607 $working = "";
2608 $in_string = false;
2609 $index = 0;
2611 // While there is another character to process
2612 while (isset($fieldspec[$index])) {
2613 // Grab the char to look at
2614 $char = $fieldspec[$index];
2616 // If it is a single quote, needs to be handled specially
2617 if ($char == "'") {
2618 // If we are not currently in a string, begin one
2619 if (! $in_string) {
2620 $in_string = true;
2621 $working = "";
2622 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2623 } else {
2624 // Check out the next character (if possible)
2625 $has_next = isset($fieldspec[$index + 1]);
2626 $next = $has_next ? $fieldspec[$index + 1] : null;
2628 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2629 if (! $has_next || $next != "'") {
2630 $enum_set_values[] = $working;
2631 $in_string = false;
2633 // Otherwise, this is a 'double quote', and can be added to the working string
2634 } elseif ($next == "'") {
2635 $working .= "'";
2636 // Skip the next char; we already know what it is
2637 $index++;
2640 // escaping of a quote?
2641 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2642 $working .= "'";
2643 $index++;
2644 // Otherwise, add it to our working string like normal
2645 } else {
2646 $working .= $char;
2648 // Increment character index
2649 $index++;
2650 } // end while
2651 } else {
2652 $enum_set_values = array();
2655 return array(
2656 'type' => $type,
2657 'spec_in_brackets' => $spec_in_brackets,
2658 'enum_set_values' => $enum_set_values
2663 * Verifies if this table's engine supports foreign keys
2665 * @param string $engine
2666 * @return boolean
2668 function PMA_foreignkey_supported($engine) {
2669 $engine = strtoupper($engine);
2670 if ('INNODB' == $engine || 'PBXT' == $engine) {
2671 return true;
2672 } else {
2673 return false;
2678 * Replaces some characters by a displayable equivalent
2680 * @param string $content
2681 * @return string the content with characters replaced
2683 function PMA_replace_binary_contents($content) {
2684 $result = str_replace("\x00", '\0', $content);
2685 $result = str_replace("\x08", '\b', $result);
2686 $result = str_replace("\x0a", '\n', $result);
2687 $result = str_replace("\x0d", '\r', $result);
2688 $result = str_replace("\x1a", '\Z', $result);
2689 return $result;
2693 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2695 * @param string $string
2696 * @return string with the chars replaced
2699 function PMA_duplicateFirstNewline($string) {
2700 $first_occurence = strpos($string, "\r\n");
2701 if ($first_occurence === 0){
2702 $string = "\n".$string;
2704 return $string;
2708 * Get the action word corresponding to a script name
2709 * in order to display it as a title in navigation panel
2711 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2712 * or $cfg['DefaultTabDatabase']
2713 * @return array
2715 function PMA_getTitleForTarget($target) {
2716 $mapping = array(
2717 // Values for $cfg['DefaultTabTable']
2718 'tbl_structure.php' => __('Structure'),
2719 'tbl_sql.php' => __('SQL'),
2720 'tbl_select.php' =>__('Search'),
2721 'tbl_change.php' =>__('Insert'),
2722 'sql.php' => __('Browse'),
2724 // Values for $cfg['DefaultTabDatabase']
2725 'db_structure.php' => __('Structure'),
2726 'db_sql.php' => __('SQL'),
2727 'db_search.php' => __('Search'),
2728 'db_operations.php' => __('Operations'),
2730 return $mapping[$target];
2734 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2736 * @param string $string Text where to do expansion.
2737 * @param function $escape Function to call for escaping variable values.
2738 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2739 * @return string
2741 function PMA_expandUserString($string, $escape = null, $updates = array()) {
2742 /* Content */
2743 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2744 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2745 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2746 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2747 $vars['database'] = $GLOBALS['db'];
2748 $vars['table'] = $GLOBALS['table'];
2749 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2751 /* Update forced variables */
2752 foreach($updates as $key => $val) {
2753 $vars[$key] = $val;
2756 /* Replacement mapping */
2758 * The __VAR__ ones are for backward compatibility, because user
2759 * might still have it in cookies.
2761 $replace = array(
2762 '@HTTP_HOST@' => $vars['http_host'],
2763 '@SERVER@' => $vars['server_name'],
2764 '__SERVER__' => $vars['server_name'],
2765 '@VERBOSE@' => $vars['server_verbose'],
2766 '@VSERVER@' => $vars['server_verbose_or_name'],
2767 '@DATABASE@' => $vars['database'],
2768 '__DB__' => $vars['database'],
2769 '@TABLE@' => $vars['table'],
2770 '__TABLE__' => $vars['table'],
2771 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2774 /* Optional escaping */
2775 if (!is_null($escape)) {
2776 foreach($replace as $key => $val) {
2777 $replace[$key] = $escape($val);
2781 /* Fetch fields list if required */
2782 if (strpos($string, '@FIELDS@') !== false) {
2783 $fields_list = PMA_DBI_fetch_result(
2784 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2785 . '.' . PMA_backquote($GLOBALS['table']));
2787 $field_names = array();
2788 foreach ($fields_list as $field) {
2789 if (!is_null($escape)) {
2790 $field_names[] = $escape($field['Field']);
2791 } else {
2792 $field_names[] = $field['Field'];
2796 $replace['@FIELDS@'] = implode(',', $field_names);
2799 /* Do the replacement */
2800 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2804 * function that generates a json output for an ajax request and ends script
2805 * execution
2807 * @param bool $message message string containing the html of the message
2808 * @param bool $success success whether the ajax request was successfull
2809 * @param array $extra_data extra_data optional - any other data as part of the json request
2812 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2814 $response = array();
2815 if( $success == true ) {
2816 $response['success'] = true;
2817 if ($message instanceof PMA_Message) {
2818 $response['message'] = $message->getDisplay();
2820 else {
2821 $response['message'] = $message;
2824 else {
2825 $response['success'] = false;
2826 if($message instanceof PMA_Message) {
2827 $response['error'] = $message->getDisplay();
2829 else {
2830 $response['error'] = $message;
2834 // If extra_data has been provided, append it to the response array
2835 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2836 $response = array_merge($response, $extra_data);
2839 // Set the Content-Type header to JSON so that jQuery parses the
2840 // response correctly.
2842 // At this point, other headers might have been sent;
2843 // even if $GLOBALS['is_header_sent'] is true,
2844 // we have to send these additional headers.
2845 header('Cache-Control: no-cache');
2846 header("Content-Type: application/json");
2848 echo json_encode($response);
2849 exit;
2853 * Display the form used to browse anywhere on the local server for the file to import
2855 * @param $max_upload_size
2857 function PMA_browseUploadFile($max_upload_size) {
2858 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2859 echo '<div id="upload_form_status" style="display: none;"></div>';
2860 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2861 echo '<input type="file" name="import_file" id="input_import_file" />';
2862 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2863 // some browsers should respect this :)
2864 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2868 * Display the form used to select a file to import from the server upload directory
2870 * @param $import_list
2871 * @param $uploaddir
2873 function PMA_selectUploadFile($import_list, $uploaddir) {
2874 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2875 $extensions = '';
2876 foreach ($import_list as $key => $val) {
2877 if (!empty($extensions)) {
2878 $extensions .= '|';
2880 $extensions .= $val['extension'];
2882 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2884 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2885 if ($files === false) {
2886 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2887 } elseif (!empty($files)) {
2888 echo "\n";
2889 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2890 echo ' <option value="">&nbsp;</option>' . "\n";
2891 echo $files;
2892 echo ' </select>' . "\n";
2893 } elseif (empty ($files)) {
2894 echo '<i>' . __('There are no files to upload') . '</i>';
2899 * Build titles and icons for action links
2901 * @return array the action titles
2903 function PMA_buildActionTitles() {
2904 $titles = array();
2906 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2907 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2908 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2909 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2910 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2911 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2912 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2913 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2914 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2915 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2916 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2917 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
2918 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'), true);
2919 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'), true);
2920 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'), true);
2921 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'), true);
2922 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'), true);
2923 return $titles;
2927 * This function processes the datatypes supported by the DB, as specified in
2928 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
2929 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
2931 * @param bool $html Whether to generate an html snippet or an array
2932 * @param string $selected The value to mark as selected in HTML mode
2934 * @return mixed An HTML snippet or an array of datatypes.
2937 function PMA_getSupportedDatatypes($html = false, $selected = '')
2939 global $cfg;
2941 if ($html) {
2942 // NOTE: the SELECT tag in not included in this snippet.
2943 $retval = '';
2944 foreach ($cfg['ColumnTypes'] as $key => $value) {
2945 if (is_array($value)) {
2946 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
2947 foreach ($value as $subvalue) {
2948 if ($subvalue == $selected) {
2949 $retval .= "<option selected='selected'>";
2950 $retval .= $subvalue;
2951 $retval .= "</option>";
2952 } else if ($subvalue === '-') {
2953 $retval .= "<option disabled='disabled'>";
2954 $retval .= $subvalue;
2955 $retval .= "</option>";
2956 } else {
2957 $retval .= "<option>$subvalue</option>";
2960 $retval .= '</optgroup>';
2961 } else {
2962 if ($selected == $value) {
2963 $retval .= "<option selected='selected'>$value</option>";
2964 } else {
2965 $retval .= "<option>$value</option>";
2969 } else {
2970 $retval = array();
2971 foreach ($cfg['ColumnTypes'] as $value) {
2972 if (is_array($value)) {
2973 foreach ($value as $subvalue) {
2974 if ($subvalue !== '-') {
2975 $retval[] = $subvalue;
2978 } else {
2979 if ($value !== '-') {
2980 $retval[] = $value;
2986 return $retval;
2987 } // end PMA_getSupportedDatatypes()
2990 * Returns a list of datatypes that are not (yet) handled by PMA.
2991 * Used by: tbl_change.php and libraries/db_routines.inc.php
2993 * @return array list of datatypes
2996 function PMA_unsupportedDatatypes() {
2997 // These GIS data types are not yet supported.
2998 $no_support_types = array('geometry',
2999 'point',
3000 'linestring',
3001 'polygon',
3002 'multipoint',
3003 'multilinestring',
3004 'multipolygon',
3005 'geometrycollection'
3008 return $no_support_types;
3012 * Creates a dropdown box with MySQL functions for a particular column.
3014 * @param array $field Data about the column for which
3015 * to generate the dropdown
3016 * @param bool $insert_mode Whether the operation is 'insert'
3018 * @global array $cfg PMA configuration
3019 * @global array $analyzed_sql Analyzed SQL query
3020 * @global mixed $data (null/string) FIXME: what is this for?
3022 * @return string An HTML snippet of a dropdown list with function
3023 * names appropriate for the requested column.
3025 function PMA_getFunctionsForField($field, $insert_mode)
3027 global $cfg, $analyzed_sql, $data;
3029 $selected = '';
3030 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3031 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3032 // which will then reveal the available dropdown options
3033 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3034 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3035 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3036 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3037 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3038 } else {
3039 $dropdown = array();
3040 $default_function = '';
3042 $dropdown_built = array();
3043 $op_spacing_needed = false;
3044 // what function defined as default?
3045 // for the first timestamp we don't set the default function
3046 // if there is a default value for the timestamp
3047 // (not including CURRENT_TIMESTAMP)
3048 // and the column does not have the
3049 // ON UPDATE DEFAULT TIMESTAMP attribute.
3050 if ($field['True_Type'] == 'timestamp'
3051 && empty($field['Default'])
3052 && empty($data)
3053 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3054 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3056 // For primary keys of type char(36) or varchar(36) UUID if the default function
3057 // Only applies to insert mode, as it would silently trash data on updates.
3058 if ($insert_mode
3059 && $field['Key'] == 'PRI'
3060 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3062 $default_function = $cfg['DefaultFunctions']['pk_char36'];
3064 // this is set only when appropriate and is always true
3065 if (isset($field['display_binary_as_hex'])) {
3066 $default_function = 'UNHEX';
3069 // Create the output
3070 $retval = ' <option></option>' . "\n";
3071 // loop on the dropdown array and print all available options for that field.
3072 foreach ($dropdown as $each_dropdown){
3073 $retval .= ' ';
3074 $retval .= '<option';
3075 if ($default_function === $each_dropdown) {
3076 $retval .= ' selected="selected"';
3078 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3079 $dropdown_built[$each_dropdown] = 'true';
3080 $op_spacing_needed = true;
3082 // For compatibility's sake, do not let out all other functions. Instead
3083 // print a separator (blank) and then show ALL functions which weren't shown
3084 // yet.
3085 $cnt_functions = count($cfg['Functions']);
3086 for ($j = 0; $j < $cnt_functions; $j++) {
3087 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3088 // Is current function defined as default?
3089 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3090 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3091 ? ' selected="selected"'
3092 : '';
3093 if ($op_spacing_needed == true) {
3094 $retval .= ' ';
3095 $retval .= '<option value="">--------</option>' . "\n";
3096 $op_spacing_needed = false;
3099 $retval .= ' ';
3100 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3102 } // end for
3104 return $retval;
3105 } // end PMA_getFunctionsForField()
3108 * Checks if the current user has a specific privilege and returns true if the
3109 * user indeed has that privilege or false if (s)he doesn't. This function must
3110 * only be used for features that are available since MySQL 5, because it
3111 * relies on the INFORMATION_SCHEMA database to be present.
3113 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3114 * // Checks if the currently logged in user has the global
3115 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3116 * // user has this privilege on database 'mydb'.
3119 * @param string $priv The privilege to check
3120 * @param mixed $db null, to only check global privileges
3121 * string, db name where to also check for privileges
3122 * @param mixed $tbl null, to only check global privileges
3123 * string, db name where to also check for privileges
3124 * @return bool
3126 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3128 // Get the username for the current user in the format
3129 // required to use in the information schema database.
3130 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3131 if ($user === false) {
3132 return false;
3134 $user = explode('@', $user);
3135 $username = "''";
3136 $username .= str_replace("'", "''", $user[0]);
3137 $username .= "''@''";
3138 $username .= str_replace("'", "''", $user[1]);
3139 $username .= "''";
3140 // Prepage the query
3141 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3142 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3143 // Check global privileges first.
3144 if (PMA_DBI_fetch_value(sprintf($query,
3145 'USER_PRIVILEGES',
3146 $username,
3147 $priv))) {
3148 return true;
3150 // If a database name was provided and user does not have the
3151 // required global privilege, try database-wise permissions.
3152 if ($db !== null) {
3153 $query .= " AND TABLE_SCHEMA='%s'";
3154 if (PMA_DBI_fetch_value(sprintf($query,
3155 'SCHEMA_PRIVILEGES',
3156 $username,
3157 $priv,
3158 PMA_sqlAddSlashes($db)))) {
3159 return true;
3161 } else {
3162 // There was no database name provided and the user
3163 // does not have the correct global privilege.
3164 return false;
3166 // If a table name was also provided and we still didn't
3167 // find any valid privileges, try table-wise privileges.
3168 if ($tbl !== null) {
3169 $query .= " AND TABLE_NAME='%s'";
3170 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3171 'TABLE_PRIVILEGES',
3172 $username,
3173 $priv,
3174 PMA_sqlAddSlashes($db),
3175 PMA_sqlAddSlashes($tbl)))) {
3176 return true;
3179 // If we reached this point, the user does not
3180 // have even valid table-wise privileges.
3181 return false;