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 * Returns an HTML IMG tag for a particular icon from a theme,
75 * which may be an actual file or an icon from a sprite.
76 * This function takes into account the PropertiesIconic
77 * configuration setting and wraps the image tag in a span tag.
79 * @param string $icon name of icon file
80 * @param string $alternate alternate text
81 * @param boolean $force_text whether to force alternate text to be displayed
83 * @return string an html snippet
85 function PMA_getIcon($icon, $alternate = '', $force_text = false)
87 // $cfg['PropertiesIconic'] is true or both
88 $include_icon = ($GLOBALS['cfg']['PropertiesIconic'] !== false);
89 // $cfg['PropertiesIconic'] is false or both
90 // OR we have no $include_icon
91 $include_text = ($force_text ||
true !== $GLOBALS['cfg']['PropertiesIconic']);
93 // Always use a span (we rely on this in js/sql.js)
94 $button = '<span class="nowrap">';
96 $button .= PMA_getImage($icon, $alternate);
98 if ($include_icon && $include_text) {
102 $button .= $alternate;
104 $button .= '</span>';
110 * Returns an HTML IMG tag for a particular image from a theme,
111 * which may be an actual file or an icon from a sprite
113 * @param string $image The name of the file to get
114 * @param string $alternate Used to set 'alt' and 'title' attributes of the image
115 * @param array $attributes An associative array of other attributes
117 * @return string an html IMG tag
119 function PMA_getImage($image, $alternate = '', $attributes = array())
123 $alternate = htmlspecialchars($alternate);
125 // Check if we have the requested image as a sprite
126 // and set $url accordingly
127 if (is_readable($_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php')) {
128 include_once $_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php';
129 $sprites = PMA_sprites();
130 $class = str_replace(array('.gif','.png'), '', $image);
131 if (array_key_exists($class, $sprites)) {
133 $url = 'themes/dot.gif';
135 $url = $GLOBALS['pmaThemeImage'] . $image;
138 $url = $GLOBALS['pmaThemeImage'] . $image;
140 // set class attribute
142 if (isset($attributes['class'])) {
143 $attributes['class'] = "icon ic_$class " . $attributes['class'];
145 $attributes['class'] = "icon ic_$class";
148 // set all other attributes
150 foreach ($attributes as $key => $value) {
151 if (! in_array($key, array('alt', 'title'))) {
152 $attr_str .= " $key=\"$value\"";
155 // override the alt attribute
156 if (isset($attributes['alt'])) {
157 $alt = $attributes['alt'];
161 // override the title attribute
162 if (isset($attributes['title'])) {
163 $title = $attributes['title'];
167 // generate the IMG tag
168 $template = '<img src="%s" title="%s" alt="%s"%s />';
169 $retval = sprintf($template, $url, $title, $alt, $attr_str);
175 * Displays the maximum size for an upload
177 * @param integer $max_upload_size the size
179 * @return string the message
183 function PMA_displayMaximumUploadSize($max_upload_size)
185 // I have to reduce the second parameter (sensitiveness) from 6 to 4
186 // to avoid weird results like 512 kKib
187 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
188 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
192 * Generates a hidden field which should indicate to the browser
193 * the maximum size for upload
195 * @param integer $max_size the size
197 * @return string the INPUT field
201 function PMA_generateHiddenMaxFileSize($max_size)
203 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
207 * Add slashes before "'" and "\" characters so a value containing them can
208 * be used in a sql comparison.
210 * @param string $a_string the string to slash
211 * @param bool $is_like whether the string will be used in a 'LIKE' clause
212 * (it then requires two more escaped sequences) or not
213 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
214 * (converts \n to \\n, \r to \\r)
215 * @param bool $php_code whether this function is used as part of the
216 * "Create PHP code" dialog
218 * @return string the slashed string
222 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
225 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
227 $a_string = str_replace('\\', '\\\\', $a_string);
233 array("\n" => '\n', "\r" => '\r', "\t" => '\t')
238 $a_string = str_replace('\'', '\\\'', $a_string);
240 $a_string = str_replace('\'', '\'\'', $a_string);
244 } // end of the 'PMA_sqlAddSlashes()' function
248 * Add slashes before "_" and "%" characters for using them in MySQL
249 * database, table and field names.
250 * Note: This function does not escape backslashes!
252 * @param string $name the string to escape
254 * @return string the escaped string
258 function PMA_escape_mysql_wildcards($name)
260 return strtr($name, array('_' => '\\_', '%' => '\\%'));
261 } // end of the 'PMA_escape_mysql_wildcards()' function
264 * removes slashes before "_" and "%" characters
265 * Note: This function does not unescape backslashes!
267 * @param string $name the string to escape
269 * @return string the escaped string
273 function PMA_unescape_mysql_wildcards($name)
275 return strtr($name, array('\\_' => '_', '\\%' => '%'));
276 } // end of the 'PMA_unescape_mysql_wildcards()' function
279 * removes quotes (',",`) from a quoted string
281 * checks if the sting is quoted and removes this quotes
283 * @param string $quoted_string string to remove quotes from
284 * @param string $quote type of quote to remove
286 * @return string unqoted string
288 function PMA_unQuote($quoted_string, $quote = null)
292 if (null === $quote) {
300 foreach ($quotes as $quote) {
301 if (substr($quoted_string, 0, 1) === $quote
302 && substr($quoted_string, -1, 1) === $quote
304 $unquoted_string = substr($quoted_string, 1, -1);
305 // replace escaped quotes
306 $unquoted_string = str_replace(
311 return $unquoted_string;
315 return $quoted_string;
321 * @param mixed $parsed_sql pre-parsed SQL structure
322 * @param string $unparsed_sql raw SQL string
324 * @return string the formatted sql
326 * @global array the configuration array
327 * @global boolean whether the current statement is a multiple one or not
330 * @todo move into PMA_Sql
332 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
336 // Check that we actually have a valid set of parsed data
338 // first check for the SQL parser having hit an error
339 if (PMA_SQP_isError()) {
340 return htmlspecialchars($parsed_sql['raw']);
342 // then check for an array
343 if (! is_array($parsed_sql)) {
344 // We don't so just return the input directly
345 // This is intended to be used for when the SQL Parser is turned off
346 $formatted_sql = "<pre>\n";
347 if ($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') {
348 $formatted_sql .= $unparsed_sql;
350 $formatted_sql .= $parsed_sql;
352 $formatted_sql .= "\n</pre>";
353 return $formatted_sql;
358 switch ($cfg['SQP']['fmtType']) {
360 if ($unparsed_sql != '') {
361 $formatted_sql = '<span class="inner_sql"><pre>' . "\n"
362 . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n"
365 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
369 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
372 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
378 return $formatted_sql;
379 } // end of the "PMA_formatSql()" function
383 * Displays a link to the official MySQL documentation
385 * @param string $chapter chapter of "HTML, one page per chapter" documentation
386 * @param string $link contains name of page/anchor that is being linked
387 * @param bool $big_icon whether to use big icon (like in left frame)
388 * @param string $anchor anchor to page part
389 * @param bool $just_open whether only the opening <a> tag should be returned
391 * @return string the html link
395 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
399 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
403 // Fixup for newly used names:
404 $chapter = str_replace('_', '-', strtolower($chapter));
405 $link = str_replace('_', '-', strtolower($link));
407 switch ($cfg['MySQLManualType']) {
409 if (empty($chapter)) {
412 if (empty($anchor)) {
415 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
418 if (empty($anchor)) {
421 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
427 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
428 if (!empty($anchor)) {
429 $url .= '#' . $anchor;
439 if (defined('PMA_MYSQL_INT_VERSION')) {
440 if (PMA_MYSQL_INT_VERSION
>= 50500) {
442 /* l10n: Please check that translation actually exists. */
443 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
444 } else if (PMA_MYSQL_INT_VERSION
>= 50100) {
446 /* l10n: Please check that translation actually exists. */
447 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
450 /* l10n: Please check that translation actually exists. */
451 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
454 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
455 if (!empty($anchor)) {
456 $url .= '#' . $anchor;
461 $open_link = '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
464 } elseif ($big_icon) {
465 return $open_link . PMA_getImage('b_sqlhelp.png', __('Documentation')) . '</a>';
466 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
467 return $open_link . PMA_getImage('b_help.png', __('Documentation')) . '</a>';
469 return '[' . $open_link . __('Documentation') . '</a>]';
471 } // end of the 'PMA_showMySQLDocu()' function
475 * Displays a link to the phpMyAdmin documentation
477 * @param string $anchor anchor in documentation
479 * @return string the html link
483 function PMA_showDocu($anchor)
485 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
486 return '<a href="Documentation.html#' . $anchor . '" target="documentation">'
487 . PMA_getImage('b_help.png', __('Documentation'))
490 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">'
491 . __('Documentation') . '</a>]';
493 } // end of the 'PMA_showDocu()' function
496 * Displays a link to the PHP documentation
498 * @param string $target anchor in documentation
500 * @return string the html link
504 function PMA_showPHPDocu($target)
506 $url = PMA_getPHPDocLink($target);
508 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
509 return '<a href="' . $url . '" target="documentation">'
510 . PMA_getImage('b_help.png', __('Documentation'))
513 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
515 } // end of the 'PMA_showPHPDocu()' function
518 * returns HTML for a footnote marker and add the messsage to the footnotes
520 * @param string $message the error message
521 * @param bool $bbcode
522 * @param string $type message types
524 * @return string html code for a footnote marker
528 function PMA_showHint($message, $bbcode = false, $type = 'notice')
530 if ($message instanceof PMA_Message
) {
531 $key = $message->getHash();
532 $type = $message->getLevel();
534 $key = md5($message);
537 if (! isset($GLOBALS['footnotes'][$key])) {
538 if (empty($GLOBALS['footnotes']) ||
! is_array($GLOBALS['footnotes'])) {
539 $GLOBALS['footnotes'] = array();
541 $nr = count($GLOBALS['footnotes']) +
1;
542 $GLOBALS['footnotes'][$key] = array(
548 $nr = $GLOBALS['footnotes'][$key]['nr'];
552 return '[sup]' . $nr . '[/sup]';
555 // footnotemarker used in js/tooltip.js
556 return '<sup class="footnotemarker">' . $nr . '</sup>' .
557 PMA_getImage('b_help.png', '', array('class' => 'footnotemarker footnote_' . $nr));
561 * Displays a MySQL error message in the right frame.
563 * @param string $error_message the error message
564 * @param string $the_query the sql query that failed
565 * @param bool $is_modify_link whether to show a "modify" link or not
566 * @param string $back_url the "back" link url (full path is not required)
567 * @param bool $exit EXIT the page?
569 * @global string the curent table
570 * @global string the current db
574 function PMA_mysqlDie($error_message = '', $the_query = '',
575 $is_modify_link = true, $back_url = '', $exit = true)
580 * start http output, display html headers
582 include_once './libraries/header.inc.php';
584 $error_msg_output = '';
586 if (!$error_message) {
587 $error_message = PMA_DBI_getError();
589 if (!$the_query && !empty($GLOBALS['sql_query'])) {
590 $the_query = $GLOBALS['sql_query'];
593 // --- Added to solve bug #641765
594 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
595 $formatted_sql = htmlspecialchars($the_query);
596 } elseif (empty($the_query) ||
trim($the_query) == '') {
599 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
600 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
602 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
606 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
607 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
608 // if the config password is wrong, or the MySQL server does not
609 // respond, do not show the query that would reveal the
611 if (!empty($the_query) && !strstr($the_query, 'connect')) {
612 // --- Added to solve bug #641765
613 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
614 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
615 $error_msg_output .= '<br />' . "\n";
618 // modified to show the help on sql errors
619 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
620 if (strstr(strtolower($formatted_sql), 'select')) {
621 // please show me help to the error on select
622 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
624 if ($is_modify_link) {
625 $_url_params = array(
626 'sql_query' => $the_query,
629 if (strlen($table)) {
630 $_url_params['db'] = $db;
631 $_url_params['table'] = $table;
632 $doedit_goto = '<a href="tbl_sql.php' . PMA_generate_common_url($_url_params) . '">';
633 } elseif (strlen($db)) {
634 $_url_params['db'] = $db;
635 $doedit_goto = '<a href="db_sql.php' . PMA_generate_common_url($_url_params) . '">';
637 $doedit_goto = '<a href="server_sql.php' . PMA_generate_common_url($_url_params) . '">';
640 $error_msg_output .= $doedit_goto
641 . PMA_getIcon('b_edit.png', __('Edit'))
644 $error_msg_output .= ' </p>' . "\n"
646 .' ' . $formatted_sql . "\n"
650 if (! empty($error_message)) {
651 $error_message = preg_replace(
652 "@((\015\012)|(\015)|(\012)){3,}@",
657 // modified to show the help on error-returns
658 // (now error-messages-server)
659 $error_msg_output .= '<p>' . "\n"
660 . ' <strong>' . __('MySQL said: ') . '</strong>'
661 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
665 // The error message will be displayed within a CODE segment.
666 // To preserve original formatting, but allow wordwrapping,
667 // we do a couple of replacements
669 // Replace all non-single blanks with their HTML-counterpart
670 $error_message = str_replace(' ', ' ', $error_message);
671 // Replace TAB-characters with their HTML-counterpart
672 $error_message = str_replace("\t", ' ', $error_message);
673 // Replace linebreaks
674 $error_message = nl2br($error_message);
676 $error_msg_output .= '<code>' . "\n"
677 . $error_message . "\n"
678 . '</code><br />' . "\n";
679 $error_msg_output .= '</div>';
681 $_SESSION['Import_message']['message'] = $error_msg_output;
685 * If in an Ajax request
686 * - avoid displaying a Back link
687 * - use PMA_ajaxResponse() to transmit the message and exit
689 if ($GLOBALS['is_ajax_request'] == true) {
690 PMA_ajaxResponse($error_msg_output, false);
692 if (! empty($back_url)) {
693 if (strstr($back_url, '?')) {
694 $back_url .= '&no_history=true';
696 $back_url .= '?no_history=true';
699 $_SESSION['Import_message']['go_back_url'] = $back_url;
701 $error_msg_output .= '<fieldset class="tblFooters">';
702 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
703 $error_msg_output .= '</fieldset>' . "\n\n";
706 echo $error_msg_output;
708 * display footer and exit
710 include './libraries/footer.inc.php';
712 echo $error_msg_output;
714 } // end of the 'PMA_mysqlDie()' function
717 * returns array with tables of given db with extended information and grouped
719 * @param string $db name of db
720 * @param string $tables name of tables
721 * @param integer $limit_offset list offset
722 * @param int|bool $limit_count max tables to return
724 * @return array (recursive) grouped table list
726 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
728 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
730 if (null === $tables) {
731 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
732 if ($GLOBALS['cfg']['NaturalOrder']) {
733 uksort($tables, 'strnatcasecmp');
737 if (count($tables) < 1) {
748 $table_groups = array();
750 // for blobstreaming - list of blobstreaming tables
752 // load PMA configuration
753 $PMA_Config = $GLOBALS['PMA_Config'];
755 foreach ($tables as $table_name => $table) {
756 // if BS tables exist
757 if (PMA_BS_IsHiddenTable($table_name)) {
761 // check for correct row count
762 if (null === $table['Rows']) {
763 // Do not check exact row count here,
764 // if row count is invalid possibly the table is defect
765 // and this would break left frame;
766 // but we can check row count if this is a view or the
767 // information_schema database
768 // since PMA_Table::countRecords() returns a limited row count
771 // set this because PMA_Table::countRecords() can use it
772 $tbl_is_view = $table['TABLE_TYPE'] == 'VIEW';
774 if ($tbl_is_view ||
PMA_is_system_schema($db)) {
775 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name'], false, true);
779 // in $group we save the reference to the place in $table_groups
780 // where to store the table info
781 if ($GLOBALS['cfg']['LeftFrameDBTree']
782 && $sep && strstr($table_name, $sep)
784 $parts = explode($sep, $table_name);
786 $group =& $table_groups;
788 $group_name_full = '';
789 $parts_cnt = count($parts) - 1;
790 while ($i < $parts_cnt
791 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
792 $group_name = $parts[$i] . $sep;
793 $group_name_full .= $group_name;
795 if (! isset($group[$group_name])) {
796 $group[$group_name] = array();
797 $group[$group_name]['is' . $sep . 'group'] = true;
798 $group[$group_name]['tab' . $sep . 'count'] = 1;
799 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
800 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
801 $table = $group[$group_name];
802 $group[$group_name] = array();
803 $group[$group_name][$group_name] = $table;
805 $group[$group_name]['is' . $sep . 'group'] = true;
806 $group[$group_name]['tab' . $sep . 'count'] = 1;
807 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
809 $group[$group_name]['tab' . $sep . 'count']++
;
811 $group =& $group[$group_name];
815 if (! isset($table_groups[$table_name])) {
816 $table_groups[$table_name] = array();
818 $group =& $table_groups;
822 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
823 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested'
825 // switch tooltip and name
826 $table['Comment'] = $table['Name'];
827 $table['disp_name'] = $table['Comment'];
829 $table['disp_name'] = $table['Name'];
832 $group[$table_name] = array_merge($default, $table);
835 return $table_groups;
838 /* ----------------------- Set of misc functions ----------------------- */
842 * Adds backquotes on both sides of a database, table or field name.
843 * and escapes backquotes inside the name with another backquote
847 * echo PMA_backquote('owner`s db'); // `owner``s db`
851 * @param mixed $a_name the database, table or field name to "backquote"
853 * @param boolean $do_it a flag to bypass this function (used by dump
856 * @return mixed the "backquoted" database, table or field name
860 function PMA_backquote($a_name, $do_it = true)
862 if (is_array($a_name)) {
863 foreach ($a_name as &$data) {
864 $data = PMA_backquote($data, $do_it);
870 global $PMA_SQPdata_forbidden_word;
872 if (! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
877 // '0' is also empty for php :-(
878 if (strlen($a_name) && $a_name !== '*') {
879 return '`' . str_replace('`', '``', $a_name) . '`';
883 } // end of the 'PMA_backquote()' function
886 * Defines the <CR><LF> value depending on the user OS.
888 * @return string the <CR><LF> value to use
892 function PMA_whichCrlf()
894 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
896 if (PMA_USR_OS
== 'Win') {
904 } // end of the 'PMA_whichCrlf()' function
907 * Reloads navigation if needed.
909 * @param bool $jsonly prints out pure JavaScript
913 function PMA_reloadNavigation($jsonly=false)
915 // Reloads the navigation frame via JavaScript if required
916 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
917 // one of the reasons for a reload is when a table is dropped
918 // in this case, get rid of the table limit offset, otherwise
919 // we have a problem when dropping a table on the last page
920 // and the offset becomes greater than the total number of tables
921 unset($_SESSION['tmp_user_values']['table_limit_offset']);
923 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
925 echo '<script type="text/javascript">' . PHP_EOL
;
929 if (typeof(window
.parent
) != 'undefined'
930 && typeof(window
.parent
.frame_navigation
) != 'undefined'
931 && window
.parent
.goTo) {
932 window
.parent
.goTo('<?php echo $reload_url; ?>');
937 echo '</script>' . PHP_EOL
;
940 unset($GLOBALS['reload']);
945 * displays the message and the query
946 * usually the message is the result of the query executed
948 * @param string $message the message to display
949 * @param string $sql_query the query to display
950 * @param string $type the type (level) of the message
951 * @param boolean $is_view is this a message after a VIEW operation?
957 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
960 * PMA_ajaxResponse uses this function to collect the string of HTML generated
961 * for showing the message. Use output buffering to collect it and return it
962 * in a string. In some special cases on sql.php, buffering has to be disabled
963 * and hence we check with $GLOBALS['buffer_message']
965 if ( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
970 if (null === $sql_query) {
971 if (! empty($GLOBALS['display_query'])) {
972 $sql_query = $GLOBALS['display_query'];
973 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
974 $sql_query = $GLOBALS['unparsed_sql'];
975 } elseif (! empty($GLOBALS['sql_query'])) {
976 $sql_query = $GLOBALS['sql_query'];
982 if (isset($GLOBALS['using_bookmark_message'])) {
983 $GLOBALS['using_bookmark_message']->display();
984 unset($GLOBALS['using_bookmark_message']);
987 // Corrects the tooltip text via JS if required
988 // @todo this is REALLY the wrong place to do this - very unexpected here
989 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
990 $tooltip = PMA_Table
::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
991 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
993 echo '<script type="text/javascript">' . "\n";
994 echo '//<![CDATA[' . "\n";
995 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('"
996 . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
998 echo '</script>' . "\n";
999 } // end if ... elseif
1001 // Checks if the table needs to be repaired after a TRUNCATE query.
1002 // @todo what about $GLOBALS['display_query']???
1003 // @todo this is REALLY the wrong place to do this - very unexpected here
1004 if (strlen($GLOBALS['table'])
1005 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])
1007 if (PMA_Table
::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE
) {
1008 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1013 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1014 // check for it's presence before using it
1015 echo '<div id="result_query" align="'
1016 . ( isset($GLOBALS['cell_align_left']) ?
$GLOBALS['cell_align_left'] : '' )
1019 if ($message instanceof PMA_Message
) {
1020 if (isset($GLOBALS['special_message'])) {
1021 $message->addMessage($GLOBALS['special_message']);
1022 unset($GLOBALS['special_message']);
1024 $message->display();
1025 $type = $message->getLevel();
1027 echo '<div class="' . $type . '">';
1028 echo PMA_sanitize($message);
1029 if (isset($GLOBALS['special_message'])) {
1030 echo PMA_sanitize($GLOBALS['special_message']);
1031 unset($GLOBALS['special_message']);
1036 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1037 // Html format the query to be displayed
1038 // If we want to show some sql code it is easiest to create it here
1039 /* SQL-Parser-Analyzer */
1041 if (! empty($GLOBALS['show_as_php'])) {
1042 $new_line = '\\n"<br />' . "\n"
1043 . ' . "';
1044 $query_base = htmlspecialchars(addslashes($sql_query));
1045 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1047 $query_base = $sql_query;
1050 $query_too_big = false;
1052 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1053 // when the query is large (for example an INSERT of binary
1054 // data), the parser chokes; so avoid parsing the query
1055 $query_too_big = true;
1056 $shortened_query_base = nl2br(
1058 substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'
1061 } elseif (! empty($GLOBALS['parsed_sql'])
1062 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1063 // (here, use "! empty" because when deleting a bookmark,
1064 // $GLOBALS['parsed_sql'] is set but empty
1065 $parsed_sql = $GLOBALS['parsed_sql'];
1067 // Parse SQL if needed
1068 $parsed_sql = PMA_SQP_parse($query_base);
1069 if (PMA_SQP_isError()) {
1075 if (isset($parsed_sql)) {
1076 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1078 // Same as below (append LIMIT), append the remembered ORDER BY
1079 if ($GLOBALS['cfg']['RememberSorting']
1080 && isset($analyzed_display_query[0]['queryflags']['select_from'])
1081 && isset($GLOBALS['sql_order_to_append'])
1083 $query_base = $analyzed_display_query[0]['section_before_limit']
1084 . "\n" . $GLOBALS['sql_order_to_append']
1085 . $analyzed_display_query[0]['section_after_limit'];
1087 // Need to reparse query
1088 $parsed_sql = PMA_SQP_parse($query_base);
1089 // update the $analyzed_display_query
1090 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
1091 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
1094 // Here we append the LIMIT added for navigation, to
1095 // enable its display. Adding it higher in the code
1096 // to $sql_query would create a problem when
1097 // using the Refresh or Edit links.
1099 // Only append it on SELECTs.
1102 * @todo what would be the best to do when someone hits Refresh:
1103 * use the current LIMITs ?
1106 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1107 && isset($GLOBALS['sql_limit_to_append'])
1109 $query_base = $analyzed_display_query[0]['section_before_limit']
1110 . "\n" . $GLOBALS['sql_limit_to_append']
1111 . $analyzed_display_query[0]['section_after_limit'];
1112 // Need to reparse query
1113 $parsed_sql = PMA_SQP_parse($query_base);
1117 if (! empty($GLOBALS['show_as_php'])) {
1118 $query_base = '$sql = "' . $query_base;
1119 } elseif (! empty($GLOBALS['validatequery'])) {
1121 $query_base = PMA_validateSQL($query_base);
1122 } catch (Exception
$e) {
1123 PMA_Message
::error(__('Failed to connect to SQL validator!'))->display();
1125 } elseif (isset($parsed_sql)) {
1126 $query_base = PMA_formatSql($parsed_sql, $query_base);
1129 // Prepares links that may be displayed to edit/explain the query
1130 // (don't go to default pages, we must go to the page
1131 // where the query box is available)
1133 // Basic url query part
1134 $url_params = array();
1135 if (! isset($GLOBALS['db'])) {
1136 $GLOBALS['db'] = '';
1138 if (strlen($GLOBALS['db'])) {
1139 $url_params['db'] = $GLOBALS['db'];
1140 if (strlen($GLOBALS['table'])) {
1141 $url_params['table'] = $GLOBALS['table'];
1142 $edit_link = 'tbl_sql.php';
1144 $edit_link = 'db_sql.php';
1147 $edit_link = 'server_sql.php';
1150 // Want to have the query explained
1151 // but only explain a SELECT (that has not been explained)
1152 /* SQL-Parser-Analyzer */
1155 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1156 $explain_params = $url_params;
1157 // Detect if we are validating as well
1158 // To preserve the validate uRL data
1159 if (! empty($GLOBALS['validatequery'])) {
1160 $explain_params['validatequery'] = 1;
1162 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1163 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1164 $_message = __('Explain SQL');
1166 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1167 $explain_params['sql_query'] = substr($sql_query, 8);
1168 $_message = __('Skip Explain SQL');
1170 if (isset($explain_params['sql_query'])) {
1171 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1172 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1176 $url_params['sql_query'] = $sql_query;
1177 $url_params['show_query'] = 1;
1179 // even if the query is big and was truncated, offer the chance
1180 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1181 if (! empty($cfg['SQLQuery']['Edit'])) {
1182 if ($cfg['EditInWindow'] == true) {
1183 $onclick = 'window.parent.focus_querywindow(\''
1184 . PMA_jsFormat($sql_query, false) . '\'); return false;';
1189 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1190 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1195 $url_qpart = PMA_generate_common_url($url_params);
1197 // Also we would like to get the SQL formed in some nice
1199 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1200 $php_params = $url_params;
1202 if (! empty($GLOBALS['show_as_php'])) {
1203 $_message = __('Without PHP Code');
1205 $php_params['show_as_php'] = 1;
1206 $_message = __('Create PHP Code');
1209 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1210 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1212 if (isset($GLOBALS['show_as_php'])) {
1213 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1214 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1221 if (! empty($cfg['SQLQuery']['Refresh'])
1222 && ! isset($GLOBALS['show_as_php']) // 'Submit query' does the same
1223 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)
1225 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1226 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1231 if (! empty($cfg['SQLValidator']['use'])
1232 && ! empty($cfg['SQLQuery']['Validate'])
1234 $validate_params = $url_params;
1235 if (!empty($GLOBALS['validatequery'])) {
1236 $validate_message = __('Skip Validate SQL');
1238 $validate_params['validatequery'] = 1;
1239 $validate_message = __('Validate SQL');
1242 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1243 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1245 $validate_link = '';
1248 if (!empty($GLOBALS['validatequery'])) {
1249 echo '<div class="sqlvalidate">';
1251 echo '<code class="sql">';
1253 if ($query_too_big) {
1254 echo $shortened_query_base;
1259 //Clean up the end of the PHP
1260 if (! empty($GLOBALS['show_as_php'])) {
1263 if (!empty($GLOBALS['validatequery'])) {
1269 echo '<div class="tools">';
1270 // avoid displaying a Profiling checkbox that could
1271 // be checked, which would reexecute an INSERT, for example
1272 if (! empty($refresh_link)) {
1273 PMA_profilingCheckbox($sql_query);
1275 // if needed, generate an invisible form that contains controls for the
1276 // Inline link; this way, the behavior of the Inline link does not
1277 // depend on the profiling support or on the refresh link
1278 if (empty($refresh_link) ||
! PMA_profilingSupported()) {
1279 echo '<form action="sql.php" method="post">';
1280 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1281 echo '<input type="hidden" name="sql_query" value="'
1282 . htmlspecialchars($sql_query) . '" />';
1286 // in the tools div, only display the Inline link when not in ajax
1287 // mode because 1) it currently does not work and 2) we would
1288 // have two similar mechanisms on the page for the same goal
1290 ||
$GLOBALS['is_ajax_request'] === false
1293 // see in js/functions.js the jQuery code attached to id inline_edit
1294 // document.write conflicts with jQuery, hence used $().append()
1295 echo "<script type=\"text/javascript\">\n" .
1297 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1298 PMA_escapeJsString(__('Inline edit of this query')) .
1299 "\" class=\"inline_edit_sql\">" .
1300 PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) .
1305 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1309 if ($GLOBALS['is_ajax_request'] === false) {
1310 echo '<br class="clearfloat" />';
1313 // If we are in an Ajax request, we have most probably been called in
1314 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1315 // to PMA_ajaxResponse(), which will encode it for JSON.
1316 if ($GLOBALS['is_ajax_request'] == true
1317 && ! isset($GLOBALS['buffer_message'])
1319 $buffer_contents = ob_get_contents();
1321 return $buffer_contents;
1324 } // end of the 'PMA_showMessage()' function
1327 * Verifies if current MySQL server supports profiling
1331 * @return boolean whether profiling is supported
1333 function PMA_profilingSupported()
1335 if (! PMA_cacheExists('profiling_supported', true)) {
1336 // 5.0.37 has profiling but for example, 5.1.20 does not
1337 // (avoid a trip to the server for MySQL before 5.0.37)
1338 // and do not set a constant as we might be switching servers
1339 if (defined('PMA_MYSQL_INT_VERSION')
1340 && PMA_MYSQL_INT_VERSION
>= 50037
1341 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")
1343 PMA_cacheSet('profiling_supported', true, true);
1345 PMA_cacheSet('profiling_supported', false, true);
1349 return PMA_cacheGet('profiling_supported', true);
1353 * Displays a form with the Profiling checkbox
1355 * @param string $sql_query sql query
1359 function PMA_profilingCheckbox($sql_query)
1361 if (PMA_profilingSupported()) {
1362 echo '<form action="sql.php" method="post">' . "\n";
1363 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1364 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1365 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1366 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1367 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1368 echo '</form>' . "\n";
1373 * Formats $value to byte view
1375 * @param double $value the value to format
1376 * @param int $limes the sensitiveness
1377 * @param int $comma the number of decimals to retain
1379 * @return array the formatted value and its unit
1383 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1385 if ($value === null) {
1390 /* l10n: shortcuts for Byte */
1392 /* l10n: shortcuts for Kilobyte */
1394 /* l10n: shortcuts for Megabyte */
1396 /* l10n: shortcuts for Gigabyte */
1398 /* l10n: shortcuts for Terabyte */
1400 /* l10n: shortcuts for Petabyte */
1402 /* l10n: shortcuts for Exabyte */
1406 $dh = PMA_pow(10, $comma);
1407 $li = PMA_pow(10, $limes);
1408 $unit = $byteUnits[0];
1410 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1411 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1412 // use 1024.0 to avoid integer overflow on 64-bit machines
1413 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1414 $unit = $byteUnits[$d];
1419 if ($unit != $byteUnits[0]) {
1420 // if the unit is not bytes (as represented in current language)
1421 // reformat with max length of 5
1422 // 4th parameter=true means do not reformat if value < 1
1423 $return_value = PMA_formatNumber($value, 5, $comma, true);
1425 // do not reformat, just handle the locale
1426 $return_value = PMA_formatNumber($value, 0);
1429 return array(trim($return_value), $unit);
1430 } // end of the 'PMA_formatByteDown' function
1433 * Changes thousands and decimal separators to locale specific values.
1435 * @param string $value the value
1439 function PMA_localizeNumber($value)
1444 /* l10n: Thousands separator */
1446 /* l10n: Decimal separator */
1454 * Formats $value to the given length and appends SI prefixes
1455 * with a $length of 0 no truncation occurs, number is only formated
1456 * to the current locale
1460 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1461 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1462 * echo PMA_formatNumber(-0.003, 6); // -3 m
1463 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1464 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1465 * echo PMA_formatNumber(0, 6); // 0
1468 * @param double $value the value to format
1469 * @param integer $digits_left number of digits left of the comma
1470 * @param integer $digits_right number of digits right of the comma
1471 * @param boolean $only_down do not reformat numbers below 1
1472 * @param boolean $noTrailingZero removes trailing zeros right of the comma
1475 * @return string the formatted value and its unit
1479 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0,
1480 $only_down = false, $noTrailingZero = true)
1486 $originalValue = $value;
1487 //number_format is not multibyte safe, str_replace is safe
1488 if ($digits_left === 0) {
1489 $value = number_format($value, $digits_right);
1490 if ($originalValue != 0 && floatval($value) == 0) {
1491 $value = ' <' . (1 / PMA_pow(10, $digits_right));
1494 return PMA_localizeNumber($value);
1497 // this units needs no translation, ISO
1518 // check for negative value to retain sign
1521 $value = abs($value);
1526 $dh = PMA_pow(10, $digits_right);
1529 * This gives us the right SI prefix already,
1530 * but $digits_left parameter not incorporated
1532 $d = floor(log10($value) / 3);
1534 * Lowering the SI prefix by 1 gives us an additional 3 zeros
1535 * So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits)
1536 * to use, then lower the SI prefix
1538 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+
1);
1539 if ($digits_left > $cur_digits) {
1540 $d-= floor(($digits_left - $cur_digits)/3);
1543 if ($d<0 && $only_down) {
1547 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1550 // If we dont want any zeros after the comma just add the thousand seperator
1551 if ($noTrailingZero) {
1552 $value = PMA_localizeNumber(
1553 preg_replace('/(?<=\d)(?=(\d{3})+(?!\d))/', ',', $value)
1556 //number_format is not multibyte safe, str_replace is safe
1557 $value = PMA_localizeNumber(number_format($value, $digits_right));
1560 if ($originalValue!=0 && floatval($value) == 0) {
1561 return ' <' . (1 / PMA_pow(10, $digits_right)) . ' ' . $unit;
1564 return $sign . $value . ' ' . $unit;
1565 } // end of the 'PMA_formatNumber' function
1568 * Returns the number of bytes when a formatted size is given
1570 * @param string $formatted_size the size expression (for example 8MB)
1572 * @return integer The numerical part of the expression (for example 8)
1574 function PMA_extractValueFromFormattedSize($formatted_size)
1578 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1579 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1580 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1581 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1582 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1583 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1585 return $return_value;
1586 }// end of the 'PMA_extractValueFromFormattedSize' function
1589 * Writes localised date
1591 * @param string $timestamp the current timestamp
1592 * @param string $format format
1594 * @return string the formatted date
1598 function PMA_localisedDate($timestamp = -1, $format = '')
1601 /* l10n: Short month name */
1603 /* l10n: Short month name */
1605 /* l10n: Short month name */
1607 /* l10n: Short month name */
1609 /* l10n: Short month name */
1610 _pgettext('Short month name', 'May'),
1611 /* l10n: Short month name */
1613 /* l10n: Short month name */
1615 /* l10n: Short month name */
1617 /* l10n: Short month name */
1619 /* l10n: Short month name */
1621 /* l10n: Short month name */
1623 /* l10n: Short month name */
1625 $day_of_week = array(
1626 /* l10n: Short week day name */
1627 _pgettext('Short week day name', 'Sun'),
1628 /* l10n: Short week day name */
1630 /* l10n: Short week day name */
1632 /* l10n: Short week day name */
1634 /* l10n: Short week day name */
1636 /* l10n: Short week day name */
1638 /* l10n: Short week day name */
1641 if ($format == '') {
1642 /* l10n: See http://www.php.net/manual/en/function.strftime.php */
1643 $format = __('%B %d, %Y at %I:%M %p');
1646 if ($timestamp == -1) {
1647 $timestamp = time();
1650 $date = preg_replace(
1652 $day_of_week[(int)strftime('%w', $timestamp)],
1655 $date = preg_replace(
1657 $month[(int)strftime('%m', $timestamp)-1],
1661 return strftime($date, $timestamp);
1662 } // end of the 'PMA_localisedDate()' function
1666 * returns a tab for tabbed navigation.
1667 * If the variables $link and $args ar left empty, an inactive tab is created
1669 * @param array $tab array with all options
1670 * @param array $url_params
1672 * @return string html code for one tab, a link if valid otherwise a span
1676 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1692 $tab = array_merge($defaults, $tab);
1694 // determine additionnal style-class
1695 if (empty($tab['class'])) {
1696 if (! empty($tab['active'])
1697 ||
PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])
1699 $tab['class'] = 'active';
1700 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1701 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1702 && empty($tab['warning'])) {
1703 $tab['class'] = 'active';
1707 if (!empty($tab['warning'])) {
1708 $tab['class'] .= ' error';
1709 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1712 // If there are any tab specific URL parameters, merge those with
1713 // the general URL parameters
1714 if (! empty($tab['url_params']) && is_array($tab['url_params'])) {
1715 $url_params = array_merge($url_params, $tab['url_params']);
1719 if (!empty($tab['link'])) {
1720 $tab['link'] = htmlentities($tab['link']);
1721 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1722 if (! empty($tab['args'])) {
1723 foreach ($tab['args'] as $param => $value) {
1724 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param)
1725 . '=' . urlencode($value);
1730 if (! empty($tab['fragment'])) {
1731 $tab['link'] .= $tab['fragment'];
1734 // display icon, even if iconic is disabled but the link-text is missing
1735 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1736 && isset($tab['icon'])
1738 // avoid generating an alt tag, because it only illustrates
1739 // the text that follows and if browser does not display
1740 // images, the text is duplicated
1741 $tab['text'] = PMA_getImage(htmlentities($tab['icon'])) . $tab['text'];
1743 } elseif (empty($tab['text'])) {
1744 // check to not display an empty link-text
1747 'empty linktext in function ' . __FUNCTION__
. '()',
1752 //Set the id for the tab, if set in the params
1753 $id_string = ( empty($tab['id']) ?
'' : ' id="'.$tab['id'].'" ' );
1754 $out = '<li' . ($tab['class'] == 'active' ?
' class="active"' : '') . '>';
1756 if (!empty($tab['link'])) {
1757 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1759 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1760 . $tab['text'] . '</a>';
1762 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1763 . $tab['text'] . '</span>';
1768 } // end of the 'PMA_generate_html_tab()' function
1771 * returns html-code for a tab navigation
1773 * @param array $tabs one element per tab
1774 * @param string $url_params
1775 * @param string $base_dir
1776 * @param string $menu_id
1778 * @return string html-code for tab-navigation
1780 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='', $menu_id='topmenu')
1782 $tab_navigation = '<div id="' . htmlentities($menu_id) . 'container" class="menucontainer">'
1783 .'<ul id="' . htmlentities($menu_id) . '">';
1785 foreach ($tabs as $tab) {
1786 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1791 .'<div class="clearfloat"></div>'
1794 return $tab_navigation;
1799 * Displays a link, or a button if the link's URL is too large, to
1800 * accommodate some browsers' limitations
1802 * @param string $url the URL
1803 * @param string $message the link message
1804 * @param mixed $tag_params string: js confirmation
1805 * array: additional tag params (f.e. style="")
1806 * @param boolean $new_form we set this to false when we are already in
1807 * a form, to avoid generating nested forms
1808 * @param boolean $strip_img whether to strip the image
1809 * @param string $target target
1811 * @return string the results to be echoed or saved in an array
1813 function PMA_linkOrButton($url, $message, $tag_params = array(),
1814 $new_form = true, $strip_img = false, $target = '')
1816 $url_length = strlen($url);
1817 // with this we should be able to catch case of image upload
1818 // into a (MEDIUM) BLOB; not worth generating even a form for these
1819 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1824 if (! is_array($tag_params)) {
1826 $tag_params = array();
1828 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1832 if (! empty($target)) {
1833 $tag_params['target'] = htmlentities($target);
1836 $tag_params_strings = array();
1837 foreach ($tag_params as $par_name => $par_value) {
1838 // htmlspecialchars() only on non javascript
1839 $par_value = substr($par_name, 0, 2) == 'on'
1841 : htmlspecialchars($par_value);
1842 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1845 $displayed_message = '';
1846 // Add text if not already added
1847 if (stristr($message, '<img')
1848 && (!$strip_img ||
$GLOBALS['cfg']['PropertiesIconic'] === true)
1849 && strip_tags($message)==$message
1851 $displayed_message = '<span>'
1853 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
1858 // Suhosin: Check that each query parameter is not above maximum
1859 $in_suhosin_limits = true;
1860 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1861 if ($suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length')) {
1862 $query_parts = PMA_splitURLQuery($url);
1863 foreach ($query_parts as $query_pair) {
1864 list($eachvar, $eachval) = explode('=', $query_pair);
1865 if (strlen($eachval) > $suhosin_get_MaxValueLength) {
1866 $in_suhosin_limits = false;
1873 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit'] && $in_suhosin_limits) {
1874 // no whitespace within an <a> else Safari will make it part of the link
1875 $ret = "\n" . '<a href="' . $url . '" '
1876 . implode(' ', $tag_params_strings) . '>'
1877 . $message . $displayed_message . '</a>' . "\n";
1879 // no spaces (linebreaks) at all
1880 // or after the hidden fields
1881 // IE will display them all
1883 // add class=link to submit button
1884 if (empty($tag_params['class'])) {
1885 $tag_params['class'] = 'link';
1888 if (! isset($query_parts)) {
1889 $query_parts = PMA_splitURLQuery($url);
1891 $url_parts = parse_url($url);
1894 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1895 . ' method="post"' . $target . ' style="display: inline;">';
1897 $subname_close = '';
1900 $query_parts[] = 'redirect=' . $url_parts['path'];
1901 if (empty($GLOBALS['subform_counter'])) {
1902 $GLOBALS['subform_counter'] = 0;
1904 $GLOBALS['subform_counter']++
;
1906 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1907 $subname_close = ']';
1908 $submit_link = '#usesubform[' . $GLOBALS['subform_counter'] . ']=1';
1910 foreach ($query_parts as $query_pair) {
1911 list($eachvar, $eachval) = explode('=', $query_pair);
1912 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1913 . $subname_close . '" value="'
1914 . htmlspecialchars(urldecode($eachval)) . '" />';
1917 $ret .= "\n" . '<a href="' . $submit_link . '" class="formLinkSubmit" '
1918 . implode(' ', $tag_params_strings) . '>'
1919 . $message . ' ' . $displayed_message . '</a>' . "\n";
1924 } // end if... else...
1927 } // end of the 'PMA_linkOrButton()' function
1931 * Splits a URL string by parameter
1933 * @param string $url the URL
1935 * @return array the parameter/value pairs, for example [0] db=sakila
1937 function PMA_splitURLQuery($url)
1939 // decode encoded url separators
1940 $separator = PMA_get_arg_separator();
1941 // on most places separator is still hard coded ...
1942 if ($separator !== '&') {
1943 // ... so always replace & with $separator
1944 $url = str_replace(htmlentities('&'), $separator, $url);
1945 $url = str_replace('&', $separator, $url);
1947 $url = str_replace(htmlentities($separator), $separator, $url);
1950 $url_parts = parse_url($url);
1951 return explode($separator, $url_parts['query']);
1955 * Returns a given timespan value in a readable format.
1957 * @param int $seconds the timespan
1959 * @return string the formatted value
1961 function PMA_timespanFormat($seconds)
1963 $days = floor($seconds / 86400);
1965 $seconds -= $days * 86400;
1967 $hours = floor($seconds / 3600);
1968 if ($days > 0 ||
$hours > 0) {
1969 $seconds -= $hours * 3600;
1971 $minutes = floor($seconds / 60);
1972 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1973 $seconds -= $minutes * 60;
1976 __('%s days, %s hours, %s minutes and %s seconds'),
1977 (string)$days, (string)$hours, (string)$minutes, (string)$seconds
1982 * Takes a string and outputs each character on a line for itself. Used
1983 * mainly for horizontalflipped display mode.
1984 * Takes care of special html-characters.
1985 * Fulfills todo-item
1986 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1988 * @param string $string The string
1989 * @param string $Separator The Separator (defaults to "<br />\n")
1992 * @todo add a multibyte safe function PMA_STR_split()
1994 * @return string The flipped string
1996 function PMA_flipstring($string, $Separator = "<br />\n")
1998 $format_string = '';
2001 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++
) {
2002 $char = $string{$i};
2006 $format_string .= $charbuff;
2008 } elseif ($char == ';' && !empty($charbuff)) {
2009 $format_string .= $charbuff . $char;
2012 } elseif (! empty($charbuff)) {
2015 $format_string .= $char;
2019 // do not add separator after the last character
2020 if ($append && ($i != $str_len - 1)) {
2021 $format_string .= $Separator;
2025 return $format_string;
2029 * Function added to avoid path disclosures.
2030 * Called by each script that needs parameters, it displays
2031 * an error message and, by default, stops the execution.
2033 * Not sure we could use a strMissingParameter message here,
2034 * would have to check if the error message file is always available
2036 * @param array $params The names of the parameters needed by the calling script.
2037 * @param bool $die Stop the execution?
2038 * (Set this manually to false in the calling script
2039 * until you know all needed parameters to check).
2040 * @param bool $request Whether to include this list in checking for special params.
2042 * @global string path to current script
2043 * @global boolean flag whether any special variable was required
2046 * @todo use PMA_fatalError() if $die === true?
2048 function PMA_checkParameters($params, $die = true, $request = true)
2050 global $checked_special;
2052 if (! isset($checked_special)) {
2053 $checked_special = false;
2056 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2057 $found_error = false;
2058 $error_message = '';
2060 foreach ($params as $param) {
2061 if ($request && $param != 'db' && $param != 'table') {
2062 $checked_special = true;
2065 if (! isset($GLOBALS[$param])) {
2066 $error_message .= $reported_script_name
2067 . ': ' . __('Missing parameter:') . ' '
2069 . PMA_showDocu('faqmissingparameters')
2071 $found_error = true;
2076 * display html meta tags
2078 include_once './libraries/header_meta_style.inc.php';
2079 echo '</head><body><p>' . $error_message . '</p></body></html>';
2087 * Function to generate unique condition for specified row.
2089 * @param resource $handle current query result
2090 * @param integer $fields_cnt number of fields
2091 * @param array $fields_meta meta information about fields
2092 * @param array $row current row
2093 * @param boolean $force_unique generate condition only on pk or unique
2097 * @return array the calculated condition and whether condition is unique
2099 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique = false)
2103 $nonprimary_condition = '';
2104 $preferred_condition = '';
2105 $primary_key_array = array();
2106 $unique_key_array = array();
2107 $nonprimary_condition_array = array();
2108 $condition_array = array();
2110 for ($i = 0; $i < $fields_cnt; ++
$i) {
2114 $field_flags = PMA_DBI_field_flags($handle, $i);
2115 $meta = $fields_meta[$i];
2117 // do not use a column alias in a condition
2118 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
2119 $meta->orgname
= $meta->name
;
2121 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2122 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])
2124 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
2125 // need (string) === (string)
2126 // '' !== 0 but '' == 0
2127 if ((string) $select_expr['alias'] === (string) $meta->name
) {
2128 $meta->orgname
= $select_expr['column'];
2135 // Do not use a table alias in a condition.
2137 // select * from galerie x WHERE
2138 //(select count(*) from galerie y where y.datum=x.datum)>1
2140 // But orgtable is present only with mysqli extension so the
2141 // fix is only for mysqli.
2142 // Also, do not use the original table name if we are dealing with
2143 // a view because this view might be updatable.
2144 // (The isView() verification should not be costly in most cases
2145 // because there is some caching in the function).
2146 if (isset($meta->orgtable
)
2147 && $meta->table
!= $meta->orgtable
2148 && ! PMA_Table
::isView($GLOBALS['db'], $meta->table
)
2150 $meta->table
= $meta->orgtable
;
2153 // to fix the bug where float fields (primary or not)
2154 // can't be matched because of the imprecision of
2155 // floating comparison, use CONCAT
2156 // (also, the syntax "CONCAT(field) IS NULL"
2157 // that we need on the next "if" will work)
2158 if ($meta->type
== 'real') {
2159 $con_key = 'CONCAT(' . PMA_backquote($meta->table
) . '.'
2160 . PMA_backquote($meta->orgname
) . ')';
2162 $con_key = PMA_backquote($meta->table
) . '.'
2163 . PMA_backquote($meta->orgname
);
2164 } // end if... else...
2165 $condition = ' ' . $con_key . ' ';
2167 if (! isset($row[$i]) ||
is_null($row[$i])) {
2168 $con_val = 'IS NULL';
2170 // timestamp is numeric on some MySQL 4.1
2171 // for real we use CONCAT above and it should compare to string
2173 && $meta->type
!= 'timestamp'
2174 && $meta->type
!= 'real'
2176 $con_val = '= ' . $row[$i];
2177 } elseif (($meta->type
== 'blob' ||
$meta->type
== 'string')
2178 // hexify only if this is a true not empty BLOB or a BINARY
2179 && stristr($field_flags, 'BINARY')
2180 && !empty($row[$i])) {
2181 // do not waste memory building a too big condition
2182 if (strlen($row[$i]) < 1000) {
2183 // use a CAST if possible, to avoid problems
2184 // if the field contains wildcard characters % or _
2185 $con_val = '= CAST(0x' . bin2hex($row[$i]) . ' AS BINARY)';
2187 // this blob won't be part of the final condition
2190 } elseif (in_array($meta->type
, PMA_getGISDatatypes())
2191 && ! empty($row[$i])
2193 // do not build a too big condition
2194 if (strlen($row[$i]) < 5000) {
2195 $condition .= '=0x' . bin2hex($row[$i]) . ' AND';
2199 } elseif ($meta->type
== 'bit') {
2200 $con_val = "= b'" . PMA_printable_bit_value($row[$i], $meta->length
) . "'";
2202 $con_val = '= \'' . PMA_sqlAddSlashes($row[$i], false, true) . '\'';
2205 if ($con_val != null) {
2206 $condition .= $con_val . ' AND';
2207 if ($meta->primary_key
> 0) {
2208 $primary_key .= $condition;
2209 $primary_key_array[$con_key] = $con_val;
2210 } elseif ($meta->unique_key
> 0) {
2211 $unique_key .= $condition;
2212 $unique_key_array[$con_key] = $con_val;
2214 $nonprimary_condition .= $condition;
2215 $nonprimary_condition_array[$con_key] = $con_val;
2219 // Correction University of Virginia 19991216:
2220 // prefer primary or unique keys for condition,
2221 // but use conjunction of all values if no primary key
2222 $clause_is_unique = true;
2224 $preferred_condition = $primary_key;
2225 $condition_array = $primary_key_array;
2226 } elseif ($unique_key) {
2227 $preferred_condition = $unique_key;
2228 $condition_array = $unique_key_array;
2229 } elseif (! $force_unique) {
2230 $preferred_condition = $nonprimary_condition;
2231 $condition_array = $nonprimary_condition_array;
2232 $clause_is_unique = false;
2235 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2236 return(array($where_clause, $clause_is_unique, $condition_array));
2240 * Generate a button or image tag
2242 * @param string $button_name name of button element
2243 * @param string $button_class class of button element
2244 * @param string $image_name name of image element
2245 * @param string $text text to display
2246 * @param string $image image to display
2247 * @param string $value value
2251 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2252 $image, $value = '')
2257 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2258 echo ' <input type="submit" name="' . $button_name . '"'
2259 .' value="' . htmlspecialchars($value) . '"'
2260 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2264 /* Opera has trouble with <input type="image"> */
2265 /* IE has trouble with <button> */
2266 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2267 echo '<button class="' . $button_class . '" type="submit"'
2268 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2269 .' title="' . htmlspecialchars($text) . '">' . "\n"
2270 . PMA_getIcon($image, $text)
2271 .'</button>' . "\n";
2273 echo '<input type="image" name="' . $image_name
2274 . '" value="' . htmlspecialchars($value)
2275 . '" title="' . htmlspecialchars($text)
2276 . '" src="' . $GLOBALS['pmaThemeImage']. $image . '" />'
2277 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both'
2278 ?
' ' . htmlspecialchars($text)
2284 * Generate a pagination selector for browsing resultsets
2286 * @param int $rows Number of rows in the pagination set
2287 * @param int $pageNow current page number
2288 * @param int $nbTotalPage number of total pages
2289 * @param int $showAll If the number of pages is lower than this
2290 * variable, no pages will be omitted in pagination
2291 * @param int $sliceStart How many rows at the beginning should always be shown?
2292 * @param int $sliceEnd How many rows at the end should always be shown?
2293 * @param int $percent Percentage of calculation page offsets to hop to a
2295 * @param int $range Near the current page, how many pages should
2296 * be considered "nearby" and displayed as well?
2297 * @param string $prompt The prompt to display (sometimes empty)
2303 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2304 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2305 $range = 10, $prompt = '')
2307 $increment = floor($nbTotalPage / $percent);
2308 $pageNowMinusRange = ($pageNow - $range);
2309 $pageNowPlusRange = ($pageNow +
$range);
2311 $gotopage = $prompt . ' <select id="pageselector" ';
2312 if ($GLOBALS['cfg']['AjaxEnable']) {
2313 $gotopage .= ' class="ajax"';
2315 $gotopage .= ' name="pos" >' . "\n";
2316 if ($nbTotalPage < $showAll) {
2317 $pages = range(1, $nbTotalPage);
2321 // Always show first X pages
2322 for ($i = 1; $i <= $sliceStart; $i++
) {
2326 // Always show last X pages
2327 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2331 // Based on the number of results we add the specified
2332 // $percent percentage to each page number,
2333 // so that we have a representing page number every now and then to
2334 // immediately jump to specific pages.
2335 // As soon as we get near our currently chosen page ($pageNow -
2336 // $range), every page number will be shown.
2338 $x = $nbTotalPage - $sliceEnd;
2339 $met_boundary = false;
2341 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2342 // If our pageselector comes near the current page, we use 1
2343 // counter increments
2345 $met_boundary = true;
2347 // We add the percentage increment to our current page to
2348 // hop to the next one in range
2351 // Make sure that we do not cross our boundaries.
2352 if ($i > $pageNowMinusRange && ! $met_boundary) {
2353 $i = $pageNowMinusRange;
2357 if ($i > 0 && $i <= $x) {
2363 Add page numbers with "geometrically increasing" distances.
2365 This helps me a lot when navigating through giant tables.
2367 Test case: table with 2.28 million sets, 76190 pages. Page of interest is
2368 between 72376 and 76190.
2369 Selecting page 72376.
2370 Now, old version enumerated only +/- 10 pages around 72376 and the
2371 percentage increment produced steps of about 3000.
2373 The following code adds page numbers +/- 2,4,8,16,32,64,128,256 etc.
2374 around the current page.
2381 $i = $pageNow +
$dist;
2382 if ($i > 0 && $i <= $x) {
2391 $i = $pageNow - $dist;
2392 if ($i > 0 && $i <= $x) {
2397 // Since because of ellipsing of the current page some numbers may be double,
2398 // we unify our array:
2400 $pages = array_unique($pages);
2403 foreach ($pages as $i) {
2404 if ($i == $pageNow) {
2405 $selected = 'selected="selected" style="font-weight: bold"';
2409 $gotopage .= ' <option ' . $selected
2410 . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2413 $gotopage .= ' </select><noscript><input type="submit" value="'
2414 . __('Go') . '" /></noscript>';
2421 * Generate navigation for a list
2423 * @param int $count number of elements in the list
2424 * @param int $pos current position in the list
2425 * @param array $_url_params url parameters
2426 * @param string $script script name for form target
2427 * @param string $frame target frame
2428 * @param int $max_count maximum number of elements to display from the list
2432 * @todo use $pos from $_url_params
2434 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count)
2437 if ($max_count < $count) {
2438 echo 'frame_navigation' == $frame
2439 ?
'<div id="navidbpageselector">' . "\n"
2441 echo __('Page number:');
2442 echo 'frame_navigation' == $frame ?
'<br />' : ' ';
2444 // Move to the beginning or to the previous page
2446 // patch #474210 - part 1
2447 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2448 $caption1 = '<<';
2449 $caption2 = ' < ';
2450 $title1 = ' title="' . _pgettext('First page', 'Begin') . '"';
2451 $title2 = ' title="' . _pgettext('Previous page', 'Previous') . '"';
2453 $caption1 = _pgettext('First page', 'Begin') . ' <<';
2454 $caption2 = _pgettext('Previous page', 'Previous') . ' <';
2457 } // end if... else...
2458 $_url_params['pos'] = 0;
2459 echo '<a' . $title1 . ' href="' . $script
2460 . PMA_generate_common_url($_url_params) . '" target="'
2461 . $frame . '">' . $caption1 . '</a>';
2462 $_url_params['pos'] = $pos - $max_count;
2463 echo '<a' . $title2 . ' href="' . $script
2464 . PMA_generate_common_url($_url_params) . '" target="'
2465 . $frame . '">' . $caption2 . '</a>';
2468 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2469 echo PMA_generate_common_hidden_inputs($_url_params);
2470 echo PMA_pageselector(
2472 floor(($pos +
1) / $max_count) +
1,
2473 ceil($count / $max_count)
2477 if ($pos +
$max_count < $count) {
2478 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2479 $caption3 = ' > ';
2480 $caption4 = '>>';
2481 $title3 = ' title="' . _pgettext('Next page', 'Next') . '"';
2482 $title4 = ' title="' . _pgettext('Last page', 'End') . '"';
2484 $caption3 = '> ' . _pgettext('Next page', 'Next');
2485 $caption4 = '>> ' . _pgettext('Last page', 'End');
2488 } // end if... else...
2489 $_url_params['pos'] = $pos +
$max_count;
2490 echo '<a' . $title3 . ' href="' . $script
2491 . PMA_generate_common_url($_url_params) . '" target="'
2492 . $frame . '">' . $caption3 . '</a>';
2493 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2494 if ($_url_params['pos'] == $count) {
2495 $_url_params['pos'] = $count - $max_count;
2497 echo '<a' . $title4 . ' href="' . $script
2498 . PMA_generate_common_url($_url_params) . '" target="'
2499 . $frame . '">' . $caption4 . '</a>';
2502 if ('frame_navigation' == $frame) {
2503 echo '</div>' . "\n";
2509 * replaces %u in given path with current user name
2513 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2517 * @param string $dir with wildcard for user
2519 * @return string per user directory
2521 function PMA_userDir($dir)
2523 // add trailing slash
2524 if (substr($dir, -1) != '/') {
2528 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2532 * returns html code for db link to default db page
2534 * @param string $database database
2536 * @return string html link to default db page
2538 function PMA_getDbLink($database = null)
2540 if (! strlen($database)) {
2541 if (! strlen($GLOBALS['db'])) {
2544 $database = $GLOBALS['db'];
2546 $database = PMA_unescape_mysql_wildcards($database);
2549 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?'
2550 . PMA_generate_common_url($database) . '" title="'
2552 __('Jump to database "%s".'),
2553 htmlspecialchars($database)
2555 . '">' . htmlspecialchars($database) . '</a>';
2559 * Displays a lightbulb hint explaining a known external bug
2560 * that affects a functionality
2562 * @param string $functionality localized message explaining the func.
2563 * @param string $component 'mysql' (eventually, 'php')
2564 * @param string $minimum_version of this component
2565 * @param string $bugref bug reference for this component
2567 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2569 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION
< $minimum_version) {
2572 __('The %s functionality is affected by a known bug, see %s'),
2574 PMA_linkURL('http://bugs.mysql.com/') . $bugref
2581 * Generates and echoes an HTML checkbox
2583 * @param string $html_field_name the checkbox HTML field
2584 * @param string $label label for checkbox
2585 * @param boolean $checked is it initially checked?
2586 * @param boolean $onclick should it submit the form on click?
2588 * @return the HTML for the checkbox
2590 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick)
2593 echo '<input type="checkbox" name="' . $html_field_name . '" id="'
2594 . $html_field_name . '"' . ($checked ?
' checked="checked"' : '')
2595 . ($onclick ?
' class="autosubmit"' : '') . ' /><label for="'
2596 . $html_field_name . '">' . $label . '</label>';
2600 * Generates and echoes a set of radio HTML fields
2602 * @param string $html_field_name the radio HTML field
2603 * @param array $choices the choices values and labels
2604 * @param string $checked_choice the choice to check by default
2605 * @param boolean $line_break whether to add an HTML line break after a choice
2606 * @param boolean $escape_label whether to use htmlspecialchars() on label
2607 * @param string $class enclose each choice with a div of this class
2609 * @return the HTML for the tadio buttons
2611 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '',
2612 $line_break = true, $escape_label = true, $class='')
2614 foreach ($choices as $choice_value => $choice_label) {
2615 if (! empty($class)) {
2616 echo '<div class="' . $class . '">';
2618 $html_field_id = $html_field_name . '_' . $choice_value;
2619 echo '<input type="radio" name="' . $html_field_name . '" id="'
2620 . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2621 if ($choice_value == $checked_choice) {
2622 echo ' checked="checked"';
2625 echo '<label for="' . $html_field_id . '">'
2626 . ($escape_label ?
htmlspecialchars($choice_label) : $choice_label)
2631 if (! empty($class)) {
2639 * Generates and returns an HTML dropdown
2641 * @param string $select_name name for the select element
2642 * @param array $choices choices values
2643 * @param string $active_choice the choice to select by default
2644 * @param string $id id of the select element; can be different in case
2645 * the dropdown is present more than once on the page
2649 * @todo support titles
2651 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2653 $result = '<select name="' . htmlspecialchars($select_name) . '" id="'
2654 . htmlspecialchars($id) . '">';
2655 foreach ($choices as $one_choice_value => $one_choice_label) {
2656 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2657 if ($one_choice_value == $active_choice) {
2658 $result .= ' selected="selected"';
2660 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2662 $result .= '</select>';
2667 * Generates a slider effect (jQjuery)
2668 * Takes care of generating the initial <div> and the link
2669 * controlling the slider; you have to generate the </div> yourself
2670 * after the sliding section.
2672 * @param string $id the id of the <div> on which to apply the effect
2673 * @param string $message the message to show as a link
2675 function PMA_generate_slider_effect($id, $message)
2677 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2678 echo '<div id="' . $id . '">';
2682 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2683 * opening the <div> with PHP itself instead of JavaScript.
2685 * @todo find a better solution that uses $.append(), the recommended method
2686 * maybe by using an additional param, the id of the div to append to
2689 <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); ?>">
2694 * Creates an AJAX sliding toggle button
2695 * (or and equivalent form when AJAX is disabled)
2697 * @param string $action The URL for the request to be executed
2698 * @param string $select_name The name for the dropdown box
2699 * @param array $options An array of options (see rte_footer.lib.php)
2700 * @param string $callback A JS snippet to execute when the request is
2701 * successfully processed
2703 * @return string HTML code for the toggle button
2705 function PMA_toggleButton($action, $select_name, $options, $callback)
2707 // Do the logic first
2708 $link_on = "$action&$select_name=" . urlencode($options[1]['value']);
2709 $link_off = "$action&$select_name=" . urlencode($options[0]['value']);
2710 if ($options[1]['selected'] == true) {
2712 } else if ($options[0]['selected'] == true) {
2719 if ($options[1]['selected'] == true) {
2720 $selected1 = " selected='selected'";
2721 } else if ($options[0]['selected'] == true) {
2722 $selected0 = " selected='selected'";
2725 $retval = "<!-- TOGGLE START -->\n";
2726 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2727 $retval .= "<noscript>\n";
2729 $retval .= "<div class='wrapper'>\n";
2730 $retval .= " <form action='$action' method='post'>\n";
2731 $retval .= " <select name='$select_name'>\n";
2732 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2733 $retval .= " {$options[1]['label']}\n";
2734 $retval .= " </option>\n";
2735 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2736 $retval .= " {$options[0]['label']}\n";
2737 $retval .= " </option>\n";
2738 $retval .= " </select>\n";
2739 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2740 $retval .= " </form>\n";
2741 $retval .= "</div>\n";
2742 if ($GLOBALS['cfg']['AjaxEnable'] && is_readable($_SESSION['PMA_Theme']->getImgPath() . 'toggle-ltr.png')) {
2743 $retval .= "</noscript>\n";
2744 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2745 $retval .= " <div class='toggleButton'>\n";
2746 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2747 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2748 $retval .= " alt='' />\n";
2749 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2750 $retval .= " <tbody>\n";
2751 $retval .= " <td class='toggleOn'>\n";
2752 $retval .= " <span class='hide'>$link_on</span>\n";
2753 $retval .= " <div>";
2754 $retval .= str_replace(' ', ' ', $options[1]['label']) . "</div>\n";
2755 $retval .= " </td>\n";
2756 $retval .= " <td><div> </div></td>\n";
2757 $retval .= " <td class='toggleOff'>\n";
2758 $retval .= " <span class='hide'>$link_off</span>\n";
2759 $retval .= " <div>";
2760 $retval .= str_replace(' ', ' ', $options[0]['label']) . "</div>\n";
2761 $retval .= " </div>\n";
2762 $retval .= " </tbody>\n";
2763 $retval .= " </tr></table>\n";
2764 $retval .= " <span class='hide callback'>$callback</span>\n";
2765 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2766 $retval .= " </div>\n";
2767 $retval .= " </div>\n";
2768 $retval .= "</div>\n";
2770 $retval .= "<!-- TOGGLE END -->";
2773 } // end PMA_toggleButton()
2776 * Clears cache content which needs to be refreshed on user change.
2780 function PMA_clearUserCache()
2782 PMA_cacheUnset('is_superuser', true);
2786 * Verifies if something is cached in the session
2788 * @param string $var variable name
2789 * @param int|true $server server
2793 function PMA_cacheExists($var, $server = 0)
2795 if (true === $server) {
2796 $server = $GLOBALS['server'];
2798 return isset($_SESSION['cache']['server_' . $server][$var]);
2802 * Gets cached information from the session
2804 * @param string $var varibale name
2805 * @param int|true $server server
2809 function PMA_cacheGet($var, $server = 0)
2811 if (true === $server) {
2812 $server = $GLOBALS['server'];
2814 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2815 return $_SESSION['cache']['server_' . $server][$var];
2822 * Caches information in the session
2824 * @param string $var variable name
2825 * @param mixed $val value
2826 * @param int|true $server server
2830 function PMA_cacheSet($var, $val = null, $server = 0)
2832 if (true === $server) {
2833 $server = $GLOBALS['server'];
2835 $_SESSION['cache']['server_' . $server][$var] = $val;
2839 * Removes cached information from the session
2841 * @param string $var variable name
2842 * @param int|true $server server
2846 function PMA_cacheUnset($var, $server = 0)
2848 if (true === $server) {
2849 $server = $GLOBALS['server'];
2851 unset($_SESSION['cache']['server_' . $server][$var]);
2855 * Converts a bit value to printable format;
2856 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2857 * function because in PHP, decbin() supports only 32 bits
2859 * @param numeric $value coming from a BIT field
2860 * @param integer $length length
2862 * @return string the printable value
2864 function PMA_printable_bit_value($value, $length)
2867 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++
) {
2868 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2870 $printable = substr($printable, -$length);
2875 * Verifies whether the value contains a non-printable character
2877 * @param string $value value
2881 function PMA_contains_nonprintable_ascii($value)
2883 return preg_match('@[^[:print:]]@', $value);
2887 * Converts a BIT type default value
2888 * for example, b'010' becomes 010
2890 * @param string $bit_default_value value
2892 * @return string the converted value
2894 function PMA_convert_bit_default_value($bit_default_value)
2896 return strtr($bit_default_value, array("b" => "", "'" => ""));
2900 * Extracts the various parts from a field type spec
2902 * @param string $fieldspec Field specification
2904 * @return array associative array containing type, spec_in_brackets
2905 * and possibly enum_set_values (another array)
2907 function PMA_extractFieldSpec($fieldspec)
2909 $first_bracket_pos = strpos($fieldspec, '(');
2910 if ($first_bracket_pos) {
2911 $spec_in_brackets = chop(
2914 $first_bracket_pos +
1,
2915 (strrpos($fieldspec, ')') - $first_bracket_pos - 1)
2918 // convert to lowercase just to be sure
2919 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2921 $type = strtolower($fieldspec);
2922 $spec_in_brackets = '';
2925 if ('enum' == $type ||
'set' == $type) {
2926 // Define our working vars
2927 $enum_set_values = array();
2932 // While there is another character to process
2933 while (isset($fieldspec[$index])) {
2934 // Grab the char to look at
2935 $char = $fieldspec[$index];
2937 // If it is a single quote, needs to be handled specially
2939 // If we are not currently in a string, begin one
2944 // Otherwise, it may be either an end of a string,
2945 // or a 'double quote' which can be handled as-is
2946 // Check out the next character (if possible)
2947 $has_next = isset($fieldspec[$index +
1]);
2948 $next = $has_next ?
$fieldspec[$index +
1] : null;
2950 //If we have reached the end of our 'working' string (because
2951 //there are no more chars,or the next char is not another quote)
2952 if (! $has_next ||
$next != "'") {
2953 $enum_set_values[] = $working;
2956 } elseif ($next == "'") {
2957 // Otherwise, this is a 'double quote',
2958 // and can be added to the working string
2960 // Skip the next char; we already know what it is
2964 } elseif ('\\' == $char
2965 && isset($fieldspec[$index +
1])
2966 && "'" == $fieldspec[$index +
1]
2968 // escaping of a quote?
2972 // Otherwise, add it to our working string like normal
2975 // Increment character index
2978 $printtype = $type . '(' . str_replace("','", "', '", $spec_in_brackets) . ')';
2983 $enum_set_values = array();
2985 /* Create printable type name */
2986 $printtype = strtolower($fieldspec);
2988 // Strip the "BINARY" attribute, except if we find "BINARY(" because
2989 // this would be a BINARY or VARBINARY field type;
2990 // by the way, a BLOB should not show the BINARY attribute
2991 // because this is not accepted in MySQL syntax.
2992 if (preg_match('@binary@', $printtype) && ! preg_match('@binary[\(]@', $printtype)) {
2993 $printtype = preg_replace('@binary@', '', $printtype);
2998 $printtype = preg_replace('@zerofill@', '', $printtype, -1, $zerofill_cnt);
2999 $zerofill = ($zerofill_cnt > 0);
3000 $printtype = preg_replace('@unsigned@', '', $printtype, -1, $unsigned_cnt);
3001 $unsigned = ($unsigned_cnt > 0);
3002 $printtype = trim($printtype);
3008 $attribute = 'BINARY';
3011 $attribute = 'UNSIGNED';
3014 $attribute = 'UNSIGNED ZEROFILL';
3019 'spec_in_brackets' => $spec_in_brackets,
3020 'enum_set_values' => $enum_set_values,
3021 'print_type' => $printtype,
3022 'binary' => $binary,
3023 'unsigned' => $unsigned,
3024 'zerofill' => $zerofill,
3025 'attribute' => $attribute,
3030 * Verifies if this table's engine supports foreign keys
3032 * @param string $engine engine
3036 function PMA_foreignkey_supported($engine)
3038 $engine = strtoupper($engine);
3039 if ('INNODB' == $engine ||
'PBXT' == $engine) {
3047 * Replaces some characters by a displayable equivalent
3049 * @param string $content content
3051 * @return string the content with characters replaced
3053 function PMA_replace_binary_contents($content)
3055 $result = str_replace("\x00", '\0', $content);
3056 $result = str_replace("\x08", '\b', $result);
3057 $result = str_replace("\x0a", '\n', $result);
3058 $result = str_replace("\x0d", '\r', $result);
3059 $result = str_replace("\x1a", '\Z', $result);
3064 * Converts GIS data to Well Known Text format
3066 * @param binary $data GIS data
3067 * @param bool $includeSRID Add SRID to the WKT
3069 * @return GIS data in Well Know Text format
3071 function PMA_asWKT($data, $includeSRID = false)
3073 // Convert to WKT format
3074 $hex = bin2hex($data);
3075 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
3077 $wktsql .= ", SRID(x'" . $hex . "')";
3079 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE
);
3080 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
3081 $wktval = $wktarr[0];
3084 $wktval = "'" . $wktval . "'," . $srid;
3086 @PMA_DBI_free_result
($wktresult);
3091 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
3093 * @param string $string string
3095 * @return string with the chars replaced
3098 function PMA_duplicateFirstNewline($string)
3100 $first_occurence = strpos($string, "\r\n");
3101 if ($first_occurence === 0) {
3102 $string = "\n".$string;
3108 * Get the action word corresponding to a script name
3109 * in order to display it as a title in navigation panel
3111 * @param string $target a valid value for $cfg['LeftDefaultTabTable'],
3112 * $cfg['DefaultTabTable'] or $cfg['DefaultTabDatabase']
3116 function PMA_getTitleForTarget($target)
3119 // Values for $cfg['DefaultTabTable']
3120 'tbl_structure.php' => __('Structure'),
3121 'tbl_sql.php' => __('SQL'),
3122 'tbl_select.php' =>__('Search'),
3123 'tbl_change.php' =>__('Insert'),
3124 'sql.php' => __('Browse'),
3126 // Values for $cfg['DefaultTabDatabase']
3127 'db_structure.php' => __('Structure'),
3128 'db_sql.php' => __('SQL'),
3129 'db_search.php' => __('Search'),
3130 'db_operations.php' => __('Operations'),
3132 return $mapping[$target];
3136 * Formats user string, expanding @VARIABLES@, accepting strftime format string.
3138 * @param string $string Text where to do expansion.
3139 * @param function $escape Function to call for escaping variable values.
3140 * @param array $updates Array with overrides for default parameters
3141 * (obtained from GLOBALS).
3145 function PMA_expandUserString($string, $escape = null, $updates = array())
3148 $vars['http_host'] = PMA_getenv('HTTP_HOST') ?
PMA_getenv('HTTP_HOST') : '';
3149 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
3150 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
3151 $vars['server_verbose_or_name'] = ! empty($GLOBALS['cfg']['Server']['verbose'])
3152 ?
$GLOBALS['cfg']['Server']['verbose']
3153 : $GLOBALS['cfg']['Server']['host'];
3154 $vars['database'] = $GLOBALS['db'];
3155 $vars['table'] = $GLOBALS['table'];
3156 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION
;
3158 /* Update forced variables */
3159 foreach ($updates as $key => $val) {
3163 /* Replacement mapping */
3165 * The __VAR__ ones are for backward compatibility, because user
3166 * might still have it in cookies.
3169 '@HTTP_HOST@' => $vars['http_host'],
3170 '@SERVER@' => $vars['server_name'],
3171 '__SERVER__' => $vars['server_name'],
3172 '@VERBOSE@' => $vars['server_verbose'],
3173 '@VSERVER@' => $vars['server_verbose_or_name'],
3174 '@DATABASE@' => $vars['database'],
3175 '__DB__' => $vars['database'],
3176 '@TABLE@' => $vars['table'],
3177 '__TABLE__' => $vars['table'],
3178 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
3181 /* Optional escaping */
3182 if (!is_null($escape)) {
3183 foreach ($replace as $key => $val) {
3184 $replace[$key] = $escape($val);
3188 /* Backward compatibility in 3.5.x */
3189 if (strpos($string, '@FIELDS@') !== false) {
3190 $string = strtr($string, array('@FIELDS@' => '@COLUMNS@'));
3193 /* Fetch columns list if required */
3194 if (strpos($string, '@COLUMNS@') !== false) {
3195 $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']);
3197 $column_names = array();
3198 foreach ($columns_list as $column) {
3199 if (! is_null($escape)) {
3200 $column_names[] = $escape($column['Field']);
3202 $column_names[] = $field['Field'];
3206 $replace['@COLUMNS@'] = implode(',', $column_names);
3209 /* Do the replacement */
3210 return strtr(strftime($string), $replace);
3214 * function that generates a json output for an ajax request and ends script
3217 * @param PMA_Message|string $message message string containing the
3218 * html of the message
3219 * @param bool $success success whether the ajax request
3221 * @param array $extra_data extra data optional -
3222 * any other data as part of the json request
3226 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
3228 $response = array();
3229 if ( $success == true ) {
3230 $response['success'] = true;
3231 if ($message instanceof PMA_Message
) {
3232 $response['message'] = $message->getDisplay();
3234 $response['message'] = $message;
3237 $response['success'] = false;
3238 if ($message instanceof PMA_Message
) {
3239 $response['error'] = $message->getDisplay();
3241 $response['error'] = $message;
3245 // If extra_data has been provided, append it to the response array
3246 if ( ! empty($extra_data) && count($extra_data) > 0 ) {
3247 $response = array_merge($response, $extra_data);
3250 // Set the Content-Type header to JSON so that jQuery parses the
3251 // response correctly.
3253 // At this point, other headers might have been sent;
3254 // even if $GLOBALS['is_header_sent'] is true,
3255 // we have to send these additional headers.
3256 header('Cache-Control: no-cache');
3257 header("Content-Type: application/json");
3259 echo json_encode($response);
3261 if (!defined('TESTSUITE'))
3266 * Display the form used to browse anywhere on the local server for a file to import
3268 * @param string $max_upload_size maximum upload size
3272 function PMA_browseUploadFile($max_upload_size)
3274 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
3275 echo '<div id="upload_form_status" style="display: none;"></div>';
3276 echo '<div id="upload_form_status_info" style="display: none;"></div>';
3277 echo '<input type="file" name="import_file" id="input_import_file" />';
3278 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
3279 // some browsers should respect this :)
3280 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
3284 * Display the form used to select a file to import from the server upload directory
3286 * @param array $import_list array of import types
3287 * @param string $uploaddir upload directory
3291 function PMA_selectUploadFile($import_list, $uploaddir)
3293 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
3295 foreach ($import_list as $key => $val) {
3296 if (!empty($extensions)) {
3299 $extensions .= $val['extension'];
3301 $matcher = '@\.(' . $extensions . ')(\.('
3302 . PMA_supportedDecompressions() . '))?$@';
3304 $active = (isset($timeout_passed) && $timeout_passed && isset($local_import_file))
3305 ?
$local_import_file
3307 $files = PMA_getFileSelectOptions(
3308 PMA_userDir($uploaddir),
3312 if ($files === false) {
3314 __('The directory you set for upload work cannot be reached')
3316 } elseif (!empty($files)) {
3318 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
3319 echo ' <option value=""> </option>' . "\n";
3321 echo ' </select>' . "\n";
3322 } elseif (empty ($files)) {
3323 echo '<i>' . __('There are no files to upload') . '</i>';
3328 * Build titles and icons for action links
3330 * @return array the action titles
3332 function PMA_buildActionTitles()
3336 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'));
3337 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'));
3338 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'));
3339 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'));
3340 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'));
3341 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'));
3342 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'));
3343 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'));
3344 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'));
3345 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'));
3346 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'));
3347 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'));
3348 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'));
3349 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'));
3350 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'));
3351 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'));
3352 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'));
3357 * This function processes the datatypes supported by the DB, as specified in
3358 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
3359 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
3361 * @param bool $html Whether to generate an html snippet or an array
3362 * @param string $selected The value to mark as selected in HTML mode
3364 * @return mixed An HTML snippet or an array of datatypes.
3367 function PMA_getSupportedDatatypes($html = false, $selected = '')
3372 // NOTE: the SELECT tag in not included in this snippet.
3374 foreach ($cfg['ColumnTypes'] as $key => $value) {
3375 if (is_array($value)) {
3376 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
3377 foreach ($value as $subvalue) {
3378 if ($subvalue == $selected) {
3379 $retval .= "<option selected='selected'>";
3380 $retval .= $subvalue;
3381 $retval .= "</option>";
3382 } else if ($subvalue === '-') {
3383 $retval .= "<option disabled='disabled'>";
3384 $retval .= $subvalue;
3385 $retval .= "</option>";
3387 $retval .= "<option>$subvalue</option>";
3390 $retval .= '</optgroup>';
3392 if ($selected == $value) {
3393 $retval .= "<option selected='selected'>$value</option>";
3395 $retval .= "<option>$value</option>";
3401 foreach ($cfg['ColumnTypes'] as $value) {
3402 if (is_array($value)) {
3403 foreach ($value as $subvalue) {
3404 if ($subvalue !== '-') {
3405 $retval[] = $subvalue;
3409 if ($value !== '-') {
3417 } // end PMA_getSupportedDatatypes()
3420 * Returns a list of datatypes that are not (yet) handled by PMA.
3421 * Used by: tbl_change.php and libraries/db_routines.inc.php
3423 * @return array list of datatypes
3425 function PMA_unsupportedDatatypes()
3427 $no_support_types = array();
3428 return $no_support_types;
3432 * Return GIS data types
3434 * @param bool $upper_case whether to return values in upper case
3436 * @return array GIS data types
3438 function PMA_getGISDatatypes($upper_case = false)
3440 $gis_data_types = array(
3448 'geometrycollection'
3451 for ($i = 0; $i < count($gis_data_types); $i++
) {
3452 $gis_data_types[$i] = strtoupper($gis_data_types[$i]);
3456 return $gis_data_types;
3460 * Generates GIS data based on the string passed.
3462 * @param string $gis_string GIS string
3464 * @return GIS data enclosed in 'GeomFromText' function
3466 function PMA_createGISData($gis_string)
3468 $gis_string = trim($gis_string);
3469 $geom_types = '(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|'
3470 . 'POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)';
3471 if (preg_match("/^'" . $geom_types . "\(.*\)',[0-9]*$/i", $gis_string)) {
3472 return 'GeomFromText(' . $gis_string . ')';
3473 } elseif (preg_match("/^" . $geom_types . "\(.*\)$/i", $gis_string)) {
3474 return "GeomFromText('" . $gis_string . "')";
3481 * Returns the names and details of the functions
3482 * that can be applied on geometry data typess.
3484 * @param string $geom_type if provided the output is limited to the functions
3485 * that are applicable to the provided geometry type.
3486 * @param bool $binary if set to false functions that take two geometries
3487 * as arguments will not be included.
3488 * @param bool $display if set to true seperators will be added to the
3491 * @return array names and details of the functions that can be applied on
3492 * geometry data typess.
3494 function PMA_getGISFunctions($geom_type = null, $binary = true, $display = false)
3498 $funcs[] = array('display' => ' ');
3501 // Unary functions common to all geomety types
3502 $funcs['Dimension'] = array('params' => 1, 'type' => 'int');
3503 $funcs['Envelope'] = array('params' => 1, 'type' => 'Polygon');
3504 $funcs['GeometryType'] = array('params' => 1, 'type' => 'text');
3505 $funcs['SRID'] = array('params' => 1, 'type' => 'int');
3506 $funcs['IsEmpty'] = array('params' => 1, 'type' => 'int');
3507 $funcs['IsSimple'] = array('params' => 1, 'type' => 'int');
3509 $geom_type = trim(strtolower($geom_type));
3510 if ($display && $geom_type != 'geometry' && $geom_type != 'multipoint') {
3511 $funcs[] = array('display' => '--------');
3514 // Unary functions that are specific to each geomety type
3515 if ($geom_type == 'point') {
3516 $funcs['X'] = array('params' => 1, 'type' => 'float');
3517 $funcs['Y'] = array('params' => 1, 'type' => 'float');
3519 } elseif ($geom_type == 'multipoint') {
3520 // no fucntions here
3521 } elseif ($geom_type == 'linestring') {
3522 $funcs['EndPoint'] = array('params' => 1, 'type' => 'point');
3523 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3524 $funcs['NumPoints'] = array('params' => 1, 'type' => 'int');
3525 $funcs['StartPoint'] = array('params' => 1, 'type' => 'point');
3526 $funcs['IsRing'] = array('params' => 1, 'type' => 'int');
3528 } elseif ($geom_type == 'multilinestring') {
3529 $funcs['GLength'] = array('params' => 1, 'type' => 'float');
3530 $funcs['IsClosed'] = array('params' => 1, 'type' => 'int');
3532 } elseif ($geom_type == 'polygon') {
3533 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3534 $funcs['ExteriorRing'] = array('params' => 1, 'type' => 'linestring');
3535 $funcs['NumInteriorRings'] = array('params' => 1, 'type' => 'int');
3537 } elseif ($geom_type == 'multipolygon') {
3538 $funcs['Area'] = array('params' => 1, 'type' => 'float');
3539 $funcs['Centroid'] = array('params' => 1, 'type' => 'point');
3540 // Not yet implemented in MySQL
3541 //$funcs['PointOnSurface'] = array('params' => 1, 'type' => 'point');
3543 } elseif ($geom_type == 'geometrycollection') {
3544 $funcs['NumGeometries'] = array('params' => 1, 'type' => 'int');
3547 // If we are asked for binary functions as well
3549 // section seperator
3551 $funcs[] = array('display' => '--------');
3553 if (PMA_MYSQL_INT_VERSION
< 50601) {
3554 $funcs['Crosses'] = array('params' => 2, 'type' => 'int');
3555 $funcs['Contains'] = array('params' => 2, 'type' => 'int');
3556 $funcs['Disjoint'] = array('params' => 2, 'type' => 'int');
3557 $funcs['Equals'] = array('params' => 2, 'type' => 'int');
3558 $funcs['Intersects'] = array('params' => 2, 'type' => 'int');
3559 $funcs['Overlaps'] = array('params' => 2, 'type' => 'int');
3560 $funcs['Touches'] = array('params' => 2, 'type' => 'int');
3561 $funcs['Within'] = array('params' => 2, 'type' => 'int');
3563 // If MySQl version is greaeter than or equal 5.6.1, use the ST_ prefix.
3564 $funcs['ST_Crosses'] = array('params' => 2, 'type' => 'int');
3565 $funcs['ST_Contains'] = array('params' => 2, 'type' => 'int');
3566 $funcs['ST_Disjoint'] = array('params' => 2, 'type' => 'int');
3567 $funcs['ST_Equals'] = array('params' => 2, 'type' => 'int');
3568 $funcs['ST_Intersects'] = array('params' => 2, 'type' => 'int');
3569 $funcs['ST_Overlaps'] = array('params' => 2, 'type' => 'int');
3570 $funcs['ST_Touches'] = array('params' => 2, 'type' => 'int');
3571 $funcs['ST_Within'] = array('params' => 2, 'type' => 'int');
3576 $funcs[] = array('display' => '--------');
3578 // Minimum bounding rectangle functions
3579 $funcs['MBRContains'] = array('params' => 2, 'type' => 'int');
3580 $funcs['MBRDisjoint'] = array('params' => 2, 'type' => 'int');
3581 $funcs['MBREquals'] = array('params' => 2, 'type' => 'int');
3582 $funcs['MBRIntersects'] = array('params' => 2, 'type' => 'int');
3583 $funcs['MBROverlaps'] = array('params' => 2, 'type' => 'int');
3584 $funcs['MBRTouches'] = array('params' => 2, 'type' => 'int');
3585 $funcs['MBRWithin'] = array('params' => 2, 'type' => 'int');
3591 * Creates a dropdown box with MySQL functions for a particular column.
3593 * @param array $field Data about the column for which
3594 * to generate the dropdown
3595 * @param bool $insert_mode Whether the operation is 'insert'
3597 * @global array $cfg PMA configuration
3598 * @global array $analyzed_sql Analyzed SQL query
3599 * @global mixed $data (null/string) FIXME: what is this for?
3601 * @return string An HTML snippet of a dropdown list with function
3602 * names appropriate for the requested column.
3604 function PMA_getFunctionsForField($field, $insert_mode)
3606 global $cfg, $analyzed_sql, $data;
3609 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3610 // or something similar. Then directly look up the entry in the
3611 // RestrictFunctions array, which'll then reveal the available dropdown options
3612 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3613 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])
3615 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3616 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3617 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3619 $dropdown = array();
3620 $default_function = '';
3622 $dropdown_built = array();
3623 $op_spacing_needed = false;
3624 // what function defined as default?
3625 // for the first timestamp we don't set the default function
3626 // if there is a default value for the timestamp
3627 // (not including CURRENT_TIMESTAMP)
3628 // and the column does not have the
3629 // ON UPDATE DEFAULT TIMESTAMP attribute.
3630 if ($field['True_Type'] == 'timestamp'
3631 && empty($field['Default'])
3633 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])
3635 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3637 // For primary keys of type char(36) or varchar(36) UUID if the default function
3638 // Only applies to insert mode, as it would silently trash data on updates.
3640 && $field['Key'] == 'PRI'
3641 && ($field['Type'] == 'char(36)' ||
$field['Type'] == 'varchar(36)')
3643 $default_function = $cfg['DefaultFunctions']['FUNC_UUID'];
3645 // this is set only when appropriate and is always true
3646 if (isset($field['display_binary_as_hex'])) {
3647 $default_function = 'UNHEX';
3650 // Create the output
3651 $retval = ' <option></option>' . "\n";
3652 // loop on the dropdown array and print all available options for that field.
3653 foreach ($dropdown as $each_dropdown) {
3655 $retval .= '<option';
3656 if ($default_function === $each_dropdown) {
3657 $retval .= ' selected="selected"';
3659 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3660 $dropdown_built[$each_dropdown] = 'true';
3661 $op_spacing_needed = true;
3663 // For compatibility's sake, do not let out all other functions. Instead
3664 // print a separator (blank) and then show ALL functions which weren't shown
3666 $cnt_functions = count($cfg['Functions']);
3667 for ($j = 0; $j < $cnt_functions; $j++
) {
3668 if (! isset($dropdown_built[$cfg['Functions'][$j]])
3669 ||
$dropdown_built[$cfg['Functions'][$j]] != 'true'
3671 // Is current function defined as default?
3672 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3673 ||
(! $field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3674 ?
' selected="selected"'
3676 if ($op_spacing_needed == true) {
3678 $retval .= '<option value="">--------</option>' . "\n";
3679 $op_spacing_needed = false;
3683 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j]
3684 . '</option>' . "\n";
3689 } // end PMA_getFunctionsForField()
3692 * Checks if the current user has a specific privilege and returns true if the
3693 * user indeed has that privilege or false if (s)he doesn't. This function must
3694 * only be used for features that are available since MySQL 5, because it
3695 * relies on the INFORMATION_SCHEMA database to be present.
3697 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3698 * // Checks if the currently logged in user has the global
3699 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3700 * // user has this privilege on database 'mydb'.
3702 * @param string $priv The privilege to check
3703 * @param mixed $db null, to only check global privileges
3704 * string, db name where to also check for privileges
3705 * @param mixed $tbl null, to only check global privileges
3706 * string, db name where to also check for privileges
3710 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3712 // Get the username for the current user in the format
3713 // required to use in the information schema database.
3714 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3715 if ($user === false) {
3718 $user = explode('@', $user);
3720 $username .= str_replace("'", "''", $user[0]);
3721 $username .= "''@''";
3722 $username .= str_replace("'", "''", $user[1]);
3724 // Prepage the query
3725 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3726 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3727 // Check global privileges first.
3728 if (PMA_DBI_fetch_value(
3739 // If a database name was provided and user does not have the
3740 // required global privilege, try database-wise permissions.
3742 $query .= " AND TABLE_SCHEMA='%s'";
3743 if (PMA_DBI_fetch_value(
3746 'SCHEMA_PRIVILEGES',
3749 PMA_sqlAddSlashes($db)
3756 // There was no database name provided and the user
3757 // does not have the correct global privilege.
3760 // If a table name was also provided and we still didn't
3761 // find any valid privileges, try table-wise privileges.
3762 if ($tbl !== null) {
3763 $query .= " AND TABLE_NAME='%s'";
3764 if ($retval = PMA_DBI_fetch_value(
3770 PMA_sqlAddSlashes($db),
3771 PMA_sqlAddSlashes($tbl)
3778 // If we reached this point, the user does not
3779 // have even valid table-wise privileges.
3784 * Returns server type for current connection
3786 * Known types are: Drizzle, MariaDB and MySQL (default)
3790 function PMA_getServerType()
3792 $server_type = 'MySQL';
3794 $server_type = 'Drizzle';
3795 } else if (strpos(PMA_MYSQL_STR_VERSION
, 'mariadb') !== false) {
3796 $server_type = 'MariaDB';
3797 } else if (stripos(PMA_MYSQL_VERSION_COMMENT
, 'percona') !== false) {
3798 $server_type = 'Percona Server';
3800 return $server_type;
3804 * Analyzes the limit clause and return the start and length attributes of it.
3806 * @param string $limit_clause limit clause
3808 * @return array Start and length attributes of the limit clause
3810 function PMA_analyzeLimitClause($limit_clause)
3812 $start_and_length = explode(',', str_ireplace('LIMIT', '', $limit_clause));
3814 'start' => trim($start_and_length[0]),
3815 'length' => trim($start_and_length[1])
3820 * Outputs HTML code for print button.
3824 function PMA_printButton()
3826 echo '<p class="print_ignore">';
3827 echo '<input type="button" id="print" value="' . __('Print') . '" />';