Translation update done using Pootle.
[phpmyadmin/sankalp_k.git] / libraries / common.lib.php
blob8be5c0e7e4f81a00601f44f64503cfcd14a1aece
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 * @uses function_exists()
13 * @uses bcpow()
14 * @uses gmp_pow()
15 * @uses gmp_strval()
16 * @uses pow()
17 * @param number $base
18 * @param number $exp
19 * @param string pow function use, or false for auto-detect
20 * @return mixed string or float
22 function PMA_pow($base, $exp, $use_function = false)
24 static $pow_function = null;
26 if (null == $pow_function) {
27 if (function_exists('bcpow')) {
28 // BCMath Arbitrary Precision Mathematics Function
29 $pow_function = 'bcpow';
30 } elseif (function_exists('gmp_pow')) {
31 // GMP Function
32 $pow_function = 'gmp_pow';
33 } else {
34 // PHP function
35 $pow_function = 'pow';
39 if (! $use_function) {
40 $use_function = $pow_function;
43 if ($exp < 0 && 'pow' != $use_function) {
44 return false;
46 switch ($use_function) {
47 case 'bcpow' :
48 // bcscale() needed for testing PMA_pow() with base values < 1
49 bcscale(10);
50 $pow = bcpow($base, $exp);
51 break;
52 case 'gmp_pow' :
53 $pow = gmp_strval(gmp_pow($base, $exp));
54 break;
55 case 'pow' :
56 $base = (float) $base;
57 $exp = (int) $exp;
58 $pow = pow($base, $exp);
59 break;
60 default:
61 $pow = $use_function($base, $exp);
64 return $pow;
67 /**
68 * string PMA_getIcon(string $icon)
70 * @uses $GLOBALS['pmaThemeImage']
71 * @uses $GLOBALS['cfg']['PropertiesIconic']
72 * @uses htmlspecialchars()
73 * @param string $icon name of icon file
74 * @param string $alternate alternate text
75 * @param boolean $container include in container
76 * @param boolean $$force_text whether to force alternate text to be displayed
77 * @return html img tag
79 function PMA_getIcon($icon, $alternate = '', $container = false, $force_text = false)
81 $include_icon = false;
82 $include_text = false;
83 $include_box = false;
84 $alternate = htmlspecialchars($alternate);
85 $button = '';
87 if ($GLOBALS['cfg']['PropertiesIconic']) {
88 $include_icon = true;
91 if ($force_text
92 || ! (true === $GLOBALS['cfg']['PropertiesIconic'])
93 || ! $include_icon) {
94 // $cfg['PropertiesIconic'] is false or both
95 // OR we have no $include_icon
96 $include_text = true;
99 if ($include_text && $include_icon && $container) {
100 // we have icon, text and request for container
101 $include_box = true;
104 // Always use a span (we rely on this in js/sql.js)
105 $button .= '<span class="nowrap">';
107 if ($include_icon) {
108 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
109 . ' title="' . $alternate . '" alt="' . $alternate . '"'
110 . ' class="icon" width="16" height="16" />';
113 if ($include_icon && $include_text) {
114 $button .= ' ';
117 if ($include_text) {
118 $button .= $alternate;
121 $button .= '</span>';
123 return $button;
127 * Displays the maximum size for an upload
129 * @uses PMA_formatByteDown()
130 * @uses sprintf()
131 * @param integer the size
133 * @return string the message
135 * @access public
137 function PMA_displayMaximumUploadSize($max_upload_size)
139 // I have to reduce the second parameter (sensitiveness) from 6 to 4
140 // to avoid weird results like 512 kKib
141 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
142 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
146 * Generates a hidden field which should indicate to the browser
147 * the maximum size for upload
149 * @param integer the size
151 * @return string the INPUT field
153 * @access public
155 function PMA_generateHiddenMaxFileSize($max_size)
157 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
161 * Add slashes before "'" and "\" characters so a value containing them can
162 * be used in a sql comparison.
164 * @uses str_replace()
165 * @param string the string to slash
166 * @param boolean whether the string will be used in a 'LIKE' clause
167 * (it then requires two more escaped sequences) or not
168 * @param boolean whether to treat cr/lfs as escape-worthy entities
169 * (converts \n to \\n, \r to \\r)
171 * @param boolean whether this function is used as part of the
172 * "Create PHP code" dialog
174 * @return string the slashed string
176 * @access public
178 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
180 if ($is_like) {
181 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
182 } else {
183 $a_string = str_replace('\\', '\\\\', $a_string);
186 if ($crlf) {
187 $a_string = str_replace("\n", '\n', $a_string);
188 $a_string = str_replace("\r", '\r', $a_string);
189 $a_string = str_replace("\t", '\t', $a_string);
192 if ($php_code) {
193 $a_string = str_replace('\'', '\\\'', $a_string);
194 } else {
195 $a_string = str_replace('\'', '\'\'', $a_string);
198 return $a_string;
199 } // end of the 'PMA_sqlAddslashes()' function
203 * Add slashes before "_" and "%" characters for using them in MySQL
204 * database, table and field names.
205 * Note: This function does not escape backslashes!
207 * @uses str_replace()
208 * @param string the string to escape
210 * @return string the escaped string
212 * @access public
214 function PMA_escape_mysql_wildcards($name)
216 $name = str_replace('_', '\\_', $name);
217 $name = str_replace('%', '\\%', $name);
219 return $name;
220 } // end of the 'PMA_escape_mysql_wildcards()' function
223 * removes slashes before "_" and "%" characters
224 * Note: This function does not unescape backslashes!
226 * @uses str_replace()
227 * @param string $name the string to escape
228 * @return string the escaped string
229 * @access public
231 function PMA_unescape_mysql_wildcards($name)
233 $name = str_replace('\\_', '_', $name);
234 $name = str_replace('\\%', '%', $name);
236 return $name;
237 } // end of the 'PMA_unescape_mysql_wildcards()' function
240 * removes quotes (',",`) from a quoted string
242 * checks if the sting is quoted and removes this quotes
244 * @uses str_replace()
245 * @uses substr()
246 * @param string $quoted_string string to remove quotes from
247 * @param string $quote type of quote to remove
248 * @return string unqoted string
250 function PMA_unQuote($quoted_string, $quote = null)
252 $quotes = array();
254 if (null === $quote) {
255 $quotes[] = '`';
256 $quotes[] = '"';
257 $quotes[] = "'";
258 } else {
259 $quotes[] = $quote;
262 foreach ($quotes as $quote) {
263 if (substr($quoted_string, 0, 1) === $quote
264 && substr($quoted_string, -1, 1) === $quote) {
265 $unquoted_string = substr($quoted_string, 1, -1);
266 // replace escaped quotes
267 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
268 return $unquoted_string;
272 return $quoted_string;
276 * format sql strings
278 * @todo move into PMA_Sql
279 * @uses PMA_SQP_isError()
280 * @uses PMA_SQP_formatHtml()
281 * @uses PMA_SQP_formatNone()
282 * @uses is_array()
283 * @param mixed pre-parsed SQL structure
285 * @return string the formatted sql
287 * @global array the configuration array
288 * @global boolean whether the current statement is a multiple one or not
290 * @access public
293 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
295 global $cfg;
297 // Check that we actually have a valid set of parsed data
298 // well, not quite
299 // first check for the SQL parser having hit an error
300 if (PMA_SQP_isError()) {
301 return htmlspecialchars($parsed_sql['raw']);
303 // then check for an array
304 if (!is_array($parsed_sql)) {
305 // We don't so just return the input directly
306 // This is intended to be used for when the SQL Parser is turned off
307 $formatted_sql = '<pre>' . "\n"
308 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
309 . '</pre>';
310 return $formatted_sql;
313 $formatted_sql = '';
315 switch ($cfg['SQP']['fmtType']) {
316 case 'none':
317 if ($unparsed_sql != '') {
318 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
319 } else {
320 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
322 break;
323 case 'html':
324 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
325 break;
326 case 'text':
327 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
328 break;
329 default:
330 break;
331 } // end switch
333 return $formatted_sql;
334 } // end of the "PMA_formatSql()" function
338 * Displays a link to the official MySQL documentation
340 * @uses $cfg['MySQLManualType']
341 * @uses $cfg['MySQLManualBase']
342 * @uses $cfg['ReplaceHelpImg']
343 * @uses $GLOBALS['pmaThemeImage']
344 * @uses PMA_MYSQL_INT_VERSION
345 * @uses strtolower()
346 * @uses str_replace()
347 * @param string chapter of "HTML, one page per chapter" documentation
348 * @param string contains name of page/anchor that is being linked
349 * @param bool whether to use big icon (like in left frame)
350 * @param string anchor to page part
352 * @return string the html link
354 * @access public
356 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
358 global $cfg;
360 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
361 return '';
364 // Fixup for newly used names:
365 $chapter = str_replace('_', '-', strtolower($chapter));
366 $link = str_replace('_', '-', strtolower($link));
368 switch ($cfg['MySQLManualType']) {
369 case 'chapters':
370 if (empty($chapter)) {
371 $chapter = 'index';
373 if (empty($anchor)) {
374 $anchor = $link;
376 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
377 break;
378 case 'big':
379 if (empty($anchor)) {
380 $anchor = $link;
382 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
383 break;
384 case 'searchable':
385 if (empty($link)) {
386 $link = 'index';
388 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
389 if (!empty($anchor)) {
390 $url .= '#' . $anchor;
392 break;
393 case 'viewable':
394 default:
395 if (empty($link)) {
396 $link = 'index';
398 $mysql = '5.0';
399 $lang = 'en';
400 if (defined('PMA_MYSQL_INT_VERSION')) {
401 if (PMA_MYSQL_INT_VERSION >= 50500) {
402 $mysql = '5.5';
403 /* l10n: Language to use for MySQL 5.5 documentation, please use only languages which do exist in official documentation. */
404 $lang = _pgettext('MySQL 5.5 documentation language', 'en');
405 } else if (PMA_MYSQL_INT_VERSION >= 50100) {
406 $mysql = '5.1';
407 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
408 $lang = _pgettext('MySQL 5.1 documentation language', 'en');
409 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
410 $mysql = '5.0';
411 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
412 $lang = _pgettext('MySQL 5.0 documentation language', 'en');
415 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
416 if (!empty($anchor)) {
417 $url .= '#' . $anchor;
419 break;
422 if ($just_open) {
423 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
424 } elseif ($big_icon) {
425 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
426 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
427 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
428 } else {
429 return '[<a href="' . PMA_linkURL($url) . '" target="mysql_doc">' . __('Documentation') . '</a>]';
431 } // end of the 'PMA_showMySQLDocu()' function
435 * Displays a link to the phpMyAdmin documentation
437 * @param string anchor in documentation
439 * @return string the html link
441 * @access public
443 function PMA_showDocu($anchor) {
444 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
445 return '<a href="Documentation.html#' . $anchor . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
446 } else {
447 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
449 } // end of the 'PMA_showDocu()' function
452 * Displays a link to the PHP documentation
454 * @param string anchor in documentation
456 * @return string the html link
458 * @access public
460 function PMA_showPHPDocu($target) {
461 $url = PMA_getPHPDocLink($target);
463 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
464 return '<a href="' . $url . '" target="documentation"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . __('Documentation') . '" title="' . __('Documentation') . '" /></a>';
465 } else {
466 return '[<a href="' . $url . '" target="documentation">' . __('Documentation') . '</a>]';
468 } // end of the 'PMA_showPHPDocu()' function
471 * returns HTML for a footnote marker and add the messsage to the footnotes
473 * @uses $GLOBALS['footnotes']
474 * @param string the error message
475 * @return string html code for a footnote marker
476 * @access public
478 function PMA_showHint($message, $bbcode = false, $type = 'notice')
480 if ($message instanceof PMA_Message) {
481 $key = $message->getHash();
482 $type = $message->getLevel();
483 } else {
484 $key = md5($message);
487 if (! isset($GLOBALS['footnotes'][$key])) {
488 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
489 $GLOBALS['footnotes'] = array();
491 $nr = count($GLOBALS['footnotes']) + 1;
492 // this is the first instance of this message
493 $instance = 1;
494 $GLOBALS['footnotes'][$key] = array(
495 'note' => $message,
496 'type' => $type,
497 'nr' => $nr,
498 'instance' => $instance
500 } else {
501 $nr = $GLOBALS['footnotes'][$key]['nr'];
502 // another instance of this message (to ensure ids are unique)
503 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
506 if ($bbcode) {
507 return '[sup]' . $nr . '[/sup]';
510 // footnotemarker used in js/tooltip.js
511 return '<sup class="footnotemarker">' . $nr . '</sup>' .
512 '<img class="footnotemarker" id="footnote_' . $nr . '_' . $instance . '" src="' .
513 $GLOBALS['pmaThemeImage'] . 'b_help.png" alt="" />';
517 * Displays a MySQL error message in the right frame.
519 * @uses footer.inc.php
520 * @uses header.inc.php
521 * @uses $GLOBALS['sql_query']
522 * @uses $GLOBALS['pmaThemeImage']
523 * @uses $GLOBALS['cfg']['PropertiesIconic']
524 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
525 * @uses PMA_backquote()
526 * @uses PMA_DBI_getError()
527 * @uses PMA_formatSql()
528 * @uses PMA_generate_common_hidden_inputs()
529 * @uses PMA_generate_common_url()
530 * @uses PMA_showMySQLDocu()
531 * @uses PMA_sqlAddslashes()
532 * @uses PMA_SQP_isError()
533 * @uses PMA_SQP_parse()
534 * @uses PMA_SQP_getErrorString()
535 * @uses strtolower()
536 * @uses urlencode()
537 * @uses str_replace()
538 * @uses nl2br()
539 * @uses substr()
540 * @uses preg_replace()
541 * @uses preg_match()
542 * @uses explode()
543 * @uses implode()
544 * @uses is_array()
545 * @uses function_exists()
546 * @uses htmlspecialchars()
547 * @uses trim()
548 * @uses strstr()
549 * @param string the error message
550 * @param string the sql query that failed
551 * @param boolean whether to show a "modify" link or not
552 * @param string the "back" link url (full path is not required)
553 * @param boolean EXIT the page?
555 * @global string the curent table
556 * @global string the current db
558 * @access public
560 function PMA_mysqlDie($error_message = '', $the_query = '',
561 $is_modify_link = true, $back_url = '', $exit = true)
563 global $table, $db;
566 * start http output, display html headers
568 require_once './libraries/header.inc.php';
570 $error_msg_output = '';
572 if (!$error_message) {
573 $error_message = PMA_DBI_getError();
575 if (!$the_query && !empty($GLOBALS['sql_query'])) {
576 $the_query = $GLOBALS['sql_query'];
579 // --- Added to solve bug #641765
580 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
581 $formatted_sql = htmlspecialchars($the_query);
582 } elseif (empty($the_query) || trim($the_query) == '') {
583 $formatted_sql = '';
584 } else {
585 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
586 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
587 } else {
588 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
591 // ---
592 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
593 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
594 // if the config password is wrong, or the MySQL server does not
595 // respond, do not show the query that would reveal the
596 // username/password
597 if (!empty($the_query) && !strstr($the_query, 'connect')) {
598 // --- Added to solve bug #641765
599 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
600 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
601 $error_msg_output .= '<br />' . "\n";
603 // ---
604 // modified to show the help on sql errors
605 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
606 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
607 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
609 if ($is_modify_link) {
610 $_url_params = array(
611 'sql_query' => $the_query,
612 'show_query' => 1,
614 if (strlen($table)) {
615 $_url_params['db'] = $db;
616 $_url_params['table'] = $table;
617 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
618 } elseif (strlen($db)) {
619 $_url_params['db'] = $db;
620 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
621 } else {
622 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
625 $error_msg_output .= $doedit_goto
626 . PMA_getIcon('b_edit.png', __('Edit'))
627 . '</a>';
628 } // end if
629 $error_msg_output .= ' </p>' . "\n"
630 .' <p>' . "\n"
631 .' ' . $formatted_sql . "\n"
632 .' </p>' . "\n";
633 } // end if
635 if (!empty($error_message)) {
636 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
638 // modified to show the help on error-returns
639 // (now error-messages-server)
640 $error_msg_output .= '<p>' . "\n"
641 . ' <strong>' . __('MySQL said: ') . '</strong>'
642 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
643 . "\n"
644 . '</p>' . "\n";
646 // The error message will be displayed within a CODE segment.
647 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
649 // Replace all non-single blanks with their HTML-counterpart
650 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
651 // Replace TAB-characters with their HTML-counterpart
652 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
653 // Replace linebreaks
654 $error_message = nl2br($error_message);
656 $error_msg_output .= '<code>' . "\n"
657 . $error_message . "\n"
658 . '</code><br />' . "\n";
659 $error_msg_output .= '</div>';
661 $_SESSION['Import_message']['message'] = $error_msg_output;
663 if ($exit) {
665 * If in an Ajax request
666 * - avoid displaying a Back link
667 * - use PMA_ajaxResponse() to transmit the message and exit
669 if($GLOBALS['is_ajax_request'] == true) {
670 PMA_ajaxResponse($error_msg_output, false);
672 if (! empty($back_url)) {
673 if (strstr($back_url, '?')) {
674 $back_url .= '&amp;no_history=true';
675 } else {
676 $back_url .= '?no_history=true';
679 $_SESSION['Import_message']['go_back_url'] = $back_url;
681 $error_msg_output .= '<fieldset class="tblFooters">';
682 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
683 $error_msg_output .= '</fieldset>' . "\n\n";
686 echo $error_msg_output;
688 * display footer and exit
690 require './libraries/footer.inc.php';
691 } else {
692 echo $error_msg_output;
694 } // end of the 'PMA_mysqlDie()' function
697 * returns array with tables of given db with extended information and grouped
699 * @uses $cfg['LeftFrameTableSeparator']
700 * @uses $cfg['LeftFrameTableLevel']
701 * @uses $cfg['ShowTooltipAliasTB']
702 * @uses $cfg['NaturalOrder']
703 * @uses PMA_backquote()
704 * @uses count()
705 * @uses array_merge
706 * @uses uksort()
707 * @uses strstr()
708 * @uses explode()
709 * @param string $db name of db
710 * @param string $tables name of tables
711 * @param integer $limit_offset list offset
712 * @param integer $limit_count max tables to return
713 * return array (recursive) grouped table list
715 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
717 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
719 if (null === $tables) {
720 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
721 if ($GLOBALS['cfg']['NaturalOrder']) {
722 uksort($tables, 'strnatcasecmp');
726 if (count($tables) < 1) {
727 return $tables;
730 $default = array(
731 'Name' => '',
732 'Rows' => 0,
733 'Comment' => '',
734 'disp_name' => '',
737 $table_groups = array();
739 // for blobstreaming - list of blobstreaming tables
741 // load PMA configuration
742 $PMA_Config = $GLOBALS['PMA_Config'];
744 foreach ($tables as $table_name => $table) {
745 // if BS tables exist
746 if (PMA_BS_IsHiddenTable($table_name)) {
747 continue;
750 // check for correct row count
751 if (null === $table['Rows']) {
752 // Do not check exact row count here,
753 // if row count is invalid possibly the table is defect
754 // and this would break left frame;
755 // but we can check row count if this is a view or the
756 // information_schema database
757 // since PMA_Table::countRecords() returns a limited row count
758 // in this case.
760 // set this because PMA_Table::countRecords() can use it
761 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
763 if ($tbl_is_view || 'information_schema' == $db) {
764 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
768 // in $group we save the reference to the place in $table_groups
769 // where to store the table info
770 if ($GLOBALS['cfg']['LeftFrameDBTree']
771 && $sep && strstr($table_name, $sep))
773 $parts = explode($sep, $table_name);
775 $group =& $table_groups;
776 $i = 0;
777 $group_name_full = '';
778 $parts_cnt = count($parts) - 1;
779 while ($i < $parts_cnt
780 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
781 $group_name = $parts[$i] . $sep;
782 $group_name_full .= $group_name;
784 if (!isset($group[$group_name])) {
785 $group[$group_name] = array();
786 $group[$group_name]['is' . $sep . 'group'] = true;
787 $group[$group_name]['tab' . $sep . 'count'] = 1;
788 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
789 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
790 $table = $group[$group_name];
791 $group[$group_name] = array();
792 $group[$group_name][$group_name] = $table;
793 unset($table);
794 $group[$group_name]['is' . $sep . 'group'] = true;
795 $group[$group_name]['tab' . $sep . 'count'] = 1;
796 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
797 } else {
798 $group[$group_name]['tab' . $sep . 'count']++;
800 $group =& $group[$group_name];
801 $i++;
803 } else {
804 if (!isset($table_groups[$table_name])) {
805 $table_groups[$table_name] = array();
807 $group =& $table_groups;
811 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
812 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
813 // switch tooltip and name
814 $table['Comment'] = $table['Name'];
815 $table['disp_name'] = $table['Comment'];
816 } else {
817 $table['disp_name'] = $table['Name'];
820 $group[$table_name] = array_merge($default, $table);
823 return $table_groups;
826 /* ----------------------- Set of misc functions ----------------------- */
830 * Adds backquotes on both sides of a database, table or field name.
831 * and escapes backquotes inside the name with another backquote
833 * example:
834 * <code>
835 * echo PMA_backquote('owner`s db'); // `owner``s db`
837 * </code>
839 * @uses PMA_backquote()
840 * @uses is_array()
841 * @uses strlen()
842 * @uses str_replace()
843 * @param mixed $a_name the database, table or field name to "backquote"
844 * or array of it
845 * @param boolean $do_it a flag to bypass this function (used by dump
846 * functions)
847 * @return mixed the "backquoted" database, table or field name if the
848 * current MySQL release is >= 3.23.6, the original one
849 * else
850 * @access public
852 function PMA_backquote($a_name, $do_it = true)
854 if (is_array($a_name)) {
855 foreach ($a_name as &$data) {
856 $data = PMA_backquote($data, $do_it);
858 return $a_name;
861 if (! $do_it) {
862 global $PMA_SQPdata_forbidden_word;
863 global $PMA_SQPdata_forbidden_word_cnt;
865 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
866 return $a_name;
870 // '0' is also empty for php :-(
871 if (strlen($a_name) && $a_name !== '*') {
872 return '`' . str_replace('`', '``', $a_name) . '`';
873 } else {
874 return $a_name;
876 } // end of the 'PMA_backquote()' function
880 * Defines the <CR><LF> value depending on the user OS.
882 * @uses PMA_USR_OS
883 * @return string the <CR><LF> value to use
885 * @access public
887 function PMA_whichCrlf()
889 $the_crlf = "\n";
891 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
892 // Win case
893 if (PMA_USR_OS == 'Win') {
894 $the_crlf = "\r\n";
896 // Others
897 else {
898 $the_crlf = "\n";
901 return $the_crlf;
902 } // end of the 'PMA_whichCrlf()' function
905 * Reloads navigation if needed.
907 * @param $jsonly prints out pure JavaScript
908 * @uses $GLOBALS['reload']
909 * @uses $GLOBALS['db']
910 * @uses PMA_generate_common_url()
911 * @global array configuration
913 * @access public
915 function PMA_reloadNavigation($jsonly=false)
917 global $cfg;
919 // Reloads the navigation frame via JavaScript if required
920 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
921 // one of the reasons for a reload is when a table is dropped
922 // in this case, get rid of the table limit offset, otherwise
923 // we have a problem when dropping a table on the last page
924 // and the offset becomes greater than the total number of tables
925 unset($_SESSION['tmp_user_values']['table_limit_offset']);
926 echo "\n";
927 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
928 if (!$jsonly)
929 echo '<script type="text/javascript">' . PHP_EOL;
931 //<![CDATA[
932 if (typeof(window.parent) != 'undefined'
933 && typeof(window.parent.frame_navigation) != 'undefined'
934 && window.parent.goTo) {
935 window.parent.goTo('<?php echo $reload_url; ?>');
937 //]]>
938 <?php
939 if (!$jsonly)
940 echo '</script>' . PHP_EOL;
942 unset($GLOBALS['reload']);
947 * displays the message and the query
948 * usually the message is the result of the query executed
950 * @param string $message the message to display
951 * @param string $sql_query the query to display
952 * @param string $type the type (level) of the message
953 * @param boolean $is_view is this a message after a VIEW operation?
954 * @global array the configuration array
955 * @uses $cfg
956 * @access public
958 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
961 * PMA_ajaxResponse uses this function to collect the string of HTML generated
962 * for showing the message. Use output buffering to collect it and return it
963 * in a string. In some special cases on sql.php, buffering has to be disabled
964 * and hence we check with $GLOBALS['buffer_message']
966 if( $GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message']) ) {
967 ob_start();
969 global $cfg;
971 if (null === $sql_query) {
972 if (! empty($GLOBALS['display_query'])) {
973 $sql_query = $GLOBALS['display_query'];
974 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
975 $sql_query = $GLOBALS['unparsed_sql'];
976 } elseif (! empty($GLOBALS['sql_query'])) {
977 $sql_query = $GLOBALS['sql_query'];
978 } else {
979 $sql_query = '';
983 if (isset($GLOBALS['using_bookmark_message'])) {
984 $GLOBALS['using_bookmark_message']->display();
985 unset($GLOBALS['using_bookmark_message']);
988 // Corrects the tooltip text via JS if required
989 // @todo this is REALLY the wrong place to do this - very unexpected here
990 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
991 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
992 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
993 echo "\n";
994 echo '<script type="text/javascript">' . "\n";
995 echo '//<![CDATA[' . "\n";
996 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
997 echo '//]]>' . "\n";
998 echo '</script>' . "\n";
999 } // end if ... elseif
1001 // Checks if the table needs to be repaired after a TRUNCATE query.
1002 // @todo what about $GLOBALS['display_query']???
1003 // @todo this is REALLY the wrong place to do this - very unexpected here
1004 if (strlen($GLOBALS['table'])
1005 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1006 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
1007 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1010 unset($tbl_status);
1012 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
1013 // check for it's presence before using it
1014 echo '<div id="result_query" align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
1016 if ($message instanceof PMA_Message) {
1017 if (isset($GLOBALS['special_message'])) {
1018 $message->addMessage($GLOBALS['special_message']);
1019 unset($GLOBALS['special_message']);
1021 $message->display();
1022 $type = $message->getLevel();
1023 } else {
1024 echo '<div class="' . $type . '">';
1025 echo PMA_sanitize($message);
1026 if (isset($GLOBALS['special_message'])) {
1027 echo PMA_sanitize($GLOBALS['special_message']);
1028 unset($GLOBALS['special_message']);
1030 echo '</div>';
1033 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1034 // Html format the query to be displayed
1035 // If we want to show some sql code it is easiest to create it here
1036 /* SQL-Parser-Analyzer */
1038 if (! empty($GLOBALS['show_as_php'])) {
1039 $new_line = '\\n"<br />' . "\n"
1040 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1041 $query_base = htmlspecialchars(addslashes($sql_query));
1042 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1043 } else {
1044 $query_base = $sql_query;
1047 $query_too_big = false;
1049 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1050 // when the query is large (for example an INSERT of binary
1051 // data), the parser chokes; so avoid parsing the query
1052 $query_too_big = true;
1053 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1054 } elseif (! empty($GLOBALS['parsed_sql'])
1055 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1056 // (here, use "! empty" because when deleting a bookmark,
1057 // $GLOBALS['parsed_sql'] is set but empty
1058 $parsed_sql = $GLOBALS['parsed_sql'];
1059 } else {
1060 // Parse SQL if needed
1061 $parsed_sql = PMA_SQP_parse($query_base);
1062 if (PMA_SQP_isError()) {
1063 unset($parsed_sql);
1067 // Analyze it
1068 if (isset($parsed_sql)) {
1069 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1070 // Here we append the LIMIT added for navigation, to
1071 // enable its display. Adding it higher in the code
1072 // to $sql_query would create a problem when
1073 // using the Refresh or Edit links.
1075 // Only append it on SELECTs.
1078 * @todo what would be the best to do when someone hits Refresh:
1079 * use the current LIMITs ?
1082 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1083 && isset($GLOBALS['sql_limit_to_append'])) {
1084 $query_base = $analyzed_display_query[0]['section_before_limit']
1085 . "\n" . $GLOBALS['sql_limit_to_append']
1086 . $analyzed_display_query[0]['section_after_limit'];
1087 // Need to reparse query
1088 $parsed_sql = PMA_SQP_parse($query_base);
1092 if (! empty($GLOBALS['show_as_php'])) {
1093 $query_base = '$sql = "' . $query_base;
1094 } elseif (! empty($GLOBALS['validatequery'])) {
1095 try {
1096 $query_base = PMA_validateSQL($query_base);
1097 } catch (Exception $e) {
1098 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1100 } elseif (isset($parsed_sql)) {
1101 $query_base = PMA_formatSql($parsed_sql, $query_base);
1104 // Prepares links that may be displayed to edit/explain the query
1105 // (don't go to default pages, we must go to the page
1106 // where the query box is available)
1108 // Basic url query part
1109 $url_params = array();
1110 if (! isset($GLOBALS['db'])) {
1111 $GLOBALS['db'] = '';
1113 if (strlen($GLOBALS['db'])) {
1114 $url_params['db'] = $GLOBALS['db'];
1115 if (strlen($GLOBALS['table'])) {
1116 $url_params['table'] = $GLOBALS['table'];
1117 $edit_link = 'tbl_sql.php';
1118 } else {
1119 $edit_link = 'db_sql.php';
1121 } else {
1122 $edit_link = 'server_sql.php';
1125 // Want to have the query explained (Mike Beck 2002-05-22)
1126 // but only explain a SELECT (that has not been explained)
1127 /* SQL-Parser-Analyzer */
1128 $explain_link = '';
1129 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1130 $explain_params = $url_params;
1131 // Detect if we are validating as well
1132 // To preserve the validate uRL data
1133 if (! empty($GLOBALS['validatequery'])) {
1134 $explain_params['validatequery'] = 1;
1136 $is_select = false;
1137 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1138 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1139 $_message = __('Explain SQL');
1140 $is_select = true;
1141 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1142 $explain_params['sql_query'] = substr($sql_query, 8);
1143 $_message = __('Skip Explain SQL');
1145 if (isset($explain_params['sql_query'])) {
1146 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1147 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1149 } //show explain
1151 $url_params['sql_query'] = $sql_query;
1152 $url_params['show_query'] = 1;
1154 // even if the query is big and was truncated, offer the chance
1155 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1156 if (! empty($cfg['SQLQuery']['Edit'])) {
1157 if ($cfg['EditInWindow'] == true) {
1158 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1159 } else {
1160 $onclick = '';
1163 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1164 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1165 } else {
1166 $edit_link = '';
1169 $url_qpart = PMA_generate_common_url($url_params);
1171 // Also we would like to get the SQL formed in some nice
1172 // php-code (Mike Beck 2002-05-22)
1173 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1174 $php_params = $url_params;
1176 if (! empty($GLOBALS['show_as_php'])) {
1177 $_message = __('Without PHP Code');
1178 } else {
1179 $php_params['show_as_php'] = 1;
1180 $_message = __('Create PHP Code');
1183 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1184 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1186 if (isset($GLOBALS['show_as_php'])) {
1187 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1188 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1190 } else {
1191 $php_link = '';
1192 } //show as php
1194 // Refresh query
1195 if (! empty($cfg['SQLQuery']['Refresh'])
1196 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1197 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1198 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1199 } else {
1200 $refresh_link = '';
1201 } //show as php
1203 if (! empty($cfg['SQLValidator']['use'])
1204 && ! empty($cfg['SQLQuery']['Validate'])) {
1205 $validate_params = $url_params;
1206 if (!empty($GLOBALS['validatequery'])) {
1207 $validate_message = __('Skip Validate SQL') ;
1208 } else {
1209 $validate_params['validatequery'] = 1;
1210 $validate_message = __('Validate SQL') ;
1213 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1214 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1215 } else {
1216 $validate_link = '';
1217 } //validator
1219 if (!empty($GLOBALS['validatequery'])) {
1220 echo '<div class="sqlvalidate">';
1221 } else {
1222 echo '<code class="sql">';
1224 if ($query_too_big) {
1225 echo $shortened_query_base;
1226 } else {
1227 echo $query_base;
1230 //Clean up the end of the PHP
1231 if (! empty($GLOBALS['show_as_php'])) {
1232 echo '";';
1234 if (!empty($GLOBALS['validatequery'])) {
1235 echo '</div>';
1236 } else {
1237 echo '</code>';
1240 echo '<div class="tools">';
1241 // avoid displaying a Profiling checkbox that could
1242 // be checked, which would reexecute an INSERT, for example
1243 if (! empty($refresh_link)) {
1244 PMA_profilingCheckbox($sql_query);
1246 // if needed, generate an invisible form that contains controls for the
1247 // Inline link; this way, the behavior of the Inline link does not
1248 // depend on the profiling support or on the refresh link
1249 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1250 echo '<form action="sql.php" method="post">';
1251 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1252 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1253 echo '</form>';
1256 // in the tools div, only display the Inline link when not in ajax
1257 // mode because 1) it currently does not work and 2) we would
1258 // have two similar mechanisms on the page for the same goal
1259 if ($is_select || $GLOBALS['is_ajax_request'] === false) {
1260 // see in js/functions.js the jQuery code attached to id inline_edit
1261 // document.write conflicts with jQuery, hence used $().append()
1262 echo "<script type=\"text/javascript\">\n" .
1263 "//<![CDATA[\n" .
1264 "$('.tools form').after('[<a href=\"#\" title=\"" .
1265 PMA_escapeJsString(__('Inline edit of this query')) .
1266 "\" id=\"inline_edit\">" .
1267 PMA_escapeJsString(__('Inline')) .
1268 "</a>]');\n" .
1269 "//]]>\n" .
1270 "</script>";
1272 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1273 echo '</div>';
1275 echo '</div>';
1276 if ($GLOBALS['is_ajax_request'] === false) {
1277 echo '<br class="clearfloat" />';
1280 // If we are in an Ajax request, we have most probably been called in
1281 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1282 // to PMA_ajaxResponse(), which will encode it for JSON.
1283 if( $GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message']) ) {
1284 $buffer_contents = ob_get_contents();
1285 ob_end_clean();
1286 return $buffer_contents;
1288 } // end of the 'PMA_showMessage()' function
1291 * Verifies if current MySQL server supports profiling
1293 * @uses $_SESSION['profiling_supported'] for caching
1294 * @uses $GLOBALS['server']
1295 * @uses PMA_DBI_fetch_value()
1296 * @uses PMA_MYSQL_INT_VERSION
1297 * @uses defined()
1298 * @access public
1299 * @return boolean whether profiling is supported
1302 function PMA_profilingSupported()
1304 if (! PMA_cacheExists('profiling_supported', true)) {
1305 // 5.0.37 has profiling but for example, 5.1.20 does not
1306 // (avoid a trip to the server for MySQL before 5.0.37)
1307 // and do not set a constant as we might be switching servers
1308 if (defined('PMA_MYSQL_INT_VERSION')
1309 && PMA_MYSQL_INT_VERSION >= 50037
1310 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1311 PMA_cacheSet('profiling_supported', true, true);
1312 } else {
1313 PMA_cacheSet('profiling_supported', false, true);
1317 return PMA_cacheGet('profiling_supported', true);
1321 * Displays a form with the Profiling checkbox
1323 * @param string $sql_query
1324 * @access public
1327 function PMA_profilingCheckbox($sql_query)
1329 if (PMA_profilingSupported()) {
1330 echo '<form action="sql.php" method="post">' . "\n";
1331 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1332 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1333 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1334 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1335 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1336 echo '</form>' . "\n";
1341 * Displays the results of SHOW PROFILE
1343 * @param array the results
1344 * @param boolean show chart
1345 * @access public
1348 function PMA_profilingResults($profiling_results, $show_chart = false)
1350 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1351 echo '<div style="float: left;">';
1352 echo '<table>' . "\n";
1353 echo ' <tr>' . "\n";
1354 echo ' <th>' . __('Status') . '</th>' . "\n";
1355 echo ' <th>' . __('Time') . '</th>' . "\n";
1356 echo ' </tr>' . "\n";
1358 foreach($profiling_results as $one_result) {
1359 echo ' <tr>' . "\n";
1360 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1361 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1364 echo '</table>' . "\n";
1365 echo '</div>';
1367 if ($show_chart) {
1368 require_once './libraries/chart.lib.php';
1369 echo '<div style="float: left;">';
1370 PMA_chart_profiling($profiling_results);
1371 echo '</div>';
1374 echo '</fieldset>' . "\n";
1378 * Formats $value to byte view
1380 * @param double the value to format
1381 * @param integer the sensitiveness
1382 * @param integer the number of decimals to retain
1384 * @return array the formatted value and its unit
1386 * @access public
1388 * @version 1.2 - 18 July 2002
1390 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1392 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1393 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1395 $dh = PMA_pow(10, $comma);
1396 $li = PMA_pow(10, $limes);
1397 $return_value = $value;
1398 $unit = $byteUnits[0];
1400 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1401 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1402 // use 1024.0 to avoid integer overflow on 64-bit machines
1403 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1404 $unit = $byteUnits[$d];
1405 break 1;
1406 } // end if
1407 } // end for
1409 if ($unit != $byteUnits[0]) {
1410 // if the unit is not bytes (as represented in current language)
1411 // reformat with max length of 5
1412 // 4th parameter=true means do not reformat if value < 1
1413 $return_value = PMA_formatNumber($value, 5, $comma, true);
1414 } else {
1415 // do not reformat, just handle the locale
1416 $return_value = PMA_formatNumber($value, 0);
1419 return array(trim($return_value), $unit);
1420 } // end of the 'PMA_formatByteDown' function
1423 * Changes thousands and decimal separators to locale specific values.
1425 function PMA_localizeNumber($value)
1427 return str_replace(
1428 array(',', '.'),
1429 array(
1430 /* l10n: Thousands separator */
1431 __(','),
1432 /* l10n: Decimal separator */
1433 __('.'),
1435 $value);
1439 * Formats $value to the given length and appends SI prefixes
1440 * $comma is not substracted from the length
1441 * with a $length of 0 no truncation occurs, number is only formated
1442 * to the current locale
1444 * examples:
1445 * <code>
1446 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1447 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1448 * echo PMA_formatNumber(-0.003, 6); // -3 m
1449 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1450 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1451 * echo PMA_formatNumber(0, 6); // 0
1453 * </code>
1454 * @param double $value the value to format
1455 * @param integer $length the max length
1456 * @param integer $comma the number of decimals to retain
1457 * @param boolean $only_down do not reformat numbers below 1
1459 * @return string the formatted value and its unit
1461 * @access public
1463 * @version 1.1.0 - 2005-10-27
1465 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1467 //number_format is not multibyte safe, str_replace is safe
1468 if ($length === 0) {
1469 return PMA_localizeNumber(number_format($value, $comma));
1472 // this units needs no translation, ISO
1473 $units = array(
1474 -8 => 'y',
1475 -7 => 'z',
1476 -6 => 'a',
1477 -5 => 'f',
1478 -4 => 'p',
1479 -3 => 'n',
1480 -2 => '&micro;',
1481 -1 => 'm',
1482 0 => ' ',
1483 1 => 'k',
1484 2 => 'M',
1485 3 => 'G',
1486 4 => 'T',
1487 5 => 'P',
1488 6 => 'E',
1489 7 => 'Z',
1490 8 => 'Y'
1493 // we need at least 3 digits to be displayed
1494 if (3 > $length + $comma) {
1495 $length = 3 - $comma;
1498 // check for negative value to retain sign
1499 if ($value < 0) {
1500 $sign = '-';
1501 $value = abs($value);
1502 } else {
1503 $sign = '';
1506 $dh = PMA_pow(10, $comma);
1507 $li = PMA_pow(10, $length);
1508 $unit = $units[0];
1510 if ($value >= 1) {
1511 for ($d = 8; $d >= 0; $d--) {
1512 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1513 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1514 $unit = $units[$d];
1515 break 1;
1516 } // end if
1517 } // end for
1518 } elseif (!$only_down && (float) $value !== 0.0) {
1519 for ($d = -8; $d <= 8; $d++) {
1520 // force using pow() because of the negative exponent
1521 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1522 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1523 $unit = $units[$d];
1524 break 1;
1525 } // end if
1526 } // end for
1527 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1529 //number_format is not multibyte safe, str_replace is safe
1530 $value = PMA_localizeNumber(number_format($value, $comma));
1532 return $sign . $value . ' ' . $unit;
1533 } // end of the 'PMA_formatNumber' function
1536 * Returns the number of bytes when a formatted size is given
1538 * @param string $size the size expression (for example 8MB)
1539 * @uses PMA_pow()
1540 * @return integer The numerical part of the expression (for example 8)
1542 function PMA_extractValueFromFormattedSize($formatted_size)
1544 $return_value = -1;
1546 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1547 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1548 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1549 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1550 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1551 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1553 return $return_value;
1554 }// end of the 'PMA_extractValueFromFormattedSize' function
1557 * Writes localised date
1559 * @param string the current timestamp
1561 * @return string the formatted date
1563 * @access public
1565 function PMA_localisedDate($timestamp = -1, $format = '')
1567 $month = array(
1568 /* l10n: Short month name */
1569 __('Jan'),
1570 /* l10n: Short month name */
1571 __('Feb'),
1572 /* l10n: Short month name */
1573 __('Mar'),
1574 /* l10n: Short month name */
1575 __('Apr'),
1576 /* l10n: Short month name */
1577 _pgettext('Short month name', 'May'),
1578 /* l10n: Short month name */
1579 __('Jun'),
1580 /* l10n: Short month name */
1581 __('Jul'),
1582 /* l10n: Short month name */
1583 __('Aug'),
1584 /* l10n: Short month name */
1585 __('Sep'),
1586 /* l10n: Short month name */
1587 __('Oct'),
1588 /* l10n: Short month name */
1589 __('Nov'),
1590 /* l10n: Short month name */
1591 __('Dec'));
1592 $day_of_week = array(
1593 /* l10n: Short week day name */
1594 __('Sun'),
1595 /* l10n: Short week day name */
1596 __('Mon'),
1597 /* l10n: Short week day name */
1598 __('Tue'),
1599 /* l10n: Short week day name */
1600 __('Wed'),
1601 /* l10n: Short week day name */
1602 __('Thu'),
1603 /* l10n: Short week day name */
1604 __('Fri'),
1605 /* l10n: Short week day name */
1606 __('Sat'));
1608 if ($format == '') {
1609 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1610 $format = __('%B %d, %Y at %I:%M %p');
1613 if ($timestamp == -1) {
1614 $timestamp = time();
1617 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1618 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1620 return strftime($date, $timestamp);
1621 } // end of the 'PMA_localisedDate()' function
1625 * returns a tab for tabbed navigation.
1626 * If the variables $link and $args ar left empty, an inactive tab is created
1628 * @uses $GLOBALS['PMA_PHP_SELF']
1629 * @uses $GLOBALS['active_page']
1630 * @uses $GLOBALS['url_query']
1631 * @uses $cfg['MainPageIconic']
1632 * @uses $GLOBALS['pmaThemeImage']
1633 * @uses PMA_generate_common_url()
1634 * @uses E_USER_NOTICE
1635 * @uses htmlentities()
1636 * @uses urlencode()
1637 * @uses sprintf()
1638 * @uses trigger_error()
1639 * @uses array_merge()
1640 * @uses basename()
1641 * @param array $tab array with all options
1642 * @param array $url_params
1643 * @return string html code for one tab, a link if valid otherwise a span
1644 * @access public
1646 function PMA_generate_html_tab($tab, $url_params = array())
1648 // default values
1649 $defaults = array(
1650 'text' => '',
1651 'class' => '',
1652 'active' => null,
1653 'link' => '',
1654 'sep' => '?',
1655 'attr' => '',
1656 'args' => '',
1657 'warning' => '',
1658 'fragment' => '',
1659 'id' => '',
1662 $tab = array_merge($defaults, $tab);
1664 // determine additionnal style-class
1665 if (empty($tab['class'])) {
1666 if (! empty($tab['active'])
1667 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1668 $tab['class'] = 'active';
1669 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1670 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1671 && empty($tab['warning'])) {
1672 $tab['class'] = 'active';
1676 if (!empty($tab['warning'])) {
1677 $tab['class'] .= ' warning';
1678 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1681 // If there are any tab specific URL parameters, merge those with the general URL parameters
1682 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1683 $url_params = array_merge($url_params, $tab['url_params']);
1686 // build the link
1687 if (!empty($tab['link'])) {
1688 $tab['link'] = htmlentities($tab['link']);
1689 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1690 if (! empty($tab['args'])) {
1691 foreach ($tab['args'] as $param => $value) {
1692 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1693 . urlencode($value);
1698 if (! empty($tab['fragment'])) {
1699 $tab['link'] .= $tab['fragment'];
1702 // display icon, even if iconic is disabled but the link-text is missing
1703 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1704 && isset($tab['icon'])) {
1705 // avoid generating an alt tag, because it only illustrates
1706 // the text that follows and if browser does not display
1707 // images, the text is duplicated
1708 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1709 .'%1$s" width="16" height="16" alt="" />%2$s';
1710 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1712 // check to not display an empty link-text
1713 elseif (empty($tab['text'])) {
1714 $tab['text'] = '?';
1715 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1716 E_USER_NOTICE);
1719 //Set the id for the tab, if set in the params
1720 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1721 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1723 if (!empty($tab['link'])) {
1724 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1725 .$id_string
1726 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1727 . $tab['text'] . '</a>';
1728 } else {
1729 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1730 . $tab['text'] . '</span>';
1733 $out .= '</li>';
1734 return $out;
1735 } // end of the 'PMA_generate_html_tab()' function
1738 * returns html-code for a tab navigation
1740 * @uses PMA_generate_html_tab()
1741 * @uses htmlentities()
1742 * @param array $tabs one element per tab
1743 * @param string $url_params
1744 * @return string html-code for tab-navigation
1746 function PMA_generate_html_tabs($tabs, $url_params)
1748 $tag_id = 'topmenu';
1749 $tab_navigation =
1750 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1751 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1753 foreach ($tabs as $tab) {
1754 $tab_navigation .= PMA_generate_html_tab($tab, $url_params);
1757 $tab_navigation .=
1758 '</ul>' . "\n"
1759 .'<div class="clearfloat"></div>'
1760 .'</div>' . "\n";
1762 return $tab_navigation;
1767 * Displays a link, or a button if the link's URL is too large, to
1768 * accommodate some browsers' limitations
1770 * @param string the URL
1771 * @param string the link message
1772 * @param mixed $tag_params string: js confirmation
1773 * array: additional tag params (f.e. style="")
1774 * @param boolean $new_form we set this to false when we are already in
1775 * a form, to avoid generating nested forms
1777 * @return string the results to be echoed or saved in an array
1779 function PMA_linkOrButton($url, $message, $tag_params = array(),
1780 $new_form = true, $strip_img = false, $target = '')
1782 $url_length = strlen($url);
1783 // with this we should be able to catch case of image upload
1784 // into a (MEDIUM) BLOB; not worth generating even a form for these
1785 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1786 return '';
1789 if (! is_array($tag_params)) {
1790 $tmp = $tag_params;
1791 $tag_params = array();
1792 if (!empty($tmp)) {
1793 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1795 unset($tmp);
1797 if (! empty($target)) {
1798 $tag_params['target'] = htmlentities($target);
1801 $tag_params_strings = array();
1802 foreach ($tag_params as $par_name => $par_value) {
1803 // htmlspecialchars() only on non javascript
1804 $par_value = substr($par_name, 0, 2) == 'on'
1805 ? $par_value
1806 : htmlspecialchars($par_value);
1807 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1810 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1811 // no whitespace within an <a> else Safari will make it part of the link
1812 $ret = "\n" . '<a href="' . $url . '" '
1813 . implode(' ', $tag_params_strings) . '>'
1814 . $message . '</a>' . "\n";
1815 } else {
1816 // no spaces (linebreaks) at all
1817 // or after the hidden fields
1818 // IE will display them all
1820 // add class=link to submit button
1821 if (empty($tag_params['class'])) {
1822 $tag_params['class'] = 'link';
1825 // decode encoded url separators
1826 $separator = PMA_get_arg_separator();
1827 // on most places separator is still hard coded ...
1828 if ($separator !== '&') {
1829 // ... so always replace & with $separator
1830 $url = str_replace(htmlentities('&'), $separator, $url);
1831 $url = str_replace('&', $separator, $url);
1833 $url = str_replace(htmlentities($separator), $separator, $url);
1834 // end decode
1836 $url_parts = parse_url($url);
1837 $query_parts = explode($separator, $url_parts['query']);
1838 if ($new_form) {
1839 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1840 . ' method="post"' . $target . ' style="display: inline;">';
1841 $subname_open = '';
1842 $subname_close = '';
1843 $submit_name = '';
1844 } else {
1845 $query_parts[] = 'redirect=' . $url_parts['path'];
1846 if (empty($GLOBALS['subform_counter'])) {
1847 $GLOBALS['subform_counter'] = 0;
1849 $GLOBALS['subform_counter']++;
1850 $ret = '';
1851 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1852 $subname_close = ']';
1853 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1855 foreach ($query_parts as $query_pair) {
1856 list($eachvar, $eachval) = explode('=', $query_pair);
1857 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1858 . $subname_close . '" value="'
1859 . htmlspecialchars(urldecode($eachval)) . '" />';
1860 } // end while
1862 if (stristr($message, '<img')) {
1863 if ($strip_img) {
1864 $message = trim(strip_tags($message));
1865 $ret .= '<input type="submit"' . $submit_name . ' '
1866 . implode(' ', $tag_params_strings)
1867 . ' value="' . htmlspecialchars($message) . '" />';
1868 } else {
1869 $displayed_message = htmlspecialchars(
1870 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1871 $message));
1872 $ret .= '<input type="image"' . $submit_name . ' '
1873 . implode(' ', $tag_params_strings)
1874 . ' src="' . preg_replace(
1875 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1876 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1877 // Here we cannot obey PropertiesIconic completely as a
1878 // generated link would have a length over LinkLengthLimit
1879 // but we can at least show the message.
1880 // If PropertiesIconic is false or 'both'
1881 if ($GLOBALS['cfg']['PropertiesIconic'] !== true) {
1882 $ret .= ' <span class="clickprevimage">' . $displayed_message . '</span>';
1885 } else {
1886 $message = trim(strip_tags($message));
1887 $ret .= '<input type="submit"' . $submit_name . ' '
1888 . implode(' ', $tag_params_strings)
1889 . ' value="' . htmlspecialchars($message) . '" />';
1891 if ($new_form) {
1892 $ret .= '</form>';
1894 } // end if... else...
1896 return $ret;
1897 } // end of the 'PMA_linkOrButton()' function
1901 * Returns a given timespan value in a readable format.
1903 * @uses sprintf()
1904 * @uses floor()
1905 * @param int the timespan
1907 * @return string the formatted value
1909 function PMA_timespanFormat($seconds)
1911 $return_string = '';
1912 $days = floor($seconds / 86400);
1913 if ($days > 0) {
1914 $seconds -= $days * 86400;
1916 $hours = floor($seconds / 3600);
1917 if ($days > 0 || $hours > 0) {
1918 $seconds -= $hours * 3600;
1920 $minutes = floor($seconds / 60);
1921 if ($days > 0 || $hours > 0 || $minutes > 0) {
1922 $seconds -= $minutes * 60;
1924 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1928 * Takes a string and outputs each character on a line for itself. Used
1929 * mainly for horizontalflipped display mode.
1930 * Takes care of special html-characters.
1931 * Fulfills todo-item
1932 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1934 * @todo add a multibyte safe function PMA_STR_split()
1935 * @uses strlen
1936 * @param string The string
1937 * @param string The Separator (defaults to "<br />\n")
1939 * @access public
1940 * @return string The flipped string
1942 function PMA_flipstring($string, $Separator = "<br />\n")
1944 $format_string = '';
1945 $charbuff = false;
1947 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1948 $char = $string{$i};
1949 $append = false;
1951 if ($char == '&') {
1952 $format_string .= $charbuff;
1953 $charbuff = $char;
1954 } elseif ($char == ';' && !empty($charbuff)) {
1955 $format_string .= $charbuff . $char;
1956 $charbuff = false;
1957 $append = true;
1958 } elseif (! empty($charbuff)) {
1959 $charbuff .= $char;
1960 } else {
1961 $format_string .= $char;
1962 $append = true;
1965 // do not add separator after the last character
1966 if ($append && ($i != $str_len - 1)) {
1967 $format_string .= $Separator;
1971 return $format_string;
1976 * Function added to avoid path disclosures.
1977 * Called by each script that needs parameters, it displays
1978 * an error message and, by default, stops the execution.
1980 * Not sure we could use a strMissingParameter message here,
1981 * would have to check if the error message file is always available
1983 * @todo localize error message
1984 * @todo use PMA_fatalError() if $die === true?
1985 * @uses PMA_getenv()
1986 * @uses header_meta_style.inc.php
1987 * @uses $GLOBALS['PMA_PHP_SELF']
1988 * basename
1989 * @param array The names of the parameters needed by the calling
1990 * script.
1991 * @param boolean Stop the execution?
1992 * (Set this manually to false in the calling script
1993 * until you know all needed parameters to check).
1994 * @param boolean Whether to include this list in checking for special params.
1995 * @global string path to current script
1996 * @global boolean flag whether any special variable was required
1998 * @access public
2000 function PMA_checkParameters($params, $die = true, $request = true)
2002 global $checked_special;
2004 if (!isset($checked_special)) {
2005 $checked_special = false;
2008 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
2009 $found_error = false;
2010 $error_message = '';
2012 foreach ($params as $param) {
2013 if ($request && $param != 'db' && $param != 'table') {
2014 $checked_special = true;
2017 if (!isset($GLOBALS[$param])) {
2018 $error_message .= $reported_script_name
2019 . ': Missing parameter: ' . $param
2020 . PMA_showDocu('faqmissingparameters')
2021 . '<br />';
2022 $found_error = true;
2025 if ($found_error) {
2027 * display html meta tags
2029 require_once './libraries/header_meta_style.inc.php';
2030 echo '</head><body><p>' . $error_message . '</p></body></html>';
2031 if ($die) {
2032 exit();
2035 } // end function
2038 * Function to generate unique condition for specified row.
2040 * @uses $GLOBALS['analyzed_sql'][0]
2041 * @uses PMA_DBI_field_flags()
2042 * @uses PMA_backquote()
2043 * @uses PMA_sqlAddslashes()
2044 * @uses PMA_printable_bit_value()
2045 * @uses stristr()
2046 * @uses bin2hex()
2047 * @uses preg_replace()
2048 * @param resource $handle current query result
2049 * @param integer $fields_cnt number of fields
2050 * @param array $fields_meta meta information about fields
2051 * @param array $row current row
2052 * @param boolean $force_unique generate condition only on pk or unique
2054 * @access public
2055 * @return string the calculated condition and whether condition is unique
2057 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
2059 $primary_key = '';
2060 $unique_key = '';
2061 $nonprimary_condition = '';
2062 $preferred_condition = '';
2064 for ($i = 0; $i < $fields_cnt; ++$i) {
2065 $condition = '';
2066 $field_flags = PMA_DBI_field_flags($handle, $i);
2067 $meta = $fields_meta[$i];
2069 // do not use a column alias in a condition
2070 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2071 $meta->orgname = $meta->name;
2073 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2074 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2075 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2076 as $select_expr) {
2077 // need (string) === (string)
2078 // '' !== 0 but '' == 0
2079 if ((string) $select_expr['alias'] === (string) $meta->name) {
2080 $meta->orgname = $select_expr['column'];
2081 break;
2082 } // end if
2083 } // end foreach
2087 // Do not use a table alias in a condition.
2088 // Test case is:
2089 // select * from galerie x WHERE
2090 //(select count(*) from galerie y where y.datum=x.datum)>1
2092 // But orgtable is present only with mysqli extension so the
2093 // fix is only for mysqli.
2094 // Also, do not use the original table name if we are dealing with
2095 // a view because this view might be updatable.
2096 // (The isView() verification should not be costly in most cases
2097 // because there is some caching in the function).
2098 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
2099 $meta->table = $meta->orgtable;
2102 // to fix the bug where float fields (primary or not)
2103 // can't be matched because of the imprecision of
2104 // floating comparison, use CONCAT
2105 // (also, the syntax "CONCAT(field) IS NULL"
2106 // that we need on the next "if" will work)
2107 if ($meta->type == 'real') {
2108 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
2109 . PMA_backquote($meta->orgname) . ') ';
2110 } else {
2111 $condition = ' ' . PMA_backquote($meta->table) . '.'
2112 . PMA_backquote($meta->orgname) . ' ';
2113 } // end if... else...
2115 if (!isset($row[$i]) || is_null($row[$i])) {
2116 $condition .= 'IS NULL AND';
2117 } else {
2118 // timestamp is numeric on some MySQL 4.1
2119 // for real we use CONCAT above and it should compare to string
2120 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
2121 $condition .= '= ' . $row[$i] . ' AND';
2122 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2123 // hexify only if this is a true not empty BLOB or a BINARY
2124 && stristr($field_flags, 'BINARY')
2125 && !empty($row[$i])) {
2126 // do not waste memory building a too big condition
2127 if (strlen($row[$i]) < 1000) {
2128 // use a CAST if possible, to avoid problems
2129 // if the field contains wildcard characters % or _
2130 $condition .= '= CAST(0x' . bin2hex($row[$i])
2131 . ' AS BINARY) AND';
2132 } else {
2133 // this blob won't be part of the final condition
2134 $condition = '';
2136 } elseif ($meta->type == 'bit') {
2137 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2138 } else {
2139 $condition .= '= \''
2140 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2143 if ($meta->primary_key > 0) {
2144 $primary_key .= $condition;
2145 } elseif ($meta->unique_key > 0) {
2146 $unique_key .= $condition;
2148 $nonprimary_condition .= $condition;
2149 } // end for
2151 // Correction University of Virginia 19991216:
2152 // prefer primary or unique keys for condition,
2153 // but use conjunction of all values if no primary key
2154 $clause_is_unique = true;
2155 if ($primary_key) {
2156 $preferred_condition = $primary_key;
2157 } elseif ($unique_key) {
2158 $preferred_condition = $unique_key;
2159 } elseif (! $force_unique) {
2160 $preferred_condition = $nonprimary_condition;
2161 $clause_is_unique = false;
2164 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2165 return(array($where_clause, $clause_is_unique));
2166 } // end function
2169 * Generate a button or image tag
2171 * @uses PMA_USR_BROWSER_AGENT
2172 * @uses $GLOBALS['pmaThemeImage']
2173 * @uses $GLOBALS['cfg']['PropertiesIconic']
2174 * @param string name of button element
2175 * @param string class of button element
2176 * @param string name of image element
2177 * @param string text to display
2178 * @param string image to display
2180 * @access public
2182 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2183 $image, $value = '')
2185 if ($value == '') {
2186 $value = $text;
2188 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2189 echo ' <input type="submit" name="' . $button_name . '"'
2190 .' value="' . htmlspecialchars($value) . '"'
2191 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2192 return;
2195 /* Opera has trouble with <input type="image"> */
2196 /* IE has trouble with <button> */
2197 if (PMA_USR_BROWSER_AGENT != 'IE') {
2198 echo '<button class="' . $button_class . '" type="submit"'
2199 .' name="' . $button_name . '" value="' . htmlspecialchars($value) . '"'
2200 .' title="' . htmlspecialchars($text) . '">' . "\n"
2201 . PMA_getIcon($image, $text)
2202 .'</button>' . "\n";
2203 } else {
2204 echo '<input type="image" name="' . $image_name . '" value="'
2205 . htmlspecialchars($value) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2206 . $image . '" />'
2207 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2209 } // end function
2212 * Generate a pagination selector for browsing resultsets
2214 * @uses range()
2215 * @param string Number of rows in the pagination set
2216 * @param string current page number
2217 * @param string number of total pages
2218 * @param string If the number of pages is lower than this
2219 * variable, no pages will be omitted in
2220 * pagination
2221 * @param string How many rows at the beginning should always
2222 * be shown?
2223 * @param string How many rows at the end should always
2224 * be shown?
2225 * @param string Percentage of calculation page offsets to
2226 * hop to a next page
2227 * @param string Near the current page, how many pages should
2228 * be considered "nearby" and displayed as
2229 * well?
2230 * @param string The prompt to display (sometimes empty)
2232 * @access public
2234 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2235 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2236 $range = 10, $prompt = '')
2238 $increment = floor($nbTotalPage / $percent);
2239 $pageNowMinusRange = ($pageNow - $range);
2240 $pageNowPlusRange = ($pageNow + $range);
2242 $gotopage = $prompt . ' <select id="pageselector" ';
2243 if ($GLOBALS['cfg']['AjaxEnable']) {
2244 $gotopage .= ' class="ajax"';
2246 $gotopage .= ' name="pos" >' . "\n";
2247 if ($nbTotalPage < $showAll) {
2248 $pages = range(1, $nbTotalPage);
2249 } else {
2250 $pages = array();
2252 // Always show first X pages
2253 for ($i = 1; $i <= $sliceStart; $i++) {
2254 $pages[] = $i;
2257 // Always show last X pages
2258 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2259 $pages[] = $i;
2262 // Based on the number of results we add the specified
2263 // $percent percentage to each page number,
2264 // so that we have a representing page number every now and then to
2265 // immediately jump to specific pages.
2266 // As soon as we get near our currently chosen page ($pageNow -
2267 // $range), every page number will be shown.
2268 $i = $sliceStart;
2269 $x = $nbTotalPage - $sliceEnd;
2270 $met_boundary = false;
2271 while ($i <= $x) {
2272 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2273 // If our pageselector comes near the current page, we use 1
2274 // counter increments
2275 $i++;
2276 $met_boundary = true;
2277 } else {
2278 // We add the percentage increment to our current page to
2279 // hop to the next one in range
2280 $i += $increment;
2282 // Make sure that we do not cross our boundaries.
2283 if ($i > $pageNowMinusRange && ! $met_boundary) {
2284 $i = $pageNowMinusRange;
2288 if ($i > 0 && $i <= $x) {
2289 $pages[] = $i;
2293 // Since because of ellipsing of the current page some numbers may be double,
2294 // we unify our array:
2295 sort($pages);
2296 $pages = array_unique($pages);
2299 foreach ($pages as $i) {
2300 if ($i == $pageNow) {
2301 $selected = 'selected="selected" style="font-weight: bold"';
2302 } else {
2303 $selected = '';
2305 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2308 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2310 return $gotopage;
2311 } // end function
2315 * Generate navigation for a list
2317 * @todo use $pos from $_url_params
2318 * @uses range()
2319 * @param integer number of elements in the list
2320 * @param integer current position in the list
2321 * @param array url parameters
2322 * @param string script name for form target
2323 * @param string target frame
2324 * @param integer maximum number of elements to display from the list
2326 * @access public
2328 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2330 if ($max_count < $count) {
2331 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2332 echo __('Page number:');
2333 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2335 // Move to the beginning or to the previous page
2336 if ($pos > 0) {
2337 // patch #474210 - part 1
2338 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2339 $caption1 = '&lt;&lt;';
2340 $caption2 = ' &lt; ';
2341 $title1 = ' title="' . __('Begin') . '"';
2342 $title2 = ' title="' . __('Previous') . '"';
2343 } else {
2344 $caption1 = __('Begin') . ' &lt;&lt;';
2345 $caption2 = __('Previous') . ' &lt;';
2346 $title1 = '';
2347 $title2 = '';
2348 } // end if... else...
2349 $_url_params['pos'] = 0;
2350 echo '<a' . $title1 . ' href="' . $script
2351 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2352 . $caption1 . '</a>';
2353 $_url_params['pos'] = $pos - $max_count;
2354 echo '<a' . $title2 . ' href="' . $script
2355 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2356 . $caption2 . '</a>';
2359 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2360 echo PMA_generate_common_hidden_inputs($_url_params);
2361 echo PMA_pageselector(
2362 $max_count,
2363 floor(($pos + 1) / $max_count) + 1,
2364 ceil($count / $max_count));
2365 echo '</form>';
2367 if ($pos + $max_count < $count) {
2368 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2369 $caption3 = ' &gt; ';
2370 $caption4 = '&gt;&gt;';
2371 $title3 = ' title="' . __('Next') . '"';
2372 $title4 = ' title="' . __('End') . '"';
2373 } else {
2374 $caption3 = '&gt; ' . __('Next');
2375 $caption4 = '&gt;&gt; ' . __('End');
2376 $title3 = '';
2377 $title4 = '';
2378 } // end if... else...
2379 $_url_params['pos'] = $pos + $max_count;
2380 echo '<a' . $title3 . ' href="' . $script
2381 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2382 . $caption3 . '</a>';
2383 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2384 if ($_url_params['pos'] == $count) {
2385 $_url_params['pos'] = $count - $max_count;
2387 echo '<a' . $title4 . ' href="' . $script
2388 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2389 . $caption4 . '</a>';
2391 echo "\n";
2392 if ('frame_navigation' == $frame) {
2393 echo '</div>' . "\n";
2399 * replaces %u in given path with current user name
2401 * example:
2402 * <code>
2403 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2405 * </code>
2406 * @uses $cfg['Server']['user']
2407 * @uses substr()
2408 * @uses str_replace()
2409 * @param string $dir with wildcard for user
2410 * @return string per user directory
2412 function PMA_userDir($dir)
2414 // add trailing slash
2415 if (substr($dir, -1) != '/') {
2416 $dir .= '/';
2419 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2423 * returns html code for db link to default db page
2425 * @uses $cfg['DefaultTabDatabase']
2426 * @uses $GLOBALS['db']
2427 * @uses PMA_generate_common_url()
2428 * @uses PMA_unescape_mysql_wildcards()
2429 * @uses strlen()
2430 * @uses sprintf()
2431 * @uses htmlspecialchars()
2432 * @param string $database
2433 * @return string html link to default db page
2435 function PMA_getDbLink($database = null)
2437 if (!strlen($database)) {
2438 if (!strlen($GLOBALS['db'])) {
2439 return '';
2441 $database = $GLOBALS['db'];
2442 } else {
2443 $database = PMA_unescape_mysql_wildcards($database);
2446 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2447 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2448 .htmlspecialchars($database) . '</a>';
2452 * Displays a lightbulb hint explaining a known external bug
2453 * that affects a functionality
2455 * @uses PMA_MYSQL_INT_VERSION
2456 * @uses PMA_showHint()
2457 * @uses sprintf()
2458 * @param string $functionality localized message explaining the func.
2459 * @param string $component 'mysql' (eventually, 'php')
2460 * @param string $minimum_version of this component
2461 * @param string $bugref bug reference for this component
2463 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2465 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2466 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2471 * Generates and echoes an HTML checkbox
2473 * @param string $html_field_name the checkbox HTML field
2474 * @param string $label
2475 * @param boolean $checked is it initially checked?
2476 * @param boolean $onclick should it submit the form on click?
2478 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2480 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>';
2484 * Generates and echoes a set of radio HTML fields
2486 * @uses htmlspecialchars()
2487 * @param string $html_field_name the radio HTML field
2488 * @param array $choices the choices values and labels
2489 * @param string $checked_choice the choice to check by default
2490 * @param boolean $line_break whether to add an HTML line break after a choice
2491 * @param boolean $escape_label whether to use htmlspecialchars() on label
2492 * @param string $class enclose each choice with a div of this class
2494 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2495 foreach ($choices as $choice_value => $choice_label) {
2496 if (! empty($class)) {
2497 echo '<div class="' . $class . '">';
2499 $html_field_id = $html_field_name . '_' . $choice_value;
2500 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2501 if ($choice_value == $checked_choice) {
2502 echo ' checked="checked"';
2504 echo ' />' . "\n";
2505 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2506 if ($line_break) {
2507 echo '<br />';
2509 if (! empty($class)) {
2510 echo '</div>';
2512 echo "\n";
2517 * Generates and returns an HTML dropdown
2519 * @uses htmlspecialchars()
2520 * @param string $select_name
2521 * @param array $choices the choices values
2522 * @param string $active_choice the choice to select by default
2523 * @param string $id the id of the select element; can be different in case
2524 * the dropdown is present more than once on the page
2525 * @todo support titles
2527 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2529 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2530 foreach ($choices as $one_choice_value => $one_choice_label) {
2531 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2532 if ($one_choice_value == $active_choice) {
2533 $result .= ' selected="selected"';
2535 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2537 $result .= '</select>';
2538 return $result;
2542 * Generates a slider effect (jQjuery)
2543 * Takes care of generating the initial <div> and the link
2544 * controlling the slider; you have to generate the </div> yourself
2545 * after the sliding section.
2547 * @uses $GLOBALS['cfg']['InitialSlidersState']
2548 * @param string $id the id of the <div> on which to apply the effect
2549 * @param string $message the message to show as a link
2551 function PMA_generate_slider_effect($id, $message)
2553 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2554 echo '<div id="' . $id . '">';
2555 return;
2558 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2559 * opening the <div> with PHP itself instead of JavaScript.
2561 * @todo find a better solution that uses $.append(), the recommended method
2562 * maybe by using an additional param, the id of the div to append to
2565 <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); ?>">
2566 <?php
2570 * Clears cache content which needs to be refreshed on user change.
2572 function PMA_clearUserCache() {
2573 PMA_cacheUnset('is_superuser', true);
2577 * Verifies if something is cached in the session
2579 * @param string $var
2580 * @param scalar $server
2581 * @return boolean
2583 function PMA_cacheExists($var, $server = 0)
2585 if (true === $server) {
2586 $server = $GLOBALS['server'];
2588 return isset($_SESSION['cache']['server_' . $server][$var]);
2592 * Gets cached information from the session
2594 * @param string $var
2595 * @param scalar $server
2596 * @return mixed
2598 function PMA_cacheGet($var, $server = 0)
2600 if (true === $server) {
2601 $server = $GLOBALS['server'];
2603 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2604 return $_SESSION['cache']['server_' . $server][$var];
2605 } else {
2606 return null;
2611 * Caches information in the session
2613 * @param string $var
2614 * @param mixed $val
2615 * @param integer $server
2616 * @return mixed
2618 function PMA_cacheSet($var, $val = null, $server = 0)
2620 if (true === $server) {
2621 $server = $GLOBALS['server'];
2623 $_SESSION['cache']['server_' . $server][$var] = $val;
2627 * Removes cached information from the session
2629 * @param string $var
2630 * @param scalar $server
2632 function PMA_cacheUnset($var, $server = 0)
2634 if (true === $server) {
2635 $server = $GLOBALS['server'];
2637 unset($_SESSION['cache']['server_' . $server][$var]);
2641 * Converts a bit value to printable format;
2642 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2643 * function because in PHP, decbin() supports only 32 bits
2645 * @uses ceil()
2646 * @uses decbin()
2647 * @uses ord()
2648 * @uses substr()
2649 * @uses sprintf()
2650 * @param numeric $value coming from a BIT field
2651 * @param integer $length
2652 * @return string the printable value
2654 function PMA_printable_bit_value($value, $length) {
2655 $printable = '';
2656 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2657 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2659 $printable = substr($printable, -$length);
2660 return $printable;
2664 * Verifies whether the value contains a non-printable character
2666 * @uses preg_match()
2667 * @param string $value
2668 * @return boolean
2670 function PMA_contains_nonprintable_ascii($value) {
2671 return preg_match('@[^[:print:]]@', $value);
2675 * Converts a BIT type default value
2676 * for example, b'010' becomes 010
2678 * @uses strtr()
2679 * @param string $bit_default_value
2680 * @return string the converted value
2682 function PMA_convert_bit_default_value($bit_default_value) {
2683 return strtr($bit_default_value, array("b" => "", "'" => ""));
2687 * Extracts the various parts from a field type spec
2689 * @uses strpos()
2690 * @uses chop()
2691 * @uses substr()
2692 * @param string $fieldspec
2693 * @return array associative array containing type, spec_in_brackets
2694 * and possibly enum_set_values (another array)
2696 function PMA_extractFieldSpec($fieldspec) {
2697 $first_bracket_pos = strpos($fieldspec, '(');
2698 if ($first_bracket_pos) {
2699 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2700 // convert to lowercase just to be sure
2701 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2702 } else {
2703 $type = $fieldspec;
2704 $spec_in_brackets = '';
2707 if ('enum' == $type || 'set' == $type) {
2708 // Define our working vars
2709 $enum_set_values = array();
2710 $working = "";
2711 $in_string = false;
2712 $index = 0;
2714 // While there is another character to process
2715 while (isset($fieldspec[$index])) {
2716 // Grab the char to look at
2717 $char = $fieldspec[$index];
2719 // If it is a single quote, needs to be handled specially
2720 if ($char == "'") {
2721 // If we are not currently in a string, begin one
2722 if (! $in_string) {
2723 $in_string = true;
2724 $working = "";
2725 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2726 } else {
2727 // Check out the next character (if possible)
2728 $has_next = isset($fieldspec[$index + 1]);
2729 $next = $has_next ? $fieldspec[$index + 1] : null;
2731 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2732 if (! $has_next || $next != "'") {
2733 $enum_set_values[] = $working;
2734 $in_string = false;
2736 // Otherwise, this is a 'double quote', and can be added to the working string
2737 } elseif ($next == "'") {
2738 $working .= "'";
2739 // Skip the next char; we already know what it is
2740 $index++;
2743 // escaping of a quote?
2744 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2745 $working .= "'";
2746 $index++;
2747 // Otherwise, add it to our working string like normal
2748 } else {
2749 $working .= $char;
2751 // Increment character index
2752 $index++;
2753 } // end while
2754 } else {
2755 $enum_set_values = array();
2758 return array(
2759 'type' => $type,
2760 'spec_in_brackets' => $spec_in_brackets,
2761 'enum_set_values' => $enum_set_values
2766 * Verifies if this table's engine supports foreign keys
2768 * @uses strtoupper()
2769 * @param string $engine
2770 * @return boolean
2772 function PMA_foreignkey_supported($engine) {
2773 $engine = strtoupper($engine);
2774 if ('INNODB' == $engine || 'PBXT' == $engine) {
2775 return true;
2776 } else {
2777 return false;
2782 * Replaces some characters by a displayable equivalent
2784 * @uses str_replace()
2785 * @param string $content
2786 * @return string the content with characters replaced
2788 function PMA_replace_binary_contents($content) {
2789 $result = str_replace("\x00", '\0', $content);
2790 $result = str_replace("\x08", '\b', $result);
2791 $result = str_replace("\x0a", '\n', $result);
2792 $result = str_replace("\x0d", '\r', $result);
2793 $result = str_replace("\x1a", '\Z', $result);
2794 return $result;
2799 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2801 * @uses strpos()
2802 * @return string with the chars replaced
2805 function PMA_duplicateFirstNewline($string){
2806 $first_occurence = strpos($string, "\r\n");
2807 if ($first_occurence === 0){
2808 $string = "\n".$string;
2810 return $string;
2814 * get the action word corresponding to a script name
2815 * in order to display it as a title in navigation panel
2817 * @uses $GLOBALS
2818 * @param string a valid value for $cfg['LeftDefaultTabTable']
2819 * or $cfg['DefaultTabTable']
2820 * or $cfg['DefaultTabDatabase']
2822 function PMA_getTitleForTarget($target) {
2824 $mapping = array(
2825 // Values for $cfg['DefaultTabTable']
2826 'tbl_structure.php' => __('Structure'),
2827 'tbl_sql.php' => __('SQL'),
2828 'tbl_select.php' =>__('Search'),
2829 'tbl_change.php' =>__('Insert'),
2830 'sql.php' => __('Browse'),
2832 // Values for $cfg['DefaultTabDatabase']
2833 'db_structure.php' => __('Structure'),
2834 'db_sql.php' => __('SQL'),
2835 'db_search.php' => __('Search'),
2836 'db_operations.php' => __('Operations'),
2838 return $mapping[$target];
2842 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2844 * @param string Text where to do expansion.
2845 * @param function Function to call for escaping variable values.
2846 * @param array Array with overrides for default parameters (obtained from GLOBALS).
2848 function PMA_expandUserString($string, $escape = NULL, $updates = array()) {
2849 /* Content */
2850 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2851 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2852 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2853 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2854 $vars['database'] = $GLOBALS['db'];
2855 $vars['table'] = $GLOBALS['table'];
2856 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2858 /* Update forced variables */
2859 foreach($updates as $key => $val) {
2860 $vars[$key] = $val;
2863 /* Replacement mapping */
2865 * The __VAR__ ones are for backward compatibility, because user
2866 * might still have it in cookies.
2868 $replace = array(
2869 '@HTTP_HOST@' => $vars['http_host'],
2870 '@SERVER@' => $vars['server_name'],
2871 '__SERVER__' => $vars['server_name'],
2872 '@VERBOSE@' => $vars['server_verbose'],
2873 '@VSERVER@' => $vars['server_verbose_or_name'],
2874 '@DATABASE@' => $vars['database'],
2875 '__DB__' => $vars['database'],
2876 '@TABLE@' => $vars['table'],
2877 '__TABLE__' => $vars['table'],
2878 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2881 /* Optional escaping */
2882 if (!is_null($escape)) {
2883 foreach($replace as $key => $val) {
2884 $replace[$key] = $escape($val);
2888 /* Fetch fields list if required */
2889 if (strpos($string, '@FIELDS@') !== FALSE) {
2890 $fields_list = PMA_DBI_fetch_result(
2891 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2892 . '.' . PMA_backquote($GLOBALS['table']));
2894 $field_names = array();
2895 foreach ($fields_list as $field) {
2896 if (!is_null($escape)) {
2897 $field_names[] = $escape($field['Field']);
2898 } else {
2899 $field_names[] = $field['Field'];
2903 $replace['@FIELDS@'] = implode(',', $field_names);
2906 /* Do the replacement */
2907 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2911 * function that generates a json output for an ajax request and ends script
2912 * execution
2914 * @param boolean success whether the ajax request was successfull
2915 * @param string message string containing the html of the message
2916 * @param array extra_data optional - any other data as part of the json request
2918 * @uses header()
2919 * @uses json_encode()
2921 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2923 $response = array();
2924 if( $success == true ) {
2925 $response['success'] = true;
2926 if ($message instanceof PMA_Message) {
2927 $response['message'] = $message->getDisplay();
2929 else {
2930 $response['message'] = $message;
2933 else {
2934 $response['success'] = false;
2935 if($message instanceof PMA_Message) {
2936 $response['error'] = $message->getDisplay();
2938 else {
2939 $response['error'] = $message;
2943 // If extra_data has been provided, append it to the response array
2944 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2945 $response = array_merge($response, $extra_data);
2948 // Set the Content-Type header to JSON so that jQuery parses the
2949 // response correctly.
2951 // At this point, other headers might have been sent;
2952 // even if $GLOBALS['is_header_sent'] is true,
2953 // we have to send these additional headers.
2954 header('Cache-Control: no-cache');
2955 header("Content-Type: application/json");
2957 echo json_encode($response);
2958 exit;
2962 * Display the form used to browse anywhere on the local server for the file to import
2964 function PMA_browseUploadFile($max_upload_size) {
2965 $uid = uniqid("");
2966 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2967 echo '<div id="upload_form_status" style="display: none;"></div>';
2968 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2969 echo '<input type="file" name="import_file" id="input_import_file" />';
2970 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2971 // some browsers should respect this :)
2972 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2976 * Display the form used to select a file to import from the server upload directory
2978 function PMA_selectUploadFile($import_list, $uploaddir) {
2979 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2980 $extensions = '';
2981 foreach ($import_list as $key => $val) {
2982 if (!empty($extensions)) {
2983 $extensions .= '|';
2985 $extensions .= $val['extension'];
2987 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2989 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2990 if ($files === FALSE) {
2991 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2992 } elseif (!empty($files)) {
2993 echo "\n";
2994 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2995 echo ' <option value="">&nbsp;</option>' . "\n";
2996 echo $files;
2997 echo ' </select>' . "\n";
2998 } elseif (empty ($files)) {
2999 echo '<i>' . __('There are no files to upload') . '</i>';
3004 * Build titles and icons for action links
3006 * @return array the action titles
3007 * @uses PMA_getIcon()
3009 function PMA_buildActionTitles() {
3010 $titles = array();
3012 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
3013 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
3014 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
3015 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
3016 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
3017 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
3018 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
3019 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
3020 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
3021 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
3022 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
3023 $titles['Edit'] = PMA_getIcon('b_edit.png', __('Edit'), true);
3024 return $titles;