Translation update done using Pootle.
[phpmyadmin-themes.git] / libraries / common.lib.php
blob35ddeee0aa415de0bff0788bd3cd6a637683de52
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 if ($include_box) {
105 $button .= '<span class="nowrap">';
108 if ($include_icon) {
109 $button .= '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
110 . ' title="' . $alternate . '" alt="' . $alternate . '"'
111 . ' class="icon" width="16" height="16" />';
114 if ($include_icon && $include_text) {
115 $button .= ' ';
118 if ($include_text) {
119 $button .= $alternate;
122 if ($include_box) {
123 $button .= '</span>';
126 return $button;
130 * Displays the maximum size for an upload
132 * @uses PMA_formatByteDown()
133 * @uses sprintf()
134 * @param integer the size
136 * @return string the message
138 * @access public
140 function PMA_displayMaximumUploadSize($max_upload_size)
142 // I have to reduce the second parameter (sensitiveness) from 6 to 4
143 // to avoid weird results like 512 kKib
144 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size, 4);
145 return '(' . sprintf(__('Max: %s%s'), $max_size, $max_unit) . ')';
149 * Generates a hidden field which should indicate to the browser
150 * the maximum size for upload
152 * @param integer the size
154 * @return string the INPUT field
156 * @access public
158 function PMA_generateHiddenMaxFileSize($max_size)
160 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
164 * Add slashes before "'" and "\" characters so a value containing them can
165 * be used in a sql comparison.
167 * @uses str_replace()
168 * @param string the string to slash
169 * @param boolean whether the string will be used in a 'LIKE' clause
170 * (it then requires two more escaped sequences) or not
171 * @param boolean whether to treat cr/lfs as escape-worthy entities
172 * (converts \n to \\n, \r to \\r)
174 * @param boolean whether this function is used as part of the
175 * "Create PHP code" dialog
177 * @return string the slashed string
179 * @access public
181 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
183 if ($is_like) {
184 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
185 } else {
186 $a_string = str_replace('\\', '\\\\', $a_string);
189 if ($crlf) {
190 $a_string = str_replace("\n", '\n', $a_string);
191 $a_string = str_replace("\r", '\r', $a_string);
192 $a_string = str_replace("\t", '\t', $a_string);
195 if ($php_code) {
196 $a_string = str_replace('\'', '\\\'', $a_string);
197 } else {
198 $a_string = str_replace('\'', '\'\'', $a_string);
201 return $a_string;
202 } // end of the 'PMA_sqlAddslashes()' function
206 * Add slashes before "_" and "%" characters for using them in MySQL
207 * database, table and field names.
208 * Note: This function does not escape backslashes!
210 * @uses str_replace()
211 * @param string the string to escape
213 * @return string the escaped string
215 * @access public
217 function PMA_escape_mysql_wildcards($name)
219 $name = str_replace('_', '\\_', $name);
220 $name = str_replace('%', '\\%', $name);
222 return $name;
223 } // end of the 'PMA_escape_mysql_wildcards()' function
226 * removes slashes before "_" and "%" characters
227 * Note: This function does not unescape backslashes!
229 * @uses str_replace()
230 * @param string $name the string to escape
231 * @return string the escaped string
232 * @access public
234 function PMA_unescape_mysql_wildcards($name)
236 $name = str_replace('\\_', '_', $name);
237 $name = str_replace('\\%', '%', $name);
239 return $name;
240 } // end of the 'PMA_unescape_mysql_wildcards()' function
243 * removes quotes (',",`) from a quoted string
245 * checks if the sting is quoted and removes this quotes
247 * @uses str_replace()
248 * @uses substr()
249 * @param string $quoted_string string to remove quotes from
250 * @param string $quote type of quote to remove
251 * @return string unqoted string
253 function PMA_unQuote($quoted_string, $quote = null)
255 $quotes = array();
257 if (null === $quote) {
258 $quotes[] = '`';
259 $quotes[] = '"';
260 $quotes[] = "'";
261 } else {
262 $quotes[] = $quote;
265 foreach ($quotes as $quote) {
266 if (substr($quoted_string, 0, 1) === $quote
267 && substr($quoted_string, -1, 1) === $quote) {
268 $unquoted_string = substr($quoted_string, 1, -1);
269 // replace escaped quotes
270 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
271 return $unquoted_string;
275 return $quoted_string;
279 * format sql strings
281 * @todo move into PMA_Sql
282 * @uses PMA_SQP_isError()
283 * @uses PMA_SQP_formatHtml()
284 * @uses PMA_SQP_formatNone()
285 * @uses is_array()
286 * @param mixed pre-parsed SQL structure
288 * @return string the formatted sql
290 * @global array the configuration array
291 * @global boolean whether the current statement is a multiple one or not
293 * @access public
296 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
298 global $cfg;
300 // Check that we actually have a valid set of parsed data
301 // well, not quite
302 // first check for the SQL parser having hit an error
303 if (PMA_SQP_isError()) {
304 return htmlspecialchars($parsed_sql['raw']);
306 // then check for an array
307 if (!is_array($parsed_sql)) {
308 // We don't so just return the input directly
309 // This is intended to be used for when the SQL Parser is turned off
310 $formatted_sql = '<pre>' . "\n"
311 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ? $unparsed_sql : $parsed_sql) . "\n"
312 . '</pre>';
313 return $formatted_sql;
316 $formatted_sql = '';
318 switch ($cfg['SQP']['fmtType']) {
319 case 'none':
320 if ($unparsed_sql != '') {
321 $formatted_sql = '<span class="inner_sql"><pre>' . "\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n" . '</pre></span>';
322 } else {
323 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
325 break;
326 case 'html':
327 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
328 break;
329 case 'text':
330 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
331 break;
332 default:
333 break;
334 } // end switch
336 return $formatted_sql;
337 } // end of the "PMA_formatSql()" function
341 * Displays a link to the official MySQL documentation
343 * @uses $cfg['MySQLManualType']
344 * @uses $cfg['MySQLManualBase']
345 * @uses $cfg['ReplaceHelpImg']
346 * @uses $GLOBALS['pmaThemeImage']
347 * @uses PMA_MYSQL_INT_VERSION
348 * @uses strtolower()
349 * @uses str_replace()
350 * @param string chapter of "HTML, one page per chapter" documentation
351 * @param string contains name of page/anchor that is being linked
352 * @param bool whether to use big icon (like in left frame)
353 * @param string anchor to page part
355 * @return string the html link
357 * @access public
359 function PMA_showMySQLDocu($chapter, $link, $big_icon = false, $anchor = '', $just_open = false)
361 global $cfg;
363 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
364 return '';
367 // Fixup for newly used names:
368 $chapter = str_replace('_', '-', strtolower($chapter));
369 $link = str_replace('_', '-', strtolower($link));
371 switch ($cfg['MySQLManualType']) {
372 case 'chapters':
373 if (empty($chapter)) {
374 $chapter = 'index';
376 if (empty($anchor)) {
377 $anchor = $link;
379 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $anchor;
380 break;
381 case 'big':
382 if (empty($anchor)) {
383 $anchor = $link;
385 $url = $cfg['MySQLManualBase'] . '#' . $anchor;
386 break;
387 case 'searchable':
388 if (empty($link)) {
389 $link = 'index';
391 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
392 if (!empty($anchor)) {
393 $url .= '#' . $anchor;
395 break;
396 case 'viewable':
397 default:
398 if (empty($link)) {
399 $link = 'index';
401 $mysql = '5.0';
402 $lang = 'en';
403 if (defined('PMA_MYSQL_INT_VERSION')) {
404 if (PMA_MYSQL_INT_VERSION >= 50100) {
405 $mysql = '5.1';
406 /* l10n: Language to use for MySQL 5.1 documentation, please use only languages which do exist in official documentation. */
407 $lang = _pgettext('$mysql_5_1_doc_lang', 'en');
408 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
409 $mysql = '5.0';
410 /* l10n: Language to use for MySQL 5.0 documentation, please use only languages which do exist in official documentation. */
411 $lang = _pgettext('$mysql_5_0_doc_lang', 'en');
414 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
415 if (!empty($anchor)) {
416 $url .= '#' . $anchor;
418 break;
421 if ($just_open) {
422 return '<a href="' . PMA_linkURL($url) . '" target="mysql_doc">';
423 } elseif ($big_icon) {
424 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>';
425 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
426 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>';
427 } else {
428 return '[<a href="' . PMA_linkURL($url) . '" target="mysql_doc">' . __('Documentation') . '</a>]';
430 } // end of the 'PMA_showMySQLDocu()' function
434 * Displays a link to the phpMyAdmin documentation
436 * @param string anchor in documentation
438 * @return string the html link
440 * @access public
442 function PMA_showDocu($anchor) {
443 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
444 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>';
445 } else {
446 return '[<a href="Documentation.html#' . $anchor . '" target="documentation">' . __('Documentation') . '</a>]';
448 } // end of the 'PMA_showDocu()' function
451 * returns HTML for a footnote marker and add the messsage to the footnotes
453 * @uses $GLOBALS['footnotes']
454 * @param string the error message
455 * @return string html code for a footnote marker
456 * @access public
458 function PMA_showHint($message, $bbcode = false, $type = 'notice')
460 if ($message instanceof PMA_Message) {
461 $key = $message->getHash();
462 $type = $message->getLevel();
463 } else {
464 $key = md5($message);
467 if (! isset($GLOBALS['footnotes'][$key])) {
468 if (empty($GLOBALS['footnotes']) || ! is_array($GLOBALS['footnotes'])) {
469 $GLOBALS['footnotes'] = array();
471 $nr = count($GLOBALS['footnotes']) + 1;
472 // this is the first instance of this message
473 $instance = 1;
474 $GLOBALS['footnotes'][$key] = array(
475 'note' => $message,
476 'type' => $type,
477 'nr' => $nr,
478 'instance' => $instance
480 } else {
481 $nr = $GLOBALS['footnotes'][$key]['nr'];
482 // another instance of this message (to ensure ids are unique)
483 $instance = ++$GLOBALS['footnotes'][$key]['instance'];
486 if ($bbcode) {
487 return '[sup]' . $nr . '[/sup]';
490 // footnotemarker used in js/tooltip.js
491 return '<sup class="footnotemarker">' . $nr . '</sup>' .
492 '<img class="footnotemarker" id="footnote_' . $nr . '_' . $instance . '" src="' .
493 $GLOBALS['pmaThemeImage'] . 'b_help.png" alt="" />';
497 * Displays a MySQL error message in the right frame.
499 * @uses footer.inc.php
500 * @uses header.inc.php
501 * @uses $GLOBALS['sql_query']
502 * @uses $GLOBALS['pmaThemeImage']
503 * @uses $GLOBALS['cfg']['PropertiesIconic']
504 * @uses $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
505 * @uses PMA_backquote()
506 * @uses PMA_DBI_getError()
507 * @uses PMA_formatSql()
508 * @uses PMA_generate_common_hidden_inputs()
509 * @uses PMA_generate_common_url()
510 * @uses PMA_showMySQLDocu()
511 * @uses PMA_sqlAddslashes()
512 * @uses PMA_SQP_isError()
513 * @uses PMA_SQP_parse()
514 * @uses PMA_SQP_getErrorString()
515 * @uses strtolower()
516 * @uses urlencode()
517 * @uses str_replace()
518 * @uses nl2br()
519 * @uses substr()
520 * @uses preg_replace()
521 * @uses preg_match()
522 * @uses explode()
523 * @uses implode()
524 * @uses is_array()
525 * @uses function_exists()
526 * @uses htmlspecialchars()
527 * @uses trim()
528 * @uses strstr()
529 * @param string the error message
530 * @param string the sql query that failed
531 * @param boolean whether to show a "modify" link or not
532 * @param string the "back" link url (full path is not required)
533 * @param boolean EXIT the page?
535 * @global string the curent table
536 * @global string the current db
538 * @access public
540 function PMA_mysqlDie($error_message = '', $the_query = '',
541 $is_modify_link = true, $back_url = '', $exit = true)
543 global $table, $db;
546 * start http output, display html headers
548 require_once './libraries/header.inc.php';
550 $error_msg_output = '';
552 if (!$error_message) {
553 $error_message = PMA_DBI_getError();
555 if (!$the_query && !empty($GLOBALS['sql_query'])) {
556 $the_query = $GLOBALS['sql_query'];
559 // --- Added to solve bug #641765
560 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) {
561 $formatted_sql = htmlspecialchars($the_query);
562 } elseif (empty($the_query) || trim($the_query) == '') {
563 $formatted_sql = '';
564 } else {
565 if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
566 $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]';
567 } else {
568 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
571 // ---
572 $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
573 $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n";
574 // if the config password is wrong, or the MySQL server does not
575 // respond, do not show the query that would reveal the
576 // username/password
577 if (!empty($the_query) && !strstr($the_query, 'connect')) {
578 // --- Added to solve bug #641765
579 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
580 $error_msg_output .= PMA_SQP_getErrorString() . "\n";
581 $error_msg_output .= '<br />' . "\n";
583 // ---
584 // modified to show the help on sql errors
585 $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n";
586 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
587 $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
589 if ($is_modify_link) {
590 $_url_params = array(
591 'sql_query' => $the_query,
592 'show_query' => 1,
594 if (strlen($table)) {
595 $_url_params['db'] = $db;
596 $_url_params['table'] = $table;
597 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($_url_params) . '">';
598 } elseif (strlen($db)) {
599 $_url_params['db'] = $db;
600 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($_url_params) . '">';
601 } else {
602 $doedit_goto = '<a href="server_sql.php?' . PMA_generate_common_url($_url_params) . '">';
605 $error_msg_output .= $doedit_goto
606 . PMA_getIcon('b_edit.png', __('Edit'))
607 . '</a>';
608 } // end if
609 $error_msg_output .= ' </p>' . "\n"
610 .' <p>' . "\n"
611 .' ' . $formatted_sql . "\n"
612 .' </p>' . "\n";
613 } // end if
615 if (!empty($error_message)) {
616 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
618 // modified to show the help on error-returns
619 // (now error-messages-server)
620 $error_msg_output .= '<p>' . "\n"
621 . ' <strong>' . __('MySQL said: ') . '</strong>'
622 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
623 . "\n"
624 . '</p>' . "\n";
626 // The error message will be displayed within a CODE segment.
627 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
629 // Replace all non-single blanks with their HTML-counterpart
630 $error_message = str_replace(' ', '&nbsp;&nbsp;', $error_message);
631 // Replace TAB-characters with their HTML-counterpart
632 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
633 // Replace linebreaks
634 $error_message = nl2br($error_message);
636 $error_msg_output .= '<code>' . "\n"
637 . $error_message . "\n"
638 . '</code><br />' . "\n";
639 $error_msg_output .= '</div>';
641 $_SESSION['Import_message']['message'] = $error_msg_output;
643 if ($exit) {
644 if (! empty($back_url)) {
645 if (strstr($back_url, '?')) {
646 $back_url .= '&amp;no_history=true';
647 } else {
648 $back_url .= '?no_history=true';
651 $_SESSION['Import_message']['go_back_url'] = $back_url;
653 $error_msg_output .= '<fieldset class="tblFooters">';
654 $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]';
655 $error_msg_output .= '</fieldset>' . "\n\n";
659 * If in an Ajax request, don't just echo and exit. Use PMA_ajaxResponse()
661 if($GLOBALS['is_ajax_request'] == true) {
662 PMA_ajaxResponse($error_msg_output, false);
664 echo $error_msg_output;
666 * display footer and exit
668 require './libraries/footer.inc.php';
669 } else {
670 echo $error_msg_output;
672 } // end of the 'PMA_mysqlDie()' function
675 * returns array with tables of given db with extended information and grouped
677 * @uses $cfg['LeftFrameTableSeparator']
678 * @uses $cfg['LeftFrameTableLevel']
679 * @uses $cfg['ShowTooltipAliasTB']
680 * @uses $cfg['NaturalOrder']
681 * @uses PMA_backquote()
682 * @uses count()
683 * @uses array_merge
684 * @uses uksort()
685 * @uses strstr()
686 * @uses explode()
687 * @param string $db name of db
688 * @param string $tables name of tables
689 * @param integer $limit_offset list offset
690 * @param integer $limit_count max tables to return
691 * return array (recursive) grouped table list
693 function PMA_getTableList($db, $tables = null, $limit_offset = 0, $limit_count = false)
695 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
697 if (null === $tables) {
698 $tables = PMA_DBI_get_tables_full($db, false, false, null, $limit_offset, $limit_count);
699 if ($GLOBALS['cfg']['NaturalOrder']) {
700 uksort($tables, 'strnatcasecmp');
704 if (count($tables) < 1) {
705 return $tables;
708 $default = array(
709 'Name' => '',
710 'Rows' => 0,
711 'Comment' => '',
712 'disp_name' => '',
715 $table_groups = array();
717 // for blobstreaming - list of blobstreaming tables
719 // load PMA configuration
720 $PMA_Config = $GLOBALS['PMA_Config'];
722 foreach ($tables as $table_name => $table) {
723 // if BS tables exist
724 if (PMA_BS_IsHiddenTable($table_name)) {
725 continue;
728 // check for correct row count
729 if (null === $table['Rows']) {
730 // Do not check exact row count here,
731 // if row count is invalid possibly the table is defect
732 // and this would break left frame;
733 // but we can check row count if this is a view or the
734 // information_schema database
735 // since PMA_Table::countRecords() returns a limited row count
736 // in this case.
738 // set this because PMA_Table::countRecords() can use it
739 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
741 if ($tbl_is_view || 'information_schema' == $db) {
742 $table['Rows'] = PMA_Table::countRecords($db, $table['Name']);
746 // in $group we save the reference to the place in $table_groups
747 // where to store the table info
748 if ($GLOBALS['cfg']['LeftFrameDBTree']
749 && $sep && strstr($table_name, $sep))
751 $parts = explode($sep, $table_name);
753 $group =& $table_groups;
754 $i = 0;
755 $group_name_full = '';
756 $parts_cnt = count($parts) - 1;
757 while ($i < $parts_cnt
758 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
759 $group_name = $parts[$i] . $sep;
760 $group_name_full .= $group_name;
762 if (!isset($group[$group_name])) {
763 $group[$group_name] = array();
764 $group[$group_name]['is' . $sep . 'group'] = true;
765 $group[$group_name]['tab' . $sep . 'count'] = 1;
766 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
767 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
768 $table = $group[$group_name];
769 $group[$group_name] = array();
770 $group[$group_name][$group_name] = $table;
771 unset($table);
772 $group[$group_name]['is' . $sep . 'group'] = true;
773 $group[$group_name]['tab' . $sep . 'count'] = 1;
774 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
775 } else {
776 $group[$group_name]['tab' . $sep . 'count']++;
778 $group =& $group[$group_name];
779 $i++;
781 } else {
782 if (!isset($table_groups[$table_name])) {
783 $table_groups[$table_name] = array();
785 $group =& $table_groups;
789 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
790 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
791 // switch tooltip and name
792 $table['Comment'] = $table['Name'];
793 $table['disp_name'] = $table['Comment'];
794 } else {
795 $table['disp_name'] = $table['Name'];
798 $group[$table_name] = array_merge($default, $table);
801 return $table_groups;
804 /* ----------------------- Set of misc functions ----------------------- */
808 * Adds backquotes on both sides of a database, table or field name.
809 * and escapes backquotes inside the name with another backquote
811 * example:
812 * <code>
813 * echo PMA_backquote('owner`s db'); // `owner``s db`
815 * </code>
817 * @uses PMA_backquote()
818 * @uses is_array()
819 * @uses strlen()
820 * @uses str_replace()
821 * @param mixed $a_name the database, table or field name to "backquote"
822 * or array of it
823 * @param boolean $do_it a flag to bypass this function (used by dump
824 * functions)
825 * @return mixed the "backquoted" database, table or field name if the
826 * current MySQL release is >= 3.23.6, the original one
827 * else
828 * @access public
830 function PMA_backquote($a_name, $do_it = true)
832 if (is_array($a_name)) {
833 foreach ($a_name as &$data) {
834 $data = PMA_backquote($data, $do_it);
836 return $a_name;
839 if (! $do_it) {
840 global $PMA_SQPdata_forbidden_word;
841 global $PMA_SQPdata_forbidden_word_cnt;
843 if(! PMA_STR_binarySearchInArr(strtoupper($a_name), $PMA_SQPdata_forbidden_word, $PMA_SQPdata_forbidden_word_cnt)) {
844 return $a_name;
848 // '0' is also empty for php :-(
849 if (strlen($a_name) && $a_name !== '*') {
850 return '`' . str_replace('`', '``', $a_name) . '`';
851 } else {
852 return $a_name;
854 } // end of the 'PMA_backquote()' function
858 * Defines the <CR><LF> value depending on the user OS.
860 * @uses PMA_USR_OS
861 * @return string the <CR><LF> value to use
863 * @access public
865 function PMA_whichCrlf()
867 $the_crlf = "\n";
869 // The 'PMA_USR_OS' constant is defined in "./libraries/Config.class.php"
870 // Win case
871 if (PMA_USR_OS == 'Win') {
872 $the_crlf = "\r\n";
874 // Others
875 else {
876 $the_crlf = "\n";
879 return $the_crlf;
880 } // end of the 'PMA_whichCrlf()' function
883 * Reloads navigation if needed.
885 * @param $jsonly prints out pure JavaScript
886 * @uses $GLOBALS['reload']
887 * @uses $GLOBALS['db']
888 * @uses PMA_generate_common_url()
889 * @global array configuration
891 * @access public
893 function PMA_reloadNavigation($jsonly=false)
895 global $cfg;
897 // Reloads the navigation frame via JavaScript if required
898 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
899 // one of the reasons for a reload is when a table is dropped
900 // in this case, get rid of the table limit offset, otherwise
901 // we have a problem when dropping a table on the last page
902 // and the offset becomes greater than the total number of tables
903 unset($_SESSION['tmp_user_values']['table_limit_offset']);
904 echo "\n";
905 $reload_url = './navigation.php?' . PMA_generate_common_url($GLOBALS['db'], '', '&');
906 if (!$jsonly)
907 echo '<script type="text/javascript">' . PHP_EOL;
909 //<![CDATA[
910 if (typeof(window.parent) != 'undefined'
911 && typeof(window.parent.frame_navigation) != 'undefined'
912 && window.parent.goTo) {
913 window.parent.goTo('<?php echo $reload_url; ?>');
915 //]]>
916 <?php
917 if (!$jsonly)
918 echo '</script>' . PHP_EOL;
920 unset($GLOBALS['reload']);
925 * displays the message and the query
926 * usually the message is the result of the query executed
928 * @param string $message the message to display
929 * @param string $sql_query the query to display
930 * @param string $type the type (level) of the message
931 * @param boolean $is_view is this a message after a VIEW operation?
932 * @global array the configuration array
933 * @uses $cfg
934 * @access public
936 function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
939 * PMA_ajaxResponse uses this function to collect the string of HTML generated
940 * for showing the message. Use output buffering to collect it and return it
941 * in a string. In some special cases on sql.php, buffering has to be disabled
942 * and hence we check with $GLOBALS['buffer_message']
944 if( $GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message']) ) {
945 ob_start();
947 global $cfg;
949 if (null === $sql_query) {
950 if (! empty($GLOBALS['display_query'])) {
951 $sql_query = $GLOBALS['display_query'];
952 } elseif ($cfg['SQP']['fmtType'] == 'none' && ! empty($GLOBALS['unparsed_sql'])) {
953 $sql_query = $GLOBALS['unparsed_sql'];
954 } elseif (! empty($GLOBALS['sql_query'])) {
955 $sql_query = $GLOBALS['sql_query'];
956 } else {
957 $sql_query = '';
961 if (isset($GLOBALS['using_bookmark_message'])) {
962 $GLOBALS['using_bookmark_message']->display();
963 unset($GLOBALS['using_bookmark_message']);
966 // Corrects the tooltip text via JS if required
967 // @todo this is REALLY the wrong place to do this - very unexpected here
968 if (! $is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
969 $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
970 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
971 echo "\n";
972 echo '<script type="text/javascript">' . "\n";
973 echo '//<![CDATA[' . "\n";
974 echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
975 echo '//]]>' . "\n";
976 echo '</script>' . "\n";
977 } // end if ... elseif
979 // Checks if the table needs to be repaired after a TRUNCATE query.
980 // @todo what about $GLOBALS['display_query']???
981 // @todo this is REALLY the wrong place to do this - very unexpected here
982 if (strlen($GLOBALS['table'])
983 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
984 if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
985 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
988 unset($tbl_status);
990 // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
991 // check for it's presence before using it
992 echo '<div align="' . ( isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '' ) . '">' . "\n";
994 if ($message instanceof PMA_Message) {
995 if (isset($GLOBALS['special_message'])) {
996 $message->addMessage($GLOBALS['special_message']);
997 unset($GLOBALS['special_message']);
999 $message->display();
1000 $type = $message->getLevel();
1001 } else {
1002 echo '<div class="' . $type . '">';
1003 echo PMA_sanitize($message);
1004 if (isset($GLOBALS['special_message'])) {
1005 echo PMA_sanitize($GLOBALS['special_message']);
1006 unset($GLOBALS['special_message']);
1008 echo '</div>';
1011 if ($cfg['ShowSQL'] == true && ! empty($sql_query)) {
1012 // Html format the query to be displayed
1013 // If we want to show some sql code it is easiest to create it here
1014 /* SQL-Parser-Analyzer */
1016 if (! empty($GLOBALS['show_as_php'])) {
1017 $new_line = '\\n"<br />' . "\n"
1018 . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
1019 $query_base = htmlspecialchars(addslashes($sql_query));
1020 $query_base = preg_replace('/((\015\012)|(\015)|(\012))/', $new_line, $query_base);
1021 } else {
1022 $query_base = $sql_query;
1025 $query_too_big = false;
1027 if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
1028 // when the query is large (for example an INSERT of binary
1029 // data), the parser chokes; so avoid parsing the query
1030 $query_too_big = true;
1031 $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
1032 } elseif (! empty($GLOBALS['parsed_sql'])
1033 && $query_base == $GLOBALS['parsed_sql']['raw']) {
1034 // (here, use "! empty" because when deleting a bookmark,
1035 // $GLOBALS['parsed_sql'] is set but empty
1036 $parsed_sql = $GLOBALS['parsed_sql'];
1037 } else {
1038 // Parse SQL if needed
1039 $parsed_sql = PMA_SQP_parse($query_base);
1040 if (PMA_SQP_isError()) {
1041 unset($parsed_sql);
1045 // Analyze it
1046 if (isset($parsed_sql)) {
1047 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1048 // Here we append the LIMIT added for navigation, to
1049 // enable its display. Adding it higher in the code
1050 // to $sql_query would create a problem when
1051 // using the Refresh or Edit links.
1053 // Only append it on SELECTs.
1056 * @todo what would be the best to do when someone hits Refresh:
1057 * use the current LIMITs ?
1060 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1061 && isset($GLOBALS['sql_limit_to_append'])) {
1062 $query_base = $analyzed_display_query[0]['section_before_limit']
1063 . "\n" . $GLOBALS['sql_limit_to_append']
1064 . $analyzed_display_query[0]['section_after_limit'];
1065 // Need to reparse query
1066 $parsed_sql = PMA_SQP_parse($query_base);
1070 if (! empty($GLOBALS['show_as_php'])) {
1071 $query_base = '$sql = "' . $query_base;
1072 } elseif (! empty($GLOBALS['validatequery'])) {
1073 try {
1074 $query_base = PMA_validateSQL($query_base);
1075 } catch (Exception $e) {
1076 PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
1078 } elseif (isset($parsed_sql)) {
1079 $query_base = PMA_formatSql($parsed_sql, $query_base);
1082 // Prepares links that may be displayed to edit/explain the query
1083 // (don't go to default pages, we must go to the page
1084 // where the query box is available)
1086 // Basic url query part
1087 $url_params = array();
1088 if (! isset($GLOBALS['db'])) {
1089 $GLOBALS['db'] = '';
1091 if (strlen($GLOBALS['db'])) {
1092 $url_params['db'] = $GLOBALS['db'];
1093 if (strlen($GLOBALS['table'])) {
1094 $url_params['table'] = $GLOBALS['table'];
1095 $edit_link = 'tbl_sql.php';
1096 } else {
1097 $edit_link = 'db_sql.php';
1099 } else {
1100 $edit_link = 'server_sql.php';
1103 // Want to have the query explained (Mike Beck 2002-05-22)
1104 // but only explain a SELECT (that has not been explained)
1105 /* SQL-Parser-Analyzer */
1106 $explain_link = '';
1107 if (! empty($cfg['SQLQuery']['Explain']) && ! $query_too_big) {
1108 $explain_params = $url_params;
1109 // Detect if we are validating as well
1110 // To preserve the validate uRL data
1111 if (! empty($GLOBALS['validatequery'])) {
1112 $explain_params['validatequery'] = 1;
1115 if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
1116 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
1117 $_message = __('Explain SQL');
1118 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
1119 $explain_params['sql_query'] = substr($sql_query, 8);
1120 $_message = __('Skip Explain SQL');
1122 if (isset($explain_params['sql_query'])) {
1123 $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
1124 $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
1126 } //show explain
1128 $url_params['sql_query'] = $sql_query;
1129 $url_params['show_query'] = 1;
1131 // even if the query is big and was truncated, offer the chance
1132 // to edit it (unless it's enormous, see PMA_linkOrButton() )
1133 if (! empty($cfg['SQLQuery']['Edit'])) {
1134 if ($cfg['EditInWindow'] == true) {
1135 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
1136 } else {
1137 $onclick = '';
1140 $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
1141 $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
1142 } else {
1143 $edit_link = '';
1146 $url_qpart = PMA_generate_common_url($url_params);
1148 // Also we would like to get the SQL formed in some nice
1149 // php-code (Mike Beck 2002-05-22)
1150 if (! empty($cfg['SQLQuery']['ShowAsPHP']) && ! $query_too_big) {
1151 $php_params = $url_params;
1153 if (! empty($GLOBALS['show_as_php'])) {
1154 $_message = __('Without PHP Code');
1155 } else {
1156 $php_params['show_as_php'] = 1;
1157 $_message = __('Create PHP Code');
1160 $php_link = 'import.php' . PMA_generate_common_url($php_params);
1161 $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
1163 if (isset($GLOBALS['show_as_php'])) {
1164 $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
1165 $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
1167 } else {
1168 $php_link = '';
1169 } //show as php
1171 // Refresh query
1172 if (! empty($cfg['SQLQuery']['Refresh'])
1173 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
1174 $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
1175 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
1176 } else {
1177 $refresh_link = '';
1178 } //show as php
1180 if (! empty($cfg['SQLValidator']['use'])
1181 && ! empty($cfg['SQLQuery']['Validate'])) {
1182 $validate_params = $url_params;
1183 if (!empty($GLOBALS['validatequery'])) {
1184 $validate_message = __('Skip Validate SQL') ;
1185 } else {
1186 $validate_params['validatequery'] = 1;
1187 $validate_message = __('Validate SQL') ;
1190 $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
1191 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1192 } else {
1193 $validate_link = '';
1194 } //validator
1196 if (!empty($GLOBALS['validatequery'])) {
1197 echo '<div class="sqlvalidate">';
1198 } else {
1199 echo '<code class="sql">';
1201 if ($query_too_big) {
1202 echo $shortened_query_base;
1203 } else {
1204 echo $query_base;
1207 //Clean up the end of the PHP
1208 if (! empty($GLOBALS['show_as_php'])) {
1209 echo '";';
1211 if (!empty($GLOBALS['validatequery'])) {
1212 echo '</div>';
1213 } else {
1214 echo '</code>';
1217 echo '<div class="tools">';
1218 // avoid displaying a Profiling checkbox that could
1219 // be checked, which would reexecute an INSERT, for example
1220 if (! empty($refresh_link)) {
1221 PMA_profilingCheckbox($sql_query);
1223 // if needed, generate an invisible form that contains controls for the
1224 // Inline link; this way, the behavior of the Inline link does not
1225 // depend on the profiling support or on the refresh link
1226 if (empty($refresh_link) || ! PMA_profilingSupported()) {
1227 echo '<form action="sql.php" method="post">';
1228 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1229 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
1230 echo '</form>';
1233 // in the tools div, only display the Inline link when not in ajax
1234 // mode because 1) it currently does not work and 2) we would
1235 // have two similar mechanisms on the page for the same goal
1236 if ($GLOBALS['is_ajax_request'] === false) {
1237 // see in js/functions.js the jQuery code attached to id inline_edit
1238 // document.write conflicts with jQuery, hence used $().append()
1239 echo "<script type=\"text/javascript\">\n" .
1240 "//<![CDATA[\n" .
1241 "$('.tools').append('[<a href=\"#\" title=\"" .
1242 PMA_escapeJsString(__('Inline edit of this query')) .
1243 "\" id=\"inline_edit\">" .
1244 PMA_escapeJsString(__('Inline')) .
1245 "</a>]');\n" .
1246 "//]]>\n" .
1247 "</script>";
1249 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1250 echo '</div>';
1252 echo '</div><br class="clearfloat" />' . "\n";
1254 // If we are in an Ajax request, we have most probably been called in
1255 // PMA_ajaxResponse(). Hence, collect the buffer contents and return it
1256 // to PMA_ajaxResponse(), which will encode it for JSON.
1257 if( $GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message']) ) {
1258 $buffer_contents = ob_get_contents();
1259 ob_end_clean();
1260 return $buffer_contents;
1262 } // end of the 'PMA_showMessage()' function
1265 * Verifies if current MySQL server supports profiling
1267 * @uses $_SESSION['profiling_supported'] for caching
1268 * @uses $GLOBALS['server']
1269 * @uses PMA_DBI_fetch_value()
1270 * @uses PMA_MYSQL_INT_VERSION
1271 * @uses defined()
1272 * @access public
1273 * @return boolean whether profiling is supported
1276 function PMA_profilingSupported()
1278 if (! PMA_cacheExists('profiling_supported', true)) {
1279 // 5.0.37 has profiling but for example, 5.1.20 does not
1280 // (avoid a trip to the server for MySQL before 5.0.37)
1281 // and do not set a constant as we might be switching servers
1282 if (defined('PMA_MYSQL_INT_VERSION')
1283 && PMA_MYSQL_INT_VERSION >= 50037
1284 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'profiling'")) {
1285 PMA_cacheSet('profiling_supported', true, true);
1286 } else {
1287 PMA_cacheSet('profiling_supported', false, true);
1291 return PMA_cacheGet('profiling_supported', true);
1295 * Displays a form with the Profiling checkbox
1297 * @param string $sql_query
1298 * @access public
1301 function PMA_profilingCheckbox($sql_query)
1303 if (PMA_profilingSupported()) {
1304 echo '<form action="sql.php" method="post">' . "\n";
1305 echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
1306 echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />' . "\n";
1307 echo '<input type="hidden" name="profiling_form" value="1" />' . "\n";
1308 PMA_display_html_checkbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
1309 echo '<noscript><input type="submit" value="' . __('Go') . '" /></noscript>' . "\n";
1310 echo '</form>' . "\n";
1315 * Displays the results of SHOW PROFILE
1317 * @param array the results
1318 * @param boolean show chart
1319 * @access public
1322 function PMA_profilingResults($profiling_results, $show_chart = false)
1324 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
1325 echo '<div style="float: left;">';
1326 echo '<table>' . "\n";
1327 echo ' <tr>' . "\n";
1328 echo ' <th>' . __('Status') . '</th>' . "\n";
1329 echo ' <th>' . __('Time') . '</th>' . "\n";
1330 echo ' </tr>' . "\n";
1332 foreach($profiling_results as $one_result) {
1333 echo ' <tr>' . "\n";
1334 echo '<td>' . $one_result['Status'] . '</td>' . "\n";
1335 echo '<td>' . $one_result['Duration'] . '</td>' . "\n";
1338 echo '</table>' . "\n";
1339 echo '</div>';
1341 if ($show_chart) {
1342 require_once './libraries/chart.lib.php';
1343 echo '<div style="float: left;">';
1344 PMA_chart_profiling($profiling_results);
1345 echo '</div>';
1348 echo '</fieldset>' . "\n";
1352 * Formats $value to byte view
1354 * @param double the value to format
1355 * @param integer the sensitiveness
1356 * @param integer the number of decimals to retain
1358 * @return array the formatted value and its unit
1360 * @access public
1362 * @version 1.2 - 18 July 2002
1364 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1366 /* l10n: shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa+ */
1367 $byteUnits = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'), __('EiB'));
1369 $dh = PMA_pow(10, $comma);
1370 $li = PMA_pow(10, $limes);
1371 $return_value = $value;
1372 $unit = $byteUnits[0];
1374 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1375 if (isset($byteUnits[$d]) && $value >= $li * PMA_pow(10, $ex)) {
1376 // use 1024.0 to avoid integer overflow on 64-bit machines
1377 $value = round($value / (PMA_pow(1024, $d) / $dh)) /$dh;
1378 $unit = $byteUnits[$d];
1379 break 1;
1380 } // end if
1381 } // end for
1383 if ($unit != $byteUnits[0]) {
1384 // if the unit is not bytes (as represented in current language)
1385 // reformat with max length of 5
1386 // 4th parameter=true means do not reformat if value < 1
1387 $return_value = PMA_formatNumber($value, 5, $comma, true);
1388 } else {
1389 // do not reformat, just handle the locale
1390 $return_value = PMA_formatNumber($value, 0);
1393 return array(trim($return_value), $unit);
1394 } // end of the 'PMA_formatByteDown' function
1397 * Changes thousands and decimal separators to locale specific values.
1399 function PMA_localizeNumber($value)
1401 return str_replace(
1402 array(',', '.'),
1403 array(
1404 /* l10n: Thousands separator */
1405 __(','),
1406 /* l10n: Decimal separator */
1407 __('.'),
1409 $value);
1413 * Formats $value to the given length and appends SI prefixes
1414 * $comma is not substracted from the length
1415 * with a $length of 0 no truncation occurs, number is only formated
1416 * to the current locale
1418 * examples:
1419 * <code>
1420 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1421 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1422 * echo PMA_formatNumber(-0.003, 6); // -3 m
1423 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1424 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1425 * echo PMA_formatNumber(0, 6); // 0
1427 * </code>
1428 * @param double $value the value to format
1429 * @param integer $length the max length
1430 * @param integer $comma the number of decimals to retain
1431 * @param boolean $only_down do not reformat numbers below 1
1433 * @return string the formatted value and its unit
1435 * @access public
1437 * @version 1.1.0 - 2005-10-27
1439 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1441 //number_format is not multibyte safe, str_replace is safe
1442 if ($length === 0) {
1443 return PMA_localizeNumber(number_format($value, $comma));
1446 // this units needs no translation, ISO
1447 $units = array(
1448 -8 => 'y',
1449 -7 => 'z',
1450 -6 => 'a',
1451 -5 => 'f',
1452 -4 => 'p',
1453 -3 => 'n',
1454 -2 => '&micro;',
1455 -1 => 'm',
1456 0 => ' ',
1457 1 => 'k',
1458 2 => 'M',
1459 3 => 'G',
1460 4 => 'T',
1461 5 => 'P',
1462 6 => 'E',
1463 7 => 'Z',
1464 8 => 'Y'
1467 // we need at least 3 digits to be displayed
1468 if (3 > $length + $comma) {
1469 $length = 3 - $comma;
1472 // check for negative value to retain sign
1473 if ($value < 0) {
1474 $sign = '-';
1475 $value = abs($value);
1476 } else {
1477 $sign = '';
1480 $dh = PMA_pow(10, $comma);
1481 $li = PMA_pow(10, $length);
1482 $unit = $units[0];
1484 if ($value >= 1) {
1485 for ($d = 8; $d >= 0; $d--) {
1486 if (isset($units[$d]) && $value >= $li * PMA_pow(1000, $d-1)) {
1487 $value = round($value / (PMA_pow(1000, $d) / $dh)) /$dh;
1488 $unit = $units[$d];
1489 break 1;
1490 } // end if
1491 } // end for
1492 } elseif (!$only_down && (float) $value !== 0.0) {
1493 for ($d = -8; $d <= 8; $d++) {
1494 // force using pow() because of the negative exponent
1495 if (isset($units[$d]) && $value <= $li * PMA_pow(1000, $d-1, 'pow')) {
1496 $value = round($value / (PMA_pow(1000, $d, 'pow') / $dh)) /$dh;
1497 $unit = $units[$d];
1498 break 1;
1499 } // end if
1500 } // end for
1501 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1503 //number_format is not multibyte safe, str_replace is safe
1504 $value = PMA_localizeNumber(number_format($value, $comma));
1506 return $sign . $value . ' ' . $unit;
1507 } // end of the 'PMA_formatNumber' function
1510 * Returns the number of bytes when a formatted size is given
1512 * @param string $size the size expression (for example 8MB)
1513 * @uses PMA_pow()
1514 * @return integer The numerical part of the expression (for example 8)
1516 function PMA_extractValueFromFormattedSize($formatted_size)
1518 $return_value = -1;
1520 if (preg_match('/^[0-9]+GB$/', $formatted_size)) {
1521 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 3);
1522 } elseif (preg_match('/^[0-9]+MB$/', $formatted_size)) {
1523 $return_value = substr($formatted_size, 0, -2) * PMA_pow(1024, 2);
1524 } elseif (preg_match('/^[0-9]+K$/', $formatted_size)) {
1525 $return_value = substr($formatted_size, 0, -1) * PMA_pow(1024, 1);
1527 return $return_value;
1528 }// end of the 'PMA_extractValueFromFormattedSize' function
1531 * Writes localised date
1533 * @param string the current timestamp
1535 * @return string the formatted date
1537 * @access public
1539 function PMA_localisedDate($timestamp = -1, $format = '')
1541 $month = array(
1542 /* l10n: Short month name */
1543 __('Jan'),
1544 /* l10n: Short month name */
1545 __('Feb'),
1546 /* l10n: Short month name */
1547 __('Mar'),
1548 /* l10n: Short month name */
1549 __('Apr'),
1550 /* l10n: Short month name */
1551 _pgettext('Short month name', 'May'),
1552 /* l10n: Short month name */
1553 __('Jun'),
1554 /* l10n: Short month name */
1555 __('Jul'),
1556 /* l10n: Short month name */
1557 __('Aug'),
1558 /* l10n: Short month name */
1559 __('Sep'),
1560 /* l10n: Short month name */
1561 __('Oct'),
1562 /* l10n: Short month name */
1563 __('Nov'),
1564 /* l10n: Short month name */
1565 __('Dec'));
1566 $day_of_week = array(
1567 /* l10n: Short week day name */
1568 __('Sun'),
1569 /* l10n: Short week day name */
1570 __('Mon'),
1571 /* l10n: Short week day name */
1572 __('Tue'),
1573 /* l10n: Short week day name */
1574 __('Wed'),
1575 /* l10n: Short week day name */
1576 __('Thu'),
1577 /* l10n: Short week day name */
1578 __('Fri'),
1579 /* l10n: Short week day name */
1580 __('Sat'));
1582 if ($format == '') {
1583 /* l10n: See http://www.php.net/manual/en/function.strftime.php to define the format string */
1584 $format = __('%B %d, %Y at %I:%M %p');
1587 if ($timestamp == -1) {
1588 $timestamp = time();
1591 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1592 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1594 return strftime($date, $timestamp);
1595 } // end of the 'PMA_localisedDate()' function
1599 * returns a tab for tabbed navigation.
1600 * If the variables $link and $args ar left empty, an inactive tab is created
1602 * @uses $GLOBALS['PMA_PHP_SELF']
1603 * @uses $GLOBALS['active_page']
1604 * @uses $GLOBALS['url_query']
1605 * @uses $cfg['MainPageIconic']
1606 * @uses $GLOBALS['pmaThemeImage']
1607 * @uses PMA_generate_common_url()
1608 * @uses E_USER_NOTICE
1609 * @uses htmlentities()
1610 * @uses urlencode()
1611 * @uses sprintf()
1612 * @uses trigger_error()
1613 * @uses array_merge()
1614 * @uses basename()
1615 * @param array $tab array with all options
1616 * @param array $url_params
1617 * @return string html code for one tab, a link if valid otherwise a span
1618 * @access public
1620 function PMA_generate_html_tab($tab, $url_params = array())
1622 // default values
1623 $defaults = array(
1624 'text' => '',
1625 'class' => '',
1626 'active' => null,
1627 'link' => '',
1628 'sep' => '?',
1629 'attr' => '',
1630 'args' => '',
1631 'warning' => '',
1632 'fragment' => '',
1633 'id' => '',
1636 $tab = array_merge($defaults, $tab);
1638 // determine additionnal style-class
1639 if (empty($tab['class'])) {
1640 if ($tab['text'] == __('Empty')
1641 || $tab['text'] == __('Drop')) {
1642 $tab['class'] = 'caution';
1643 } elseif (! empty($tab['active'])
1644 || PMA_isValid($GLOBALS['active_page'], 'identical', $tab['link'])) {
1645 $tab['class'] = 'active';
1646 } elseif (is_null($tab['active']) && empty($GLOBALS['active_page'])
1647 && basename($GLOBALS['PMA_PHP_SELF']) == $tab['link']
1648 && empty($tab['warning'])) {
1649 $tab['class'] = 'active';
1653 if (!empty($tab['warning'])) {
1654 $tab['class'] .= ' warning';
1655 $tab['attr'] .= ' title="' . htmlspecialchars($tab['warning']) . '"';
1658 // If there are any tab specific URL parameters, merge those with the general URL parameters
1659 if(! empty($tab['url_params']) && is_array($tab['url_params'])) {
1660 $url_params = array_merge($url_params, $tab['url_params']);
1663 // build the link
1664 if (!empty($tab['link'])) {
1665 $tab['link'] = htmlentities($tab['link']);
1666 $tab['link'] = $tab['link'] . PMA_generate_common_url($url_params);
1667 if (! empty($tab['args'])) {
1668 foreach ($tab['args'] as $param => $value) {
1669 $tab['link'] .= PMA_get_arg_separator('html') . urlencode($param) . '='
1670 . urlencode($value);
1675 if (! empty($tab['fragment'])) {
1676 $tab['link'] .= $tab['fragment'];
1679 // display icon, even if iconic is disabled but the link-text is missing
1680 if (($GLOBALS['cfg']['MainPageIconic'] || empty($tab['text']))
1681 && isset($tab['icon'])) {
1682 // avoid generating an alt tag, because it only illustrates
1683 // the text that follows and if browser does not display
1684 // images, the text is duplicated
1685 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1686 .'%1$s" width="16" height="16" alt="" />%2$s';
1687 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1689 // check to not display an empty link-text
1690 elseif (empty($tab['text'])) {
1691 $tab['text'] = '?';
1692 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1693 E_USER_NOTICE);
1696 //Set the id for the tab, if set in the params
1697 $id_string = ( empty($tab['id']) ? '' : ' id="'.$tab['id'].'" ' );
1698 $out = '<li' . ($tab['class'] == 'active' ? ' class="active"' : '') . '>';
1700 if (!empty($tab['link'])) {
1701 $out .= '<a class="tab' . htmlentities($tab['class']) . '"'
1702 .$id_string
1703 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1704 . $tab['text'] . '</a>';
1705 } else {
1706 $out .= '<span class="tab' . htmlentities($tab['class']) . '"'.$id_string.'>'
1707 . $tab['text'] . '</span>';
1710 $out .= '</li>';
1711 return $out;
1712 } // end of the 'PMA_generate_html_tab()' function
1715 * returns html-code for a tab navigation
1717 * @uses PMA_generate_html_tab()
1718 * @uses htmlentities()
1719 * @param array $tabs one element per tab
1720 * @param string $url_params
1721 * @return string html-code for tab-navigation
1723 function PMA_generate_html_tabs($tabs, $url_params)
1725 $tag_id = 'topmenu';
1726 $tab_navigation =
1727 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1728 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1730 foreach ($tabs as $tab) {
1731 $tab_navigation .= PMA_generate_html_tab($tab, $url_params);
1734 $tab_navigation .=
1735 '</ul>' . "\n"
1736 .'<div class="clearfloat"></div>'
1737 .'</div>' . "\n";
1739 return $tab_navigation;
1744 * Displays a link, or a button if the link's URL is too large, to
1745 * accommodate some browsers' limitations
1747 * @param string the URL
1748 * @param string the link message
1749 * @param mixed $tag_params string: js confirmation
1750 * array: additional tag params (f.e. style="")
1751 * @param boolean $new_form we set this to false when we are already in
1752 * a form, to avoid generating nested forms
1754 * @return string the results to be echoed or saved in an array
1756 function PMA_linkOrButton($url, $message, $tag_params = array(),
1757 $new_form = true, $strip_img = false, $target = '')
1759 $url_length = strlen($url);
1760 // with this we should be able to catch case of image upload
1761 // into a (MEDIUM) BLOB; not worth generating even a form for these
1762 if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
1763 return '';
1766 if (! is_array($tag_params)) {
1767 $tmp = $tag_params;
1768 $tag_params = array();
1769 if (!empty($tmp)) {
1770 $tag_params['onclick'] = 'return confirmLink(this, \'' . PMA_escapeJsString($tmp) . '\')';
1772 unset($tmp);
1774 if (! empty($target)) {
1775 $tag_params['target'] = htmlentities($target);
1778 $tag_params_strings = array();
1779 foreach ($tag_params as $par_name => $par_value) {
1780 // htmlspecialchars() only on non javascript
1781 $par_value = substr($par_name, 0, 2) == 'on'
1782 ? $par_value
1783 : htmlspecialchars($par_value);
1784 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1787 if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
1788 // no whitespace within an <a> else Safari will make it part of the link
1789 $ret = "\n" . '<a href="' . $url . '" '
1790 . implode(' ', $tag_params_strings) . '>'
1791 . $message . '</a>' . "\n";
1792 } else {
1793 // no spaces (linebreaks) at all
1794 // or after the hidden fields
1795 // IE will display them all
1797 // add class=link to submit button
1798 if (empty($tag_params['class'])) {
1799 $tag_params['class'] = 'link';
1802 // decode encoded url separators
1803 $separator = PMA_get_arg_separator();
1804 // on most places separator is still hard coded ...
1805 if ($separator !== '&') {
1806 // ... so always replace & with $separator
1807 $url = str_replace(htmlentities('&'), $separator, $url);
1808 $url = str_replace('&', $separator, $url);
1810 $url = str_replace(htmlentities($separator), $separator, $url);
1811 // end decode
1813 $url_parts = parse_url($url);
1814 $query_parts = explode($separator, $url_parts['query']);
1815 if ($new_form) {
1816 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1817 . ' method="post"' . $target . ' style="display: inline;">';
1818 $subname_open = '';
1819 $subname_close = '';
1820 $submit_name = '';
1821 } else {
1822 $query_parts[] = 'redirect=' . $url_parts['path'];
1823 if (empty($GLOBALS['subform_counter'])) {
1824 $GLOBALS['subform_counter'] = 0;
1826 $GLOBALS['subform_counter']++;
1827 $ret = '';
1828 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1829 $subname_close = ']';
1830 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1832 foreach ($query_parts as $query_pair) {
1833 list($eachvar, $eachval) = explode('=', $query_pair);
1834 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1835 . $subname_close . '" value="'
1836 . htmlspecialchars(urldecode($eachval)) . '" />';
1837 } // end while
1839 if (stristr($message, '<img')) {
1840 if ($strip_img) {
1841 $message = trim(strip_tags($message));
1842 $ret .= '<input type="submit"' . $submit_name . ' '
1843 . implode(' ', $tag_params_strings)
1844 . ' value="' . htmlspecialchars($message) . '" />';
1845 } else {
1846 $displayed_message = htmlspecialchars(
1847 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1848 $message));
1849 $ret .= '<input type="image"' . $submit_name . ' '
1850 . implode(' ', $tag_params_strings)
1851 . ' src="' . preg_replace(
1852 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1853 . ' value="' . $displayed_message . '" title="' . $displayed_message . '" />';
1855 } else {
1856 $message = trim(strip_tags($message));
1857 $ret .= '<input type="submit"' . $submit_name . ' '
1858 . implode(' ', $tag_params_strings)
1859 . ' value="' . htmlspecialchars($message) . '" />';
1861 if ($new_form) {
1862 $ret .= '</form>';
1864 } // end if... else...
1866 return $ret;
1867 } // end of the 'PMA_linkOrButton()' function
1871 * Returns a given timespan value in a readable format.
1873 * @uses sprintf()
1874 * @uses floor()
1875 * @param int the timespan
1877 * @return string the formatted value
1879 function PMA_timespanFormat($seconds)
1881 $return_string = '';
1882 $days = floor($seconds / 86400);
1883 if ($days > 0) {
1884 $seconds -= $days * 86400;
1886 $hours = floor($seconds / 3600);
1887 if ($days > 0 || $hours > 0) {
1888 $seconds -= $hours * 3600;
1890 $minutes = floor($seconds / 60);
1891 if ($days > 0 || $hours > 0 || $minutes > 0) {
1892 $seconds -= $minutes * 60;
1894 return sprintf(__('%s days, %s hours, %s minutes and %s seconds'), (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1898 * Takes a string and outputs each character on a line for itself. Used
1899 * mainly for horizontalflipped display mode.
1900 * Takes care of special html-characters.
1901 * Fulfills todo-item
1902 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1904 * @todo add a multibyte safe function PMA_STR_split()
1905 * @uses strlen
1906 * @param string The string
1907 * @param string The Separator (defaults to "<br />\n")
1909 * @access public
1910 * @return string The flipped string
1912 function PMA_flipstring($string, $Separator = "<br />\n")
1914 $format_string = '';
1915 $charbuff = false;
1917 for ($i = 0, $str_len = strlen($string); $i < $str_len; $i++) {
1918 $char = $string{$i};
1919 $append = false;
1921 if ($char == '&') {
1922 $format_string .= $charbuff;
1923 $charbuff = $char;
1924 } elseif ($char == ';' && !empty($charbuff)) {
1925 $format_string .= $charbuff . $char;
1926 $charbuff = false;
1927 $append = true;
1928 } elseif (! empty($charbuff)) {
1929 $charbuff .= $char;
1930 } else {
1931 $format_string .= $char;
1932 $append = true;
1935 // do not add separator after the last character
1936 if ($append && ($i != $str_len - 1)) {
1937 $format_string .= $Separator;
1941 return $format_string;
1946 * Function added to avoid path disclosures.
1947 * Called by each script that needs parameters, it displays
1948 * an error message and, by default, stops the execution.
1950 * Not sure we could use a strMissingParameter message here,
1951 * would have to check if the error message file is always available
1953 * @todo localize error message
1954 * @todo use PMA_fatalError() if $die === true?
1955 * @uses PMA_getenv()
1956 * @uses header_meta_style.inc.php
1957 * @uses $GLOBALS['PMA_PHP_SELF']
1958 * basename
1959 * @param array The names of the parameters needed by the calling
1960 * script.
1961 * @param boolean Stop the execution?
1962 * (Set this manually to false in the calling script
1963 * until you know all needed parameters to check).
1964 * @param boolean Whether to include this list in checking for special params.
1965 * @global string path to current script
1966 * @global boolean flag whether any special variable was required
1968 * @access public
1970 function PMA_checkParameters($params, $die = true, $request = true)
1972 global $checked_special;
1974 if (!isset($checked_special)) {
1975 $checked_special = false;
1978 $reported_script_name = basename($GLOBALS['PMA_PHP_SELF']);
1979 $found_error = false;
1980 $error_message = '';
1982 foreach ($params as $param) {
1983 if ($request && $param != 'db' && $param != 'table') {
1984 $checked_special = true;
1987 if (!isset($GLOBALS[$param])) {
1988 $error_message .= $reported_script_name
1989 . ': Missing parameter: ' . $param
1990 . PMA_showDocu('faqmissingparameters')
1991 . '<br />';
1992 $found_error = true;
1995 if ($found_error) {
1997 * display html meta tags
1999 require_once './libraries/header_meta_style.inc.php';
2000 echo '</head><body><p>' . $error_message . '</p></body></html>';
2001 if ($die) {
2002 exit();
2005 } // end function
2008 * Function to generate unique condition for specified row.
2010 * @uses $GLOBALS['analyzed_sql'][0]
2011 * @uses PMA_DBI_field_flags()
2012 * @uses PMA_backquote()
2013 * @uses PMA_sqlAddslashes()
2014 * @uses PMA_printable_bit_value()
2015 * @uses stristr()
2016 * @uses bin2hex()
2017 * @uses preg_replace()
2018 * @param resource $handle current query result
2019 * @param integer $fields_cnt number of fields
2020 * @param array $fields_meta meta information about fields
2021 * @param array $row current row
2022 * @param boolean $force_unique generate condition only on pk or unique
2024 * @access public
2025 * @return string the calculated condition and whether condition is unique
2027 function PMA_getUniqueCondition($handle, $fields_cnt, $fields_meta, $row, $force_unique=false)
2029 $primary_key = '';
2030 $unique_key = '';
2031 $nonprimary_condition = '';
2032 $preferred_condition = '';
2034 for ($i = 0; $i < $fields_cnt; ++$i) {
2035 $condition = '';
2036 $field_flags = PMA_DBI_field_flags($handle, $i);
2037 $meta = $fields_meta[$i];
2039 // do not use a column alias in a condition
2040 if (! isset($meta->orgname) || ! strlen($meta->orgname)) {
2041 $meta->orgname = $meta->name;
2043 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2044 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2045 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2046 as $select_expr) {
2047 // need (string) === (string)
2048 // '' !== 0 but '' == 0
2049 if ((string) $select_expr['alias'] === (string) $meta->name) {
2050 $meta->orgname = $select_expr['column'];
2051 break;
2052 } // end if
2053 } // end foreach
2057 // Do not use a table alias in a condition.
2058 // Test case is:
2059 // select * from galerie x WHERE
2060 //(select count(*) from galerie y where y.datum=x.datum)>1
2062 // But orgtable is present only with mysqli extension so the
2063 // fix is only for mysqli.
2064 // Also, do not use the original table name if we are dealing with
2065 // a view because this view might be updatable.
2066 // (The isView() verification should not be costly in most cases
2067 // because there is some caching in the function).
2068 if (isset($meta->orgtable) && $meta->table != $meta->orgtable && ! PMA_Table::isView($GLOBALS['db'], $meta->table)) {
2069 $meta->table = $meta->orgtable;
2072 // to fix the bug where float fields (primary or not)
2073 // can't be matched because of the imprecision of
2074 // floating comparison, use CONCAT
2075 // (also, the syntax "CONCAT(field) IS NULL"
2076 // that we need on the next "if" will work)
2077 if ($meta->type == 'real') {
2078 $condition = ' CONCAT(' . PMA_backquote($meta->table) . '.'
2079 . PMA_backquote($meta->orgname) . ') ';
2080 } else {
2081 $condition = ' ' . PMA_backquote($meta->table) . '.'
2082 . PMA_backquote($meta->orgname) . ' ';
2083 } // end if... else...
2085 if (!isset($row[$i]) || is_null($row[$i])) {
2086 $condition .= 'IS NULL AND';
2087 } else {
2088 // timestamp is numeric on some MySQL 4.1
2089 // for real we use CONCAT above and it should compare to string
2090 if ($meta->numeric && $meta->type != 'timestamp' && $meta->type != 'real') {
2091 $condition .= '= ' . $row[$i] . ' AND';
2092 } elseif (($meta->type == 'blob' || $meta->type == 'string')
2093 // hexify only if this is a true not empty BLOB or a BINARY
2094 && stristr($field_flags, 'BINARY')
2095 && !empty($row[$i])) {
2096 // do not waste memory building a too big condition
2097 if (strlen($row[$i]) < 1000) {
2098 // use a CAST if possible, to avoid problems
2099 // if the field contains wildcard characters % or _
2100 $condition .= '= CAST(0x' . bin2hex($row[$i])
2101 . ' AS BINARY) AND';
2102 } else {
2103 // this blob won't be part of the final condition
2104 $condition = '';
2106 } elseif ($meta->type == 'bit') {
2107 $condition .= "= b'" . PMA_printable_bit_value($row[$i], $meta->length) . "' AND";
2108 } else {
2109 $condition .= '= \''
2110 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2113 if ($meta->primary_key > 0) {
2114 $primary_key .= $condition;
2115 } elseif ($meta->unique_key > 0) {
2116 $unique_key .= $condition;
2118 $nonprimary_condition .= $condition;
2119 } // end for
2121 // Correction University of Virginia 19991216:
2122 // prefer primary or unique keys for condition,
2123 // but use conjunction of all values if no primary key
2124 $clause_is_unique = true;
2125 if ($primary_key) {
2126 $preferred_condition = $primary_key;
2127 } elseif ($unique_key) {
2128 $preferred_condition = $unique_key;
2129 } elseif (! $force_unique) {
2130 $preferred_condition = $nonprimary_condition;
2131 $clause_is_unique = false;
2134 $where_clause = trim(preg_replace('|\s?AND$|', '', $preferred_condition));
2135 return(array($where_clause, $clause_is_unique));
2136 } // end function
2139 * Generate a button or image tag
2141 * @uses PMA_USR_BROWSER_AGENT
2142 * @uses $GLOBALS['pmaThemeImage']
2143 * @uses $GLOBALS['cfg']['PropertiesIconic']
2144 * @param string name of button element
2145 * @param string class of button element
2146 * @param string name of image element
2147 * @param string text to display
2148 * @param string image to display
2150 * @access public
2152 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2153 $image)
2155 if (false === $GLOBALS['cfg']['PropertiesIconic']) {
2156 echo ' <input type="submit" name="' . $button_name . '"'
2157 .' value="' . htmlspecialchars($text) . '"'
2158 .' title="' . htmlspecialchars($text) . '" />' . "\n";
2159 return;
2162 /* Opera has trouble with <input type="image"> */
2163 /* IE has trouble with <button> */
2164 if (PMA_USR_BROWSER_AGENT != 'IE') {
2165 echo '<button class="' . $button_class . '" type="submit"'
2166 .' name="' . $button_name . '" value="' . htmlspecialchars($text) . '"'
2167 .' title="' . htmlspecialchars($text) . '">' . "\n"
2168 . PMA_getIcon($image, $text)
2169 .'</button>' . "\n";
2170 } else {
2171 echo '<input type="image" name="' . $image_name . '" value="'
2172 . htmlspecialchars($text) . '" title="' . htmlspecialchars($text) . '" src="' . $GLOBALS['pmaThemeImage']
2173 . $image . '" />'
2174 . ($GLOBALS['cfg']['PropertiesIconic'] === 'both' ? '&nbsp;' . htmlspecialchars($text) : '') . "\n";
2176 } // end function
2179 * Generate a pagination selector for browsing resultsets
2181 * @uses range()
2182 * @param string Number of rows in the pagination set
2183 * @param string current page number
2184 * @param string number of total pages
2185 * @param string If the number of pages is lower than this
2186 * variable, no pages will be omitted in
2187 * pagination
2188 * @param string How many rows at the beginning should always
2189 * be shown?
2190 * @param string How many rows at the end should always
2191 * be shown?
2192 * @param string Percentage of calculation page offsets to
2193 * hop to a next page
2194 * @param string Near the current page, how many pages should
2195 * be considered "nearby" and displayed as
2196 * well?
2197 * @param string The prompt to display (sometimes empty)
2199 * @access public
2201 function PMA_pageselector($rows, $pageNow = 1, $nbTotalPage = 1,
2202 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2203 $range = 10, $prompt = '')
2205 $increment = floor($nbTotalPage / $percent);
2206 $pageNowMinusRange = ($pageNow - $range);
2207 $pageNowPlusRange = ($pageNow + $range);
2209 $gotopage = $prompt . ' <select id="pageselector" ';
2210 if ($GLOBALS['cfg']['AjaxEnable']) {
2211 $gotopage .= ' class="ajax"';
2213 $gotopage .= ' name="pos" >' . "\n";
2214 if ($nbTotalPage < $showAll) {
2215 $pages = range(1, $nbTotalPage);
2216 } else {
2217 $pages = array();
2219 // Always show first X pages
2220 for ($i = 1; $i <= $sliceStart; $i++) {
2221 $pages[] = $i;
2224 // Always show last X pages
2225 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2226 $pages[] = $i;
2229 // Based on the number of results we add the specified
2230 // $percent percentage to each page number,
2231 // so that we have a representing page number every now and then to
2232 // immediately jump to specific pages.
2233 // As soon as we get near our currently chosen page ($pageNow -
2234 // $range), every page number will be shown.
2235 $i = $sliceStart;
2236 $x = $nbTotalPage - $sliceEnd;
2237 $met_boundary = false;
2238 while ($i <= $x) {
2239 if ($i >= $pageNowMinusRange && $i <= $pageNowPlusRange) {
2240 // If our pageselector comes near the current page, we use 1
2241 // counter increments
2242 $i++;
2243 $met_boundary = true;
2244 } else {
2245 // We add the percentage increment to our current page to
2246 // hop to the next one in range
2247 $i += $increment;
2249 // Make sure that we do not cross our boundaries.
2250 if ($i > $pageNowMinusRange && ! $met_boundary) {
2251 $i = $pageNowMinusRange;
2255 if ($i > 0 && $i <= $x) {
2256 $pages[] = $i;
2260 // Since because of ellipsing of the current page some numbers may be double,
2261 // we unify our array:
2262 sort($pages);
2263 $pages = array_unique($pages);
2266 foreach ($pages as $i) {
2267 if ($i == $pageNow) {
2268 $selected = 'selected="selected" style="font-weight: bold"';
2269 } else {
2270 $selected = '';
2272 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2275 $gotopage .= ' </select><noscript><input type="submit" value="' . __('Go') . '" /></noscript>';
2277 return $gotopage;
2278 } // end function
2282 * Generate navigation for a list
2284 * @todo use $pos from $_url_params
2285 * @uses range()
2286 * @param integer number of elements in the list
2287 * @param integer current position in the list
2288 * @param array url parameters
2289 * @param string script name for form target
2290 * @param string target frame
2291 * @param integer maximum number of elements to display from the list
2293 * @access public
2295 function PMA_listNavigator($count, $pos, $_url_params, $script, $frame, $max_count) {
2297 if ($max_count < $count) {
2298 echo 'frame_navigation' == $frame ? '<div id="navidbpageselector">' . "\n" : '';
2299 echo __('Page number:');
2300 echo 'frame_navigation' == $frame ? '<br />' : ' ';
2302 // Move to the beginning or to the previous page
2303 if ($pos > 0) {
2304 // patch #474210 - part 1
2305 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2306 $caption1 = '&lt;&lt;';
2307 $caption2 = ' &lt; ';
2308 $title1 = ' title="' . __('Begin') . '"';
2309 $title2 = ' title="' . __('Previous') . '"';
2310 } else {
2311 $caption1 = __('Begin') . ' &lt;&lt;';
2312 $caption2 = __('Previous') . ' &lt;';
2313 $title1 = '';
2314 $title2 = '';
2315 } // end if... else...
2316 $_url_params['pos'] = 0;
2317 echo '<a' . $title1 . ' href="' . $script
2318 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2319 . $caption1 . '</a>';
2320 $_url_params['pos'] = $pos - $max_count;
2321 echo '<a' . $title2 . ' href="' . $script
2322 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2323 . $caption2 . '</a>';
2326 echo "\n", '<form action="./', basename($script), '" method="post" target="', $frame, '">', "\n";
2327 echo PMA_generate_common_hidden_inputs($_url_params);
2328 echo PMA_pageselector(
2329 $max_count,
2330 floor(($pos + 1) / $max_count) + 1,
2331 ceil($count / $max_count));
2332 echo '</form>';
2334 if ($pos + $max_count < $count) {
2335 if ($GLOBALS['cfg']['NavigationBarIconic']) {
2336 $caption3 = ' &gt; ';
2337 $caption4 = '&gt;&gt;';
2338 $title3 = ' title="' . __('Next') . '"';
2339 $title4 = ' title="' . __('End') . '"';
2340 } else {
2341 $caption3 = '&gt; ' . __('Next');
2342 $caption4 = '&gt;&gt; ' . __('End');
2343 $title3 = '';
2344 $title4 = '';
2345 } // end if... else...
2346 $_url_params['pos'] = $pos + $max_count;
2347 echo '<a' . $title3 . ' href="' . $script
2348 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2349 . $caption3 . '</a>';
2350 $_url_params['pos'] = floor($count / $max_count) * $max_count;
2351 if ($_url_params['pos'] == $count) {
2352 $_url_params['pos'] = $count - $max_count;
2354 echo '<a' . $title4 . ' href="' . $script
2355 . PMA_generate_common_url($_url_params) . '" target="' . $frame . '">'
2356 . $caption4 . '</a>';
2358 echo "\n";
2359 if ('frame_navigation' == $frame) {
2360 echo '</div>' . "\n";
2366 * replaces %u in given path with current user name
2368 * example:
2369 * <code>
2370 * $user_dir = PMA_userDir('/var/pma_tmp/%u/'); // '/var/pma_tmp/root/'
2372 * </code>
2373 * @uses $cfg['Server']['user']
2374 * @uses substr()
2375 * @uses str_replace()
2376 * @param string $dir with wildcard for user
2377 * @return string per user directory
2379 function PMA_userDir($dir)
2381 // add trailing slash
2382 if (substr($dir, -1) != '/') {
2383 $dir .= '/';
2386 return str_replace('%u', $GLOBALS['cfg']['Server']['user'], $dir);
2390 * returns html code for db link to default db page
2392 * @uses $cfg['DefaultTabDatabase']
2393 * @uses $GLOBALS['db']
2394 * @uses PMA_generate_common_url()
2395 * @uses PMA_unescape_mysql_wildcards()
2396 * @uses strlen()
2397 * @uses sprintf()
2398 * @uses htmlspecialchars()
2399 * @param string $database
2400 * @return string html link to default db page
2402 function PMA_getDbLink($database = null)
2404 if (!strlen($database)) {
2405 if (!strlen($GLOBALS['db'])) {
2406 return '';
2408 $database = $GLOBALS['db'];
2409 } else {
2410 $database = PMA_unescape_mysql_wildcards($database);
2413 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2414 .' title="' . sprintf(__('Jump to database &quot;%s&quot;.'), htmlspecialchars($database)) . '">'
2415 .htmlspecialchars($database) . '</a>';
2419 * Displays a lightbulb hint explaining a known external bug
2420 * that affects a functionality
2422 * @uses PMA_MYSQL_INT_VERSION
2423 * @uses PMA_showHint()
2424 * @uses sprintf()
2425 * @param string $functionality localized message explaining the func.
2426 * @param string $component 'mysql' (eventually, 'php')
2427 * @param string $minimum_version of this component
2428 * @param string $bugref bug reference for this component
2430 function PMA_externalBug($functionality, $component, $minimum_version, $bugref)
2432 if ($component == 'mysql' && PMA_MYSQL_INT_VERSION < $minimum_version) {
2433 echo PMA_showHint(sprintf(__('The %s functionality is affected by a known bug, see %s'), $functionality, PMA_linkURL('http://bugs.mysql.com/') . $bugref));
2438 * Generates and echoes an HTML checkbox
2440 * @param string $html_field_name the checkbox HTML field
2441 * @param string $label
2442 * @param boolean $checked is it initially checked?
2443 * @param boolean $onclick should it submit the form on click?
2445 function PMA_display_html_checkbox($html_field_name, $label, $checked, $onclick) {
2447 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>';
2451 * Generates and echoes a set of radio HTML fields
2453 * @uses htmlspecialchars()
2454 * @param string $html_field_name the radio HTML field
2455 * @param array $choices the choices values and labels
2456 * @param string $checked_choice the choice to check by default
2457 * @param boolean $line_break whether to add an HTML line break after a choice
2458 * @param boolean $escape_label whether to use htmlspecialchars() on label
2459 * @param string $class enclose each choice with a div of this class
2461 function PMA_display_html_radio($html_field_name, $choices, $checked_choice = '', $line_break = true, $escape_label = true, $class='') {
2462 foreach ($choices as $choice_value => $choice_label) {
2463 if (! empty($class)) {
2464 echo '<div class="' . $class . '">';
2466 $html_field_id = $html_field_name . '_' . $choice_value;
2467 echo '<input type="radio" name="' . $html_field_name . '" id="' . $html_field_id . '" value="' . htmlspecialchars($choice_value) . '"';
2468 if ($choice_value == $checked_choice) {
2469 echo ' checked="checked"';
2471 echo ' />' . "\n";
2472 echo '<label for="' . $html_field_id . '">' . ($escape_label ? htmlspecialchars($choice_label) : $choice_label) . '</label>';
2473 if ($line_break) {
2474 echo '<br />';
2476 if (! empty($class)) {
2477 echo '</div>';
2479 echo "\n";
2484 * Generates and returns an HTML dropdown
2486 * @uses htmlspecialchars()
2487 * @param string $select_name
2488 * @param array $choices the choices values
2489 * @param string $active_choice the choice to select by default
2490 * @param string $id the id of the select element; can be different in case
2491 * the dropdown is present more than once on the page
2492 * @todo support titles
2494 function PMA_generate_html_dropdown($select_name, $choices, $active_choice, $id)
2496 $result = '<select name="' . htmlspecialchars($select_name) . '" id="' . htmlspecialchars($id) . '">';
2497 foreach ($choices as $one_choice_value => $one_choice_label) {
2498 $result .= '<option value="' . htmlspecialchars($one_choice_value) . '"';
2499 if ($one_choice_value == $active_choice) {
2500 $result .= ' selected="selected"';
2502 $result .= '>' . htmlspecialchars($one_choice_label) . '</option>';
2504 $result .= '</select>';
2505 return $result;
2509 * Generates a slider effect (jQjuery)
2510 * Takes care of generating the initial <div> and the link
2511 * controlling the slider; you have to generate the </div> yourself
2512 * after the sliding section.
2514 * @uses $GLOBALS['cfg']['InitialSlidersState']
2515 * @param string $id the id of the <div> on which to apply the effect
2516 * @param string $message the message to show as a link
2518 function PMA_generate_slider_effect($id, $message)
2520 if ($GLOBALS['cfg']['InitialSlidersState'] == 'disabled') {
2521 echo '<div id="' . $id . '">';
2522 return;
2525 * Bad hack on the next line. document.write() conflicts with jQuery, hence,
2526 * opening the <div> with PHP itself instead of JavaScript.
2528 * @todo find a better solution that uses $.append(), the recommended method
2529 * maybe by using an additional param, the id of the div to append to
2532 <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); ?>">
2533 <?php
2537 * Clears cache content which needs to be refreshed on user change.
2539 function PMA_clearUserCache() {
2540 PMA_cacheUnset('is_superuser', true);
2544 * Verifies if something is cached in the session
2546 * @param string $var
2547 * @param scalar $server
2548 * @return boolean
2550 function PMA_cacheExists($var, $server = 0)
2552 if (true === $server) {
2553 $server = $GLOBALS['server'];
2555 return isset($_SESSION['cache']['server_' . $server][$var]);
2559 * Gets cached information from the session
2561 * @param string $var
2562 * @param scalar $server
2563 * @return mixed
2565 function PMA_cacheGet($var, $server = 0)
2567 if (true === $server) {
2568 $server = $GLOBALS['server'];
2570 if (isset($_SESSION['cache']['server_' . $server][$var])) {
2571 return $_SESSION['cache']['server_' . $server][$var];
2572 } else {
2573 return null;
2578 * Caches information in the session
2580 * @param string $var
2581 * @param mixed $val
2582 * @param integer $server
2583 * @return mixed
2585 function PMA_cacheSet($var, $val = null, $server = 0)
2587 if (true === $server) {
2588 $server = $GLOBALS['server'];
2590 $_SESSION['cache']['server_' . $server][$var] = $val;
2594 * Removes cached information from the session
2596 * @param string $var
2597 * @param scalar $server
2599 function PMA_cacheUnset($var, $server = 0)
2601 if (true === $server) {
2602 $server = $GLOBALS['server'];
2604 unset($_SESSION['cache']['server_' . $server][$var]);
2608 * Converts a bit value to printable format;
2609 * in MySQL a BIT field can be from 1 to 64 bits so we need this
2610 * function because in PHP, decbin() supports only 32 bits
2612 * @uses ceil()
2613 * @uses decbin()
2614 * @uses ord()
2615 * @uses substr()
2616 * @uses sprintf()
2617 * @param numeric $value coming from a BIT field
2618 * @param integer $length
2619 * @return string the printable value
2621 function PMA_printable_bit_value($value, $length) {
2622 $printable = '';
2623 for ($i = 0, $len_ceiled = ceil($length / 8); $i < $len_ceiled; $i++) {
2624 $printable .= sprintf('%08d', decbin(ord(substr($value, $i, 1))));
2626 $printable = substr($printable, -$length);
2627 return $printable;
2631 * Verifies whether the value contains a non-printable character
2633 * @uses preg_match()
2634 * @param string $value
2635 * @return boolean
2637 function PMA_contains_nonprintable_ascii($value) {
2638 return preg_match('@[^[:print:]]@', $value);
2642 * Converts a BIT type default value
2643 * for example, b'010' becomes 010
2645 * @uses strtr()
2646 * @param string $bit_default_value
2647 * @return string the converted value
2649 function PMA_convert_bit_default_value($bit_default_value) {
2650 return strtr($bit_default_value, array("b" => "", "'" => ""));
2654 * Extracts the various parts from a field type spec
2656 * @uses strpos()
2657 * @uses chop()
2658 * @uses substr()
2659 * @param string $fieldspec
2660 * @return array associative array containing type, spec_in_brackets
2661 * and possibly enum_set_values (another array)
2663 function PMA_extractFieldSpec($fieldspec) {
2664 $first_bracket_pos = strpos($fieldspec, '(');
2665 if ($first_bracket_pos) {
2666 $spec_in_brackets = chop(substr($fieldspec, $first_bracket_pos + 1, (strrpos($fieldspec, ')') - $first_bracket_pos - 1)));
2667 // convert to lowercase just to be sure
2668 $type = strtolower(chop(substr($fieldspec, 0, $first_bracket_pos)));
2669 } else {
2670 $type = $fieldspec;
2671 $spec_in_brackets = '';
2674 if ('enum' == $type || 'set' == $type) {
2675 // Define our working vars
2676 $enum_set_values = array();
2677 $working = "";
2678 $in_string = false;
2679 $index = 0;
2681 // While there is another character to process
2682 while (isset($fieldspec[$index])) {
2683 // Grab the char to look at
2684 $char = $fieldspec[$index];
2686 // If it is a single quote, needs to be handled specially
2687 if ($char == "'") {
2688 // If we are not currently in a string, begin one
2689 if (! $in_string) {
2690 $in_string = true;
2691 $working = "";
2692 // Otherwise, it may be either an end of a string, or a 'double quote' which can be handled as-is
2693 } else {
2694 // Check out the next character (if possible)
2695 $has_next = isset($fieldspec[$index + 1]);
2696 $next = $has_next ? $fieldspec[$index + 1] : null;
2698 // If we have reached the end of our 'working' string (because there are no more chars, or the next char is not another quote)
2699 if (! $has_next || $next != "'") {
2700 $enum_set_values[] = $working;
2701 $in_string = false;
2703 // Otherwise, this is a 'double quote', and can be added to the working string
2704 } elseif ($next == "'") {
2705 $working .= "'";
2706 // Skip the next char; we already know what it is
2707 $index++;
2710 // escaping of a quote?
2711 } elseif ('\\' == $char && isset($fieldspec[$index + 1]) && "'" == $fieldspec[$index + 1]) {
2712 $working .= "'";
2713 $index++;
2714 // Otherwise, add it to our working string like normal
2715 } else {
2716 $working .= $char;
2718 // Increment character index
2719 $index++;
2720 } // end while
2721 } else {
2722 $enum_set_values = array();
2725 return array(
2726 'type' => $type,
2727 'spec_in_brackets' => $spec_in_brackets,
2728 'enum_set_values' => $enum_set_values
2733 * Verifies if this table's engine supports foreign keys
2735 * @uses strtoupper()
2736 * @param string $engine
2737 * @return boolean
2739 function PMA_foreignkey_supported($engine) {
2740 $engine = strtoupper($engine);
2741 if ('INNODB' == $engine || 'PBXT' == $engine) {
2742 return true;
2743 } else {
2744 return false;
2749 * Replaces some characters by a displayable equivalent
2751 * @uses str_replace()
2752 * @param string $content
2753 * @return string the content with characters replaced
2755 function PMA_replace_binary_contents($content) {
2756 $result = str_replace("\x00", '\0', $content);
2757 $result = str_replace("\x08", '\b', $result);
2758 $result = str_replace("\x0a", '\n', $result);
2759 $result = str_replace("\x0d", '\r', $result);
2760 $result = str_replace("\x1a", '\Z', $result);
2761 return $result;
2766 * If the string starts with a \r\n pair (0x0d0a) add an extra \n
2768 * @uses strpos()
2769 * @return string with the chars replaced
2772 function PMA_duplicateFirstNewline($string){
2773 $first_occurence = strpos($string, "\r\n");
2774 if ($first_occurence === 0){
2775 $string = "\n".$string;
2777 return $string;
2781 * get the action word corresponding to a script name
2782 * in order to display it as a title in navigation panel
2784 * @uses $GLOBALS
2785 * @param string a valid value for $cfg['LeftDefaultTabTable']
2786 * or $cfg['DefaultTabTable']
2787 * or $cfg['DefaultTabDatabase']
2789 function PMA_getTitleForTarget($target) {
2791 $mapping = array(
2792 // Values for $cfg['DefaultTabTable']
2793 'tbl_structure.php' => __('Structure'),
2794 'tbl_sql.php' => __('SQL'),
2795 'tbl_select.php' =>__('Search'),
2796 'tbl_change.php' =>__('Insert'),
2797 'sql.php' => __('Browse'),
2799 // Values for $cfg['DefaultTabDatabase']
2800 'db_structure.php' => __('Structure'),
2801 'db_sql.php' => __('SQL'),
2802 'db_search.php' => __('Search'),
2803 'db_operations.php' => __('Operations'),
2805 return $mapping[$target];
2809 * Formats user string, expading @VARIABLES@, accepting strftime format string.
2811 * @param string Text where to do expansion.
2812 * @param function Function to call for escaping variable values.
2813 * @param array Array with overrides for default parameters (obtained from GLOBALS).
2815 function PMA_expandUserString($string, $escape = NULL, $updates = array()) {
2816 /* Content */
2817 $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : '';
2818 $vars['server_name'] = $GLOBALS['cfg']['Server']['host'];
2819 $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose'];
2820 $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host'];
2821 $vars['database'] = $GLOBALS['db'];
2822 $vars['table'] = $GLOBALS['table'];
2823 $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION;
2825 /* Update forced variables */
2826 foreach($updates as $key => $val) {
2827 $vars[$key] = $val;
2830 /* Replacement mapping */
2832 * The __VAR__ ones are for backward compatibility, because user
2833 * might still have it in cookies.
2835 $replace = array(
2836 '@HTTP_HOST@' => $vars['http_host'],
2837 '@SERVER@' => $vars['server_name'],
2838 '__SERVER__' => $vars['server_name'],
2839 '@VERBOSE@' => $vars['server_verbose'],
2840 '@VSERVER@' => $vars['server_verbose_or_name'],
2841 '@DATABASE@' => $vars['database'],
2842 '__DB__' => $vars['database'],
2843 '@TABLE@' => $vars['table'],
2844 '__TABLE__' => $vars['table'],
2845 '@PHPMYADMIN@' => $vars['phpmyadmin_version'],
2848 /* Optional escaping */
2849 if (!is_null($escape)) {
2850 foreach($replace as $key => $val) {
2851 $replace[$key] = $escape($val);
2855 /* Fetch fields list if required */
2856 if (strpos($string, '@FIELDS@') !== FALSE) {
2857 $fields_list = PMA_DBI_fetch_result(
2858 'SHOW COLUMNS FROM ' . PMA_backquote($GLOBALS['db'])
2859 . '.' . PMA_backquote($GLOBALS['table']));
2861 $field_names = array();
2862 foreach ($fields_list as $field) {
2863 if (!is_null($escape)) {
2864 $field_names[] = $escape($field['Field']);
2865 } else {
2866 $field_names[] = $field['Field'];
2870 $replace['@FIELDS@'] = implode(',', $field_names);
2873 /* Do the replacement */
2874 return str_replace(array_keys($replace), array_values($replace), strftime($string));
2878 * function that generates a json output for an ajax request and ends script
2879 * execution
2881 * @param boolean success whether the ajax request was successfull
2882 * @param string message string containing the html of the message
2883 * @param array extra_data optional - any other data as part of the json request
2885 * @uses header()
2886 * @uses json_encode()
2888 function PMA_ajaxResponse($message, $success = true, $extra_data = array())
2890 $response = array();
2891 if( $success == true ) {
2892 $response['success'] = true;
2893 if ($message instanceof PMA_Message) {
2894 $response['message'] = $message->getDisplay();
2896 else {
2897 $response['message'] = $message;
2900 else {
2901 $response['success'] = false;
2902 if($message instanceof PMA_Message) {
2903 $response['error'] = $message->getDisplay();
2905 else {
2906 $response['error'] = $message;
2910 // If extra_data has been provided, append it to the response array
2911 if( ! empty($extra_data) && count($extra_data) > 0 ) {
2912 $response = array_merge($response, $extra_data);
2915 // Set the Content-Type header to JSON so that jQuery parses the response correctly
2916 if(!isset($GLOBALS['is_header_sent'])) {
2917 header('Cache-Control: no-cache');
2918 header("Content-Type: application/json");
2920 echo json_encode($response);
2921 exit;
2925 * Display the form used to browse anywhere on the local server for the file to import
2927 function PMA_browseUploadFile($max_upload_size) {
2928 $uid = uniqid("");
2929 echo '<label for="radio_import_file">' . __("Browse your computer:") . '</label>';
2930 echo '<div id="upload_form_status" style="display: none;"></div>';
2931 echo '<div id="upload_form_status_info" style="display: none;"></div>';
2932 echo '<input type="file" name="import_file" id="input_import_file" />';
2933 echo PMA_displayMaximumUploadSize($max_upload_size) . "\n";
2934 // some browsers should respect this :)
2935 echo PMA_generateHiddenMaxFileSize($max_upload_size) . "\n";
2939 * Display the form used to select a file to import from the server upload directory
2941 function PMA_selectUploadFile($import_list, $uploaddir) {
2942 echo '<label for="radio_local_import_file">' . sprintf(__("Select from the web server upload directory <b>%s</b>:"), htmlspecialchars(PMA_userDir($uploaddir))) . '</label>';
2943 $extensions = '';
2944 foreach ($import_list as $key => $val) {
2945 if (!empty($extensions)) {
2946 $extensions .= '|';
2948 $extensions .= $val['extension'];
2950 $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@';
2952 $files = PMA_getFileSelectOptions(PMA_userDir($uploaddir), $matcher, (isset($timeout_passed) && $timeout_passed && isset($local_import_file)) ? $local_import_file : '');
2953 if ($files === FALSE) {
2954 PMA_Message::error(__('The directory you set for upload work cannot be reached'))->display();
2955 } elseif (!empty($files)) {
2956 echo "\n";
2957 echo ' <select style="margin: 5px" size="1" name="local_import_file" id="select_local_import_file">' . "\n";
2958 echo ' <option value="">&nbsp;</option>' . "\n";
2959 echo $files;
2960 echo ' </select>' . "\n";
2961 } elseif (empty ($files)) {
2962 echo '<i>' . __('There are no files to upload') . '</i>';
2967 * Build titles and icons for action links
2969 * @return array the action titles
2970 * @uses PMA_getIcon()
2972 function PMA_buildActionTitles() {
2973 $titles = array();
2975 $titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse'), true);
2976 $titles['NoBrowse'] = PMA_getIcon('bd_browse.png', __('Browse'), true);
2977 $titles['Search'] = PMA_getIcon('b_select.png', __('Search'), true);
2978 $titles['NoSearch'] = PMA_getIcon('bd_select.png', __('Search'), true);
2979 $titles['Insert'] = PMA_getIcon('b_insrow.png', __('Insert'), true);
2980 $titles['NoInsert'] = PMA_getIcon('bd_insrow.png', __('Insert'), true);
2981 $titles['Structure'] = PMA_getIcon('b_props.png', __('Structure'), true);
2982 $titles['Drop'] = PMA_getIcon('b_drop.png', __('Drop'), true);
2983 $titles['NoDrop'] = PMA_getIcon('bd_drop.png', __('Drop'), true);
2984 $titles['Empty'] = PMA_getIcon('b_empty.png', __('Empty'), true);
2985 $titles['NoEmpty'] = PMA_getIcon('bd_empty.png', __('Empty'), true);
2986 return $titles;