Merge branch 'master' of git://phpmyadmin.git.sourceforge.net/gitroot/phpmyadmin...
[phpmyadmin/crack.git] / libraries / common.lib.php
bloba9d7e1ff75561309b59f2599b482fadbcbb5362e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Misc functions used all over the scripts.
6 * @package phpMyAdmin
7 */
9 /**
10 * Exponential expression / raise number into power
12 * @param string $base base to raise
13 * @param string $exp exponent to use
14 * @param mixed $use_function pow function to use, or false for auto-detect
15 * @return mixed string or float
17 function PMA_pow($base, $exp, $use_function = false)
19 static $pow_function = null;
21 if (null == $pow_function) {
22 if (function_exists('bcpow')) {
23 // BCMath Arbitrary Precision Mathematics Function
24 $pow_function = 'bcpow';
25 } elseif (function_exists('gmp_pow')) {
26 // GMP Function
27 $pow_function = 'gmp_pow';
28 } else {
29 // PHP function
30 $pow_function = 'pow';
34 if (! $use_function) {
35 $use_function = $pow_function;
38 if ($exp < 0 && 'pow' != $use_function) {
39 return false;
41 switch ($use_function) {
42 case 'bcpow' :
43 // bcscale() needed for testing PMA_pow() with base values < 1
44 bcscale(10);
45 $pow = bcpow($base, $exp);
46 break;
47 case 'gmp_pow' :
48 $pow = gmp_strval(gmp_pow($base, $exp));
49 break;
50 case 'pow' :
51 $base = (float) $base;
52 $exp = (int) $exp;
53 $pow = pow($base, $exp);
54 break;
55 default:
56 $pow = $use_function($base, $exp);
59 return $pow;
62 /**
63 * string PMA_getIcon(string $icon)
65 * @param string $icon name of icon file
66 * @param string $alternate alternate text
67 * @param boolean $container include in container
68 * @param boolean $force_text whether to force alternate text to be displayed
69 * @return html img tag
71 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
73 $include_icon = false;
74 $include_text = false;
75 $include_box = false;
76 $alternate = htmlspecialchars($alternate);
77 $button = '';
79 if ($GLOBALS['cfg']['PropertiesIconic']) {
80 $include_icon = true;
83 if ($force_text
84 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
85 || ! $include_icon) {
86 // $cfg['PropertiesIconic'] is false or both
87 // OR we have no $include_icon
88 $include_text = true;
91 if ($include_text && $include_icon && $container) {
92 // we have icon, text and request for container
93 $include_box = true;
96 // Always use a span (we rely on this in js/sql.js)
97 $button .= '<span class="nowrap">';
99 if ($include_icon) {
100 $button .= '<img src="themes/dot.gif"'
101 . ' title="' . $alternate . '" alt="' . $alternate . '"'
102 . ' class="icon ic_' . str_replace('.png','',$icon) . '" />';
105 if ($include_icon && $include_text) {
106 $button .= ' ';
109 if ($include_text) {
110 $button .= $alternate;
113 $button .= '</span>';
115 return $button;
119 * Displays the maximum size for an upload
121 * @param integer $max_upload_size the size
122 * @return string the message
124 * @access public
126 function PMA_displayMaximumUploadSize($max_upload_size)
128 // I have to reduce the second parameter (sensitiveness) from 6 to 4
129 // to avoid weird results like 512 kKib
130 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
131 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
135 * Generates a hidden field which should indicate to the browser
136 * the maximum size for upload
138 * @param integer $max_size the size
139 * @return string the INPUT field
141 * @access public
143 function PMA_generateHiddenMaxFileSize($max_size)
145 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
149 * Add slashes before "'" and "\" characters so a value containing them can
150 * be used in a sql comparison.
152 * @param string $a_string the string to slash
153 * @param bool $is_like whether the string will be used in a 'LIKE' clause
154 * (it then requires two more escaped sequences) or not
155 * @param bool $crlf whether to treat cr/lfs as escape-worthy entities
156 * (converts \n to \\n, \r to \\r)
157 * @param bool $php_code whether this function is used as part of the
158 * "Create PHP code" dialog
160 * @return string the slashed string
162 * @access public
164 function PMA_sqlAddSlashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
166 if ($is_like) {
167 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
168 } else {
169 $a_string = str_replace('\\', '\\\\', $a_string);
172 if ($crlf) {
173 $a_string = str_replace("\n", '\n', $a_string);
174 $a_string = str_replace("\r", '\r', $a_string);
175 $a_string = str_replace("\t", '\t', $a_string);
178 if ($php_code) {
179 $a_string = str_replace('\'', '\\\'', $a_string);
180 } else {
181 $a_string = str_replace('\'', '\'\'', $a_string);
184 return $a_string;
185 } // end of the 'PMA_sqlAddSlashes()' function
189 * Add slashes before "_" and "%" characters for using them in MySQL
190 * database, table and field names.
191 * Note: This function does not escape backslashes!
193 * @param string $name the string to escape
194 * @return string the escaped string
196 * @access public
198 function PMA_escape_mysql_wildcards($name)
200 $name = str_replace('_', '\\_', $name);
201 $name = str_replace('%', '\\%', $name);
203 return $name;
204 } // end of the 'PMA_escape_mysql_wildcards()' function
207 * removes slashes before "_" and "%" characters
208 * Note: This function does not unescape backslashes!
210 * @param string $name the string to escape
211 * @return string the escaped string
212 * @access public
214 function PMA_unescape_mysql_wildcards($name)
216 $name = str_replace('\\_', '_', $name);
217 $name = str_replace('\\%', '%', $name);
219 return $name;
220 } // end of the 'PMA_unescape_mysql_wildcards()' function
223 * removes quotes (',",`) from a quoted string
225 * checks if the sting is quoted and removes this quotes
227 * @param string $quoted_string string to remove quotes from
228 * @param string $quote type of quote to remove
229 * @return string unqoted string
231 function PMA_unQuote($quoted_string, $quote = null)
233 $quotes = array();
235 if (null === $quote) {
236 $quotes[] = '`';
237 $quotes[] = '"';
238 $quotes[] = "'";
239 } else {
240 $quotes[] = $quote;
243 foreach ($quotes as $quote) {
244 if (substr($quoted_string, 0, 1) === $quote
245 && substr($quoted_string, -1, 1) === $quote) {
246 $unquoted_string = substr($quoted_string, 1, -1);
247 // replace escaped quotes
248 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
249 return $unquoted_string;
253 return $quoted_string;
257 * format sql strings
259 * @todo move into PMA_Sql
260 * @param mixed $parsed_sql pre-parsed SQL structure
261 * @param string $unparsed_sql raw SQL string
262 * @return string the formatted sql
264 * @global array the configuration array
265 * @global boolean whether the current statement is a multiple one or not
267 * @access public
270 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
272 global $cfg;
274 // Check that we actually have a valid set of parsed data
275 // well, not quite
276 // first check for the SQL parser having hit an error
277 if (PMA_SQP_isError()) {
278 return htmlspecialchars($parsed_sql['raw']);
280 // then check for an array
281 if (! is_array($parsed_sql)) {
282 // We don't so just return the input directly
283 // This is intended to be used for when the SQL Parser is turned off
284 $formatted_sql = '<pre>' . "\n"
285 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
286 . '</pre>';
287 return $formatted_sql;
290 $formatted_sql = '';
292 switch ($cfg['SQP']['fmtType']) {
293 case 'none':
294 if ($unparsed_sql != '') {
295 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
296 } else {
297 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
299 break;
300 case 'html':
301 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
302 break;
303 case 'text':
304 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
305 break;
306 default:
307 break;
308 } // end switch
310 return $formatted_sql;
311 } // end of the "PMA_formatSql()" function
315 * Displays a link to the official MySQL documentation
317 * @param string $chapter chapter of "HTML, one page per chapter" documentation
318 * @param string $link contains name of page/anchor that is being linked
319 * @param bool $big_icon whether to use big icon (like in left frame)
320 * @param string $anchor anchor to page part
321 * @param bool $just_open whether only the opening <a> tag should be returned
323 * @return string the html link
325 * @access public
327 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
329 global $cfg;
331 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
332 return '';
335 // Fixup for newly used names:
336 $chapter = str_replace('_', '-', strtolower($chapter));
337 $link = str_replace('_', '-', strtolower($link));
339 switch ($cfg['MySQLManualType']) {
340 case 'chapters':
341 if (empty($chapter)) {
342 $chapter = 'index';
344 if (empty($anchor)) {
345 $anchor = $link;
347 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
348 break;
349 case 'big':
350 if (empty($anchor)) {
351 $anchor = $link;
353 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
354 break;
355 case 'searchable':
356 if (empty($link)) {
357 $link = 'index';
359 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
360 if (!empty($anchor)) {
361 $url .= '#' . $anchor;
363 break;
364 case 'viewable':
365 default:
366 if (empty($link)) {
367 $link = 'index';
369 $mysql = '5.0';
370 $lang = 'en';
371 if (defined('PMA_MYSQL_INT_VERSION')) {
372 if (PMA_MYSQL_INT_VERSION >= 50500) {
373 $mysql = '5.5';
374 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
375 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
376 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
377 $mysql = '5.1';
378 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
379 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
380 } else {
381 $mysql = '5.0';
382 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
383 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
386 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
387 if (!empty($anchor)) {
388 $url .= '#' . $anchor;
390 break;
393 if ($just_open) {
394 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
395 } elseif ($big_icon) {
396 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon ic_b_sqlhelp" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
397 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
398 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
399 } else {
400 return '[<a href="' . PMA_linkURL($url) . '" target="mysql_doc">' . __('Documentation') . '</a>]';
402 } // end of the 'PMA_showMySQLDocu()' function
406 * Displays a link to the phpMyAdmin documentation
408 * @param string $anchor anchor in documentation
409 * @return string the html link
411 * @access public
413 function PMA_showDocu($anchor) {
414 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
415 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
416 } else {
417 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
419 } // end of the 'PMA_showDocu()' function
422 * Displays a link to the PHP documentation
424 * @param string $target anchor in documentation
425 * @return string the html link
427 * @access public
429 function PMA_showPHPDocu($target) {
430 $url = PMA_getPHPDocLink($target);
432 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
433 return '<a href="' . $url . '" target="documentation"><img class="icon ic_b_help_s" src="themes/dot.gif" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
434 } else {
435 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
437 } // end of the 'PMA_showPHPDocu()' function
440 * returns HTML for a footnote marker and add the messsage to the footnotes
442 * @param string $message the error message
443 * @param bool $bbcode
444 * @param string $type
445 * @return string html code for a footnote marker
446 * @access public
448 function PMA_showHint($message, $bbcode = false, $type = 'notice')
450 if ($message instanceof PMA_Message) {
451 $key = $message->getHash();
452 $type = $message->getLevel();
453 } else {
454 $key = md5($message);
457 if (! isset($GLOBALS['footnotes'][$key])) {
458 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
459 $GLOBALS['footnotes'] = array();
461 $nr = count($GLOBALS['footnotes']) + 1;
462 $GLOBALS['footnotes'][$key] = array(
463 'note' => $message,
464 'type' => $type,
465 'nr' => $nr,
467 } else {
468 $nr = $GLOBALS['footnotes'][$key]['nr'];
471 if ($bbcode) {
472 return '[sup]' . $nr . '[/sup]';
475 // footnotemarker used in js/tooltip.js
476 return '<sup class="footnotemarker">' . $nr . '</sup>' .
477 '<img class="footnotemarker ic_b_help footnote_' . $nr . '" src="themes/dot.gif" alt="" />';
481 * Displays a MySQL error message in the right frame.
483 * @param string $error_message the error message
484 * @param string $the_query the sql query that failed
485 * @param bool $is_modify_link whether to show a "modify" link or not
486 * @param string $back_url the "back" link url (full path is not required)
487 * @param bool $exit EXIT the page?
489 * @global string the curent table
490 * @global string the current db
492 * @access public
494 function PMA_mysqlDie($error_message = '', $the_query = '',
495 $is_modify_link = true, $back_url = '', $exit = true)
497 global $table, $db;
500 * start http output, display html headers
502 require_once './libraries/header.inc.php';
504 $error_msg_output = '';
506 if (!$error_message) {
507 $error_message = PMA_DBI_getError();
509 if (!$the_query && !empty($GLOBALS['sql_query'])) {
510 $the_query = $GLOBALS['sql_query'];
513 // --- Added to solve bug #641765
514 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
515 $formatted_sql = htmlspecialchars($the_query);
516 } elseif (empty($the_query) || trim($the_query) == '') {
517 $formatted_sql = '';
518 } else {
519 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
520 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
521 } else {
522 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
525 // ---
526 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
527 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
528 // if the config password is wrong, or the MySQL server does not
529 // respond, do not show the query that would reveal the
530 // username/password
531 if (!empty($the_query) && !strstr($the_query, 'connect')) {
532 // --- Added to solve bug #641765
533 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
534 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
535 $error_msg_output .= '<br />' . "\n";
537 // ---
538 // modified to show the help on sql errors
539 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
540 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
541 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
543 if ($is_modify_link) {
544 $_url_params = array(
545 'sql_query' => $the_query,
546 'show_query' => 1,
548 if (strlen($table)) {
549 $_url_params['db'] = $db;
550 $_url_params['table'] = $table;
551 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
552 } elseif (strlen($db)) {
553 $_url_params['db'] = $db;
554 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
555 } else {
556 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
559 $error_msg_output .= $doedit_goto
560 . PMA_getIcon('b_edit.png', __('Edit'))
561 . '</a>';
562 } // end if
563 $error_msg_output .= ' </p>' . "\n"
564 .' <p>' . "\n"
565 .' ' . $formatted_sql . "\n"
566 .' </p>' . "\n";
567 } // end if
569 if (!empty($error_message)) {
570 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
572 // modified to show the help on error-returns
573 // (now error-messages-server)
574 $error_msg_output .= '<p>' . "\n"
575 . ' <strong>' . __('MySQL said: ') . '</strong>'
576 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
577 . "\n"
578 . '</p>' . "\n";
580 // The error message will be displayed within a CODE segment.
581 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
583 // Replace all non-single blanks with their HTML-counterpart
584 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
585 // Replace TAB-characters with their HTML-counterpart
586 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
587 // Replace linebreaks
588 $error_message = nl2br($error_message);
590 $error_msg_output .= '<code>' . "\n"
591 . $error_message . "\n"
592 . '</code><br />' . "\n";
593 $error_msg_output .= '</div>';
595 $_SESSION['Import_message']['message'] = $error_msg_output;
597 if ($exit) {
599 * If in an Ajax request
600 * - avoid displaying a Back link
601 * - use PMA_ajaxResponse() to transmit the message and exit
603 if($GLOBALS['is_ajax_request'] == true) {
604 PMA_ajaxResponse($error_msg_output, false);
606 if (! empty($back_url)) {
607 if (strstr($back_url, '?')) {
608 $back_url .= '&amp;no_history=true';
609 } else {
610 $back_url .= '?no_history=true';
613 $_SESSION['Import_message']['go_back_url'] = $back_url;
615 $error_msg_output .= '<fieldset class="tblFooters">';
616 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
617 $error_msg_output .= '</fieldset>' . "\n\n";
620 echo $error_msg_output;
622 * display footer and exit
624 require './libraries/footer.inc.php';
625 } else {
626 echo $error_msg_output;
628 } // end of the 'PMA_mysqlDie()' function
631 * returns array with tables of given db with extended information and grouped
633 * @param string $db name of db
634 * @param string $tables name of tables
635 * @param integer $limit_offset list offset
636 * @param int|bool $limit_count max tables to return
637 * @return array (recursive) grouped table list
639 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
641 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
643 if (null === $tables) {
644 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
645 if ($GLOBALS['cfg']['NaturalOrder']) {
646 uksort($tables, 'strnatcasecmp');
650 if (count($tables) < 1) {
651 return $tables;
654 $default = array(
655 'Name' => '',
656 'Rows' => 0,
657 'Comment' => '',
658 'disp_name' => '',
661 $table_groups = array();
663 // for blobstreaming - list of blobstreaming tables
665 // load PMA configuration
666 $PMA_Config = $GLOBALS['PMA_Config'];
668 foreach ($tables as $table_name => $table) {
669 // if BS tables exist
670 if (PMA_BS_IsHiddenTable($table_name)) {
671 continue;
674 // check for correct row count
675 if (null === $table['Rows']) {
676 // Do not check exact row count here,
677 // if row count is invalid possibly the table is defect
678 // and this would break left frame;
679 // but we can check row count if this is a view or the
680 // information_schema database
681 // since PMA_Table::countRecords() returns a limited row count
682 // in this case.
684 // set this because PMA_Table::countRecords() can use it
685 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
687 if ($tbl_is_view || 'information_schema' == $db) {
688 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
692 // in $group we save the reference to the place in $table_groups
693 // where to store the table info
694 if ($GLOBALS['cfg']['LeftFrameDBTree']
695 && $sep && strstr($table_name, $sep))
697 $parts = explode($sep, $table_name);
699 $group =& $table_groups;
700 $i = 0;
701 $group_name_full = '';
702 $parts_cnt = count($parts) - 1;
703 while ($i < $parts_cnt
704 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
705 $group_name = $parts[$i] . $sep;
706 $group_name_full .= $group_name;
708 if (! isset($group[$group_name])) {
709 $group[$group_name] = array();
710 $group[$group_name]['is' . $sep . 'group'] = true;
711 $group[$group_name]['tab' . $sep . 'count'] = 1;
712 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
713 } elseif (! isset($group[$group_name]['is' . $sep . 'group'])) {
714 $table = $group[$group_name];
715 $group[$group_name] = array();
716 $group[$group_name][$group_name] = $table;
717 unset($table);
718 $group[$group_name]['is' . $sep . 'group'] = true;
719 $group[$group_name]['tab' . $sep . 'count'] = 1;
720 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
721 } else {
722 $group[$group_name]['tab' . $sep . 'count']++;
724 $group =& $group[$group_name];
725 $i++;
727 } else {
728 if (! isset($table_groups[$table_name])) {
729 $table_groups[$table_name] = array();
731 $group =& $table_groups;
735 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
736 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
737 // switch tooltip and name
738 $table['Comment'] = $table['Name'];
739 $table['disp_name'] = $table['Comment'];
740 } else {
741 $table['disp_name'] = $table['Name'];
744 $group[$table_name] = array_merge($default, $table);
747 return $table_groups;
750 /* ----------------------- Set of misc functions ----------------------- */
754 * Adds backquotes on both sides of a database, table or field name.
755 * and escapes backquotes inside the name with another backquote
757 * example:
758 * <code>
759 * echo PMA_backquote('owner`s db'); // `owner``s db`
761 * </code>
763 * @param mixed $a_name the database, table or field name to "backquote"
764 * or array of it
765 * @param boolean $do_it a flag to bypass this function (used by dump
766 * functions)
767 * @return mixed the "backquoted" database, table or field name
768 * @access public
770 function PMA_backquote($a_name, $do_it = true)
772 if (is_array($a_name)) {
773 foreach ($a_name as &$data) {
774 $data = PMA_backquote($data, $do_it);
776 return $a_name;
779 if (! $do_it) {
780 global $PMA_SQPdata_forbidden_word;
782 if(! in_array(strtoupper($a_name), $PMA_SQPdata_forbidden_word)) {
783 return $a_name;
787 // '0' is also empty for php :-(
788 if (strlen($a_name) && $a_name !== '*') {
789 return '`' . str_replace('`', '``', $a_name) . '`';
790 } else {
791 return $a_name;
793 } // end of the 'PMA_backquote()' function
796 * Defines the <CR><LF> value depending on the user OS.
798 * @return string the <CR><LF> value to use
800 * @access public
802 function PMA_whichCrlf()
804 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
805 // Win case
806 if (PMA_USR_OS == 'Win') {
807 $the_crlf = "\r\n";
809 // Others
810 else {
811 $the_crlf = "\n";
814 return $the_crlf;
815 } // end of the 'PMA_whichCrlf()' function
818 * Reloads navigation if needed.
820 * @param bool $jsonly prints out pure JavaScript
822 * @access public
824 function PMA_reloadNavigation($jsonly=false)
826 // Reloads the navigation frame via JavaScript if required
827 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
828 // one of the reasons for a reload is when a table is dropped
829 // in this case, get rid of the table limit offset, otherwise
830 // we have a problem when dropping a table on the last page
831 // and the offset becomes greater than the total number of tables
832 unset($_SESSION['tmp_user_values']['table_limit_offset']);
833 echo "\n";
834 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
835 if (!$jsonly)
836 echo '<script type="text/javascript">' . PHP_EOL;
838 //<![CDATA[
839 if (typeof(window.parent) != 'undefined'
840 && typeof(window.parent.frame_navigation) != 'undefined'
841 && window.parent.goTo) {
842 window.parent.goTo('<?php echo $reload_url; ?>');
844 //]]>
845 <?php
846 if (!$jsonly)
847 echo '</script>' . PHP_EOL;
849 unset($GLOBALS['reload']);
854 * displays the message and the query
855 * usually the message is the result of the query executed
857 * @param string $message the message to display
858 * @param string $sql_query the query to display
859 * @param string $type the type (level) of the message
860 * @param boolean $is_view is this a message after a VIEW operation?
861 * @return string
862 * @access public
864 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
867 * PMA_ajaxResponse uses this function to collect the string of HTML generated
868 * for showing the message. Use output buffering to collect it and return it
869 * in a string. In some special cases on sql.php, buffering has to be disabled
870 * and hence we check with $GLOBALS['buffer_message']
872 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
873 ob_start();
875 global $cfg;
877 if (null === $sql_query) {
878 if (! empty($GLOBALS['display_query'])) {
879 $sql_query = $GLOBALS['display_query'];
880 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
881 $sql_query = $GLOBALS['unparsed_sql'];
882 } elseif (! empty($GLOBALS['sql_query'])) {
883 $sql_query = $GLOBALS['sql_query'];
884 } else {
885 $sql_query = '';
889 if (isset($GLOBALS['using_bookmark_message'])) {
890 $GLOBALS['using_bookmark_message']->display();
891 unset($GLOBALS['using_bookmark_message']);
894 // Corrects the tooltip text via JS if required
895 // @todo this is REALLY the wrong place to do this - very unexpected here
896 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
897 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
898 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
899 echo "\n";
900 echo '<script type="text/javascript">' . "\n";
901 echo '//<![CDATA[' . "\n";
902 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
903 echo '//]]>' . "\n";
904 echo '</script>' . "\n";
905 } // end if ... elseif
907 // Checks if the table needs to be repaired after a TRUNCATE query.
908 // @todo what about $GLOBALS['display_query']???
909 // @todo this is REALLY the wrong place to do this - very unexpected here
910 if (strlen($GLOBALS['table'])
911 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
912 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
913 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
916 unset($tbl_status);
918 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
919 // check for it's presence before using it
920 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
922 if ($message instanceof PMA_Message) {
923 if (isset($GLOBALS['special_message'])) {
924 $message->addMessage($GLOBALS['special_message']);
925 unset($GLOBALS['special_message']);
927 $message->display();
928 $type = $message->getLevel();
929 } else {
930 echo '<div class="' . $type . '">';
931 echo PMA_sanitize($message);
932 if (isset($GLOBALS['special_message'])) {
933 echo PMA_sanitize($GLOBALS['special_message']);
934 unset($GLOBALS['special_message']);
936 echo '</div>';
939 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
940 // Html format the query to be displayed
941 // If we want to show some sql code it is easiest to create it here
942 /* SQL-Parser-Analyzer */
944 if (! empty($GLOBALS['show_as_php'])) {
945 $new_line = '\\n"<br />' . "\n"
946 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
947 $query_base = htmlspecialchars(addslashes($sql_query));
948 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
949 } else {
950 $query_base = $sql_query;
953 $query_too_big = false;
955 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
956 // when the query is large (for example an INSERT of binary
957 // data), the parser chokes; so avoid parsing the query
958 $query_too_big = true;
959 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
960 } elseif (! empty($GLOBALS['parsed_sql'])
961 && $query_base == $GLOBALS['parsed_sql']['raw']) {
962 // (here, use "! empty" because when deleting a bookmark,
963 // $GLOBALS['parsed_sql'] is set but empty
964 $parsed_sql = $GLOBALS['parsed_sql'];
965 } else {
966 // Parse SQL if needed
967 $parsed_sql = PMA_SQP_parse($query_base);
968 if (PMA_SQP_isError()) {
969 unset($parsed_sql);
973 // Analyze it
974 if (isset($parsed_sql)) {
975 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
977 // Same as below (append LIMIT), append the remembered ORDER BY
978 if ($GLOBALS['cfg']['RememberSorting']
979 && isset($analyzed_display_query[0]['queryflags']['select_from'])
980 && isset($GLOBALS['sql_order_to_append'])) {
981 $query_base = $analyzed_display_query[0]['section_before_limit']
982 . "\n" . $GLOBALS['sql_order_to_append']
983 . $analyzed_display_query[0]['section_after_limit'];
985 // Need to reparse query
986 $parsed_sql = PMA_SQP_parse($query_base);
987 // update the $analyzed_display_query
988 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
989 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
992 // Here we append the LIMIT added for navigation, to
993 // enable its display. Adding it higher in the code
994 // to $sql_query would create a problem when
995 // using the Refresh or Edit links.
997 // Only append it on SELECTs.
1000 * @todo what would be the best to do when someone hits Refresh:
1001 * use the current LIMITs ?
1004 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1005 && isset($GLOBALS['sql_limit_to_append'])) {
1006 $query_base = $analyzed_display_query[0]['section_before_limit']
1007 . "\n" . $GLOBALS['sql_limit_to_append']
1008 . $analyzed_display_query[0]['section_after_limit'];
1009 // Need to reparse query
1010 $parsed_sql = PMA_SQP_parse($query_base);
1014 if (! empty($GLOBALS['show_as_php'])) {
1015 $query_base = '$sql = "' . $query_base;
1016 } elseif (! empty($GLOBALS['validatequery'])) {
1017 try {
1018 $query_base = PMA_validateSQL($query_base);
1019 } catch (Exception $e) {
1020 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1022 } elseif (isset($parsed_sql)) {
1023 $query_base = PMA_formatSql($parsed_sql, $query_base);
1026 // Prepares links that may be displayed to edit/explain the query
1027 // (don't go to default pages, we must go to the page
1028 // where the query box is available)
1030 // Basic url query part
1031 $url_params = array();
1032 if (! isset($GLOBALS['db'])) {
1033 $GLOBALS['db'] = '';
1035 if (strlen($GLOBALS['db'])) {
1036 $url_params['db'] = $GLOBALS['db'];
1037 if (strlen($GLOBALS['table'])) {
1038 $url_params['table'] = $GLOBALS['table'];
1039 $edit_link = 'tbl_sql.php';
1040 } else {
1041 $edit_link = 'db_sql.php';
1043 } else {
1044 $edit_link = 'server_sql.php';
1047 // Want to have the query explained
1048 // but only explain a SELECT (that has not been explained)
1049 /* SQL-Parser-Analyzer */
1050 $explain_link = '';
1051 $is_select = false;
1052 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1053 $explain_params = $url_params;
1054 // Detect if we are validating as well
1055 // To preserve the validate uRL data
1056 if (! empty($GLOBALS['validatequery'])) {
1057 $explain_params['validatequery'] = 1;
1059 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1060 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1061 $_message = __('Explain SQL');
1062 $is_select = true;
1063 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1064 $explain_params['sql_query'] = substr($sql_query, 8);
1065 $_message = __('Skip Explain SQL');
1067 if (isset($explain_params['sql_query'])) {
1068 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1069 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1071 } //show explain
1073 $url_params['sql_query'] = $sql_query;
1074 $url_params['show_query'] = 1;
1076 // even if the query is big and was truncated, offer the chance
1077 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1078 if (! empty($cfg['SQLQuery']['Edit'])) {
1079 if ($cfg['EditInWindow'] == true) {
1080 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1081 } else {
1082 $onclick = '';
1085 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1086 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1087 } else {
1088 $edit_link = '';
1091 $url_qpart = PMA_generate_common_url($url_params);
1093 // Also we would like to get the SQL formed in some nice
1094 // php-code
1095 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1096 $php_params = $url_params;
1098 if (! empty($GLOBALS['show_as_php'])) {
1099 $_message = __('Without PHP Code');
1100 } else {
1101 $php_params['show_as_php'] = 1;
1102 $_message = __('Create PHP Code');
1105 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1106 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1108 if (isset($GLOBALS['show_as_php'])) {
1109 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1110 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1112 } else {
1113 $php_link = '';
1114 } //show as php
1116 // Refresh query
1117 if (! empty($cfg['SQLQuery']['Refresh'])
1118 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1119 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1120 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1121 } else {
1122 $refresh_link = '';
1123 } //show as php
1125 if (! empty($cfg['SQLValidator']['use'])
1126 && ! empty($cfg['SQLQuery']['Validate'])) {
1127 $validate_params = $url_params;
1128 if (!empty($GLOBALS['validatequery'])) {
1129 $validate_message = __('Skip Validate SQL') ;
1130 } else {
1131 $validate_params['validatequery'] = 1;
1132 $validate_message = __('Validate SQL') ;
1135 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1136 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1137 } else {
1138 $validate_link = '';
1139 } //validator
1141 if (!empty($GLOBALS['validatequery'])) {
1142 echo '<div class="sqlvalidate">';
1143 } else {
1144 echo '<code class="sql">';
1146 if ($query_too_big) {
1147 echo $shortened_query_base;
1148 } else {
1149 echo $query_base;
1152 //Clean up the end of the PHP
1153 if (! empty($GLOBALS['show_as_php'])) {
1154 echo '";';
1156 if (!empty($GLOBALS['validatequery'])) {
1157 echo '</div>';
1158 } else {
1159 echo '</code>';
1162 echo '<div class="tools">';
1163 // avoid displaying a Profiling checkbox that could
1164 // be checked, which would reexecute an INSERT, for example
1165 if (! empty($refresh_link)) {
1166 PMA_profilingCheckbox($sql_query);
1168 // if needed, generate an invisible form that contains controls for the
1169 // Inline link; this way, the behavior of the Inline link does not
1170 // depend on the profiling support or on the refresh link
1171 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1172 echo '<form action="sql.php" method="post">';
1173 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1174 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1175 echo '</form>';
1178 // in the tools div, only display the Inline link when not in ajax
1179 // mode because 1) it currently does not work and 2) we would
1180 // have two similar mechanisms on the page for the same goal
1181 if ($is_select || $GLOBALS['is_ajax_request'] === false) {
1182 // see in js/functions.js the jQuery code attached to id inline_edit
1183 // document.write conflicts with jQuery, hence used $().append()
1184 echo "<script type=\"text/javascript\">\n" .
1185 "//<![CDATA[\n" .
1186 "$('.tools form').last().after('[<a href=\"#\" title=\"" .
1187 PMA_escapeJsString(__('Inline edit of this query')) .
1188 "\" class=\"inline_edit_sql\">" .
1189 PMA_escapeJsString(__('Inline')) .
1190 "</a>]');\n" .
1191 "//]]>\n" .
1192 "</script>";
1194 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1195 echo '</div>';
1197 echo '</div>';
1198 if ($GLOBALS['is_ajax_request'] === false) {
1199 echo '<br class="clearfloat" />';
1202 // If we are in an Ajax request, we have most probably been called in
1203 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1204 // to PMA_ajaxResponse(), which will encode it for JSON.
1205 if( $GLOBALS['is_ajax_request'] == true && ! isset($GLOBALS['buffer_message']) ) {
1206 $buffer_contents = ob_get_contents();
1207 ob_end_clean();
1208 return $buffer_contents;
1210 return null;
1211 } // end of the 'PMA_showMessage()' function
1214 * Verifies if current MySQL server supports profiling
1216 * @access public
1217 * @return boolean whether profiling is supported
1219 function PMA_profilingSupported()
1221 if (! PMA_cacheExists('profiling_supported', true)) {
1222 // 5.0.37 has profiling but for example, 5.1.20 does not
1223 // (avoid a trip to the server for MySQL before 5.0.37)
1224 // and do not set a constant as we might be switching servers
1225 if (defined('PMA_MYSQL_INT_VERSION')
1226 && PMA_MYSQL_INT_VERSION >= 50037
1227 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1228 PMA_cacheSet('profiling_supported', true, true);
1229 } else {
1230 PMA_cacheSet('profiling_supported', false, true);
1234 return PMA_cacheGet('profiling_supported', true);
1238 * Displays a form with the Profiling checkbox
1240 * @param string $sql_query
1241 * @access public
1243 function PMA_profilingCheckbox($sql_query)
1245 if (PMA_profilingSupported()) {
1246 echo '<form action="sql.php" method="post">' . "\n";
1247 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1248 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1249 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1250 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1251 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1252 echo '</form>' . "\n";
1257 * Formats $value to byte view
1259 * @param double $value the value to format
1260 * @param int $limes the sensitiveness
1261 * @param int $comma the number of decimals to retain
1263 * @return array the formatted value and its unit
1265 * @access public
1267 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1269 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1270 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1272 $dh = PMA_pow(10, $comma);
1273 $li = PMA_pow(10, $limes);
1274 $unit = $byteUnits[0];
1276 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1277 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1278 // use 1024.0 to avoid integer overflow on 64-bit machines
1279 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1280 $unit = $byteUnits[$d];
1281 break 1;
1282 } // end if
1283 } // end for
1285 if ($unit != $byteUnits[0]) {
1286 // if the unit is not bytes (as represented in current language)
1287 // reformat with max length of 5
1288 // 4th parameter=true means do not reformat if value < 1
1289 $return_value = PMA_formatNumber($value, 5, $comma, true);
1290 } else {
1291 // do not reformat, just handle the locale
1292 $return_value = PMA_formatNumber($value, 0);
1295 return array(trim($return_value), $unit);
1296 } // end of the 'PMA_formatByteDown' function
1299 * Changes thousands and decimal separators to locale specific values.
1301 * @param $value
1302 * @return string
1304 function PMA_localizeNumber($value)
1306 return str_replace(
1307 array(',', '.'),
1308 array(
1309 /* l10n: Thousands separator */
1310 __(','),
1311 /* l10n: Decimal separator */
1312 __('.'),
1314 $value);
1318 * Formats $value to the given length and appends SI prefixes
1319 * with a $length of 0 no truncation occurs, number is only formated
1320 * to the current locale
1322 * examples:
1323 * <code>
1324 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1325 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1326 * echo PMA_formatNumber(-0.003, 6); // -3 m
1327 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1328 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1329 * echo PMA_formatNumber(0, 6); // 0
1331 * </code>
1332 * @param double $value the value to format
1333 * @param integer $digits_left number of digits left of the comma
1334 * @param integer $digits_right number of digits right of the comma
1335 * @param boolean $only_down do not reformat numbers below 1
1336 * @param boolean $noTrailingZero removes trailing zeros right of the comma (default: true)
1338 * @return string the formatted value and its unit
1340 * @access public
1342 function PMA_formatNumber($value, $digits_left = 3, $digits_right = 0, $only_down = false, $noTrailingZero = true)
1344 if($value==0) return '0';
1346 $originalValue = $value;
1347 //number_format is not multibyte safe, str_replace is safe
1348 if ($digits_left === 0) {
1349 $value = number_format($value, $digits_right);
1350 if($originalValue!=0 && floatval($value) == 0) $value = ' <'.(1/PMA_pow(10,$digits_right));
1352 return PMA_localizeNumber($value);
1355 // this units needs no translation, ISO
1356 $units = array(
1357 -8 => 'y',
1358 -7 => 'z',
1359 -6 => 'a',
1360 -5 => 'f',
1361 -4 => 'p',
1362 -3 => 'n',
1363 -2 => '&micro;',
1364 -1 => 'm',
1365 0 => ' ',
1366 1 => 'k',
1367 2 => 'M',
1368 3 => 'G',
1369 4 => 'T',
1370 5 => 'P',
1371 6 => 'E',
1372 7 => 'Z',
1373 8 => 'Y'
1376 // check for negative value to retain sign
1377 if ($value < 0) {
1378 $sign = '-';
1379 $value = abs($value);
1380 } else {
1381 $sign = '';
1384 $dh = PMA_pow(10, $digits_right);
1386 // This gives us the right SI prefix already, but $digits_left parameter not incorporated
1387 $d = floor(log10($value) / 3);
1388 // Lowering the SI prefix by 1 gives us an additional 3 zeros
1389 // So if we have 3,6,9,12.. free digits ($digits_left - $cur_digits) to use, then lower the SI prefix
1390 $cur_digits = floor(log10($value / PMA_pow(1000, $d, 'pow'))+1);
1391 if($digits_left > $cur_digits) {
1392 $d-= floor(($digits_left - $cur_digits)/3);
1395 if($d<0 && $only_down) $d=0;
1397 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1398 $unit = $units[$d];
1400 // If we dont want any zeros after the comma just add the thousand seperator
1401 if($noTrailingZero)
1402 $value = PMA_localizeNumber(preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$value));
1403 else
1404 $value = PMA_localizeNumber(number_format($value, $digits_right)); //number_format is not multibyte safe, str_replace is safe
1406 if($originalValue!=0 && floatval($value) == 0) return ' <'.(1/PMA_pow(10,$digits_right)).' '.$unit;
1408 return $sign . $value . ' ' . $unit;
1409 } // end of the 'PMA_formatNumber' function
1412 * Returns the number of bytes when a formatted size is given
1414 * @param string $formatted_size the size expression (for example 8MB)
1415 * @return integer The numerical part of the expression (for example 8)
1417 function PMA_extractValueFromFormattedSize($formatted_size)
1419 $return_value = -1;
1421 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1422 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1423 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1424 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1425 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1426 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1428 return $return_value;
1429 }// end of the 'PMA_extractValueFromFormattedSize' function
1432 * Writes localised date
1434 * @param string $timestamp the current timestamp
1435 * @param string $format format
1436 * @return string the formatted date
1438 * @access public
1440 function PMA_localisedDate($timestamp = -1, $format = '')
1442 $month = array(
1443 /* l10n: Short month name */
1444 __('Jan'),
1445 /* l10n: Short month name */
1446 __('Feb'),
1447 /* l10n: Short month name */
1448 __('Mar'),
1449 /* l10n: Short month name */
1450 __('Apr'),
1451 /* l10n: Short month name */
1452 _pgettext('Short month name', 'May'),
1453 /* l10n: Short month name */
1454 __('Jun'),
1455 /* l10n: Short month name */
1456 __('Jul'),
1457 /* l10n: Short month name */
1458 __('Aug'),
1459 /* l10n: Short month name */
1460 __('Sep'),
1461 /* l10n: Short month name */
1462 __('Oct'),
1463 /* l10n: Short month name */
1464 __('Nov'),
1465 /* l10n: Short month name */
1466 __('Dec'));
1467 $day_of_week = array(
1468 /* l10n: Short week day name */
1469 __('Sun'),
1470 /* l10n: Short week day name */
1471 __('Mon'),
1472 /* l10n: Short week day name */
1473 __('Tue'),
1474 /* l10n: Short week day name */
1475 __('Wed'),
1476 /* l10n: Short week day name */
1477 __('Thu'),
1478 /* l10n: Short week day name */
1479 __('Fri'),
1480 /* l10n: Short week day name */
1481 __('Sat'));
1483 if ($format == '') {
1484 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1485 $format = __('%B %d, %Y at %I:%M %p');
1488 if ($timestamp == -1) {
1489 $timestamp = time();
1492 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1493 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1495 return strftime($date, $timestamp);
1496 } // end of the 'PMA_localisedDate()' function
1500 * returns a tab for tabbed navigation.
1501 * If the variables $link and $args ar left empty, an inactive tab is created
1503 * @param array $tab array with all options
1504 * @param array $url_params
1505 * @return string html code for one tab, a link if valid otherwise a span
1506 * @access public
1508 function PMA_generate_html_tab($tab, $url_params = array(), $base_dir='')
1510 // default values
1511 $defaults = array(
1512 'text' => '',
1513 'class' => '',
1514 'active' => null,
1515 'link' => '',
1516 'sep' => '?',
1517 'attr' => '',
1518 'args' => '',
1519 'warning' => '',
1520 'fragment' => '',
1521 'id' => '',
1524 $tab = array_merge($defaults, $tab);
1526 // determine additionnal style-class
1527 if (empty($tab['class'])) {
1528 if (! empty($tab['active'])
1529 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1530 $tab['class'] = 'active';
1531 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1532 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1533 && empty($tab['warning'])) {
1534 $tab['class'] = 'active';
1538 if (!empty($tab['warning'])) {
1539 $tab['class'] .= ' error';
1540 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1543 // If there are any tab specific URL parameters, merge those with the general URL parameters
1544 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1545 $url_params = array_merge($url_params, $tab['url_params']);
1548 // build the link
1549 if (!empty($tab['link'])) {
1550 $tab['link'] = htmlentities($tab['link']);
1551 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1552 if (! empty($tab['args'])) {
1553 foreach ($tab['args'] as $param => $value) {
1554 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1555 . urlencode($value);
1560 if (! empty($tab['fragment'])) {
1561 $tab['link'] .= $tab['fragment'];
1564 // display icon, even if iconic is disabled but the link-text is missing
1565 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1566 && isset($tab['icon'])) {
1567 // avoid generating an alt tag, because it only illustrates
1568 // the text that follows and if browser does not display
1569 // images, the text is duplicated
1570 $image = '<img class="icon %1$s" src="' . $base_dir . 'themes/dot.gif"'
1571 .' width="16" height="16" alt="" />%2$s';
1572 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1574 // check to not display an empty link-text
1575 elseif (empty($tab['text'])) {
1576 $tab['text'] = '?';
1577 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1578 E_USER_NOTICE);
1581 //Set the id for the tab, if set in the params
1582 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1583 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1585 if (!empty($tab['link'])) {
1586 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1587 .$id_string
1588 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1589 . $tab['text'] . '</a>';
1590 } else {
1591 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1592 . $tab['text'] . '</span>';
1595 $out .= '</li>';
1596 return $out;
1597 } // end of the 'PMA_generate_html_tab()' function
1600 * returns html-code for a tab navigation
1602 * @param array $tabs one element per tab
1603 * @param string $url_params
1604 * @return string html-code for tab-navigation
1606 function PMA_generate_html_tabs($tabs, $url_params, $base_dir='')
1608 $tag_id = 'topmenu';
1609 $tab_navigation =
1610 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1611 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1613 foreach ($tabs as $tab) {
1614 $tab_navigation .= PMA_generate_html_tab($tab, $url_params, $base_dir);
1617 $tab_navigation .=
1618 '</ul>' . "\n"
1619 .'<div class="clearfloat"></div>'
1620 .'</div>' . "\n";
1622 return $tab_navigation;
1627 * Displays a link, or a button if the link's URL is too large, to
1628 * accommodate some browsers' limitations
1630 * @param string $url the URL
1631 * @param string $message the link message
1632 * @param mixed $tag_params string: js confirmation
1633 * array: additional tag params (f.e. style="")
1634 * @param boolean $new_form we set this to false when we are already in
1635 * a form, to avoid generating nested forms
1636 * @param boolean $strip_img
1637 * @param string $target
1639 * @return string the results to be echoed or saved in an array
1641 function PMA_linkOrButton($url, $message, $tag_params = array(),
1642 $new_form = true, $strip_img = false, $target = '')
1644 $url_length = strlen($url);
1645 // with this we should be able to catch case of image upload
1646 // into a (MEDIUM) BLOB; not worth generating even a form for these
1647 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1648 return '';
1651 if (! is_array($tag_params)) {
1652 $tmp = $tag_params;
1653 $tag_params = array();
1654 if (!empty($tmp)) {
1655 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1657 unset($tmp);
1659 if (! empty($target)) {
1660 $tag_params['target'] = htmlentities($target);
1663 $tag_params_strings = array();
1664 foreach ($tag_params as $par_name => $par_value) {
1665 // htmlspecialchars() only on non javascript
1666 $par_value = substr($par_name, 0, 2) == 'on'
1667 ? $par_value
1668 : htmlspecialchars($par_value);
1669 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1672 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1673 // no whitespace within an <a> else Safari will make it part of the link
1674 $ret = "\n" . '<a href="' . $url . '" '
1675 . implode(' ', $tag_params_strings) . '>'
1676 . $message . '</a>' . "\n";
1677 } else {
1678 // no spaces (linebreaks) at all
1679 // or after the hidden fields
1680 // IE will display them all
1682 // add class=link to submit button
1683 if (empty($tag_params['class'])) {
1684 $tag_params['class'] = 'link';
1687 // decode encoded url separators
1688 $separator = PMA_get_arg_separator();
1689 // on most places separator is still hard coded ...
1690 if ($separator !== '&') {
1691 // ... so always replace & with $separator
1692 $url = str_replace(htmlentities('&'), $separator, $url);
1693 $url = str_replace('&', $separator, $url);
1695 $url = str_replace(htmlentities($separator), $separator, $url);
1696 // end decode
1698 $url_parts = parse_url($url);
1699 $query_parts = explode($separator, $url_parts['query']);
1700 if ($new_form) {
1701 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1702 . ' method="post"' . $target . ' style="display: inline;">';
1703 $subname_open = '';
1704 $subname_close = '';
1705 $submit_name = '';
1706 } else {
1707 $query_parts[] = 'redirect=' . $url_parts['path'];
1708 if (empty($GLOBALS['subform_counter'])) {
1709 $GLOBALS['subform_counter'] = 0;
1711 $GLOBALS['subform_counter']++;
1712 $ret = '';
1713 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1714 $subname_close = ']';
1715 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1717 foreach ($query_parts as $query_pair) {
1718 list($eachvar, $eachval) = explode('=', $query_pair);
1719 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1720 . $subname_close . '" value="'
1721 . htmlspecialchars(urldecode($eachval)) . '" />';
1722 } // end while
1724 if (stristr($message, '<img')) {
1725 if ($strip_img) {
1726 $message = trim(strip_tags($message));
1727 $ret .= '<input type="submit"' . $submit_name . ' '
1728 . implode(' ', $tag_params_strings)
1729 . ' value="' . htmlspecialchars($message) . '" />';
1730 } else {
1731 $displayed_message = htmlspecialchars(
1732 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1733 $message));
1734 $ret .= '<input type="image"' . $submit_name . ' '
1735 . implode(' ', $tag_params_strings)
1736 . ' src="' . preg_replace(
1737 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1738 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1739 // Here we cannot obey PropertiesIconic completely as a
1740 // generated link would have a length over LinkLengthLimit
1741 // but we can at least show the message.
1742 // If PropertiesIconic is false or 'both'
1743 if ($GLOBALS['cfg']['PropertiesIconic'] !== true) {
1744 $ret .= ' <span class="clickprevimage">' . $displayed_message . '</span>';
1747 } else {
1748 $message = trim(strip_tags($message));
1749 $ret .= '<input type="submit"' . $submit_name . ' '
1750 . implode(' ', $tag_params_strings)
1751 . ' value="' . htmlspecialchars($message) . '" />';
1753 if ($new_form) {
1754 $ret .= '</form>';
1756 } // end if... else...
1758 return $ret;
1759 } // end of the 'PMA_linkOrButton()' function
1763 * Returns a given timespan value in a readable format.
1765 * @param int $seconds the timespan
1767 * @return string the formatted value
1769 function PMA_timespanFormat($seconds)
1771 $days = floor($seconds / 86400);
1772 if ($days > 0) {
1773 $seconds -= $days * 86400;
1775 $hours = floor($seconds / 3600);
1776 if ($days > 0 || $hours > 0) {
1777 $seconds -= $hours * 3600;
1779 $minutes = floor($seconds / 60);
1780 if ($days > 0 || $hours > 0 || $minutes > 0) {
1781 $seconds -= $minutes * 60;
1783 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1787 * Takes a string and outputs each character on a line for itself. Used
1788 * mainly for horizontalflipped display mode.
1789 * Takes care of special html-characters.
1790 * Fulfills todo-item
1791 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1793 * @todo add a multibyte safe function PMA_STR_split()
1794 * @param string $string The string
1795 * @param string $Separator The Separator (defaults to "<br />\n")
1797 * @access public
1798 * @return string The flipped string
1800 function PMA_flipstring($string, $Separator = "<br />\n")
1802 $format_string = '';
1803 $charbuff = false;
1805 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1806 $char = $string{$i};
1807 $append = false;
1809 if ($char == '&') {
1810 $format_string .= $charbuff;
1811 $charbuff = $char;
1812 } elseif ($char == ';' && !empty($charbuff)) {
1813 $format_string .= $charbuff . $char;
1814 $charbuff = false;
1815 $append = true;
1816 } elseif (! empty($charbuff)) {
1817 $charbuff .= $char;
1818 } else {
1819 $format_string .= $char;
1820 $append = true;
1823 // do not add separator after the last character
1824 if ($append && ($i != $str_len - 1)) {
1825 $format_string .= $Separator;
1829 return $format_string;
1833 * Function added to avoid path disclosures.
1834 * Called by each script that needs parameters, it displays
1835 * an error message and, by default, stops the execution.
1837 * Not sure we could use a strMissingParameter message here,
1838 * would have to check if the error message file is always available
1840 * @todo use PMA_fatalError() if $die === true?
1841 * @param array $params The names of the parameters needed by the calling script.
1842 * @param bool $die Stop the execution?
1843 * (Set this manually to false in the calling script
1844 * until you know all needed parameters to check).
1845 * @param bool $request Whether to include this list in checking for special params.
1846 * @global string path to current script
1847 * @global boolean flag whether any special variable was required
1849 * @access public
1851 function PMA_checkParameters($params, $die = true, $request = true)
1853 global $checked_special;
1855 if (! isset($checked_special)) {
1856 $checked_special = false;
1859 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1860 $found_error = false;
1861 $error_message = '';
1863 foreach ($params as $param) {
1864 if ($request && $param != 'db' && $param != 'table') {
1865 $checked_special = true;
1868 if (! isset($GLOBALS[$param])) {
1869 $error_message .= $reported_script_name
1870 . ': ' . __('Missing parameter:') . ' '
1871 . $param
1872 . PMA_showDocu('faqmissingparameters')
1873 . '<br />';
1874 $found_error = true;
1877 if ($found_error) {
1879 * display html meta tags
1881 require_once './libraries/header_meta_style.inc.php';
1882 echo '</head><body><p>' . $error_message . '</p></body></html>';
1883 if ($die) {
1884 exit();
1887 } // end function
1890 * Function to generate unique condition for specified row.
1892 * @param resource $handle current query result
1893 * @param integer $fields_cnt number of fields
1894 * @param array $fields_meta meta information about fields
1895 * @param array $row current row
1896 * @param boolean $force_unique generate condition only on pk or unique
1898 * @access public
1899 * @return array the calculated condition and whether condition is unique
1901 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
1903 $primary_key = '';
1904 $unique_key = '';
1905 $nonprimary_condition = '';
1906 $preferred_condition = '';
1908 for ($i = 0; $i < $fields_cnt; ++$i) {
1909 $condition = '';
1910 $field_flags = PMA_DBI_field_flags($handle, $i);
1911 $meta = $fields_meta[$i];
1913 // do not use a column alias in a condition
1914 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
1915 $meta->orgname = $meta->name;
1917 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
1918 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
1919 foreach ($GLOBALS['analyzed_sql'][0]['select_expr'] as $select_expr) {
1920 // need (string) === (string)
1921 // '' !== 0 but '' == 0
1922 if ((string) $select_expr['alias'] === (string) $meta->name) {
1923 $meta->orgname = $select_expr['column'];
1924 break;
1925 } // end if
1926 } // end foreach
1930 // Do not use a table alias in a condition.
1931 // Test case is:
1932 // select * from galerie x WHERE
1933 //(select count(*) from galerie y where y.datum=x.datum)>1
1935 // But orgtable is present only with mysqli extension so the
1936 // fix is only for mysqli.
1937 // Also, do not use the original table name if we are dealing with
1938 // a view because this view might be updatable.
1939 // (The isView() verification should not be costly in most cases
1940 // because there is some caching in the function).
1941 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
1942 $meta->table = $meta->orgtable;
1945 // to fix the bug where float fields (primary or not)
1946 // can't be matched because of the imprecision of
1947 // floating comparison, use CONCAT
1948 // (also, the syntax "CONCAT(field) IS NULL"
1949 // that we need on the next "if" will work)
1950 if ($meta->type == 'real') {
1951 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
1952 . PMA_backquote($meta->orgname) . ') ';
1953 } else {
1954 $condition = ' ' . PMA_backquote($meta->table) . '.'
1955 . PMA_backquote($meta->orgname) . ' ';
1956 } // end if... else...
1958 if (! isset($row[$i]) || is_null($row[$i])) {
1959 $condition .= 'IS NULL AND';
1960 } else {
1961 // timestamp is numeric on some MySQL 4.1
1962 // for real we use CONCAT above and it should compare to string
1963 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
1964 $condition .= '= ' . $row[$i] . ' AND';
1965 } elseif (($meta->type == 'blob' || $meta->type == 'string')
1966 // hexify only if this is a true not empty BLOB or a BINARY
1967 && stristr($field_flags, 'BINARY')
1968 && !empty($row[$i])) {
1969 // do not waste memory building a too big condition
1970 if (strlen($row[$i]) < 1000) {
1971 // use a CAST if possible, to avoid problems
1972 // if the field contains wildcard characters % or _
1973 $condition .= '= CAST(0x' . bin2hex($row[$i])
1974 . ' AS BINARY) AND';
1975 } else {
1976 // this blob won't be part of the final condition
1977 $condition = '';
1979 } elseif ($meta->type == 'bit') {
1980 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
1981 } else {
1982 $condition .= '= \''
1983 . PMA_sqlAddSlashes($row[$i], false, true) . '\' AND';
1986 if ($meta->primary_key > 0) {
1987 $primary_key .= $condition;
1988 } elseif ($meta->unique_key > 0) {
1989 $unique_key .= $condition;
1991 $nonprimary_condition .= $condition;
1992 } // end for
1994 // Correction University of Virginia 19991216:
1995 // prefer primary or unique keys for condition,
1996 // but use conjunction of all values if no primary key
1997 $clause_is_unique = true;
1998 if ($primary_key) {
1999 $preferred_condition = $primary_key;
2000 } elseif ($unique_key) {
2001 $preferred_condition = $unique_key;
2002 } elseif (! $force_unique) {
2003 $preferred_condition = $nonprimary_condition;
2004 $clause_is_unique = false;
2007 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2008 return(array($where_clause, $clause_is_unique));
2009 } // end function
2012 * Generate a button or image tag
2014 * @param string $button_name name of button element
2015 * @param string $button_class class of button element
2016 * @param string $image_name name of image element
2017 * @param string $text text to display
2018 * @param string $image image to display
2019 * @param string $value
2021 * @access public
2023 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2024 $image, $value = '')
2026 if ($value == '') {
2027 $value = $text;
2029 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2030 echo ' <input type="submit" name="' . $button_name . '"'
2031 .' value="' . htmlspecialchars($value) . '"'
2032 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2033 return;
2036 /* Opera has trouble with <input type="image"> */
2037 /* IE has trouble with <button> */
2038 if (PMA_USR_BROWSER_AGENT != 'IE') {
2039 echo '<button class="' . $button_class . '" type="submit"'
2040 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2041 .' title="' . htmlspecialchars($text) . '">' . "\n"
2042 . PMA_getIcon($image, $text)
2043 .'</button>' . "\n";
2044 } else {
2045 echo '<input type="image" name="' . $image_name . '" value="'
2046 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2047 . $image . '" />'
2048 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2050 } // end function
2053 * Generate a pagination selector for browsing resultsets
2055 * @param int $rows Number of rows in the pagination set
2056 * @param int $pageNow current page number
2057 * @param int $nbTotalPage number of total pages
2058 * @param int $showAll If the number of pages is lower than this
2059 * variable, no pages will be omitted in pagination
2060 * @param int $sliceStart How many rows at the beginning should always be shown?
2061 * @param int $sliceEnd How many rows at the end should always be shown?
2062 * @param int $percent Percentage of calculation page offsets to hop to a next page
2063 * @param int $range Near the current page, how many pages should
2064 * be considered "nearby" and displayed as well?
2065 * @param string $prompt The prompt to display (sometimes empty)
2067 * @return string
2068 * @access public
2070 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2071 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2072 $range = 10, $prompt = '')
2074 $increment = floor($nbTotalPage / $percent);
2075 $pageNowMinusRange = ($pageNow - $range);
2076 $pageNowPlusRange = ($pageNow + $range);
2078 $gotopage = $prompt . ' <select id="pageselector" ';
2079 if ($GLOBALS['cfg']['AjaxEnable']) {
2080 $gotopage .= ' class="ajax"';
2082 $gotopage .= ' name="pos" >' . "\n";
2083 if ($nbTotalPage < $showAll) {
2084 $pages = range(1, $nbTotalPage);
2085 } else {
2086 $pages = array();
2088 // Always show first X pages
2089 for ($i = 1; $i <= $sliceStart; $i++) {
2090 $pages[] = $i;
2093 // Always show last X pages
2094 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2095 $pages[] = $i;
2098 // Based on the number of results we add the specified
2099 // $percent percentage to each page number,
2100 // so that we have a representing page number every now and then to
2101 // immediately jump to specific pages.
2102 // As soon as we get near our currently chosen page ($pageNow -
2103 // $range), every page number will be shown.
2104 $i = $sliceStart;
2105 $x = $nbTotalPage - $sliceEnd;
2106 $met_boundary = false;
2107 while ($i <= $x) {
2108 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2109 // If our pageselector comes near the current page, we use 1
2110 // counter increments
2111 $i++;
2112 $met_boundary = true;
2113 } else {
2114 // We add the percentage increment to our current page to
2115 // hop to the next one in range
2116 $i += $increment;
2118 // Make sure that we do not cross our boundaries.
2119 if ($i > $pageNowMinusRange && ! $met_boundary) {
2120 $i = $pageNowMinusRange;
2124 if ($i > 0 && $i <= $x) {
2125 $pages[] = $i;
2129 // Since because of ellipsing of the current page some numbers may be double,
2130 // we unify our array:
2131 sort($pages);
2132 $pages = array_unique($pages);
2135 foreach ($pages as $i) {
2136 if ($i == $pageNow) {
2137 $selected = 'selected="selected" style="font-weight: bold"';
2138 } else {
2139 $selected = '';
2141 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2144 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2146 return $gotopage;
2147 } // end function
2151 * Generate navigation for a list
2153 * @todo use $pos from $_url_params
2154 * @param int $count number of elements in the list
2155 * @param int $pos current position in the list
2156 * @param array $_url_params url parameters
2157 * @param string $script script name for form target
2158 * @param string $frame target frame
2159 * @param int $max_count maximum number of elements to display from the list
2161 * @access public
2163 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2165 if ($max_count < $count) {
2166 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2167 echo __('Page number:');
2168 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2170 // Move to the beginning or to the previous page
2171 if ($pos > 0) {
2172 // patch #474210 - part 1
2173 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2174 $caption1 = '&lt;&lt;';
2175 $caption2 = ' &lt; ';
2176 $title1 = ' title="' . __('Begin') . '"';
2177 $title2 = ' title="' . __('Previous') . '"';
2178 } else {
2179 $caption1 = __('Begin') . ' &lt;&lt;';
2180 $caption2 = __('Previous') . ' &lt;';
2181 $title1 = '';
2182 $title2 = '';
2183 } // end if... else...
2184 $_url_params['pos'] = 0;
2185 echo '<a' . $title1 . ' href="' . $script
2186 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2187 . $caption1 . '</a>';
2188 $_url_params['pos'] = $pos - $max_count;
2189 echo '<a' . $title2 . ' href="' . $script
2190 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2191 . $caption2 . '</a>';
2194 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2195 echo PMA_generate_common_hidden_inputs($_url_params);
2196 echo PMA_pageselector(
2197 $max_count,
2198 floor(($pos + 1) / $max_count) + 1,
2199 ceil($count / $max_count));
2200 echo '</form>';
2202 if ($pos + $max_count < $count) {
2203 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2204 $caption3 = ' &gt; ';
2205 $caption4 = '&gt;&gt;';
2206 $title3 = ' title="' . __('Next') . '"';
2207 $title4 = ' title="' . __('End') . '"';
2208 } else {
2209 $caption3 = '&gt; ' . __('Next');
2210 $caption4 = '&gt;&gt; ' . __('End');
2211 $title3 = '';
2212 $title4 = '';
2213 } // end if... else...
2214 $_url_params['pos'] = $pos + $max_count;
2215 echo '<a' . $title3 . ' href="' . $script
2216 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2217 . $caption3 . '</a>';
2218 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2219 if ($_url_params['pos'] == $count) {
2220 $_url_params['pos'] = $count - $max_count;
2222 echo '<a' . $title4 . ' href="' . $script
2223 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2224 . $caption4 . '</a>';
2226 echo "\n";
2227 if ('frame_navigation' == $frame) {
2228 echo '</div>' . "\n";
2234 * replaces %u in given path with current user name
2236 * example:
2237 * <code>
2238 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2240 * </code>
2241 * @param string $dir with wildcard for user
2242 * @return string per user directory
2244 function PMA_userDir($dir)
2246 // add trailing slash
2247 if (substr($dir, -1) != '/') {
2248 $dir .= '/';
2251 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2255 * returns html code for db link to default db page
2257 * @param string $database
2258 * @return string html link to default db page
2260 function PMA_getDbLink($database = null)
2262 if (! strlen($database)) {
2263 if (! strlen($GLOBALS['db'])) {
2264 return '';
2266 $database = $GLOBALS['db'];
2267 } else {
2268 $database = PMA_unescape_mysql_wildcards($database);
2271 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2272 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2273 .htmlspecialchars($database) . '</a>';
2277 * Displays a lightbulb hint explaining a known external bug
2278 * that affects a functionality
2280 * @param string $functionality localized message explaining the func.
2281 * @param string $component 'mysql' (eventually, 'php')
2282 * @param string $minimum_version of this component
2283 * @param string $bugref bug reference for this component
2285 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2287 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2288 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2293 * Generates and echoes an HTML checkbox
2295 * @param string $html_field_name the checkbox HTML field
2296 * @param string $label
2297 * @param boolean $checked is it initially checked?
2298 * @param boolean $onclick should it submit the form on click?
2300 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2302 echo '<input type="checkbox" name="' . $html_field_name . '" id="' . $html_field_name . '"' . ($checked ? ' checked="checked"' : '') . ($onclick ? ' onclick="this.form.submit();"' : '') . ' /><label for="' . $html_field_name . '">' . $label . '</label>';
2306 * Generates and echoes a set of radio HTML fields
2308 * @param string $html_field_name the radio HTML field
2309 * @param array $choices the choices values and labels
2310 * @param string $checked_choice the choice to check by default
2311 * @param boolean $line_break whether to add an HTML line break after a choice
2312 * @param boolean $escape_label whether to use htmlspecialchars() on label
2313 * @param string $class enclose each choice with a div of this class
2315 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2316 foreach ($choices as $choice_value => $choice_label) {
2317 if (! empty($class)) {
2318 echo '<div class="' . $class . '">';
2320 $html_field_id = $html_field_name . '_' . $choice_value;
2321 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2322 if ($choice_value == $checked_choice) {
2323 echo ' checked="checked"';
2325 echo ' />' . "\n";
2326 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2327 if ($line_break) {
2328 echo '<br />';
2330 if (! empty($class)) {
2331 echo '</div>';
2333 echo "\n";
2338 * Generates and returns an HTML dropdown
2340 * @param string $select_name
2341 * @param array $choices choices values
2342 * @param string $active_choice the choice to select by default
2343 * @param string $id id of the select element; can be different in case
2344 * the dropdown is present more than once on the page
2345 * @return string
2346 * @todo support titles
2348 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2350 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2351 foreach ($choices as $one_choice_value => $one_choice_label) {
2352 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2353 if ($one_choice_value == $active_choice) {
2354 $result .= ' selected="selected"';
2356 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2358 $result .= '</select>';
2359 return $result;
2363 * Generates a slider effect (jQjuery)
2364 * Takes care of generating the initial <div> and the link
2365 * controlling the slider; you have to generate the </div> yourself
2366 * after the sliding section.
2368 * @param string $id the id of the <div> on which to apply the effect
2369 * @param string $message the message to show as a link
2371 function PMA_generate_slider_effect($id, $message)
2373 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2374 echo '<div id="' . $id . '">';
2375 return;
2378 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2379 * opening the <div> with PHP itself instead of JavaScript.
2381 * @todo find a better solution that uses $.append(), the recommended method
2382 * maybe by using an additional param, the id of the div to append to
2385 <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); ?>">
2386 <?php
2390 * Creates an AJAX sliding toggle button (or and equivalent form when AJAX is disabled)
2392 * @param string $action The URL for the request to be executed
2393 * @param string $select_name The name for the dropdown box
2394 * @param array $options An array of options (see rte_footer.lib.php)
2395 * @param string $callback A JS snippet to execute when the request is
2396 * successfully processed
2398 * @return string HTML code for the toggle button
2400 function PMA_toggleButton($action, $select_name, $options, $callback)
2402 // Do the logic first
2403 $link_on = "$action&amp;$select_name=" . urlencode($options[1]['value']);
2404 $link_off = "$action&amp;$select_name=" . urlencode($options[0]['value']);
2405 if ($options[1]['selected'] == true) {
2406 $state = 'on';
2407 } else if ($options[0]['selected'] == true) {
2408 $state = 'off';
2409 } else {
2410 $state = 'on';
2412 $selected1 = '';
2413 $selected0 = '';
2414 if ($options[1]['selected'] == true) {
2415 $selected1 = " selected='selected'";
2416 } else if ($options[0]['selected'] == true) {
2417 $selected0 = " selected='selected'";
2419 // Generate output
2420 $retval = "<!-- TOGGLE START -->\n";
2421 if ($GLOBALS['cfg']['AjaxEnable']) {
2422 $retval .= "<noscript>\n";
2424 $retval .= "<div class='wrapper'>\n";
2425 $retval .= " <form action='$action' method='post'>\n";
2426 $retval .= " <select name='$select_name'>\n";
2427 $retval .= " <option value='{$options[1]['value']}'$selected1>";
2428 $retval .= " {$options[1]['label']}\n";
2429 $retval .= " </option>\n";
2430 $retval .= " <option value='{$options[0]['value']}'$selected0>";
2431 $retval .= " {$options[0]['label']}\n";
2432 $retval .= " </option>\n";
2433 $retval .= " </select>\n";
2434 $retval .= " <input type='submit' value='" . __('Change') . "'/>\n";
2435 $retval .= " </form>\n";
2436 $retval .= "</div>\n";
2437 if ($GLOBALS['cfg']['AjaxEnable']) {
2438 $retval .= "</noscript>\n";
2439 $retval .= "<div class='wrapper toggleAjax hide'>\n";
2440 $retval .= " <div class='toggleButton'>\n";
2441 $retval .= " <div title='" . __('Click to toggle') . "' class='container $state'>\n";
2442 $retval .= " <img src='{$GLOBALS['pmaThemeImage']}toggle-{$GLOBALS['text_dir']}.png'\n";
2443 $retval .= " alt='' />\n";
2444 $retval .= " <table cellspacing='0' cellpadding='0'><tr>\n";
2445 $retval .= " <tbody>\n";
2446 $retval .= " <td class='toggleOn'>\n";
2447 $retval .= " <span class='hide'>$link_on</span>\n";
2448 $retval .= " <div>";
2449 $retval .= str_replace(' ', '&nbsp;', $options[1]['label']) . "</div>\n";
2450 $retval .= " </td>\n";
2451 $retval .= " <td><div>&nbsp;</div></td>\n";
2452 $retval .= " <td class='toggleOff'>\n";
2453 $retval .= " <span class='hide'>$link_off</span>\n";
2454 $retval .= " <div>";
2455 $retval .= str_replace(' ', '&nbsp;', $options[0]['label']) . "</div>\n";
2456 $retval .= " </div>\n";
2457 $retval .= " </tbody>\n";
2458 $retval .= " </tr></table>\n";
2459 $retval .= " <span class='hide callback'>$callback</span>\n";
2460 $retval .= " <span class='hide text_direction'>{$GLOBALS['text_dir']}</span>\n";
2461 $retval .= " </div>\n";
2462 $retval .= " </div>\n";
2463 $retval .= "</div>\n";
2465 $retval .= "<!-- TOGGLE END -->";
2467 return $retval;
2468 } // end PMA_toggleButton()
2471 * Clears cache content which needs to be refreshed on user change.
2473 function PMA_clearUserCache() {
2474 PMA_cacheUnset('is_superuser', true);
2478 * Verifies if something is cached in the session
2480 * @param string $var
2481 * @param int|true $server
2482 * @return boolean
2484 function PMA_cacheExists($var, $server = 0)
2486 if (true === $server) {
2487 $server = $GLOBALS['server'];
2489 return isset($_SESSION['cache']['server_' . $server][$var]);
2493 * Gets cached information from the session
2495 * @param string $var
2496 * @param int|true $server
2497 * @return mixed
2499 function PMA_cacheGet($var, $server = 0)
2501 if (true === $server) {
2502 $server = $GLOBALS['server'];
2504 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2505 return $_SESSION['cache']['server_' . $server][$var];
2506 } else {
2507 return null;
2512 * Caches information in the session
2514 * @param string $var
2515 * @param mixed $val
2516 * @param int|true $server
2517 * @return mixed
2519 function PMA_cacheSet($var, $val = null, $server = 0)
2521 if (true === $server) {
2522 $server = $GLOBALS['server'];
2524 $_SESSION['cache']['server_' . $server][$var] = $val;
2528 * Removes cached information from the session
2530 * @param string $var
2531 * @param int|true $server
2533 function PMA_cacheUnset($var, $server = 0)
2535 if (true === $server) {
2536 $server = $GLOBALS['server'];
2538 unset($_SESSION['cache']['server_' . $server][$var]);
2542 * Converts a bit value to printable format;
2543 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2544 * function because in PHP, decbin() supports only 32 bits
2546 * @param numeric $value coming from a BIT field
2547 * @param integer $length
2548 * @return string the printable value
2550 function PMA_printable_bit_value($value, $length) {
2551 $printable = '';
2552 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2553 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2555 $printable = substr($printable, -$length);
2556 return $printable;
2560 * Verifies whether the value contains a non-printable character
2562 * @param string $value
2563 * @return boolean
2565 function PMA_contains_nonprintable_ascii($value) {
2566 return preg_match('@[^[:print:]]@', $value);
2570 * Converts a BIT type default value
2571 * for example, b'010' becomes 010
2573 * @param string $bit_default_value
2574 * @return string the converted value
2576 function PMA_convert_bit_default_value($bit_default_value) {
2577 return strtr($bit_default_value, array("b" => "", "'" => ""));
2581 * Extracts the various parts from a field type spec
2583 * @param string $fieldspec
2584 * @return array associative array containing type, spec_in_brackets
2585 * and possibly enum_set_values (another array)
2587 function PMA_extractFieldSpec($fieldspec) {
2588 $first_bracket_pos = strpos($fieldspec, '(');
2589 if ($first_bracket_pos) {
2590 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2591 // convert to lowercase just to be sure
2592 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2593 } else {
2594 $type = $fieldspec;
2595 $spec_in_brackets = '';
2598 if ('enum' == $type || 'set' == $type) {
2599 // Define our working vars
2600 $enum_set_values = array();
2601 $working = "";
2602 $in_string = false;
2603 $index = 0;
2605 // While there is another character to process
2606 while (isset($fieldspec[$index])) {
2607 // Grab the char to look at
2608 $char = $fieldspec[$index];
2610 // If it is a single quote, needs to be handled specially
2611 if ($char == "'") {
2612 // If we are not currently in a string, begin one
2613 if (! $in_string) {
2614 $in_string = true;
2615 $working = "";
2616 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2617 } else {
2618 // Check out the next character (if possible)
2619 $has_next = isset($fieldspec[$index + 1]);
2620 $next = $has_next ? $fieldspec[$index + 1] : null;
2622 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2623 if (! $has_next || $next != "'") {
2624 $enum_set_values[] = $working;
2625 $in_string = false;
2627 // Otherwise, this is a 'double quote', and can be added to the working string
2628 } elseif ($next == "'") {
2629 $working .= "'";
2630 // Skip the next char; we already know what it is
2631 $index++;
2634 // escaping of a quote?
2635 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2636 $working .= "'";
2637 $index++;
2638 // Otherwise, add it to our working string like normal
2639 } else {
2640 $working .= $char;
2642 // Increment character index
2643 $index++;
2644 } // end while
2645 } else {
2646 $enum_set_values = array();
2649 return array(
2650 'type' => $type,
2651 'spec_in_brackets' => $spec_in_brackets,
2652 'enum_set_values' => $enum_set_values
2657 * Verifies if this table's engine supports foreign keys
2659 * @param string $engine
2660 * @return boolean
2662 function PMA_foreignkey_supported($engine) {
2663 $engine = strtoupper($engine);
2664 if ('INNODB' == $engine || 'PBXT' == $engine) {
2665 return true;
2666 } else {
2667 return false;
2672 * Replaces some characters by a displayable equivalent
2674 * @param string $content
2675 * @return string the content with characters replaced
2677 function PMA_replace_binary_contents($content) {
2678 $result = str_replace("\x00", '\0', $content);
2679 $result = str_replace("\x08", '\b', $result);
2680 $result = str_replace("\x0a", '\n', $result);
2681 $result = str_replace("\x0d", '\r', $result);
2682 $result = str_replace("\x1a", '\Z', $result);
2683 return $result;
2687 * Converts GIS data to Well Known Text format
2689 * @param $data GIS data
2690 * @param $includeSRID Add SRID to the WKT
2691 * @return GIS data in Well Know Text format
2693 function PMA_asWKT($data, $includeSRID = false) {
2694 // Convert to WKT format
2695 $hex = bin2hex($data);
2696 $wktsql = "SELECT ASTEXT(x'" . $hex . "')";
2697 if ($includeSRID) {
2698 $wktsql .= ", SRID(x'" . $hex . "')";
2700 $wktresult = PMA_DBI_try_query($wktsql, null, PMA_DBI_QUERY_STORE);
2701 $wktarr = PMA_DBI_fetch_row($wktresult, 0);
2702 $wktval = $wktarr[0];
2703 if ($includeSRID) {
2704 $srid = $wktarr[1];
2705 $wktval = "'" . $wktval . "'," . $srid;
2707 @PMA_DBI_free_result($wktresult);
2708 return $wktval;
2712 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2714 * @param string $string
2715 * @return string with the chars replaced
2718 function PMA_duplicateFirstNewline($string) {
2719 $first_occurence = strpos($string, "\r\n");
2720 if ($first_occurence === 0){
2721 $string = "\n".$string;
2723 return $string;
2727 * Get the action word corresponding to a script name
2728 * in order to display it as a title in navigation panel
2730 * @param string $target a valid value for $cfg['LeftDefaultTabTable'], $cfg['DefaultTabTable']
2731 * or $cfg['DefaultTabDatabase']
2732 * @return array
2734 function PMA_getTitleForTarget($target) {
2735 $mapping = array(
2736 // Values for $cfg['DefaultTabTable']
2737 'tbl_structure.php' => __('Structure'),
2738 'tbl_sql.php' => __('SQL'),
2739 'tbl_select.php' =>__('Search'),
2740 'tbl_change.php' =>__('Insert'),
2741 'sql.php' => __('Browse'),
2743 // Values for $cfg['DefaultTabDatabase']
2744 'db_structure.php' => __('Structure'),
2745 'db_sql.php' => __('SQL'),
2746 'db_search.php' => __('Search'),
2747 'db_operations.php' => __('Operations'),
2749 return $mapping[$target];
2753 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2755 * @param string $string Text where to do expansion.
2756 * @param function $escape Function to call for escaping variable values.
2757 * @param array $updates Array with overrides for default parameters (obtained from GLOBALS).
2758 * @return string
2760 function PMA_expandUserString($string, $escape = null, $updates = array()) {
2761 /* Content */
2762 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2763 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2764 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2765 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2766 $vars['database'] = $GLOBALS['db'];
2767 $vars['table'] = $GLOBALS['table'];
2768 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2770 /* Update forced variables */
2771 foreach ($updates as $key => $val) {
2772 $vars[$key] = $val;
2775 /* Replacement mapping */
2777 * The __VAR__ ones are for backward compatibility, because user
2778 * might still have it in cookies.
2780 $replace = array(
2781 '@HTTP_HOST@' => $vars['http_host'],
2782 '@SERVER@' => $vars['server_name'],
2783 '__SERVER__' => $vars['server_name'],
2784 '@VERBOSE@' => $vars['server_verbose'],
2785 '@VSERVER@' => $vars['server_verbose_or_name'],
2786 '@DATABASE@' => $vars['database'],
2787 '__DB__' => $vars['database'],
2788 '@TABLE@' => $vars['table'],
2789 '__TABLE__' => $vars['table'],
2790 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2793 /* Optional escaping */
2794 if (!is_null($escape)) {
2795 foreach ($replace as $key => $val) {
2796 $replace[$key] = $escape($val);
2800 /* Fetch fields list if required */
2801 if (strpos($string, '@FIELDS@') !== false) {
2802 $fields_list = PMA_DBI_fetch_result(
2803 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2804 . '.' . PMA_backquote($GLOBALS['table']));
2806 $field_names = array();
2807 foreach ($fields_list as $field) {
2808 if (!is_null($escape)) {
2809 $field_names[] = $escape($field['Field']);
2810 } else {
2811 $field_names[] = $field['Field'];
2815 $replace['@FIELDS@'] = implode(',', $field_names);
2818 /* Do the replacement */
2819 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2823 * function that generates a json output for an ajax request and ends script
2824 * execution
2826 * @param bool $message message string containing the html of the message
2827 * @param bool $success success whether the ajax request was successfull
2828 * @param array $extra_data extra_data optional - any other data as part of the json request
2831 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2833 $response = array();
2834 if( $success == true ) {
2835 $response['success'] = true;
2836 if ($message instanceof PMA_Message) {
2837 $response['message'] = $message->getDisplay();
2839 else {
2840 $response['message'] = $message;
2843 else {
2844 $response['success'] = false;
2845 if($message instanceof PMA_Message) {
2846 $response['error'] = $message->getDisplay();
2848 else {
2849 $response['error'] = $message;
2853 // If extra_data has been provided, append it to the response array
2854 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2855 $response = array_merge($response, $extra_data);
2858 // Set the Content-Type header to JSON so that jQuery parses the
2859 // response correctly.
2861 // At this point, other headers might have been sent;
2862 // even if $GLOBALS['is_header_sent'] is true,
2863 // we have to send these additional headers.
2864 header('Cache-Control: no-cache');
2865 header("Content-Type: application/json");
2867 echo json_encode($response);
2869 if(!defined('TESTSUITE'))
2870 exit;
2874 * Display the form used to browse anywhere on the local server for the file to import
2876 * @param $max_upload_size
2878 function PMA_browseUploadFile($max_upload_size) {
2879 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2880 echo '<div id="upload_form_status" style="display: none;"></div>';
2881 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2882 echo '<input type="file" name="import_file" id="input_import_file" />';
2883 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2884 // some browsers should respect this :)
2885 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2889 * Display the form used to select a file to import from the server upload directory
2891 * @param $import_list
2892 * @param $uploaddir
2894 function PMA_selectUploadFile($import_list, $uploaddir) {
2895 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2896 $extensions = '';
2897 foreach ($import_list as $key => $val) {
2898 if (!empty($extensions)) {
2899 $extensions .= '|';
2901 $extensions .= $val['extension'];
2903 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2905 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2906 if ($files === false) {
2907 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2908 } elseif (!empty($files)) {
2909 echo "\n";
2910 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2911 echo ' <option value="">&nbsp;</option>' . "\n";
2912 echo $files;
2913 echo ' </select>' . "\n";
2914 } elseif (empty ($files)) {
2915 echo '<i>' . __('There are no files to upload') . '</i>';
2920 * Build titles and icons for action links
2922 * @return array the action titles
2924 function PMA_buildActionTitles() {
2925 $titles = array();
2927 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2928 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2929 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2930 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2931 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2932 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2933 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2934 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2935 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2936 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2937 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2938 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
2939 $titles['NoEdit'] = PMA_getIcon('bd_edit.png', __('Edit'), true);
2940 $titles['Export'] = PMA_getIcon('b_export.png', __('Export'), true);
2941 $titles['NoExport'] = PMA_getIcon('bd_export.png', __('Export'), true);
2942 $titles['Execute'] = PMA_getIcon('b_nextpage.png', __('Execute'), true);
2943 $titles['NoExecute'] = PMA_getIcon('bd_nextpage.png', __('Execute'), true);
2944 return $titles;
2948 * This function processes the datatypes supported by the DB, as specified in
2949 * $cfg['ColumnTypes'] and either returns an array (useful for quickly checking
2950 * if a datatype is supported) or an HTML snippet that creates a drop-down list.
2952 * @param bool $html Whether to generate an html snippet or an array
2953 * @param string $selected The value to mark as selected in HTML mode
2955 * @return mixed An HTML snippet or an array of datatypes.
2958 function PMA_getSupportedDatatypes($html = false, $selected = '')
2960 global $cfg;
2962 if ($html) {
2963 // NOTE: the SELECT tag in not included in this snippet.
2964 $retval = '';
2965 foreach ($cfg['ColumnTypes'] as $key => $value) {
2966 if (is_array($value)) {
2967 $retval .= "<optgroup label='" . htmlspecialchars($key) . "'>";
2968 foreach ($value as $subvalue) {
2969 if ($subvalue == $selected) {
2970 $retval .= "<option selected='selected'>";
2971 $retval .= $subvalue;
2972 $retval .= "</option>";
2973 } else if ($subvalue === '-') {
2974 $retval .= "<option disabled='disabled'>";
2975 $retval .= $subvalue;
2976 $retval .= "</option>";
2977 } else {
2978 $retval .= "<option>$subvalue</option>";
2981 $retval .= '</optgroup>';
2982 } else {
2983 if ($selected == $value) {
2984 $retval .= "<option selected='selected'>$value</option>";
2985 } else {
2986 $retval .= "<option>$value</option>";
2990 } else {
2991 $retval = array();
2992 foreach ($cfg['ColumnTypes'] as $value) {
2993 if (is_array($value)) {
2994 foreach ($value as $subvalue) {
2995 if ($subvalue !== '-') {
2996 $retval[] = $subvalue;
2999 } else {
3000 if ($value !== '-') {
3001 $retval[] = $value;
3007 return $retval;
3008 } // end PMA_getSupportedDatatypes()
3011 * Returns a list of datatypes that are not (yet) handled by PMA.
3012 * Used by: tbl_change.php and libraries/db_routines.inc.php
3014 * @return array list of datatypes
3017 function PMA_unsupportedDatatypes() {
3018 $no_support_types = array();
3019 return $no_support_types;
3022 function PMA_getGISDatatypes() {
3023 $gis_data_types = array('geometry',
3024 'point',
3025 'linestring',
3026 'polygon',
3027 'multipoint',
3028 'multilinestring',
3029 'multipolygon',
3030 'geometrycollection'
3033 return $gis_data_types;
3036 * Creates a dropdown box with MySQL functions for a particular column.
3038 * @param array $field Data about the column for which
3039 * to generate the dropdown
3040 * @param bool $insert_mode Whether the operation is 'insert'
3042 * @global array $cfg PMA configuration
3043 * @global array $analyzed_sql Analyzed SQL query
3044 * @global mixed $data (null/string) FIXME: what is this for?
3046 * @return string An HTML snippet of a dropdown list with function
3047 * names appropriate for the requested column.
3049 function PMA_getFunctionsForField($field, $insert_mode)
3051 global $cfg, $analyzed_sql, $data;
3053 $selected = '';
3054 // Find the current type in the RestrictColumnTypes. Will result in 'FUNC_CHAR'
3055 // or something similar. Then directly look up the entry in the RestrictFunctions array,
3056 // which will then reveal the available dropdown options
3057 if (isset($cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])])
3058 && isset($cfg['RestrictFunctions'][$cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])]])) {
3059 $current_func_type = $cfg['RestrictColumnTypes'][strtoupper($field['True_Type'])];
3060 $dropdown = $cfg['RestrictFunctions'][$current_func_type];
3061 $default_function = $cfg['DefaultFunctions'][$current_func_type];
3062 } else {
3063 $dropdown = array();
3064 $default_function = '';
3066 $dropdown_built = array();
3067 $op_spacing_needed = false;
3068 // what function defined as default?
3069 // for the first timestamp we don't set the default function
3070 // if there is a default value for the timestamp
3071 // (not including CURRENT_TIMESTAMP)
3072 // and the column does not have the
3073 // ON UPDATE DEFAULT TIMESTAMP attribute.
3074 if ($field['True_Type'] == 'timestamp'
3075 && empty($field['Default'])
3076 && empty($data)
3077 && ! isset($analyzed_sql[0]['create_table_fields'][$field['Field']]['on_update_current_timestamp'])) {
3078 $default_function = $cfg['DefaultFunctions']['first_timestamp'];
3080 // For primary keys of type char(36) or varchar(36) UUID if the default function
3081 // Only applies to insert mode, as it would silently trash data on updates.
3082 if ($insert_mode
3083 && $field['Key'] == 'PRI'
3084 && ($field['Type'] == 'char(36)' || $field['Type'] == 'varchar(36)')
3086 $default_function = $cfg['DefaultFunctions']['pk_char36'];
3088 // this is set only when appropriate and is always true
3089 if (isset($field['display_binary_as_hex'])) {
3090 $default_function = 'UNHEX';
3093 // Create the output
3094 $retval = ' <option></option>' . "\n";
3095 // loop on the dropdown array and print all available options for that field.
3096 foreach ($dropdown as $each_dropdown){
3097 $retval .= ' ';
3098 $retval .= '<option';
3099 if ($default_function === $each_dropdown) {
3100 $retval .= ' selected="selected"';
3102 $retval .= '>' . $each_dropdown . '</option>' . "\n";
3103 $dropdown_built[$each_dropdown] = 'true';
3104 $op_spacing_needed = true;
3106 // For compatibility's sake, do not let out all other functions. Instead
3107 // print a separator (blank) and then show ALL functions which weren't shown
3108 // yet.
3109 $cnt_functions = count($cfg['Functions']);
3110 for ($j = 0; $j < $cnt_functions; $j++) {
3111 if (! isset($dropdown_built[$cfg['Functions'][$j]]) || $dropdown_built[$cfg['Functions'][$j]] != 'true') {
3112 // Is current function defined as default?
3113 $selected = ($field['first_timestamp'] && $cfg['Functions'][$j] == $cfg['DefaultFunctions']['first_timestamp'])
3114 || (!$field['first_timestamp'] && $cfg['Functions'][$j] == $default_function)
3115 ? ' selected="selected"'
3116 : '';
3117 if ($op_spacing_needed == true) {
3118 $retval .= ' ';
3119 $retval .= '<option value="">--------</option>' . "\n";
3120 $op_spacing_needed = false;
3123 $retval .= ' ';
3124 $retval .= '<option' . $selected . '>' . $cfg['Functions'][$j] . '</option>' . "\n";
3126 } // end for
3128 return $retval;
3129 } // end PMA_getFunctionsForField()
3132 * Checks if the current user has a specific privilege and returns true if the
3133 * user indeed has that privilege or false if (s)he doesn't. This function must
3134 * only be used for features that are available since MySQL 5, because it
3135 * relies on the INFORMATION_SCHEMA database to be present.
3137 * Example: PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
3138 * // Checks if the currently logged in user has the global
3139 * // 'CREATE ROUTINE' privilege or, if not, checks if the
3140 * // user has this privilege on database 'mydb'.
3143 * @param string $priv The privilege to check
3144 * @param mixed $db null, to only check global privileges
3145 * string, db name where to also check for privileges
3146 * @param mixed $tbl null, to only check global privileges
3147 * string, db name where to also check for privileges
3148 * @return bool
3150 function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
3152 // Get the username for the current user in the format
3153 // required to use in the information schema database.
3154 $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
3155 if ($user === false) {
3156 return false;
3158 $user = explode('@', $user);
3159 $username = "''";
3160 $username .= str_replace("'", "''", $user[0]);
3161 $username .= "''@''";
3162 $username .= str_replace("'", "''", $user[1]);
3163 $username .= "''";
3164 // Prepage the query
3165 $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` "
3166 . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
3167 // Check global privileges first.
3168 if (PMA_DBI_fetch_value(sprintf($query,
3169 'USER_PRIVILEGES',
3170 $username,
3171 $priv))) {
3172 return true;
3174 // If a database name was provided and user does not have the
3175 // required global privilege, try database-wise permissions.
3176 if ($db !== null) {
3177 $query .= " AND TABLE_SCHEMA='%s'";
3178 if (PMA_DBI_fetch_value(sprintf($query,
3179 'SCHEMA_PRIVILEGES',
3180 $username,
3181 $priv,
3182 PMA_sqlAddSlashes($db)))) {
3183 return true;
3185 } else {
3186 // There was no database name provided and the user
3187 // does not have the correct global privilege.
3188 return false;
3190 // If a table name was also provided and we still didn't
3191 // find any valid privileges, try table-wise privileges.
3192 if ($tbl !== null) {
3193 $query .= " AND TABLE_NAME='%s'";
3194 if ($retval = PMA_DBI_fetch_value(sprintf($query,
3195 'TABLE_PRIVILEGES',
3196 $username,
3197 $priv,
3198 PMA_sqlAddSlashes($db),
3199 PMA_sqlAddSlashes($tbl)))) {
3200 return true;
3203 // If we reached this point, the user does not
3204 // have even valid table-wise privileges.
3205 return false;