This should be checked in common, not in dbi library
[phpmyadmin.git] / libraries / common.lib.php
blob61f5aa69362b240f56eafd9501cb049d807567d7
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 base to raise
13 * @param string $exp exponent to use
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 * @param boolean $noSprite If true, the image source will be not replaced with a CSS Sprite
70 * @return html img tag
72 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false, $noSprite = false)
74 $include_icon = false;
75 $include_text = false;
76 $include_box = false;
77 $alternate = htmlspecialchars($alternate);
78 $button = '';
80 if ($GLOBALS['cfg']['PropertiesIconic']) {
81 $include_icon = true;
84 if ($force_text || true !== $GLOBALS['cfg']['PropertiesIconic']) {
85 // $cfg['PropertiesIconic'] is false or both
86 // OR we have no $include_icon
87 $include_text = true;
90 if ($include_text && $include_icon && $container) {
91 // we have icon, text and request for container
92 $include_box = true;
95 // Always use a span (we rely on this in js/sql.js)
96 $button .= '<span class="nowrap">';
98 if ($include_icon) {
99 if($noSprite) {
100 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
101 . ' class="icon" width="16" height="16" />';
102 } else {
103 $button .= '<img src="themes/dot.gif"'
104 . ' title="' . $alternate . '" alt="' . $alternate . '"'
105 . ' class="icon ic_' . str_replace(array('.gif','.png'),array('',''),$icon) . '" />';
109 if ($include_icon && $include_text) {
110 $button .= ' ';
113 if ($include_text) {
114 $button .= $alternate;
117 $button .= '</span>';
119 return $button;
123 * Displays the maximum size for an upload
125 * @param integer $max_upload_size the size
126 * @return string the message
128 * @access public
130 function PMA_displayMaximumUploadSize($max_upload_size)
132 // I have to reduce the second parameter (sensitiveness) from 6 to 4
133 // to avoid weird results like 512 kKib
134 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
135 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
139 * Generates a hidden field which should indicate to the browser
140 * the maximum size for upload
142 * @param integer $max_size the size
143 * @return string the INPUT field
145 * @access public
147 function PMA_generateHiddenMaxFileSize($max_size)
149 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
153 * Add slashes before "'" and "\" characters so a value containing them can
154 * be used in a sql comparison.
156 * @param string $a_string the string to slash
157 * @param bool $is_like whether the string will be used in a 'LIKE' clause
158 * (it then requires two more escaped sequences) or not
159 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
160 * (converts \n to \\n, \r to \\r)
161 * @param bool $php_code whether this function is used as part of the
162 * "Create PHP code" dialog
164 * @return string the slashed string
166 * @access public
168 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
170 if ($is_like) {
171 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
172 } else {
173 $a_string = str_replace('\\', '\\\\', $a_string);
176 if ($crlf) {
177 $a_string = str_replace("\n", '\n', $a_string);
178 $a_string = str_replace("\r", '\r', $a_string);
179 $a_string = str_replace("\t", '\t', $a_string);
182 if ($php_code) {
183 $a_string = str_replace('\'', '\\\'', $a_string);
184 } else {
185 $a_string = str_replace('\'', '\'\'', $a_string);
188 return $a_string;
189 } // end of the 'PMA_sqlAddSlashes()' function
193 * Add slashes before "_" and "%" characters for using them in MySQL
194 * database, table and field names.
195 * Note: This function does not escape backslashes!
197 * @param string $name the string to escape
198 * @return string the escaped string
200 * @access public
202 function PMA_escape_mysql_wildcards($name)
204 $name = str_replace('_', '\\_', $name);
205 $name = str_replace('%', '\\%', $name);
207 return $name;
208 } // end of the 'PMA_escape_mysql_wildcards()' function
211 * removes slashes before "_" and "%" characters
212 * Note: This function does not unescape backslashes!
214 * @param string $name the string to escape
215 * @return string the escaped string
216 * @access public
218 function PMA_unescape_mysql_wildcards($name)
220 $name = str_replace('\\_', '_', $name);
221 $name = str_replace('\\%', '%', $name);
223 return $name;
224 } // end of the 'PMA_unescape_mysql_wildcards()' function
227 * removes quotes (',",`) from a quoted string
229 * checks if the sting is quoted and removes this quotes
231 * @param string $quoted_string string to remove quotes from
232 * @param string $quote type of quote to remove
233 * @return string unqoted string
235 function PMA_unQuote($quoted_string, $quote = null)
237 $quotes = array();
239 if (null === $quote) {
240 $quotes[] = '`';
241 $quotes[] = '"';
242 $quotes[] = "'";
243 } else {
244 $quotes[] = $quote;
247 foreach ($quotes as $quote) {
248 if (substr($quoted_string, 0, 1) === $quote
249 && substr($quoted_string, -1, 1) === $quote) {
250 $unquoted_string = substr($quoted_string, 1, -1);
251 // replace escaped quotes
252 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
253 return $unquoted_string;
257 return $quoted_string;
261 * format sql strings
263 * @todo move into PMA_Sql
264 * @param mixed $parsed_sql pre-parsed SQL structure
265 * @param string $unparsed_sql raw SQL string
266 * @return string the formatted sql
268 * @global array the configuration array
269 * @global boolean whether the current statement is a multiple one or not
271 * @access public
274 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
276 global $cfg;
278 // Check that we actually have a valid set of parsed data
279 // well, not quite
280 // first check for the SQL parser having hit an error
281 if (PMA_SQP_isError()) {
282 return htmlspecialchars($parsed_sql['raw']);
284 // then check for an array
285 if (! is_array($parsed_sql)) {
286 // We don't so just return the input directly
287 // This is intended to be used for when the SQL Parser is turned off
288 $formatted_sql = '<pre>' . "\n"
289 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
290 . '</pre>';
291 return $formatted_sql;
294 $formatted_sql = '';
296 switch ($cfg['SQP']['fmtType']) {
297 case 'none':
298 if ($unparsed_sql != '') {
299 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
300 } else {
301 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
303 break;
304 case 'html':
305 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
306 break;
307 case 'text':
308 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
309 break;
310 default:
311 break;
312 } // end switch
314 return $formatted_sql;
315 } // end of the "PMA_formatSql()" function
319 * Displays a link to the official MySQL documentation
321 * @param string $chapter chapter of "HTML, one page per chapter" documentation
322 * @param string $link contains name of page/anchor that is being linked
323 * @param bool $big_icon whether to use big icon (like in left frame)
324 * @param string $anchor anchor to page part
325 * @param bool $just_open whether only the opening <a> tag should be returned
327 * @return string the html link
329 * @access public
331 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
333 global $cfg;
335 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
336 return '';
339 // Fixup for newly used names:
340 $chapter = str_replace('_', '-', strtolower($chapter));
341 $link = str_replace('_', '-', strtolower($link));
343 switch ($cfg['MySQLManualType']) {
344 case 'chapters':
345 if (empty($chapter)) {
346 $chapter = 'index';
348 if (empty($anchor)) {
349 $anchor = $link;
351 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
352 break;
353 case 'big':
354 if (empty($anchor)) {
355 $anchor = $link;
357 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
358 break;
359 case 'searchable':
360 if (empty($link)) {
361 $link = 'index';
363 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
364 if (!empty($anchor)) {
365 $url .= '#' . $anchor;
367 break;
368 case 'viewable':
369 default:
370 if (empty($link)) {
371 $link = 'index';
373 $mysql = '5.0';
374 $lang = 'en';
375 if (defined('PMA_MYSQL_INT_VERSION')) {
376 if (PMA_MYSQL_INT_VERSION >= 50500) {
377 $mysql = '5.5';
378 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
379 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
380 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
381 $mysql = '5.1';
382 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
383 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
384 } else {
385 $mysql = '5.0';
386 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
387 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
390 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
391 if (!empty($anchor)) {
392 $url .= '#' . $anchor;
394 break;
397 if ($just_open) {
398 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
399 } elseif ($big_icon) {
400 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon ic_b_sqlhelp" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
401 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
402 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
403 } else {
404 return '[<a href="' . PMA_linkURL($url) . '" target="mysql_doc">' . __('Documentation') . '</a>]';
406 } // end of the 'PMA_showMySQLDocu()' function
410 * Displays a link to the phpMyAdmin documentation
412 * @param string $anchor anchor in documentation
413 * @return string the html link
415 * @access public
417 function PMA_showDocu($anchor) {
418 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
419 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
420 } else {
421 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
423 } // end of the 'PMA_showDocu()' function
426 * Displays a link to the PHP documentation
428 * @param string $target anchor in documentation
429 * @return string the html link
431 * @access public
433 function PMA_showPHPDocu($target) {
434 $url = PMA_getPHPDocLink($target);
436 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
437 return '<a href="' . $url . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
438 } else {
439 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
441 } // end of the 'PMA_showPHPDocu()' function
444 * returns HTML for a footnote marker and add the messsage to the footnotes
446 * @param string $message the error message
447 * @param bool $bbcode
448 * @param string $type
449 * @return string html code for a footnote marker
450 * @access public
452 function PMA_showHint($message, $bbcode = false, $type = 'notice')
454 if ($message instanceof PMA_Message) {
455 $key = $message->getHash();
456 $type = $message->getLevel();
457 } else {
458 $key = md5($message);
461 if (! isset($GLOBALS['footnotes'][$key])) {
462 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
463 $GLOBALS['footnotes'] = array();
465 $nr = count($GLOBALS['footnotes']) + 1;
466 $GLOBALS['footnotes'][$key] = array(
467 'note' => $message,
468 'type' => $type,
469 'nr' => $nr,
471 } else {
472 $nr = $GLOBALS['footnotes'][$key]['nr'];
475 if ($bbcode) {
476 return '[sup]' . $nr . '[/sup]';
479 // footnotemarker used in js/tooltip.js
480 return '<sup class="footnotemarker">' . $nr . '</sup>' .
481 '<img class="footnotemarker footnote_' . $nr . ' ic_b_help" src="themes/dot.gif" alt="" />';
485 * Displays a MySQL error message in the right frame.
487 * @param string $error_message the error message
488 * @param string $the_query the sql query that failed
489 * @param bool $is_modify_link whether to show a "modify" link or not
490 * @param string $back_url the "back" link url (full path is not required)
491 * @param bool $exit EXIT the page?
493 * @global string the curent table
494 * @global string the current db
496 * @access public
498 function PMA_mysqlDie($error_message = '', $the_query = '',
499 $is_modify_link = true, $back_url = '', $exit = true)
501 global $table, $db;
504 * start http output, display html headers
506 require_once './libraries/header.inc.php';
508 $error_msg_output = '';
510 if (!$error_message) {
511 $error_message = PMA_DBI_getError();
513 if (!$the_query && !empty($GLOBALS['sql_query'])) {
514 $the_query = $GLOBALS['sql_query'];
517 // --- Added to solve bug #641765
518 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
519 $formatted_sql = htmlspecialchars($the_query);
520 } elseif (empty($the_query) || trim($the_query) == '') {
521 $formatted_sql = '';
522 } else {
523 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
524 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
525 } else {
526 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
529 // ---
530 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
531 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
532 // if the config password is wrong, or the MySQL server does not
533 // respond, do not show the query that would reveal the
534 // username/password
535 if (!empty($the_query) && !strstr($the_query, 'connect')) {
536 // --- Added to solve bug #641765
537 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
538 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
539 $error_msg_output .= '<br />' . "\n";
541 // ---
542 // modified to show the help on sql errors
543 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
544 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
545 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
547 if ($is_modify_link) {
548 $_url_params = array(
549 'sql_query' => $the_query,
550 'show_query' => 1,
552 if (strlen($table)) {
553 $_url_params['db'] = $db;
554 $_url_params['table'] = $table;
555 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
556 } elseif (strlen($db)) {
557 $_url_params['db'] = $db;
558 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
559 } else {
560 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
563 $error_msg_output .= $doedit_goto
564 . PMA_getIcon('b_edit.png', __('Edit'))
565 . '</a>';
566 } // end if
567 $error_msg_output .= ' </p>' . "\n"
568 .' <p>' . "\n"
569 .' ' . $formatted_sql . "\n"
570 .' </p>' . "\n";
571 } // end if
573 if (!empty($error_message)) {
574 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
576 // modified to show the help on error-returns
577 // (now error-messages-server)
578 $error_msg_output .= '<p>' . "\n"
579 . ' <strong>' . __('MySQL said: ') . '</strong>'
580 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
581 . "\n"
582 . '</p>' . "\n";
584 // The error message will be displayed within a CODE segment.
585 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
587 // Replace all non-single blanks with their HTML-counterpart
588 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
589 // Replace TAB-characters with their HTML-counterpart
590 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
591 // Replace linebreaks
592 $error_message = nl2br($error_message);
594 $error_msg_output .= '<code>' . "\n"
595 . $error_message . "\n"
596 . '</code><br />' . "\n";
597 $error_msg_output .= '</div>';
599 $_SESSION['Import_message']['message'] = $error_msg_output;
601 if ($exit) {
603 * If in an Ajax request
604 * - avoid displaying a Back link
605 * - use PMA_ajaxResponse() to transmit the message and exit
607 if ($GLOBALS['is_ajax_request'] == true) {
608 PMA_ajaxResponse($error_msg_output, false);
610 if (! empty($back_url)) {
611 if (strstr($back_url, '?')) {
612 $back_url .= '&amp;no_history=true';
613 } else {
614 $back_url .= '?no_history=true';
617 $_SESSION['Import_message']['go_back_url'] = $back_url;
619 $error_msg_output .= '<fieldset class="tblFooters">';
620 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
621 $error_msg_output .= '</fieldset>' . "\n\n";
624 echo $error_msg_output;
626 * display footer and exit
628 require './libraries/footer.inc.php';
629 } else {
630 echo $error_msg_output;
632 } // end of the 'PMA_mysqlDie()' function
635 * returns array with tables of given db with extended information and grouped
637 * @param string $db name of db
638 * @param string $tables name of tables
639 * @param integer $limit_offset list offset
640 * @param int|bool $limit_count max tables to return
641 * @return array (recursive) grouped table list
643 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
645 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
647 if (null === $tables) {
648 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
649 if ($GLOBALS['cfg']['NaturalOrder']) {
650 uksort($tables, 'strnatcasecmp');
654 if (count($tables) < 1) {
655 return $tables;
658 $default = array(
659 'Name' => '',
660 'Rows' => 0,
661 'Comment' => '',
662 'disp_name' => '',
665 $table_groups = array();
667 // for blobstreaming - list of blobstreaming tables
669 // load PMA configuration
670 $PMA_Config = $GLOBALS['PMA_Config'];
672 foreach ($tables as $table_name => $table) {
673 // if BS tables exist
674 if (PMA_BS_IsHiddenTable($table_name)) {
675 continue;
678 // check for correct row count
679 if (null === $table['Rows']) {
680 // Do not check exact row count here,
681 // if row count is invalid possibly the table is defect
682 // and this would break left frame;
683 // but we can check row count if this is a view or the
684 // information_schema database
685 // since PMA_Table::countRecords() returns a limited row count
686 // in this case.
688 // set this because PMA_Table::countRecords() can use it
689 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
691 if ($tbl_is_view || 'information_schema' == $db) {
692 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
696 // in $group we save the reference to the place in $table_groups
697 // where to store the table info
698 if ($GLOBALS['cfg']['LeftFrameDBTree']
699 && $sep && strstr($table_name, $sep))
701 $parts = explode($sep, $table_name);
703 $group =& $table_groups;
704 $i = 0;
705 $group_name_full = '';
706 $parts_cnt = count($parts) - 1;
707 while ($i < $parts_cnt
708 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
709 $group_name = $parts[$i] . $sep;
710 $group_name_full .= $group_name;
712 if (! isset($group[$group_name])) {
713 $group[$group_name] = array();
714 $group[$group_name]['is' . $sep . 'group'] = true;
715 $group[$group_name]['tab' . $sep . 'count'] = 1;
716 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
717 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
718 $table = $group[$group_name];
719 $group[$group_name] = array();
720 $group[$group_name][$group_name] = $table;
721 unset($table);
722 $group[$group_name]['is' . $sep . 'group'] = true;
723 $group[$group_name]['tab' . $sep . 'count'] = 1;
724 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
725 } else {
726 $group[$group_name]['tab' . $sep . 'count']++;
728 $group =& $group[$group_name];
729 $i++;
731 } else {
732 if (! isset($table_groups[$table_name])) {
733 $table_groups[$table_name] = array();
735 $group =& $table_groups;
739 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
740 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
741 // switch tooltip and name
742 $table['Comment'] = $table['Name'];
743 $table['disp_name'] = $table['Comment'];
744 } else {
745 $table['disp_name'] = $table['Name'];
748 $group[$table_name] = array_merge($default, $table);
751 return $table_groups;
754 /* ----------------------- Set of misc functions ----------------------- */
758 * Adds backquotes on both sides of a database, table or field name.
759 * and escapes backquotes inside the name with another backquote
761 * example:
762 * <code>
763 * echo PMA_backquote('owner`s db'); // `owner``s db`
765 * </code>
767 * @param mixed $a_name the database, table or field name to "backquote"
768 * or array of it
769 * @param boolean $do_it a flag to bypass this function (used by dump
770 * functions)
771 * @return mixed the "backquoted" database, table or field name
772 * @access public
774 function PMA_backquote($a_name, $do_it = true)
776 if (is_array($a_name)) {
777 foreach ($a_name as &$data) {
778 $data = PMA_backquote($data, $do_it);
780 return $a_name;
783 if (! $do_it) {
784 global $PMA_SQPdata_forbidden_word;
786 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
787 return $a_name;
791 // '0' is also empty for php :-(
792 if (strlen($a_name) && $a_name !== '*') {
793 return '`' . str_replace('`', '``', $a_name) . '`';
794 } else {
795 return $a_name;
797 } // end of the 'PMA_backquote()' function
800 * Defines the <CR><LF> value depending on the user OS.
802 * @return string the <CR><LF> value to use
804 * @access public
806 function PMA_whichCrlf()
808 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
809 // Win case
810 if (PMA_USR_OS == 'Win') {
811 $the_crlf = "\r\n";
813 // Others
814 else {
815 $the_crlf = "\n";
818 return $the_crlf;
819 } // end of the 'PMA_whichCrlf()' function
822 * Reloads navigation if needed.
824 * @param bool $jsonly prints out pure JavaScript
826 * @access public
828 function PMA_reloadNavigation($jsonly=false)
830 // Reloads the navigation frame via JavaScript if required
831 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
832 // one of the reasons for a reload is when a table is dropped
833 // in this case, get rid of the table limit offset, otherwise
834 // we have a problem when dropping a table on the last page
835 // and the offset becomes greater than the total number of tables
836 unset($_SESSION['tmp_user_values']['table_limit_offset']);
837 echo "\n";
838 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
839 if (!$jsonly)
840 echo '<script type="text/javascript">' . PHP_EOL;
842 //<![CDATA[
843 if (typeof(window.parent) != 'undefined'
844 && typeof(window.parent.frame_navigation) != 'undefined'
845 && window.parent.goTo) {
846 window.parent.goTo('<?php echo $reload_url; ?>');
848 //]]>
849 <?php
850 if (!$jsonly)
851 echo '</script>' . PHP_EOL;
853 unset($GLOBALS['reload']);
858 * displays the message and the query
859 * usually the message is the result of the query executed
861 * @param string $message the message to display
862 * @param string $sql_query the query to display
863 * @param string $type the type (level) of the message
864 * @param boolean $is_view is this a message after a VIEW operation?
865 * @return string
866 * @access public
868 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
871 * PMA_ajaxResponse uses this function to collect the string of HTML generated
872 * for showing the message. Use output buffering to collect it and return it
873 * in a string. In some special cases on sql.php, buffering has to be disabled
874 * and hence we check with $GLOBALS['buffer_message']
876 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
877 ob_start();
879 global $cfg;
881 if (null === $sql_query) {
882 if (! empty($GLOBALS['display_query'])) {
883 $sql_query = $GLOBALS['display_query'];
884 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
885 $sql_query = $GLOBALS['unparsed_sql'];
886 } elseif (! empty($GLOBALS['sql_query'])) {
887 $sql_query = $GLOBALS['sql_query'];
888 } else {
889 $sql_query = '';
893 if (isset($GLOBALS['using_bookmark_message'])) {
894 $GLOBALS['using_bookmark_message']->display();
895 unset($GLOBALS['using_bookmark_message']);
898 // Corrects the tooltip text via JS if required
899 // @todo this is REALLY the wrong place to do this - very unexpected here
900 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
901 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
902 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
903 echo "\n";
904 echo '<script type="text/javascript">' . "\n";
905 echo '//<![CDATA[' . "\n";
906 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
907 echo '//]]>' . "\n";
908 echo '</script>' . "\n";
909 } // end if ... elseif
911 // Checks if the table needs to be repaired after a TRUNCATE query.
912 // @todo what about $GLOBALS['display_query']???
913 // @todo this is REALLY the wrong place to do this - very unexpected here
914 if (strlen($GLOBALS['table'])
915 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
916 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
917 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
920 unset($tbl_status);
922 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
923 // check for it's presence before using it
924 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
926 if ($message instanceof PMA_Message) {
927 if (isset($GLOBALS['special_message'])) {
928 $message->addMessage($GLOBALS['special_message']);
929 unset($GLOBALS['special_message']);
931 $message->display();
932 $type = $message->getLevel();
933 } else {
934 echo '<div class="' . $type . '">';
935 echo PMA_sanitize($message);
936 if (isset($GLOBALS['special_message'])) {
937 echo PMA_sanitize($GLOBALS['special_message']);
938 unset($GLOBALS['special_message']);
940 echo '</div>';
943 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
944 // Html format the query to be displayed
945 // If we want to show some sql code it is easiest to create it here
946 /* SQL-Parser-Analyzer */
948 if (! empty($GLOBALS['show_as_php'])) {
949 $new_line = '\\n"<br />' . "\n"
950 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
951 $query_base = htmlspecialchars(addslashes($sql_query));
952 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
953 } else {
954 $query_base = $sql_query;
957 $query_too_big = false;
959 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
960 // when the query is large (for example an INSERT of binary
961 // data), the parser chokes; so avoid parsing the query
962 $query_too_big = true;
963 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
964 } elseif (! empty($GLOBALS['parsed_sql'])
965 && $query_base == $GLOBALS['parsed_sql']['raw']) {
966 // (here, use "! empty" because when deleting a bookmark,
967 // $GLOBALS['parsed_sql'] is set but empty
968 $parsed_sql = $GLOBALS['parsed_sql'];
969 } else {
970 // Parse SQL if needed
971 $parsed_sql = PMA_SQP_parse($query_base);
972 if (PMA_SQP_isError()) {
973 unset($parsed_sql);
977 // Analyze it
978 if (isset($parsed_sql)) {
979 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
981 // Same as below (append LIMIT), append the remembered ORDER BY
982 if ($GLOBALS['cfg']['RememberSorting']
983 && isset($analyzed_display_query[0]['queryflags']['select_from'])
984 && isset($GLOBALS['sql_order_to_append'])) {
985 $query_base = $analyzed_display_query[0]['section_before_limit']
986 . "\n" . $GLOBALS['sql_order_to_append']
987 . $analyzed_display_query[0]['section_after_limit'];
989 // Need to reparse query
990 $parsed_sql = PMA_SQP_parse($query_base);
991 // update the $analyzed_display_query
992 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
993 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
996 // Here we append the LIMIT added for navigation, to
997 // enable its display. Adding it higher in the code
998 // to $sql_query would create a problem when
999 // using the Refresh or Edit links.
1001 // Only append it on SELECTs.
1004 * @todo what would be the best to do when someone hits Refresh:
1005 * use the current LIMITs ?
1008 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1009 && isset($GLOBALS['sql_limit_to_append'])) {
1010 $query_base = $analyzed_display_query[0]['section_before_limit']
1011 . "\n" . $GLOBALS['sql_limit_to_append']
1012 . $analyzed_display_query[0]['section_after_limit'];
1013 // Need to reparse query
1014 $parsed_sql = PMA_SQP_parse($query_base);
1018 if (! empty($GLOBALS['show_as_php'])) {
1019 $query_base = '$sql = "' . $query_base;
1020 } elseif (! empty($GLOBALS['validatequery'])) {
1021 try {
1022 $query_base = PMA_validateSQL($query_base);
1023 } catch (Exception $e) {
1024 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1026 } elseif (isset($parsed_sql)) {
1027 $query_base = PMA_formatSql($parsed_sql, $query_base);
1030 // Prepares links that may be displayed to edit/explain the query
1031 // (don't go to default pages, we must go to the page
1032 // where the query box is available)
1034 // Basic url query part
1035 $url_params = array();
1036 if (! isset($GLOBALS['db'])) {
1037 $GLOBALS['db'] = '';
1039 if (strlen($GLOBALS['db'])) {
1040 $url_params['db'] = $GLOBALS['db'];
1041 if (strlen($GLOBALS['table'])) {
1042 $url_params['table'] = $GLOBALS['table'];
1043 $edit_link = 'tbl_sql.php';
1044 } else {
1045 $edit_link = 'db_sql.php';
1047 } else {
1048 $edit_link = 'server_sql.php';
1051 // Want to have the query explained
1052 // but only explain a SELECT (that has not been explained)
1053 /* SQL-Parser-Analyzer */
1054 $explain_link = '';
1055 $is_select = false;
1056 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1057 $explain_params = $url_params;
1058 // Detect if we are validating as well
1059 // To preserve the validate uRL data
1060 if (! empty($GLOBALS['validatequery'])) {
1061 $explain_params['validatequery'] = 1;
1063 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1064 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1065 $_message = __('Explain SQL');
1066 $is_select = true;
1067 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1068 $explain_params['sql_query'] = substr($sql_query, 8);
1069 $_message = __('Skip Explain SQL');
1071 if (isset($explain_params['sql_query'])) {
1072 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1073 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1075 } //show explain
1077 $url_params['sql_query'] = $sql_query;
1078 $url_params['show_query'] = 1;
1080 // even if the query is big and was truncated, offer the chance
1081 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1082 if (! empty($cfg['SQLQuery']['Edit'])) {
1083 if ($cfg['EditInWindow'] == true) {
1084 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1085 } else {
1086 $onclick = '';
1089 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1090 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1091 } else {
1092 $edit_link = '';
1095 $url_qpart = PMA_generate_common_url($url_params);
1097 // Also we would like to get the SQL formed in some nice
1098 // php-code
1099 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1100 $php_params = $url_params;
1102 if (! empty($GLOBALS['show_as_php'])) {
1103 $_message = __('Without PHP Code');
1104 } else {
1105 $php_params['show_as_php'] = 1;
1106 $_message = __('Create PHP Code');
1109 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1110 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1112 if (isset($GLOBALS['show_as_php'])) {
1113 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1114 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1116 } else {
1117 $php_link = '';
1118 } //show as php
1120 // Refresh query
1121 if (! empty($cfg['SQLQuery']['Refresh'])
1122 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1123 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1124 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1125 } else {
1126 $refresh_link = '';
1127 } //show as php
1129 if (! empty($cfg['SQLValidator']['use'])
1130 && ! empty($cfg['SQLQuery']['Validate'])) {
1131 $validate_params = $url_params;
1132 if (!empty($GLOBALS['validatequery'])) {
1133 $validate_message = __('Skip Validate SQL') ;
1134 } else {
1135 $validate_params['validatequery'] = 1;
1136 $validate_message = __('Validate SQL') ;
1139 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1140 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1141 } else {
1142 $validate_link = '';
1143 } //validator
1145 if (!empty($GLOBALS['validatequery'])) {
1146 echo '<div class="sqlvalidate">';
1147 } else {
1148 echo '<code class="sql">';
1150 if ($query_too_big) {
1151 echo $shortened_query_base;
1152 } else {
1153 echo $query_base;
1156 //Clean up the end of the PHP
1157 if (! empty($GLOBALS['show_as_php'])) {
1158 echo '";';
1160 if (!empty($GLOBALS['validatequery'])) {
1161 echo '</div>';
1162 } else {
1163 echo '</code>';
1166 echo '<div class="tools">';
1167 // avoid displaying a Profiling checkbox that could
1168 // be checked, which would reexecute an INSERT, for example
1169 if (! empty($refresh_link)) {
1170 PMA_profilingCheckbox($sql_query);
1172 // if needed, generate an invisible form that contains controls for the
1173 // Inline link; this way, the behavior of the Inline link does not
1174 // depend on the profiling support or on the refresh link
1175 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1176 echo '<form action="sql.php" method="post">';
1177 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1178 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1179 echo '</form>';
1182 // in the tools div, only display the Inline link when not in ajax
1183 // mode because 1) it currently does not work and 2) we would
1184 // have two similar mechanisms on the page for the same goal
1185 if ($is_select || $GLOBALS['is_ajax_request'] === false) {
1186 // see in js/functions.js the jQuery code attached to id inline_edit
1187 // document.write conflicts with jQuery, hence used $().append()
1188 echo "<script type=\"text/javascript\">\n" .
1189 "//<![CDATA[\n" .
1190 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1191 PMA_escapeJsString(__('Inline edit of this query')) .
1192 "\" class=\"inline_edit_sql\">" .
1193 PMA_escapeJsString(__('Inline')) .
1194 "</a>]');\n" .
1195 "//]]>\n" .
1196 "</script>";
1198 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1199 echo '</div>';
1201 echo '</div>';
1202 if ($GLOBALS['is_ajax_request'] === false) {
1203 echo '<br class="clearfloat" />';
1206 // If we are in an Ajax request, we have most probably been called in
1207 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1208 // to PMA_ajaxResponse(), which will encode it for JSON.
1209 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1210 $buffer_contents = ob_get_contents();
1211 ob_end_clean();
1212 return $buffer_contents;
1214 return null;
1215 } // end of the 'PMA_showMessage()' function
1218 * Verifies if current MySQL server supports profiling
1220 * @access public
1221 * @return boolean whether profiling is supported
1223 function PMA_profilingSupported()
1225 if (! PMA_cacheExists('profiling_supported', true)) {
1226 // 5.0.37 has profiling but for example, 5.1.20 does not
1227 // (avoid a trip to the server for MySQL before 5.0.37)
1228 // and do not set a constant as we might be switching servers
1229 if (defined('PMA_MYSQL_INT_VERSION')
1230 && PMA_MYSQL_INT_VERSION >= 50037
1231 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1232 PMA_cacheSet('profiling_supported', true, true);
1233 } else {
1234 PMA_cacheSet('profiling_supported', false, true);
1238 return PMA_cacheGet('profiling_supported', true);
1242 * Displays a form with the Profiling checkbox
1244 * @param string $sql_query
1245 * @access public
1247 function PMA_profilingCheckbox($sql_query)
1249 if (PMA_profilingSupported()) {
1250 echo '<form action="sql.php" method="post">' . "\n";
1251 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1252 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1253 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1254 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1255 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1256 echo '</form>' . "\n";
1261 * Formats $value to byte view
1263 * @param double $value the value to format
1264 * @param int $limes the sensitiveness
1265 * @param int $comma the number of decimals to retain
1267 * @return array the formatted value and its unit
1269 * @access public
1271 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1273 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1274 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1276 $dh = PMA_pow(10, $comma);
1277 $li = PMA_pow(10, $limes);
1278 $unit = $byteUnits[0];
1280 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1281 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1282 // use 1024.0 to avoid integer overflow on 64-bit machines
1283 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1284 $unit = $byteUnits[$d];
1285 break 1;
1286 } // end if
1287 } // end for
1289 if ($unit != $byteUnits[0]) {
1290 // if the unit is not bytes (as represented in current language)
1291 // reformat with max length of 5
1292 // 4th parameter=true means do not reformat if value < 1
1293 $return_value = PMA_formatNumber($value, 5, $comma, true);
1294 } else {
1295 // do not reformat, just handle the locale
1296 $return_value = PMA_formatNumber($value, 0);
1299 return array(trim($return_value), $unit);
1300 } // end of the 'PMA_formatByteDown' function
1303 * Changes thousands and decimal separators to locale specific values.
1305 * @param $value
1306 * @return string
1308 function PMA_localizeNumber($value)
1310 return str_replace(
1311 array(',', '.'),
1312 array(
1313 /* l10n: Thousands separator */
1314 __(','),
1315 /* l10n: Decimal separator */
1316 __('.'),
1318 $value);
1322 * Formats $value to the given length and appends SI prefixes
1323 * with a $length of 0 no truncation occurs, number is only formated
1324 * to the current locale
1326 * examples:
1327 * <code>
1328 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1329 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1330 * echo PMA_formatNumber(-0.003, 6); // -3 m
1331 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1332 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1333 * echo PMA_formatNumber(0, 6); // 0
1335 * </code>
1336 * @param double $value the value to format
1337 * @param integer $digits_left number of digits left of the comma
1338 * @param integer $digits_right number of digits right of the comma
1339 * @param boolean $only_down do not reformat numbers below 1
1340 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1342 * @return string the formatted value and its unit
1344 * @access public
1346 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1348 if ($value==0) return '0';
1350 $originalValue = $value;
1351 //number_format is not multibyte safe, str_replace is safe
1352 if ($digits_left === 0) {
1353 $value = number_format($value, $digits_right);
1354 if ($originalValue!=0 && floatval($value) == 0) $value = ' <'.(1/PMA_pow(10,$digits_right));
1356 return PMA_localizeNumber($value);
1359 // this units needs no translation, ISO
1360 $units = array(
1361 -8 => 'y',
1362 -7 => 'z',
1363 -6 => 'a',
1364 -5 => 'f',
1365 -4 => 'p',
1366 -3 => 'n',
1367 -2 => '&micro;',
1368 -1 => 'm',
1369 0 => ' ',
1370 1 => 'k',
1371 2 => 'M',
1372 3 => 'G',
1373 4 => 'T',
1374 5 => 'P',
1375 6 => 'E',
1376 7 => 'Z',
1377 8 => 'Y'
1380 // check for negative value to retain sign
1381 if ($value < 0) {
1382 $sign = '-';
1383 $value = abs($value);
1384 } else {
1385 $sign = '';
1388 $dh = PMA_pow(10, $digits_right);
1390 // This gives us the right SI prefix already, but $digits_left parameter not incorporated
1391 $d = floor(log10($value) / 3);
1392 // Lowering the SI prefix by 1 gives us an additional 3 zeros
1393 // So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits) to use, then lower the SI prefix
1394 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1395 if ($digits_left > $cur_digits) {
1396 $d-= floor(($digits_left - $cur_digits)/3);
1399 if ($d<0 && $only_down) $d=0;
1401 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1402 $unit = $units[$d];
1404 // If we dont want any zeros after the comma just add the thousand seperator
1405 if ($noTrailingZero)
1406 $value = PMA_localizeNumber(preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$value));
1407 else
1408 $value = PMA_localizeNumber(number_format($value, $digits_right)); //number_format is not multibyte safe, str_replace is safe
1410 if ($originalValue!=0 && floatval($value) == 0) return ' <'.(1/PMA_pow(10,$digits_right)).' '.$unit;
1412 return $sign . $value . ' ' . $unit;
1413 } // end of the 'PMA_formatNumber' function
1416 * Returns the number of bytes when a formatted size is given
1418 * @param string $formatted_size the size expression (for example 8MB)
1419 * @return integer The numerical part of the expression (for example 8)
1421 function PMA_extractValueFromFormattedSize($formatted_size)
1423 $return_value = -1;
1425 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1426 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1427 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1428 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1429 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1430 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1432 return $return_value;
1433 }// end of the 'PMA_extractValueFromFormattedSize' function
1436 * Writes localised date
1438 * @param string $timestamp the current timestamp
1439 * @param string $format format
1440 * @return string the formatted date
1442 * @access public
1444 function PMA_localisedDate($timestamp = -1, $format = '')
1446 $month = array(
1447 /* l10n: Short month name */
1448 __('Jan'),
1449 /* l10n: Short month name */
1450 __('Feb'),
1451 /* l10n: Short month name */
1452 __('Mar'),
1453 /* l10n: Short month name */
1454 __('Apr'),
1455 /* l10n: Short month name */
1456 _pgettext('Short month name', 'May'),
1457 /* l10n: Short month name */
1458 __('Jun'),
1459 /* l10n: Short month name */
1460 __('Jul'),
1461 /* l10n: Short month name */
1462 __('Aug'),
1463 /* l10n: Short month name */
1464 __('Sep'),
1465 /* l10n: Short month name */
1466 __('Oct'),
1467 /* l10n: Short month name */
1468 __('Nov'),
1469 /* l10n: Short month name */
1470 __('Dec'));
1471 $day_of_week = array(
1472 /* l10n: Short week day name */
1473 __('Sun'),
1474 /* l10n: Short week day name */
1475 __('Mon'),
1476 /* l10n: Short week day name */
1477 __('Tue'),
1478 /* l10n: Short week day name */
1479 __('Wed'),
1480 /* l10n: Short week day name */
1481 __('Thu'),
1482 /* l10n: Short week day name */
1483 __('Fri'),
1484 /* l10n: Short week day name */
1485 __('Sat'));
1487 if ($format == '') {
1488 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1489 $format = __('%B %d, %Y at %I:%M %p');
1492 if ($timestamp == -1) {
1493 $timestamp = time();
1496 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1497 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1499 return strftime($date, $timestamp);
1500 } // end of the 'PMA_localisedDate()' function
1504 * returns a tab for tabbed navigation.
1505 * If the variables $link and $args ar left empty, an inactive tab is created
1507 * @param array $tab array with all options
1508 * @param array $url_params
1509 * @return string html code for one tab, a link if valid otherwise a span
1510 * @access public
1512 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1514 // default values
1515 $defaults = array(
1516 'text' => '',
1517 'class' => '',
1518 'active' => null,
1519 'link' => '',
1520 'sep' => '?',
1521 'attr' => '',
1522 'args' => '',
1523 'warning' => '',
1524 'fragment' => '',
1525 'id' => '',
1528 $tab = array_merge($defaults, $tab);
1530 // determine additionnal style-class
1531 if (empty($tab['class'])) {
1532 if (! empty($tab['active'])
1533 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1534 $tab['class'] = 'active';
1535 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1536 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1537 && empty($tab['warning'])) {
1538 $tab['class'] = 'active';
1542 if (!empty($tab['warning'])) {
1543 $tab['class'] .= ' error';
1544 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1547 // If there are any tab specific URL parameters, merge those with the general URL parameters
1548 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1549 $url_params = array_merge($url_params, $tab['url_params']);
1552 // build the link
1553 if (!empty($tab['link'])) {
1554 $tab['link'] = htmlentities($tab['link']);
1555 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1556 if (! empty($tab['args'])) {
1557 foreach ($tab['args'] as $param => $value) {
1558 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1559 . urlencode($value);
1564 if (! empty($tab['fragment'])) {
1565 $tab['link'] .= $tab['fragment'];
1568 // display icon, even if iconic is disabled but the link-text is missing
1569 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1570 && isset($tab['icon'])) {
1571 // avoid generating an alt tag, because it only illustrates
1572 // the text that follows and if browser does not display
1573 // images, the text is duplicated
1574 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1575 .' width="16" height="16" alt="" />%2$s';
1576 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1578 // check to not display an empty link-text
1579 elseif (empty($tab['text'])) {
1580 $tab['text'] = '?';
1581 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1582 E_USER_NOTICE);
1585 //Set the id for the tab, if set in the params
1586 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1587 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1589 if (!empty($tab['link'])) {
1590 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1591 .$id_string
1592 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1593 . $tab['text'] . '</a>';
1594 } else {
1595 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1596 . $tab['text'] . '</span>';
1599 $out .= '</li>';
1600 return $out;
1601 } // end of the 'PMA_generate_html_tab()' function
1604 * returns html-code for a tab navigation
1606 * @param array $tabs one element per tab
1607 * @param string $url_params
1608 * @return string html-code for tab-navigation
1610 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1612 $tag_id = 'topmenu';
1613 $tab_navigation =
1614 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1615 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1617 foreach ($tabs as $tab) {
1618 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1621 $tab_navigation .=
1622 '</ul>' . "\n"
1623 .'<div class="clearfloat"></div>'
1624 .'</div>' . "\n";
1626 return $tab_navigation;
1631 * Displays a link, or a button if the link's URL is too large, to
1632 * accommodate some browsers' limitations
1634 * @param string $url the URL
1635 * @param string $message the link message
1636 * @param mixed $tag_params string: js confirmation
1637 * array: additional tag params (f.e. style="")
1638 * @param boolean $new_form we set this to false when we are already in
1639 * a form, to avoid generating nested forms
1640 * @param boolean $strip_img
1641 * @param string $target
1643 * @return string the results to be echoed or saved in an array
1645 function PMA_linkOrButton($url, $message, $tag_params = array(),
1646 $new_form = true, $strip_img = false, $target = '')
1648 $url_length = strlen($url);
1649 // with this we should be able to catch case of image upload
1650 // into a (MEDIUM) BLOB; not worth generating even a form for these
1651 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1652 return '';
1656 if (! is_array($tag_params)) {
1657 $tmp = $tag_params;
1658 $tag_params = array();
1659 if (!empty($tmp)) {
1660 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1662 unset($tmp);
1664 if (! empty($target)) {
1665 $tag_params['target'] = htmlentities($target);
1668 $tag_params_strings = array();
1669 foreach ($tag_params as $par_name => $par_value) {
1670 // htmlspecialchars() only on non javascript
1671 $par_value = substr($par_name, 0, 2) == 'on'
1672 ? $par_value
1673 : htmlspecialchars($par_value);
1674 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1677 $displayed_message = '';
1678 // Add text if not already added
1679 if (stristr($message, '<img') && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true) && strip_tags($message)==$message) {
1680 $displayed_message = '<span>' . htmlspecialchars(preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)) . '</span>';
1683 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1684 // no whitespace within an <a> else Safari will make it part of the link
1685 $ret = "\n" . '<a href="' . $url . '" '
1686 . implode(' ', $tag_params_strings) . '>'
1687 . $message . $displayed_message . '</a>' . "\n";
1688 } else {
1689 // no spaces (linebreaks) at all
1690 // or after the hidden fields
1691 // IE will display them all
1693 // add class=link to submit button
1694 if (empty($tag_params['class'])) {
1695 $tag_params['class'] = 'link';
1698 // decode encoded url separators
1699 $separator = PMA_get_arg_separator();
1700 // on most places separator is still hard coded ...
1701 if ($separator !== '&') {
1702 // ... so always replace & with $separator
1703 $url = str_replace(htmlentities('&'), $separator, $url);
1704 $url = str_replace('&', $separator, $url);
1706 $url = str_replace(htmlentities($separator), $separator, $url);
1707 // end decode
1709 $url_parts = parse_url($url);
1710 $query_parts = explode($separator, $url_parts['query']);
1711 if ($new_form) {
1712 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1713 . ' method="post"' . $target . ' style="display: inline;">';
1714 $subname_open = '';
1715 $subname_close = '';
1716 $submit_link = '#';
1717 } else {
1718 $query_parts[] = 'redirect=' . $url_parts['path'];
1719 if (empty($GLOBALS['subform_counter'])) {
1720 $GLOBALS['subform_counter'] = 0;
1722 $GLOBALS['subform_counter']++;
1723 $ret = '';
1724 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1725 $subname_close = ']';
1726 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1728 foreach ($query_parts as $query_pair) {
1729 list($eachvar, $eachval) = explode('=', $query_pair);
1730 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1731 . $subname_close . '" value="'
1732 . htmlspecialchars(urldecode($eachval)) . '" />';
1733 } // end while
1735 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1736 . implode(' ', $tag_params_strings) . '>'
1737 . $message . ' ' . $displayed_message . '</a>' . "\n";
1739 if ($new_form) {
1740 $ret .= '</form>';
1742 } // end if... else...
1744 return $ret;
1745 } // end of the 'PMA_linkOrButton()' function
1749 * Returns a given timespan value in a readable format.
1751 * @param int $seconds the timespan
1753 * @return string the formatted value
1755 function PMA_timespanFormat($seconds)
1757 $days = floor($seconds / 86400);
1758 if ($days > 0) {
1759 $seconds -= $days * 86400;
1761 $hours = floor($seconds / 3600);
1762 if ($days > 0 || $hours > 0) {
1763 $seconds -= $hours * 3600;
1765 $minutes = floor($seconds / 60);
1766 if ($days > 0 || $hours > 0 || $minutes > 0) {
1767 $seconds -= $minutes * 60;
1769 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1773 * Takes a string and outputs each character on a line for itself. Used
1774 * mainly for horizontalflipped display mode.
1775 * Takes care of special html-characters.
1776 * Fulfills todo-item
1777 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1779 * @todo add a multibyte safe function PMA_STR_split()
1780 * @param string $string The string
1781 * @param string $Separator The Separator (defaults to "<br />\n")
1783 * @access public
1784 * @return string The flipped string
1786 function PMA_flipstring($string, $Separator = "<br />\n")
1788 $format_string = '';
1789 $charbuff = false;
1791 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1792 $char = $string{$i};
1793 $append = false;
1795 if ($char == '&') {
1796 $format_string .= $charbuff;
1797 $charbuff = $char;
1798 } elseif ($char == ';' && !empty($charbuff)) {
1799 $format_string .= $charbuff . $char;
1800 $charbuff = false;
1801 $append = true;
1802 } elseif (! empty($charbuff)) {
1803 $charbuff .= $char;
1804 } else {
1805 $format_string .= $char;
1806 $append = true;
1809 // do not add separator after the last character
1810 if ($append && ($i != $str_len - 1)) {
1811 $format_string .= $Separator;
1815 return $format_string;
1819 * Function added to avoid path disclosures.
1820 * Called by each script that needs parameters, it displays
1821 * an error message and, by default, stops the execution.
1823 * Not sure we could use a strMissingParameter message here,
1824 * would have to check if the error message file is always available
1826 * @todo use PMA_fatalError() if $die === true?
1827 * @param array $params The names of the parameters needed by the calling script.
1828 * @param bool $die Stop the execution?
1829 * (Set this manually to false in the calling script
1830 * until you know all needed parameters to check).
1831 * @param bool $request Whether to include this list in checking for special params.
1832 * @global string path to current script
1833 * @global boolean flag whether any special variable was required
1835 * @access public
1837 function PMA_checkParameters($params, $die = true, $request = true)
1839 global $checked_special;
1841 if (! isset($checked_special)) {
1842 $checked_special = false;
1845 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1846 $found_error = false;
1847 $error_message = '';
1849 foreach ($params as $param) {
1850 if ($request && $param != 'db' && $param != 'table') {
1851 $checked_special = true;
1854 if (! isset($GLOBALS[$param])) {
1855 $error_message .= $reported_script_name
1856 . ': ' . __('Missing parameter:') . ' '
1857 . $param
1858 . PMA_showDocu('faqmissingparameters')
1859 . '<br />';
1860 $found_error = true;
1863 if ($found_error) {
1865 * display html meta tags
1867 require_once './libraries/header_meta_style.inc.php';
1868 echo '</head><body><p>' . $error_message . '</p></body></html>';
1869 if ($die) {
1870 exit();
1873 } // end function
1876 * Function to generate unique condition for specified row.
1878 * @param resource $handle current query result
1879 * @param integer $fields_cnt number of fields
1880 * @param array $fields_meta meta information about fields
1881 * @param array $row current row
1882 * @param boolean $force_unique generate condition only on pk or unique
1884 * @access public
1885 * @return array the calculated condition and whether condition is unique
1887 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1889 $primary_key = '';
1890 $unique_key = '';
1891 $nonprimary_condition = '';
1892 $preferred_condition = '';
1894 for ($i = 0; $i < $fields_cnt; ++$i) {
1895 $condition = '';
1896 $field_flags = PMA_DBI_field_flags($handle, $i);
1897 $meta = $fields_meta[$i];
1899 // do not use a column alias in a condition
1900 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1901 $meta->orgname = $meta->name;
1903 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1904 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1905 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
1906 // need (string) === (string)
1907 // '' !== 0 but '' == 0
1908 if ((string) $select_expr['alias'] === (string) $meta->name) {
1909 $meta->orgname = $select_expr['column'];
1910 break;
1911 } // end if
1912 } // end foreach
1916 // Do not use a table alias in a condition.
1917 // Test case is:
1918 // select * from galerie x WHERE
1919 //(select count(*) from galerie y where y.datum=x.datum)>1
1921 // But orgtable is present only with mysqli extension so the
1922 // fix is only for mysqli.
1923 // Also, do not use the original table name if we are dealing with
1924 // a view because this view might be updatable.
1925 // (The isView() verification should not be costly in most cases
1926 // because there is some caching in the function).
1927 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1928 $meta->table = $meta->orgtable;
1931 // to fix the bug where float fields (primary or not)
1932 // can't be matched because of the imprecision of
1933 // floating comparison, use CONCAT
1934 // (also, the syntax "CONCAT(field) IS NULL"
1935 // that we need on the next "if" will work)
1936 if ($meta->type == 'real') {
1937 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1938 . PMA_backquote($meta->orgname) . ') ';
1939 } else {
1940 $condition = ' ' . PMA_backquote($meta->table) . '.'
1941 . PMA_backquote($meta->orgname) . ' ';
1942 } // end if... else...
1944 if (! isset($row[$i]) || is_null($row[$i])) {
1945 $condition .= 'IS NULL AND';
1946 } else {
1947 // timestamp is numeric on some MySQL 4.1
1948 // for real we use CONCAT above and it should compare to string
1949 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
1950 $condition .= '= ' . $row[$i] . ' AND';
1951 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1952 // hexify only if this is a true not empty BLOB or a BINARY
1953 && stristr($field_flags, 'BINARY')
1954 && !empty($row[$i])) {
1955 // do not waste memory building a too big condition
1956 if (strlen($row[$i]) < 1000) {
1957 // use a CAST if possible, to avoid problems
1958 // if the field contains wildcard characters % or _
1959 $condition .= '= CAST(0x' . bin2hex($row[$i])
1960 . ' AS BINARY) AND';
1961 } else {
1962 // this blob won't be part of the final condition
1963 $condition = '';
1965 } elseif ($meta->type == 'bit') {
1966 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
1967 } else {
1968 $condition .= '= \''
1969 . PMA_sqlAddSlashes($row[$i], false, true) . '\' AND';
1972 if ($meta->primary_key > 0) {
1973 $primary_key .= $condition;
1974 } elseif ($meta->unique_key > 0) {
1975 $unique_key .= $condition;
1977 $nonprimary_condition .= $condition;
1978 } // end for
1980 // Correction University of Virginia 19991216:
1981 // prefer primary or unique keys for condition,
1982 // but use conjunction of all values if no primary key
1983 $clause_is_unique = true;
1984 if ($primary_key) {
1985 $preferred_condition = $primary_key;
1986 } elseif ($unique_key) {
1987 $preferred_condition = $unique_key;
1988 } elseif (! $force_unique) {
1989 $preferred_condition = $nonprimary_condition;
1990 $clause_is_unique = false;
1993 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
1994 return(array($where_clause, $clause_is_unique));
1995 } // end function
1998 * Generate a button or image tag
2000 * @param string $button_name name of button element
2001 * @param string $button_class class of button element
2002 * @param string $image_name name of image element
2003 * @param string $text text to display
2004 * @param string $image image to display
2005 * @param string $value
2007 * @access public
2009 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2010 $image, $value = '')
2012 if ($value == '') {
2013 $value = $text;
2015 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2016 echo ' <input type="submit" name="' . $button_name . '"'
2017 .' value="' . htmlspecialchars($value) . '"'
2018 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2019 return;
2022 /* Opera has trouble with <input type="image"> */
2023 /* IE has trouble with <button> */
2024 if (PMA_USR_BROWSER_AGENT != 'IE') {
2025 echo '<button class="' . $button_class . '" type="submit"'
2026 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2027 .' title="' . htmlspecialchars($text) . '">' . "\n"
2028 . PMA_getIcon($image, $text)
2029 .'</button>' . "\n";
2030 } else {
2031 echo '<input type="image" name="' . $image_name . '" value="'
2032 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2033 . $image . '" />'
2034 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2036 } // end function
2039 * Generate a pagination selector for browsing resultsets
2041 * @param int $rows Number of rows in the pagination set
2042 * @param int $pageNow current page number
2043 * @param int $nbTotalPage number of total pages
2044 * @param int $showAll If the number of pages is lower than this
2045 * variable, no pages will be omitted in pagination
2046 * @param int $sliceStart How many rows at the beginning should always be shown?
2047 * @param int $sliceEnd How many rows at the end should always be shown?
2048 * @param int $percent Percentage of calculation page offsets to hop to a next page
2049 * @param int $range Near the current page, how many pages should
2050 * be considered "nearby" and displayed as well?
2051 * @param string $prompt The prompt to display (sometimes empty)
2053 * @return string
2054 * @access public
2056 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2057 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2058 $range = 10, $prompt = '')
2060 $increment = floor($nbTotalPage / $percent);
2061 $pageNowMinusRange = ($pageNow - $range);
2062 $pageNowPlusRange = ($pageNow + $range);
2064 $gotopage = $prompt . ' <select id="pageselector" ';
2065 if ($GLOBALS['cfg']['AjaxEnable']) {
2066 $gotopage .= ' class="ajax"';
2068 $gotopage .= ' name="pos" >' . "\n";
2069 if ($nbTotalPage < $showAll) {
2070 $pages = range(1, $nbTotalPage);
2071 } else {
2072 $pages = array();
2074 // Always show first X pages
2075 for ($i = 1; $i <= $sliceStart; $i++) {
2076 $pages[] = $i;
2079 // Always show last X pages
2080 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2081 $pages[] = $i;
2084 // Based on the number of results we add the specified
2085 // $percent percentage to each page number,
2086 // so that we have a representing page number every now and then to
2087 // immediately jump to specific pages.
2088 // As soon as we get near our currently chosen page ($pageNow -
2089 // $range), every page number will be shown.
2090 $i = $sliceStart;
2091 $x = $nbTotalPage - $sliceEnd;
2092 $met_boundary = false;
2093 while ($i <= $x) {
2094 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2095 // If our pageselector comes near the current page, we use 1
2096 // counter increments
2097 $i++;
2098 $met_boundary = true;
2099 } else {
2100 // We add the percentage increment to our current page to
2101 // hop to the next one in range
2102 $i += $increment;
2104 // Make sure that we do not cross our boundaries.
2105 if ($i > $pageNowMinusRange && ! $met_boundary) {
2106 $i = $pageNowMinusRange;
2110 if ($i > 0 && $i <= $x) {
2111 $pages[] = $i;
2115 // Since because of ellipsing of the current page some numbers may be double,
2116 // we unify our array:
2117 sort($pages);
2118 $pages = array_unique($pages);
2121 foreach ($pages as $i) {
2122 if ($i == $pageNow) {
2123 $selected = 'selected="selected" style="font-weight: bold"';
2124 } else {
2125 $selected = '';
2127 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2130 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2132 return $gotopage;
2133 } // end function
2137 * Generate navigation for a list
2139 * @todo use $pos from $_url_params
2140 * @param int $count number of elements in the list
2141 * @param int $pos current position in the list
2142 * @param array $_url_params url parameters
2143 * @param string $script script name for form target
2144 * @param string $frame target frame
2145 * @param int $max_count maximum number of elements to display from the list
2147 * @access public
2149 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2151 if ($max_count < $count) {
2152 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2153 echo __('Page number:');
2154 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2156 // Move to the beginning or to the previous page
2157 if ($pos > 0) {
2158 // patch #474210 - part 1
2159 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2160 $caption1 = '&lt;&lt;';
2161 $caption2 = ' &lt; ';
2162 $title1 = ' title="' . __('Begin') . '"';
2163 $title2 = ' title="' . __('Previous') . '"';
2164 } else {
2165 $caption1 = __('Begin') . ' &lt;&lt;';
2166 $caption2 = __('Previous') . ' &lt;';
2167 $title1 = '';
2168 $title2 = '';
2169 } // end if... else...
2170 $_url_params['pos'] = 0;
2171 echo '<a' . $title1 . ' href="' . $script
2172 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2173 . $caption1 . '</a>';
2174 $_url_params['pos'] = $pos - $max_count;
2175 echo '<a' . $title2 . ' href="' . $script
2176 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2177 . $caption2 . '</a>';
2180 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2181 echo PMA_generate_common_hidden_inputs($_url_params);
2182 echo PMA_pageselector(
2183 $max_count,
2184 floor(($pos + 1) / $max_count) + 1,
2185 ceil($count / $max_count));
2186 echo '</form>';
2188 if ($pos + $max_count < $count) {
2189 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2190 $caption3 = ' &gt; ';
2191 $caption4 = '&gt;&gt;';
2192 $title3 = ' title="' . __('Next') . '"';
2193 $title4 = ' title="' . __('End') . '"';
2194 } else {
2195 $caption3 = '&gt; ' . __('Next');
2196 $caption4 = '&gt;&gt; ' . __('End');
2197 $title3 = '';
2198 $title4 = '';
2199 } // end if... else...
2200 $_url_params['pos'] = $pos + $max_count;
2201 echo '<a' . $title3 . ' href="' . $script
2202 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2203 . $caption3 . '</a>';
2204 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2205 if ($_url_params['pos'] == $count) {
2206 $_url_params['pos'] = $count - $max_count;
2208 echo '<a' . $title4 . ' href="' . $script
2209 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2210 . $caption4 . '</a>';
2212 echo "\n";
2213 if ('frame_navigation' == $frame) {
2214 echo '</div>' . "\n";
2220 * replaces %u in given path with current user name
2222 * example:
2223 * <code>
2224 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2226 * </code>
2227 * @param string $dir with wildcard for user
2228 * @return string per user directory
2230 function PMA_userDir($dir)
2232 // add trailing slash
2233 if (substr($dir, -1) != '/') {
2234 $dir .= '/';
2237 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2241 * returns html code for db link to default db page
2243 * @param string $database
2244 * @return string html link to default db page
2246 function PMA_getDbLink($database = null)
2248 if (! strlen($database)) {
2249 if (! strlen($GLOBALS['db'])) {
2250 return '';
2252 $database = $GLOBALS['db'];
2253 } else {
2254 $database = PMA_unescape_mysql_wildcards($database);
2257 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2258 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2259 .htmlspecialchars($database) . '</a>';
2263 * Displays a lightbulb hint explaining a known external bug
2264 * that affects a functionality
2266 * @param string $functionality localized message explaining the func.
2267 * @param string $component 'mysql' (eventually, 'php')
2268 * @param string $minimum_version of this component
2269 * @param string $bugref bug reference for this component
2271 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2273 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2274 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2279 * Generates and echoes an HTML checkbox
2281 * @param string $html_field_name the checkbox HTML field
2282 * @param string $label
2283 * @param boolean $checked is it initially checked?
2284 * @param boolean $onclick should it submit the form on click?
2286 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2288 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>';
2292 * Generates and echoes a set of radio HTML fields
2294 * @param string $html_field_name the radio HTML field
2295 * @param array $choices the choices values and labels
2296 * @param string $checked_choice the choice to check by default
2297 * @param boolean $line_break whether to add an HTML line break after a choice
2298 * @param boolean $escape_label whether to use htmlspecialchars() on label
2299 * @param string $class enclose each choice with a div of this class
2301 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2302 foreach ($choices as $choice_value => $choice_label) {
2303 if (! empty($class)) {
2304 echo '<div class="' . $class . '">';
2306 $html_field_id = $html_field_name . '_' . $choice_value;
2307 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2308 if ($choice_value == $checked_choice) {
2309 echo ' checked="checked"';
2311 echo ' />' . "\n";
2312 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2313 if ($line_break) {
2314 echo '<br />';
2316 if (! empty($class)) {
2317 echo '</div>';
2319 echo "\n";
2324 * Generates and returns an HTML dropdown
2326 * @param string $select_name
2327 * @param array $choices choices values
2328 * @param string $active_choice the choice to select by default
2329 * @param string $id id of the select element; can be different in case
2330 * the dropdown is present more than once on the page
2331 * @return string
2332 * @todo support titles
2334 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2336 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2337 foreach ($choices as $one_choice_value => $one_choice_label) {
2338 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2339 if ($one_choice_value == $active_choice) {
2340 $result .= ' selected="selected"';
2342 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2344 $result .= '</select>';
2345 return $result;
2349 * Generates a slider effect (jQjuery)
2350 * Takes care of generating the initial <div> and the link
2351 * controlling the slider; you have to generate the </div> yourself
2352 * after the sliding section.
2354 * @param string $id the id of the <div> on which to apply the effect
2355 * @param string $message the message to show as a link
2357 function PMA_generate_slider_effect($id, $message)
2359 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2360 echo '<div id="' . $id . '">';
2361 return;
2364 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2365 * opening the <div> with PHP itself instead of JavaScript.
2367 * @todo find a better solution that uses $.append(), the recommended method
2368 * maybe by using an additional param, the id of the div to append to
2371 <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); ?>">
2372 <?php
2376 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2378 * @param string $action The URL for the request to be executed
2379 * @param string $select_name The name for the dropdown box
2380 * @param array $options An array of options (see rte_footer.lib.php)
2381 * @param string $callback A JS snippet to execute when the request is
2382 * successfully processed
2384 * @return string HTML code for the toggle button
2386 function PMA_toggleButton($action, $select_name, $options, $callback)
2388 // Do the logic first
2389 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2390 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2391 if ($options[1]['selected'] == true) {
2392 $state = 'on';
2393 } else if ($options[0]['selected'] == true) {
2394 $state = 'off';
2395 } else {
2396 $state = 'on';
2398 $selected1 = '';
2399 $selected0 = '';
2400 if ($options[1]['selected'] == true) {
2401 $selected1 = " selected='selected'";
2402 } else if ($options[0]['selected'] == true) {
2403 $selected0 = " selected='selected'";
2405 // Generate output
2406 $retval = "<!-- TOGGLE START -->\n";
2407 if ($GLOBALS['cfg']['AjaxEnable']) {
2408 $retval .= "<noscript>\n";
2410 $retval .= "<div class='wrapper'>\n";
2411 $retval .= " <form action='$action' method='post'>\n";
2412 $retval .= " <select name='$select_name'>\n";
2413 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2414 $retval .= " {$options[1]['label']}\n";
2415 $retval .= " </option>\n";
2416 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2417 $retval .= " {$options[0]['label']}\n";
2418 $retval .= " </option>\n";
2419 $retval .= " </select>\n";
2420 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2421 $retval .= " </form>\n";
2422 $retval .= "</div>\n";
2423 if ($GLOBALS['cfg']['AjaxEnable']) {
2424 $retval .= "</noscript>\n";
2425 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2426 $retval .= " <div class='toggleButton'>\n";
2427 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2428 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2429 $retval .= " alt='' />\n";
2430 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2431 $retval .= " <tbody>\n";
2432 $retval .= " <td class='toggleOn'>\n";
2433 $retval .= " <span class='hide'>$link_on</span>\n";
2434 $retval .= " <div>";
2435 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2436 $retval .= " </td>\n";
2437 $retval .= " <td><div>&nbsp;</div></td>\n";
2438 $retval .= " <td class='toggleOff'>\n";
2439 $retval .= " <span class='hide'>$link_off</span>\n";
2440 $retval .= " <div>";
2441 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2442 $retval .= " </div>\n";
2443 $retval .= " </tbody>\n";
2444 $retval .= " </tr></table>\n";
2445 $retval .= " <span class='hide callback'>$callback</span>\n";
2446 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2447 $retval .= " </div>\n";
2448 $retval .= " </div>\n";
2449 $retval .= "</div>\n";
2451 $retval .= "<!-- TOGGLE END -->";
2453 return $retval;
2454 } // end PMA_toggleButton()
2457 * Clears cache content which needs to be refreshed on user change.
2459 function PMA_clearUserCache() {
2460 PMA_cacheUnset('is_superuser', true);
2464 * Verifies if something is cached in the session
2466 * @param string $var
2467 * @param int|true $server
2468 * @return boolean
2470 function PMA_cacheExists($var, $server = 0)
2472 if (true === $server) {
2473 $server = $GLOBALS['server'];
2475 return isset($_SESSION['cache']['server_' . $server][$var]);
2479 * Gets cached information from the session
2481 * @param string $var
2482 * @param int|true $server
2483 * @return mixed
2485 function PMA_cacheGet($var, $server = 0)
2487 if (true === $server) {
2488 $server = $GLOBALS['server'];
2490 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2491 return $_SESSION['cache']['server_' . $server][$var];
2492 } else {
2493 return null;
2498 * Caches information in the session
2500 * @param string $var
2501 * @param mixed $val
2502 * @param int|true $server
2503 * @return mixed
2505 function PMA_cacheSet($var, $val = null, $server = 0)
2507 if (true === $server) {
2508 $server = $GLOBALS['server'];
2510 $_SESSION['cache']['server_' . $server][$var] = $val;
2514 * Removes cached information from the session
2516 * @param string $var
2517 * @param int|true $server
2519 function PMA_cacheUnset($var, $server = 0)
2521 if (true === $server) {
2522 $server = $GLOBALS['server'];
2524 unset($_SESSION['cache']['server_' . $server][$var]);
2528 * Converts a bit value to printable format;
2529 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2530 * function because in PHP, decbin() supports only 32 bits
2532 * @param numeric $value coming from a BIT field
2533 * @param integer $length
2534 * @return string the printable value
2536 function PMA_printable_bit_value($value, $length) {
2537 $printable = '';
2538 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2539 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2541 $printable = substr($printable, -$length);
2542 return $printable;
2546 * Verifies whether the value contains a non-printable character
2548 * @param string $value
2549 * @return boolean
2551 function PMA_contains_nonprintable_ascii($value) {
2552 return preg_match('@[^[:print:]]@', $value);
2556 * Converts a BIT type default value
2557 * for example, b'010' becomes 010
2559 * @param string $bit_default_value
2560 * @return string the converted value
2562 function PMA_convert_bit_default_value($bit_default_value) {
2563 return strtr($bit_default_value, array("b" => "", "'" => ""));
2567 * Extracts the various parts from a field type spec
2569 * @param string $fieldspec
2570 * @return array associative array containing type, spec_in_brackets
2571 * and possibly enum_set_values (another array)
2573 function PMA_extractFieldSpec($fieldspec) {
2574 $first_bracket_pos = strpos($fieldspec, '(');
2575 if ($first_bracket_pos) {
2576 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2577 // convert to lowercase just to be sure
2578 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2579 } else {
2580 $type = $fieldspec;
2581 $spec_in_brackets = '';
2584 if ('enum' == $type || 'set' == $type) {
2585 // Define our working vars
2586 $enum_set_values = array();
2587 $working = "";
2588 $in_string = false;
2589 $index = 0;
2591 // While there is another character to process
2592 while (isset($fieldspec[$index])) {
2593 // Grab the char to look at
2594 $char = $fieldspec[$index];
2596 // If it is a single quote, needs to be handled specially
2597 if ($char == "'") {
2598 // If we are not currently in a string, begin one
2599 if (! $in_string) {
2600 $in_string = true;
2601 $working = "";
2602 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2603 } else {
2604 // Check out the next character (if possible)
2605 $has_next = isset($fieldspec[$index + 1]);
2606 $next = $has_next ? $fieldspec[$index + 1] : null;
2608 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2609 if (! $has_next || $next != "'") {
2610 $enum_set_values[] = $working;
2611 $in_string = false;
2613 // Otherwise, this is a 'double quote', and can be added to the working string
2614 } elseif ($next == "'") {
2615 $working .= "'";
2616 // Skip the next char; we already know what it is
2617 $index++;
2620 // escaping of a quote?
2621 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2622 $working .= "'";
2623 $index++;
2624 // Otherwise, add it to our working string like normal
2625 } else {
2626 $working .= $char;
2628 // Increment character index
2629 $index++;
2630 } // end while
2631 } else {
2632 $enum_set_values = array();
2635 return array(
2636 'type' => $type,
2637 'spec_in_brackets' => $spec_in_brackets,
2638 'enum_set_values' => $enum_set_values
2643 * Verifies if this table's engine supports foreign keys
2645 * @param string $engine
2646 * @return boolean
2648 function PMA_foreignkey_supported($engine) {
2649 $engine = strtoupper($engine);
2650 if ('INNODB' == $engine || 'PBXT' == $engine) {
2651 return true;
2652 } else {
2653 return false;
2658 * Replaces some characters by a displayable equivalent
2660 * @param string $content
2661 * @return string the content with characters replaced
2663 function PMA_replace_binary_contents($content) {
2664 $result = str_replace("\x00", '\0', $content);
2665 $result = str_replace("\x08", '\b', $result);
2666 $result = str_replace("\x0a", '\n', $result);
2667 $result = str_replace("\x0d", '\r', $result);
2668 $result = str_replace("\x1a", '\Z', $result);
2669 return $result;
2673 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2675 * @param string $string
2676 * @return string with the chars replaced
2679 function PMA_duplicateFirstNewline($string) {
2680 $first_occurence = strpos($string, "\r\n");
2681 if ($first_occurence === 0) {
2682 $string = "\n".$string;
2684 return $string;
2688 * Get the action word corresponding to a script name
2689 * in order to display it as a title in navigation panel
2691 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2692 * or $cfg['DefaultTabDatabase']
2693 * @return array
2695 function PMA_getTitleForTarget($target) {
2696 $mapping = array(
2697 // Values for $cfg['DefaultTabTable']
2698 'tbl_structure.php' => __('Structure'),
2699 'tbl_sql.php' => __('SQL'),
2700 'tbl_select.php' =>__('Search'),
2701 'tbl_change.php' =>__('Insert'),
2702 'sql.php' => __('Browse'),
2704 // Values for $cfg['DefaultTabDatabase']
2705 'db_structure.php' => __('Structure'),
2706 'db_sql.php' => __('SQL'),
2707 'db_search.php' => __('Search'),
2708 'db_operations.php' => __('Operations'),
2710 return $mapping[$target];
2714 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2716 * @param string $string Text where to do expansion.
2717 * @param function $escape Function to call for escaping variable values.
2718 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2719 * @return string
2721 function PMA_expandUserString($string, $escape = null, $updates = array()) {
2722 /* Content */
2723 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2724 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2725 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2726 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2727 $vars['database'] = $GLOBALS['db'];
2728 $vars['table'] = $GLOBALS['table'];
2729 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2731 /* Update forced variables */
2732 foreach ($updates as $key => $val) {
2733 $vars[$key] = $val;
2736 /* Replacement mapping */
2738 * The __VAR__ ones are for backward compatibility, because user
2739 * might still have it in cookies.
2741 $replace = array(
2742 '@HTTP_HOST@' => $vars['http_host'],
2743 '@SERVER@' => $vars['server_name'],
2744 '__SERVER__' => $vars['server_name'],
2745 '@VERBOSE@' => $vars['server_verbose'],
2746 '@VSERVER@' => $vars['server_verbose_or_name'],
2747 '@DATABASE@' => $vars['database'],
2748 '__DB__' => $vars['database'],
2749 '@TABLE@' => $vars['table'],
2750 '__TABLE__' => $vars['table'],
2751 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2754 /* Optional escaping */
2755 if (!is_null($escape)) {
2756 foreach ($replace as $key => $val) {
2757 $replace[$key] = $escape($val);
2761 /* Fetch fields list if required */
2762 if (strpos($string, '@FIELDS@') !== false) {
2763 $fields_list = PMA_DBI_fetch_result(
2764 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2765 . '.' . PMA_backquote($GLOBALS['table']));
2767 $field_names = array();
2768 foreach ($fields_list as $field) {
2769 if (!is_null($escape)) {
2770 $field_names[] = $escape($field['Field']);
2771 } else {
2772 $field_names[] = $field['Field'];
2776 $replace['@FIELDS@'] = implode(',', $field_names);
2779 /* Do the replacement */
2780 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2784 * function that generates a json output for an ajax request and ends script
2785 * execution
2787 * @param bool $message message string containing the html of the message
2788 * @param bool $success success whether the ajax request was successfull
2789 * @param array $extra_data extra_data optional - any other data as part of the json request
2792 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2794 $response = array();
2795 if ( $success == true ) {
2796 $response['success'] = true;
2797 if ($message instanceof PMA_Message) {
2798 $response['message'] = $message->getDisplay();
2800 else {
2801 $response['message'] = $message;
2804 else {
2805 $response['success'] = false;
2806 if ($message instanceof PMA_Message) {
2807 $response['error'] = $message->getDisplay();
2809 else {
2810 $response['error'] = $message;
2814 // If extra_data has been provided, append it to the response array
2815 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
2816 $response = array_merge($response, $extra_data);
2819 // Set the Content-Type header to JSON so that jQuery parses the
2820 // response correctly.
2822 // At this point, other headers might have been sent;
2823 // even if $GLOBALS['is_header_sent'] is true,
2824 // we have to send these additional headers.
2825 header('Cache-Control: no-cache');
2826 header("Content-Type: application/json");
2828 echo json_encode($response);
2830 if (!defined('TESTSUITE'))
2831 exit;
2835 * Display the form used to browse anywhere on the local server for the file to import
2837 * @param $max_upload_size
2839 function PMA_browseUploadFile($max_upload_size) {
2840 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2841 echo '<div id="upload_form_status" style="display: none;"></div>';
2842 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2843 echo '<input type="file" name="import_file" id="input_import_file" />';
2844 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2845 // some browsers should respect this :)
2846 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2850 * Display the form used to select a file to import from the server upload directory
2852 * @param $import_list
2853 * @param $uploaddir
2855 function PMA_selectUploadFile($import_list, $uploaddir) {
2856 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2857 $extensions = '';
2858 foreach ($import_list as $key => $val) {
2859 if (!empty($extensions)) {
2860 $extensions .= '|';
2862 $extensions .= $val['extension'];
2864 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2866 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2867 if ($files === false) {
2868 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2869 } elseif (!empty($files)) {
2870 echo "\n";
2871 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2872 echo ' <option value="">&nbsp;</option>' . "\n";
2873 echo $files;
2874 echo ' </select>' . "\n";
2875 } elseif (empty ($files)) {
2876 echo '<i>' . __('There are no files to upload') . '</i>';
2881 * Build titles and icons for action links
2883 * @return array the action titles
2885 function PMA_buildActionTitles() {
2886 $titles = array();
2888 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2889 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2890 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2891 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2892 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2893 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2894 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2895 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2896 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2897 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2898 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2899 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
2900 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'), true);
2901 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'), true);
2902 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'), true);
2903 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'), true);
2904 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'), true);
2905 return $titles;
2909 * This function processes the datatypes supported by the DB, as specified in
2910 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
2911 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
2913 * @param bool $html Whether to generate an html snippet or an array
2914 * @param string $selected The value to mark as selected in HTML mode
2916 * @return mixed An HTML snippet or an array of datatypes.
2919 function PMA_getSupportedDatatypes($html = false, $selected = '')
2921 global $cfg;
2923 if ($html) {
2924 // NOTE: the SELECT tag in not included in this snippet.
2925 $retval = '';
2926 foreach ($cfg['ColumnTypes'] as $key => $value) {
2927 if (is_array($value)) {
2928 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
2929 foreach ($value as $subvalue) {
2930 if ($subvalue == $selected) {
2931 $retval .= "<option selected='selected'>";
2932 $retval .= $subvalue;
2933 $retval .= "</option>";
2934 } else if ($subvalue === '-') {
2935 $retval .= "<option disabled='disabled'>";
2936 $retval .= $subvalue;
2937 $retval .= "</option>";
2938 } else {
2939 $retval .= "<option>$subvalue</option>";
2942 $retval .= '</optgroup>';
2943 } else {
2944 if ($selected == $value) {
2945 $retval .= "<option selected='selected'>$value</option>";
2946 } else {
2947 $retval .= "<option>$value</option>";
2951 } else {
2952 $retval = array();
2953 foreach ($cfg['ColumnTypes'] as $value) {
2954 if (is_array($value)) {
2955 foreach ($value as $subvalue) {
2956 if ($subvalue !== '-') {
2957 $retval[] = $subvalue;
2960 } else {
2961 if ($value !== '-') {
2962 $retval[] = $value;
2968 return $retval;
2969 } // end PMA_getSupportedDatatypes()
2972 * Returns a list of datatypes that are not (yet) handled by PMA.
2973 * Used by: tbl_change.php and libraries/db_routines.inc.php
2975 * @return array list of datatypes
2978 function PMA_unsupportedDatatypes() {
2979 // These GIS data types are not yet supported.
2980 $no_support_types = array('geometry',
2981 'point',
2982 'linestring',
2983 'polygon',
2984 'multipoint',
2985 'multilinestring',
2986 'multipolygon',
2987 'geometrycollection'
2990 return $no_support_types;
2994 * Creates a dropdown box with MySQL functions for a particular column.
2996 * @param array $field Data about the column for which
2997 * to generate the dropdown
2998 * @param bool $insert_mode Whether the operation is 'insert'
3000 * @global array $cfg PMA configuration
3001 * @global array $analyzed_sql Analyzed SQL query
3002 * @global mixed $data (null/string) FIXME: what is this for?
3004 * @return string An HTML snippet of a dropdown list with function
3005 * names appropriate for the requested column.
3007 function PMA_getFunctionsForField($field, $insert_mode)
3009 global $cfg, $analyzed_sql, $data;
3011 $selected = '';
3012 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3013 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3014 // which will then reveal the available dropdown options
3015 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3016 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3017 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3018 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3019 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3020 } else {
3021 $dropdown = array();
3022 $default_function = '';
3024 $dropdown_built = array();
3025 $op_spacing_needed = false;
3026 // what function defined as default?
3027 // for the first timestamp we don't set the default function
3028 // if there is a default value for the timestamp
3029 // (not including CURRENT_TIMESTAMP)
3030 // and the column does not have the
3031 // ON UPDATE DEFAULT TIMESTAMP attribute.
3032 if ($field['True_Type'] == 'timestamp'
3033 && empty($field['Default'])
3034 && empty($data)
3035 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3036 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3038 // For primary keys of type char(36) or varchar(36) UUID if the default function
3039 // Only applies to insert mode, as it would silently trash data on updates.
3040 if ($insert_mode
3041 && $field['Key'] == 'PRI'
3042 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3044 $default_function = $cfg['DefaultFunctions']['pk_char36'];
3046 // this is set only when appropriate and is always true
3047 if (isset($field['display_binary_as_hex'])) {
3048 $default_function = 'UNHEX';
3051 // Create the output
3052 $retval = ' <option></option>' . "\n";
3053 // loop on the dropdown array and print all available options for that field.
3054 foreach ($dropdown as $each_dropdown) {
3055 $retval .= ' ';
3056 $retval .= '<option';
3057 if ($default_function === $each_dropdown) {
3058 $retval .= ' selected="selected"';
3060 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3061 $dropdown_built[$each_dropdown] = 'true';
3062 $op_spacing_needed = true;
3064 // For compatibility's sake, do not let out all other functions. Instead
3065 // print a separator (blank) and then show ALL functions which weren't shown
3066 // yet.
3067 $cnt_functions = count($cfg['Functions']);
3068 for ($j = 0; $j < $cnt_functions; $j++) {
3069 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3070 // Is current function defined as default?
3071 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3072 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3073 ? ' selected="selected"'
3074 : '';
3075 if ($op_spacing_needed == true) {
3076 $retval .= ' ';
3077 $retval .= '<option value="">--------</option>' . "\n";
3078 $op_spacing_needed = false;
3081 $retval .= ' ';
3082 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3084 } // end for
3086 return $retval;
3087 } // end PMA_getFunctionsForField()
3090 * Checks if the current user has a specific privilege and returns true if the
3091 * user indeed has that privilege or false if (s)he doesn't. This function must
3092 * only be used for features that are available since MySQL 5, because it
3093 * relies on the INFORMATION_SCHEMA database to be present.
3095 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3096 * // Checks if the currently logged in user has the global
3097 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3098 * // user has this privilege on database 'mydb'.
3101 * @param string $priv The privilege to check
3102 * @param mixed $db null, to only check global privileges
3103 * string, db name where to also check for privileges
3104 * @param mixed $tbl null, to only check global privileges
3105 * string, db name where to also check for privileges
3106 * @return bool
3108 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3110 // Get the username for the current user in the format
3111 // required to use in the information schema database.
3112 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3113 if ($user === false) {
3114 return false;
3116 $user = explode('@', $user);
3117 $username = "''";
3118 $username .= str_replace("'", "''", $user[0]);
3119 $username .= "''@''";
3120 $username .= str_replace("'", "''", $user[1]);
3121 $username .= "''";
3122 // Prepage the query
3123 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3124 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3125 // Check global privileges first.
3126 if (PMA_DBI_fetch_value(sprintf($query,
3127 'USER_PRIVILEGES',
3128 $username,
3129 $priv))) {
3130 return true;
3132 // If a database name was provided and user does not have the
3133 // required global privilege, try database-wise permissions.
3134 if ($db !== null) {
3135 $query .= " AND TABLE_SCHEMA='%s'";
3136 if (PMA_DBI_fetch_value(sprintf($query,
3137 'SCHEMA_PRIVILEGES',
3138 $username,
3139 $priv,
3140 PMA_sqlAddSlashes($db)))) {
3141 return true;
3143 } else {
3144 // There was no database name provided and the user
3145 // does not have the correct global privilege.
3146 return false;
3148 // If a table name was also provided and we still didn't
3149 // find any valid privileges, try table-wise privileges.
3150 if ($tbl !== null) {
3151 $query .= " AND TABLE_NAME='%s'";
3152 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3153 'TABLE_PRIVILEGES',
3154 $username,
3155 $priv,
3156 PMA_sqlAddSlashes($db),
3157 PMA_sqlAddSlashes($tbl)))) {
3158 return true;
3161 // If we reached this point, the user does not
3162 // have even valid table-wise privileges.
3163 return false;