Advisor: mark that 'Rate of reading fixed position' may be wrong, requires further...
[phpmyadmin/thilanka.git] / libraries / common.lib.php
blobf232b985cb91584bac6307c9c3d0e4ccdcef1a46
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 with a CSS Sprite
81 * @return html img tag
83 function PMA_getIcon($icon, $alternate = '', $force_text = false, $noSprite = false)
85 // $cfg['PropertiesIconic'] is true or both
86 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
87 // $cfg['PropertiesIconic'] is false or both
88 // OR we have no $include_icon
89 $include_text = ($force_text || true !== $GLOBALS['cfg']['PropertiesIconic']);
90 $alternate = htmlspecialchars($alternate);
91 $button = '';
93 // Always use a span (we rely on this in js/sql.js)
94 $button .= '<span class="nowrap">';
96 if ($include_icon) {
97 if ($noSprite) {
98 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
99 . ' class="icon" width="16" height="16" />';
100 } else {
101 $button .= '<img src="themes/dot.gif"'
102 . ' title="' . $alternate . '" alt="' . $alternate . '"'
103 . ' class="icon ic_' . str_replace(array('.gif','.png'), '', $icon) . '" />';
107 if ($include_icon && $include_text) {
108 $button .= ' ';
111 if ($include_text) {
112 $button .= $alternate;
115 $button .= '</span>';
117 return $button;
121 * Displays the maximum size for an upload
123 * @param integer $max_upload_size the size
125 * @return string the message
127 * @access public
129 function PMA_displayMaximumUploadSize($max_upload_size)
131 // I have to reduce the second parameter (sensitiveness) from 6 to 4
132 // to avoid weird results like 512 kKib
133 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
134 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
138 * Generates a hidden field which should indicate to the browser
139 * the maximum size for upload
141 * @param integer $max_size the size
143 * @return string the INPUT field
145 * @access public
147 function PMA_generateHiddenMaxFileSize($max_size)
149 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
153 * Add slashes before "'" and "\" characters so a value containing them can
154 * be used in a sql comparison.
156 * @param string $a_string the string to slash
157 * @param bool $is_like whether the string will be used in a 'LIKE' clause
158 * (it then requires two more escaped sequences) or not
159 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
160 * (converts \n to \\n, \r to \\r)
161 * @param bool $php_code whether this function is used as part of the
162 * "Create PHP code" dialog
164 * @return string the slashed string
166 * @access public
168 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
170 if ($is_like) {
171 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
172 } else {
173 $a_string = str_replace('\\', '\\\\', $a_string);
176 if ($crlf) {
177 $a_string = strtr(
178 $a_string,
179 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
183 if ($php_code) {
184 $a_string = str_replace('\'', '\\\'', $a_string);
185 } else {
186 $a_string = str_replace('\'', '\'\'', $a_string);
189 return $a_string;
190 } // end of the 'PMA_sqlAddSlashes()' function
194 * Add slashes before "_" and "%" characters for using them in MySQL
195 * database, table and field names.
196 * Note: This function does not escape backslashes!
198 * @param string $name the string to escape
200 * @return string the escaped string
202 * @access public
204 function PMA_escape_mysql_wildcards($name)
206 return strtr($name, array('_' => '\\_', '%' => '\\%'));
207 } // end of the 'PMA_escape_mysql_wildcards()' function
210 * removes slashes before "_" and "%" characters
211 * Note: This function does not unescape backslashes!
213 * @param string $name the string to escape
215 * @return string the escaped string
217 * @access public
219 function PMA_unescape_mysql_wildcards($name)
221 return strtr($name, array('\\_' => '_', '\\%' => '%'));
222 } // end of the 'PMA_unescape_mysql_wildcards()' function
225 * removes quotes (',",`) from a quoted string
227 * checks if the sting is quoted and removes this quotes
229 * @param string $quoted_string string to remove quotes from
230 * @param string $quote type of quote to remove
232 * @return string unqoted string
234 function PMA_unQuote($quoted_string, $quote = null)
236 $quotes = array();
238 if (null === $quote) {
239 $quotes[] = '`';
240 $quotes[] = '"';
241 $quotes[] = "'";
242 } else {
243 $quotes[] = $quote;
246 foreach ($quotes as $quote) {
247 if (substr($quoted_string, 0, 1) === $quote
248 && substr($quoted_string, -1, 1) === $quote) {
249 $unquoted_string = substr($quoted_string, 1, -1);
250 // replace escaped quotes
251 $unquoted_string = str_replace(
252 $quote . $quote,
253 $quote,
254 $unquoted_string);
255 return $unquoted_string;
259 return $quoted_string;
263 * format sql strings
265 * @todo move into PMA_Sql
266 * @param mixed $parsed_sql pre-parsed SQL structure
267 * @param string $unparsed_sql raw SQL string
269 * @return string the formatted sql
271 * @global array the configuration array
272 * @global boolean whether the current statement is a multiple one or not
274 * @access public
277 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
279 global $cfg;
281 // Check that we actually have a valid set of parsed data
282 // well, not quite
283 // first check for the SQL parser having hit an error
284 if (PMA_SQP_isError()) {
285 return htmlspecialchars($parsed_sql['raw']);
287 // then check for an array
288 if (! is_array($parsed_sql)) {
289 // We don't so just return the input directly
290 // This is intended to be used for when the SQL Parser is turned off
291 $formatted_sql = "<pre>\n";
292 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
293 $formatted_sql .= $unparsed_sql;
294 } else {
295 $formatted_sql .= $parsed_sql;
297 $formatted_sql .= "\n</pre>";
298 return $formatted_sql;
301 $formatted_sql = '';
303 switch ($cfg['SQP']['fmtType']) {
304 case 'none':
305 if ($unparsed_sql != '') {
306 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
307 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
308 . '</pre></span>';
309 } else {
310 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
312 break;
313 case 'html':
314 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
315 break;
316 case 'text':
317 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
318 break;
319 default:
320 break;
321 } // end switch
323 return $formatted_sql;
324 } // end of the "PMA_formatSql()" function
328 * Displays a link to the official MySQL documentation
330 * @param string $chapter chapter of "HTML, one page per chapter" documentation
331 * @param string $link contains name of page/anchor that is being linked
332 * @param bool $big_icon whether to use big icon (like in left frame)
333 * @param string $anchor anchor to page part
334 * @param bool $just_open whether only the opening <a> tag should be returned
336 * @return string the html link
338 * @access public
340 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
342 global $cfg;
344 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
345 return '';
348 // Fixup for newly used names:
349 $chapter = str_replace('_', '-', strtolower($chapter));
350 $link = str_replace('_', '-', strtolower($link));
352 switch ($cfg['MySQLManualType']) {
353 case 'chapters':
354 if (empty($chapter)) {
355 $chapter = 'index';
357 if (empty($anchor)) {
358 $anchor = $link;
360 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
361 break;
362 case 'big':
363 if (empty($anchor)) {
364 $anchor = $link;
366 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
367 break;
368 case 'searchable':
369 if (empty($link)) {
370 $link = 'index';
372 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
373 if (!empty($anchor)) {
374 $url .= '#' . $anchor;
376 break;
377 case 'viewable':
378 default:
379 if (empty($link)) {
380 $link = 'index';
382 $mysql = '5.0';
383 $lang = 'en';
384 if (defined('PMA_MYSQL_INT_VERSION')) {
385 if (PMA_MYSQL_INT_VERSION >= 50500) {
386 $mysql = '5.5';
387 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
388 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
389 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
390 $mysql = '5.1';
391 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
392 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
393 } else {
394 $mysql = '5.0';
395 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
396 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
399 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
400 if (!empty($anchor)) {
401 $url .= '#' . $anchor;
403 break;
406 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
407 if ($just_open) {
408 return $open_link;
409 } elseif ($big_icon) {
410 return $open_link . '<img class="icon ic_b_sqlhelp" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
411 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
412 return $open_link . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
413 } else {
414 return '[' . $open_link . __('Documentation') . '</a>]';
416 } // end of the 'PMA_showMySQLDocu()' function
420 * Displays a link to the phpMyAdmin documentation
422 * @param string $anchor anchor in documentation
424 * @return string the html link
426 * @access public
428 function PMA_showDocu($anchor)
430 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
431 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
432 } else {
433 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
435 } // end of the 'PMA_showDocu()' function
438 * Displays a link to the PHP documentation
440 * @param string $target anchor in documentation
442 * @return string the html link
444 * @access public
446 function PMA_showPHPDocu($target)
448 $url = PMA_getPHPDocLink($target);
450 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
451 return '<a href="' . $url . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
452 } else {
453 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
455 } // end of the 'PMA_showPHPDocu()' function
458 * returns HTML for a footnote marker and add the messsage to the footnotes
460 * @param string $message the error message
461 * @param bool $bbcode
462 * @param string $type
464 * @return string html code for a footnote marker
466 * @access public
468 function PMA_showHint($message, $bbcode = false, $type = 'notice')
470 if ($message instanceof PMA_Message) {
471 $key = $message->getHash();
472 $type = $message->getLevel();
473 } else {
474 $key = md5($message);
477 if (! isset($GLOBALS['footnotes'][$key])) {
478 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
479 $GLOBALS['footnotes'] = array();
481 $nr = count($GLOBALS['footnotes']) + 1;
482 $GLOBALS['footnotes'][$key] = array(
483 'note' => $message,
484 'type' => $type,
485 'nr' => $nr,
487 } else {
488 $nr = $GLOBALS['footnotes'][$key]['nr'];
491 if ($bbcode) {
492 return '[sup]' . $nr . '[/sup]';
495 // footnotemarker used in js/tooltip.js
496 return '<sup class="footnotemarker">' . $nr . '</sup>' .
497 '<img class="footnotemarker footnote_' . $nr . ' ic_b_help" src="themes/dot.gif" alt="" />';
501 * Displays a MySQL error message in the right frame.
503 * @param string $error_message the error message
504 * @param string $the_query the sql query that failed
505 * @param bool $is_modify_link whether to show a "modify" link or not
506 * @param string $back_url the "back" link url (full path is not required)
507 * @param bool $exit EXIT the page?
509 * @global string the curent table
510 * @global string the current db
512 * @access public
514 function PMA_mysqlDie($error_message = '', $the_query = '',
515 $is_modify_link = true, $back_url = '', $exit = true)
517 global $table, $db;
520 * start http output, display html headers
522 require_once './libraries/header.inc.php';
524 $error_msg_output = '';
526 if (!$error_message) {
527 $error_message = PMA_DBI_getError();
529 if (!$the_query && !empty($GLOBALS['sql_query'])) {
530 $the_query = $GLOBALS['sql_query'];
533 // --- Added to solve bug #641765
534 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
535 $formatted_sql = htmlspecialchars($the_query);
536 } elseif (empty($the_query) || trim($the_query) == '') {
537 $formatted_sql = '';
538 } else {
539 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
540 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
541 } else {
542 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
545 // ---
546 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
547 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
548 // if the config password is wrong, or the MySQL server does not
549 // respond, do not show the query that would reveal the
550 // username/password
551 if (!empty($the_query) && !strstr($the_query, 'connect')) {
552 // --- Added to solve bug #641765
553 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
554 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
555 $error_msg_output .= '<br />' . "\n";
557 // ---
558 // modified to show the help on sql errors
559 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
560 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
561 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
563 if ($is_modify_link) {
564 $_url_params = array(
565 'sql_query' => $the_query,
566 'show_query' => 1,
568 if (strlen($table)) {
569 $_url_params['db'] = $db;
570 $_url_params['table'] = $table;
571 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
572 } elseif (strlen($db)) {
573 $_url_params['db'] = $db;
574 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
575 } else {
576 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
579 $error_msg_output .= $doedit_goto
580 . PMA_getIcon('b_edit.png', __('Edit'))
581 . '</a>';
582 } // end if
583 $error_msg_output .= ' </p>' . "\n"
584 .' <p>' . "\n"
585 .' ' . $formatted_sql . "\n"
586 .' </p>' . "\n";
587 } // end if
589 if (!empty($error_message)) {
590 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
592 // modified to show the help on error-returns
593 // (now error-messages-server)
594 $error_msg_output .= '<p>' . "\n"
595 . ' <strong>' . __('MySQL said: ') . '</strong>'
596 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
597 . "\n"
598 . '</p>' . "\n";
600 // The error message will be displayed within a CODE segment.
601 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
603 // Replace all non-single blanks with their HTML-counterpart
604 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
605 // Replace TAB-characters with their HTML-counterpart
606 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
607 // Replace linebreaks
608 $error_message = nl2br($error_message);
610 $error_msg_output .= '<code>' . "\n"
611 . $error_message . "\n"
612 . '</code><br />' . "\n";
613 $error_msg_output .= '</div>';
615 $_SESSION['Import_message']['message'] = $error_msg_output;
617 if ($exit) {
619 * If in an Ajax request
620 * - avoid displaying a Back link
621 * - use PMA_ajaxResponse() to transmit the message and exit
623 if ($GLOBALS['is_ajax_request'] == true) {
624 PMA_ajaxResponse($error_msg_output, false);
626 if (! empty($back_url)) {
627 if (strstr($back_url, '?')) {
628 $back_url .= '&amp;no_history=true';
629 } else {
630 $back_url .= '?no_history=true';
633 $_SESSION['Import_message']['go_back_url'] = $back_url;
635 $error_msg_output .= '<fieldset class="tblFooters">';
636 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
637 $error_msg_output .= '</fieldset>' . "\n\n";
640 echo $error_msg_output;
642 * display footer and exit
644 require './libraries/footer.inc.php';
645 } else {
646 echo $error_msg_output;
648 } // end of the 'PMA_mysqlDie()' function
651 * returns array with tables of given db with extended information and grouped
653 * @param string $db name of db
654 * @param string $tables name of tables
655 * @param integer $limit_offset list offset
656 * @param int|bool $limit_count max tables to return
658 * @return array (recursive) grouped table list
660 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
662 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
664 if (null === $tables) {
665 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
666 if ($GLOBALS['cfg']['NaturalOrder']) {
667 uksort($tables, 'strnatcasecmp');
671 if (count($tables) < 1) {
672 return $tables;
675 $default = array(
676 'Name' => '',
677 'Rows' => 0,
678 'Comment' => '',
679 'disp_name' => '',
682 $table_groups = array();
684 // for blobstreaming - list of blobstreaming tables
686 // load PMA configuration
687 $PMA_Config = $GLOBALS['PMA_Config'];
689 foreach ($tables as $table_name => $table) {
690 // if BS tables exist
691 if (PMA_BS_IsHiddenTable($table_name)) {
692 continue;
695 // check for correct row count
696 if (null === $table['Rows']) {
697 // Do not check exact row count here,
698 // if row count is invalid possibly the table is defect
699 // and this would break left frame;
700 // but we can check row count if this is a view or the
701 // information_schema database
702 // since PMA_Table::countRecords() returns a limited row count
703 // in this case.
705 // set this because PMA_Table::countRecords() can use it
706 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
708 if ($tbl_is_view || 'information_schema' == $db) {
709 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
713 // in $group we save the reference to the place in $table_groups
714 // where to store the table info
715 if ($GLOBALS['cfg']['LeftFrameDBTree']
716 && $sep && strstr($table_name, $sep)
718 $parts = explode($sep, $table_name);
720 $group =& $table_groups;
721 $i = 0;
722 $group_name_full = '';
723 $parts_cnt = count($parts) - 1;
724 while ($i < $parts_cnt
725 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
726 $group_name = $parts[$i] . $sep;
727 $group_name_full .= $group_name;
729 if (! isset($group[$group_name])) {
730 $group[$group_name] = array();
731 $group[$group_name]['is' . $sep . 'group'] = true;
732 $group[$group_name]['tab' . $sep . 'count'] = 1;
733 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
734 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
735 $table = $group[$group_name];
736 $group[$group_name] = array();
737 $group[$group_name][$group_name] = $table;
738 unset($table);
739 $group[$group_name]['is' . $sep . 'group'] = true;
740 $group[$group_name]['tab' . $sep . 'count'] = 1;
741 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
742 } else {
743 $group[$group_name]['tab' . $sep . 'count']++;
745 $group =& $group[$group_name];
746 $i++;
748 } else {
749 if (! isset($table_groups[$table_name])) {
750 $table_groups[$table_name] = array();
752 $group =& $table_groups;
756 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
757 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
759 // switch tooltip and name
760 $table['Comment'] = $table['Name'];
761 $table['disp_name'] = $table['Comment'];
762 } else {
763 $table['disp_name'] = $table['Name'];
766 $group[$table_name] = array_merge($default, $table);
769 return $table_groups;
772 /* ----------------------- Set of misc functions ----------------------- */
776 * Adds backquotes on both sides of a database, table or field name.
777 * and escapes backquotes inside the name with another backquote
779 * example:
780 * <code>
781 * echo PMA_backquote('owner`s db'); // `owner``s db`
783 * </code>
785 * @param mixed $a_name the database, table or field name to "backquote"
786 * or array of it
787 * @param boolean $do_it a flag to bypass this function (used by dump
788 * functions)
790 * @return mixed the "backquoted" database, table or field name
792 * @access public
794 function PMA_backquote($a_name, $do_it = true)
796 if (is_array($a_name)) {
797 foreach ($a_name as &$data) {
798 $data = PMA_backquote($data, $do_it);
800 return $a_name;
803 if (! $do_it) {
804 global $PMA_SQPdata_forbidden_word;
806 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
807 return $a_name;
811 // '0' is also empty for php :-(
812 if (strlen($a_name) && $a_name !== '*') {
813 return '`' . str_replace('`', '``', $a_name) . '`';
814 } else {
815 return $a_name;
817 } // end of the 'PMA_backquote()' function
820 * Defines the <CR><LF> value depending on the user OS.
822 * @return string the <CR><LF> value to use
824 * @access public
826 function PMA_whichCrlf()
828 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
829 // Win case
830 if (PMA_USR_OS == 'Win') {
831 $the_crlf = "\r\n";
833 // Others
834 else {
835 $the_crlf = "\n";
838 return $the_crlf;
839 } // end of the 'PMA_whichCrlf()' function
842 * Reloads navigation if needed.
844 * @param bool $jsonly prints out pure JavaScript
846 * @access public
848 function PMA_reloadNavigation($jsonly=false)
850 // Reloads the navigation frame via JavaScript if required
851 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
852 // one of the reasons for a reload is when a table is dropped
853 // in this case, get rid of the table limit offset, otherwise
854 // we have a problem when dropping a table on the last page
855 // and the offset becomes greater than the total number of tables
856 unset($_SESSION['tmp_user_values']['table_limit_offset']);
857 echo "\n";
858 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
859 if (!$jsonly) {
860 echo '<script type="text/javascript">' . PHP_EOL;
863 //<![CDATA[
864 if (typeof(window.parent) != 'undefined'
865 && typeof(window.parent.frame_navigation) != 'undefined'
866 && window.parent.goTo) {
867 window.parent.goTo('<?php echo $reload_url; ?>');
869 //]]>
870 <?php
871 if (!$jsonly) {
872 echo '</script>' . PHP_EOL;
875 unset($GLOBALS['reload']);
880 * displays the message and the query
881 * usually the message is the result of the query executed
883 * @param string $message the message to display
884 * @param string $sql_query the query to display
885 * @param string $type the type (level) of the message
886 * @param boolean $is_view is this a message after a VIEW operation?
888 * @return string
890 * @access public
892 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
895 * PMA_ajaxResponse uses this function to collect the string of HTML generated
896 * for showing the message. Use output buffering to collect it and return it
897 * in a string. In some special cases on sql.php, buffering has to be disabled
898 * and hence we check with $GLOBALS['buffer_message']
900 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
901 ob_start();
903 global $cfg;
905 if (null === $sql_query) {
906 if (! empty($GLOBALS['display_query'])) {
907 $sql_query = $GLOBALS['display_query'];
908 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
909 $sql_query = $GLOBALS['unparsed_sql'];
910 } elseif (! empty($GLOBALS['sql_query'])) {
911 $sql_query = $GLOBALS['sql_query'];
912 } else {
913 $sql_query = '';
917 if (isset($GLOBALS['using_bookmark_message'])) {
918 $GLOBALS['using_bookmark_message']->display();
919 unset($GLOBALS['using_bookmark_message']);
922 // Corrects the tooltip text via JS if required
923 // @todo this is REALLY the wrong place to do this - very unexpected here
924 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
925 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
926 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
927 echo "\n";
928 echo '<script type="text/javascript">' . "\n";
929 echo '//<![CDATA[' . "\n";
930 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
931 echo '//]]>' . "\n";
932 echo '</script>' . "\n";
933 } // end if ... elseif
935 // Checks if the table needs to be repaired after a TRUNCATE query.
936 // @todo what about $GLOBALS['display_query']???
937 // @todo this is REALLY the wrong place to do this - very unexpected here
938 if (strlen($GLOBALS['table'])
939 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
941 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
942 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
945 unset($tbl_status);
947 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
948 // check for it's presence before using it
949 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
951 if ($message instanceof PMA_Message) {
952 if (isset($GLOBALS['special_message'])) {
953 $message->addMessage($GLOBALS['special_message']);
954 unset($GLOBALS['special_message']);
956 $message->display();
957 $type = $message->getLevel();
958 } else {
959 echo '<div class="' . $type . '">';
960 echo PMA_sanitize($message);
961 if (isset($GLOBALS['special_message'])) {
962 echo PMA_sanitize($GLOBALS['special_message']);
963 unset($GLOBALS['special_message']);
965 echo '</div>';
968 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
969 // Html format the query to be displayed
970 // If we want to show some sql code it is easiest to create it here
971 /* SQL-Parser-Analyzer */
973 if (! empty($GLOBALS['show_as_php'])) {
974 $new_line = '\\n"<br />' . "\n"
975 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
976 $query_base = htmlspecialchars(addslashes($sql_query));
977 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
978 } else {
979 $query_base = $sql_query;
982 $query_too_big = false;
984 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
985 // when the query is large (for example an INSERT of binary
986 // data), the parser chokes; so avoid parsing the query
987 $query_too_big = true;
988 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
989 } elseif (! empty($GLOBALS['parsed_sql'])
990 && $query_base == $GLOBALS['parsed_sql']['raw']) {
991 // (here, use "! empty" because when deleting a bookmark,
992 // $GLOBALS['parsed_sql'] is set but empty
993 $parsed_sql = $GLOBALS['parsed_sql'];
994 } else {
995 // Parse SQL if needed
996 $parsed_sql = PMA_SQP_parse($query_base);
997 if (PMA_SQP_isError()) {
998 unset($parsed_sql);
1002 // Analyze it
1003 if (isset($parsed_sql)) {
1004 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1006 // Same as below (append LIMIT), append the remembered ORDER BY
1007 if ($GLOBALS['cfg']['RememberSorting']
1008 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1009 && isset($GLOBALS['sql_order_to_append'])) {
1010 $query_base = $analyzed_display_query[0]['section_before_limit']
1011 . "\n" . $GLOBALS['sql_order_to_append']
1012 . $analyzed_display_query[0]['section_after_limit'];
1014 // Need to reparse query
1015 $parsed_sql = PMA_SQP_parse($query_base);
1016 // update the $analyzed_display_query
1017 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1018 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1021 // Here we append the LIMIT added for navigation, to
1022 // enable its display. Adding it higher in the code
1023 // to $sql_query would create a problem when
1024 // using the Refresh or Edit links.
1026 // Only append it on SELECTs.
1029 * @todo what would be the best to do when someone hits Refresh:
1030 * use the current LIMITs ?
1033 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1034 && isset($GLOBALS['sql_limit_to_append'])
1036 $query_base = $analyzed_display_query[0]['section_before_limit']
1037 . "\n" . $GLOBALS['sql_limit_to_append']
1038 . $analyzed_display_query[0]['section_after_limit'];
1039 // Need to reparse query
1040 $parsed_sql = PMA_SQP_parse($query_base);
1044 if (! empty($GLOBALS['show_as_php'])) {
1045 $query_base = '$sql = "' . $query_base;
1046 } elseif (! empty($GLOBALS['validatequery'])) {
1047 try {
1048 $query_base = PMA_validateSQL($query_base);
1049 } catch (Exception $e) {
1050 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1052 } elseif (isset($parsed_sql)) {
1053 $query_base = PMA_formatSql($parsed_sql, $query_base);
1056 // Prepares links that may be displayed to edit/explain the query
1057 // (don't go to default pages, we must go to the page
1058 // where the query box is available)
1060 // Basic url query part
1061 $url_params = array();
1062 if (! isset($GLOBALS['db'])) {
1063 $GLOBALS['db'] = '';
1065 if (strlen($GLOBALS['db'])) {
1066 $url_params['db'] = $GLOBALS['db'];
1067 if (strlen($GLOBALS['table'])) {
1068 $url_params['table'] = $GLOBALS['table'];
1069 $edit_link = 'tbl_sql.php';
1070 } else {
1071 $edit_link = 'db_sql.php';
1073 } else {
1074 $edit_link = 'server_sql.php';
1077 // Want to have the query explained
1078 // but only explain a SELECT (that has not been explained)
1079 /* SQL-Parser-Analyzer */
1080 $explain_link = '';
1081 $is_select = false;
1082 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1083 $explain_params = $url_params;
1084 // Detect if we are validating as well
1085 // To preserve the validate uRL data
1086 if (! empty($GLOBALS['validatequery'])) {
1087 $explain_params['validatequery'] = 1;
1089 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1090 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1091 $_message = __('Explain SQL');
1092 $is_select = true;
1093 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1094 $explain_params['sql_query'] = substr($sql_query, 8);
1095 $_message = __('Skip Explain SQL');
1097 if (isset($explain_params['sql_query'])) {
1098 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1099 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1101 } //show explain
1103 $url_params['sql_query'] = $sql_query;
1104 $url_params['show_query'] = 1;
1106 // even if the query is big and was truncated, offer the chance
1107 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1108 if (! empty($cfg['SQLQuery']['Edit'])) {
1109 if ($cfg['EditInWindow'] == true) {
1110 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1111 } else {
1112 $onclick = '';
1115 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1116 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1117 } else {
1118 $edit_link = '';
1121 $url_qpart = PMA_generate_common_url($url_params);
1123 // Also we would like to get the SQL formed in some nice
1124 // php-code
1125 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1126 $php_params = $url_params;
1128 if (! empty($GLOBALS['show_as_php'])) {
1129 $_message = __('Without PHP Code');
1130 } else {
1131 $php_params['show_as_php'] = 1;
1132 $_message = __('Create PHP Code');
1135 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1136 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1138 if (isset($GLOBALS['show_as_php'])) {
1139 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1140 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1142 } else {
1143 $php_link = '';
1144 } //show as php
1146 // Refresh query
1147 if (! empty($cfg['SQLQuery']['Refresh'])
1148 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1150 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1151 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1152 } else {
1153 $refresh_link = '';
1154 } //show as php
1156 if (! empty($cfg['SQLValidator']['use'])
1157 && ! empty($cfg['SQLQuery']['Validate'])
1159 $validate_params = $url_params;
1160 if (!empty($GLOBALS['validatequery'])) {
1161 $validate_message = __('Skip Validate SQL') ;
1162 } else {
1163 $validate_params['validatequery'] = 1;
1164 $validate_message = __('Validate SQL') ;
1167 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1168 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1169 } else {
1170 $validate_link = '';
1171 } //validator
1173 if (!empty($GLOBALS['validatequery'])) {
1174 echo '<div class="sqlvalidate">';
1175 } else {
1176 echo '<code class="sql">';
1178 if ($query_too_big) {
1179 echo $shortened_query_base;
1180 } else {
1181 echo $query_base;
1184 //Clean up the end of the PHP
1185 if (! empty($GLOBALS['show_as_php'])) {
1186 echo '";';
1188 if (!empty($GLOBALS['validatequery'])) {
1189 echo '</div>';
1190 } else {
1191 echo '</code>';
1194 echo '<div class="tools">';
1195 // avoid displaying a Profiling checkbox that could
1196 // be checked, which would reexecute an INSERT, for example
1197 if (! empty($refresh_link)) {
1198 PMA_profilingCheckbox($sql_query);
1200 // if needed, generate an invisible form that contains controls for the
1201 // Inline link; this way, the behavior of the Inline link does not
1202 // depend on the profiling support or on the refresh link
1203 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1204 echo '<form action="sql.php" method="post">';
1205 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1206 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1207 echo '</form>';
1210 // in the tools div, only display the Inline link when not in ajax
1211 // mode because 1) it currently does not work and 2) we would
1212 // have two similar mechanisms on the page for the same goal
1213 if ($is_select || $GLOBALS['is_ajax_request'] === false && ! $query_too_big) {
1214 // see in js/functions.js the jQuery code attached to id inline_edit
1215 // document.write conflicts with jQuery, hence used $().append()
1216 echo "<script type=\"text/javascript\">\n" .
1217 "//<![CDATA[\n" .
1218 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1219 PMA_escapeJsString(__('Inline edit of this query')) .
1220 "\" class=\"inline_edit_sql\">" .
1221 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1222 "</a>]');\n" .
1223 "//]]>\n" .
1224 "</script>";
1226 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1227 echo '</div>';
1229 echo '</div>';
1230 if ($GLOBALS['is_ajax_request'] === false) {
1231 echo '<br class="clearfloat" />';
1234 // If we are in an Ajax request, we have most probably been called in
1235 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1236 // to PMA_ajaxResponse(), which will encode it for JSON.
1237 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1238 $buffer_contents = ob_get_contents();
1239 ob_end_clean();
1240 return $buffer_contents;
1242 return null;
1243 } // end of the 'PMA_showMessage()' function
1246 * Verifies if current MySQL server supports profiling
1248 * @access public
1250 * @return boolean whether profiling is supported
1252 function PMA_profilingSupported()
1254 if (! PMA_cacheExists('profiling_supported', true)) {
1255 // 5.0.37 has profiling but for example, 5.1.20 does not
1256 // (avoid a trip to the server for MySQL before 5.0.37)
1257 // and do not set a constant as we might be switching servers
1258 if (defined('PMA_MYSQL_INT_VERSION')
1259 && PMA_MYSQL_INT_VERSION >= 50037
1260 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1262 PMA_cacheSet('profiling_supported', true, true);
1263 } else {
1264 PMA_cacheSet('profiling_supported', false, true);
1268 return PMA_cacheGet('profiling_supported', true);
1272 * Displays a form with the Profiling checkbox
1274 * @param string $sql_query
1275 * @access public
1277 function PMA_profilingCheckbox($sql_query)
1279 if (PMA_profilingSupported()) {
1280 echo '<form action="sql.php" method="post">' . "\n";
1281 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1282 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1283 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1284 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1285 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1286 echo '</form>' . "\n";
1291 * Formats $value to byte view
1293 * @param double $value the value to format
1294 * @param int $limes the sensitiveness
1295 * @param int $comma the number of decimals to retain
1297 * @return array the formatted value and its unit
1299 * @access public
1301 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1303 $byteUnits = array(
1304 /* l10n: shortcuts for Byte */
1305 __('B'),
1306 /* l10n: shortcuts for Kilobyte */
1307 __('KiB'),
1308 /* l10n: shortcuts for Megabyte */
1309 __('MiB'),
1310 /* l10n: shortcuts for Gigabyte */
1311 __('GiB'),
1312 /* l10n: shortcuts for Terabyte */
1313 __('TiB'),
1314 /* l10n: shortcuts for Petabyte */
1315 __('PiB'),
1316 /* l10n: shortcuts for Exabyte */
1317 __('EiB')
1320 $dh = PMA_pow(10, $comma);
1321 $li = PMA_pow(10, $limes);
1322 $unit = $byteUnits[0];
1324 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1325 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1326 // use 1024.0 to avoid integer overflow on 64-bit machines
1327 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1328 $unit = $byteUnits[$d];
1329 break 1;
1330 } // end if
1331 } // end for
1333 if ($unit != $byteUnits[0]) {
1334 // if the unit is not bytes (as represented in current language)
1335 // reformat with max length of 5
1336 // 4th parameter=true means do not reformat if value < 1
1337 $return_value = PMA_formatNumber($value, 5, $comma, true);
1338 } else {
1339 // do not reformat, just handle the locale
1340 $return_value = PMA_formatNumber($value, 0);
1343 return array(trim($return_value), $unit);
1344 } // end of the 'PMA_formatByteDown' function
1347 * Changes thousands and decimal separators to locale specific values.
1349 * @param $value
1351 * @return string
1353 function PMA_localizeNumber($value)
1355 return str_replace(
1356 array(',', '.'),
1357 array(
1358 /* l10n: Thousands separator */
1359 __(','),
1360 /* l10n: Decimal separator */
1361 __('.'),
1363 $value);
1367 * Formats $value to the given length and appends SI prefixes
1368 * with a $length of 0 no truncation occurs, number is only formated
1369 * to the current locale
1371 * examples:
1372 * <code>
1373 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1374 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1375 * echo PMA_formatNumber(-0.003, 6); // -3 m
1376 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1377 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1378 * echo PMA_formatNumber(0, 6); // 0
1380 * </code>
1381 * @param double $value the value to format
1382 * @param integer $digits_left number of digits left of the comma
1383 * @param integer $digits_right number of digits right of the comma
1384 * @param boolean $only_down do not reformat numbers below 1
1385 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1387 * @return string the formatted value and its unit
1389 * @access public
1391 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1393 if ($value==0) return '0';
1395 $originalValue = $value;
1396 //number_format is not multibyte safe, str_replace is safe
1397 if ($digits_left === 0) {
1398 $value = number_format($value, $digits_right);
1399 if ($originalValue != 0 && floatval($value) == 0) {
1400 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1403 return PMA_localizeNumber($value);
1406 // this units needs no translation, ISO
1407 $units = array(
1408 -8 => 'y',
1409 -7 => 'z',
1410 -6 => 'a',
1411 -5 => 'f',
1412 -4 => 'p',
1413 -3 => 'n',
1414 -2 => '&micro;',
1415 -1 => 'm',
1416 0 => ' ',
1417 1 => 'k',
1418 2 => 'M',
1419 3 => 'G',
1420 4 => 'T',
1421 5 => 'P',
1422 6 => 'E',
1423 7 => 'Z',
1424 8 => 'Y'
1427 // check for negative value to retain sign
1428 if ($value < 0) {
1429 $sign = '-';
1430 $value = abs($value);
1431 } else {
1432 $sign = '';
1435 $dh = PMA_pow(10, $digits_right);
1438 * This gives us the right SI prefix already,
1439 * but $digits_left parameter not incorporated
1441 $d = floor(log10($value) / 3);
1443 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1444 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1445 * to use, then lower the SI prefix
1447 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1448 if ($digits_left > $cur_digits) {
1449 $d-= floor(($digits_left - $cur_digits)/3);
1452 if ($d<0 && $only_down) $d=0;
1454 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1455 $unit = $units[$d];
1457 // If we dont want any zeros after the comma just add the thousand seperator
1458 if ($noTrailingZero) {
1459 $value = PMA_localizeNumber(
1460 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1462 } else {
1463 //number_format is not multibyte safe, str_replace is safe
1464 $value = PMA_localizeNumber(number_format($value, $digits_right));
1467 if ($originalValue!=0 && floatval($value) == 0) {
1468 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1471 return $sign . $value . ' ' . $unit;
1472 } // end of the 'PMA_formatNumber' function
1475 * Returns the number of bytes when a formatted size is given
1477 * @param string $formatted_size the size expression (for example 8MB)
1479 * @return integer The numerical part of the expression (for example 8)
1481 function PMA_extractValueFromFormattedSize($formatted_size)
1483 $return_value = -1;
1485 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1486 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1487 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1488 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1489 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1490 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1492 return $return_value;
1493 }// end of the 'PMA_extractValueFromFormattedSize' function
1496 * Writes localised date
1498 * @param string $timestamp the current timestamp
1499 * @param string $format format
1501 * @return string the formatted date
1503 * @access public
1505 function PMA_localisedDate($timestamp = -1, $format = '')
1507 $month = array(
1508 /* l10n: Short month name */
1509 __('Jan'),
1510 /* l10n: Short month name */
1511 __('Feb'),
1512 /* l10n: Short month name */
1513 __('Mar'),
1514 /* l10n: Short month name */
1515 __('Apr'),
1516 /* l10n: Short month name */
1517 _pgettext('Short month name', 'May'),
1518 /* l10n: Short month name */
1519 __('Jun'),
1520 /* l10n: Short month name */
1521 __('Jul'),
1522 /* l10n: Short month name */
1523 __('Aug'),
1524 /* l10n: Short month name */
1525 __('Sep'),
1526 /* l10n: Short month name */
1527 __('Oct'),
1528 /* l10n: Short month name */
1529 __('Nov'),
1530 /* l10n: Short month name */
1531 __('Dec'));
1532 $day_of_week = array(
1533 /* l10n: Short week day name */
1534 _pgettext('Short week day name', 'Sun'),
1535 /* l10n: Short week day name */
1536 __('Mon'),
1537 /* l10n: Short week day name */
1538 __('Tue'),
1539 /* l10n: Short week day name */
1540 __('Wed'),
1541 /* l10n: Short week day name */
1542 __('Thu'),
1543 /* l10n: Short week day name */
1544 __('Fri'),
1545 /* l10n: Short week day name */
1546 __('Sat'));
1548 if ($format == '') {
1549 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1550 $format = __('%B %d, %Y at %I:%M %p');
1553 if ($timestamp == -1) {
1554 $timestamp = time();
1557 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1558 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1560 return strftime($date, $timestamp);
1561 } // end of the 'PMA_localisedDate()' function
1565 * returns a tab for tabbed navigation.
1566 * If the variables $link and $args ar left empty, an inactive tab is created
1568 * @param array $tab array with all options
1569 * @param array $url_params
1571 * @return string html code for one tab, a link if valid otherwise a span
1573 * @access public
1575 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1577 // default values
1578 $defaults = array(
1579 'text' => '',
1580 'class' => '',
1581 'active' => null,
1582 'link' => '',
1583 'sep' => '?',
1584 'attr' => '',
1585 'args' => '',
1586 'warning' => '',
1587 'fragment' => '',
1588 'id' => '',
1591 $tab = array_merge($defaults, $tab);
1593 // determine additionnal style-class
1594 if (empty($tab['class'])) {
1595 if (! empty($tab['active'])
1596 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1597 $tab['class'] = 'active';
1598 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1599 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1600 && empty($tab['warning'])) {
1601 $tab['class'] = 'active';
1605 if (!empty($tab['warning'])) {
1606 $tab['class'] .= ' error';
1607 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1610 // If there are any tab specific URL parameters, merge those with the general URL parameters
1611 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1612 $url_params = array_merge($url_params, $tab['url_params']);
1615 // build the link
1616 if (!empty($tab['link'])) {
1617 $tab['link'] = htmlentities($tab['link']);
1618 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1619 if (! empty($tab['args'])) {
1620 foreach ($tab['args'] as $param => $value) {
1621 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1622 . urlencode($value);
1627 if (! empty($tab['fragment'])) {
1628 $tab['link'] .= $tab['fragment'];
1631 // display icon, even if iconic is disabled but the link-text is missing
1632 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1633 && isset($tab['icon'])) {
1634 // avoid generating an alt tag, because it only illustrates
1635 // the text that follows and if browser does not display
1636 // images, the text is duplicated
1637 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1638 .' width="16" height="16" alt="" />%2$s';
1639 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1641 // check to not display an empty link-text
1642 elseif (empty($tab['text'])) {
1643 $tab['text'] = '?';
1644 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1645 E_USER_NOTICE);
1648 //Set the id for the tab, if set in the params
1649 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1650 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1652 if (!empty($tab['link'])) {
1653 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1654 .$id_string
1655 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1656 . $tab['text'] . '</a>';
1657 } else {
1658 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1659 . $tab['text'] . '</span>';
1662 $out .= '</li>';
1663 return $out;
1664 } // end of the 'PMA_generate_html_tab()' function
1667 * returns html-code for a tab navigation
1669 * @param array $tabs one element per tab
1670 * @param string $url_params
1672 * @return string html-code for tab-navigation
1674 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1676 $tag_id = 'topmenu';
1677 $tab_navigation =
1678 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1679 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1681 foreach ($tabs as $tab) {
1682 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1685 $tab_navigation .=
1686 '</ul>' . "\n"
1687 .'<div class="clearfloat"></div>'
1688 .'</div>' . "\n";
1690 return $tab_navigation;
1695 * Displays a link, or a button if the link's URL is too large, to
1696 * accommodate some browsers' limitations
1698 * @param string $url the URL
1699 * @param string $message the link message
1700 * @param mixed $tag_params string: js confirmation
1701 * array: additional tag params (f.e. style="")
1702 * @param boolean $new_form we set this to false when we are already in
1703 * a form, to avoid generating nested forms
1704 * @param boolean $strip_img
1705 * @param string $target
1707 * @return string the results to be echoed or saved in an array
1709 function PMA_linkOrButton($url, $message, $tag_params = array(),
1710 $new_form = true, $strip_img = false, $target = '')
1712 $url_length = strlen($url);
1713 // with this we should be able to catch case of image upload
1714 // into a (MEDIUM) BLOB; not worth generating even a form for these
1715 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1716 return '';
1720 if (! is_array($tag_params)) {
1721 $tmp = $tag_params;
1722 $tag_params = array();
1723 if (!empty($tmp)) {
1724 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1726 unset($tmp);
1728 if (! empty($target)) {
1729 $tag_params['target'] = htmlentities($target);
1732 $tag_params_strings = array();
1733 foreach ($tag_params as $par_name => $par_value) {
1734 // htmlspecialchars() only on non javascript
1735 $par_value = substr($par_name, 0, 2) == 'on'
1736 ? $par_value
1737 : htmlspecialchars($par_value);
1738 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1741 $displayed_message = '';
1742 // Add text if not already added
1743 if (stristr($message, '<img')
1744 && (!$strip_img || $GLOBALS['cfg']['PropertiesIconic'] === true)
1745 && strip_tags($message)==$message
1747 $displayed_message = '<span>' . htmlspecialchars(preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)) . '</span>';
1750 // Suhosin: Check that each query parameter is not above maximum
1751 $in_suhosin_limits = true;
1752 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1753 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1754 $query_parts = PMA_splitURLQuery($url);
1755 foreach($query_parts as $query_pair) {
1756 list($eachvar, $eachval) = explode('=', $query_pair);
1757 if(strlen($eachval) > $suhosin_get_MaxValueLength) {
1758 $in_suhosin_limits = false;
1759 break;
1765 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1766 // no whitespace within an <a> else Safari will make it part of the link
1767 $ret = "\n" . '<a href="' . $url . '" '
1768 . implode(' ', $tag_params_strings) . '>'
1769 . $message . $displayed_message . '</a>' . "\n";
1770 } else {
1771 // no spaces (linebreaks) at all
1772 // or after the hidden fields
1773 // IE will display them all
1775 // add class=link to submit button
1776 if (empty($tag_params['class'])) {
1777 $tag_params['class'] = 'link';
1780 if (! isset($query_parts)) {
1781 $query_parts = PMA_splitURLQuery($url);
1783 $url_parts = parse_url($url);
1785 if ($new_form) {
1786 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1787 . ' method="post"' . $target . ' style="display: inline;">';
1788 $subname_open = '';
1789 $subname_close = '';
1790 $submit_link = '#';
1791 } else {
1792 $query_parts[] = 'redirect=' . $url_parts['path'];
1793 if (empty($GLOBALS['subform_counter'])) {
1794 $GLOBALS['subform_counter'] = 0;
1796 $GLOBALS['subform_counter']++;
1797 $ret = '';
1798 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1799 $subname_close = ']';
1800 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1802 foreach ($query_parts as $query_pair) {
1803 list($eachvar, $eachval) = explode('=', $query_pair);
1804 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1805 . $subname_close . '" value="'
1806 . htmlspecialchars(urldecode($eachval)) . '" />';
1807 } // end while
1809 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1810 . implode(' ', $tag_params_strings) . '>'
1811 . $message . ' ' . $displayed_message . '</a>' . "\n";
1813 if ($new_form) {
1814 $ret .= '</form>';
1816 } // end if... else...
1818 return $ret;
1819 } // end of the 'PMA_linkOrButton()' function
1823 * Splits a URL string by parameter
1825 * @param string $url the URL
1826 * @return array the parameter/value pairs, for example [0] db=sakila
1828 function PMA_splitURLQuery($url) {
1829 // decode encoded url separators
1830 $separator = PMA_get_arg_separator();
1831 // on most places separator is still hard coded ...
1832 if ($separator !== '&') {
1833 // ... so always replace & with $separator
1834 $url = str_replace(htmlentities('&'), $separator, $url);
1835 $url = str_replace('&', $separator, $url);
1837 $url = str_replace(htmlentities($separator), $separator, $url);
1838 // end decode
1840 $url_parts = parse_url($url);
1841 return explode($separator, $url_parts['query']);
1845 * Returns a given timespan value in a readable format.
1847 * @param int $seconds the timespan
1849 * @return string the formatted value
1851 function PMA_timespanFormat($seconds)
1853 $days = floor($seconds / 86400);
1854 if ($days > 0) {
1855 $seconds -= $days * 86400;
1857 $hours = floor($seconds / 3600);
1858 if ($days > 0 || $hours > 0) {
1859 $seconds -= $hours * 3600;
1861 $minutes = floor($seconds / 60);
1862 if ($days > 0 || $hours > 0 || $minutes > 0) {
1863 $seconds -= $minutes * 60;
1865 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1869 * Takes a string and outputs each character on a line for itself. Used
1870 * mainly for horizontalflipped display mode.
1871 * Takes care of special html-characters.
1872 * Fulfills todo-item
1873 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1875 * @todo add a multibyte safe function PMA_STR_split()
1876 * @param string $string The string
1877 * @param string $Separator The Separator (defaults to "<br />\n")
1879 * @access public
1881 * @return string The flipped string
1883 function PMA_flipstring($string, $Separator = "<br />\n")
1885 $format_string = '';
1886 $charbuff = false;
1888 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1889 $char = $string{$i};
1890 $append = false;
1892 if ($char == '&') {
1893 $format_string .= $charbuff;
1894 $charbuff = $char;
1895 } elseif ($char == ';' && !empty($charbuff)) {
1896 $format_string .= $charbuff . $char;
1897 $charbuff = false;
1898 $append = true;
1899 } elseif (! empty($charbuff)) {
1900 $charbuff .= $char;
1901 } else {
1902 $format_string .= $char;
1903 $append = true;
1906 // do not add separator after the last character
1907 if ($append && ($i != $str_len - 1)) {
1908 $format_string .= $Separator;
1912 return $format_string;
1916 * Function added to avoid path disclosures.
1917 * Called by each script that needs parameters, it displays
1918 * an error message and, by default, stops the execution.
1920 * Not sure we could use a strMissingParameter message here,
1921 * would have to check if the error message file is always available
1923 * @todo use PMA_fatalError() if $die === true?
1924 * @param array $params The names of the parameters needed by the calling script.
1925 * @param bool $die Stop the execution?
1926 * (Set this manually to false in the calling script
1927 * until you know all needed parameters to check).
1928 * @param bool $request Whether to include this list in checking for special params.
1929 * @global string path to current script
1930 * @global boolean flag whether any special variable was required
1932 * @access public
1934 function PMA_checkParameters($params, $die = true, $request = true)
1936 global $checked_special;
1938 if (! isset($checked_special)) {
1939 $checked_special = false;
1942 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1943 $found_error = false;
1944 $error_message = '';
1946 foreach ($params as $param) {
1947 if ($request && $param != 'db' && $param != 'table') {
1948 $checked_special = true;
1951 if (! isset($GLOBALS[$param])) {
1952 $error_message .= $reported_script_name
1953 . ': ' . __('Missing parameter:') . ' '
1954 . $param
1955 . PMA_showDocu('faqmissingparameters')
1956 . '<br />';
1957 $found_error = true;
1960 if ($found_error) {
1962 * display html meta tags
1964 require_once './libraries/header_meta_style.inc.php';
1965 echo '</head><body><p>' . $error_message . '</p></body></html>';
1966 if ($die) {
1967 exit();
1970 } // end function
1973 * Function to generate unique condition for specified row.
1975 * @param resource $handle current query result
1976 * @param integer $fields_cnt number of fields
1977 * @param array $fields_meta meta information about fields
1978 * @param array $row current row
1979 * @param boolean $force_unique generate condition only on pk or unique
1981 * @access public
1983 * @return array the calculated condition and whether condition is unique
1985 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1987 $primary_key = '';
1988 $unique_key = '';
1989 $nonprimary_condition = '';
1990 $preferred_condition = '';
1991 $primary_key_array = array();
1992 $unique_key_array = array();
1993 $nonprimary_condition_array = array();
1994 $condition_array = array();
1996 for ($i = 0; $i < $fields_cnt; ++$i) {
1997 $condition = '';
1998 $con_key = '';
1999 $con_val = '';
2000 $field_flags = PMA_DBI_field_flags($handle, $i);
2001 $meta = $fields_meta[$i];
2003 // do not use a column alias in a condition
2004 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2005 $meta->orgname = $meta->name;
2007 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2008 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2010 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2011 // need (string) === (string)
2012 // '' !== 0 but '' == 0
2013 if ((string) $select_expr['alias'] === (string) $meta->name) {
2014 $meta->orgname = $select_expr['column'];
2015 break;
2016 } // end if
2017 } // end foreach
2021 // Do not use a table alias in a condition.
2022 // Test case is:
2023 // select * from galerie x WHERE
2024 //(select count(*) from galerie y where y.datum=x.datum)>1
2026 // But orgtable is present only with mysqli extension so the
2027 // fix is only for mysqli.
2028 // Also, do not use the original table name if we are dealing with
2029 // a view because this view might be updatable.
2030 // (The isView() verification should not be costly in most cases
2031 // because there is some caching in the function).
2032 if (isset($meta->orgtable)
2033 && $meta->table != $meta->orgtable
2034 && ! PMA_Table::isView($GLOBALS['db'], $meta->table)
2036 $meta->table = $meta->orgtable;
2039 // to fix the bug where float fields (primary or not)
2040 // can't be matched because of the imprecision of
2041 // floating comparison, use CONCAT
2042 // (also, the syntax "CONCAT(field) IS NULL"
2043 // that we need on the next "if" will work)
2044 if ($meta->type == 'real') {
2045 $con_key = 'CONCAT(' . PMA_backquote($meta->table) . '.'
2046 . PMA_backquote($meta->orgname) . ')';
2047 } else {
2048 $con_key = PMA_backquote($meta->table) . '.'
2049 . PMA_backquote($meta->orgname);
2050 } // end if... else...
2051 $condition = ' ' . $con_key . ' ';
2053 if (! isset($row[$i]) || is_null($row[$i])) {
2054 $con_val = 'IS NULL';
2055 } else {
2056 // timestamp is numeric on some MySQL 4.1
2057 // for real we use CONCAT above and it should compare to string
2058 if ($meta->numeric
2059 && $meta->type != 'timestamp'
2060 && $meta->type != 'real'
2062 $con_val = '= ' . $row[$i];
2063 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2064 // hexify only if this is a true not empty BLOB or a BINARY
2065 && stristr($field_flags, 'BINARY')
2066 && !empty($row[$i])) {
2067 // do not waste memory building a too big condition
2068 if (strlen($row[$i]) < 1000) {
2069 // use a CAST if possible, to avoid problems
2070 // if the field contains wildcard characters % or _
2071 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2072 } else {
2073 // this blob won't be part of the final condition
2074 $con_val = null;
2076 } elseif (in_array($meta->type, PMA_getGISDatatypes()) && ! empty($row[$i])) {
2077 // do not build a too big condition
2078 if (strlen($row[$i]) < 5000) {
2079 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2080 } else {
2081 $condition = '';
2083 } elseif ($meta->type == 'bit') {
2084 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "'";
2085 } else {
2086 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2089 if ($con_val != null) {
2090 $condition .= $con_val . ' AND';
2091 if ($meta->primary_key > 0) {
2092 $primary_key .= $condition;
2093 $primary_key_array[$con_key] = $con_val;
2094 } elseif ($meta->unique_key > 0) {
2095 $unique_key .= $condition;
2096 $unique_key_array[$con_key] = $con_val;
2098 $nonprimary_condition .= $condition;
2099 $nonprimary_condition_array[$con_key] = $con_val;
2101 } // end for
2103 // Correction University of Virginia 19991216:
2104 // prefer primary or unique keys for condition,
2105 // but use conjunction of all values if no primary key
2106 $clause_is_unique = true;
2107 if ($primary_key) {
2108 $preferred_condition = $primary_key;
2109 $condition_array = $primary_key_array;
2110 } elseif ($unique_key) {
2111 $preferred_condition = $unique_key;
2112 $condition_array = $unique_key_array;
2113 } elseif (! $force_unique) {
2114 $preferred_condition = $nonprimary_condition;
2115 $condition_array = $nonprimary_condition_array;
2116 $clause_is_unique = false;
2119 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2120 return(array($where_clause, $clause_is_unique, $condition_array));
2121 } // end function
2124 * Generate a button or image tag
2126 * @param string $button_name name of button element
2127 * @param string $button_class class of button element
2128 * @param string $image_name name of image element
2129 * @param string $text text to display
2130 * @param string $image image to display
2131 * @param string $value
2133 * @access public
2135 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2136 $image, $value = '')
2138 if ($value == '') {
2139 $value = $text;
2141 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2142 echo ' <input type="submit" name="' . $button_name . '"'
2143 .' value="' . htmlspecialchars($value) . '"'
2144 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2145 return;
2148 /* Opera has trouble with <input type="image"> */
2149 /* IE has trouble with <button> */
2150 if (PMA_USR_BROWSER_AGENT != 'IE') {
2151 echo '<button class="' . $button_class . '" type="submit"'
2152 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2153 .' title="' . htmlspecialchars($text) . '">' . "\n"
2154 . PMA_getIcon($image, $text)
2155 .'</button>' . "\n";
2156 } else {
2157 echo '<input type="image" name="' . $image_name
2158 . '" value="' . htmlspecialchars($value)
2159 . '" title="' . htmlspecialchars($text)
2160 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2161 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2162 ? '&nbsp;' . htmlspecialchars($text)
2163 : '') . "\n";
2165 } // end function
2168 * Generate a pagination selector for browsing resultsets
2170 * @param int $rows Number of rows in the pagination set
2171 * @param int $pageNow current page number
2172 * @param int $nbTotalPage number of total pages
2173 * @param int $showAll If the number of pages is lower than this
2174 * variable, no pages will be omitted in pagination
2175 * @param int $sliceStart How many rows at the beginning should always be shown?
2176 * @param int $sliceEnd How many rows at the end should always be shown?
2177 * @param int $percent Percentage of calculation page offsets to hop to a next page
2178 * @param int $range Near the current page, how many pages should
2179 * be considered "nearby" and displayed as well?
2180 * @param string $prompt The prompt to display (sometimes empty)
2182 * @return string
2184 * @access public
2186 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2187 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2188 $range = 10, $prompt = '')
2190 $increment = floor($nbTotalPage / $percent);
2191 $pageNowMinusRange = ($pageNow - $range);
2192 $pageNowPlusRange = ($pageNow + $range);
2194 $gotopage = $prompt . ' <select id="pageselector" ';
2195 if ($GLOBALS['cfg']['AjaxEnable']) {
2196 $gotopage .= ' class="ajax"';
2198 $gotopage .= ' name="pos" >' . "\n";
2199 if ($nbTotalPage < $showAll) {
2200 $pages = range(1, $nbTotalPage);
2201 } else {
2202 $pages = array();
2204 // Always show first X pages
2205 for ($i = 1; $i <= $sliceStart; $i++) {
2206 $pages[] = $i;
2209 // Always show last X pages
2210 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2211 $pages[] = $i;
2214 // Based on the number of results we add the specified
2215 // $percent percentage to each page number,
2216 // so that we have a representing page number every now and then to
2217 // immediately jump to specific pages.
2218 // As soon as we get near our currently chosen page ($pageNow -
2219 // $range), every page number will be shown.
2220 $i = $sliceStart;
2221 $x = $nbTotalPage - $sliceEnd;
2222 $met_boundary = false;
2223 while ($i <= $x) {
2224 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2225 // If our pageselector comes near the current page, we use 1
2226 // counter increments
2227 $i++;
2228 $met_boundary = true;
2229 } else {
2230 // We add the percentage increment to our current page to
2231 // hop to the next one in range
2232 $i += $increment;
2234 // Make sure that we do not cross our boundaries.
2235 if ($i > $pageNowMinusRange && ! $met_boundary) {
2236 $i = $pageNowMinusRange;
2240 if ($i > 0 && $i <= $x) {
2241 $pages[] = $i;
2245 // Since because of ellipsing of the current page some numbers may be double,
2246 // we unify our array:
2247 sort($pages);
2248 $pages = array_unique($pages);
2251 foreach ($pages as $i) {
2252 if ($i == $pageNow) {
2253 $selected = 'selected="selected" style="font-weight: bold"';
2254 } else {
2255 $selected = '';
2257 $gotopage .= ' <option ' . $selected
2258 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2261 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2263 return $gotopage;
2264 } // end function
2268 * Generate navigation for a list
2270 * @todo use $pos from $_url_params
2271 * @param int $count number of elements in the list
2272 * @param int $pos current position in the list
2273 * @param array $_url_params url parameters
2274 * @param string $script script name for form target
2275 * @param string $frame target frame
2276 * @param int $max_count maximum number of elements to display from the list
2278 * @access public
2280 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2283 if ($max_count < $count) {
2284 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2285 echo __('Page number:');
2286 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2288 // Move to the beginning or to the previous page
2289 if ($pos > 0) {
2290 // patch #474210 - part 1
2291 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2292 $caption1 = '&lt;&lt;';
2293 $caption2 = ' &lt; ';
2294 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2295 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2296 } else {
2297 $caption1 = _pgettext('First page', 'Begin') . ' &lt;&lt;';
2298 $caption2 = _pgettext('Previous page', 'Previous') . ' &lt;';
2299 $title1 = '';
2300 $title2 = '';
2301 } // end if... else...
2302 $_url_params['pos'] = 0;
2303 echo '<a' . $title1 . ' href="' . $script
2304 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2305 . $caption1 . '</a>';
2306 $_url_params['pos'] = $pos - $max_count;
2307 echo '<a' . $title2 . ' href="' . $script
2308 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2309 . $caption2 . '</a>';
2312 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2313 echo PMA_generate_common_hidden_inputs($_url_params);
2314 echo PMA_pageselector(
2315 $max_count,
2316 floor(($pos + 1) / $max_count) + 1,
2317 ceil($count / $max_count));
2318 echo '</form>';
2320 if ($pos + $max_count < $count) {
2321 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2322 $caption3 = ' &gt; ';
2323 $caption4 = '&gt;&gt;';
2324 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2325 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2326 } else {
2327 $caption3 = '&gt; ' . _pgettext('Next page', 'Next');
2328 $caption4 = '&gt;&gt; ' . _pgettext('Last page', 'End');
2329 $title3 = '';
2330 $title4 = '';
2331 } // end if... else...
2332 $_url_params['pos'] = $pos + $max_count;
2333 echo '<a' . $title3 . ' href="' . $script
2334 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2335 . $caption3 . '</a>';
2336 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2337 if ($_url_params['pos'] == $count) {
2338 $_url_params['pos'] = $count - $max_count;
2340 echo '<a' . $title4 . ' href="' . $script
2341 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2342 . $caption4 . '</a>';
2344 echo "\n";
2345 if ('frame_navigation' == $frame) {
2346 echo '</div>' . "\n";
2352 * replaces %u in given path with current user name
2354 * example:
2355 * <code>
2356 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2358 * </code>
2360 * @param string $dir with wildcard for user
2362 * @return string per user directory
2364 function PMA_userDir($dir)
2366 // add trailing slash
2367 if (substr($dir, -1) != '/') {
2368 $dir .= '/';
2371 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2375 * returns html code for db link to default db page
2377 * @param string $database
2379 * @return string html link to default db page
2381 function PMA_getDbLink($database = null)
2383 if (! strlen($database)) {
2384 if (! strlen($GLOBALS['db'])) {
2385 return '';
2387 $database = $GLOBALS['db'];
2388 } else {
2389 $database = PMA_unescape_mysql_wildcards($database);
2392 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2393 . ' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2394 . htmlspecialchars($database) . '</a>';
2398 * Displays a lightbulb hint explaining a known external bug
2399 * that affects a functionality
2401 * @param string $functionality localized message explaining the func.
2402 * @param string $component 'mysql' (eventually, 'php')
2403 * @param string $minimum_version of this component
2404 * @param string $bugref bug reference for this component
2406 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2408 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2409 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2414 * Generates and echoes an HTML checkbox
2416 * @param string $html_field_name the checkbox HTML field
2417 * @param string $label label for checkbox
2418 * @param boolean $checked is it initially checked?
2419 * @param boolean $onclick should it submit the form on click?
2421 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2424 echo '<input type="checkbox" name="' . $html_field_name . '" id="' . $html_field_name . '"' . ($checked ? ' checked="checked"' : '') . ($onclick ? ' class="autosubmit"' : '') . ' /><label for="' . $html_field_name . '">' . $label . '</label>';
2428 * Generates and echoes a set of radio HTML fields
2430 * @param string $html_field_name the radio HTML field
2431 * @param array $choices the choices values and labels
2432 * @param string $checked_choice the choice to check by default
2433 * @param boolean $line_break whether to add an HTML line break after a choice
2434 * @param boolean $escape_label whether to use htmlspecialchars() on label
2435 * @param string $class enclose each choice with a div of this class
2437 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='')
2439 foreach ($choices as $choice_value => $choice_label) {
2440 if (! empty($class)) {
2441 echo '<div class="' . $class . '">';
2443 $html_field_id = $html_field_name . '_' . $choice_value;
2444 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2445 if ($choice_value == $checked_choice) {
2446 echo ' checked="checked"';
2448 echo ' />' . "\n";
2449 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2450 if ($line_break) {
2451 echo '<br />';
2453 if (! empty($class)) {
2454 echo '</div>';
2456 echo "\n";
2461 * Generates and returns an HTML dropdown
2463 * @param string $select_name
2464 * @param array $choices choices values
2465 * @param string $active_choice the choice to select by default
2466 * @param string $id id of the select element; can be different in case
2467 * the dropdown is present more than once on the page
2468 * @return string
2470 * @todo support titles
2472 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2474 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2475 foreach ($choices as $one_choice_value => $one_choice_label) {
2476 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2477 if ($one_choice_value == $active_choice) {
2478 $result .= ' selected="selected"';
2480 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2482 $result .= '</select>';
2483 return $result;
2487 * Generates a slider effect (jQjuery)
2488 * Takes care of generating the initial <div> and the link
2489 * controlling the slider; you have to generate the </div> yourself
2490 * after the sliding section.
2492 * @param string $id the id of the <div> on which to apply the effect
2493 * @param string $message the message to show as a link
2495 function PMA_generate_slider_effect($id, $message)
2497 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2498 echo '<div id="' . $id . '">';
2499 return;
2502 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2503 * opening the <div> with PHP itself instead of JavaScript.
2505 * @todo find a better solution that uses $.append(), the recommended method
2506 * maybe by using an additional param, the id of the div to append to
2509 <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); ?>">
2510 <?php
2514 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2516 * @param string $action The URL for the request to be executed
2517 * @param string $select_name The name for the dropdown box
2518 * @param array $options An array of options (see rte_footer.lib.php)
2519 * @param string $callback A JS snippet to execute when the request is
2520 * successfully processed
2522 * @return string HTML code for the toggle button
2524 function PMA_toggleButton($action, $select_name, $options, $callback)
2526 // Do the logic first
2527 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2528 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2529 if ($options[1]['selected'] == true) {
2530 $state = 'on';
2531 } else if ($options[0]['selected'] == true) {
2532 $state = 'off';
2533 } else {
2534 $state = 'on';
2536 $selected1 = '';
2537 $selected0 = '';
2538 if ($options[1]['selected'] == true) {
2539 $selected1 = " selected='selected'";
2540 } else if ($options[0]['selected'] == true) {
2541 $selected0 = " selected='selected'";
2543 // Generate output
2544 $retval = "<!-- TOGGLE START -->\n";
2545 if ($GLOBALS['cfg']['AjaxEnable']) {
2546 $retval .= "<noscript>\n";
2548 $retval .= "<div class='wrapper'>\n";
2549 $retval .= " <form action='$action' method='post'>\n";
2550 $retval .= " <select name='$select_name'>\n";
2551 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2552 $retval .= " {$options[1]['label']}\n";
2553 $retval .= " </option>\n";
2554 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2555 $retval .= " {$options[0]['label']}\n";
2556 $retval .= " </option>\n";
2557 $retval .= " </select>\n";
2558 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2559 $retval .= " </form>\n";
2560 $retval .= "</div>\n";
2561 if ($GLOBALS['cfg']['AjaxEnable']) {
2562 $retval .= "</noscript>\n";
2563 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2564 $retval .= " <div class='toggleButton'>\n";
2565 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2566 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2567 $retval .= " alt='' />\n";
2568 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2569 $retval .= " <tbody>\n";
2570 $retval .= " <td class='toggleOn'>\n";
2571 $retval .= " <span class='hide'>$link_on</span>\n";
2572 $retval .= " <div>";
2573 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2574 $retval .= " </td>\n";
2575 $retval .= " <td><div>&nbsp;</div></td>\n";
2576 $retval .= " <td class='toggleOff'>\n";
2577 $retval .= " <span class='hide'>$link_off</span>\n";
2578 $retval .= " <div>";
2579 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2580 $retval .= " </div>\n";
2581 $retval .= " </tbody>\n";
2582 $retval .= " </tr></table>\n";
2583 $retval .= " <span class='hide callback'>$callback</span>\n";
2584 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2585 $retval .= " </div>\n";
2586 $retval .= " </div>\n";
2587 $retval .= "</div>\n";
2589 $retval .= "<!-- TOGGLE END -->";
2591 return $retval;
2592 } // end PMA_toggleButton()
2595 * Clears cache content which needs to be refreshed on user change.
2597 function PMA_clearUserCache()
2599 PMA_cacheUnset('is_superuser', true);
2603 * Verifies if something is cached in the session
2605 * @param string $var
2606 * @param int|true $server
2608 * @return boolean
2610 function PMA_cacheExists($var, $server = 0)
2612 if (true === $server) {
2613 $server = $GLOBALS['server'];
2615 return isset($_SESSION['cache']['server_' . $server][$var]);
2619 * Gets cached information from the session
2621 * @param string $var
2622 * @param int|true $server
2624 * @return mixed
2626 function PMA_cacheGet($var, $server = 0)
2628 if (true === $server) {
2629 $server = $GLOBALS['server'];
2631 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2632 return $_SESSION['cache']['server_' . $server][$var];
2633 } else {
2634 return null;
2639 * Caches information in the session
2641 * @param string $var
2642 * @param mixed $val
2643 * @param int|true $server
2645 * @return mixed
2647 function PMA_cacheSet($var, $val = null, $server = 0)
2649 if (true === $server) {
2650 $server = $GLOBALS['server'];
2652 $_SESSION['cache']['server_' . $server][$var] = $val;
2656 * Removes cached information from the session
2658 * @param string $var
2659 * @param int|true $server
2661 function PMA_cacheUnset($var, $server = 0)
2663 if (true === $server) {
2664 $server = $GLOBALS['server'];
2666 unset($_SESSION['cache']['server_' . $server][$var]);
2670 * Converts a bit value to printable format;
2671 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2672 * function because in PHP, decbin() supports only 32 bits
2674 * @param numeric $value coming from a BIT field
2675 * @param integer $length
2677 * @return string the printable value
2679 function PMA_printable_bit_value($value, $length)
2681 $printable = '';
2682 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2683 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2685 $printable = substr($printable, -$length);
2686 return $printable;
2690 * Verifies whether the value contains a non-printable character
2692 * @param string $value
2694 * @return boolean
2696 function PMA_contains_nonprintable_ascii($value)
2698 return preg_match('@[^[:print:]]@', $value);
2702 * Converts a BIT type default value
2703 * for example, b'010' becomes 010
2705 * @param string $bit_default_value
2707 * @return string the converted value
2709 function PMA_convert_bit_default_value($bit_default_value)
2711 return strtr($bit_default_value, array("b" => "", "'" => ""));
2715 * Extracts the various parts from a field type spec
2717 * @param string $fieldspec
2719 * @return array associative array containing type, spec_in_brackets
2720 * and possibly enum_set_values (another array)
2722 function PMA_extractFieldSpec($fieldspec)
2724 $first_bracket_pos = strpos($fieldspec, '(');
2725 if ($first_bracket_pos) {
2726 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2727 // convert to lowercase just to be sure
2728 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2729 } else {
2730 $type = strtolower($fieldspec);
2731 $spec_in_brackets = '';
2734 if ('enum' == $type || 'set' == $type) {
2735 // Define our working vars
2736 $enum_set_values = array();
2737 $working = "";
2738 $in_string = false;
2739 $index = 0;
2741 // While there is another character to process
2742 while (isset($fieldspec[$index])) {
2743 // Grab the char to look at
2744 $char = $fieldspec[$index];
2746 // If it is a single quote, needs to be handled specially
2747 if ($char == "'") {
2748 // If we are not currently in a string, begin one
2749 if (! $in_string) {
2750 $in_string = true;
2751 $working = "";
2752 } else {
2753 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2754 // Check out the next character (if possible)
2755 $has_next = isset($fieldspec[$index + 1]);
2756 $next = $has_next ? $fieldspec[$index + 1] : null;
2758 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2759 if (! $has_next || $next != "'") {
2760 $enum_set_values[] = $working;
2761 $in_string = false;
2763 // Otherwise, this is a 'double quote', and can be added to the working string
2764 } elseif ($next == "'") {
2765 $working .= "'";
2766 // Skip the next char; we already know what it is
2767 $index++;
2770 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2771 // escaping of a quote?
2772 $working .= "'";
2773 $index++;
2774 } else {
2775 // Otherwise, add it to our working string like normal
2776 $working .= $char;
2778 // Increment character index
2779 $index++;
2780 } // end while
2781 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2782 $binary = false;
2783 $unsigned = false;
2784 $zerofill = false;
2785 } else {
2786 $enum_set_values = array();
2788 /* Create printable type name */
2789 $printtype = strtolower($fieldspec);
2791 // strip the "BINARY" attribute, except if we find "BINARY(" because
2792 // this would be a BINARY or VARBINARY field type
2793 if (!preg_match('@binary[\(]@', $printtype)) {
2794 $binary = strpos($printtype, 'blob') !== false || strpos($printtype, 'binary') !== false;
2795 $printtype = preg_replace('@binary@', '', $printtype);
2796 } else {
2797 $binary = false;
2799 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2800 $zerofill = ($zerofill_cnt > 0);
2801 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
2802 $unsigned = ($unsigned_cnt > 0);
2803 $printtype = trim($printtype);
2807 $attribute = ' ';
2808 if ($binary) {
2809 $attribute = 'BINARY';
2811 if ($unsigned) {
2812 $attribute = 'UNSIGNED';
2814 if ($zerofill) {
2815 $attribute = 'UNSIGNED ZEROFILL';
2818 return array(
2819 'type' => $type,
2820 'spec_in_brackets' => $spec_in_brackets,
2821 'enum_set_values' => $enum_set_values,
2822 'print_type' => $printtype,
2823 'binary' => $binary,
2824 'unsigned' => $unsigned,
2825 'zerofill' => $zerofill,
2826 'attribute' => $attribute,
2831 * Verifies if this table's engine supports foreign keys
2833 * @param string $engine
2835 * @return boolean
2837 function PMA_foreignkey_supported($engine)
2839 $engine = strtoupper($engine);
2840 if ('INNODB' == $engine || 'PBXT' == $engine) {
2841 return true;
2842 } else {
2843 return false;
2848 * Replaces some characters by a displayable equivalent
2850 * @param string $content
2852 * @return string the content with characters replaced
2854 function PMA_replace_binary_contents($content)
2856 $result = str_replace("\x00", '\0', $content);
2857 $result = str_replace("\x08", '\b', $result);
2858 $result = str_replace("\x0a", '\n', $result);
2859 $result = str_replace("\x0d", '\r', $result);
2860 $result = str_replace("\x1a", '\Z', $result);
2861 return $result;
2865 * Converts GIS data to Well Known Text format
2867 * @param $data GIS data
2868 * @param $includeSRID Add SRID to the WKT
2869 * @return GIS data in Well Know Text format
2871 function PMA_asWKT($data, $includeSRID = false) {
2872 // Convert to WKT format
2873 $hex = bin2hex($data);
2874 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
2875 if ($includeSRID) {
2876 $wktsql .= ", SRID(x'" . $hex . "')";
2878 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
2879 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
2880 $wktval = $wktarr[0];
2881 if ($includeSRID) {
2882 $srid = $wktarr[1];
2883 $wktval = "'" . $wktval . "'," . $srid;
2885 @PMA_DBI_free_result($wktresult);
2886 return $wktval;
2890 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2892 * @param string $string
2894 * @return string with the chars replaced
2897 function PMA_duplicateFirstNewline($string)
2899 $first_occurence = strpos($string, "\r\n");
2900 if ($first_occurence === 0) {
2901 $string = "\n".$string;
2903 return $string;
2907 * Get the action word corresponding to a script name
2908 * in order to display it as a title in navigation panel
2910 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2911 * or $cfg['DefaultTabDatabase']
2913 * @return array
2915 function PMA_getTitleForTarget($target)
2917 $mapping = array(
2918 // Values for $cfg['DefaultTabTable']
2919 'tbl_structure.php' => __('Structure'),
2920 'tbl_sql.php' => __('SQL'),
2921 'tbl_select.php' =>__('Search'),
2922 'tbl_change.php' =>__('Insert'),
2923 'sql.php' => __('Browse'),
2925 // Values for $cfg['DefaultTabDatabase']
2926 'db_structure.php' => __('Structure'),
2927 'db_sql.php' => __('SQL'),
2928 'db_search.php' => __('Search'),
2929 'db_operations.php' => __('Operations'),
2931 return $mapping[$target];
2935 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2937 * @param string $string Text where to do expansion.
2938 * @param function $escape Function to call for escaping variable values.
2939 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2941 * @return string
2943 function PMA_expandUserString($string, $escape = null, $updates = array())
2945 /* Content */
2946 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2947 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2948 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2949 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2950 $vars['database'] = $GLOBALS['db'];
2951 $vars['table'] = $GLOBALS['table'];
2952 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2954 /* Update forced variables */
2955 foreach ($updates as $key => $val) {
2956 $vars[$key] = $val;
2959 /* Replacement mapping */
2961 * The __VAR__ ones are for backward compatibility, because user
2962 * might still have it in cookies.
2964 $replace = array(
2965 '@HTTP_HOST@' => $vars['http_host'],
2966 '@SERVER@' => $vars['server_name'],
2967 '__SERVER__' => $vars['server_name'],
2968 '@VERBOSE@' => $vars['server_verbose'],
2969 '@VSERVER@' => $vars['server_verbose_or_name'],
2970 '@DATABASE@' => $vars['database'],
2971 '__DB__' => $vars['database'],
2972 '@TABLE@' => $vars['table'],
2973 '__TABLE__' => $vars['table'],
2974 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2977 /* Optional escaping */
2978 if (!is_null($escape)) {
2979 foreach ($replace as $key => $val) {
2980 $replace[$key] = $escape($val);
2984 /* Fetch fields list if required */
2985 if (strpos($string, '@FIELDS@') !== false) {
2986 $fields_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
2988 $field_names = array();
2989 foreach ($fields_list as $field) {
2990 if (!is_null($escape)) {
2991 $field_names[] = $escape($field['Field']);
2992 } else {
2993 $field_names[] = $field['Field'];
2997 $replace['@FIELDS@'] = implode(',', $field_names);
3000 /* Do the replacement */
3001 return strtr(strftime($string), $replace);
3005 * function that generates a json output for an ajax request and ends script
3006 * execution
3008 * @param PMA_Message|string $message message string containing the html of the message
3009 * @param bool $success success whether the ajax request was successfull
3010 * @param array $extra_data extra_data optional - any other data as part of the json request
3012 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3014 $response = array();
3015 if ( $success == true ) {
3016 $response['success'] = true;
3017 if ($message instanceof PMA_Message) {
3018 $response['message'] = $message->getDisplay();
3020 else {
3021 $response['message'] = $message;
3024 else {
3025 $response['success'] = false;
3026 if ($message instanceof PMA_Message) {
3027 $response['error'] = $message->getDisplay();
3029 else {
3030 $response['error'] = $message;
3034 // If extra_data has been provided, append it to the response array
3035 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3036 $response = array_merge($response, $extra_data);
3039 // Set the Content-Type header to JSON so that jQuery parses the
3040 // response correctly.
3042 // At this point, other headers might have been sent;
3043 // even if $GLOBALS['is_header_sent'] is true,
3044 // we have to send these additional headers.
3045 header('Cache-Control: no-cache');
3046 header("Content-Type: application/json");
3048 echo json_encode($response);
3050 if (!defined('TESTSUITE'))
3051 exit;
3055 * Display the form used to browse anywhere on the local server for the file to import
3057 * @param $max_upload_size
3059 function PMA_browseUploadFile($max_upload_size)
3061 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3062 echo '<div id="upload_form_status" style="display: none;"></div>';
3063 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3064 echo '<input type="file" name="import_file" id="input_import_file" />';
3065 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3066 // some browsers should respect this :)
3067 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3071 * Display the form used to select a file to import from the server upload directory
3073 * @param $import_list
3074 * @param $uploaddir
3076 function PMA_selectUploadFile($import_list, $uploaddir)
3078 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3079 $extensions = '';
3080 foreach ($import_list as $key => $val) {
3081 if (!empty($extensions)) {
3082 $extensions .= '|';
3084 $extensions .= $val['extension'];
3086 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
3088 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
3089 if ($files === false) {
3090 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
3091 } elseif (!empty($files)) {
3092 echo "\n";
3093 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3094 echo ' <option value="">&nbsp;</option>' . "\n";
3095 echo $files;
3096 echo ' </select>' . "\n";
3097 } elseif (empty ($files)) {
3098 echo '<i>' . __('There are no files to upload') . '</i>';
3103 * Build titles and icons for action links
3105 * @return array the action titles
3107 function PMA_buildActionTitles()
3109 $titles = array();
3111 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3112 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3113 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3114 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3115 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3116 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3117 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3118 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3119 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3120 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3121 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3122 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3123 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3124 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3125 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3126 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3127 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3128 return $titles;
3132 * This function processes the datatypes supported by the DB, as specified in
3133 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3134 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3136 * @param bool $html Whether to generate an html snippet or an array
3137 * @param string $selected The value to mark as selected in HTML mode
3139 * @return mixed An HTML snippet or an array of datatypes.
3142 function PMA_getSupportedDatatypes($html = false, $selected = '')
3144 global $cfg;
3146 if ($html) {
3147 // NOTE: the SELECT tag in not included in this snippet.
3148 $retval = '';
3149 foreach ($cfg['ColumnTypes'] as $key => $value) {
3150 if (is_array($value)) {
3151 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3152 foreach ($value as $subvalue) {
3153 if ($subvalue == $selected) {
3154 $retval .= "<option selected='selected'>";
3155 $retval .= $subvalue;
3156 $retval .= "</option>";
3157 } else if ($subvalue === '-') {
3158 $retval .= "<option disabled='disabled'>";
3159 $retval .= $subvalue;
3160 $retval .= "</option>";
3161 } else {
3162 $retval .= "<option>$subvalue</option>";
3165 $retval .= '</optgroup>';
3166 } else {
3167 if ($selected == $value) {
3168 $retval .= "<option selected='selected'>$value</option>";
3169 } else {
3170 $retval .= "<option>$value</option>";
3174 } else {
3175 $retval = array();
3176 foreach ($cfg['ColumnTypes'] as $value) {
3177 if (is_array($value)) {
3178 foreach ($value as $subvalue) {
3179 if ($subvalue !== '-') {
3180 $retval[] = $subvalue;
3183 } else {
3184 if ($value !== '-') {
3185 $retval[] = $value;
3191 return $retval;
3192 } // end PMA_getSupportedDatatypes()
3195 * Returns a list of datatypes that are not (yet) handled by PMA.
3196 * Used by: tbl_change.php and libraries/db_routines.inc.php
3198 * @return array list of datatypes
3201 function PMA_unsupportedDatatypes() {
3202 $no_support_types = array();
3203 return $no_support_types;
3206 function PMA_getGISDatatypes($upper_case = false) {
3207 $gis_data_types = array('geometry',
3208 'point',
3209 'linestring',
3210 'polygon',
3211 'multipoint',
3212 'multilinestring',
3213 'multipolygon',
3214 'geometrycollection'
3216 if ($upper_case) {
3217 for ($i = 0; $i < count($gis_data_types); $i++) {
3218 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3222 return $gis_data_types;
3226 * Generates GIS data based on the string passed.
3228 * @param string $gis_string GIS string
3230 function PMA_createGISData($gis_string) {
3231 $gis_string = trim($gis_string);
3232 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3233 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3234 return 'GeomFromText(' . $gis_string . ')';
3235 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3236 return "GeomFromText('" . $gis_string . "')";
3237 } else {
3238 return $gis_string;
3243 * Returns the names and details of the functions
3244 * that can be applied on geometry data typess.
3246 * @param string $geom_type if provided the output is limited to the functions
3247 * that are applicable to the provided geometry type.
3248 * @param bool $binary if set to false functions that take two geometries
3249 * as arguments will not be included.
3250 * @param bool $display if set to true seperators will be added to the
3251 * output array.
3253 * @return array names and details of the functions that can be applied on
3254 * geometry data typess.
3256 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false) {
3258 $funcs = array();
3259 if ($display) {
3260 $funcs[] = array('display' => ' ');
3263 // Unary functions common to all geomety types
3264 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3265 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3266 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3267 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3268 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3269 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3271 $geom_type = trim(strtolower($geom_type));
3272 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3273 $funcs[] = array('display' => '--------');
3276 // Unary functions that are specific to each geomety type
3277 if ($geom_type == 'point') {
3278 $funcs['X'] = array('params' => 1, 'type' => 'float');
3279 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3281 } elseif ($geom_type == 'multipoint') {
3282 // no fucntions here
3283 } elseif ($geom_type == 'linestring') {
3284 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3285 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3286 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3287 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3288 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3290 } elseif ($geom_type == 'multilinestring') {
3291 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3292 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3294 } elseif ($geom_type == 'polygon') {
3295 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3296 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3297 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3299 } elseif ($geom_type == 'multipolygon') {
3300 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3301 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3302 // Not yet implemented in MySQL
3303 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3305 } elseif ($geom_type == 'geometrycollection') {
3306 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3309 // If we are asked for binary functions as well
3310 if ($binary) {
3311 // section seperator
3312 if ($display) {
3313 $funcs[] = array('display' => '--------');
3315 if (PMA_MYSQL_INT_VERSION < 50601) {
3316 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3317 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3318 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3319 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3320 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3321 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3322 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3323 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3324 } else {
3325 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3326 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3327 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3328 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3329 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3330 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3331 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3332 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3333 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3337 if ($display) {
3338 $funcs[] = array('display' => '--------');
3340 // Minimum bounding rectangle functions
3341 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3342 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3343 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3344 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3345 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3346 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3347 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3349 return $funcs;
3353 * Creates a dropdown box with MySQL functions for a particular column.
3355 * @param array $field Data about the column for which
3356 * to generate the dropdown
3357 * @param bool $insert_mode Whether the operation is 'insert'
3359 * @global array $cfg PMA configuration
3360 * @global array $analyzed_sql Analyzed SQL query
3361 * @global mixed $data (null/string) FIXME: what is this for?
3363 * @return string An HTML snippet of a dropdown list with function
3364 * names appropriate for the requested column.
3366 function PMA_getFunctionsForField($field, $insert_mode)
3368 global $cfg, $analyzed_sql, $data;
3370 $selected = '';
3371 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3372 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3373 // which will then reveal the available dropdown options
3374 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3375 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3377 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3378 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3379 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3380 } else {
3381 $dropdown = array();
3382 $default_function = '';
3384 $dropdown_built = array();
3385 $op_spacing_needed = false;
3386 // what function defined as default?
3387 // for the first timestamp we don't set the default function
3388 // if there is a default value for the timestamp
3389 // (not including CURRENT_TIMESTAMP)
3390 // and the column does not have the
3391 // ON UPDATE DEFAULT TIMESTAMP attribute.
3392 if ($field['True_Type'] == 'timestamp'
3393 && empty($field['Default'])
3394 && empty($data)
3395 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3397 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3399 // For primary keys of type char(36) or varchar(36) UUID if the default function
3400 // Only applies to insert mode, as it would silently trash data on updates.
3401 if ($insert_mode
3402 && $field['Key'] == 'PRI'
3403 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3405 $default_function = $cfg['DefaultFunctions']['pk_char36'];
3407 // this is set only when appropriate and is always true
3408 if (isset($field['display_binary_as_hex'])) {
3409 $default_function = 'UNHEX';
3412 // Create the output
3413 $retval = ' <option></option>' . "\n";
3414 // loop on the dropdown array and print all available options for that field.
3415 foreach ($dropdown as $each_dropdown) {
3416 $retval .= ' ';
3417 $retval .= '<option';
3418 if ($default_function === $each_dropdown) {
3419 $retval .= ' selected="selected"';
3421 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3422 $dropdown_built[$each_dropdown] = 'true';
3423 $op_spacing_needed = true;
3425 // For compatibility's sake, do not let out all other functions. Instead
3426 // print a separator (blank) and then show ALL functions which weren't shown
3427 // yet.
3428 $cnt_functions = count($cfg['Functions']);
3429 for ($j = 0; $j < $cnt_functions; $j++) {
3430 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3431 // Is current function defined as default?
3432 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3433 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3434 ? ' selected="selected"'
3435 : '';
3436 if ($op_spacing_needed == true) {
3437 $retval .= ' ';
3438 $retval .= '<option value="">--------</option>' . "\n";
3439 $op_spacing_needed = false;
3442 $retval .= ' ';
3443 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3445 } // end for
3447 return $retval;
3448 } // end PMA_getFunctionsForField()
3451 * Checks if the current user has a specific privilege and returns true if the
3452 * user indeed has that privilege or false if (s)he doesn't. This function must
3453 * only be used for features that are available since MySQL 5, because it
3454 * relies on the INFORMATION_SCHEMA database to be present.
3456 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3457 * // Checks if the currently logged in user has the global
3458 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3459 * // user has this privilege on database 'mydb'.
3462 * @param string $priv The privilege to check
3463 * @param mixed $db null, to only check global privileges
3464 * string, db name where to also check for privileges
3465 * @param mixed $tbl null, to only check global privileges
3466 * string, db name where to also check for privileges
3468 * @return bool
3470 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3472 // Get the username for the current user in the format
3473 // required to use in the information schema database.
3474 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3475 if ($user === false) {
3476 return false;
3478 $user = explode('@', $user);
3479 $username = "''";
3480 $username .= str_replace("'", "''", $user[0]);
3481 $username .= "''@''";
3482 $username .= str_replace("'", "''", $user[1]);
3483 $username .= "''";
3484 // Prepage the query
3485 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3486 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3487 // Check global privileges first.
3488 if (PMA_DBI_fetch_value(sprintf($query,
3489 'USER_PRIVILEGES',
3490 $username,
3491 $priv))) {
3492 return true;
3494 // If a database name was provided and user does not have the
3495 // required global privilege, try database-wise permissions.
3496 if ($db !== null) {
3497 $query .= " AND TABLE_SCHEMA='%s'";
3498 if (PMA_DBI_fetch_value(sprintf($query,
3499 'SCHEMA_PRIVILEGES',
3500 $username,
3501 $priv,
3502 PMA_sqlAddSlashes($db)))) {
3503 return true;
3505 } else {
3506 // There was no database name provided and the user
3507 // does not have the correct global privilege.
3508 return false;
3510 // If a table name was also provided and we still didn't
3511 // find any valid privileges, try table-wise privileges.
3512 if ($tbl !== null) {
3513 $query .= " AND TABLE_NAME='%s'";
3514 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3515 'TABLE_PRIVILEGES',
3516 $username,
3517 $priv,
3518 PMA_sqlAddSlashes($db),
3519 PMA_sqlAddSlashes($tbl)))) {
3520 return true;
3523 // If we reached this point, the user does not
3524 // have even valid table-wise privileges.
3525 return false;