2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Misc functions used all over the scripts.
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
19 } elseif (function_exists('gmp_pow')) {
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) {
52 switch ($use_function) {
54 // bcscale() needed for testing PMA_pow() with base values < 1
56 $pow = bcpow($base, $exp);
59 $pow = gmp_strval(gmp_pow($base, $exp));
62 $base = (float) $base;
64 $pow = pow($base, $exp);
67 $pow = $use_function($base, $exp);
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
82 * @return html img tag
84 function PMA_getIcon($icon, $alternate = '', $force_text = false, $noSprite = false)
86 // $cfg['PropertiesIconic'] is true or both
87 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
88 // $cfg['PropertiesIconic'] is false or both
89 // OR we have no $include_icon
90 $include_text = ($force_text ||
true !== $GLOBALS['cfg']['PropertiesIconic']);
91 $alternate = htmlspecialchars($alternate);
94 // Always use a span (we rely on this in js/sql.js)
95 $button .= '<span class="nowrap">';
99 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
100 . ' class="icon" width="16" height="16" />';
102 $button .= '<img src="themes/dot.gif"' . ' title="'
103 . $alternate . '" alt="' . $alternate . '"' . ' class="icon ic_'
104 . str_replace(array('.gif','.png'), '', $icon) . '" />';
108 if ($include_icon && $include_text) {
113 $button .= $alternate;
116 $button .= '</span>';
122 * Displays the maximum size for an upload
124 * @param integer $max_upload_size the size
126 * @return string the message
130 function PMA_displayMaximumUploadSize($max_upload_size)
132 // I have to reduce the second parameter (sensitiveness) from 6 to 4
133 // to avoid weird results like 512 kKib
134 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
135 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
139 * Generates a hidden field which should indicate to the browser
140 * the maximum size for upload
142 * @param integer $max_size the size
144 * @return string the INPUT field
148 function PMA_generateHiddenMaxFileSize($max_size)
150 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
154 * Add slashes before "'" and "\" characters so a value containing them can
155 * be used in a sql comparison.
157 * @param string $a_string the string to slash
158 * @param bool $is_like whether the string will be used in a 'LIKE' clause
159 * (it then requires two more escaped sequences) or not
160 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
161 * (converts \n to \\n, \r to \\r)
162 * @param bool $php_code whether this function is used as part of the
163 * "Create PHP code" dialog
165 * @return string the slashed string
169 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
172 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
174 $a_string = str_replace('\\', '\\\\', $a_string);
180 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
185 $a_string = str_replace('\'', '\\\'', $a_string);
187 $a_string = str_replace('\'', '\'\'', $a_string);
191 } // end of the 'PMA_sqlAddSlashes()' function
195 * Add slashes before "_" and "%" characters for using them in MySQL
196 * database, table and field names.
197 * Note: This function does not escape backslashes!
199 * @param string $name the string to escape
201 * @return string the escaped string
205 function PMA_escape_mysql_wildcards($name)
207 return strtr($name, array('_' => '\\_', '%' => '\\%'));
208 } // end of the 'PMA_escape_mysql_wildcards()' function
211 * removes slashes before "_" and "%" characters
212 * Note: This function does not unescape backslashes!
214 * @param string $name the string to escape
216 * @return string the escaped string
220 function PMA_unescape_mysql_wildcards($name)
222 return strtr($name, array('\\_' => '_', '\\%' => '%'));
223 } // end of the 'PMA_unescape_mysql_wildcards()' function
226 * removes quotes (',",`) from a quoted string
228 * checks if the sting is quoted and removes this quotes
230 * @param string $quoted_string string to remove quotes from
231 * @param string $quote type of quote to remove
233 * @return string unqoted string
235 function PMA_unQuote($quoted_string, $quote = null)
239 if (null === $quote) {
247 foreach ($quotes as $quote) {
248 if (substr($quoted_string, 0, 1) === $quote
249 && substr($quoted_string, -1, 1) === $quote
251 $unquoted_string = substr($quoted_string, 1, -1);
252 // replace escaped quotes
253 $unquoted_string = str_replace(
258 return $unquoted_string;
262 return $quoted_string;
268 * @param mixed $parsed_sql pre-parsed SQL structure
269 * @param string $unparsed_sql raw SQL string
271 * @return string the formatted sql
273 * @global array the configuration array
274 * @global boolean whether the current statement is a multiple one or not
277 * @todo move into PMA_Sql
279 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
283 // Check that we actually have a valid set of parsed data
285 // first check for the SQL parser having hit an error
286 if (PMA_SQP_isError()) {
287 return htmlspecialchars($parsed_sql['raw']);
289 // then check for an array
290 if (! is_array($parsed_sql)) {
291 // We don't so just return the input directly
292 // This is intended to be used for when the SQL Parser is turned off
293 $formatted_sql = "<pre>\n";
294 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
295 $formatted_sql .= $unparsed_sql;
297 $formatted_sql .= $parsed_sql;
299 $formatted_sql .= "\n</pre>";
300 return $formatted_sql;
305 switch ($cfg['SQP']['fmtType']) {
307 if ($unparsed_sql != '') {
308 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
309 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
312 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
316 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
319 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
325 return $formatted_sql;
326 } // end of the "PMA_formatSql()" function
330 * Displays a link to the official MySQL documentation
332 * @param string $chapter chapter of "HTML, one page per chapter" documentation
333 * @param string $link contains name of page/anchor that is being linked
334 * @param bool $big_icon whether to use big icon (like in left frame)
335 * @param string $anchor anchor to page part
336 * @param bool $just_open whether only the opening <a> tag should be returned
338 * @return string the html link
342 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
346 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
350 // Fixup for newly used names:
351 $chapter = str_replace('_', '-', strtolower($chapter));
352 $link = str_replace('_', '-', strtolower($link));
354 switch ($cfg['MySQLManualType']) {
356 if (empty($chapter)) {
359 if (empty($anchor)) {
362 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
365 if (empty($anchor)) {
368 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
374 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
375 if (!empty($anchor)) {
376 $url .= '#' . $anchor;
386 if (defined('PMA_MYSQL_INT_VERSION')) {
387 if (PMA_MYSQL_INT_VERSION
>= 50500) {
389 /* l10n: Please check that translation actually exists. */
390 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
391 } else if (PMA_MYSQL_INT_VERSION
>= 50100) {
393 /* l10n: Please check that translation actually exists. */
394 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
397 /* l10n: Please check that translation actually exists. */
398 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
401 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
402 if (!empty($anchor)) {
403 $url .= '#' . $anchor;
408 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
411 } elseif ($big_icon) {
412 return $open_link . '<img class="icon ic_b_sqlhelp" src="themes/dot.gif" alt="'
413 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
414 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
415 return $open_link . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="'
416 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
418 return '[' . $open_link . __('Documentation') . '</a>]';
420 } // end of the 'PMA_showMySQLDocu()' function
424 * Displays a link to the phpMyAdmin documentation
426 * @param string $anchor anchor in documentation
428 * @return string the html link
432 function PMA_showDocu($anchor)
434 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
435 return '<a href="Documentation.html#' . $anchor . '" target="documentation">'
436 . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="'
437 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
439 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">'
440 . __('Documentation') . '</a>]';
442 } // end of the 'PMA_showDocu()' function
445 * Displays a link to the PHP documentation
447 * @param string $target anchor in documentation
449 * @return string the html link
453 function PMA_showPHPDocu($target)
455 $url = PMA_getPHPDocLink($target);
457 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
458 return '<a href="' . $url . '" target="documentation">'
459 . '<img class="icon ic_b_help_s" src="themes/dot.gif" alt="'
460 . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
462 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
464 } // end of the 'PMA_showPHPDocu()' function
467 * returns HTML for a footnote marker and add the messsage to the footnotes
469 * @param string $message the error message
470 * @param bool $bbcode
471 * @param string $type message types
473 * @return string html code for a footnote marker
477 function PMA_showHint($message, $bbcode = false, $type = 'notice')
479 if ($message instanceof PMA_Message
) {
480 $key = $message->getHash();
481 $type = $message->getLevel();
483 $key = md5($message);
486 if (! isset($GLOBALS['footnotes'][$key])) {
487 if (empty($GLOBALS['footnotes']) ||
! is_array($GLOBALS['footnotes'])) {
488 $GLOBALS['footnotes'] = array();
490 $nr = count($GLOBALS['footnotes']) +
1;
491 $GLOBALS['footnotes'][$key] = array(
497 $nr = $GLOBALS['footnotes'][$key]['nr'];
501 return '[sup]' . $nr . '[/sup]';
504 // footnotemarker used in js/tooltip.js
505 return '<sup class="footnotemarker">' . $nr . '</sup>' .
506 '<img class="footnotemarker footnote_' . $nr . ' ic_b_help" src="themes/dot.gif" alt="" />';
510 * Displays a MySQL error message in the right frame.
512 * @param string $error_message the error message
513 * @param string $the_query the sql query that failed
514 * @param bool $is_modify_link whether to show a "modify" link or not
515 * @param string $back_url the "back" link url (full path is not required)
516 * @param bool $exit EXIT the page?
518 * @global string the curent table
519 * @global string the current db
523 function PMA_mysqlDie($error_message = '', $the_query = '',
524 $is_modify_link = true, $back_url = '', $exit = true)
529 * start http output, display html headers
531 include_once './libraries/header.inc.php';
533 $error_msg_output = '';
535 if (!$error_message) {
536 $error_message = PMA_DBI_getError();
538 if (!$the_query && !empty($GLOBALS['sql_query'])) {
539 $the_query = $GLOBALS['sql_query'];
542 // --- Added to solve bug #641765
543 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
544 $formatted_sql = htmlspecialchars($the_query);
545 } elseif (empty($the_query) ||
trim($the_query) == '') {
548 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
549 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
551 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
555 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
556 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
557 // if the config password is wrong, or the MySQL server does not
558 // respond, do not show the query that would reveal the
560 if (!empty($the_query) && !strstr($the_query, 'connect')) {
561 // --- Added to solve bug #641765
562 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
563 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
564 $error_msg_output .= '<br />' . "\n";
567 // modified to show the help on sql errors
568 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
569 if (strstr(strtolower($formatted_sql), 'select')) {
570 // please show me help to the error on select
571 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
573 if ($is_modify_link) {
574 $_url_params = array(
575 'sql_query' => $the_query,
578 if (strlen($table)) {
579 $_url_params['db'] = $db;
580 $_url_params['table'] = $table;
581 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
582 } elseif (strlen($db)) {
583 $_url_params['db'] = $db;
584 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
586 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
589 $error_msg_output .= $doedit_goto
590 . PMA_getIcon('b_edit.png', __('Edit'))
593 $error_msg_output .= ' </p>' . "\n"
595 .' ' . $formatted_sql . "\n"
599 if (! empty($error_message)) {
600 $error_message = preg_replace(
601 "@((\015\012)|(\015)|(\012)){3,}@",
606 // modified to show the help on error-returns
607 // (now error-messages-server)
608 $error_msg_output .= '<p>' . "\n"
609 . ' <strong>' . __('MySQL said: ') . '</strong>'
610 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
614 // The error message will be displayed within a CODE segment.
615 // To preserve original formatting, but allow wordwrapping,
616 // we do a couple of replacements
618 // Replace all non-single blanks with their HTML-counterpart
619 $error_message = str_replace(' ', ' ', $error_message);
620 // Replace TAB-characters with their HTML-counterpart
621 $error_message = str_replace("\t", ' ', $error_message);
622 // Replace linebreaks
623 $error_message = nl2br($error_message);
625 $error_msg_output .= '<code>' . "\n"
626 . $error_message . "\n"
627 . '</code><br />' . "\n";
628 $error_msg_output .= '</div>';
630 $_SESSION['Import_message']['message'] = $error_msg_output;
634 * If in an Ajax request
635 * - avoid displaying a Back link
636 * - use PMA_ajaxResponse() to transmit the message and exit
638 if ($GLOBALS['is_ajax_request'] == true) {
639 PMA_ajaxResponse($error_msg_output, false);
641 if (! empty($back_url)) {
642 if (strstr($back_url, '?')) {
643 $back_url .= '&no_history=true';
645 $back_url .= '?no_history=true';
648 $_SESSION['Import_message']['go_back_url'] = $back_url;
650 $error_msg_output .= '<fieldset class="tblFooters">';
651 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
652 $error_msg_output .= '</fieldset>' . "\n\n";
655 echo $error_msg_output;
657 * display footer and exit
659 include './libraries/footer.inc.php';
661 echo $error_msg_output;
663 } // end of the 'PMA_mysqlDie()' function
666 * returns array with tables of given db with extended information and grouped
668 * @param string $db name of db
669 * @param string $tables name of tables
670 * @param integer $limit_offset list offset
671 * @param int|bool $limit_count max tables to return
673 * @return array (recursive) grouped table list
675 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
677 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
679 if (null === $tables) {
680 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
681 if ($GLOBALS['cfg']['NaturalOrder']) {
682 uksort($tables, 'strnatcasecmp');
686 if (count($tables) < 1) {
697 $table_groups = array();
699 // for blobstreaming - list of blobstreaming tables
701 // load PMA configuration
702 $PMA_Config = $GLOBALS['PMA_Config'];
704 foreach ($tables as $table_name => $table) {
705 // if BS tables exist
706 if (PMA_BS_IsHiddenTable($table_name)) {
710 // check for correct row count
711 if (null === $table['Rows']) {
712 // Do not check exact row count here,
713 // if row count is invalid possibly the table is defect
714 // and this would break left frame;
715 // but we can check row count if this is a view or the
716 // information_schema database
717 // since PMA_Table::countRecords() returns a limited row count
720 // set this because PMA_Table::countRecords() can use it
721 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
723 if ($tbl_is_view ||
'information_schema' == $db) {
724 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name']);
728 // in $group we save the reference to the place in $table_groups
729 // where to store the table info
730 if ($GLOBALS['cfg']['LeftFrameDBTree']
731 && $sep && strstr($table_name, $sep)
733 $parts = explode($sep, $table_name);
735 $group =& $table_groups;
737 $group_name_full = '';
738 $parts_cnt = count($parts) - 1;
739 while ($i < $parts_cnt
740 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
741 $group_name = $parts[$i] . $sep;
742 $group_name_full .= $group_name;
744 if (! isset($group[$group_name])) {
745 $group[$group_name] = array();
746 $group[$group_name]['is' . $sep . 'group'] = true;
747 $group[$group_name]['tab' . $sep . 'count'] = 1;
748 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
749 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
750 $table = $group[$group_name];
751 $group[$group_name] = array();
752 $group[$group_name][$group_name] = $table;
754 $group[$group_name]['is' . $sep . 'group'] = true;
755 $group[$group_name]['tab' . $sep . 'count'] = 1;
756 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
758 $group[$group_name]['tab' . $sep . 'count']++
;
760 $group =& $group[$group_name];
764 if (! isset($table_groups[$table_name])) {
765 $table_groups[$table_name] = array();
767 $group =& $table_groups;
771 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
772 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
774 // switch tooltip and name
775 $table['Comment'] = $table['Name'];
776 $table['disp_name'] = $table['Comment'];
778 $table['disp_name'] = $table['Name'];
781 $group[$table_name] = array_merge($default, $table);
784 return $table_groups;
787 /* ----------------------- Set of misc functions ----------------------- */
791 * Adds backquotes on both sides of a database, table or field name.
792 * and escapes backquotes inside the name with another backquote
796 * echo PMA_backquote('owner`s db'); // `owner``s db`
800 * @param mixed $a_name the database, table or field name to "backquote"
802 * @param boolean $do_it a flag to bypass this function (used by dump
805 * @return mixed the "backquoted" database, table or field name
809 function PMA_backquote($a_name, $do_it = true)
811 if (is_array($a_name)) {
812 foreach ($a_name as &$data) {
813 $data = PMA_backquote($data, $do_it);
819 global $PMA_SQPdata_forbidden_word;
821 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
826 // '0' is also empty for php :-(
827 if (strlen($a_name) && $a_name !== '*') {
828 return '`' . str_replace('`', '``', $a_name) . '`';
832 } // end of the 'PMA_backquote()' function
835 * Defines the <CR><LF> value depending on the user OS.
837 * @return string the <CR><LF> value to use
841 function PMA_whichCrlf()
843 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
845 if (PMA_USR_OS
== 'Win') {
853 } // end of the 'PMA_whichCrlf()' function
856 * Reloads navigation if needed.
858 * @param bool $jsonly prints out pure JavaScript
862 function PMA_reloadNavigation($jsonly=false)
864 // Reloads the navigation frame via JavaScript if required
865 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
866 // one of the reasons for a reload is when a table is dropped
867 // in this case, get rid of the table limit offset, otherwise
868 // we have a problem when dropping a table on the last page
869 // and the offset becomes greater than the total number of tables
870 unset($_SESSION['tmp_user_values']['table_limit_offset']);
872 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
874 echo '<script type="text/javascript">' . PHP_EOL
;
878 if (typeof(window
.parent
) != 'undefined'
879 && typeof(window
.parent
.frame_navigation
) != 'undefined'
880 && window
.parent
.goTo) {
881 window
.parent
.goTo('<?php echo $reload_url; ?>');
886 echo '</script>' . PHP_EOL
;
889 unset($GLOBALS['reload']);
894 * displays the message and the query
895 * usually the message is the result of the query executed
897 * @param string $message the message to display
898 * @param string $sql_query the query to display
899 * @param string $type the type (level) of the message
900 * @param boolean $is_view is this a message after a VIEW operation?
906 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
909 * PMA_ajaxResponse uses this function to collect the string of HTML generated
910 * for showing the message. Use output buffering to collect it and return it
911 * in a string. In some special cases on sql.php, buffering has to be disabled
912 * and hence we check with $GLOBALS['buffer_message']
914 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
919 if (null === $sql_query) {
920 if (! empty($GLOBALS['display_query'])) {
921 $sql_query = $GLOBALS['display_query'];
922 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
923 $sql_query = $GLOBALS['unparsed_sql'];
924 } elseif (! empty($GLOBALS['sql_query'])) {
925 $sql_query = $GLOBALS['sql_query'];
931 if (isset($GLOBALS['using_bookmark_message'])) {
932 $GLOBALS['using_bookmark_message']->display();
933 unset($GLOBALS['using_bookmark_message']);
936 // Corrects the tooltip text via JS if required
937 // @todo this is REALLY the wrong place to do this - very unexpected here
938 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
939 $tooltip = PMA_Table
::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
940 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
942 echo '<script type="text/javascript">' . "\n";
943 echo '//<![CDATA[' . "\n";
944 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
945 . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
947 echo '</script>' . "\n";
948 } // end if ... elseif
950 // Checks if the table needs to be repaired after a TRUNCATE query.
951 // @todo what about $GLOBALS['display_query']???
952 // @todo this is REALLY the wrong place to do this - very unexpected here
953 if (strlen($GLOBALS['table'])
954 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
956 if (PMA_Table
::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
957 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
962 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
963 // check for it's presence before using it
964 echo '<div id="result_query" align="'
965 . ( isset($GLOBALS['cell_align_left']) ?
$GLOBALS['cell_align_left'] : '' )
968 if ($message instanceof PMA_Message
) {
969 if (isset($GLOBALS['special_message'])) {
970 $message->addMessage($GLOBALS['special_message']);
971 unset($GLOBALS['special_message']);
974 $type = $message->getLevel();
976 echo '<div class="' . $type . '">';
977 echo PMA_sanitize($message);
978 if (isset($GLOBALS['special_message'])) {
979 echo PMA_sanitize($GLOBALS['special_message']);
980 unset($GLOBALS['special_message']);
985 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
986 // Html format the query to be displayed
987 // If we want to show some sql code it is easiest to create it here
988 /* SQL-Parser-Analyzer */
990 if (! empty($GLOBALS['show_as_php'])) {
991 $new_line = '\\n"<br />' . "\n"
992 . ' . "';
993 $query_base = htmlspecialchars(addslashes($sql_query));
994 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
996 $query_base = $sql_query;
999 $query_too_big = false;
1001 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1002 // when the query is large (for example an INSERT of binary
1003 // data), the parser chokes; so avoid parsing the query
1004 $query_too_big = true;
1005 $shortened_query_base = nl2br(
1007 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
1010 } elseif (! empty($GLOBALS['parsed_sql'])
1011 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1012 // (here, use "! empty" because when deleting a bookmark,
1013 // $GLOBALS['parsed_sql'] is set but empty
1014 $parsed_sql = $GLOBALS['parsed_sql'];
1016 // Parse SQL if needed
1017 $parsed_sql = PMA_SQP_parse($query_base);
1018 if (PMA_SQP_isError()) {
1024 if (isset($parsed_sql)) {
1025 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1027 // Same as below (append LIMIT), append the remembered ORDER BY
1028 if ($GLOBALS['cfg']['RememberSorting']
1029 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1030 && isset($GLOBALS['sql_order_to_append'])
1032 $query_base = $analyzed_display_query[0]['section_before_limit']
1033 . "\n" . $GLOBALS['sql_order_to_append']
1034 . $analyzed_display_query[0]['section_after_limit'];
1036 // Need to reparse query
1037 $parsed_sql = PMA_SQP_parse($query_base);
1038 // update the $analyzed_display_query
1039 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1040 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1043 // Here we append the LIMIT added for navigation, to
1044 // enable its display. Adding it higher in the code
1045 // to $sql_query would create a problem when
1046 // using the Refresh or Edit links.
1048 // Only append it on SELECTs.
1051 * @todo what would be the best to do when someone hits Refresh:
1052 * use the current LIMITs ?
1055 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1056 && isset($GLOBALS['sql_limit_to_append'])
1058 $query_base = $analyzed_display_query[0]['section_before_limit']
1059 . "\n" . $GLOBALS['sql_limit_to_append']
1060 . $analyzed_display_query[0]['section_after_limit'];
1061 // Need to reparse query
1062 $parsed_sql = PMA_SQP_parse($query_base);
1066 if (! empty($GLOBALS['show_as_php'])) {
1067 $query_base = '$sql = "' . $query_base;
1068 } elseif (! empty($GLOBALS['validatequery'])) {
1070 $query_base = PMA_validateSQL($query_base);
1071 } catch (Exception
$e) {
1072 PMA_Message
::error(__('Failed to connect to SQL validator!'))->display();
1074 } elseif (isset($parsed_sql)) {
1075 $query_base = PMA_formatSql($parsed_sql, $query_base);
1078 // Prepares links that may be displayed to edit/explain the query
1079 // (don't go to default pages, we must go to the page
1080 // where the query box is available)
1082 // Basic url query part
1083 $url_params = array();
1084 if (! isset($GLOBALS['db'])) {
1085 $GLOBALS['db'] = '';
1087 if (strlen($GLOBALS['db'])) {
1088 $url_params['db'] = $GLOBALS['db'];
1089 if (strlen($GLOBALS['table'])) {
1090 $url_params['table'] = $GLOBALS['table'];
1091 $edit_link = 'tbl_sql.php';
1093 $edit_link = 'db_sql.php';
1096 $edit_link = 'server_sql.php';
1099 // Want to have the query explained
1100 // but only explain a SELECT (that has not been explained)
1101 /* SQL-Parser-Analyzer */
1104 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1105 $explain_params = $url_params;
1106 // Detect if we are validating as well
1107 // To preserve the validate uRL data
1108 if (! empty($GLOBALS['validatequery'])) {
1109 $explain_params['validatequery'] = 1;
1111 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1112 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1113 $_message = __('Explain SQL');
1115 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1116 $explain_params['sql_query'] = substr($sql_query, 8);
1117 $_message = __('Skip Explain SQL');
1119 if (isset($explain_params['sql_query'])) {
1120 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1121 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1125 $url_params['sql_query'] = $sql_query;
1126 $url_params['show_query'] = 1;
1128 // even if the query is big and was truncated, offer the chance
1129 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1130 if (! empty($cfg['SQLQuery']['Edit'])) {
1131 if ($cfg['EditInWindow'] == true) {
1132 $onclick = 'window.parent.focus_querywindow(\''
1133 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1138 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1139 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1144 $url_qpart = PMA_generate_common_url($url_params);
1146 // Also we would like to get the SQL formed in some nice
1148 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1149 $php_params = $url_params;
1151 if (! empty($GLOBALS['show_as_php'])) {
1152 $_message = __('Without PHP Code');
1154 $php_params['show_as_php'] = 1;
1155 $_message = __('Create PHP Code');
1158 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1159 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1161 if (isset($GLOBALS['show_as_php'])) {
1162 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1163 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1170 if (! empty($cfg['SQLQuery']['Refresh'])
1171 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1173 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1174 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1179 if (! empty($cfg['SQLValidator']['use'])
1180 && ! empty($cfg['SQLQuery']['Validate'])
1182 $validate_params = $url_params;
1183 if (!empty($GLOBALS['validatequery'])) {
1184 $validate_message = __('Skip Validate SQL');
1186 $validate_params['validatequery'] = 1;
1187 $validate_message = __('Validate SQL');
1190 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1191 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1193 $validate_link = '';
1196 if (!empty($GLOBALS['validatequery'])) {
1197 echo '<div class="sqlvalidate">';
1199 echo '<code class="sql">';
1201 if ($query_too_big) {
1202 echo $shortened_query_base;
1207 //Clean up the end of the PHP
1208 if (! empty($GLOBALS['show_as_php'])) {
1211 if (!empty($GLOBALS['validatequery'])) {
1217 echo '<div class="tools">';
1218 // avoid displaying a Profiling checkbox that could
1219 // be checked, which would reexecute an INSERT, for example
1220 if (! empty($refresh_link)) {
1221 PMA_profilingCheckbox($sql_query);
1223 // if needed, generate an invisible form that contains controls for the
1224 // Inline link; this way, the behavior of the Inline link does not
1225 // depend on the profiling support or on the refresh link
1226 if (empty($refresh_link) ||
! PMA_profilingSupported()) {
1227 echo '<form action="sql.php" method="post">';
1228 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1229 echo '<input type="hidden" name="sql_query" value="'
1230 . htmlspecialchars($sql_query) . '" />';
1234 // in the tools div, only display the Inline link when not in ajax
1235 // mode because 1) it currently does not work and 2) we would
1236 // have two similar mechanisms on the page for the same goal
1238 ||
$GLOBALS['is_ajax_request'] === false
1241 // see in js/functions.js the jQuery code attached to id inline_edit
1242 // document.write conflicts with jQuery, hence used $().append()
1243 echo "<script type=\"text/javascript\">\n" .
1245 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1246 PMA_escapeJsString(__('Inline edit of this query')) .
1247 "\" class=\"inline_edit_sql\">" .
1248 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1253 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1257 if ($GLOBALS['is_ajax_request'] === false) {
1258 echo '<br class="clearfloat" />';
1261 // If we are in an Ajax request, we have most probably been called in
1262 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1263 // to PMA_ajaxResponse(), which will encode it for JSON.
1264 if ($GLOBALS['is_ajax_request'] == true
1265 && ! isset($GLOBALS['buffer_message'])
1267 $buffer_contents = ob_get_contents();
1269 return $buffer_contents;
1272 } // end of the 'PMA_showMessage()' function
1275 * Verifies if current MySQL server supports profiling
1279 * @return boolean whether profiling is supported
1281 function PMA_profilingSupported()
1283 if (! PMA_cacheExists('profiling_supported', true)) {
1284 // 5.0.37 has profiling but for example, 5.1.20 does not
1285 // (avoid a trip to the server for MySQL before 5.0.37)
1286 // and do not set a constant as we might be switching servers
1287 if (defined('PMA_MYSQL_INT_VERSION')
1288 && PMA_MYSQL_INT_VERSION
>= 50037
1289 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1291 PMA_cacheSet('profiling_supported', true, true);
1293 PMA_cacheSet('profiling_supported', false, true);
1297 return PMA_cacheGet('profiling_supported', true);
1301 * Displays a form with the Profiling checkbox
1303 * @param string $sql_query sql query
1307 function PMA_profilingCheckbox($sql_query)
1309 if (PMA_profilingSupported()) {
1310 echo '<form action="sql.php" method="post">' . "\n";
1311 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1312 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1313 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1314 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1315 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1316 echo '</form>' . "\n";
1321 * Formats $value to byte view
1323 * @param double $value the value to format
1324 * @param int $limes the sensitiveness
1325 * @param int $comma the number of decimals to retain
1327 * @return array the formatted value and its unit
1331 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1334 /* l10n: shortcuts for Byte */
1336 /* l10n: shortcuts for Kilobyte */
1338 /* l10n: shortcuts for Megabyte */
1340 /* l10n: shortcuts for Gigabyte */
1342 /* l10n: shortcuts for Terabyte */
1344 /* l10n: shortcuts for Petabyte */
1346 /* l10n: shortcuts for Exabyte */
1350 $dh = PMA_pow(10, $comma);
1351 $li = PMA_pow(10, $limes);
1352 $unit = $byteUnits[0];
1354 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1355 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1356 // use 1024.0 to avoid integer overflow on 64-bit machines
1357 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1358 $unit = $byteUnits[$d];
1363 if ($unit != $byteUnits[0]) {
1364 // if the unit is not bytes (as represented in current language)
1365 // reformat with max length of 5
1366 // 4th parameter=true means do not reformat if value < 1
1367 $return_value = PMA_formatNumber($value, 5, $comma, true);
1369 // do not reformat, just handle the locale
1370 $return_value = PMA_formatNumber($value, 0);
1373 return array(trim($return_value), $unit);
1374 } // end of the 'PMA_formatByteDown' function
1377 * Changes thousands and decimal separators to locale specific values.
1379 * @param string $value the value
1383 function PMA_localizeNumber($value)
1388 /* l10n: Thousands separator */
1390 /* l10n: Decimal separator */
1398 * Formats $value to the given length and appends SI prefixes
1399 * with a $length of 0 no truncation occurs, number is only formated
1400 * to the current locale
1404 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1405 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1406 * echo PMA_formatNumber(-0.003, 6); // -3 m
1407 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1408 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1409 * echo PMA_formatNumber(0, 6); // 0
1412 * @param double $value the value to format
1413 * @param integer $digits_left number of digits left of the comma
1414 * @param integer $digits_right number of digits right of the comma
1415 * @param boolean $only_down do not reformat numbers below 1
1416 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1419 * @return string the formatted value and its unit
1423 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1424 $only_down = false, $noTrailingZero = true)
1430 $originalValue = $value;
1431 //number_format is not multibyte safe, str_replace is safe
1432 if ($digits_left === 0) {
1433 $value = number_format($value, $digits_right);
1434 if ($originalValue != 0 && floatval($value) == 0) {
1435 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1438 return PMA_localizeNumber($value);
1441 // this units needs no translation, ISO
1462 // check for negative value to retain sign
1465 $value = abs($value);
1470 $dh = PMA_pow(10, $digits_right);
1473 * This gives us the right SI prefix already,
1474 * but $digits_left parameter not incorporated
1476 $d = floor(log10($value) / 3);
1478 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1479 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1480 * to use, then lower the SI prefix
1482 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+
1);
1483 if ($digits_left > $cur_digits) {
1484 $d-= floor(($digits_left - $cur_digits)/3);
1487 if ($d<0 && $only_down) {
1491 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1494 // If we dont want any zeros after the comma just add the thousand seperator
1495 if ($noTrailingZero) {
1496 $value = PMA_localizeNumber(
1497 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1500 //number_format is not multibyte safe, str_replace is safe
1501 $value = PMA_localizeNumber(number_format($value, $digits_right));
1504 if ($originalValue!=0 && floatval($value) == 0) {
1505 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1508 return $sign . $value . ' ' . $unit;
1509 } // end of the 'PMA_formatNumber' function
1512 * Returns the number of bytes when a formatted size is given
1514 * @param string $formatted_size the size expression (for example 8MB)
1516 * @return integer The numerical part of the expression (for example 8)
1518 function PMA_extractValueFromFormattedSize($formatted_size)
1522 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1523 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1524 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1525 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1526 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1527 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1529 return $return_value;
1530 }// end of the 'PMA_extractValueFromFormattedSize' function
1533 * Writes localised date
1535 * @param string $timestamp the current timestamp
1536 * @param string $format format
1538 * @return string the formatted date
1542 function PMA_localisedDate($timestamp = -1, $format = '')
1545 /* l10n: Short month name */
1547 /* l10n: Short month name */
1549 /* l10n: Short month name */
1551 /* l10n: Short month name */
1553 /* l10n: Short month name */
1554 _pgettext('Short month name', 'May'),
1555 /* l10n: Short month name */
1557 /* l10n: Short month name */
1559 /* l10n: Short month name */
1561 /* l10n: Short month name */
1563 /* l10n: Short month name */
1565 /* l10n: Short month name */
1567 /* l10n: Short month name */
1569 $day_of_week = array(
1570 /* l10n: Short week day name */
1571 _pgettext('Short week day name', 'Sun'),
1572 /* l10n: Short week day name */
1574 /* l10n: Short week day name */
1576 /* l10n: Short week day name */
1578 /* l10n: Short week day name */
1580 /* l10n: Short week day name */
1582 /* l10n: Short week day name */
1585 if ($format == '') {
1586 /* l10n: See http://www.php.net/manual/en/function.strftime.php
1587 * to define the format string
1589 $format = __('%B %d, %Y at %I:%M %p');
1592 if ($timestamp == -1) {
1593 $timestamp = time();
1596 $date = preg_replace(
1598 $day_of_week[(int)strftime('%w', $timestamp)],
1601 $date = preg_replace(
1603 $month[(int)strftime('%m', $timestamp)-1],
1607 return strftime($date, $timestamp);
1608 } // end of the 'PMA_localisedDate()' function
1612 * returns a tab for tabbed navigation.
1613 * If the variables $link and $args ar left empty, an inactive tab is created
1615 * @param array $tab array with all options
1616 * @param array $url_params
1618 * @return string html code for one tab, a link if valid otherwise a span
1622 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1638 $tab = array_merge($defaults, $tab);
1640 // determine additionnal style-class
1641 if (empty($tab['class'])) {
1642 if (! empty($tab['active'])
1643 ||
PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1645 $tab['class'] = 'active';
1646 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1647 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1648 && empty($tab['warning'])) {
1649 $tab['class'] = 'active';
1653 if (!empty($tab['warning'])) {
1654 $tab['class'] .= ' error';
1655 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1658 // If there are any tab specific URL parameters, merge those with
1659 // the general URL parameters
1660 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1661 $url_params = array_merge($url_params, $tab['url_params']);
1665 if (!empty($tab['link'])) {
1666 $tab['link'] = htmlentities($tab['link']);
1667 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1668 if (! empty($tab['args'])) {
1669 foreach ($tab['args'] as $param => $value) {
1670 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1671 . '=' . urlencode($value);
1676 if (! empty($tab['fragment'])) {
1677 $tab['link'] .= $tab['fragment'];
1680 // display icon, even if iconic is disabled but the link-text is missing
1681 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1682 && isset($tab['icon'])
1684 // avoid generating an alt tag, because it only illustrates
1685 // the text that follows and if browser does not display
1686 // images, the text is duplicated
1687 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1688 .' width="16" height="16" alt="" />%2$s';
1689 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1690 } elseif (empty($tab['text'])) {
1691 // check to not display an empty link-text
1694 'empty linktext in function ' . __FUNCTION__
. '()',
1699 //Set the id for the tab, if set in the params
1700 $id_string = ( empty($tab['id']) ?
'' : ' id="'.$tab['id'].'" ' );
1701 $out = '<li' . ($tab['class'] == 'active' ?
' class="active"' : '') . '>';
1703 if (!empty($tab['link'])) {
1704 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1706 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1707 . $tab['text'] . '</a>';
1709 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1710 . $tab['text'] . '</span>';
1715 } // end of the 'PMA_generate_html_tab()' function
1718 * returns html-code for a tab navigation
1720 * @param array $tabs one element per tab
1721 * @param string $url_params
1723 * @return string html-code for tab-navigation
1725 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1727 $tag_id = 'topmenu';
1728 $tab_navigation = '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1729 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1731 foreach ($tabs as $tab) {
1732 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1737 .'<div class="clearfloat"></div>'
1740 return $tab_navigation;
1745 * Displays a link, or a button if the link's URL is too large, to
1746 * accommodate some browsers' limitations
1748 * @param string $url the URL
1749 * @param string $message the link message
1750 * @param mixed $tag_params string: js confirmation
1751 * array: additional tag params (f.e. style="")
1752 * @param boolean $new_form we set this to false when we are already in
1753 * a form, to avoid generating nested forms
1754 * @param boolean $strip_img whether to strip the image
1755 * @param string $target target
1757 * @return string the results to be echoed or saved in an array
1759 function PMA_linkOrButton($url, $message, $tag_params = array(),
1760 $new_form = true, $strip_img = false, $target = '')
1762 $url_length = strlen($url);
1763 // with this we should be able to catch case of image upload
1764 // into a (MEDIUM) BLOB; not worth generating even a form for these
1765 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1770 if (! is_array($tag_params)) {
1772 $tag_params = array();
1774 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1778 if (! empty($target)) {
1779 $tag_params['target'] = htmlentities($target);
1782 $tag_params_strings = array();
1783 foreach ($tag_params as $par_name => $par_value) {
1784 // htmlspecialchars() only on non javascript
1785 $par_value = substr($par_name, 0, 2) == 'on'
1787 : htmlspecialchars($par_value);
1788 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1791 $displayed_message = '';
1792 // Add text if not already added
1793 if (stristr($message, '<img')
1794 && (!$strip_img ||
$GLOBALS['cfg']['PropertiesIconic'] === true)
1795 && strip_tags($message)==$message
1797 $displayed_message = '<span>'
1799 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1804 // Suhosin: Check that each query parameter is not above maximum
1805 $in_suhosin_limits = true;
1806 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1807 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1808 $query_parts = PMA_splitURLQuery($url);
1809 foreach ($query_parts as $query_pair) {
1810 list($eachvar, $eachval) = explode('=', $query_pair);
1811 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1812 $in_suhosin_limits = false;
1819 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1820 // no whitespace within an <a> else Safari will make it part of the link
1821 $ret = "\n" . '<a href="' . $url . '" '
1822 . implode(' ', $tag_params_strings) . '>'
1823 . $message . $displayed_message . '</a>' . "\n";
1825 // no spaces (linebreaks) at all
1826 // or after the hidden fields
1827 // IE will display them all
1829 // add class=link to submit button
1830 if (empty($tag_params['class'])) {
1831 $tag_params['class'] = 'link';
1834 if (! isset($query_parts)) {
1835 $query_parts = PMA_splitURLQuery($url);
1837 $url_parts = parse_url($url);
1840 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1841 . ' method="post"' . $target . ' style="display: inline;">';
1843 $subname_close = '';
1846 $query_parts[] = 'redirect=' . $url_parts['path'];
1847 if (empty($GLOBALS['subform_counter'])) {
1848 $GLOBALS['subform_counter'] = 0;
1850 $GLOBALS['subform_counter']++
;
1852 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1853 $subname_close = ']';
1854 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1856 foreach ($query_parts as $query_pair) {
1857 list($eachvar, $eachval) = explode('=', $query_pair);
1858 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1859 . $subname_close . '" value="'
1860 . htmlspecialchars(urldecode($eachval)) . '" />';
1863 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1864 . implode(' ', $tag_params_strings) . '>'
1865 . $message . ' ' . $displayed_message . '</a>' . "\n";
1870 } // end if... else...
1873 } // end of the 'PMA_linkOrButton()' function
1877 * Splits a URL string by parameter
1879 * @param string $url the URL
1881 * @return array the parameter/value pairs, for example [0] db=sakila
1883 function PMA_splitURLQuery($url)
1885 // decode encoded url separators
1886 $separator = PMA_get_arg_separator();
1887 // on most places separator is still hard coded ...
1888 if ($separator !== '&') {
1889 // ... so always replace & with $separator
1890 $url = str_replace(htmlentities('&'), $separator, $url);
1891 $url = str_replace('&', $separator, $url);
1893 $url = str_replace(htmlentities($separator), $separator, $url);
1896 $url_parts = parse_url($url);
1897 return explode($separator, $url_parts['query']);
1901 * Returns a given timespan value in a readable format.
1903 * @param int $seconds the timespan
1905 * @return string the formatted value
1907 function PMA_timespanFormat($seconds)
1909 $days = floor($seconds / 86400);
1911 $seconds -= $days * 86400;
1913 $hours = floor($seconds / 3600);
1914 if ($days > 0 ||
$hours > 0) {
1915 $seconds -= $hours * 3600;
1917 $minutes = floor($seconds / 60);
1918 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1919 $seconds -= $minutes * 60;
1922 __('%s days, %s hours, %s minutes and %s seconds'),
1923 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1928 * Takes a string and outputs each character on a line for itself. Used
1929 * mainly for horizontalflipped display mode.
1930 * Takes care of special html-characters.
1931 * Fulfills todo-item
1932 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1934 * @param string $string The string
1935 * @param string $Separator The Separator (defaults to "<br />\n")
1938 * @todo add a multibyte safe function PMA_STR_split()
1940 * @return string The flipped string
1942 function PMA_flipstring($string, $Separator = "<br />\n")
1944 $format_string = '';
1947 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++
) {
1948 $char = $string{$i};
1952 $format_string .= $charbuff;
1954 } elseif ($char == ';' && !empty($charbuff)) {
1955 $format_string .= $charbuff . $char;
1958 } elseif (! empty($charbuff)) {
1961 $format_string .= $char;
1965 // do not add separator after the last character
1966 if ($append && ($i != $str_len - 1)) {
1967 $format_string .= $Separator;
1971 return $format_string;
1975 * Function added to avoid path disclosures.
1976 * Called by each script that needs parameters, it displays
1977 * an error message and, by default, stops the execution.
1979 * Not sure we could use a strMissingParameter message here,
1980 * would have to check if the error message file is always available
1982 * @param array $params The names of the parameters needed by the calling script.
1983 * @param bool $die Stop the execution?
1984 * (Set this manually to false in the calling script
1985 * until you know all needed parameters to check).
1986 * @param bool $request Whether to include this list in checking for special params.
1988 * @global string path to current script
1989 * @global boolean flag whether any special variable was required
1992 * @todo use PMA_fatalError() if $die === true?
1994 function PMA_checkParameters($params, $die = true, $request = true)
1996 global $checked_special;
1998 if (! isset($checked_special)) {
1999 $checked_special = false;
2002 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2003 $found_error = false;
2004 $error_message = '';
2006 foreach ($params as $param) {
2007 if ($request && $param != 'db' && $param != 'table') {
2008 $checked_special = true;
2011 if (! isset($GLOBALS[$param])) {
2012 $error_message .= $reported_script_name
2013 . ': ' . __('Missing parameter:') . ' '
2015 . PMA_showDocu('faqmissingparameters')
2017 $found_error = true;
2022 * display html meta tags
2024 include_once './libraries/header_meta_style.inc.php';
2025 echo '</head><body><p>' . $error_message . '</p></body></html>';
2033 * Function to generate unique condition for specified row.
2035 * @param resource $handle current query result
2036 * @param integer $fields_cnt number of fields
2037 * @param array $fields_meta meta information about fields
2038 * @param array $row current row
2039 * @param boolean $force_unique generate condition only on pk or unique
2043 * @return array the calculated condition and whether condition is unique
2045 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2049 $nonprimary_condition = '';
2050 $preferred_condition = '';
2051 $primary_key_array = array();
2052 $unique_key_array = array();
2053 $nonprimary_condition_array = array();
2054 $condition_array = array();
2056 for ($i = 0; $i < $fields_cnt; ++
$i) {
2060 $field_flags = PMA_DBI_field_flags($handle, $i);
2061 $meta = $fields_meta[$i];
2063 // do not use a column alias in a condition
2064 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
2065 $meta->orgname
= $meta->name
;
2067 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2068 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2070 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2071 // need (string) === (string)
2072 // '' !== 0 but '' == 0
2073 if ((string) $select_expr['alias'] === (string) $meta->name
) {
2074 $meta->orgname
= $select_expr['column'];
2081 // Do not use a table alias in a condition.
2083 // select * from galerie x WHERE
2084 //(select count(*) from galerie y where y.datum=x.datum)>1
2086 // But orgtable is present only with mysqli extension so the
2087 // fix is only for mysqli.
2088 // Also, do not use the original table name if we are dealing with
2089 // a view because this view might be updatable.
2090 // (The isView() verification should not be costly in most cases
2091 // because there is some caching in the function).
2092 if (isset($meta->orgtable
)
2093 && $meta->table
!= $meta->orgtable
2094 && ! PMA_Table
::isView($GLOBALS['db'], $meta->table
)
2096 $meta->table
= $meta->orgtable
;
2099 // to fix the bug where float fields (primary or not)
2100 // can't be matched because of the imprecision of
2101 // floating comparison, use CONCAT
2102 // (also, the syntax "CONCAT(field) IS NULL"
2103 // that we need on the next "if" will work)
2104 if ($meta->type
== 'real') {
2105 $con_key = 'CONCAT(' . PMA_backquote($meta->table
) . '.'
2106 . PMA_backquote($meta->orgname
) . ')';
2108 $con_key = PMA_backquote($meta->table
) . '.'
2109 . PMA_backquote($meta->orgname
);
2110 } // end if... else...
2111 $condition = ' ' . $con_key . ' ';
2113 if (! isset($row[$i]) ||
is_null($row[$i])) {
2114 $con_val = 'IS NULL';
2116 // timestamp is numeric on some MySQL 4.1
2117 // for real we use CONCAT above and it should compare to string
2119 && $meta->type
!= 'timestamp'
2120 && $meta->type
!= 'real'
2122 $con_val = '= ' . $row[$i];
2123 } elseif (($meta->type
== 'blob' ||
$meta->type
== 'string')
2124 // hexify only if this is a true not empty BLOB or a BINARY
2125 && stristr($field_flags, 'BINARY')
2126 && !empty($row[$i])) {
2127 // do not waste memory building a too big condition
2128 if (strlen($row[$i]) < 1000) {
2129 // use a CAST if possible, to avoid problems
2130 // if the field contains wildcard characters % or _
2131 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2133 // this blob won't be part of the final condition
2136 } elseif (in_array($meta->type
, PMA_getGISDatatypes())
2137 && ! empty($row[$i])
2139 // do not build a too big condition
2140 if (strlen($row[$i]) < 5000) {
2141 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2145 } elseif ($meta->type
== 'bit') {
2146 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length
) . "'";
2148 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2151 if ($con_val != null) {
2152 $condition .= $con_val . ' AND';
2153 if ($meta->primary_key
> 0) {
2154 $primary_key .= $condition;
2155 $primary_key_array[$con_key] = $con_val;
2156 } elseif ($meta->unique_key
> 0) {
2157 $unique_key .= $condition;
2158 $unique_key_array[$con_key] = $con_val;
2160 $nonprimary_condition .= $condition;
2161 $nonprimary_condition_array[$con_key] = $con_val;
2165 // Correction University of Virginia 19991216:
2166 // prefer primary or unique keys for condition,
2167 // but use conjunction of all values if no primary key
2168 $clause_is_unique = true;
2170 $preferred_condition = $primary_key;
2171 $condition_array = $primary_key_array;
2172 } elseif ($unique_key) {
2173 $preferred_condition = $unique_key;
2174 $condition_array = $unique_key_array;
2175 } elseif (! $force_unique) {
2176 $preferred_condition = $nonprimary_condition;
2177 $condition_array = $nonprimary_condition_array;
2178 $clause_is_unique = false;
2181 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2182 return(array($where_clause, $clause_is_unique, $condition_array));
2186 * Generate a button or image tag
2188 * @param string $button_name name of button element
2189 * @param string $button_class class of button element
2190 * @param string $image_name name of image element
2191 * @param string $text text to display
2192 * @param string $image image to display
2193 * @param string $value value
2197 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2198 $image, $value = '')
2203 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2204 echo ' <input type="submit" name="' . $button_name . '"'
2205 .' value="' . htmlspecialchars($value) . '"'
2206 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2210 /* Opera has trouble with <input type="image"> */
2211 /* IE has trouble with <button> */
2212 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2213 echo '<button class="' . $button_class . '" type="submit"'
2214 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2215 .' title="' . htmlspecialchars($text) . '">' . "\n"
2216 . PMA_getIcon($image, $text)
2217 .'</button>' . "\n";
2219 echo '<input type="image" name="' . $image_name
2220 . '" value="' . htmlspecialchars($value)
2221 . '" title="' . htmlspecialchars($text)
2222 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2223 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2224 ?
' ' . htmlspecialchars($text)
2230 * Generate a pagination selector for browsing resultsets
2232 * @param int $rows Number of rows in the pagination set
2233 * @param int $pageNow current page number
2234 * @param int $nbTotalPage number of total pages
2235 * @param int $showAll If the number of pages is lower than this
2236 * variable, no pages will be omitted in pagination
2237 * @param int $sliceStart How many rows at the beginning should always be shown?
2238 * @param int $sliceEnd How many rows at the end should always be shown?
2239 * @param int $percent Percentage of calculation page offsets to hop to a
2241 * @param int $range Near the current page, how many pages should
2242 * be considered "nearby" and displayed as well?
2243 * @param string $prompt The prompt to display (sometimes empty)
2249 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2250 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2251 $range = 10, $prompt = '')
2253 $increment = floor($nbTotalPage / $percent);
2254 $pageNowMinusRange = ($pageNow - $range);
2255 $pageNowPlusRange = ($pageNow +
$range);
2257 $gotopage = $prompt . ' <select id="pageselector" ';
2258 if ($GLOBALS['cfg']['AjaxEnable']) {
2259 $gotopage .= ' class="ajax"';
2261 $gotopage .= ' name="pos" >' . "\n";
2262 if ($nbTotalPage < $showAll) {
2263 $pages = range(1, $nbTotalPage);
2267 // Always show first X pages
2268 for ($i = 1; $i <= $sliceStart; $i++
) {
2272 // Always show last X pages
2273 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2277 // Based on the number of results we add the specified
2278 // $percent percentage to each page number,
2279 // so that we have a representing page number every now and then to
2280 // immediately jump to specific pages.
2281 // As soon as we get near our currently chosen page ($pageNow -
2282 // $range), every page number will be shown.
2284 $x = $nbTotalPage - $sliceEnd;
2285 $met_boundary = false;
2287 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2288 // If our pageselector comes near the current page, we use 1
2289 // counter increments
2291 $met_boundary = true;
2293 // We add the percentage increment to our current page to
2294 // hop to the next one in range
2297 // Make sure that we do not cross our boundaries.
2298 if ($i > $pageNowMinusRange && ! $met_boundary) {
2299 $i = $pageNowMinusRange;
2303 if ($i > 0 && $i <= $x) {
2308 // Since because of ellipsing of the current page some numbers may be double,
2309 // we unify our array:
2311 $pages = array_unique($pages);
2314 foreach ($pages as $i) {
2315 if ($i == $pageNow) {
2316 $selected = 'selected="selected" style="font-weight: bold"';
2320 $gotopage .= ' <option ' . $selected
2321 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2324 $gotopage .= ' </select><noscript><input type="submit" value="'
2325 . __('Go') . '" /></noscript>';
2332 * Generate navigation for a list
2334 * @param int $count number of elements in the list
2335 * @param int $pos current position in the list
2336 * @param array $_url_params url parameters
2337 * @param string $script script name for form target
2338 * @param string $frame target frame
2339 * @param int $max_count maximum number of elements to display from the list
2343 * @todo use $pos from $_url_params
2345 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2348 if ($max_count < $count) {
2349 echo 'frame_navigation' == $frame
2350 ?
'<div id="navidbpageselector">' . "\n"
2352 echo __('Page number:');
2353 echo 'frame_navigation' == $frame ?
'<br />' : ' ';
2355 // Move to the beginning or to the previous page
2357 // patch #474210 - part 1
2358 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2359 $caption1 = '<<';
2360 $caption2 = ' < ';
2361 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2362 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2364 $caption1 = _pgettext('First page', 'Begin') . ' <<';
2365 $caption2 = _pgettext('Previous page', 'Previous') . ' <';
2368 } // end if... else...
2369 $_url_params['pos'] = 0;
2370 echo '<a' . $title1 . ' href="' . $script
2371 . PMA_generate_common_url($_url_params) . '" target="'
2372 . $frame . '">' . $caption1 . '</a>';
2373 $_url_params['pos'] = $pos - $max_count;
2374 echo '<a' . $title2 . ' href="' . $script
2375 . PMA_generate_common_url($_url_params) . '" target="'
2376 . $frame . '">' . $caption2 . '</a>';
2379 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2380 echo PMA_generate_common_hidden_inputs($_url_params);
2381 echo PMA_pageselector(
2383 floor(($pos +
1) / $max_count) +
1,
2384 ceil($count / $max_count)
2388 if ($pos +
$max_count < $count) {
2389 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2390 $caption3 = ' > ';
2391 $caption4 = '>>';
2392 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2393 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2395 $caption3 = '> ' . _pgettext('Next page', 'Next');
2396 $caption4 = '>> ' . _pgettext('Last page', 'End');
2399 } // end if... else...
2400 $_url_params['pos'] = $pos +
$max_count;
2401 echo '<a' . $title3 . ' href="' . $script
2402 . PMA_generate_common_url($_url_params) . '" target="'
2403 . $frame . '">' . $caption3 . '</a>';
2404 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2405 if ($_url_params['pos'] == $count) {
2406 $_url_params['pos'] = $count - $max_count;
2408 echo '<a' . $title4 . ' href="' . $script
2409 . PMA_generate_common_url($_url_params) . '" target="'
2410 . $frame . '">' . $caption4 . '</a>';
2413 if ('frame_navigation' == $frame) {
2414 echo '</div>' . "\n";
2420 * replaces %u in given path with current user name
2424 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2428 * @param string $dir with wildcard for user
2430 * @return string per user directory
2432 function PMA_userDir($dir)
2434 // add trailing slash
2435 if (substr($dir, -1) != '/') {
2439 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2443 * returns html code for db link to default db page
2445 * @param string $database database
2447 * @return string html link to default db page
2449 function PMA_getDbLink($database = null)
2451 if (! strlen($database)) {
2452 if (! strlen($GLOBALS['db'])) {
2455 $database = $GLOBALS['db'];
2457 $database = PMA_unescape_mysql_wildcards($database);
2460 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2461 . PMA_generate_common_url($database) . '" title="'
2463 __('Jump to database "%s".'),
2464 htmlspecialchars($database)
2466 . '">' . htmlspecialchars($database) . '</a>';
2470 * Displays a lightbulb hint explaining a known external bug
2471 * that affects a functionality
2473 * @param string $functionality localized message explaining the func.
2474 * @param string $component 'mysql' (eventually, 'php')
2475 * @param string $minimum_version of this component
2476 * @param string $bugref bug reference for this component
2478 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2480 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION
< $minimum_version) {
2483 __('The %s functionality is affected by a known bug, see %s'),
2485 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2492 * Generates and echoes an HTML checkbox
2494 * @param string $html_field_name the checkbox HTML field
2495 * @param string $label label for checkbox
2496 * @param boolean $checked is it initially checked?
2497 * @param boolean $onclick should it submit the form on click?
2499 * @return the HTML for the checkbox
2501 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2504 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2505 . $html_field_name . '"' . ($checked ?
' checked="checked"' : '')
2506 . ($onclick ?
' class="autosubmit"' : '') . ' /><label for="'
2507 . $html_field_name . '">' . $label . '</label>';
2511 * Generates and echoes a set of radio HTML fields
2513 * @param string $html_field_name the radio HTML field
2514 * @param array $choices the choices values and labels
2515 * @param string $checked_choice the choice to check by default
2516 * @param boolean $line_break whether to add an HTML line break after a choice
2517 * @param boolean $escape_label whether to use htmlspecialchars() on label
2518 * @param string $class enclose each choice with a div of this class
2520 * @return the HTML for the tadio buttons
2522 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2523 $line_break = true, $escape_label = true, $class='')
2525 foreach ($choices as $choice_value => $choice_label) {
2526 if (! empty($class)) {
2527 echo '<div class="' . $class . '">';
2529 $html_field_id = $html_field_name . '_' . $choice_value;
2530 echo '<input type="radio" name="' . $html_field_name . '" id="'
2531 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2532 if ($choice_value == $checked_choice) {
2533 echo ' checked="checked"';
2536 echo '<label for="' . $html_field_id . '">'
2537 . ($escape_label ?
htmlspecialchars($choice_label) : $choice_label)
2542 if (! empty($class)) {
2550 * Generates and returns an HTML dropdown
2552 * @param string $select_name name for the select element
2553 * @param array $choices choices values
2554 * @param string $active_choice the choice to select by default
2555 * @param string $id id of the select element; can be different in case
2556 * the dropdown is present more than once on the page
2560 * @todo support titles
2562 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2564 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2565 . htmlspecialchars($id) . '">';
2566 foreach ($choices as $one_choice_value => $one_choice_label) {
2567 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2568 if ($one_choice_value == $active_choice) {
2569 $result .= ' selected="selected"';
2571 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2573 $result .= '</select>';
2578 * Generates a slider effect (jQjuery)
2579 * Takes care of generating the initial <div> and the link
2580 * controlling the slider; you have to generate the </div> yourself
2581 * after the sliding section.
2583 * @param string $id the id of the <div> on which to apply the effect
2584 * @param string $message the message to show as a link
2586 function PMA_generate_slider_effect($id, $message)
2588 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2589 echo '<div id="' . $id . '">';
2593 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2594 * opening the <div> with PHP itself instead of JavaScript.
2596 * @todo find a better solution that uses $.append(), the recommended method
2597 * maybe by using an additional param, the id of the div to append to
2600 <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); ?>">
2605 * Creates an AJAX sliding toggle button
2606 * (or and equivalent form when AJAX is disabled)
2608 * @param string $action The URL for the request to be executed
2609 * @param string $select_name The name for the dropdown box
2610 * @param array $options An array of options (see rte_footer.lib.php)
2611 * @param string $callback A JS snippet to execute when the request is
2612 * successfully processed
2614 * @return string HTML code for the toggle button
2616 function PMA_toggleButton($action, $select_name, $options, $callback)
2618 // Do the logic first
2619 $link_on = "$action&$select_name=" . urlencode($options[1]['value']);
2620 $link_off = "$action&$select_name=" . urlencode($options[0]['value']);
2621 if ($options[1]['selected'] == true) {
2623 } else if ($options[0]['selected'] == true) {
2630 if ($options[1]['selected'] == true) {
2631 $selected1 = " selected='selected'";
2632 } else if ($options[0]['selected'] == true) {
2633 $selected0 = " selected='selected'";
2636 $retval = "<!-- TOGGLE START -->\n";
2637 if ($GLOBALS['cfg']['AjaxEnable']) {
2638 $retval .= "<noscript>\n";
2640 $retval .= "<div class='wrapper'>\n";
2641 $retval .= " <form action='$action' method='post'>\n";
2642 $retval .= " <select name='$select_name'>\n";
2643 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2644 $retval .= " {$options[1]['label']}\n";
2645 $retval .= " </option>\n";
2646 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2647 $retval .= " {$options[0]['label']}\n";
2648 $retval .= " </option>\n";
2649 $retval .= " </select>\n";
2650 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2651 $retval .= " </form>\n";
2652 $retval .= "</div>\n";
2653 if ($GLOBALS['cfg']['AjaxEnable']) {
2654 $retval .= "</noscript>\n";
2655 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2656 $retval .= " <div class='toggleButton'>\n";
2657 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2658 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2659 $retval .= " alt='' />\n";
2660 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2661 $retval .= " <tbody>\n";
2662 $retval .= " <td class='toggleOn'>\n";
2663 $retval .= " <span class='hide'>$link_on</span>\n";
2664 $retval .= " <div>";
2665 $retval .= str_replace(' ', ' ', $options[1]['label']) . "</div>\n";
2666 $retval .= " </td>\n";
2667 $retval .= " <td><div> </div></td>\n";
2668 $retval .= " <td class='toggleOff'>\n";
2669 $retval .= " <span class='hide'>$link_off</span>\n";
2670 $retval .= " <div>";
2671 $retval .= str_replace(' ', ' ', $options[0]['label']) . "</div>\n";
2672 $retval .= " </div>\n";
2673 $retval .= " </tbody>\n";
2674 $retval .= " </tr></table>\n";
2675 $retval .= " <span class='hide callback'>$callback</span>\n";
2676 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2677 $retval .= " </div>\n";
2678 $retval .= " </div>\n";
2679 $retval .= "</div>\n";
2681 $retval .= "<!-- TOGGLE END -->";
2684 } // end PMA_toggleButton()
2687 * Clears cache content which needs to be refreshed on user change.
2691 function PMA_clearUserCache()
2693 PMA_cacheUnset('is_superuser', true);
2697 * Verifies if something is cached in the session
2699 * @param string $var variable name
2700 * @param int|true $server server
2704 function PMA_cacheExists($var, $server = 0)
2706 if (true === $server) {
2707 $server = $GLOBALS['server'];
2709 return isset($_SESSION['cache']['server_' . $server][$var]);
2713 * Gets cached information from the session
2715 * @param string $var varibale name
2716 * @param int|true $server server
2720 function PMA_cacheGet($var, $server = 0)
2722 if (true === $server) {
2723 $server = $GLOBALS['server'];
2725 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2726 return $_SESSION['cache']['server_' . $server][$var];
2733 * Caches information in the session
2735 * @param string $var variable name
2736 * @param mixed $val value
2737 * @param int|true $server server
2741 function PMA_cacheSet($var, $val = null, $server = 0)
2743 if (true === $server) {
2744 $server = $GLOBALS['server'];
2746 $_SESSION['cache']['server_' . $server][$var] = $val;
2750 * Removes cached information from the session
2752 * @param string $var variable name
2753 * @param int|true $server server
2757 function PMA_cacheUnset($var, $server = 0)
2759 if (true === $server) {
2760 $server = $GLOBALS['server'];
2762 unset($_SESSION['cache']['server_' . $server][$var]);
2766 * Converts a bit value to printable format;
2767 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2768 * function because in PHP, decbin() supports only 32 bits
2770 * @param numeric $value coming from a BIT field
2771 * @param integer $length length
2773 * @return string the printable value
2775 function PMA_printable_bit_value($value, $length)
2778 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++
) {
2779 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2781 $printable = substr($printable, -$length);
2786 * Verifies whether the value contains a non-printable character
2788 * @param string $value value
2792 function PMA_contains_nonprintable_ascii($value)
2794 return preg_match('@[^[:print:]]@', $value);
2798 * Converts a BIT type default value
2799 * for example, b'010' becomes 010
2801 * @param string $bit_default_value value
2803 * @return string the converted value
2805 function PMA_convert_bit_default_value($bit_default_value)
2807 return strtr($bit_default_value, array("b" => "", "'" => ""));
2811 * Extracts the various parts from a field type spec
2813 * @param string $fieldspec Field specification
2815 * @return array associative array containing type, spec_in_brackets
2816 * and possibly enum_set_values (another array)
2818 function PMA_extractFieldSpec($fieldspec)
2820 $first_bracket_pos = strpos($fieldspec, '(');
2821 if ($first_bracket_pos) {
2822 $spec_in_brackets = chop(
2825 $first_bracket_pos +
1,
2826 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2829 // convert to lowercase just to be sure
2830 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2832 $type = strtolower($fieldspec);
2833 $spec_in_brackets = '';
2836 if ('enum' == $type ||
'set' == $type) {
2837 // Define our working vars
2838 $enum_set_values = array();
2843 // While there is another character to process
2844 while (isset($fieldspec[$index])) {
2845 // Grab the char to look at
2846 $char = $fieldspec[$index];
2848 // If it is a single quote, needs to be handled specially
2850 // If we are not currently in a string, begin one
2855 // Otherwise, it may be either an end of a string,
2856 // or a 'double quote' which can be handled as-is
2857 // Check out the next character (if possible)
2858 $has_next = isset($fieldspec[$index +
1]);
2859 $next = $has_next ?
$fieldspec[$index +
1] : null;
2861 //If we have reached the end of our 'working' string (because
2862 //there are no more chars,or the next char is not another quote)
2863 if (! $has_next ||
$next != "'") {
2864 $enum_set_values[] = $working;
2867 } elseif ($next == "'") {
2868 // Otherwise, this is a 'double quote',
2869 // and can be added to the working string
2871 // Skip the next char; we already know what it is
2875 } elseif ('\\' == $char
2876 && isset($fieldspec[$index +
1])
2877 && "'" == $fieldspec[$index +
1]
2879 // escaping of a quote?
2883 // Otherwise, add it to our working string like normal
2886 // Increment character index
2889 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2894 $enum_set_values = array();
2896 /* Create printable type name */
2897 $printtype = strtolower($fieldspec);
2899 // strip the "BINARY" attribute, except if we find "BINARY(" because
2900 // this would be a BINARY or VARBINARY field type
2901 if (!preg_match('@binary[\(]@', $printtype)) {
2902 $binary = strpos($printtype, 'blob') !== false ||
strpos($printtype, 'binary') !== false;
2903 $printtype = preg_replace('@binary@', '', $printtype);
2907 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2908 $zerofill = ($zerofill_cnt > 0);
2909 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
2910 $unsigned = ($unsigned_cnt > 0);
2911 $printtype = trim($printtype);
2917 $attribute = 'BINARY';
2920 $attribute = 'UNSIGNED';
2923 $attribute = 'UNSIGNED ZEROFILL';
2928 'spec_in_brackets' => $spec_in_brackets,
2929 'enum_set_values' => $enum_set_values,
2930 'print_type' => $printtype,
2931 'binary' => $binary,
2932 'unsigned' => $unsigned,
2933 'zerofill' => $zerofill,
2934 'attribute' => $attribute,
2939 * Verifies if this table's engine supports foreign keys
2941 * @param string $engine engine
2945 function PMA_foreignkey_supported($engine)
2947 $engine = strtoupper($engine);
2948 if ('INNODB' == $engine ||
'PBXT' == $engine) {
2956 * Replaces some characters by a displayable equivalent
2958 * @param string $content content
2960 * @return string the content with characters replaced
2962 function PMA_replace_binary_contents($content)
2964 $result = str_replace("\x00", '\0', $content);
2965 $result = str_replace("\x08", '\b', $result);
2966 $result = str_replace("\x0a", '\n', $result);
2967 $result = str_replace("\x0d", '\r', $result);
2968 $result = str_replace("\x1a", '\Z', $result);
2973 * Converts GIS data to Well Known Text format
2975 * @param binary $data GIS data
2976 * @param bool $includeSRID Add SRID to the WKT
2978 * @return GIS data in Well Know Text format
2980 function PMA_asWKT($data, $includeSRID = false)
2982 // Convert to WKT format
2983 $hex = bin2hex($data);
2984 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
2986 $wktsql .= ", SRID(x'" . $hex . "')";
2988 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE
);
2989 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
2990 $wktval = $wktarr[0];
2993 $wktval = "'" . $wktval . "'," . $srid;
2995 @PMA_DBI_free_result
($wktresult);
3000 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3002 * @param string $string string
3004 * @return string with the chars replaced
3007 function PMA_duplicateFirstNewline($string)
3009 $first_occurence = strpos($string, "\r\n");
3010 if ($first_occurence === 0) {
3011 $string = "\n".$string;
3017 * Get the action word corresponding to a script name
3018 * in order to display it as a title in navigation panel
3020 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3021 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3025 function PMA_getTitleForTarget($target)
3028 // Values for $cfg['DefaultTabTable']
3029 'tbl_structure.php' => __('Structure'),
3030 'tbl_sql.php' => __('SQL'),
3031 'tbl_select.php' =>__('Search'),
3032 'tbl_change.php' =>__('Insert'),
3033 'sql.php' => __('Browse'),
3035 // Values for $cfg['DefaultTabDatabase']
3036 'db_structure.php' => __('Structure'),
3037 'db_sql.php' => __('SQL'),
3038 'db_search.php' => __('Search'),
3039 'db_operations.php' => __('Operations'),
3041 return $mapping[$target];
3045 * Formats user string, expading @VARIABLES@, accepting strftime format string.
3047 * @param string $string Text where to do expansion.
3048 * @param function $escape Function to call for escaping variable values.
3049 * @param array $updates Array with overrides for default parameters
3050 * (obtained from GLOBALS).
3054 function PMA_expandUserString($string, $escape = null, $updates = array())
3057 $vars['http_host'] = PMA_getenv('HTTP_HOST') ?
PMA_getenv('HTTP_HOST') : '';
3058 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3059 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3060 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3061 ?
$GLOBALS['cfg']['Server']['verbose']
3062 : $GLOBALS['cfg']['Server']['host'];
3063 $vars['database'] = $GLOBALS['db'];
3064 $vars['table'] = $GLOBALS['table'];
3065 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION
;
3067 /* Update forced variables */
3068 foreach ($updates as $key => $val) {
3072 /* Replacement mapping */
3074 * The __VAR__ ones are for backward compatibility, because user
3075 * might still have it in cookies.
3078 '@HTTP_HOST@' => $vars['http_host'],
3079 '@SERVER@' => $vars['server_name'],
3080 '__SERVER__' => $vars['server_name'],
3081 '@VERBOSE@' => $vars['server_verbose'],
3082 '@VSERVER@' => $vars['server_verbose_or_name'],
3083 '@DATABASE@' => $vars['database'],
3084 '__DB__' => $vars['database'],
3085 '@TABLE@' => $vars['table'],
3086 '__TABLE__' => $vars['table'],
3087 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3090 /* Optional escaping */
3091 if (!is_null($escape)) {
3092 foreach ($replace as $key => $val) {
3093 $replace[$key] = $escape($val);
3097 /* Fetch fields list if required */
3098 if (strpos($string, '@FIELDS@') !== false) {
3099 $fields_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3101 $field_names = array();
3102 foreach ($fields_list as $field) {
3103 if (!is_null($escape)) {
3104 $field_names[] = $escape($field['Field']);
3106 $field_names[] = $field['Field'];
3110 $replace['@FIELDS@'] = implode(',', $field_names);
3113 /* Do the replacement */
3114 return strtr(strftime($string), $replace);
3118 * function that generates a json output for an ajax request and ends script
3121 * @param PMA_Message|string $message message string containing the
3122 * html of the message
3123 * @param bool $success success whether the ajax request
3125 * @param array $extra_data extra data optional -
3126 * any other data as part of the json request
3130 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3132 $response = array();
3133 if ( $success == true ) {
3134 $response['success'] = true;
3135 if ($message instanceof PMA_Message
) {
3136 $response['message'] = $message->getDisplay();
3138 $response['message'] = $message;
3141 $response['success'] = false;
3142 if ($message instanceof PMA_Message
) {
3143 $response['error'] = $message->getDisplay();
3145 $response['error'] = $message;
3149 // If extra_data has been provided, append it to the response array
3150 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3151 $response = array_merge($response, $extra_data);
3154 // Set the Content-Type header to JSON so that jQuery parses the
3155 // response correctly.
3157 // At this point, other headers might have been sent;
3158 // even if $GLOBALS['is_header_sent'] is true,
3159 // we have to send these additional headers.
3160 header('Cache-Control: no-cache');
3161 header("Content-Type: application/json");
3163 echo json_encode($response);
3165 if (!defined('TESTSUITE'))
3170 * Display the form used to browse anywhere on the local server for a file to import
3172 * @param string $max_upload_size maximum upload size
3176 function PMA_browseUploadFile($max_upload_size)
3178 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3179 echo '<div id="upload_form_status" style="display: none;"></div>';
3180 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3181 echo '<input type="file" name="import_file" id="input_import_file" />';
3182 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3183 // some browsers should respect this :)
3184 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3188 * Display the form used to select a file to import from the server upload directory
3190 * @param array $import_list array of import types
3191 * @param string $uploaddir upload directory
3195 function PMA_selectUploadFile($import_list, $uploaddir)
3197 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3199 foreach ($import_list as $key => $val) {
3200 if (!empty($extensions)) {
3203 $extensions .= $val['extension'];
3205 $matcher = '@\.(' . $extensions . ')(\.('
3206 . PMA_supportedDecompressions() . '))?$@';
3208 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3209 ?
$local_import_file
3211 $files = PMA_getFileSelectOptions(
3212 PMA_userDir($uploaddir),
3216 if ($files === false) {
3218 __('The directory you set for upload work cannot be reached')
3220 } elseif (!empty($files)) {
3222 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3223 echo ' <option value=""> </option>' . "\n";
3225 echo ' </select>' . "\n";
3226 } elseif (empty ($files)) {
3227 echo '<i>' . __('There are no files to upload') . '</i>';
3232 * Build titles and icons for action links
3234 * @return array the action titles
3236 function PMA_buildActionTitles()
3240 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3241 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3242 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3243 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3244 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3245 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3246 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3247 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3248 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3249 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3250 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3251 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3252 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3253 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3254 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3255 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3256 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3261 * This function processes the datatypes supported by the DB, as specified in
3262 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3263 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3265 * @param bool $html Whether to generate an html snippet or an array
3266 * @param string $selected The value to mark as selected in HTML mode
3268 * @return mixed An HTML snippet or an array of datatypes.
3271 function PMA_getSupportedDatatypes($html = false, $selected = '')
3276 // NOTE: the SELECT tag in not included in this snippet.
3278 foreach ($cfg['ColumnTypes'] as $key => $value) {
3279 if (is_array($value)) {
3280 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3281 foreach ($value as $subvalue) {
3282 if ($subvalue == $selected) {
3283 $retval .= "<option selected='selected'>";
3284 $retval .= $subvalue;
3285 $retval .= "</option>";
3286 } else if ($subvalue === '-') {
3287 $retval .= "<option disabled='disabled'>";
3288 $retval .= $subvalue;
3289 $retval .= "</option>";
3291 $retval .= "<option>$subvalue</option>";
3294 $retval .= '</optgroup>';
3296 if ($selected == $value) {
3297 $retval .= "<option selected='selected'>$value</option>";
3299 $retval .= "<option>$value</option>";
3305 foreach ($cfg['ColumnTypes'] as $value) {
3306 if (is_array($value)) {
3307 foreach ($value as $subvalue) {
3308 if ($subvalue !== '-') {
3309 $retval[] = $subvalue;
3313 if ($value !== '-') {
3321 } // end PMA_getSupportedDatatypes()
3324 * Returns a list of datatypes that are not (yet) handled by PMA.
3325 * Used by: tbl_change.php and libraries/db_routines.inc.php
3327 * @return array list of datatypes
3329 function PMA_unsupportedDatatypes()
3331 $no_support_types = array();
3332 return $no_support_types;
3336 * Return GIS data types
3338 * @param bool $upper_case whether to return values in upper case
3340 * @return array GIS data types
3342 function PMA_getGISDatatypes($upper_case = false)
3344 $gis_data_types = array(
3352 'geometrycollection'
3355 for ($i = 0; $i < count($gis_data_types); $i++
) {
3356 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3360 return $gis_data_types;
3364 * Generates GIS data based on the string passed.
3366 * @param string $gis_string GIS string
3368 * @return GIS data enclosed in 'GeomFromText' function
3370 function PMA_createGISData($gis_string)
3372 $gis_string = trim($gis_string);
3373 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3374 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3375 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3376 return 'GeomFromText(' . $gis_string . ')';
3377 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3378 return "GeomFromText('" . $gis_string . "')";
3385 * Returns the names and details of the functions
3386 * that can be applied on geometry data typess.
3388 * @param string $geom_type if provided the output is limited to the functions
3389 * that are applicable to the provided geometry type.
3390 * @param bool $binary if set to false functions that take two geometries
3391 * as arguments will not be included.
3392 * @param bool $display if set to true seperators will be added to the
3395 * @return array names and details of the functions that can be applied on
3396 * geometry data typess.
3398 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3402 $funcs[] = array('display' => ' ');
3405 // Unary functions common to all geomety types
3406 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3407 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3408 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3409 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3410 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3411 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3413 $geom_type = trim(strtolower($geom_type));
3414 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3415 $funcs[] = array('display' => '--------');
3418 // Unary functions that are specific to each geomety type
3419 if ($geom_type == 'point') {
3420 $funcs['X'] = array('params' => 1, 'type' => 'float');
3421 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3423 } elseif ($geom_type == 'multipoint') {
3424 // no fucntions here
3425 } elseif ($geom_type == 'linestring') {
3426 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3427 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3428 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3429 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3430 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3432 } elseif ($geom_type == 'multilinestring') {
3433 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3434 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3436 } elseif ($geom_type == 'polygon') {
3437 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3438 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3439 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3441 } elseif ($geom_type == 'multipolygon') {
3442 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3443 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3444 // Not yet implemented in MySQL
3445 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3447 } elseif ($geom_type == 'geometrycollection') {
3448 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3451 // If we are asked for binary functions as well
3453 // section seperator
3455 $funcs[] = array('display' => '--------');
3457 if (PMA_MYSQL_INT_VERSION
< 50601) {
3458 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3459 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3460 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3461 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3462 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3463 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3464 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3465 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3467 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3468 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3469 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3470 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3471 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3472 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3473 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3474 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3475 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3480 $funcs[] = array('display' => '--------');
3482 // Minimum bounding rectangle functions
3483 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3484 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3485 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3486 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3487 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3488 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3489 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3495 * Creates a dropdown box with MySQL functions for a particular column.
3497 * @param array $field Data about the column for which
3498 * to generate the dropdown
3499 * @param bool $insert_mode Whether the operation is 'insert'
3501 * @global array $cfg PMA configuration
3502 * @global array $analyzed_sql Analyzed SQL query
3503 * @global mixed $data (null/string) FIXME: what is this for?
3505 * @return string An HTML snippet of a dropdown list with function
3506 * names appropriate for the requested column.
3508 function PMA_getFunctionsForField($field, $insert_mode)
3510 global $cfg, $analyzed_sql, $data;
3513 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3514 // or something similar. Then directly look up the entry in the
3515 // RestrictFunctions array, which'll then reveal the available dropdown options
3516 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3517 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3519 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3520 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3521 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3523 $dropdown = array();
3524 $default_function = '';
3526 $dropdown_built = array();
3527 $op_spacing_needed = false;
3528 // what function defined as default?
3529 // for the first timestamp we don't set the default function
3530 // if there is a default value for the timestamp
3531 // (not including CURRENT_TIMESTAMP)
3532 // and the column does not have the
3533 // ON UPDATE DEFAULT TIMESTAMP attribute.
3534 if ($field['True_Type'] == 'timestamp'
3535 && empty($field['Default'])
3537 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3539 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3541 // For primary keys of type char(36) or varchar(36) UUID if the default function
3542 // Only applies to insert mode, as it would silently trash data on updates.
3544 && $field['Key'] == 'PRI'
3545 && ($field['Type'] == 'char(36)' ||
$field['Type'] == 'varchar(36)')
3547 $default_function = $cfg['DefaultFunctions']['pk_char36'];
3549 // this is set only when appropriate and is always true
3550 if (isset($field['display_binary_as_hex'])) {
3551 $default_function = 'UNHEX';
3554 // Create the output
3555 $retval = ' <option></option>' . "\n";
3556 // loop on the dropdown array and print all available options for that field.
3557 foreach ($dropdown as $each_dropdown) {
3559 $retval .= '<option';
3560 if ($default_function === $each_dropdown) {
3561 $retval .= ' selected="selected"';
3563 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3564 $dropdown_built[$each_dropdown] = 'true';
3565 $op_spacing_needed = true;
3567 // For compatibility's sake, do not let out all other functions. Instead
3568 // print a separator (blank) and then show ALL functions which weren't shown
3570 $cnt_functions = count($cfg['Functions']);
3571 for ($j = 0; $j < $cnt_functions; $j++
) {
3572 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3573 ||
$dropdown_built[$cfg['Functions'][$j]] != 'true'
3575 // Is current function defined as default?
3576 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3577 ||
(! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3578 ?
' selected="selected"'
3580 if ($op_spacing_needed == true) {
3582 $retval .= '<option value="">--------</option>' . "\n";
3583 $op_spacing_needed = false;
3587 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3588 . '</option>' . "\n";
3593 } // end PMA_getFunctionsForField()
3596 * Checks if the current user has a specific privilege and returns true if the
3597 * user indeed has that privilege or false if (s)he doesn't. This function must
3598 * only be used for features that are available since MySQL 5, because it
3599 * relies on the INFORMATION_SCHEMA database to be present.
3601 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3602 * // Checks if the currently logged in user has the global
3603 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3604 * // user has this privilege on database 'mydb'.
3606 * @param string $priv The privilege to check
3607 * @param mixed $db null, to only check global privileges
3608 * string, db name where to also check for privileges
3609 * @param mixed $tbl null, to only check global privileges
3610 * string, db name where to also check for privileges
3614 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3616 // Get the username for the current user in the format
3617 // required to use in the information schema database.
3618 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3619 if ($user === false) {
3622 $user = explode('@', $user);
3624 $username .= str_replace("'", "''", $user[0]);
3625 $username .= "''@''";
3626 $username .= str_replace("'", "''", $user[1]);
3628 // Prepage the query
3629 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3630 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3631 // Check global privileges first.
3632 if (PMA_DBI_fetch_value(
3643 // If a database name was provided and user does not have the
3644 // required global privilege, try database-wise permissions.
3646 $query .= " AND TABLE_SCHEMA='%s'";
3647 if (PMA_DBI_fetch_value(
3650 'SCHEMA_PRIVILEGES',
3653 PMA_sqlAddSlashes($db)
3660 // There was no database name provided and the user
3661 // does not have the correct global privilege.
3664 // If a table name was also provided and we still didn't
3665 // find any valid privileges, try table-wise privileges.
3666 if ($tbl !== null) {
3667 $query .= " AND TABLE_NAME='%s'";
3668 if ($retval = PMA_DBI_fetch_value(
3674 PMA_sqlAddSlashes($db),
3675 PMA_sqlAddSlashes($tbl)
3682 // If we reached this point, the user does not
3683 // have even valid table-wise privileges.