Bug: Live query chart always zero
[phpmyadmin/tyronm.git] / libraries / common.lib.php
blob0a4bd5deb345ebacf21445e014f10b6ed8881121
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 * Detects which function to use for PMA_pow.
12 * @return string Function name.
14 function PMA_detect_pow()
16 if (function_exists('bcpow')) {
17 // BCMath Arbitrary Precision Mathematics Function
18 return 'bcpow';
19 } elseif (function_exists('gmp_pow')) {
20 // GMP Function
21 return 'gmp_pow';
22 } else {
23 // PHP function
24 return 'pow';
28 /**
29 * Exponential expression / raise number into power
31 * @param string $base base to raise
32 * @param string $exp exponent to use
33 * @param mixed $use_function pow function to use, or false for auto-detect
35 * @return mixed string or float
37 function PMA_pow($base, $exp, $use_function = false)
39 static $pow_function = null;
41 if (null == $pow_function) {
42 $pow_function = PMA_detect_pow();
45 if (! $use_function) {
46 $use_function = $pow_function;
49 if ($exp < 0 && 'pow' != $use_function) {
50 return false;
52 switch ($use_function) {
53 case 'bcpow' :
54 // bcscale() needed for testing PMA_pow() with base values < 1
55 bcscale(10);
56 $pow = bcpow($base, $exp);
57 break;
58 case 'gmp_pow' :
59 $pow = gmp_strval(gmp_pow($base, $exp));
60 break;
61 case 'pow' :
62 $base = (float) $base;
63 $exp = (int) $exp;
64 $pow = pow($base, $exp);
65 break;
66 default:
67 $pow = $use_function($base, $exp);
70 return $pow;
73 /**
74 * string PMA_getIcon(string $icon)
76 * @param string $icon name of icon file
77 * @param string $alternate alternate text
78 * @param boolean $force_text whether to force alternate text to be displayed
79 * @param boolean $noSprite If true, the image source will be not replaced
80 * with a CSS Sprite
82 * @return html img tag
84 function PMA_getIcon($icon, $alternate = '', $force_text = false, $noSprite = false)
86 // $cfg['PropertiesIconic'] is true or both
87 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
88 // $cfg['PropertiesIconic'] is false or both
89 // OR we have no $include_icon
90 $include_text = ($force_text || true !== $GLOBALS['cfg']['PropertiesIconic']);
91 $alternate = htmlspecialchars($alternate);
92 $button = '';
94 // Always use a span (we rely on this in js/sql.js)
95 $button .= '<span class="nowrap">';
97 if ($include_icon) {
98 if ($noSprite) {
99 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
100 . ' class="icon" width="16" height="16" />';
101 } else {
102 $button .= '<img src="themes/dot.gif"' . ' title="'
103 . $alternate . '" alt="' . $alternate . '"' . ' class="icon ic_'
104 . str_replace(array('.gif','.png'), '', $icon) . '" />';
108 if ($include_icon && $include_text) {
109 $button .= ' ';
112 if ($include_text) {
113 $button .= $alternate;
116 $button .= '</span>';
118 return $button;
122 * Displays the maximum size for an upload
124 * @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
144 * @return string the INPUT field
146 * @access public
148 function PMA_generateHiddenMaxFileSize($max_size)
150 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
154 * Add slashes before "'" and "\" characters so a value containing them can
155 * be used in a sql comparison.
157 * @param string $a_string the string to slash
158 * @param bool $is_like whether the string will be used in a 'LIKE' clause
159 * (it then requires two more escaped sequences) or not
160 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
161 * (converts \n to \\n, \r to \\r)
162 * @param bool $php_code whether this function is used as part of the
163 * "Create PHP code" dialog
165 * @return string the slashed string
167 * @access public
169 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
171 if ($is_like) {
172 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
173 } else {
174 $a_string = str_replace('\\', '\\\\', $a_string);
177 if ($crlf) {
178 $a_string = strtr(
179 $a_string,
180 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
184 if ($php_code) {
185 $a_string = str_replace('\'', '\\\'', $a_string);
186 } else {
187 $a_string = str_replace('\'', '\'\'', $a_string);
190 return $a_string;
191 } // end of the 'PMA_sqlAddSlashes()' function
195 * Add slashes before "_" and "%" characters for using them in MySQL
196 * database, table and field names.
197 * Note: This function does not escape backslashes!
199 * @param string $name the string to escape
201 * @return string the escaped string
203 * @access public
205 function PMA_escape_mysql_wildcards($name)
207 return strtr($name, array('_' => '\\_', '%' => '\\%'));
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
216 * @return string the escaped string
218 * @access public
220 function PMA_unescape_mysql_wildcards($name)
222 return strtr($name, array('\\_' => '_', '\\%' => '%'));
223 } // end of the 'PMA_unescape_mysql_wildcards()' function
226 * removes quotes (',",`) from a quoted string
228 * checks if the sting is quoted and removes this quotes
230 * @param string $quoted_string string to remove quotes from
231 * @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
251 $unquoted_string = substr($quoted_string, 1, -1);
252 // replace escaped quotes
253 $unquoted_string = str_replace(
254 $quote . $quote,
255 $quote,
256 $unquoted_string
258 return $unquoted_string;
262 return $quoted_string;
266 * format sql strings
268 * @param mixed $parsed_sql pre-parsed SQL structure
269 * @param string $unparsed_sql raw SQL string
271 * @return string the formatted sql
273 * @global array the configuration array
274 * @global boolean whether the current statement is a multiple one or not
276 * @access public
277 * @todo move into PMA_Sql
279 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
281 global $cfg;
283 // Check that we actually have a valid set of parsed data
284 // well, not quite
285 // first check for the SQL parser having hit an error
286 if (PMA_SQP_isError()) {
287 return htmlspecialchars($parsed_sql['raw']);
289 // then check for an array
290 if (! is_array($parsed_sql)) {
291 // We don't so just return the input directly
292 // This is intended to be used for when the SQL Parser is turned off
293 $formatted_sql = "<pre>\n";
294 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
295 $formatted_sql .= $unparsed_sql;
296 } else {
297 $formatted_sql .= $parsed_sql;
299 $formatted_sql .= "\n</pre>";
300 return $formatted_sql;
303 $formatted_sql = '';
305 switch ($cfg['SQP']['fmtType']) {
306 case 'none':
307 if ($unparsed_sql != '') {
308 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
309 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
310 . '</pre></span>';
311 } else {
312 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
314 break;
315 case 'html':
316 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
317 break;
318 case 'text':
319 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
320 break;
321 default:
322 break;
323 } // end switch
325 return $formatted_sql;
326 } // end of the "PMA_formatSql()" function
330 * Displays a link to the official MySQL documentation
332 * @param string $chapter chapter of "HTML, one page per chapter" documentation
333 * @param string $link contains name of page/anchor that is being linked
334 * @param bool $big_icon whether to use big icon (like in left frame)
335 * @param string $anchor anchor to page part
336 * @param bool $just_open whether only the opening <a> tag should be returned
338 * @return string the html link
340 * @access public
342 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
344 global $cfg;
346 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
347 return '';
350 // Fixup for newly used names:
351 $chapter = str_replace('_', '-', strtolower($chapter));
352 $link = str_replace('_', '-', strtolower($link));
354 switch ($cfg['MySQLManualType']) {
355 case 'chapters':
356 if (empty($chapter)) {
357 $chapter = 'index';
359 if (empty($anchor)) {
360 $anchor = $link;
362 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
363 break;
364 case 'big':
365 if (empty($anchor)) {
366 $anchor = $link;
368 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
369 break;
370 case 'searchable':
371 if (empty($link)) {
372 $link = 'index';
374 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
375 if (!empty($anchor)) {
376 $url .= '#' . $anchor;
378 break;
379 case 'viewable':
380 default:
381 if (empty($link)) {
382 $link = 'index';
384 $mysql = '5.0';
385 $lang = 'en';
386 if (defined('PMA_MYSQL_INT_VERSION')) {
387 if (PMA_MYSQL_INT_VERSION >= 50500) {
388 $mysql = '5.5';
389 /* l10n: Please check that translation actually exists. */
390 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
391 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
392 $mysql = '5.1';
393 /* l10n: Please check that translation actually exists. */
394 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
395 } else {
396 $mysql = '5.0';
397 /* l10n: Please check that translation actually exists. */
398 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
401 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
402 if (!empty($anchor)) {
403 $url .= '#' . $anchor;
405 break;
408 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
409 if ($just_open) {
410 return $open_link;
411 } elseif ($big_icon) {
412 return $open_link . '<img class="icon ic_b_sqlhelp" src="themes/dot.gif" alt="'
413 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
414 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
415 return $open_link . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="'
416 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
417 } else {
418 return '[' . $open_link . __('Documentation') . '</a>]';
420 } // end of the 'PMA_showMySQLDocu()' function
424 * Displays a link to the phpMyAdmin documentation
426 * @param string $anchor anchor in documentation
428 * @return string the html link
430 * @access public
432 function PMA_showDocu($anchor)
434 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
435 return '<a href="Documentation.html#' . $anchor . '" target="documentation">'
436 . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="'
437 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
438 } else {
439 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">'
440 . __('Documentation') . '</a>]';
442 } // end of the 'PMA_showDocu()' function
445 * Displays a link to the PHP documentation
447 * @param string $target anchor in documentation
449 * @return string the html link
451 * @access public
453 function PMA_showPHPDocu($target)
455 $url = PMA_getPHPDocLink($target);
457 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
458 return '<a href="' . $url . '" target="documentation">'
459 . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="'
460 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
461 } else {
462 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
464 } // end of the 'PMA_showPHPDocu()' function
467 * returns HTML for a footnote marker and add the messsage to the footnotes
469 * @param string $message the error message
470 * @param bool $bbcode
471 * @param string $type message types
473 * @return string html code for a footnote marker
475 * @access public
477 function PMA_showHint($message, $bbcode = false, $type = 'notice')
479 if ($message instanceof PMA_Message) {
480 $key = $message->getHash();
481 $type = $message->getLevel();
482 } else {
483 $key = md5($message);
486 if (! isset($GLOBALS['footnotes'][$key])) {
487 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
488 $GLOBALS['footnotes'] = array();
490 $nr = count($GLOBALS['footnotes']) + 1;
491 $GLOBALS['footnotes'][$key] = array(
492 'note' => $message,
493 'type' => $type,
494 'nr' => $nr,
496 } else {
497 $nr = $GLOBALS['footnotes'][$key]['nr'];
500 if ($bbcode) {
501 return '[sup]' . $nr . '[/sup]';
504 // footnotemarker used in js/tooltip.js
505 return '<sup class="footnotemarker">' . $nr . '</sup>' .
506 '<img class="footnotemarker footnote_' . $nr . ' ic_b_help" src="themes/dot.gif" alt="" />';
510 * Displays a MySQL error message in the right frame.
512 * @param string $error_message the error message
513 * @param string $the_query the sql query that failed
514 * @param bool $is_modify_link whether to show a "modify" link or not
515 * @param string $back_url the "back" link url (full path is not required)
516 * @param bool $exit EXIT the page?
518 * @global string the curent table
519 * @global string the current db
521 * @access public
523 function PMA_mysqlDie($error_message = '', $the_query = '',
524 $is_modify_link = true, $back_url = '', $exit = true)
526 global $table, $db;
529 * start http output, display html headers
531 include_once './libraries/header.inc.php';
533 $error_msg_output = '';
535 if (!$error_message) {
536 $error_message = PMA_DBI_getError();
538 if (!$the_query && !empty($GLOBALS['sql_query'])) {
539 $the_query = $GLOBALS['sql_query'];
542 // --- Added to solve bug #641765
543 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
544 $formatted_sql = htmlspecialchars($the_query);
545 } elseif (empty($the_query) || trim($the_query) == '') {
546 $formatted_sql = '';
547 } else {
548 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
549 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
550 } else {
551 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
554 // ---
555 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
556 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
557 // if the config password is wrong, or the MySQL server does not
558 // respond, do not show the query that would reveal the
559 // username/password
560 if (!empty($the_query) && !strstr($the_query, 'connect')) {
561 // --- Added to solve bug #641765
562 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
563 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
564 $error_msg_output .= '<br />' . "\n";
566 // ---
567 // modified to show the help on sql errors
568 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
569 if (strstr(strtolower($formatted_sql), 'select')) {
570 // please show me help to the error on select
571 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
573 if ($is_modify_link) {
574 $_url_params = array(
575 'sql_query' => $the_query,
576 'show_query' => 1,
578 if (strlen($table)) {
579 $_url_params['db'] = $db;
580 $_url_params['table'] = $table;
581 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
582 } elseif (strlen($db)) {
583 $_url_params['db'] = $db;
584 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
585 } else {
586 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
589 $error_msg_output .= $doedit_goto
590 . PMA_getIcon('b_edit.png', __('Edit'))
591 . '</a>';
592 } // end if
593 $error_msg_output .= ' </p>' . "\n"
594 .' <p>' . "\n"
595 .' ' . $formatted_sql . "\n"
596 .' </p>' . "\n";
597 } // end if
599 if (! empty($error_message)) {
600 $error_message = preg_replace(
601 "@((\015\012)|(\015)|(\012)){3,}@",
602 "\n\n",
603 $error_message
606 // modified to show the help on error-returns
607 // (now error-messages-server)
608 $error_msg_output .= '<p>' . "\n"
609 . ' <strong>' . __('MySQL said: ') . '</strong>'
610 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
611 . "\n"
612 . '</p>' . "\n";
614 // The error message will be displayed within a CODE segment.
615 // To preserve original formatting, but allow wordwrapping,
616 // we do a couple of replacements
618 // Replace all non-single blanks with their HTML-counterpart
619 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
620 // Replace TAB-characters with their HTML-counterpart
621 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
622 // Replace linebreaks
623 $error_message = nl2br($error_message);
625 $error_msg_output .= '<code>' . "\n"
626 . $error_message . "\n"
627 . '</code><br />' . "\n";
628 $error_msg_output .= '</div>';
630 $_SESSION['Import_message']['message'] = $error_msg_output;
632 if ($exit) {
634 * If in an Ajax request
635 * - avoid displaying a Back link
636 * - use PMA_ajaxResponse() to transmit the message and exit
638 if ($GLOBALS['is_ajax_request'] == true) {
639 PMA_ajaxResponse($error_msg_output, false);
641 if (! empty($back_url)) {
642 if (strstr($back_url, '?')) {
643 $back_url .= '&amp;no_history=true';
644 } else {
645 $back_url .= '?no_history=true';
648 $_SESSION['Import_message']['go_back_url'] = $back_url;
650 $error_msg_output .= '<fieldset class="tblFooters">';
651 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
652 $error_msg_output .= '</fieldset>' . "\n\n";
655 echo $error_msg_output;
657 * display footer and exit
659 include './libraries/footer.inc.php';
660 } else {
661 echo $error_msg_output;
663 } // end of the 'PMA_mysqlDie()' function
666 * returns array with tables of given db with extended information and grouped
668 * @param string $db name of db
669 * @param string $tables name of tables
670 * @param integer $limit_offset list offset
671 * @param int|bool $limit_count max tables to return
673 * @return array (recursive) grouped table list
675 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
677 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
679 if (null === $tables) {
680 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
681 if ($GLOBALS['cfg']['NaturalOrder']) {
682 uksort($tables, 'strnatcasecmp');
686 if (count($tables) < 1) {
687 return $tables;
690 $default = array(
691 'Name' => '',
692 'Rows' => 0,
693 'Comment' => '',
694 'disp_name' => '',
697 $table_groups = array();
699 // for blobstreaming - list of blobstreaming tables
701 // load PMA configuration
702 $PMA_Config = $GLOBALS['PMA_Config'];
704 foreach ($tables as $table_name => $table) {
705 // if BS tables exist
706 if (PMA_BS_IsHiddenTable($table_name)) {
707 continue;
710 // check for correct row count
711 if (null === $table['Rows']) {
712 // Do not check exact row count here,
713 // if row count is invalid possibly the table is defect
714 // and this would break left frame;
715 // but we can check row count if this is a view or the
716 // information_schema database
717 // since PMA_Table::countRecords() returns a limited row count
718 // in this case.
720 // set this because PMA_Table::countRecords() can use it
721 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
723 if ($tbl_is_view || 'information_schema' == $db) {
724 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
728 // in $group we save the reference to the place in $table_groups
729 // where to store the table info
730 if ($GLOBALS['cfg']['LeftFrameDBTree']
731 && $sep && strstr($table_name, $sep)
733 $parts = explode($sep, $table_name);
735 $group =& $table_groups;
736 $i = 0;
737 $group_name_full = '';
738 $parts_cnt = count($parts) - 1;
739 while ($i < $parts_cnt
740 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
741 $group_name = $parts[$i] . $sep;
742 $group_name_full .= $group_name;
744 if (! isset($group[$group_name])) {
745 $group[$group_name] = array();
746 $group[$group_name]['is' . $sep . 'group'] = true;
747 $group[$group_name]['tab' . $sep . 'count'] = 1;
748 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
749 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
750 $table = $group[$group_name];
751 $group[$group_name] = array();
752 $group[$group_name][$group_name] = $table;
753 unset($table);
754 $group[$group_name]['is' . $sep . 'group'] = true;
755 $group[$group_name]['tab' . $sep . 'count'] = 1;
756 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
757 } else {
758 $group[$group_name]['tab' . $sep . 'count']++;
760 $group =& $group[$group_name];
761 $i++;
763 } else {
764 if (! isset($table_groups[$table_name])) {
765 $table_groups[$table_name] = array();
767 $group =& $table_groups;
771 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
772 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
774 // switch tooltip and name
775 $table['Comment'] = $table['Name'];
776 $table['disp_name'] = $table['Comment'];
777 } else {
778 $table['disp_name'] = $table['Name'];
781 $group[$table_name] = array_merge($default, $table);
784 return $table_groups;
787 /* ----------------------- Set of misc functions ----------------------- */
791 * Adds backquotes on both sides of a database, table or field name.
792 * and escapes backquotes inside the name with another backquote
794 * example:
795 * <code>
796 * echo PMA_backquote('owner`s db'); // `owner``s db`
798 * </code>
800 * @param mixed $a_name the database, table or field name to "backquote"
801 * or array of it
802 * @param boolean $do_it a flag to bypass this function (used by dump
803 * functions)
805 * @return mixed the "backquoted" database, table or field name
807 * @access public
809 function PMA_backquote($a_name, $do_it = true)
811 if (is_array($a_name)) {
812 foreach ($a_name as &$data) {
813 $data = PMA_backquote($data, $do_it);
815 return $a_name;
818 if (! $do_it) {
819 global $PMA_SQPdata_forbidden_word;
821 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
822 return $a_name;
826 // '0' is also empty for php :-(
827 if (strlen($a_name) && $a_name !== '*') {
828 return '`' . str_replace('`', '``', $a_name) . '`';
829 } else {
830 return $a_name;
832 } // end of the 'PMA_backquote()' function
835 * Defines the <CR><LF> value depending on the user OS.
837 * @return string the <CR><LF> value to use
839 * @access public
841 function PMA_whichCrlf()
843 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
844 // Win case
845 if (PMA_USR_OS == 'Win') {
846 $the_crlf = "\r\n";
847 } else {
848 // Others
849 $the_crlf = "\n";
852 return $the_crlf;
853 } // end of the 'PMA_whichCrlf()' function
856 * Reloads navigation if needed.
858 * @param bool $jsonly prints out pure JavaScript
860 * @access public
862 function PMA_reloadNavigation($jsonly=false)
864 // Reloads the navigation frame via JavaScript if required
865 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
866 // one of the reasons for a reload is when a table is dropped
867 // in this case, get rid of the table limit offset, otherwise
868 // we have a problem when dropping a table on the last page
869 // and the offset becomes greater than the total number of tables
870 unset($_SESSION['tmp_user_values']['table_limit_offset']);
871 echo "\n";
872 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
873 if (!$jsonly) {
874 echo '<script type="text/javascript">' . PHP_EOL;
877 //<![CDATA[
878 if (typeof(window.parent) != 'undefined'
879 && typeof(window.parent.frame_navigation) != 'undefined'
880 && window.parent.goTo) {
881 window.parent.goTo('<?php echo $reload_url; ?>');
883 //]]>
884 <?php
885 if (!$jsonly) {
886 echo '</script>' . PHP_EOL;
889 unset($GLOBALS['reload']);
894 * displays the message and the query
895 * usually the message is the result of the query executed
897 * @param string $message the message to display
898 * @param string $sql_query the query to display
899 * @param string $type the type (level) of the message
900 * @param boolean $is_view is this a message after a VIEW operation?
902 * @return string
904 * @access public
906 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
909 * PMA_ajaxResponse uses this function to collect the string of HTML generated
910 * for showing the message. Use output buffering to collect it and return it
911 * in a string. In some special cases on sql.php, buffering has to be disabled
912 * and hence we check with $GLOBALS['buffer_message']
914 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
915 ob_start();
917 global $cfg;
919 if (null === $sql_query) {
920 if (! empty($GLOBALS['display_query'])) {
921 $sql_query = $GLOBALS['display_query'];
922 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
923 $sql_query = $GLOBALS['unparsed_sql'];
924 } elseif (! empty($GLOBALS['sql_query'])) {
925 $sql_query = $GLOBALS['sql_query'];
926 } else {
927 $sql_query = '';
931 if (isset($GLOBALS['using_bookmark_message'])) {
932 $GLOBALS['using_bookmark_message']->display();
933 unset($GLOBALS['using_bookmark_message']);
936 // Corrects the tooltip text via JS if required
937 // @todo this is REALLY the wrong place to do this - very unexpected here
938 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
939 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
940 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
941 echo "\n";
942 echo '<script type="text/javascript">' . "\n";
943 echo '//<![CDATA[' . "\n";
944 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
945 . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
946 echo '//]]>' . "\n";
947 echo '</script>' . "\n";
948 } // end if ... elseif
950 // Checks if the table needs to be repaired after a TRUNCATE query.
951 // @todo what about $GLOBALS['display_query']???
952 // @todo this is REALLY the wrong place to do this - very unexpected here
953 if (strlen($GLOBALS['table'])
954 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
956 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
957 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
960 unset($tbl_status);
962 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
963 // check for it's presence before using it
964 echo '<div id="result_query" align="'
965 . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' )
966 . '">' . "\n";
968 if ($message instanceof PMA_Message) {
969 if (isset($GLOBALS['special_message'])) {
970 $message->addMessage($GLOBALS['special_message']);
971 unset($GLOBALS['special_message']);
973 $message->display();
974 $type = $message->getLevel();
975 } else {
976 echo '<div class="' . $type . '">';
977 echo PMA_sanitize($message);
978 if (isset($GLOBALS['special_message'])) {
979 echo PMA_sanitize($GLOBALS['special_message']);
980 unset($GLOBALS['special_message']);
982 echo '</div>';
985 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
986 // Html format the query to be displayed
987 // If we want to show some sql code it is easiest to create it here
988 /* SQL-Parser-Analyzer */
990 if (! empty($GLOBALS['show_as_php'])) {
991 $new_line = '\\n"<br />' . "\n"
992 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
993 $query_base = htmlspecialchars(addslashes($sql_query));
994 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
995 } else {
996 $query_base = $sql_query;
999 $query_too_big = false;
1001 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1002 // when the query is large (for example an INSERT of binary
1003 // data), the parser chokes; so avoid parsing the query
1004 $query_too_big = true;
1005 $shortened_query_base = nl2br(
1006 htmlspecialchars(
1007 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
1010 } elseif (! empty($GLOBALS['parsed_sql'])
1011 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1012 // (here, use "! empty" because when deleting a bookmark,
1013 // $GLOBALS['parsed_sql'] is set but empty
1014 $parsed_sql = $GLOBALS['parsed_sql'];
1015 } else {
1016 // Parse SQL if needed
1017 $parsed_sql = PMA_SQP_parse($query_base);
1018 if (PMA_SQP_isError()) {
1019 unset($parsed_sql);
1023 // Analyze it
1024 if (isset($parsed_sql)) {
1025 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1027 // Same as below (append LIMIT), append the remembered ORDER BY
1028 if ($GLOBALS['cfg']['RememberSorting']
1029 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1030 && isset($GLOBALS['sql_order_to_append'])
1032 $query_base = $analyzed_display_query[0]['section_before_limit']
1033 . "\n" . $GLOBALS['sql_order_to_append']
1034 . $analyzed_display_query[0]['section_after_limit'];
1036 // Need to reparse query
1037 $parsed_sql = PMA_SQP_parse($query_base);
1038 // update the $analyzed_display_query
1039 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1040 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1043 // Here we append the LIMIT added for navigation, to
1044 // enable its display. Adding it higher in the code
1045 // to $sql_query would create a problem when
1046 // using the Refresh or Edit links.
1048 // Only append it on SELECTs.
1051 * @todo what would be the best to do when someone hits Refresh:
1052 * use the current LIMITs ?
1055 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1056 && isset($GLOBALS['sql_limit_to_append'])
1058 $query_base = $analyzed_display_query[0]['section_before_limit']
1059 . "\n" . $GLOBALS['sql_limit_to_append']
1060 . $analyzed_display_query[0]['section_after_limit'];
1061 // Need to reparse query
1062 $parsed_sql = PMA_SQP_parse($query_base);
1066 if (! empty($GLOBALS['show_as_php'])) {
1067 $query_base = '$sql = "' . $query_base;
1068 } elseif (! empty($GLOBALS['validatequery'])) {
1069 try {
1070 $query_base = PMA_validateSQL($query_base);
1071 } catch (Exception $e) {
1072 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1074 } elseif (isset($parsed_sql)) {
1075 $query_base = PMA_formatSql($parsed_sql, $query_base);
1078 // Prepares links that may be displayed to edit/explain the query
1079 // (don't go to default pages, we must go to the page
1080 // where the query box is available)
1082 // Basic url query part
1083 $url_params = array();
1084 if (! isset($GLOBALS['db'])) {
1085 $GLOBALS['db'] = '';
1087 if (strlen($GLOBALS['db'])) {
1088 $url_params['db'] = $GLOBALS['db'];
1089 if (strlen($GLOBALS['table'])) {
1090 $url_params['table'] = $GLOBALS['table'];
1091 $edit_link = 'tbl_sql.php';
1092 } else {
1093 $edit_link = 'db_sql.php';
1095 } else {
1096 $edit_link = 'server_sql.php';
1099 // Want to have the query explained
1100 // but only explain a SELECT (that has not been explained)
1101 /* SQL-Parser-Analyzer */
1102 $explain_link = '';
1103 $is_select = false;
1104 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1105 $explain_params = $url_params;
1106 // Detect if we are validating as well
1107 // To preserve the validate uRL data
1108 if (! empty($GLOBALS['validatequery'])) {
1109 $explain_params['validatequery'] = 1;
1111 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1112 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1113 $_message = __('Explain SQL');
1114 $is_select = true;
1115 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1116 $explain_params['sql_query'] = substr($sql_query, 8);
1117 $_message = __('Skip Explain SQL');
1119 if (isset($explain_params['sql_query'])) {
1120 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1121 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1123 } //show explain
1125 $url_params['sql_query'] = $sql_query;
1126 $url_params['show_query'] = 1;
1128 // even if the query is big and was truncated, offer the chance
1129 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1130 if (! empty($cfg['SQLQuery']['Edit'])) {
1131 if ($cfg['EditInWindow'] == true) {
1132 $onclick = 'window.parent.focus_querywindow(\''
1133 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1134 } else {
1135 $onclick = '';
1138 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1139 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1140 } else {
1141 $edit_link = '';
1144 $url_qpart = PMA_generate_common_url($url_params);
1146 // Also we would like to get the SQL formed in some nice
1147 // php-code
1148 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1149 $php_params = $url_params;
1151 if (! empty($GLOBALS['show_as_php'])) {
1152 $_message = __('Without PHP Code');
1153 } else {
1154 $php_params['show_as_php'] = 1;
1155 $_message = __('Create PHP Code');
1158 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1159 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1161 if (isset($GLOBALS['show_as_php'])) {
1162 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1163 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1165 } else {
1166 $php_link = '';
1167 } //show as php
1169 // Refresh query
1170 if (! empty($cfg['SQLQuery']['Refresh'])
1171 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1173 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1174 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1175 } else {
1176 $refresh_link = '';
1177 } //show as php
1179 if (! empty($cfg['SQLValidator']['use'])
1180 && ! empty($cfg['SQLQuery']['Validate'])
1182 $validate_params = $url_params;
1183 if (!empty($GLOBALS['validatequery'])) {
1184 $validate_message = __('Skip Validate SQL');
1185 } else {
1186 $validate_params['validatequery'] = 1;
1187 $validate_message = __('Validate SQL');
1190 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1191 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1192 } else {
1193 $validate_link = '';
1194 } //validator
1196 if (!empty($GLOBALS['validatequery'])) {
1197 echo '<div class="sqlvalidate">';
1198 } else {
1199 echo '<code class="sql">';
1201 if ($query_too_big) {
1202 echo $shortened_query_base;
1203 } else {
1204 echo $query_base;
1207 //Clean up the end of the PHP
1208 if (! empty($GLOBALS['show_as_php'])) {
1209 echo '";';
1211 if (!empty($GLOBALS['validatequery'])) {
1212 echo '</div>';
1213 } else {
1214 echo '</code>';
1217 echo '<div class="tools">';
1218 // avoid displaying a Profiling checkbox that could
1219 // be checked, which would reexecute an INSERT, for example
1220 if (! empty($refresh_link)) {
1221 PMA_profilingCheckbox($sql_query);
1223 // if needed, generate an invisible form that contains controls for the
1224 // Inline link; this way, the behavior of the Inline link does not
1225 // depend on the profiling support or on the refresh link
1226 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1227 echo '<form action="sql.php" method="post">';
1228 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1229 echo '<input type="hidden" name="sql_query" value="'
1230 . htmlspecialchars($sql_query) . '" />';
1231 echo '</form>';
1234 // in the tools div, only display the Inline link when not in ajax
1235 // mode because 1) it currently does not work and 2) we would
1236 // have two similar mechanisms on the page for the same goal
1237 if ($is_select
1238 || $GLOBALS['is_ajax_request'] === false
1239 && ! $query_too_big
1241 // see in js/functions.js the jQuery code attached to id inline_edit
1242 // document.write conflicts with jQuery, hence used $().append()
1243 echo "<script type=\"text/javascript\">\n" .
1244 "//<![CDATA[\n" .
1245 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1246 PMA_escapeJsString(__('Inline edit of this query')) .
1247 "\" class=\"inline_edit_sql\">" .
1248 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1249 "</a>]');\n" .
1250 "//]]>\n" .
1251 "</script>";
1253 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1254 echo '</div>';
1256 echo '</div>';
1257 if ($GLOBALS['is_ajax_request'] === false) {
1258 echo '<br class="clearfloat" />';
1261 // If we are in an Ajax request, we have most probably been called in
1262 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1263 // to PMA_ajaxResponse(), which will encode it for JSON.
1264 if ($GLOBALS['is_ajax_request'] == true
1265 && ! isset($GLOBALS['buffer_message'])
1267 $buffer_contents = ob_get_contents();
1268 ob_end_clean();
1269 return $buffer_contents;
1271 return null;
1272 } // end of the 'PMA_showMessage()' function
1275 * Verifies if current MySQL server supports profiling
1277 * @access public
1279 * @return boolean whether profiling is supported
1281 function PMA_profilingSupported()
1283 if (! PMA_cacheExists('profiling_supported', true)) {
1284 // 5.0.37 has profiling but for example, 5.1.20 does not
1285 // (avoid a trip to the server for MySQL before 5.0.37)
1286 // and do not set a constant as we might be switching servers
1287 if (defined('PMA_MYSQL_INT_VERSION')
1288 && PMA_MYSQL_INT_VERSION >= 50037
1289 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1291 PMA_cacheSet('profiling_supported', true, true);
1292 } else {
1293 PMA_cacheSet('profiling_supported', false, true);
1297 return PMA_cacheGet('profiling_supported', true);
1301 * Displays a form with the Profiling checkbox
1303 * @param string $sql_query sql query
1305 * @access public
1307 function PMA_profilingCheckbox($sql_query)
1309 if (PMA_profilingSupported()) {
1310 echo '<form action="sql.php" method="post">' . "\n";
1311 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1312 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1313 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1314 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1315 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1316 echo '</form>' . "\n";
1321 * Formats $value to byte view
1323 * @param double $value the value to format
1324 * @param int $limes the sensitiveness
1325 * @param int $comma the number of decimals to retain
1327 * @return array the formatted value and its unit
1329 * @access public
1331 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1333 $byteUnits = array(
1334 /* l10n: shortcuts for Byte */
1335 __('B'),
1336 /* l10n: shortcuts for Kilobyte */
1337 __('KiB'),
1338 /* l10n: shortcuts for Megabyte */
1339 __('MiB'),
1340 /* l10n: shortcuts for Gigabyte */
1341 __('GiB'),
1342 /* l10n: shortcuts for Terabyte */
1343 __('TiB'),
1344 /* l10n: shortcuts for Petabyte */
1345 __('PiB'),
1346 /* l10n: shortcuts for Exabyte */
1347 __('EiB')
1350 $dh = PMA_pow(10, $comma);
1351 $li = PMA_pow(10, $limes);
1352 $unit = $byteUnits[0];
1354 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1355 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1356 // use 1024.0 to avoid integer overflow on 64-bit machines
1357 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1358 $unit = $byteUnits[$d];
1359 break 1;
1360 } // end if
1361 } // end for
1363 if ($unit != $byteUnits[0]) {
1364 // if the unit is not bytes (as represented in current language)
1365 // reformat with max length of 5
1366 // 4th parameter=true means do not reformat if value < 1
1367 $return_value = PMA_formatNumber($value, 5, $comma, true);
1368 } else {
1369 // do not reformat, just handle the locale
1370 $return_value = PMA_formatNumber($value, 0);
1373 return array(trim($return_value), $unit);
1374 } // end of the 'PMA_formatByteDown' function
1377 * Changes thousands and decimal separators to locale specific values.
1379 * @param string $value the value
1381 * @return string
1383 function PMA_localizeNumber($value)
1385 return str_replace(
1386 array(',', '.'),
1387 array(
1388 /* l10n: Thousands separator */
1389 __(','),
1390 /* l10n: Decimal separator */
1391 __('.'),
1393 $value
1398 * Formats $value to the given length and appends SI prefixes
1399 * with a $length of 0 no truncation occurs, number is only formated
1400 * to the current locale
1402 * examples:
1403 * <code>
1404 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1405 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1406 * echo PMA_formatNumber(-0.003, 6); // -3 m
1407 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1408 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1409 * echo PMA_formatNumber(0, 6); // 0
1410 * </code>
1412 * @param double $value the value to format
1413 * @param integer $digits_left number of digits left of the comma
1414 * @param integer $digits_right number of digits right of the comma
1415 * @param boolean $only_down do not reformat numbers below 1
1416 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1417 * (default: true)
1419 * @return string the formatted value and its unit
1421 * @access public
1423 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1424 $only_down = false, $noTrailingZero = true)
1426 if ($value==0) {
1427 return '0';
1430 $originalValue = $value;
1431 //number_format is not multibyte safe, str_replace is safe
1432 if ($digits_left === 0) {
1433 $value = number_format($value, $digits_right);
1434 if ($originalValue != 0 && floatval($value) == 0) {
1435 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1438 return PMA_localizeNumber($value);
1441 // this units needs no translation, ISO
1442 $units = array(
1443 -8 => 'y',
1444 -7 => 'z',
1445 -6 => 'a',
1446 -5 => 'f',
1447 -4 => 'p',
1448 -3 => 'n',
1449 -2 => '&micro;',
1450 -1 => 'm',
1451 0 => ' ',
1452 1 => 'k',
1453 2 => 'M',
1454 3 => 'G',
1455 4 => 'T',
1456 5 => 'P',
1457 6 => 'E',
1458 7 => 'Z',
1459 8 => 'Y'
1462 // check for negative value to retain sign
1463 if ($value < 0) {
1464 $sign = '-';
1465 $value = abs($value);
1466 } else {
1467 $sign = '';
1470 $dh = PMA_pow(10, $digits_right);
1473 * This gives us the right SI prefix already,
1474 * but $digits_left parameter not incorporated
1476 $d = floor(log10($value) / 3);
1478 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1479 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1480 * to use, then lower the SI prefix
1482 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1483 if ($digits_left > $cur_digits) {
1484 $d-= floor(($digits_left - $cur_digits)/3);
1487 if ($d<0 && $only_down) {
1488 $d=0;
1491 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1492 $unit = $units[$d];
1494 // If we dont want any zeros after the comma just add the thousand seperator
1495 if ($noTrailingZero) {
1496 $value = PMA_localizeNumber(
1497 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1499 } else {
1500 //number_format is not multibyte safe, str_replace is safe
1501 $value = PMA_localizeNumber(number_format($value, $digits_right));
1504 if ($originalValue!=0 && floatval($value) == 0) {
1505 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1508 return $sign . $value . ' ' . $unit;
1509 } // end of the 'PMA_formatNumber' function
1512 * Returns the number of bytes when a formatted size is given
1514 * @param string $formatted_size the size expression (for example 8MB)
1516 * @return integer The numerical part of the expression (for example 8)
1518 function PMA_extractValueFromFormattedSize($formatted_size)
1520 $return_value = -1;
1522 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1523 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1524 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1525 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1526 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1527 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1529 return $return_value;
1530 }// end of the 'PMA_extractValueFromFormattedSize' function
1533 * Writes localised date
1535 * @param string $timestamp the current timestamp
1536 * @param string $format format
1538 * @return string the formatted date
1540 * @access public
1542 function PMA_localisedDate($timestamp = -1, $format = '')
1544 $month = array(
1545 /* l10n: Short month name */
1546 __('Jan'),
1547 /* l10n: Short month name */
1548 __('Feb'),
1549 /* l10n: Short month name */
1550 __('Mar'),
1551 /* l10n: Short month name */
1552 __('Apr'),
1553 /* l10n: Short month name */
1554 _pgettext('Short month name', 'May'),
1555 /* l10n: Short month name */
1556 __('Jun'),
1557 /* l10n: Short month name */
1558 __('Jul'),
1559 /* l10n: Short month name */
1560 __('Aug'),
1561 /* l10n: Short month name */
1562 __('Sep'),
1563 /* l10n: Short month name */
1564 __('Oct'),
1565 /* l10n: Short month name */
1566 __('Nov'),
1567 /* l10n: Short month name */
1568 __('Dec'));
1569 $day_of_week = array(
1570 /* l10n: Short week day name */
1571 _pgettext('Short week day name', 'Sun'),
1572 /* l10n: Short week day name */
1573 __('Mon'),
1574 /* l10n: Short week day name */
1575 __('Tue'),
1576 /* l10n: Short week day name */
1577 __('Wed'),
1578 /* l10n: Short week day name */
1579 __('Thu'),
1580 /* l10n: Short week day name */
1581 __('Fri'),
1582 /* l10n: Short week day name */
1583 __('Sat'));
1585 if ($format == '') {
1586 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1587 $format = __('%B %d, %Y at %I:%M %p');
1590 if ($timestamp == -1) {
1591 $timestamp = time();
1594 $date = preg_replace(
1595 '@%[aA]@',
1596 $day_of_week[(int)strftime('%w', $timestamp)],
1597 $format
1599 $date = preg_replace(
1600 '@%[bB]@',
1601 $month[(int)strftime('%m', $timestamp)-1],
1602 $date
1605 return strftime($date, $timestamp);
1606 } // end of the 'PMA_localisedDate()' function
1610 * returns a tab for tabbed navigation.
1611 * If the variables $link and $args ar left empty, an inactive tab is created
1613 * @param array $tab array with all options
1614 * @param array $url_params
1616 * @return string html code for one tab, a link if valid otherwise a span
1618 * @access public
1620 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1622 // default values
1623 $defaults = array(
1624 'text' => '',
1625 'class' => '',
1626 'active' => null,
1627 'link' => '',
1628 'sep' => '?',
1629 'attr' => '',
1630 'args' => '',
1631 'warning' => '',
1632 'fragment' => '',
1633 'id' => '',
1636 $tab = array_merge($defaults, $tab);
1638 // determine additionnal style-class
1639 if (empty($tab['class'])) {
1640 if (! empty($tab['active'])
1641 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1643 $tab['class'] = 'active';
1644 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1645 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1646 && empty($tab['warning'])) {
1647 $tab['class'] = 'active';
1651 if (!empty($tab['warning'])) {
1652 $tab['class'] .= ' error';
1653 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1656 // If there are any tab specific URL parameters, merge those with
1657 // the general URL parameters
1658 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1659 $url_params = array_merge($url_params, $tab['url_params']);
1662 // build the link
1663 if (!empty($tab['link'])) {
1664 $tab['link'] = htmlentities($tab['link']);
1665 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1666 if (! empty($tab['args'])) {
1667 foreach ($tab['args'] as $param => $value) {
1668 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1669 . '=' . urlencode($value);
1674 if (! empty($tab['fragment'])) {
1675 $tab['link'] .= $tab['fragment'];
1678 // display icon, even if iconic is disabled but the link-text is missing
1679 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1680 && isset($tab['icon'])
1682 // avoid generating an alt tag, because it only illustrates
1683 // the text that follows and if browser does not display
1684 // images, the text is duplicated
1685 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1686 .' width="16" height="16" alt="" />%2$s';
1687 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1688 } elseif (empty($tab['text'])) {
1689 // check to not display an empty link-text
1690 $tab['text'] = '?';
1691 trigger_error(
1692 'empty linktext in function ' . __FUNCTION__ . '()',
1693 E_USER_NOTICE
1697 //Set the id for the tab, if set in the params
1698 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1699 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1701 if (!empty($tab['link'])) {
1702 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1703 .$id_string
1704 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1705 . $tab['text'] . '</a>';
1706 } else {
1707 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1708 . $tab['text'] . '</span>';
1711 $out .= '</li>';
1712 return $out;
1713 } // end of the 'PMA_generate_html_tab()' function
1716 * returns html-code for a tab navigation
1718 * @param array $tabs one element per tab
1719 * @param string $url_params
1721 * @return string html-code for tab-navigation
1723 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1725 $tag_id = 'topmenu';
1726 $tab_navigation = '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1727 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1729 foreach ($tabs as $tab) {
1730 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1733 $tab_navigation .=
1734 '</ul>' . "\n"
1735 .'<div class="clearfloat"></div>'
1736 .'</div>' . "\n";
1738 return $tab_navigation;
1743 * Displays a link, or a button if the link's URL is too large, to
1744 * accommodate some browsers' limitations
1746 * @param string $url the URL
1747 * @param string $message the link message
1748 * @param mixed $tag_params string: js confirmation
1749 * array: additional tag params (f.e. style="")
1750 * @param boolean $new_form we set this to false when we are already in
1751 * a form, to avoid generating nested forms
1752 * @param boolean $strip_img whether to strip the image
1753 * @param string $target target
1755 * @return string the results to be echoed or saved in an array
1757 function PMA_linkOrButton($url, $message, $tag_params = array(),
1758 $new_form = true, $strip_img = false, $target = '')
1760 $url_length = strlen($url);
1761 // with this we should be able to catch case of image upload
1762 // into a (MEDIUM) BLOB; not worth generating even a form for these
1763 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1764 return '';
1768 if (! is_array($tag_params)) {
1769 $tmp = $tag_params;
1770 $tag_params = array();
1771 if (!empty($tmp)) {
1772 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1774 unset($tmp);
1776 if (! empty($target)) {
1777 $tag_params['target'] = htmlentities($target);
1780 $tag_params_strings = array();
1781 foreach ($tag_params as $par_name => $par_value) {
1782 // htmlspecialchars() only on non javascript
1783 $par_value = substr($par_name, 0, 2) == 'on'
1784 ? $par_value
1785 : htmlspecialchars($par_value);
1786 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1789 $displayed_message = '';
1790 // Add text if not already added
1791 if (stristr($message, '<img')
1792 && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
1793 && strip_tags($message)==$message
1795 $displayed_message = '<span>'
1796 . htmlspecialchars(
1797 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1799 . '</span>';
1802 // Suhosin: Check that each query parameter is not above maximum
1803 $in_suhosin_limits = true;
1804 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1805 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1806 $query_parts = PMA_splitURLQuery($url);
1807 foreach ($query_parts as $query_pair) {
1808 list($eachvar, $eachval) = explode('=', $query_pair);
1809 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1810 $in_suhosin_limits = false;
1811 break;
1817 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1818 // no whitespace within an <a> else Safari will make it part of the link
1819 $ret = "\n" . '<a href="' . $url . '" '
1820 . implode(' ', $tag_params_strings) . '>'
1821 . $message . $displayed_message . '</a>' . "\n";
1822 } else {
1823 // no spaces (linebreaks) at all
1824 // or after the hidden fields
1825 // IE will display them all
1827 // add class=link to submit button
1828 if (empty($tag_params['class'])) {
1829 $tag_params['class'] = 'link';
1832 if (! isset($query_parts)) {
1833 $query_parts = PMA_splitURLQuery($url);
1835 $url_parts = parse_url($url);
1837 if ($new_form) {
1838 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1839 . ' method="post"' . $target . ' style="display: inline;">';
1840 $subname_open = '';
1841 $subname_close = '';
1842 $submit_link = '#';
1843 } else {
1844 $query_parts[] = 'redirect=' . $url_parts['path'];
1845 if (empty($GLOBALS['subform_counter'])) {
1846 $GLOBALS['subform_counter'] = 0;
1848 $GLOBALS['subform_counter']++;
1849 $ret = '';
1850 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1851 $subname_close = ']';
1852 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1854 foreach ($query_parts as $query_pair) {
1855 list($eachvar, $eachval) = explode('=', $query_pair);
1856 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1857 . $subname_close . '" value="'
1858 . htmlspecialchars(urldecode($eachval)) . '" />';
1859 } // end while
1861 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1862 . implode(' ', $tag_params_strings) . '>'
1863 . $message . ' ' . $displayed_message . '</a>' . "\n";
1865 if ($new_form) {
1866 $ret .= '</form>';
1868 } // end if... else...
1870 return $ret;
1871 } // end of the 'PMA_linkOrButton()' function
1875 * Splits a URL string by parameter
1877 * @param string $url the URL
1879 * @return array the parameter/value pairs, for example [0] db=sakila
1881 function PMA_splitURLQuery($url)
1883 // decode encoded url separators
1884 $separator = PMA_get_arg_separator();
1885 // on most places separator is still hard coded ...
1886 if ($separator !== '&') {
1887 // ... so always replace & with $separator
1888 $url = str_replace(htmlentities('&'), $separator, $url);
1889 $url = str_replace('&', $separator, $url);
1891 $url = str_replace(htmlentities($separator), $separator, $url);
1892 // end decode
1894 $url_parts = parse_url($url);
1895 return explode($separator, $url_parts['query']);
1899 * Returns a given timespan value in a readable format.
1901 * @param int $seconds the timespan
1903 * @return string the formatted value
1905 function PMA_timespanFormat($seconds)
1907 $days = floor($seconds / 86400);
1908 if ($days > 0) {
1909 $seconds -= $days * 86400;
1911 $hours = floor($seconds / 3600);
1912 if ($days > 0 || $hours > 0) {
1913 $seconds -= $hours * 3600;
1915 $minutes = floor($seconds / 60);
1916 if ($days > 0 || $hours > 0 || $minutes > 0) {
1917 $seconds -= $minutes * 60;
1919 return sprintf(
1920 __('%s days, %s hours, %s minutes and %s seconds'),
1921 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1926 * Takes a string and outputs each character on a line for itself. Used
1927 * mainly for horizontalflipped display mode.
1928 * Takes care of special html-characters.
1929 * Fulfills todo-item
1930 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1932 * @param string $string The string
1933 * @param string $Separator The Separator (defaults to "<br />\n")
1935 * @access public
1936 * @todo add a multibyte safe function PMA_STR_split()
1938 * @return string The flipped string
1940 function PMA_flipstring($string, $Separator = "<br />\n")
1942 $format_string = '';
1943 $charbuff = false;
1945 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1946 $char = $string{$i};
1947 $append = false;
1949 if ($char == '&') {
1950 $format_string .= $charbuff;
1951 $charbuff = $char;
1952 } elseif ($char == ';' && !empty($charbuff)) {
1953 $format_string .= $charbuff . $char;
1954 $charbuff = false;
1955 $append = true;
1956 } elseif (! empty($charbuff)) {
1957 $charbuff .= $char;
1958 } else {
1959 $format_string .= $char;
1960 $append = true;
1963 // do not add separator after the last character
1964 if ($append && ($i != $str_len - 1)) {
1965 $format_string .= $Separator;
1969 return $format_string;
1973 * Function added to avoid path disclosures.
1974 * Called by each script that needs parameters, it displays
1975 * an error message and, by default, stops the execution.
1977 * Not sure we could use a strMissingParameter message here,
1978 * would have to check if the error message file is always available
1980 * @param array $params The names of the parameters needed by the calling script.
1981 * @param bool $die Stop the execution?
1982 * (Set this manually to false in the calling script
1983 * until you know all needed parameters to check).
1984 * @param bool $request Whether to include this list in checking for special params.
1986 * @global string path to current script
1987 * @global boolean flag whether any special variable was required
1989 * @access public
1990 * @todo use PMA_fatalError() if $die === true?
1992 function PMA_checkParameters($params, $die = true, $request = true)
1994 global $checked_special;
1996 if (! isset($checked_special)) {
1997 $checked_special = false;
2000 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2001 $found_error = false;
2002 $error_message = '';
2004 foreach ($params as $param) {
2005 if ($request && $param != 'db' && $param != 'table') {
2006 $checked_special = true;
2009 if (! isset($GLOBALS[$param])) {
2010 $error_message .= $reported_script_name
2011 . ': ' . __('Missing parameter:') . ' '
2012 . $param
2013 . PMA_showDocu('faqmissingparameters')
2014 . '<br />';
2015 $found_error = true;
2018 if ($found_error) {
2020 * display html meta tags
2022 include_once './libraries/header_meta_style.inc.php';
2023 echo '</head><body><p>' . $error_message . '</p></body></html>';
2024 if ($die) {
2025 exit();
2028 } // end function
2031 * Function to generate unique condition for specified row.
2033 * @param resource $handle current query result
2034 * @param integer $fields_cnt number of fields
2035 * @param array $fields_meta meta information about fields
2036 * @param array $row current row
2037 * @param boolean $force_unique generate condition only on pk or unique
2039 * @access public
2041 * @return array the calculated condition and whether condition is unique
2043 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2045 $primary_key = '';
2046 $unique_key = '';
2047 $nonprimary_condition = '';
2048 $preferred_condition = '';
2049 $primary_key_array = array();
2050 $unique_key_array = array();
2051 $nonprimary_condition_array = array();
2052 $condition_array = array();
2054 for ($i = 0; $i < $fields_cnt; ++$i) {
2055 $condition = '';
2056 $con_key = '';
2057 $con_val = '';
2058 $field_flags = PMA_DBI_field_flags($handle, $i);
2059 $meta = $fields_meta[$i];
2061 // do not use a column alias in a condition
2062 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2063 $meta->orgname = $meta->name;
2065 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2066 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2068 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2069 // need (string) === (string)
2070 // '' !== 0 but '' == 0
2071 if ((string) $select_expr['alias'] === (string) $meta->name) {
2072 $meta->orgname = $select_expr['column'];
2073 break;
2074 } // end if
2075 } // end foreach
2079 // Do not use a table alias in a condition.
2080 // Test case is:
2081 // select * from galerie x WHERE
2082 //(select count(*) from galerie y where y.datum=x.datum)>1
2084 // But orgtable is present only with mysqli extension so the
2085 // fix is only for mysqli.
2086 // Also, do not use the original table name if we are dealing with
2087 // a view because this view might be updatable.
2088 // (The isView() verification should not be costly in most cases
2089 // because there is some caching in the function).
2090 if (isset($meta->orgtable)
2091 && $meta->table != $meta->orgtable
2092 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2094 $meta->table = $meta->orgtable;
2097 // to fix the bug where float fields (primary or not)
2098 // can't be matched because of the imprecision of
2099 // floating comparison, use CONCAT
2100 // (also, the syntax "CONCAT(field) IS NULL"
2101 // that we need on the next "if" will work)
2102 if ($meta->type == 'real') {
2103 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2104 . PMA_backquote($meta->orgname) . ')';
2105 } else {
2106 $con_key = PMA_backquote($meta->table) . '.'
2107 . PMA_backquote($meta->orgname);
2108 } // end if... else...
2109 $condition = ' ' . $con_key . ' ';
2111 if (! isset($row[$i]) || is_null($row[$i])) {
2112 $con_val = 'IS NULL';
2113 } else {
2114 // timestamp is numeric on some MySQL 4.1
2115 // for real we use CONCAT above and it should compare to string
2116 if ($meta->numeric
2117 && $meta->type != 'timestamp'
2118 && $meta->type != 'real'
2120 $con_val = '= ' . $row[$i];
2121 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2122 // hexify only if this is a true not empty BLOB or a BINARY
2123 && stristr($field_flags, 'BINARY')
2124 && !empty($row[$i])) {
2125 // do not waste memory building a too big condition
2126 if (strlen($row[$i]) < 1000) {
2127 // use a CAST if possible, to avoid problems
2128 // if the field contains wildcard characters % or _
2129 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2130 } else {
2131 // this blob won't be part of the final condition
2132 $con_val = null;
2134 } elseif (in_array($meta->type, PMA_getGISDatatypes())
2135 && ! empty($row[$i])
2137 // do not build a too big condition
2138 if (strlen($row[$i]) < 5000) {
2139 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2140 } else {
2141 $condition = '';
2143 } elseif ($meta->type == 'bit') {
2144 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2145 } else {
2146 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2149 if ($con_val != null) {
2150 $condition .= $con_val . ' AND';
2151 if ($meta->primary_key > 0) {
2152 $primary_key .= $condition;
2153 $primary_key_array[$con_key] = $con_val;
2154 } elseif ($meta->unique_key > 0) {
2155 $unique_key .= $condition;
2156 $unique_key_array[$con_key] = $con_val;
2158 $nonprimary_condition .= $condition;
2159 $nonprimary_condition_array[$con_key] = $con_val;
2161 } // end for
2163 // Correction University of Virginia 19991216:
2164 // prefer primary or unique keys for condition,
2165 // but use conjunction of all values if no primary key
2166 $clause_is_unique = true;
2167 if ($primary_key) {
2168 $preferred_condition = $primary_key;
2169 $condition_array = $primary_key_array;
2170 } elseif ($unique_key) {
2171 $preferred_condition = $unique_key;
2172 $condition_array = $unique_key_array;
2173 } elseif (! $force_unique) {
2174 $preferred_condition = $nonprimary_condition;
2175 $condition_array = $nonprimary_condition_array;
2176 $clause_is_unique = false;
2179 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2180 return(array($where_clause, $clause_is_unique, $condition_array));
2181 } // end function
2184 * Generate a button or image tag
2186 * @param string $button_name name of button element
2187 * @param string $button_class class of button element
2188 * @param string $image_name name of image element
2189 * @param string $text text to display
2190 * @param string $image image to display
2191 * @param string $value value
2193 * @access public
2195 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2196 $image, $value = '')
2198 if ($value == '') {
2199 $value = $text;
2201 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2202 echo ' <input type="submit" name="' . $button_name . '"'
2203 .' value="' . htmlspecialchars($value) . '"'
2204 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2205 return;
2208 /* Opera has trouble with <input type="image"> */
2209 /* IE has trouble with <button> */
2210 if (PMA_USR_BROWSER_AGENT != 'IE') {
2211 echo '<button class="' . $button_class . '" type="submit"'
2212 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2213 .' title="' . htmlspecialchars($text) . '">' . "\n"
2214 . PMA_getIcon($image, $text)
2215 .'</button>' . "\n";
2216 } else {
2217 echo '<input type="image" name="' . $image_name
2218 . '" value="' . htmlspecialchars($value)
2219 . '" title="' . htmlspecialchars($text)
2220 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2221 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2222 ? '&nbsp;' . htmlspecialchars($text)
2223 : '') . "\n";
2225 } // end function
2228 * Generate a pagination selector for browsing resultsets
2230 * @param int $rows Number of rows in the pagination set
2231 * @param int $pageNow current page number
2232 * @param int $nbTotalPage number of total pages
2233 * @param int $showAll If the number of pages is lower than this
2234 * variable, no pages will be omitted in pagination
2235 * @param int $sliceStart How many rows at the beginning should always be shown?
2236 * @param int $sliceEnd How many rows at the end should always be shown?
2237 * @param int $percent Percentage of calculation page offsets to hop to a
2238 * next page
2239 * @param int $range Near the current page, how many pages should
2240 * be considered "nearby" and displayed as well?
2241 * @param string $prompt The prompt to display (sometimes empty)
2243 * @return string
2245 * @access public
2247 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2248 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2249 $range = 10, $prompt = '')
2251 $increment = floor($nbTotalPage / $percent);
2252 $pageNowMinusRange = ($pageNow - $range);
2253 $pageNowPlusRange = ($pageNow + $range);
2255 $gotopage = $prompt . ' <select id="pageselector" ';
2256 if ($GLOBALS['cfg']['AjaxEnable']) {
2257 $gotopage .= ' class="ajax"';
2259 $gotopage .= ' name="pos" >' . "\n";
2260 if ($nbTotalPage < $showAll) {
2261 $pages = range(1, $nbTotalPage);
2262 } else {
2263 $pages = array();
2265 // Always show first X pages
2266 for ($i = 1; $i <= $sliceStart; $i++) {
2267 $pages[] = $i;
2270 // Always show last X pages
2271 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2272 $pages[] = $i;
2275 // Based on the number of results we add the specified
2276 // $percent percentage to each page number,
2277 // so that we have a representing page number every now and then to
2278 // immediately jump to specific pages.
2279 // As soon as we get near our currently chosen page ($pageNow -
2280 // $range), every page number will be shown.
2281 $i = $sliceStart;
2282 $x = $nbTotalPage - $sliceEnd;
2283 $met_boundary = false;
2284 while ($i <= $x) {
2285 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2286 // If our pageselector comes near the current page, we use 1
2287 // counter increments
2288 $i++;
2289 $met_boundary = true;
2290 } else {
2291 // We add the percentage increment to our current page to
2292 // hop to the next one in range
2293 $i += $increment;
2295 // Make sure that we do not cross our boundaries.
2296 if ($i > $pageNowMinusRange && ! $met_boundary) {
2297 $i = $pageNowMinusRange;
2301 if ($i > 0 && $i <= $x) {
2302 $pages[] = $i;
2306 // Since because of ellipsing of the current page some numbers may be double,
2307 // we unify our array:
2308 sort($pages);
2309 $pages = array_unique($pages);
2312 foreach ($pages as $i) {
2313 if ($i == $pageNow) {
2314 $selected = 'selected="selected" style="font-weight: bold"';
2315 } else {
2316 $selected = '';
2318 $gotopage .= ' <option ' . $selected
2319 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2322 $gotopage .= ' </select><noscript><input type="submit" value="'
2323 . __('Go') . '" /></noscript>';
2325 return $gotopage;
2326 } // end function
2330 * Generate navigation for a list
2332 * @param int $count number of elements in the list
2333 * @param int $pos current position in the list
2334 * @param array $_url_params url parameters
2335 * @param string $script script name for form target
2336 * @param string $frame target frame
2337 * @param int $max_count maximum number of elements to display from the list
2339 * @access public
2341 * @todo use $pos from $_url_params
2343 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2346 if ($max_count < $count) {
2347 echo 'frame_navigation' == $frame
2348 ? '<div id="navidbpageselector">' . "\n"
2349 : '';
2350 echo __('Page number:');
2351 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2353 // Move to the beginning or to the previous page
2354 if ($pos > 0) {
2355 // patch #474210 - part 1
2356 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2357 $caption1 = '&lt;&lt;';
2358 $caption2 = ' &lt; ';
2359 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2360 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2361 } else {
2362 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2363 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2364 $title1 = '';
2365 $title2 = '';
2366 } // end if... else...
2367 $_url_params['pos'] = 0;
2368 echo '<a' . $title1 . ' href="' . $script
2369 . PMA_generate_common_url($_url_params) . '" target="'
2370 . $frame . '">' . $caption1 . '</a>';
2371 $_url_params['pos'] = $pos - $max_count;
2372 echo '<a' . $title2 . ' href="' . $script
2373 . PMA_generate_common_url($_url_params) . '" target="'
2374 . $frame . '">' . $caption2 . '</a>';
2377 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2378 echo PMA_generate_common_hidden_inputs($_url_params);
2379 echo PMA_pageselector(
2380 $max_count,
2381 floor(($pos + 1) / $max_count) + 1,
2382 ceil($count / $max_count)
2384 echo '</form>';
2386 if ($pos + $max_count < $count) {
2387 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2388 $caption3 = ' &gt; ';
2389 $caption4 = '&gt;&gt;';
2390 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2391 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2392 } else {
2393 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2394 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2395 $title3 = '';
2396 $title4 = '';
2397 } // end if... else...
2398 $_url_params['pos'] = $pos + $max_count;
2399 echo '<a' . $title3 . ' href="' . $script
2400 . PMA_generate_common_url($_url_params) . '" target="'
2401 . $frame . '">' . $caption3 . '</a>';
2402 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2403 if ($_url_params['pos'] == $count) {
2404 $_url_params['pos'] = $count - $max_count;
2406 echo '<a' . $title4 . ' href="' . $script
2407 . PMA_generate_common_url($_url_params) . '" target="'
2408 . $frame . '">' . $caption4 . '</a>';
2410 echo "\n";
2411 if ('frame_navigation' == $frame) {
2412 echo '</div>' . "\n";
2418 * replaces %u in given path with current user name
2420 * example:
2421 * <code>
2422 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2424 * </code>
2426 * @param string $dir with wildcard for user
2428 * @return string per user directory
2430 function PMA_userDir($dir)
2432 // add trailing slash
2433 if (substr($dir, -1) != '/') {
2434 $dir .= '/';
2437 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2441 * returns html code for db link to default db page
2443 * @param string $database database
2445 * @return string html link to default db page
2447 function PMA_getDbLink($database = null)
2449 if (! strlen($database)) {
2450 if (! strlen($GLOBALS['db'])) {
2451 return '';
2453 $database = $GLOBALS['db'];
2454 } else {
2455 $database = PMA_unescape_mysql_wildcards($database);
2458 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2459 . PMA_generate_common_url($database) . '" title="'
2460 . sprintf(
2461 __('Jump to database &quot;%s&quot;.'),
2462 htmlspecialchars($database)
2464 . '">' . htmlspecialchars($database) . '</a>';
2468 * Displays a lightbulb hint explaining a known external bug
2469 * that affects a functionality
2471 * @param string $functionality localized message explaining the func.
2472 * @param string $component 'mysql' (eventually, 'php')
2473 * @param string $minimum_version of this component
2474 * @param string $bugref bug reference for this component
2476 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2478 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2479 echo PMA_showHint(
2480 sprintf(
2481 __('The %s functionality is affected by a known bug, see %s'),
2482 $functionality,
2483 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2490 * Generates and echoes an HTML checkbox
2492 * @param string $html_field_name the checkbox HTML field
2493 * @param string $label label for checkbox
2494 * @param boolean $checked is it initially checked?
2495 * @param boolean $onclick should it submit the form on click?
2497 * @return the HTML for the checkbox
2499 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2502 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2503 . $html_field_name . '"' . ($checked ? ' checked="checked"' : '')
2504 . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="'
2505 . $html_field_name . '">' . $label . '</label>';
2509 * Generates and echoes a set of radio HTML fields
2511 * @param string $html_field_name the radio HTML field
2512 * @param array $choices the choices values and labels
2513 * @param string $checked_choice the choice to check by default
2514 * @param boolean $line_break whether to add an HTML line break after a choice
2515 * @param boolean $escape_label whether to use htmlspecialchars() on label
2516 * @param string $class enclose each choice with a div of this class
2518 * @return the HTML for the tadio buttons
2520 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2521 $line_break = true, $escape_label = true, $class='')
2523 foreach ($choices as $choice_value => $choice_label) {
2524 if (! empty($class)) {
2525 echo '<div class="' . $class . '">';
2527 $html_field_id = $html_field_name . '_' . $choice_value;
2528 echo '<input type="radio" name="' . $html_field_name . '" id="'
2529 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2530 if ($choice_value == $checked_choice) {
2531 echo ' checked="checked"';
2533 echo ' />' . "\n";
2534 echo '<label for="' . $html_field_id . '">'
2535 . ($escape_label ? htmlspecialchars($choice_label) : $choice_label)
2536 . '</label>';
2537 if ($line_break) {
2538 echo '<br />';
2540 if (! empty($class)) {
2541 echo '</div>';
2543 echo "\n";
2548 * Generates and returns an HTML dropdown
2550 * @param string $select_name name for the select element
2551 * @param array $choices choices values
2552 * @param string $active_choice the choice to select by default
2553 * @param string $id id of the select element; can be different in case
2554 * the dropdown is present more than once on the page
2556 * @return string
2558 * @todo support titles
2560 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2562 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2563 . htmlspecialchars($id) . '">';
2564 foreach ($choices as $one_choice_value => $one_choice_label) {
2565 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2566 if ($one_choice_value == $active_choice) {
2567 $result .= ' selected="selected"';
2569 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2571 $result .= '</select>';
2572 return $result;
2576 * Generates a slider effect (jQjuery)
2577 * Takes care of generating the initial <div> and the link
2578 * controlling the slider; you have to generate the </div> yourself
2579 * after the sliding section.
2581 * @param string $id the id of the <div> on which to apply the effect
2582 * @param string $message the message to show as a link
2584 function PMA_generate_slider_effect($id, $message)
2586 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2587 echo '<div id="' . $id . '">';
2588 return;
2591 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2592 * opening the <div> with PHP itself instead of JavaScript.
2594 * @todo find a better solution that uses $.append(), the recommended method
2595 * maybe by using an additional param, the id of the div to append to
2598 <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); ?>">
2599 <?php
2603 * Creates an AJAX sliding toggle button
2604 * (or and equivalent form when AJAX is disabled)
2606 * @param string $action The URL for the request to be executed
2607 * @param string $select_name The name for the dropdown box
2608 * @param array $options An array of options (see rte_footer.lib.php)
2609 * @param string $callback A JS snippet to execute when the request is
2610 * successfully processed
2612 * @return string HTML code for the toggle button
2614 function PMA_toggleButton($action, $select_name, $options, $callback)
2616 // Do the logic first
2617 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2618 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2619 if ($options[1]['selected'] == true) {
2620 $state = 'on';
2621 } else if ($options[0]['selected'] == true) {
2622 $state = 'off';
2623 } else {
2624 $state = 'on';
2626 $selected1 = '';
2627 $selected0 = '';
2628 if ($options[1]['selected'] == true) {
2629 $selected1 = " selected='selected'";
2630 } else if ($options[0]['selected'] == true) {
2631 $selected0 = " selected='selected'";
2633 // Generate output
2634 $retval = "<!-- TOGGLE START -->\n";
2635 if ($GLOBALS['cfg']['AjaxEnable']) {
2636 $retval .= "<noscript>\n";
2638 $retval .= "<div class='wrapper'>\n";
2639 $retval .= " <form action='$action' method='post'>\n";
2640 $retval .= " <select name='$select_name'>\n";
2641 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2642 $retval .= " {$options[1]['label']}\n";
2643 $retval .= " </option>\n";
2644 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2645 $retval .= " {$options[0]['label']}\n";
2646 $retval .= " </option>\n";
2647 $retval .= " </select>\n";
2648 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2649 $retval .= " </form>\n";
2650 $retval .= "</div>\n";
2651 if ($GLOBALS['cfg']['AjaxEnable']) {
2652 $retval .= "</noscript>\n";
2653 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2654 $retval .= " <div class='toggleButton'>\n";
2655 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2656 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2657 $retval .= " alt='' />\n";
2658 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2659 $retval .= " <tbody>\n";
2660 $retval .= " <td class='toggleOn'>\n";
2661 $retval .= " <span class='hide'>$link_on</span>\n";
2662 $retval .= " <div>";
2663 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2664 $retval .= " </td>\n";
2665 $retval .= " <td><div>&nbsp;</div></td>\n";
2666 $retval .= " <td class='toggleOff'>\n";
2667 $retval .= " <span class='hide'>$link_off</span>\n";
2668 $retval .= " <div>";
2669 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2670 $retval .= " </div>\n";
2671 $retval .= " </tbody>\n";
2672 $retval .= " </tr></table>\n";
2673 $retval .= " <span class='hide callback'>$callback</span>\n";
2674 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2675 $retval .= " </div>\n";
2676 $retval .= " </div>\n";
2677 $retval .= "</div>\n";
2679 $retval .= "<!-- TOGGLE END -->";
2681 return $retval;
2682 } // end PMA_toggleButton()
2685 * Clears cache content which needs to be refreshed on user change.
2687 * @return nothing
2689 function PMA_clearUserCache()
2691 PMA_cacheUnset('is_superuser', true);
2695 * Verifies if something is cached in the session
2697 * @param string $var variable name
2698 * @param int|true $server server
2700 * @return boolean
2702 function PMA_cacheExists($var, $server = 0)
2704 if (true === $server) {
2705 $server = $GLOBALS['server'];
2707 return isset($_SESSION['cache']['server_' . $server][$var]);
2711 * Gets cached information from the session
2713 * @param string $var varibale name
2714 * @param int|true $server server
2716 * @return mixed
2718 function PMA_cacheGet($var, $server = 0)
2720 if (true === $server) {
2721 $server = $GLOBALS['server'];
2723 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2724 return $_SESSION['cache']['server_' . $server][$var];
2725 } else {
2726 return null;
2731 * Caches information in the session
2733 * @param string $var variable name
2734 * @param mixed $val value
2735 * @param int|true $server server
2737 * @return mixed
2739 function PMA_cacheSet($var, $val = null, $server = 0)
2741 if (true === $server) {
2742 $server = $GLOBALS['server'];
2744 $_SESSION['cache']['server_' . $server][$var] = $val;
2748 * Removes cached information from the session
2750 * @param string $var variable name
2751 * @param int|true $server server
2753 * @return nothing
2755 function PMA_cacheUnset($var, $server = 0)
2757 if (true === $server) {
2758 $server = $GLOBALS['server'];
2760 unset($_SESSION['cache']['server_' . $server][$var]);
2764 * Converts a bit value to printable format;
2765 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2766 * function because in PHP, decbin() supports only 32 bits
2768 * @param numeric $value coming from a BIT field
2769 * @param integer $length length
2771 * @return string the printable value
2773 function PMA_printable_bit_value($value, $length)
2775 $printable = '';
2776 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2777 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2779 $printable = substr($printable, -$length);
2780 return $printable;
2784 * Verifies whether the value contains a non-printable character
2786 * @param string $value value
2788 * @return boolean
2790 function PMA_contains_nonprintable_ascii($value)
2792 return preg_match('@[^[:print:]]@', $value);
2796 * Converts a BIT type default value
2797 * for example, b'010' becomes 010
2799 * @param string $bit_default_value value
2801 * @return string the converted value
2803 function PMA_convert_bit_default_value($bit_default_value)
2805 return strtr($bit_default_value, array("b" => "", "'" => ""));
2809 * Extracts the various parts from a field type spec
2811 * @param string $fieldspec Field specification
2813 * @return array associative array containing type, spec_in_brackets
2814 * and possibly enum_set_values (another array)
2816 function PMA_extractFieldSpec($fieldspec)
2818 $first_bracket_pos = strpos($fieldspec, '(');
2819 if ($first_bracket_pos) {
2820 $spec_in_brackets = chop(
2821 substr(
2822 $fieldspec,
2823 $first_bracket_pos + 1,
2824 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2827 // convert to lowercase just to be sure
2828 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2829 } else {
2830 $type = strtolower($fieldspec);
2831 $spec_in_brackets = '';
2834 if ('enum' == $type || 'set' == $type) {
2835 // Define our working vars
2836 $enum_set_values = array();
2837 $working = "";
2838 $in_string = false;
2839 $index = 0;
2841 // While there is another character to process
2842 while (isset($fieldspec[$index])) {
2843 // Grab the char to look at
2844 $char = $fieldspec[$index];
2846 // If it is a single quote, needs to be handled specially
2847 if ($char == "'") {
2848 // If we are not currently in a string, begin one
2849 if (! $in_string) {
2850 $in_string = true;
2851 $working = "";
2852 } else {
2853 // Otherwise, it may be either an end of a string,
2854 // or a 'double quote' which can be handled as-is
2855 // Check out the next character (if possible)
2856 $has_next = isset($fieldspec[$index + 1]);
2857 $next = $has_next ? $fieldspec[$index + 1] : null;
2859 //If we have reached the end of our 'working' string (because
2860 //there are no more chars,or the next char is not another quote)
2861 if (! $has_next || $next != "'") {
2862 $enum_set_values[] = $working;
2863 $in_string = false;
2865 } elseif ($next == "'") {
2866 // Otherwise, this is a 'double quote',
2867 // and can be added to the working string
2868 $working .= "'";
2869 // Skip the next char; we already know what it is
2870 $index++;
2873 } elseif ('\\' == $char
2874 && isset($fieldspec[$index + 1])
2875 && "'" == $fieldspec[$index + 1]
2877 // escaping of a quote?
2878 $working .= "'";
2879 $index++;
2880 } else {
2881 // Otherwise, add it to our working string like normal
2882 $working .= $char;
2884 // Increment character index
2885 $index++;
2886 } // end while
2887 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2888 $binary = false;
2889 $unsigned = false;
2890 $zerofill = false;
2891 } else {
2892 $enum_set_values = array();
2894 /* Create printable type name */
2895 $printtype = strtolower($fieldspec);
2897 // strip the "BINARY" attribute, except if we find "BINARY(" because
2898 // this would be a BINARY or VARBINARY field type
2899 if (!preg_match('@binary[\(]@', $printtype)) {
2900 $binary = strpos($printtype, 'blob') !== false || strpos($printtype, 'binary') !== false;
2901 $printtype = preg_replace('@binary@', '', $printtype);
2902 } else {
2903 $binary = false;
2905 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2906 $zerofill = ($zerofill_cnt > 0);
2907 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
2908 $unsigned = ($unsigned_cnt > 0);
2909 $printtype = trim($printtype);
2913 $attribute = ' ';
2914 if ($binary) {
2915 $attribute = 'BINARY';
2917 if ($unsigned) {
2918 $attribute = 'UNSIGNED';
2920 if ($zerofill) {
2921 $attribute = 'UNSIGNED ZEROFILL';
2924 return array(
2925 'type' => $type,
2926 'spec_in_brackets' => $spec_in_brackets,
2927 'enum_set_values' => $enum_set_values,
2928 'print_type' => $printtype,
2929 'binary' => $binary,
2930 'unsigned' => $unsigned,
2931 'zerofill' => $zerofill,
2932 'attribute' => $attribute,
2937 * Verifies if this table's engine supports foreign keys
2939 * @param string $engine engine
2941 * @return boolean
2943 function PMA_foreignkey_supported($engine)
2945 $engine = strtoupper($engine);
2946 if ('INNODB' == $engine || 'PBXT' == $engine) {
2947 return true;
2948 } else {
2949 return false;
2954 * Replaces some characters by a displayable equivalent
2956 * @param string $content content
2958 * @return string the content with characters replaced
2960 function PMA_replace_binary_contents($content)
2962 $result = str_replace("\x00", '\0', $content);
2963 $result = str_replace("\x08", '\b', $result);
2964 $result = str_replace("\x0a", '\n', $result);
2965 $result = str_replace("\x0d", '\r', $result);
2966 $result = str_replace("\x1a", '\Z', $result);
2967 return $result;
2971 * Converts GIS data to Well Known Text format
2973 * @param binary $data GIS data
2974 * @param bool $includeSRID Add SRID to the WKT
2976 * @return GIS data in Well Know Text format
2978 function PMA_asWKT($data, $includeSRID = false)
2980 // Convert to WKT format
2981 $hex = bin2hex($data);
2982 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
2983 if ($includeSRID) {
2984 $wktsql .= ", SRID(x'" . $hex . "')";
2986 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
2987 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
2988 $wktval = $wktarr[0];
2989 if ($includeSRID) {
2990 $srid = $wktarr[1];
2991 $wktval = "'" . $wktval . "'," . $srid;
2993 @PMA_DBI_free_result($wktresult);
2994 return $wktval;
2998 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3000 * @param string $string string
3002 * @return string with the chars replaced
3005 function PMA_duplicateFirstNewline($string)
3007 $first_occurence = strpos($string, "\r\n");
3008 if ($first_occurence === 0) {
3009 $string = "\n".$string;
3011 return $string;
3015 * Get the action word corresponding to a script name
3016 * in order to display it as a title in navigation panel
3018 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3019 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3021 * @return array
3023 function PMA_getTitleForTarget($target)
3025 $mapping = array(
3026 // Values for $cfg['DefaultTabTable']
3027 'tbl_structure.php' => __('Structure'),
3028 'tbl_sql.php' => __('SQL'),
3029 'tbl_select.php' =>__('Search'),
3030 'tbl_change.php' =>__('Insert'),
3031 'sql.php' => __('Browse'),
3033 // Values for $cfg['DefaultTabDatabase']
3034 'db_structure.php' => __('Structure'),
3035 'db_sql.php' => __('SQL'),
3036 'db_search.php' => __('Search'),
3037 'db_operations.php' => __('Operations'),
3039 return $mapping[$target];
3043 * Formats user string, expading @VARIABLES@, accepting strftime format string.
3045 * @param string $string Text where to do expansion.
3046 * @param function $escape Function to call for escaping variable values.
3047 * @param array $updates Array with overrides for default parameters
3048 * (obtained from GLOBALS).
3050 * @return string
3052 function PMA_expandUserString($string, $escape = null, $updates = array())
3054 /* Content */
3055 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
3056 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3057 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3058 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3059 ? $GLOBALS['cfg']['Server']['verbose']
3060 : $GLOBALS['cfg']['Server']['host'];
3061 $vars['database'] = $GLOBALS['db'];
3062 $vars['table'] = $GLOBALS['table'];
3063 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
3065 /* Update forced variables */
3066 foreach ($updates as $key => $val) {
3067 $vars[$key] = $val;
3070 /* Replacement mapping */
3072 * The __VAR__ ones are for backward compatibility, because user
3073 * might still have it in cookies.
3075 $replace = array(
3076 '@HTTP_HOST@' => $vars['http_host'],
3077 '@SERVER@' => $vars['server_name'],
3078 '__SERVER__' => $vars['server_name'],
3079 '@VERBOSE@' => $vars['server_verbose'],
3080 '@VSERVER@' => $vars['server_verbose_or_name'],
3081 '@DATABASE@' => $vars['database'],
3082 '__DB__' => $vars['database'],
3083 '@TABLE@' => $vars['table'],
3084 '__TABLE__' => $vars['table'],
3085 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3088 /* Optional escaping */
3089 if (!is_null($escape)) {
3090 foreach ($replace as $key => $val) {
3091 $replace[$key] = $escape($val);
3095 /* Fetch fields list if required */
3096 if (strpos($string, '@FIELDS@') !== false) {
3097 $fields_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3099 $field_names = array();
3100 foreach ($fields_list as $field) {
3101 if (!is_null($escape)) {
3102 $field_names[] = $escape($field['Field']);
3103 } else {
3104 $field_names[] = $field['Field'];
3108 $replace['@FIELDS@'] = implode(',', $field_names);
3111 /* Do the replacement */
3112 return strtr(strftime($string), $replace);
3116 * function that generates a json output for an ajax request and ends script
3117 * execution
3119 * @param PMA_Message|string $message message string containing the
3120 * html of the message
3121 * @param bool $success success whether the ajax request
3122 * was successfull
3123 * @param array $extra_data extra data optional -
3124 * any other data as part of the json request
3126 * @return nothing
3128 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3130 $response = array();
3131 if ( $success == true ) {
3132 $response['success'] = true;
3133 if ($message instanceof PMA_Message) {
3134 $response['message'] = $message->getDisplay();
3135 } else {
3136 $response['message'] = $message;
3138 } else {
3139 $response['success'] = false;
3140 if ($message instanceof PMA_Message) {
3141 $response['error'] = $message->getDisplay();
3142 } else {
3143 $response['error'] = $message;
3147 // If extra_data has been provided, append it to the response array
3148 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3149 $response = array_merge($response, $extra_data);
3152 // Set the Content-Type header to JSON so that jQuery parses the
3153 // response correctly.
3155 // At this point, other headers might have been sent;
3156 // even if $GLOBALS['is_header_sent'] is true,
3157 // we have to send these additional headers.
3158 header('Cache-Control: no-cache');
3159 header("Content-Type: application/json");
3161 echo json_encode($response);
3163 if (!defined('TESTSUITE'))
3164 exit;
3168 * Display the form used to browse anywhere on the local server for a file to import
3170 * @param string $max_upload_size maximum upload size
3172 * @return nothing
3174 function PMA_browseUploadFile($max_upload_size)
3176 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3177 echo '<div id="upload_form_status" style="display: none;"></div>';
3178 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3179 echo '<input type="file" name="import_file" id="input_import_file" />';
3180 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3181 // some browsers should respect this :)
3182 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3186 * Display the form used to select a file to import from the server upload directory
3188 * @param array $import_list array of import types
3189 * @param string $uploaddir upload directory
3191 * @return nothing
3193 function PMA_selectUploadFile($import_list, $uploaddir)
3195 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3196 $extensions = '';
3197 foreach ($import_list as $key => $val) {
3198 if (!empty($extensions)) {
3199 $extensions .= '|';
3201 $extensions .= $val['extension'];
3203 $matcher = '@\.(' . $extensions . ')(\.('
3204 . PMA_supportedDecompressions() . '))?$@';
3206 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3207 ? $local_import_file
3208 : '';
3209 $files = PMA_getFileSelectOptions(
3210 PMA_userDir($uploaddir),
3211 $matcher,
3212 $active
3214 if ($files === false) {
3215 PMA_Message::error(
3216 __('The directory you set for upload work cannot be reached')
3217 )->display();
3218 } elseif (!empty($files)) {
3219 echo "\n";
3220 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3221 echo ' <option value="">&nbsp;</option>' . "\n";
3222 echo $files;
3223 echo ' </select>' . "\n";
3224 } elseif (empty ($files)) {
3225 echo '<i>' . __('There are no files to upload') . '</i>';
3230 * Build titles and icons for action links
3232 * @return array the action titles
3234 function PMA_buildActionTitles()
3236 $titles = array();
3238 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3239 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3240 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3241 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3242 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3243 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3244 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3245 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3246 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3247 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3248 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3249 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3250 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3251 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3252 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3253 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3254 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3255 return $titles;
3259 * This function processes the datatypes supported by the DB, as specified in
3260 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3261 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3263 * @param bool $html Whether to generate an html snippet or an array
3264 * @param string $selected The value to mark as selected in HTML mode
3266 * @return mixed An HTML snippet or an array of datatypes.
3269 function PMA_getSupportedDatatypes($html = false, $selected = '')
3271 global $cfg;
3273 if ($html) {
3274 // NOTE: the SELECT tag in not included in this snippet.
3275 $retval = '';
3276 foreach ($cfg['ColumnTypes'] as $key => $value) {
3277 if (is_array($value)) {
3278 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3279 foreach ($value as $subvalue) {
3280 if ($subvalue == $selected) {
3281 $retval .= "<option selected='selected'>";
3282 $retval .= $subvalue;
3283 $retval .= "</option>";
3284 } else if ($subvalue === '-') {
3285 $retval .= "<option disabled='disabled'>";
3286 $retval .= $subvalue;
3287 $retval .= "</option>";
3288 } else {
3289 $retval .= "<option>$subvalue</option>";
3292 $retval .= '</optgroup>';
3293 } else {
3294 if ($selected == $value) {
3295 $retval .= "<option selected='selected'>$value</option>";
3296 } else {
3297 $retval .= "<option>$value</option>";
3301 } else {
3302 $retval = array();
3303 foreach ($cfg['ColumnTypes'] as $value) {
3304 if (is_array($value)) {
3305 foreach ($value as $subvalue) {
3306 if ($subvalue !== '-') {
3307 $retval[] = $subvalue;
3310 } else {
3311 if ($value !== '-') {
3312 $retval[] = $value;
3318 return $retval;
3319 } // end PMA_getSupportedDatatypes()
3322 * Returns a list of datatypes that are not (yet) handled by PMA.
3323 * Used by: tbl_change.php and libraries/db_routines.inc.php
3325 * @return array list of datatypes
3327 function PMA_unsupportedDatatypes()
3329 $no_support_types = array();
3330 return $no_support_types;
3334 * Return GIS data types
3336 * @param bool $upper_case whether to return values in upper case
3338 * @return array GIS data types
3340 function PMA_getGISDatatypes($upper_case = false)
3342 $gis_data_types = array(
3343 'geometry',
3344 'point',
3345 'linestring',
3346 'polygon',
3347 'multipoint',
3348 'multilinestring',
3349 'multipolygon',
3350 'geometrycollection'
3352 if ($upper_case) {
3353 for ($i = 0; $i < count($gis_data_types); $i++) {
3354 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3358 return $gis_data_types;
3362 * Generates GIS data based on the string passed.
3364 * @param string $gis_string GIS string
3366 * @return GIS data enclosed in 'GeomFromText' function
3368 function PMA_createGISData($gis_string)
3370 $gis_string = trim($gis_string);
3371 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3372 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3373 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3374 return 'GeomFromText(' . $gis_string . ')';
3375 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3376 return "GeomFromText('" . $gis_string . "')";
3377 } else {
3378 return $gis_string;
3383 * Returns the names and details of the functions
3384 * that can be applied on geometry data typess.
3386 * @param string $geom_type if provided the output is limited to the functions
3387 * that are applicable to the provided geometry type.
3388 * @param bool $binary if set to false functions that take two geometries
3389 * as arguments will not be included.
3390 * @param bool $display if set to true seperators will be added to the
3391 * output array.
3393 * @return array names and details of the functions that can be applied on
3394 * geometry data typess.
3396 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3398 $funcs = array();
3399 if ($display) {
3400 $funcs[] = array('display' => ' ');
3403 // Unary functions common to all geomety types
3404 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3405 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3406 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3407 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3408 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3409 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3411 $geom_type = trim(strtolower($geom_type));
3412 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3413 $funcs[] = array('display' => '--------');
3416 // Unary functions that are specific to each geomety type
3417 if ($geom_type == 'point') {
3418 $funcs['X'] = array('params' => 1, 'type' => 'float');
3419 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3421 } elseif ($geom_type == 'multipoint') {
3422 // no fucntions here
3423 } elseif ($geom_type == 'linestring') {
3424 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3425 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3426 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3427 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3428 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3430 } elseif ($geom_type == 'multilinestring') {
3431 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3432 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3434 } elseif ($geom_type == 'polygon') {
3435 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3436 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3437 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3439 } elseif ($geom_type == 'multipolygon') {
3440 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3441 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3442 // Not yet implemented in MySQL
3443 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3445 } elseif ($geom_type == 'geometrycollection') {
3446 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3449 // If we are asked for binary functions as well
3450 if ($binary) {
3451 // section seperator
3452 if ($display) {
3453 $funcs[] = array('display' => '--------');
3455 if (PMA_MYSQL_INT_VERSION < 50601) {
3456 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3457 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3458 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3459 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3460 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3461 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3462 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3463 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3464 } else {
3465 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3466 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3467 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3468 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3469 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3470 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3471 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3472 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3473 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3477 if ($display) {
3478 $funcs[] = array('display' => '--------');
3480 // Minimum bounding rectangle functions
3481 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3482 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3483 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3484 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3485 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3486 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3487 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3489 return $funcs;
3493 * Creates a dropdown box with MySQL functions for a particular column.
3495 * @param array $field Data about the column for which
3496 * to generate the dropdown
3497 * @param bool $insert_mode Whether the operation is 'insert'
3499 * @global array $cfg PMA configuration
3500 * @global array $analyzed_sql Analyzed SQL query
3501 * @global mixed $data (null/string) FIXME: what is this for?
3503 * @return string An HTML snippet of a dropdown list with function
3504 * names appropriate for the requested column.
3506 function PMA_getFunctionsForField($field, $insert_mode)
3508 global $cfg, $analyzed_sql, $data;
3510 $selected = '';
3511 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3512 // or something similar. Then directly look up the entry in the
3513 // RestrictFunctions array, which'll then reveal the available dropdown options
3514 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3515 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3517 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3518 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3519 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3520 } else {
3521 $dropdown = array();
3522 $default_function = '';
3524 $dropdown_built = array();
3525 $op_spacing_needed = false;
3526 // what function defined as default?
3527 // for the first timestamp we don't set the default function
3528 // if there is a default value for the timestamp
3529 // (not including CURRENT_TIMESTAMP)
3530 // and the column does not have the
3531 // ON UPDATE DEFAULT TIMESTAMP attribute.
3532 if ($field['True_Type'] == 'timestamp'
3533 && empty($field['Default'])
3534 && empty($data)
3535 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3537 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3539 // For primary keys of type char(36) or varchar(36) UUID if the default function
3540 // Only applies to insert mode, as it would silently trash data on updates.
3541 if ($insert_mode
3542 && $field['Key'] == 'PRI'
3543 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3545 $default_function = $cfg['DefaultFunctions']['pk_char36'];
3547 // this is set only when appropriate and is always true
3548 if (isset($field['display_binary_as_hex'])) {
3549 $default_function = 'UNHEX';
3552 // Create the output
3553 $retval = ' <option></option>' . "\n";
3554 // loop on the dropdown array and print all available options for that field.
3555 foreach ($dropdown as $each_dropdown) {
3556 $retval .= ' ';
3557 $retval .= '<option';
3558 if ($default_function === $each_dropdown) {
3559 $retval .= ' selected="selected"';
3561 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3562 $dropdown_built[$each_dropdown] = 'true';
3563 $op_spacing_needed = true;
3565 // For compatibility's sake, do not let out all other functions. Instead
3566 // print a separator (blank) and then show ALL functions which weren't shown
3567 // yet.
3568 $cnt_functions = count($cfg['Functions']);
3569 for ($j = 0; $j < $cnt_functions; $j++) {
3570 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3571 || $dropdown_built[$cfg['Functions'][$j]] != 'true'
3573 // Is current function defined as default?
3574 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3575 || (! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3576 ? ' selected="selected"'
3577 : '';
3578 if ($op_spacing_needed == true) {
3579 $retval .= ' ';
3580 $retval .= '<option value="">--------</option>' . "\n";
3581 $op_spacing_needed = false;
3584 $retval .= ' ';
3585 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3586 . '</option>' . "\n";
3588 } // end for
3590 return $retval;
3591 } // end PMA_getFunctionsForField()
3594 * Checks if the current user has a specific privilege and returns true if the
3595 * user indeed has that privilege or false if (s)he doesn't. This function must
3596 * only be used for features that are available since MySQL 5, because it
3597 * relies on the INFORMATION_SCHEMA database to be present.
3599 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3600 * // Checks if the currently logged in user has the global
3601 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3602 * // user has this privilege on database 'mydb'.
3604 * @param string $priv The privilege to check
3605 * @param mixed $db null, to only check global privileges
3606 * string, db name where to also check for privileges
3607 * @param mixed $tbl null, to only check global privileges
3608 * string, db name where to also check for privileges
3610 * @return bool
3612 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3614 // Get the username for the current user in the format
3615 // required to use in the information schema database.
3616 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3617 if ($user === false) {
3618 return false;
3620 $user = explode('@', $user);
3621 $username = "''";
3622 $username .= str_replace("'", "''", $user[0]);
3623 $username .= "''@''";
3624 $username .= str_replace("'", "''", $user[1]);
3625 $username .= "''";
3626 // Prepage the query
3627 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3628 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3629 // Check global privileges first.
3630 if (PMA_DBI_fetch_value(
3631 sprintf(
3632 $query,
3633 'USER_PRIVILEGES',
3634 $username,
3635 $priv
3639 return true;
3641 // If a database name was provided and user does not have the
3642 // required global privilege, try database-wise permissions.
3643 if ($db !== null) {
3644 $query .= " AND TABLE_SCHEMA='%s'";
3645 if (PMA_DBI_fetch_value(
3646 sprintf(
3647 $query,
3648 'SCHEMA_PRIVILEGES',
3649 $username,
3650 $priv,
3651 PMA_sqlAddSlashes($db)
3655 return true;
3657 } else {
3658 // There was no database name provided and the user
3659 // does not have the correct global privilege.
3660 return false;
3662 // If a table name was also provided and we still didn't
3663 // find any valid privileges, try table-wise privileges.
3664 if ($tbl !== null) {
3665 $query .= " AND TABLE_NAME='%s'";
3666 if ($retval = PMA_DBI_fetch_value(
3667 sprintf(
3668 $query,
3669 'TABLE_PRIVILEGES',
3670 $username,
3671 $priv,
3672 PMA_sqlAddSlashes($db),
3673 PMA_sqlAddSlashes($tbl)
3677 return true;
3680 // If we reached this point, the user does not
3681 // have even valid table-wise privileges.
3682 return false;