Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / libraries / common.lib.php
blob64a8b4a8871ee27430903483798d68d172684534
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 = $table['TABLE_TYPE'] == 'VIEW';
691 if ($tbl_is_view || strtolower($db) == 'information_schema'
692 || (PMA_DRIZZLE && strtolower($db) == 'data_dictionary')) {
693 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'], false, true);
697 // in $group we save the reference to the place in $table_groups
698 // where to store the table info
699 if ($GLOBALS['cfg']['LeftFrameDBTree']
700 && $sep && strstr($table_name, $sep))
702 $parts = explode($sep, $table_name);
704 $group =& $table_groups;
705 $i = 0;
706 $group_name_full = '';
707 $parts_cnt = count($parts) - 1;
708 while ($i < $parts_cnt
709 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
710 $group_name = $parts[$i] . $sep;
711 $group_name_full .= $group_name;
713 if (! isset($group[$group_name])) {
714 $group[$group_name] = array();
715 $group[$group_name]['is' . $sep . 'group'] = true;
716 $group[$group_name]['tab' . $sep . 'count'] = 1;
717 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
718 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
719 $table = $group[$group_name];
720 $group[$group_name] = array();
721 $group[$group_name][$group_name] = $table;
722 unset($table);
723 $group[$group_name]['is' . $sep . 'group'] = true;
724 $group[$group_name]['tab' . $sep . 'count'] = 1;
725 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
726 } else {
727 $group[$group_name]['tab' . $sep . 'count']++;
729 $group =& $group[$group_name];
730 $i++;
732 } else {
733 if (! isset($table_groups[$table_name])) {
734 $table_groups[$table_name] = array();
736 $group =& $table_groups;
740 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
741 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
742 // switch tooltip and name
743 $table['Comment'] = $table['Name'];
744 $table['disp_name'] = $table['Comment'];
745 } else {
746 $table['disp_name'] = $table['Name'];
749 $group[$table_name] = array_merge($default, $table);
752 return $table_groups;
755 /* ----------------------- Set of misc functions ----------------------- */
759 * Adds backquotes on both sides of a database, table or field name.
760 * and escapes backquotes inside the name with another backquote
762 * example:
763 * <code>
764 * echo PMA_backquote('owner`s db'); // `owner``s db`
766 * </code>
768 * @param mixed $a_name the database, table or field name to "backquote"
769 * or array of it
770 * @param boolean $do_it a flag to bypass this function (used by dump
771 * functions)
772 * @return mixed the "backquoted" database, table or field name
773 * @access public
775 function PMA_backquote($a_name, $do_it = true)
777 if (is_array($a_name)) {
778 foreach ($a_name as &$data) {
779 $data = PMA_backquote($data, $do_it);
781 return $a_name;
784 if (! $do_it) {
785 global $PMA_SQPdata_forbidden_word;
787 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
788 return $a_name;
792 // '0' is also empty for php :-(
793 if (strlen($a_name) && $a_name !== '*') {
794 return '`' . str_replace('`', '``', $a_name) . '`';
795 } else {
796 return $a_name;
798 } // end of the 'PMA_backquote()' function
801 * Defines the <CR><LF> value depending on the user OS.
803 * @return string the <CR><LF> value to use
805 * @access public
807 function PMA_whichCrlf()
809 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
810 // Win case
811 if (PMA_USR_OS == 'Win') {
812 $the_crlf = "\r\n";
814 // Others
815 else {
816 $the_crlf = "\n";
819 return $the_crlf;
820 } // end of the 'PMA_whichCrlf()' function
823 * Reloads navigation if needed.
825 * @param bool $jsonly prints out pure JavaScript
827 * @access public
829 function PMA_reloadNavigation($jsonly=false)
831 // Reloads the navigation frame via JavaScript if required
832 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
833 // one of the reasons for a reload is when a table is dropped
834 // in this case, get rid of the table limit offset, otherwise
835 // we have a problem when dropping a table on the last page
836 // and the offset becomes greater than the total number of tables
837 unset($_SESSION['tmp_user_values']['table_limit_offset']);
838 echo "\n";
839 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
840 if (!$jsonly)
841 echo '<script type="text/javascript">' . PHP_EOL;
843 //<![CDATA[
844 if (typeof(window.parent) != 'undefined'
845 && typeof(window.parent.frame_navigation) != 'undefined'
846 && window.parent.goTo) {
847 window.parent.goTo('<?php echo $reload_url; ?>');
849 //]]>
850 <?php
851 if (!$jsonly)
852 echo '</script>' . PHP_EOL;
854 unset($GLOBALS['reload']);
859 * displays the message and the query
860 * usually the message is the result of the query executed
862 * @param string $message the message to display
863 * @param string $sql_query the query to display
864 * @param string $type the type (level) of the message
865 * @param boolean $is_view is this a message after a VIEW operation?
866 * @return string
867 * @access public
869 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
872 * PMA_ajaxResponse uses this function to collect the string of HTML generated
873 * for showing the message. Use output buffering to collect it and return it
874 * in a string. In some special cases on sql.php, buffering has to be disabled
875 * and hence we check with $GLOBALS['buffer_message']
877 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
878 ob_start();
880 global $cfg;
882 if (null === $sql_query) {
883 if (! empty($GLOBALS['display_query'])) {
884 $sql_query = $GLOBALS['display_query'];
885 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
886 $sql_query = $GLOBALS['unparsed_sql'];
887 } elseif (! empty($GLOBALS['sql_query'])) {
888 $sql_query = $GLOBALS['sql_query'];
889 } else {
890 $sql_query = '';
894 if (isset($GLOBALS['using_bookmark_message'])) {
895 $GLOBALS['using_bookmark_message']->display();
896 unset($GLOBALS['using_bookmark_message']);
899 // Corrects the tooltip text via JS if required
900 // @todo this is REALLY the wrong place to do this - very unexpected here
901 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
902 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
903 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
904 echo "\n";
905 echo '<script type="text/javascript">' . "\n";
906 echo '//<![CDATA[' . "\n";
907 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
908 echo '//]]>' . "\n";
909 echo '</script>' . "\n";
910 } // end if ... elseif
912 // Checks if the table needs to be repaired after a TRUNCATE query.
913 // @todo what about $GLOBALS['display_query']???
914 // @todo this is REALLY the wrong place to do this - very unexpected here
915 if (strlen($GLOBALS['table'])
916 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
917 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
918 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
921 unset($tbl_status);
923 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
924 // check for it's presence before using it
925 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
927 if ($message instanceof PMA_Message) {
928 if (isset($GLOBALS['special_message'])) {
929 $message->addMessage($GLOBALS['special_message']);
930 unset($GLOBALS['special_message']);
932 $message->display();
933 $type = $message->getLevel();
934 } else {
935 echo '<div class="' . $type . '">';
936 echo PMA_sanitize($message);
937 if (isset($GLOBALS['special_message'])) {
938 echo PMA_sanitize($GLOBALS['special_message']);
939 unset($GLOBALS['special_message']);
941 echo '</div>';
944 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
945 // Html format the query to be displayed
946 // If we want to show some sql code it is easiest to create it here
947 /* SQL-Parser-Analyzer */
949 if (! empty($GLOBALS['show_as_php'])) {
950 $new_line = '\\n"<br />' . "\n"
951 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
952 $query_base = htmlspecialchars(addslashes($sql_query));
953 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
954 } else {
955 $query_base = $sql_query;
958 $query_too_big = false;
960 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
961 // when the query is large (for example an INSERT of binary
962 // data), the parser chokes; so avoid parsing the query
963 $query_too_big = true;
964 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
965 } elseif (! empty($GLOBALS['parsed_sql'])
966 && $query_base == $GLOBALS['parsed_sql']['raw']) {
967 // (here, use "! empty" because when deleting a bookmark,
968 // $GLOBALS['parsed_sql'] is set but empty
969 $parsed_sql = $GLOBALS['parsed_sql'];
970 } else {
971 // Parse SQL if needed
972 $parsed_sql = PMA_SQP_parse($query_base);
973 if (PMA_SQP_isError()) {
974 unset($parsed_sql);
978 // Analyze it
979 if (isset($parsed_sql)) {
980 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
982 // Same as below (append LIMIT), append the remembered ORDER BY
983 if ($GLOBALS['cfg']['RememberSorting']
984 && isset($analyzed_display_query[0]['queryflags']['select_from'])
985 && isset($GLOBALS['sql_order_to_append'])) {
986 $query_base = $analyzed_display_query[0]['section_before_limit']
987 . "\n" . $GLOBALS['sql_order_to_append']
988 . $analyzed_display_query[0]['section_after_limit'];
990 // Need to reparse query
991 $parsed_sql = PMA_SQP_parse($query_base);
992 // update the $analyzed_display_query
993 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
994 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
997 // Here we append the LIMIT added for navigation, to
998 // enable its display. Adding it higher in the code
999 // to $sql_query would create a problem when
1000 // using the Refresh or Edit links.
1002 // Only append it on SELECTs.
1005 * @todo what would be the best to do when someone hits Refresh:
1006 * use the current LIMITs ?
1009 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1010 && isset($GLOBALS['sql_limit_to_append'])) {
1011 $query_base = $analyzed_display_query[0]['section_before_limit']
1012 . "\n" . $GLOBALS['sql_limit_to_append']
1013 . $analyzed_display_query[0]['section_after_limit'];
1014 // Need to reparse query
1015 $parsed_sql = PMA_SQP_parse($query_base);
1019 if (! empty($GLOBALS['show_as_php'])) {
1020 $query_base = '$sql = "' . $query_base;
1021 } elseif (! empty($GLOBALS['validatequery'])) {
1022 try {
1023 $query_base = PMA_validateSQL($query_base);
1024 } catch (Exception $e) {
1025 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1027 } elseif (isset($parsed_sql)) {
1028 $query_base = PMA_formatSql($parsed_sql, $query_base);
1031 // Prepares links that may be displayed to edit/explain the query
1032 // (don't go to default pages, we must go to the page
1033 // where the query box is available)
1035 // Basic url query part
1036 $url_params = array();
1037 if (! isset($GLOBALS['db'])) {
1038 $GLOBALS['db'] = '';
1040 if (strlen($GLOBALS['db'])) {
1041 $url_params['db'] = $GLOBALS['db'];
1042 if (strlen($GLOBALS['table'])) {
1043 $url_params['table'] = $GLOBALS['table'];
1044 $edit_link = 'tbl_sql.php';
1045 } else {
1046 $edit_link = 'db_sql.php';
1048 } else {
1049 $edit_link = 'server_sql.php';
1052 // Want to have the query explained
1053 // but only explain a SELECT (that has not been explained)
1054 /* SQL-Parser-Analyzer */
1055 $explain_link = '';
1056 $is_select = false;
1057 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1058 $explain_params = $url_params;
1059 // Detect if we are validating as well
1060 // To preserve the validate uRL data
1061 if (! empty($GLOBALS['validatequery'])) {
1062 $explain_params['validatequery'] = 1;
1064 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1065 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1066 $_message = __('Explain SQL');
1067 $is_select = true;
1068 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1069 $explain_params['sql_query'] = substr($sql_query, 8);
1070 $_message = __('Skip Explain SQL');
1072 if (isset($explain_params['sql_query'])) {
1073 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1074 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1076 } //show explain
1078 $url_params['sql_query'] = $sql_query;
1079 $url_params['show_query'] = 1;
1081 // even if the query is big and was truncated, offer the chance
1082 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1083 if (! empty($cfg['SQLQuery']['Edit'])) {
1084 if ($cfg['EditInWindow'] == true) {
1085 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1086 } else {
1087 $onclick = '';
1090 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1091 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1092 } else {
1093 $edit_link = '';
1096 $url_qpart = PMA_generate_common_url($url_params);
1098 // Also we would like to get the SQL formed in some nice
1099 // php-code
1100 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1101 $php_params = $url_params;
1103 if (! empty($GLOBALS['show_as_php'])) {
1104 $_message = __('Without PHP Code');
1105 } else {
1106 $php_params['show_as_php'] = 1;
1107 $_message = __('Create PHP Code');
1110 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1111 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1113 if (isset($GLOBALS['show_as_php'])) {
1114 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1115 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1117 } else {
1118 $php_link = '';
1119 } //show as php
1121 // Refresh query
1122 if (! empty($cfg['SQLQuery']['Refresh'])
1123 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1124 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1125 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1126 } else {
1127 $refresh_link = '';
1128 } //show as php
1130 if (! empty($cfg['SQLValidator']['use'])
1131 && ! empty($cfg['SQLQuery']['Validate'])) {
1132 $validate_params = $url_params;
1133 if (!empty($GLOBALS['validatequery'])) {
1134 $validate_message = __('Skip Validate SQL') ;
1135 } else {
1136 $validate_params['validatequery'] = 1;
1137 $validate_message = __('Validate SQL') ;
1140 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1141 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1142 } else {
1143 $validate_link = '';
1144 } //validator
1146 if (!empty($GLOBALS['validatequery'])) {
1147 echo '<div class="sqlvalidate">';
1148 } else {
1149 echo '<code class="sql">';
1151 if ($query_too_big) {
1152 echo $shortened_query_base;
1153 } else {
1154 echo $query_base;
1157 //Clean up the end of the PHP
1158 if (! empty($GLOBALS['show_as_php'])) {
1159 echo '";';
1161 if (!empty($GLOBALS['validatequery'])) {
1162 echo '</div>';
1163 } else {
1164 echo '</code>';
1167 echo '<div class="tools">';
1168 // avoid displaying a Profiling checkbox that could
1169 // be checked, which would reexecute an INSERT, for example
1170 if (! empty($refresh_link)) {
1171 PMA_profilingCheckbox($sql_query);
1173 // if needed, generate an invisible form that contains controls for the
1174 // Inline link; this way, the behavior of the Inline link does not
1175 // depend on the profiling support or on the refresh link
1176 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1177 echo '<form action="sql.php" method="post">';
1178 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1179 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1180 echo '</form>';
1183 // in the tools div, only display the Inline link when not in ajax
1184 // mode because 1) it currently does not work and 2) we would
1185 // have two similar mechanisms on the page for the same goal
1186 if ($is_select || $GLOBALS['is_ajax_request'] === false && ! $query_too_big) {
1187 // see in js/functions.js the jQuery code attached to id inline_edit
1188 // document.write conflicts with jQuery, hence used $().append()
1189 echo "<script type=\"text/javascript\">\n" .
1190 "//<![CDATA[\n" .
1191 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1192 PMA_escapeJsString(__('Inline edit of this query')) .
1193 "\" class=\"inline_edit_sql\">" .
1194 PMA_escapeJsString(__('Inline')) .
1195 "</a>]');\n" .
1196 "//]]>\n" .
1197 "</script>";
1199 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1200 echo '</div>';
1202 echo '</div>';
1203 if ($GLOBALS['is_ajax_request'] === false) {
1204 echo '<br class="clearfloat" />';
1207 // If we are in an Ajax request, we have most probably been called in
1208 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1209 // to PMA_ajaxResponse(), which will encode it for JSON.
1210 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1211 $buffer_contents = ob_get_contents();
1212 ob_end_clean();
1213 return $buffer_contents;
1215 return null;
1216 } // end of the 'PMA_showMessage()' function
1219 * Verifies if current MySQL server supports profiling
1221 * @access public
1222 * @return boolean whether profiling is supported
1224 function PMA_profilingSupported()
1226 if (! PMA_cacheExists('profiling_supported', true)) {
1227 // 5.0.37 has profiling but for example, 5.1.20 does not
1228 // (avoid a trip to the server for MySQL before 5.0.37)
1229 // and do not set a constant as we might be switching servers
1230 if (defined('PMA_MYSQL_INT_VERSION')
1231 && PMA_MYSQL_INT_VERSION >= 50037
1232 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1233 PMA_cacheSet('profiling_supported', true, true);
1234 } else {
1235 PMA_cacheSet('profiling_supported', false, true);
1239 return PMA_cacheGet('profiling_supported', true);
1243 * Displays a form with the Profiling checkbox
1245 * @param string $sql_query
1246 * @access public
1248 function PMA_profilingCheckbox($sql_query)
1250 if (PMA_profilingSupported()) {
1251 echo '<form action="sql.php" method="post">' . "\n";
1252 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1253 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1254 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1255 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1256 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1257 echo '</form>' . "\n";
1262 * Formats $value to byte view
1264 * @param double $value the value to format
1265 * @param int $limes the sensitiveness
1266 * @param int $comma the number of decimals to retain
1268 * @return array the formatted value and its unit
1270 * @access public
1272 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1274 if ($value === null) {
1275 return null;
1278 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1279 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1281 $dh = PMA_pow(10, $comma);
1282 $li = PMA_pow(10, $limes);
1283 $unit = $byteUnits[0];
1285 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1286 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1287 // use 1024.0 to avoid integer overflow on 64-bit machines
1288 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1289 $unit = $byteUnits[$d];
1290 break 1;
1291 } // end if
1292 } // end for
1294 if ($unit != $byteUnits[0]) {
1295 // if the unit is not bytes (as represented in current language)
1296 // reformat with max length of 5
1297 // 4th parameter=true means do not reformat if value < 1
1298 $return_value = PMA_formatNumber($value, 5, $comma, true);
1299 } else {
1300 // do not reformat, just handle the locale
1301 $return_value = PMA_formatNumber($value, 0);
1304 return array(trim($return_value), $unit);
1305 } // end of the 'PMA_formatByteDown' function
1308 * Changes thousands and decimal separators to locale specific values.
1310 * @param $value
1311 * @return string
1313 function PMA_localizeNumber($value)
1315 return str_replace(
1316 array(',', '.'),
1317 array(
1318 /* l10n: Thousands separator */
1319 __(','),
1320 /* l10n: Decimal separator */
1321 __('.'),
1323 $value);
1327 * Formats $value to the given length and appends SI prefixes
1328 * with a $length of 0 no truncation occurs, number is only formated
1329 * to the current locale
1331 * examples:
1332 * <code>
1333 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1334 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1335 * echo PMA_formatNumber(-0.003, 6); // -3 m
1336 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1337 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1338 * echo PMA_formatNumber(0, 6); // 0
1340 * </code>
1341 * @param double $value the value to format
1342 * @param integer $digits_left number of digits left of the comma
1343 * @param integer $digits_right number of digits right of the comma
1344 * @param boolean $only_down do not reformat numbers below 1
1345 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1347 * @return string the formatted value and its unit
1349 * @access public
1351 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1353 if ($value==0) return '0';
1355 $originalValue = $value;
1356 //number_format is not multibyte safe, str_replace is safe
1357 if ($digits_left === 0) {
1358 $value = number_format($value, $digits_right);
1359 if ($originalValue!=0 && floatval($value) == 0) $value = ' <'.(1/PMA_pow(10,$digits_right));
1361 return PMA_localizeNumber($value);
1364 // this units needs no translation, ISO
1365 $units = array(
1366 -8 => 'y',
1367 -7 => 'z',
1368 -6 => 'a',
1369 -5 => 'f',
1370 -4 => 'p',
1371 -3 => 'n',
1372 -2 => '&micro;',
1373 -1 => 'm',
1374 0 => ' ',
1375 1 => 'k',
1376 2 => 'M',
1377 3 => 'G',
1378 4 => 'T',
1379 5 => 'P',
1380 6 => 'E',
1381 7 => 'Z',
1382 8 => 'Y'
1385 // check for negative value to retain sign
1386 if ($value < 0) {
1387 $sign = '-';
1388 $value = abs($value);
1389 } else {
1390 $sign = '';
1393 $dh = PMA_pow(10, $digits_right);
1395 // This gives us the right SI prefix already, but $digits_left parameter not incorporated
1396 $d = floor(log10($value) / 3);
1397 // Lowering the SI prefix by 1 gives us an additional 3 zeros
1398 // So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits) to use, then lower the SI prefix
1399 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1400 if ($digits_left > $cur_digits) {
1401 $d-= floor(($digits_left - $cur_digits)/3);
1404 if ($d<0 && $only_down) $d=0;
1406 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1407 $unit = $units[$d];
1409 // If we dont want any zeros after the comma just add the thousand seperator
1410 if ($noTrailingZero)
1411 $value = PMA_localizeNumber(preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$value));
1412 else
1413 $value = PMA_localizeNumber(number_format($value, $digits_right)); //number_format is not multibyte safe, str_replace is safe
1415 if ($originalValue!=0 && floatval($value) == 0) return ' <'.(1/PMA_pow(10,$digits_right)).' '.$unit;
1417 return $sign . $value . ' ' . $unit;
1418 } // end of the 'PMA_formatNumber' function
1421 * Returns the number of bytes when a formatted size is given
1423 * @param string $formatted_size the size expression (for example 8MB)
1424 * @return integer The numerical part of the expression (for example 8)
1426 function PMA_extractValueFromFormattedSize($formatted_size)
1428 $return_value = -1;
1430 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1431 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1432 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1433 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1434 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1435 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1437 return $return_value;
1438 }// end of the 'PMA_extractValueFromFormattedSize' function
1441 * Writes localised date
1443 * @param string $timestamp the current timestamp
1444 * @param string $format format
1445 * @return string the formatted date
1447 * @access public
1449 function PMA_localisedDate($timestamp = -1, $format = '')
1451 $month = array(
1452 /* l10n: Short month name */
1453 __('Jan'),
1454 /* l10n: Short month name */
1455 __('Feb'),
1456 /* l10n: Short month name */
1457 __('Mar'),
1458 /* l10n: Short month name */
1459 __('Apr'),
1460 /* l10n: Short month name */
1461 _pgettext('Short month name', 'May'),
1462 /* l10n: Short month name */
1463 __('Jun'),
1464 /* l10n: Short month name */
1465 __('Jul'),
1466 /* l10n: Short month name */
1467 __('Aug'),
1468 /* l10n: Short month name */
1469 __('Sep'),
1470 /* l10n: Short month name */
1471 __('Oct'),
1472 /* l10n: Short month name */
1473 __('Nov'),
1474 /* l10n: Short month name */
1475 __('Dec'));
1476 $day_of_week = array(
1477 /* l10n: Short week day name */
1478 __('Sun'),
1479 /* l10n: Short week day name */
1480 __('Mon'),
1481 /* l10n: Short week day name */
1482 __('Tue'),
1483 /* l10n: Short week day name */
1484 __('Wed'),
1485 /* l10n: Short week day name */
1486 __('Thu'),
1487 /* l10n: Short week day name */
1488 __('Fri'),
1489 /* l10n: Short week day name */
1490 __('Sat'));
1492 if ($format == '') {
1493 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1494 $format = __('%B %d, %Y at %I:%M %p');
1497 if ($timestamp == -1) {
1498 $timestamp = time();
1501 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1502 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1504 return strftime($date, $timestamp);
1505 } // end of the 'PMA_localisedDate()' function
1509 * returns a tab for tabbed navigation.
1510 * If the variables $link and $args ar left empty, an inactive tab is created
1512 * @param array $tab array with all options
1513 * @param array $url_params
1514 * @return string html code for one tab, a link if valid otherwise a span
1515 * @access public
1517 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1519 // default values
1520 $defaults = array(
1521 'text' => '',
1522 'class' => '',
1523 'active' => null,
1524 'link' => '',
1525 'sep' => '?',
1526 'attr' => '',
1527 'args' => '',
1528 'warning' => '',
1529 'fragment' => '',
1530 'id' => '',
1533 $tab = array_merge($defaults, $tab);
1535 // determine additionnal style-class
1536 if (empty($tab['class'])) {
1537 if (! empty($tab['active'])
1538 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1539 $tab['class'] = 'active';
1540 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1541 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1542 && empty($tab['warning'])) {
1543 $tab['class'] = 'active';
1547 if (!empty($tab['warning'])) {
1548 $tab['class'] .= ' error';
1549 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1552 // If there are any tab specific URL parameters, merge those with the general URL parameters
1553 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1554 $url_params = array_merge($url_params, $tab['url_params']);
1557 // build the link
1558 if (!empty($tab['link'])) {
1559 $tab['link'] = htmlentities($tab['link']);
1560 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1561 if (! empty($tab['args'])) {
1562 foreach ($tab['args'] as $param => $value) {
1563 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1564 . urlencode($value);
1569 if (! empty($tab['fragment'])) {
1570 $tab['link'] .= $tab['fragment'];
1573 // display icon, even if iconic is disabled but the link-text is missing
1574 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1575 && isset($tab['icon'])) {
1576 // avoid generating an alt tag, because it only illustrates
1577 // the text that follows and if browser does not display
1578 // images, the text is duplicated
1579 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1580 .' width="16" height="16" alt="" />%2$s';
1581 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1583 // check to not display an empty link-text
1584 elseif (empty($tab['text'])) {
1585 $tab['text'] = '?';
1586 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1587 E_USER_NOTICE);
1590 //Set the id for the tab, if set in the params
1591 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1592 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1594 if (!empty($tab['link'])) {
1595 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1596 .$id_string
1597 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1598 . $tab['text'] . '</a>';
1599 } else {
1600 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1601 . $tab['text'] . '</span>';
1604 $out .= '</li>';
1605 return $out;
1606 } // end of the 'PMA_generate_html_tab()' function
1609 * returns html-code for a tab navigation
1611 * @param array $tabs one element per tab
1612 * @param string $url_params
1613 * @return string html-code for tab-navigation
1615 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1617 $tag_id = 'topmenu';
1618 $tab_navigation =
1619 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1620 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1622 foreach ($tabs as $tab) {
1623 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1626 $tab_navigation .=
1627 '</ul>' . "\n"
1628 .'<div class="clearfloat"></div>'
1629 .'</div>' . "\n";
1631 return $tab_navigation;
1636 * Displays a link, or a button if the link's URL is too large, to
1637 * accommodate some browsers' limitations
1639 * @param string $url the URL
1640 * @param string $message the link message
1641 * @param mixed $tag_params string: js confirmation
1642 * array: additional tag params (f.e. style="")
1643 * @param boolean $new_form we set this to false when we are already in
1644 * a form, to avoid generating nested forms
1645 * @param boolean $strip_img
1646 * @param string $target
1648 * @return string the results to be echoed or saved in an array
1650 function PMA_linkOrButton($url, $message, $tag_params = array(),
1651 $new_form = true, $strip_img = false, $target = '')
1653 $url_length = strlen($url);
1654 // with this we should be able to catch case of image upload
1655 // into a (MEDIUM) BLOB; not worth generating even a form for these
1656 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1657 return '';
1661 if (! is_array($tag_params)) {
1662 $tmp = $tag_params;
1663 $tag_params = array();
1664 if (!empty($tmp)) {
1665 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1667 unset($tmp);
1669 if (! empty($target)) {
1670 $tag_params['target'] = htmlentities($target);
1673 $tag_params_strings = array();
1674 foreach ($tag_params as $par_name => $par_value) {
1675 // htmlspecialchars() only on non javascript
1676 $par_value = substr($par_name, 0, 2) == 'on'
1677 ? $par_value
1678 : htmlspecialchars($par_value);
1679 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1682 $displayed_message = '';
1683 // Add text if not already added
1684 if (stristr($message, '<img') && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true) && strip_tags($message)==$message) {
1685 $displayed_message = '<span>' . htmlspecialchars(preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)) . '</span>';
1688 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1689 // no whitespace within an <a> else Safari will make it part of the link
1690 $ret = "\n" . '<a href="' . $url . '" '
1691 . implode(' ', $tag_params_strings) . '>'
1692 . $message . $displayed_message . '</a>' . "\n";
1693 } else {
1694 // no spaces (linebreaks) at all
1695 // or after the hidden fields
1696 // IE will display them all
1698 // add class=link to submit button
1699 if (empty($tag_params['class'])) {
1700 $tag_params['class'] = 'link';
1703 // decode encoded url separators
1704 $separator = PMA_get_arg_separator();
1705 // on most places separator is still hard coded ...
1706 if ($separator !== '&') {
1707 // ... so always replace & with $separator
1708 $url = str_replace(htmlentities('&'), $separator, $url);
1709 $url = str_replace('&', $separator, $url);
1711 $url = str_replace(htmlentities($separator), $separator, $url);
1712 // end decode
1714 $url_parts = parse_url($url);
1715 $query_parts = explode($separator, $url_parts['query']);
1716 if ($new_form) {
1717 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1718 . ' method="post"' . $target . ' style="display: inline;">';
1719 $subname_open = '';
1720 $subname_close = '';
1721 $submit_link = '#';
1722 } else {
1723 $query_parts[] = 'redirect=' . $url_parts['path'];
1724 if (empty($GLOBALS['subform_counter'])) {
1725 $GLOBALS['subform_counter'] = 0;
1727 $GLOBALS['subform_counter']++;
1728 $ret = '';
1729 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1730 $subname_close = ']';
1731 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1733 foreach ($query_parts as $query_pair) {
1734 list($eachvar, $eachval) = explode('=', $query_pair);
1735 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1736 . $subname_close . '" value="'
1737 . htmlspecialchars(urldecode($eachval)) . '" />';
1738 } // end while
1740 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1741 . implode(' ', $tag_params_strings) . '>'
1742 . $message . ' ' . $displayed_message . '</a>' . "\n";
1744 if ($new_form) {
1745 $ret .= '</form>';
1747 } // end if... else...
1749 return $ret;
1750 } // end of the 'PMA_linkOrButton()' function
1754 * Returns a given timespan value in a readable format.
1756 * @param int $seconds the timespan
1758 * @return string the formatted value
1760 function PMA_timespanFormat($seconds)
1762 $days = floor($seconds / 86400);
1763 if ($days > 0) {
1764 $seconds -= $days * 86400;
1766 $hours = floor($seconds / 3600);
1767 if ($days > 0 || $hours > 0) {
1768 $seconds -= $hours * 3600;
1770 $minutes = floor($seconds / 60);
1771 if ($days > 0 || $hours > 0 || $minutes > 0) {
1772 $seconds -= $minutes * 60;
1774 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1778 * Takes a string and outputs each character on a line for itself. Used
1779 * mainly for horizontalflipped display mode.
1780 * Takes care of special html-characters.
1781 * Fulfills todo-item
1782 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1784 * @todo add a multibyte safe function PMA_STR_split()
1785 * @param string $string The string
1786 * @param string $Separator The Separator (defaults to "<br />\n")
1788 * @access public
1789 * @return string The flipped string
1791 function PMA_flipstring($string, $Separator = "<br />\n")
1793 $format_string = '';
1794 $charbuff = false;
1796 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1797 $char = $string{$i};
1798 $append = false;
1800 if ($char == '&') {
1801 $format_string .= $charbuff;
1802 $charbuff = $char;
1803 } elseif ($char == ';' && !empty($charbuff)) {
1804 $format_string .= $charbuff . $char;
1805 $charbuff = false;
1806 $append = true;
1807 } elseif (! empty($charbuff)) {
1808 $charbuff .= $char;
1809 } else {
1810 $format_string .= $char;
1811 $append = true;
1814 // do not add separator after the last character
1815 if ($append && ($i != $str_len - 1)) {
1816 $format_string .= $Separator;
1820 return $format_string;
1824 * Function added to avoid path disclosures.
1825 * Called by each script that needs parameters, it displays
1826 * an error message and, by default, stops the execution.
1828 * Not sure we could use a strMissingParameter message here,
1829 * would have to check if the error message file is always available
1831 * @todo use PMA_fatalError() if $die === true?
1832 * @param array $params The names of the parameters needed by the calling script.
1833 * @param bool $die Stop the execution?
1834 * (Set this manually to false in the calling script
1835 * until you know all needed parameters to check).
1836 * @param bool $request Whether to include this list in checking for special params.
1837 * @global string path to current script
1838 * @global boolean flag whether any special variable was required
1840 * @access public
1842 function PMA_checkParameters($params, $die = true, $request = true)
1844 global $checked_special;
1846 if (! isset($checked_special)) {
1847 $checked_special = false;
1850 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1851 $found_error = false;
1852 $error_message = '';
1854 foreach ($params as $param) {
1855 if ($request && $param != 'db' && $param != 'table') {
1856 $checked_special = true;
1859 if (! isset($GLOBALS[$param])) {
1860 $error_message .= $reported_script_name
1861 . ': ' . __('Missing parameter:') . ' '
1862 . $param
1863 . PMA_showDocu('faqmissingparameters')
1864 . '<br />';
1865 $found_error = true;
1868 if ($found_error) {
1870 * display html meta tags
1872 require_once './libraries/header_meta_style.inc.php';
1873 echo '</head><body><p>' . $error_message . '</p></body></html>';
1874 if ($die) {
1875 exit();
1878 } // end function
1881 * Function to generate unique condition for specified row.
1883 * @param resource $handle current query result
1884 * @param integer $fields_cnt number of fields
1885 * @param array $fields_meta meta information about fields
1886 * @param array $row current row
1887 * @param boolean $force_unique generate condition only on pk or unique
1889 * @access public
1890 * @return array the calculated condition and whether condition is unique
1892 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1894 $primary_key = '';
1895 $unique_key = '';
1896 $nonprimary_condition = '';
1897 $preferred_condition = '';
1899 for ($i = 0; $i < $fields_cnt; ++$i) {
1900 $condition = '';
1901 $field_flags = PMA_DBI_field_flags($handle, $i);
1902 $meta = $fields_meta[$i];
1904 // do not use a column alias in a condition
1905 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1906 $meta->orgname = $meta->name;
1908 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1909 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1910 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
1911 // need (string) === (string)
1912 // '' !== 0 but '' == 0
1913 if ((string) $select_expr['alias'] === (string) $meta->name) {
1914 $meta->orgname = $select_expr['column'];
1915 break;
1916 } // end if
1917 } // end foreach
1921 // Do not use a table alias in a condition.
1922 // Test case is:
1923 // select * from galerie x WHERE
1924 //(select count(*) from galerie y where y.datum=x.datum)>1
1926 // But orgtable is present only with mysqli extension so the
1927 // fix is only for mysqli.
1928 // Also, do not use the original table name if we are dealing with
1929 // a view because this view might be updatable.
1930 // (The isView() verification should not be costly in most cases
1931 // because there is some caching in the function).
1932 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1933 $meta->table = $meta->orgtable;
1936 // to fix the bug where float fields (primary or not)
1937 // can't be matched because of the imprecision of
1938 // floating comparison, use CONCAT
1939 // (also, the syntax "CONCAT(field) IS NULL"
1940 // that we need on the next "if" will work)
1941 if ($meta->type == 'real') {
1942 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1943 . PMA_backquote($meta->orgname) . ') ';
1944 } else {
1945 $condition = ' ' . PMA_backquote($meta->table) . '.'
1946 . PMA_backquote($meta->orgname) . ' ';
1947 } // end if... else...
1949 if (! isset($row[$i]) || is_null($row[$i])) {
1950 $condition .= 'IS NULL AND';
1951 } else {
1952 // timestamp is numeric on some MySQL 4.1
1953 // for real we use CONCAT above and it should compare to string
1954 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
1955 $condition .= '= ' . $row[$i] . ' AND';
1956 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1957 // hexify only if this is a true not empty BLOB or a BINARY
1958 && stristr($field_flags, 'BINARY')
1959 && !empty($row[$i])) {
1960 // do not waste memory building a too big condition
1961 if (strlen($row[$i]) < 1000) {
1962 // use a CAST if possible, to avoid problems
1963 // if the field contains wildcard characters % or _
1964 $condition .= '= CAST(0x' . bin2hex($row[$i])
1965 . ' AS BINARY) AND';
1966 } else {
1967 // this blob won't be part of the final condition
1968 $condition = '';
1970 } elseif ($meta->type == 'bit') {
1971 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
1972 } else {
1973 $condition .= '= \''
1974 . PMA_sqlAddSlashes($row[$i], false, true) . '\' AND';
1977 if ($meta->primary_key > 0) {
1978 $primary_key .= $condition;
1979 } elseif ($meta->unique_key > 0) {
1980 $unique_key .= $condition;
1982 $nonprimary_condition .= $condition;
1983 } // end for
1985 // Correction University of Virginia 19991216:
1986 // prefer primary or unique keys for condition,
1987 // but use conjunction of all values if no primary key
1988 $clause_is_unique = true;
1989 if ($primary_key) {
1990 $preferred_condition = $primary_key;
1991 } elseif ($unique_key) {
1992 $preferred_condition = $unique_key;
1993 } elseif (! $force_unique) {
1994 $preferred_condition = $nonprimary_condition;
1995 $clause_is_unique = false;
1998 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
1999 return(array($where_clause, $clause_is_unique));
2000 } // end function
2003 * Generate a button or image tag
2005 * @param string $button_name name of button element
2006 * @param string $button_class class of button element
2007 * @param string $image_name name of image element
2008 * @param string $text text to display
2009 * @param string $image image to display
2010 * @param string $value
2012 * @access public
2014 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2015 $image, $value = '')
2017 if ($value == '') {
2018 $value = $text;
2020 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2021 echo ' <input type="submit" name="' . $button_name . '"'
2022 .' value="' . htmlspecialchars($value) . '"'
2023 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2024 return;
2027 /* Opera has trouble with <input type="image"> */
2028 /* IE has trouble with <button> */
2029 if (PMA_USR_BROWSER_AGENT != 'IE') {
2030 echo '<button class="' . $button_class . '" type="submit"'
2031 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2032 .' title="' . htmlspecialchars($text) . '">' . "\n"
2033 . PMA_getIcon($image, $text)
2034 .'</button>' . "\n";
2035 } else {
2036 echo '<input type="image" name="' . $image_name . '" value="'
2037 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2038 . $image . '" />'
2039 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2041 } // end function
2044 * Generate a pagination selector for browsing resultsets
2046 * @param int $rows Number of rows in the pagination set
2047 * @param int $pageNow current page number
2048 * @param int $nbTotalPage number of total pages
2049 * @param int $showAll If the number of pages is lower than this
2050 * variable, no pages will be omitted in pagination
2051 * @param int $sliceStart How many rows at the beginning should always be shown?
2052 * @param int $sliceEnd How many rows at the end should always be shown?
2053 * @param int $percent Percentage of calculation page offsets to hop to a next page
2054 * @param int $range Near the current page, how many pages should
2055 * be considered "nearby" and displayed as well?
2056 * @param string $prompt The prompt to display (sometimes empty)
2058 * @return string
2059 * @access public
2061 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2062 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2063 $range = 10, $prompt = '')
2065 $increment = floor($nbTotalPage / $percent);
2066 $pageNowMinusRange = ($pageNow - $range);
2067 $pageNowPlusRange = ($pageNow + $range);
2069 $gotopage = $prompt . ' <select id="pageselector" ';
2070 if ($GLOBALS['cfg']['AjaxEnable']) {
2071 $gotopage .= ' class="ajax"';
2073 $gotopage .= ' name="pos" >' . "\n";
2074 if ($nbTotalPage < $showAll) {
2075 $pages = range(1, $nbTotalPage);
2076 } else {
2077 $pages = array();
2079 // Always show first X pages
2080 for ($i = 1; $i <= $sliceStart; $i++) {
2081 $pages[] = $i;
2084 // Always show last X pages
2085 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2086 $pages[] = $i;
2089 // Based on the number of results we add the specified
2090 // $percent percentage to each page number,
2091 // so that we have a representing page number every now and then to
2092 // immediately jump to specific pages.
2093 // As soon as we get near our currently chosen page ($pageNow -
2094 // $range), every page number will be shown.
2095 $i = $sliceStart;
2096 $x = $nbTotalPage - $sliceEnd;
2097 $met_boundary = false;
2098 while ($i <= $x) {
2099 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2100 // If our pageselector comes near the current page, we use 1
2101 // counter increments
2102 $i++;
2103 $met_boundary = true;
2104 } else {
2105 // We add the percentage increment to our current page to
2106 // hop to the next one in range
2107 $i += $increment;
2109 // Make sure that we do not cross our boundaries.
2110 if ($i > $pageNowMinusRange && ! $met_boundary) {
2111 $i = $pageNowMinusRange;
2115 if ($i > 0 && $i <= $x) {
2116 $pages[] = $i;
2120 // Since because of ellipsing of the current page some numbers may be double,
2121 // we unify our array:
2122 sort($pages);
2123 $pages = array_unique($pages);
2126 foreach ($pages as $i) {
2127 if ($i == $pageNow) {
2128 $selected = 'selected="selected" style="font-weight: bold"';
2129 } else {
2130 $selected = '';
2132 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2135 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2137 return $gotopage;
2138 } // end function
2142 * Generate navigation for a list
2144 * @todo use $pos from $_url_params
2145 * @param int $count number of elements in the list
2146 * @param int $pos current position in the list
2147 * @param array $_url_params url parameters
2148 * @param string $script script name for form target
2149 * @param string $frame target frame
2150 * @param int $max_count maximum number of elements to display from the list
2152 * @access public
2154 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2156 if ($max_count < $count) {
2157 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2158 echo __('Page number:');
2159 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2161 // Move to the beginning or to the previous page
2162 if ($pos > 0) {
2163 // patch #474210 - part 1
2164 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2165 $caption1 = '&lt;&lt;';
2166 $caption2 = ' &lt; ';
2167 $title1 = ' title="' . __('Begin') . '"';
2168 $title2 = ' title="' . __('Previous') . '"';
2169 } else {
2170 $caption1 = __('Begin') . ' &lt;&lt;';
2171 $caption2 = __('Previous') . ' &lt;';
2172 $title1 = '';
2173 $title2 = '';
2174 } // end if... else...
2175 $_url_params['pos'] = 0;
2176 echo '<a' . $title1 . ' href="' . $script
2177 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2178 . $caption1 . '</a>';
2179 $_url_params['pos'] = $pos - $max_count;
2180 echo '<a' . $title2 . ' href="' . $script
2181 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2182 . $caption2 . '</a>';
2185 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2186 echo PMA_generate_common_hidden_inputs($_url_params);
2187 echo PMA_pageselector(
2188 $max_count,
2189 floor(($pos + 1) / $max_count) + 1,
2190 ceil($count / $max_count));
2191 echo '</form>';
2193 if ($pos + $max_count < $count) {
2194 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2195 $caption3 = ' &gt; ';
2196 $caption4 = '&gt;&gt;';
2197 $title3 = ' title="' . __('Next') . '"';
2198 $title4 = ' title="' . __('End') . '"';
2199 } else {
2200 $caption3 = '&gt; ' . __('Next');
2201 $caption4 = '&gt;&gt; ' . __('End');
2202 $title3 = '';
2203 $title4 = '';
2204 } // end if... else...
2205 $_url_params['pos'] = $pos + $max_count;
2206 echo '<a' . $title3 . ' href="' . $script
2207 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2208 . $caption3 . '</a>';
2209 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2210 if ($_url_params['pos'] == $count) {
2211 $_url_params['pos'] = $count - $max_count;
2213 echo '<a' . $title4 . ' href="' . $script
2214 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2215 . $caption4 . '</a>';
2217 echo "\n";
2218 if ('frame_navigation' == $frame) {
2219 echo '</div>' . "\n";
2225 * replaces %u in given path with current user name
2227 * example:
2228 * <code>
2229 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2231 * </code>
2232 * @param string $dir with wildcard for user
2233 * @return string per user directory
2235 function PMA_userDir($dir)
2237 // add trailing slash
2238 if (substr($dir, -1) != '/') {
2239 $dir .= '/';
2242 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2246 * returns html code for db link to default db page
2248 * @param string $database
2249 * @return string html link to default db page
2251 function PMA_getDbLink($database = null)
2253 if (! strlen($database)) {
2254 if (! strlen($GLOBALS['db'])) {
2255 return '';
2257 $database = $GLOBALS['db'];
2258 } else {
2259 $database = PMA_unescape_mysql_wildcards($database);
2262 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2263 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2264 .htmlspecialchars($database) . '</a>';
2268 * Displays a lightbulb hint explaining a known external bug
2269 * that affects a functionality
2271 * @param string $functionality localized message explaining the func.
2272 * @param string $component 'mysql' (eventually, 'php')
2273 * @param string $minimum_version of this component
2274 * @param string $bugref bug reference for this component
2276 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2278 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2279 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2284 * Generates and echoes an HTML checkbox
2286 * @param string $html_field_name the checkbox HTML field
2287 * @param string $label
2288 * @param boolean $checked is it initially checked?
2289 * @param boolean $onclick should it submit the form on click?
2291 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2293 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>';
2297 * Generates and echoes a set of radio HTML fields
2299 * @param string $html_field_name the radio HTML field
2300 * @param array $choices the choices values and labels
2301 * @param string $checked_choice the choice to check by default
2302 * @param boolean $line_break whether to add an HTML line break after a choice
2303 * @param boolean $escape_label whether to use htmlspecialchars() on label
2304 * @param string $class enclose each choice with a div of this class
2306 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2307 foreach ($choices as $choice_value => $choice_label) {
2308 if (! empty($class)) {
2309 echo '<div class="' . $class . '">';
2311 $html_field_id = $html_field_name . '_' . $choice_value;
2312 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2313 if ($choice_value == $checked_choice) {
2314 echo ' checked="checked"';
2316 echo ' />' . "\n";
2317 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2318 if ($line_break) {
2319 echo '<br />';
2321 if (! empty($class)) {
2322 echo '</div>';
2324 echo "\n";
2329 * Generates and returns an HTML dropdown
2331 * @param string $select_name
2332 * @param array $choices choices values
2333 * @param string $active_choice the choice to select by default
2334 * @param string $id id of the select element; can be different in case
2335 * the dropdown is present more than once on the page
2336 * @return string
2337 * @todo support titles
2339 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2341 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2342 foreach ($choices as $one_choice_value => $one_choice_label) {
2343 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2344 if ($one_choice_value == $active_choice) {
2345 $result .= ' selected="selected"';
2347 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2349 $result .= '</select>';
2350 return $result;
2354 * Generates a slider effect (jQjuery)
2355 * Takes care of generating the initial <div> and the link
2356 * controlling the slider; you have to generate the </div> yourself
2357 * after the sliding section.
2359 * @param string $id the id of the <div> on which to apply the effect
2360 * @param string $message the message to show as a link
2362 function PMA_generate_slider_effect($id, $message)
2364 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2365 echo '<div id="' . $id . '">';
2366 return;
2369 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2370 * opening the <div> with PHP itself instead of JavaScript.
2372 * @todo find a better solution that uses $.append(), the recommended method
2373 * maybe by using an additional param, the id of the div to append to
2376 <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); ?>">
2377 <?php
2381 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2383 * @param string $action The URL for the request to be executed
2384 * @param string $select_name The name for the dropdown box
2385 * @param array $options An array of options (see rte_footer.lib.php)
2386 * @param string $callback A JS snippet to execute when the request is
2387 * successfully processed
2389 * @return string HTML code for the toggle button
2391 function PMA_toggleButton($action, $select_name, $options, $callback)
2393 // Do the logic first
2394 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2395 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2396 if ($options[1]['selected'] == true) {
2397 $state = 'on';
2398 } else if ($options[0]['selected'] == true) {
2399 $state = 'off';
2400 } else {
2401 $state = 'on';
2403 $selected1 = '';
2404 $selected0 = '';
2405 if ($options[1]['selected'] == true) {
2406 $selected1 = " selected='selected'";
2407 } else if ($options[0]['selected'] == true) {
2408 $selected0 = " selected='selected'";
2410 // Generate output
2411 $retval = "<!-- TOGGLE START -->\n";
2412 if ($GLOBALS['cfg']['AjaxEnable']) {
2413 $retval .= "<noscript>\n";
2415 $retval .= "<div class='wrapper'>\n";
2416 $retval .= " <form action='$action' method='post'>\n";
2417 $retval .= " <select name='$select_name'>\n";
2418 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2419 $retval .= " {$options[1]['label']}\n";
2420 $retval .= " </option>\n";
2421 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2422 $retval .= " {$options[0]['label']}\n";
2423 $retval .= " </option>\n";
2424 $retval .= " </select>\n";
2425 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2426 $retval .= " </form>\n";
2427 $retval .= "</div>\n";
2428 if ($GLOBALS['cfg']['AjaxEnable']) {
2429 $retval .= "</noscript>\n";
2430 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2431 $retval .= " <div class='toggleButton'>\n";
2432 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2433 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2434 $retval .= " alt='' />\n";
2435 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2436 $retval .= " <tbody>\n";
2437 $retval .= " <td class='toggleOn'>\n";
2438 $retval .= " <span class='hide'>$link_on</span>\n";
2439 $retval .= " <div>";
2440 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2441 $retval .= " </td>\n";
2442 $retval .= " <td><div>&nbsp;</div></td>\n";
2443 $retval .= " <td class='toggleOff'>\n";
2444 $retval .= " <span class='hide'>$link_off</span>\n";
2445 $retval .= " <div>";
2446 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2447 $retval .= " </div>\n";
2448 $retval .= " </tbody>\n";
2449 $retval .= " </tr></table>\n";
2450 $retval .= " <span class='hide callback'>$callback</span>\n";
2451 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2452 $retval .= " </div>\n";
2453 $retval .= " </div>\n";
2454 $retval .= "</div>\n";
2456 $retval .= "<!-- TOGGLE END -->";
2458 return $retval;
2459 } // end PMA_toggleButton()
2462 * Clears cache content which needs to be refreshed on user change.
2464 function PMA_clearUserCache() {
2465 PMA_cacheUnset('is_superuser', true);
2469 * Verifies if something is cached in the session
2471 * @param string $var
2472 * @param int|true $server
2473 * @return boolean
2475 function PMA_cacheExists($var, $server = 0)
2477 if (true === $server) {
2478 $server = $GLOBALS['server'];
2480 return isset($_SESSION['cache']['server_' . $server][$var]);
2484 * Gets cached information from the session
2486 * @param string $var
2487 * @param int|true $server
2488 * @return mixed
2490 function PMA_cacheGet($var, $server = 0)
2492 if (true === $server) {
2493 $server = $GLOBALS['server'];
2495 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2496 return $_SESSION['cache']['server_' . $server][$var];
2497 } else {
2498 return null;
2503 * Caches information in the session
2505 * @param string $var
2506 * @param mixed $val
2507 * @param int|true $server
2508 * @return mixed
2510 function PMA_cacheSet($var, $val = null, $server = 0)
2512 if (true === $server) {
2513 $server = $GLOBALS['server'];
2515 $_SESSION['cache']['server_' . $server][$var] = $val;
2519 * Removes cached information from the session
2521 * @param string $var
2522 * @param int|true $server
2524 function PMA_cacheUnset($var, $server = 0)
2526 if (true === $server) {
2527 $server = $GLOBALS['server'];
2529 unset($_SESSION['cache']['server_' . $server][$var]);
2533 * Converts a bit value to printable format;
2534 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2535 * function because in PHP, decbin() supports only 32 bits
2537 * @param numeric $value coming from a BIT field
2538 * @param integer $length
2539 * @return string the printable value
2541 function PMA_printable_bit_value($value, $length) {
2542 $printable = '';
2543 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2544 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2546 $printable = substr($printable, -$length);
2547 return $printable;
2551 * Verifies whether the value contains a non-printable character
2553 * @param string $value
2554 * @return boolean
2556 function PMA_contains_nonprintable_ascii($value) {
2557 return preg_match('@[^[:print:]]@', $value);
2561 * Converts a BIT type default value
2562 * for example, b'010' becomes 010
2564 * @param string $bit_default_value
2565 * @return string the converted value
2567 function PMA_convert_bit_default_value($bit_default_value) {
2568 return strtr($bit_default_value, array("b" => "", "'" => ""));
2572 * Extracts the various parts from a field type spec
2574 * @param string $fieldspec
2575 * @return array associative array containing type, spec_in_brackets
2576 * and possibly enum_set_values (another array)
2578 function PMA_extractFieldSpec($fieldspec) {
2579 $first_bracket_pos = strpos($fieldspec, '(');
2580 if ($first_bracket_pos) {
2581 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2582 // convert to lowercase just to be sure
2583 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2584 } else {
2585 $type = $fieldspec;
2586 $spec_in_brackets = '';
2589 if ('enum' == $type || 'set' == $type) {
2590 // Define our working vars
2591 $enum_set_values = array();
2592 $working = "";
2593 $in_string = false;
2594 $index = 0;
2596 // While there is another character to process
2597 while (isset($fieldspec[$index])) {
2598 // Grab the char to look at
2599 $char = $fieldspec[$index];
2601 // If it is a single quote, needs to be handled specially
2602 if ($char == "'") {
2603 // If we are not currently in a string, begin one
2604 if (! $in_string) {
2605 $in_string = true;
2606 $working = "";
2607 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2608 } else {
2609 // Check out the next character (if possible)
2610 $has_next = isset($fieldspec[$index + 1]);
2611 $next = $has_next ? $fieldspec[$index + 1] : null;
2613 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2614 if (! $has_next || $next != "'") {
2615 $enum_set_values[] = $working;
2616 $in_string = false;
2618 // Otherwise, this is a 'double quote', and can be added to the working string
2619 } elseif ($next == "'") {
2620 $working .= "'";
2621 // Skip the next char; we already know what it is
2622 $index++;
2625 // escaping of a quote?
2626 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2627 $working .= "'";
2628 $index++;
2629 // Otherwise, add it to our working string like normal
2630 } else {
2631 $working .= $char;
2633 // Increment character index
2634 $index++;
2635 } // end while
2636 } else {
2637 $enum_set_values = array();
2640 return array(
2641 'type' => $type,
2642 'spec_in_brackets' => $spec_in_brackets,
2643 'enum_set_values' => $enum_set_values
2648 * Verifies if this table's engine supports foreign keys
2650 * @param string $engine
2651 * @return boolean
2653 function PMA_foreignkey_supported($engine) {
2654 $engine = strtoupper($engine);
2655 if ('INNODB' == $engine || 'PBXT' == $engine) {
2656 return true;
2657 } else {
2658 return false;
2663 * Replaces some characters by a displayable equivalent
2665 * @param string $content
2666 * @return string the content with characters replaced
2668 function PMA_replace_binary_contents($content) {
2669 $result = str_replace("\x00", '\0', $content);
2670 $result = str_replace("\x08", '\b', $result);
2671 $result = str_replace("\x0a", '\n', $result);
2672 $result = str_replace("\x0d", '\r', $result);
2673 $result = str_replace("\x1a", '\Z', $result);
2674 return $result;
2678 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2680 * @param string $string
2681 * @return string with the chars replaced
2684 function PMA_duplicateFirstNewline($string) {
2685 $first_occurence = strpos($string, "\r\n");
2686 if ($first_occurence === 0) {
2687 $string = "\n".$string;
2689 return $string;
2693 * Get the action word corresponding to a script name
2694 * in order to display it as a title in navigation panel
2696 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2697 * or $cfg['DefaultTabDatabase']
2698 * @return array
2700 function PMA_getTitleForTarget($target) {
2701 $mapping = array(
2702 // Values for $cfg['DefaultTabTable']
2703 'tbl_structure.php' => __('Structure'),
2704 'tbl_sql.php' => __('SQL'),
2705 'tbl_select.php' =>__('Search'),
2706 'tbl_change.php' =>__('Insert'),
2707 'sql.php' => __('Browse'),
2709 // Values for $cfg['DefaultTabDatabase']
2710 'db_structure.php' => __('Structure'),
2711 'db_sql.php' => __('SQL'),
2712 'db_search.php' => __('Search'),
2713 'db_operations.php' => __('Operations'),
2715 return $mapping[$target];
2719 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2721 * @param string $string Text where to do expansion.
2722 * @param function $escape Function to call for escaping variable values.
2723 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2724 * @return string
2726 function PMA_expandUserString($string, $escape = null, $updates = array()) {
2727 /* Content */
2728 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2729 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2730 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2731 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2732 $vars['database'] = $GLOBALS['db'];
2733 $vars['table'] = $GLOBALS['table'];
2734 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2736 /* Update forced variables */
2737 foreach ($updates as $key => $val) {
2738 $vars[$key] = $val;
2741 /* Replacement mapping */
2743 * The __VAR__ ones are for backward compatibility, because user
2744 * might still have it in cookies.
2746 $replace = array(
2747 '@HTTP_HOST@' => $vars['http_host'],
2748 '@SERVER@' => $vars['server_name'],
2749 '__SERVER__' => $vars['server_name'],
2750 '@VERBOSE@' => $vars['server_verbose'],
2751 '@VSERVER@' => $vars['server_verbose_or_name'],
2752 '@DATABASE@' => $vars['database'],
2753 '__DB__' => $vars['database'],
2754 '@TABLE@' => $vars['table'],
2755 '__TABLE__' => $vars['table'],
2756 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2759 /* Optional escaping */
2760 if (!is_null($escape)) {
2761 foreach ($replace as $key => $val) {
2762 $replace[$key] = $escape($val);
2766 /* Fetch fields list if required */
2767 if (strpos($string, '@FIELDS@') !== false) {
2768 $fields_list = PMA_DBI_fetch_result(
2769 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2770 . '.' . PMA_backquote($GLOBALS['table']));
2772 $field_names = array();
2773 foreach ($fields_list as $field) {
2774 if (!is_null($escape)) {
2775 $field_names[] = $escape($field['Field']);
2776 } else {
2777 $field_names[] = $field['Field'];
2781 $replace['@FIELDS@'] = implode(',', $field_names);
2784 /* Do the replacement */
2785 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2789 * function that generates a json output for an ajax request and ends script
2790 * execution
2792 * @param bool $message message string containing the html of the message
2793 * @param bool $success success whether the ajax request was successfull
2794 * @param array $extra_data extra_data optional - any other data as part of the json request
2797 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2799 $response = array();
2800 if ( $success == true ) {
2801 $response['success'] = true;
2802 if ($message instanceof PMA_Message) {
2803 $response['message'] = $message->getDisplay();
2805 else {
2806 $response['message'] = $message;
2809 else {
2810 $response['success'] = false;
2811 if ($message instanceof PMA_Message) {
2812 $response['error'] = $message->getDisplay();
2814 else {
2815 $response['error'] = $message;
2819 // If extra_data has been provided, append it to the response array
2820 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
2821 $response = array_merge($response, $extra_data);
2824 // Set the Content-Type header to JSON so that jQuery parses the
2825 // response correctly.
2827 // At this point, other headers might have been sent;
2828 // even if $GLOBALS['is_header_sent'] is true,
2829 // we have to send these additional headers.
2830 header('Cache-Control: no-cache');
2831 header("Content-Type: application/json");
2833 echo json_encode($response);
2835 if (!defined('TESTSUITE'))
2836 exit;
2840 * Display the form used to browse anywhere on the local server for the file to import
2842 * @param $max_upload_size
2844 function PMA_browseUploadFile($max_upload_size) {
2845 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2846 echo '<div id="upload_form_status" style="display: none;"></div>';
2847 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2848 echo '<input type="file" name="import_file" id="input_import_file" />';
2849 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2850 // some browsers should respect this :)
2851 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2855 * Display the form used to select a file to import from the server upload directory
2857 * @param $import_list
2858 * @param $uploaddir
2860 function PMA_selectUploadFile($import_list, $uploaddir) {
2861 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2862 $extensions = '';
2863 foreach ($import_list as $key => $val) {
2864 if (!empty($extensions)) {
2865 $extensions .= '|';
2867 $extensions .= $val['extension'];
2869 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2871 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2872 if ($files === false) {
2873 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2874 } elseif (!empty($files)) {
2875 echo "\n";
2876 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2877 echo ' <option value="">&nbsp;</option>' . "\n";
2878 echo $files;
2879 echo ' </select>' . "\n";
2880 } elseif (empty ($files)) {
2881 echo '<i>' . __('There are no files to upload') . '</i>';
2886 * Build titles and icons for action links
2888 * @return array the action titles
2890 function PMA_buildActionTitles() {
2891 $titles = array();
2893 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2894 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2895 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2896 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2897 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2898 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2899 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2900 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2901 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2902 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2903 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2904 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
2905 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'), true);
2906 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'), true);
2907 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'), true);
2908 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'), true);
2909 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'), true);
2910 return $titles;
2914 * This function processes the datatypes supported by the DB, as specified in
2915 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
2916 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
2918 * @param bool $html Whether to generate an html snippet or an array
2919 * @param string $selected The value to mark as selected in HTML mode
2921 * @return mixed An HTML snippet or an array of datatypes.
2924 function PMA_getSupportedDatatypes($html = false, $selected = '')
2926 global $cfg;
2928 if ($html) {
2929 // NOTE: the SELECT tag in not included in this snippet.
2930 $retval = '';
2931 foreach ($cfg['ColumnTypes'] as $key => $value) {
2932 if (is_array($value)) {
2933 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
2934 foreach ($value as $subvalue) {
2935 if ($subvalue == $selected) {
2936 $retval .= "<option selected='selected'>";
2937 $retval .= $subvalue;
2938 $retval .= "</option>";
2939 } else if ($subvalue === '-') {
2940 $retval .= "<option disabled='disabled'>";
2941 $retval .= $subvalue;
2942 $retval .= "</option>";
2943 } else {
2944 $retval .= "<option>$subvalue</option>";
2947 $retval .= '</optgroup>';
2948 } else {
2949 if ($selected == $value) {
2950 $retval .= "<option selected='selected'>$value</option>";
2951 } else {
2952 $retval .= "<option>$value</option>";
2956 } else {
2957 $retval = array();
2958 foreach ($cfg['ColumnTypes'] as $value) {
2959 if (is_array($value)) {
2960 foreach ($value as $subvalue) {
2961 if ($subvalue !== '-') {
2962 $retval[] = $subvalue;
2965 } else {
2966 if ($value !== '-') {
2967 $retval[] = $value;
2973 return $retval;
2974 } // end PMA_getSupportedDatatypes()
2977 * Returns a list of datatypes that are not (yet) handled by PMA.
2978 * Used by: tbl_change.php and libraries/db_routines.inc.php
2980 * @return array list of datatypes
2983 function PMA_unsupportedDatatypes() {
2984 // These GIS data types are not yet supported.
2985 $no_support_types = array('geometry',
2986 'point',
2987 'linestring',
2988 'polygon',
2989 'multipoint',
2990 'multilinestring',
2991 'multipolygon',
2992 'geometrycollection'
2995 return $no_support_types;
2999 * Creates a dropdown box with MySQL functions for a particular column.
3001 * @param array $field Data about the column for which
3002 * to generate the dropdown
3003 * @param bool $insert_mode Whether the operation is 'insert'
3005 * @global array $cfg PMA configuration
3006 * @global array $analyzed_sql Analyzed SQL query
3007 * @global mixed $data (null/string) FIXME: what is this for?
3009 * @return string An HTML snippet of a dropdown list with function
3010 * names appropriate for the requested column.
3012 function PMA_getFunctionsForField($field, $insert_mode)
3014 global $cfg, $analyzed_sql, $data;
3016 $selected = '';
3017 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3018 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3019 // which will then reveal the available dropdown options
3020 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3021 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3022 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3023 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3024 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3025 } else {
3026 $dropdown = array();
3027 $default_function = '';
3029 $dropdown_built = array();
3030 $op_spacing_needed = false;
3031 // what function defined as default?
3032 // for the first timestamp we don't set the default function
3033 // if there is a default value for the timestamp
3034 // (not including CURRENT_TIMESTAMP)
3035 // and the column does not have the
3036 // ON UPDATE DEFAULT TIMESTAMP attribute.
3037 if ($field['True_Type'] == 'timestamp'
3038 && empty($field['Default'])
3039 && empty($data)
3040 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3041 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3043 // For primary keys of type char(36) or varchar(36) UUID if the default function
3044 // Only applies to insert mode, as it would silently trash data on updates.
3045 if ($insert_mode
3046 && $field['Key'] == 'PRI'
3047 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3049 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3051 // this is set only when appropriate and is always true
3052 if (isset($field['display_binary_as_hex'])) {
3053 $default_function = 'UNHEX';
3056 // Create the output
3057 $retval = ' <option></option>' . "\n";
3058 // loop on the dropdown array and print all available options for that field.
3059 foreach ($dropdown as $each_dropdown) {
3060 $retval .= ' ';
3061 $retval .= '<option';
3062 if ($default_function === $each_dropdown) {
3063 $retval .= ' selected="selected"';
3065 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3066 $dropdown_built[$each_dropdown] = 'true';
3067 $op_spacing_needed = true;
3069 // For compatibility's sake, do not let out all other functions. Instead
3070 // print a separator (blank) and then show ALL functions which weren't shown
3071 // yet.
3072 $cnt_functions = count($cfg['Functions']);
3073 for ($j = 0; $j < $cnt_functions; $j++) {
3074 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3075 // Is current function defined as default?
3076 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3077 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3078 ? ' selected="selected"'
3079 : '';
3080 if ($op_spacing_needed == true) {
3081 $retval .= ' ';
3082 $retval .= '<option value="">--------</option>' . "\n";
3083 $op_spacing_needed = false;
3086 $retval .= ' ';
3087 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3089 } // end for
3091 return $retval;
3092 } // end PMA_getFunctionsForField()
3095 * Checks if the current user has a specific privilege and returns true if the
3096 * user indeed has that privilege or false if (s)he doesn't. This function must
3097 * only be used for features that are available since MySQL 5, because it
3098 * relies on the INFORMATION_SCHEMA database to be present.
3100 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3101 * // Checks if the currently logged in user has the global
3102 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3103 * // user has this privilege on database 'mydb'.
3106 * @param string $priv The privilege to check
3107 * @param mixed $db null, to only check global privileges
3108 * string, db name where to also check for privileges
3109 * @param mixed $tbl null, to only check global privileges
3110 * string, db name where to also check for privileges
3111 * @return bool
3113 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3115 // Get the username for the current user in the format
3116 // required to use in the information schema database.
3117 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3118 if ($user === false) {
3119 return false;
3121 $user = explode('@', $user);
3122 $username = "''";
3123 $username .= str_replace("'", "''", $user[0]);
3124 $username .= "''@''";
3125 $username .= str_replace("'", "''", $user[1]);
3126 $username .= "''";
3127 // Prepage the query
3128 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3129 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3130 // Check global privileges first.
3131 if (PMA_DBI_fetch_value(sprintf($query,
3132 'USER_PRIVILEGES',
3133 $username,
3134 $priv))) {
3135 return true;
3137 // If a database name was provided and user does not have the
3138 // required global privilege, try database-wise permissions.
3139 if ($db !== null) {
3140 $query .= " AND TABLE_SCHEMA='%s'";
3141 if (PMA_DBI_fetch_value(sprintf($query,
3142 'SCHEMA_PRIVILEGES',
3143 $username,
3144 $priv,
3145 PMA_sqlAddSlashes($db)))) {
3146 return true;
3148 } else {
3149 // There was no database name provided and the user
3150 // does not have the correct global privilege.
3151 return false;
3153 // If a table name was also provided and we still didn't
3154 // find any valid privileges, try table-wise privileges.
3155 if ($tbl !== null) {
3156 $query .= " AND TABLE_NAME='%s'";
3157 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3158 'TABLE_PRIVILEGES',
3159 $username,
3160 $priv,
3161 PMA_sqlAddSlashes($db),
3162 PMA_sqlAddSlashes($tbl)))) {
3163 return true;
3166 // If we reached this point, the user does not
3167 // have even valid table-wise privileges.
3168 return false;
3172 * Returns server type for current connection
3174 * Known types are: Drizzle, MariaDB and MySQL (default)
3176 * @return string
3178 function PMA_getServerType()
3180 $server_type = 'MySQL';
3181 if (PMA_DRIZZLE) {
3182 $server_type = 'Drizzle';
3183 } else if (strpos(PMA_MYSQL_STR_VERSION, 'mariadb') !== false) {
3184 $server_type = 'MariaDB';
3186 return $server_type;