3 // vim: expandtab sw=4 ts=4 sts=4:
6 * Misc stuff and functions used by almost all the scripts.
7 * Among other things, it contains the advanced authentication work.
11 * Order of sections for common.lib.php:
13 * the include of libraries/defines_mysql.lib.php must be after the connection
14 * to db to get the MySql version
16 * the authentication libraries must be before the connection to db
18 * ... so the required order is:
20 * LABEL_definition_of_functions
21 * - definition of functions
22 * LABEL_variables_init
23 * - init some variables always needed
24 * LABEL_parsing_config_file
25 * - parsing of the config file
26 * LABEL_loading_language_file
27 * - loading language file
31 * - load of mysql extension (if necessary) label_loading_mysql
32 * - loading of an authentication library label_
34 * - authentication work
35 * - load of the libraries/defines_mysql.lib.php library to get the MySQL
40 * For now, avoid warnings of E_STRICT mode
41 * (this must be done before function definitions)
44 if (defined('E_STRICT')) {
45 $old_error_reporting = error_reporting(0);
46 if ($old_error_reporting & E_STRICT
) {
47 error_reporting($old_error_reporting ^ E_STRICT
);
49 error_reporting($old_error_reporting);
51 unset($old_error_reporting);
55 * Avoid object cloning errors
58 @ini_set
('zend.ze1_compatibility_mode',false);
61 * Avoid problems with magic_quotes_runtime
64 @ini_set
('magic_quotes_runtime',false);
67 /******************************************************************************/
68 /* definition of functions LABEL_definition_of_functions */
70 * Removes insecure parts in a path; used before include() or
71 * require() when a part of the path comes from an insecure source
72 * like a cookie or form.
74 * @param string The path to check
76 * @return string The secured path
79 * @author Marc Delisle (lem9@users.sourceforge.net)
81 function PMA_securePath($path)
84 $path = preg_replace('@\.\.*@', '.', $path);
90 * returns count of tables in given db
92 * @param string $db database to count tables for
93 * @return integer count of tables in $db
95 function PMA_getTableCount($db)
97 $tables = PMA_DBI_try_query(
98 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
99 null, PMA_DBI_QUERY_STORE
);
101 $num_tables = PMA_DBI_num_rows($tables);
102 PMA_DBI_free_result($tables);
111 * Converts numbers like 10M into bytes
112 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
113 * (renamed with PMA prefix to avoid double definition when embedded
116 * @param string $size
117 * @return integer $size
119 function PMA_get_real_size($size = 0)
124 $scan['MB'] = 1048576;
125 $scan['Mb'] = 1048576;
126 $scan['M'] = 1048576;
127 $scan['m'] = 1048576;
133 while (list($key) = each($scan)) {
134 if ((strlen($size) > strlen($key))
135 && (substr($size, strlen($size) - strlen($key)) == $key)) {
136 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
141 } // end function PMA_get_real_size()
147 * @uses extension_loaded()
149 * @uses function_exists()
153 * @uses ob_get_contents()
154 * @uses ob_end_clean()
159 * @param string $module name if module to load
160 * @return boolean success loading module
162 function PMA_dl($module)
164 static $dl_allowed = null;
166 if (extension_loaded($module)) {
170 if (null === $dl_allowed) {
171 if (!@ini_get
('safe_mode')
172 && @ini_get
('enable_dl')
173 && @function_exists
('dl')) {
175 phpinfo(INFO_GENERAL
); /* Only general info */
176 $a = strip_tags(ob_get_contents());
178 if (preg_match('@Thread Safety[[:space:]]*enabled@', $a)) {
179 if (preg_match('@Server API[[:space:]]*\(CGI\|CLI\)@', $a)) {
196 /* Once we require PHP >= 4.3, we might use PHP_SHLIB_SUFFIX here */
197 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
198 $module_file = 'php_' . $module . '.dll';
199 } elseif (PHP_OS
=='HP-UX') {
200 $module_file = $module . '.sl';
202 $module_file = $module . '.so';
205 return @dl
($module_file);
209 * merges array recursive like array_merge_recursive() but keyed-values are
210 * always overwritten.
212 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
214 * @see http://php.net/array_merge
215 * @see http://php.net/array_merge_recursive
216 * @uses func_num_args()
217 * @uses func_get_arg()
219 * @uses call_user_func_array()
220 * @param array array to merge
221 * @param array array to merge
223 * @return array merged array
225 function PMA_array_merge_recursive()
227 switch(func_num_args()) {
232 // when does that happen?
233 return func_get_arg(0);
236 $args = func_get_args();
237 if (!is_array($args[0]) ||
!is_array($args[1])) {
240 foreach ($args[1] as $key2 => $value2) {
241 if (isset($args[0][$key2]) && !is_int($key2)) {
242 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
245 // we erase the parent array, otherwise we cannot override a directive that
246 // contains array elements, like this:
247 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
248 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
249 if (is_int($key2) && $key2 == 0) {
252 $args[0][$key2] = $value2;
258 $args = func_get_args();
259 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
261 return call_user_func_array('PMA_array_merge_recursive', $args);
267 * calls $function vor every element in $array recursively
269 * @param array $array array to walk
270 * @param string $function function to call for every array element
272 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
274 foreach ($array as $key => $value) {
275 if (is_array($value)) {
276 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
278 $array[$key] = $function($value);
281 if ($apply_to_keys_also && is_string($key)) {
282 $new_key = $function($key);
283 if ($new_key != $key) {
284 $array[$new_key] = $array[$key];
292 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
294 * checks given given $page against given $whitelist and returns true if valid
295 * it ignores optionaly query paramters in $page (script.php?ignored)
301 * @param string &$page page to check
302 * @param array $whitelist whitelist to check page against
303 * @return boolean whether $page is valid or not (in $whitelist or not)
305 function PMA_checkPageValidity(&$page, $whitelist)
307 if (! isset($page)) {
311 if (in_array($page, $whitelist)) {
313 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
316 $_page = urldecode($page);
317 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
325 * trys to find the value for the given environment vriable name
327 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
330 * @param string $var_name variable name
331 * @return string value of $var or empty string
333 function PMA_getenv($var_name) {
334 if (isset($_SERVER[$var_name])) {
335 return $_SERVER[$var_name];
336 } elseif (isset($_ENV[$var_name])) {
337 return $_ENV[$var_name];
338 } elseif (getenv($var_name)) {
339 return getenv($var_name);
340 } elseif (function_exists('apache_getenv')
341 && apache_getenv($var_name, true)) {
342 return apache_getenv($var_name, true);
349 * include here only libraries which contain only function definitions
355 require_once './libraries/sanitizing.lib.php';
357 * the PMA_Theme class
359 require_once './libraries/Theme.class.php';
361 * the PMA_Theme_Manager class
363 require_once './libraries/Theme_Manager.class.php';
365 * the PMA_Config class
367 require_once './libraries/Config.class.php';
369 * the PMA_Table class
371 require_once './libraries/Table.class.php';
375 if (!defined('PMA_MINIMUM_COMMON')) {
378 * string PMA_getIcon(string $icon)
380 * @uses $GLOBALS['pmaThemeImage']
381 * @param $icon name of icon
382 * @return html img tag
384 function PMA_getIcon($icon, $alternate = '')
386 if ($GLOBALS['cfg']['PropertiesIconic']) {
387 return '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
388 . ' title="' . $alternate . '" alt="' . $alternate . '"'
389 . ' class="icon" width="16" height="16" />';
396 * Displays the maximum size for an upload
398 * @param integer the size
400 * @return string the message
404 function PMA_displayMaximumUploadSize($max_upload_size)
406 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size);
407 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
411 * Generates a hidden field which should indicate to the browser
412 * the maximum size for upload
414 * @param integer the size
416 * @return string the INPUT field
420 function PMA_generateHiddenMaxFileSize($max_size)
422 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
426 * Add slashes before "'" and "\" characters so a value containing them can
427 * be used in a sql comparison.
429 * @param string the string to slash
430 * @param boolean whether the string will be used in a 'LIKE' clause
431 * (it then requires two more escaped sequences) or not
432 * @param boolean whether to treat cr/lfs as escape-worthy entities
433 * (converts \n to \\n, \r to \\r)
435 * @param boolean whether this function is used as part of the
436 * "Create PHP code" dialog
438 * @return string the slashed string
442 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
445 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
447 $a_string = str_replace('\\', '\\\\', $a_string);
451 $a_string = str_replace("\n", '\n', $a_string);
452 $a_string = str_replace("\r", '\r', $a_string);
453 $a_string = str_replace("\t", '\t', $a_string);
457 $a_string = str_replace('\'', '\\\'', $a_string);
459 $a_string = str_replace('\'', '\'\'', $a_string);
463 } // end of the 'PMA_sqlAddslashes()' function
467 * Add slashes before "_" and "%" characters for using them in MySQL
468 * database, table and field names.
469 * Note: This function does not escape backslashes!
471 * @param string the string to escape
473 * @return string the escaped string
477 function PMA_escape_mysql_wildcards($name)
479 $name = str_replace('_', '\\_', $name);
480 $name = str_replace('%', '\\%', $name);
483 } // end of the 'PMA_escape_mysql_wildcards()' function
486 * removes slashes before "_" and "%" characters
487 * Note: This function does not unescape backslashes!
489 * @param string $name the string to escape
490 * @return string the escaped string
493 function PMA_unescape_mysql_wildcards($name)
495 $name = str_replace('\\_', '_', $name);
496 $name = str_replace('\\%', '%', $name);
499 } // end of the 'PMA_unescape_mysql_wildcards()' function
502 * removes quotes (',",`) from a quoted string
504 * checks if the sting is quoted and removes this quotes
506 * @param string $quoted_string string to remove quotes from
507 * @param string $quote type of quote to remove
508 * @return string unqoted string
510 function PMA_unQuote($quoted_string, $quote = null)
514 if (null === $quote) {
522 foreach ($quotes as $quote) {
523 if (substr($quoted_string, 0, 1) === $quote
524 && substr($quoted_string, -1, 1) === $quote ) {
525 $unquoted_string = substr($quoted_string, 1, -1);
526 // replace escaped quotes
527 $unquoted_string = str_replace($quote . $quote, $quote, $unquoted_string);
528 return $unquoted_string;
532 return $quoted_string;
538 * @param mixed pre-parsed SQL structure
540 * @return string the formatted sql
542 * @global array the configuration array
543 * @global boolean whether the current statement is a multiple one or not
547 * @author Robin Johnson <robbat2@users.sourceforge.net>
549 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
553 // Check that we actually have a valid set of parsed data
555 // first check for the SQL parser having hit an error
556 if (PMA_SQP_isError()) {
559 // then check for an array
560 if (!is_array($parsed_sql)) {
561 // We don't so just return the input directly
562 // This is intended to be used for when the SQL Parser is turned off
563 $formatted_sql = '<pre>' . "\n"
564 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ?
$unparsed_sql : $parsed_sql) . "\n"
566 return $formatted_sql;
571 switch ($cfg['SQP']['fmtType']) {
573 if ($unparsed_sql != '') {
574 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
576 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
580 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
583 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
584 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
590 return $formatted_sql;
591 } // end of the "PMA_formatSql()" function
595 * Displays a link to the official MySQL documentation
597 * @param string chapter of "HTML, one page per chapter" documentation
598 * @param string contains name of page/anchor that is being linked
599 * @param bool whether to use big icon (like in left frame)
601 * @return string the html link
605 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
609 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
613 // Fixup for newly used names:
614 $chapter = str_replace('_', '-', strtolower($chapter));
615 $link = str_replace('_', '-', strtolower($link));
617 switch ($cfg['MySQLManualType']) {
619 if (empty($chapter)) {
622 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
625 $url = $cfg['MySQLManualBase'] . '#' . $link;
631 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
640 if (defined('PMA_MYSQL_INT_VERSION')) {
641 if (PMA_MYSQL_INT_VERSION
< 50000) {
643 if (!empty($GLOBALS['mysql_4_1_doc_lang'])) {
644 $lang = $GLOBALS['mysql_4_1_doc_lang'];
646 } elseif (PMA_MYSQL_INT_VERSION
>= 50100) {
648 if (!empty($GLOBALS['mysql_5_1_doc_lang'])) {
649 $lang = $GLOBALS['mysql_5_1_doc_lang'];
651 } elseif (PMA_MYSQL_INT_VERSION
>= 50000) {
653 if (!empty($GLOBALS['mysql_5_0_doc_lang'])) {
654 $lang = $GLOBALS['mysql_5_0_doc_lang'];
658 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/' . $lang . '/' . $link . '.html';
663 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_sqlhelp.png" width="16" height="16" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
664 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
665 return '<a href="' . $url . '" target="mysql_doc"><img class="icon" src="' . $GLOBALS['pmaThemeImage'] . 'b_help.png" width="11" height="11" alt="' . $GLOBALS['strDocu'] . '" title="' . $GLOBALS['strDocu'] . '" /></a>';
667 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
669 } // end of the 'PMA_showMySQLDocu()' function
672 * Displays a hint icon, on mouse over show the hint
674 * @param string the error message
678 function PMA_showHint($hint_message)
680 //return '<img class="lightbulb" src="' . $GLOBALS['pmaThemeImage'] . 'b_tipp.png" width="16" height="16" border="0" alt="' . $hint_message . '" title="' . $hint_message . '" align="middle" onclick="alert(\'' . PMA_jsFormat($hint_message, false) . '\');" />';
681 return '<img class="lightbulb" src="' . $GLOBALS['pmaThemeImage'] . 'b_tipp.png" width="16" height="16" alt="Tip" title="Tip" onmouseover="pmaTooltip(\'' . PMA_jsFormat($hint_message, false) . '\'); return false;" onmouseout="swapTooltip(\'default\'); return false;" />';
685 * Displays a MySQL error message in the right frame.
687 * @param string the error message
688 * @param string the sql query that failed
689 * @param boolean whether to show a "modify" link or not
690 * @param string the "back" link url (full path is not required)
691 * @param boolean EXIT the page?
693 * @global array the configuration array
697 function PMA_mysqlDie($error_message = '', $the_query = '',
698 $is_modify_link = true, $back_url = '',
701 global $cfg, $table, $db, $sql_query;
704 * start http output, display html headers
706 require_once './libraries/header.inc.php';
708 if (!$error_message) {
709 $error_message = PMA_DBI_getError();
711 if (!$the_query && !empty($GLOBALS['sql_query'])) {
712 $the_query = $GLOBALS['sql_query'];
715 // --- Added to solve bug #641765
716 // Robbat2 - 12 January 2003, 9:46PM
717 // Revised, Robbat2 - 13 January 2003, 2:59PM
718 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
719 $formatted_sql = htmlspecialchars($the_query);
720 } elseif (empty($the_query) ||
trim($the_query) == '') {
723 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
726 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
727 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
728 // if the config password is wrong, or the MySQL server does not
729 // respond, do not show the query that would reveal the
731 if (!empty($the_query) && !strstr($the_query, 'connect')) {
732 // --- Added to solve bug #641765
733 // Robbat2 - 12 January 2003, 9:46PM
734 // Revised, Robbat2 - 13 January 2003, 2:59PM
735 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
736 echo PMA_SQP_getErrorString() . "\n";
737 echo '<br />' . "\n";
740 // modified to show me the help on sql errors (Michael Keck)
741 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
742 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
743 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
745 if ($is_modify_link && isset($db)) {
747 $doedit_goto = '<a href="tbl_sql.php?' . PMA_generate_common_url($db, $table) . '&sql_query=' . urlencode($the_query) . '&show_query=1">';
749 $doedit_goto = '<a href="db_sql.php?' . PMA_generate_common_url($db) . '&sql_query=' . urlencode($the_query) . '&show_query=1">';
751 if ($GLOBALS['cfg']['PropertiesIconic']) {
753 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
757 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
763 .' ' . $formatted_sql . "\n"
767 $tmp_mysql_error = ''; // for saving the original $error_message
768 if (!empty($error_message)) {
769 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
770 $error_message = htmlspecialchars($error_message);
771 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
773 // modified to show me the help on error-returns (Michael Keck)
774 // (now error-messages-server)
776 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
777 . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server')
781 // The error message will be displayed within a CODE segment.
782 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
784 // Replace all non-single blanks with their HTML-counterpart
785 $error_message = str_replace(' ', ' ', $error_message);
786 // Replace TAB-characters with their HTML-counterpart
787 $error_message = str_replace("\t", ' ', $error_message);
788 // Replace linebreaks
789 $error_message = nl2br($error_message);
792 . $error_message . "\n"
793 . '</code><br />' . "\n";
795 // feature request #1036254:
796 // Add a link by MySQL-Error #1062 - Duplicate entry
797 // 2004-10-20 by mkkeck
798 // 2005-01-17 modified by mkkeck bugfix
799 if (substr($error_message, 1, 4) == '1062') {
800 // get the duplicate entry
804 * @todo what would be the best delimiter, while avoiding special
805 * characters that can become high-ascii after editing, depending
806 * upon which editor is used by the developer?
808 $error_table = array();
809 if (preg_match('@ALTER\s*TABLE\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
810 $error_table = $error_table[1];
811 } elseif (preg_match('@INSERT\s*INTO\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
812 $error_table = $error_table[1];
813 } elseif (preg_match('@UPDATE\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
814 $error_table = $error_table[1];
815 } elseif (preg_match('@INSERT\s*\`([^\`]+)\`@iu', $the_query, $error_table)) {
816 $error_table = $error_table[1];
820 $error_fields = array();
821 if (preg_match('@\(([^\)]+)\)@i', $the_query, $error_fields)) {
822 $error_fields = explode(',', $error_fields[1]);
823 } elseif (preg_match('@(`[^`]+`)\s*=@i', $the_query, $error_fields)) {
824 $error_fields = explode(',', $error_fields[1]);
826 if (is_array($error_table) ||
is_array($error_fields)) {
829 $duplicate_value = array();
830 preg_match('@\'([^\']+)\'@i', $tmp_mysql_error, $duplicate_value);
831 $duplicate_value = $duplicate_value[1];
835 FROM ' . PMA_backquote($error_table) . '
836 WHERE CONCAT_WS("-", ' . implode(', ', $error_fields) . ')
837 = "' . PMA_sqlAddslashes($duplicate_value) . '"
838 ORDER BY ' . implode(', ', $error_fields);
839 unset($error_table, $error_fields, $duplicate_value);
841 echo ' <form method="post" action="import.php" style="padding: 0; margin: 0">' ."\n"
842 .' <input type="hidden" name="sql_query" value="' . htmlentities($sql) . '" />' . "\n"
843 .' ' . PMA_generate_common_hidden_inputs($db, $table) . "\n"
844 .' <input type="submit" name="submit" value="' . $GLOBALS['strBrowse'] . '" />' . "\n"
848 } // end of show duplicate entry
851 echo '<fieldset class="tblFooters">';
853 if (!empty($back_url) && $exit) {
854 $goto_back_url='<a href="' . (strstr($back_url, '?') ?
$back_url . '&no_history=true' : $back_url . '?no_history=true') . '">';
855 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
857 echo ' </fieldset>' . "\n\n";
860 * display footer and exit
862 require_once './libraries/footer.inc.php';
864 } // end of the 'PMA_mysqlDie()' function
867 * Returns a string formatted with CONVERT ... USING
868 * if MySQL supports it
870 * @param string the string itself
871 * @param string the mode: quoted or unquoted (this one by default)
873 * @return the formatted string
877 function PMA_convert_using($string, $mode='unquoted')
879 if ($mode == 'quoted') {
880 $possible_quote = "'";
882 $possible_quote = "";
885 if (PMA_MYSQL_INT_VERSION
>= 40100) {
886 list($conn_charset) = explode('_', $GLOBALS['collation_connection']);
887 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $conn_charset . ")";
889 $converted_string = $possible_quote . $string . $possible_quote;
891 return $converted_string;
895 * Send HTTP header, taking IIS limits into account (600 seems ok)
897 * @param string $uri the header to send
898 * @return boolean always true
900 function PMA_sendHeaderLocation($uri)
902 if (PMA_IS_IIS
&& strlen($uri) > 600) {
904 echo '<html><head><title>- - -</title>' . "\n";
905 echo '<meta http-equiv="expires" content="0">' . "\n";
906 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
907 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
908 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
909 echo '<script type="text/javascript" language="javascript">' . "\n";
910 echo '//<![CDATA[' . "\n";
911 echo 'setTimeout ("window.location = unescape(\'"' . $uri . '"\')",2000); </script>' . "\n";
913 echo '</head>' . "\n";
914 echo '<body>' . "\n";
915 echo '<script type="text/javascript" language="javascript">' . "\n";
916 echo '//<![CDATA[' . "\n";
917 echo 'document.write (\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
919 echo '</script></body></html>' . "\n";
923 if (strpos($uri, '?') === false) {
924 header('Location: ' . $uri . '?' . SID
);
926 $separator = PMA_get_arg_separator();
927 header('Location: ' . $uri . $separator . SID
);
930 session_write_close();
931 if (headers_sent()) {
932 if (function_exists(debug_print_backtrace
)) {
934 debug_print_backtrace();
937 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
939 // bug #1523784: IE6 does not like 'Refresh: 0', it
940 // results in a blank page
941 // but we need it when coming from the cookie login panel)
942 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
943 header('Refresh: 0; ' . $uri);
945 header('Location: ' . $uri);
952 * returns array with tables of given db with extended infomation and grouped
954 * @uses $GLOBALS['cfg']['LeftFrameTableSeparator']
955 * @uses $GLOBALS['cfg']['LeftFrameTableLevel']
956 * @uses $GLOBALS['cfg']['ShowTooltipAliasTB']
957 * @uses $GLOBALS['cfg']['NaturalOrder']
958 * @uses PMA_backquote()
964 * @param string $db name of db
965 * return array (rekursive) grouped table list
967 function PMA_getTableList($db, $tables = null)
969 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
971 if ( null === $tables ) {
972 $tables = PMA_DBI_get_tables_full($db);
973 if ($GLOBALS['cfg']['NaturalOrder']) {
974 uksort($tables, 'strnatcasecmp');
978 if (count($tables) < 1) {
989 $table_groups = array();
991 foreach ($tables as $table_name => $table) {
993 // check for correct row count
994 if (null === $table['Rows']) {
995 // Do not check exact row count here,
996 // if row count is invalid possibly the table is defect
997 // and this would break left frame;
998 // but we can check row count if this is a view,
999 // since PMA_Table::countRecords() returns a limited row count
1002 // set this because PMA_Table::countRecords() can use it
1003 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
1006 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name'],
1011 // in $group we save the reference to the place in $table_groups
1012 // where to store the table info
1013 if ($GLOBALS['cfg']['LeftFrameDBTree']
1014 && $sep && strstr($table_name, $sep))
1016 $parts = explode($sep, $table_name);
1018 $group =& $table_groups;
1020 $group_name_full = '';
1021 while ($i < count($parts) - 1
1022 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
1023 $group_name = $parts[$i] . $sep;
1024 $group_name_full .= $group_name;
1026 if (!isset($group[$group_name])) {
1027 $group[$group_name] = array();
1028 $group[$group_name]['is' . $sep . 'group'] = true;
1029 $group[$group_name]['tab' . $sep . 'count'] = 1;
1030 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
1031 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
1032 $table = $group[$group_name];
1033 $group[$group_name] = array();
1034 $group[$group_name][$group_name] = $table;
1036 $group[$group_name]['is' . $sep . 'group'] = true;
1037 $group[$group_name]['tab' . $sep . 'count'] = 1;
1038 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
1040 $group[$group_name]['tab' . $sep . 'count']++
;
1042 $group =& $group[$group_name];
1046 if (!isset($table_groups[$table_name])) {
1047 $table_groups[$table_name] = array();
1049 $group =& $table_groups;
1053 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
1054 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
1055 // switch tooltip and name
1056 $table['Comment'] = $table['Name'];
1057 $table['disp_name'] = $table['Comment'];
1059 $table['disp_name'] = $table['Name'];
1062 $group[$table_name] = array_merge($default, $table);
1065 return $table_groups;
1068 /* ----------------------- Set of misc functions ----------------------- */
1072 * Adds backquotes on both sides of a database, table or field name.
1073 * and escapes backquotes inside the name with another backquote
1076 * echo PMA_backquote('owner`s db'); // `owner``s db`
1079 * @param mixed $a_name the database, table or field name to "backquote"
1081 * @param boolean $do_it a flag to bypass this function (used by dump
1083 * @return mixed the "backquoted" database, table or field name if the
1084 * current MySQL release is >= 3.23.6, the original one
1088 function PMA_backquote($a_name, $do_it = true)
1094 if (is_array($a_name)) {
1096 foreach ($a_name as $key => $val) {
1097 $result[$key] = PMA_backquote($val);
1102 // '0' is also empty for php :-(
1103 if (strlen($a_name) && $a_name != '*') {
1104 return '`' . str_replace('`', '``', $a_name) . '`';
1108 } // end of the 'PMA_backquote()' function
1112 * Format a string so it can be a string inside JavaScript code inside an
1113 * eventhandler (onclick, onchange, on..., ).
1114 * This function is used to displays a javascript confirmation box for
1115 * "DROP/DELETE/ALTER" queries.
1117 * @uses PMA_escapeJsString()
1118 * @uses PMA_backquote()
1120 * @uses htmlspecialchars()
1121 * @uses str_replace()
1122 * @param string $a_string the string to format
1123 * @param boolean $add_backquotes whether to add backquotes to the string or not
1125 * @return string the formated string
1129 function PMA_jsFormat($a_string = '', $add_backquotes = true)
1131 if (is_string($a_string)) {
1132 $a_string = htmlspecialchars($a_string);
1133 $a_string = PMA_escapeJsString($a_string);
1135 * @todo what is this good for?
1137 $a_string = str_replace('#', '\\#', $a_string);
1140 return (($add_backquotes) ?
PMA_backquote($a_string) : $a_string);
1141 } // end of the 'PMA_jsFormat()' function
1144 * escapes a string to be inserted as string a JavaScript block
1145 * enclosed by <![CDATA[ ... ]]>
1146 * this requires only to escape ' with \' and end of script block
1149 * @param string $string the string to be escaped
1150 * @return string the escaped string
1152 function PMA_escapeJsString($string)
1154 return strtr($string, array(
1159 '</script' => '<\' + \'script'));
1163 * Defines the <CR><LF> value depending on the user OS.
1165 * @return string the <CR><LF> value to use
1169 function PMA_whichCrlf()
1173 // The 'PMA_USR_OS' constant is defined in "./libraries/defines.lib.php"
1175 if (PMA_USR_OS
== 'Win') {
1184 } // end of the 'PMA_whichCrlf()' function
1187 * Reloads navigation if needed.
1189 * @global mixed configuration
1190 * @global bool whether to reload
1194 function PMA_reloadNavigation()
1198 // Reloads the navigation frame via JavaScript if required
1199 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
1201 $reload_url = './navigation.php?' . PMA_generate_common_url((isset($GLOBALS['db']) ?
$GLOBALS['db'] : ''), '', '&');
1203 <script type
="text/javascript" language
="javascript">
1205 if (typeof(window
.parent
) != 'undefined'
1206 && typeof(window
.parent
.frame_navigation
) != 'undefined') {
1207 window
.parent
.goTo('<?php echo $reload_url; ?>');
1212 unset($GLOBALS['reload']);
1217 * Displays a message at the top of the "main" (right) frame
1219 * @param string the message to display
1221 * @global array the configuration array
1225 function PMA_showMessage($message)
1229 // Sanitizes $message
1230 $message = PMA_sanitize($message);
1232 // Corrects the tooltip text via JS if required
1233 if ( isset($GLOBALS['table']) && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1234 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
1236 $tbl_status = PMA_DBI_fetch_assoc($result);
1237 $tooltip = (empty($tbl_status['Comment']))
1239 : $tbl_status['Comment'] . ' ';
1240 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
1241 PMA_DBI_free_result($result);
1242 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1245 <script type
="text/javascript" language
="javascript">
1247 window
.parent
.updateTableTitle('<?php echo $uni_tbl; ?>', '<?php echo PMA_jsFormat($tooltip, false); ?>');
1252 } // end if ... elseif
1254 // Checks if the table needs to be repaired after a TRUNCATE query.
1255 if (isset($GLOBALS['table']) && isset($GLOBALS['sql_query'])
1256 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1257 if (!isset($tbl_status)) {
1258 $result = @PMA_DBI_try_query
('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
1260 $tbl_status = PMA_DBI_fetch_assoc($result);
1261 PMA_DBI_free_result($result);
1264 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
1265 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1271 <div align
="<?php echo $GLOBALS['cell_align_left']; ?>">
1273 if (!empty($GLOBALS['show_error_header'])) {
1276 <h1
><?php
echo $GLOBALS['strError']; ?
></h1
>
1281 if (isset($GLOBALS['special_message'])) {
1282 echo PMA_sanitize($GLOBALS['special_message']);
1283 unset($GLOBALS['special_message']);
1286 if (!empty($GLOBALS['show_error_header'])) {
1290 if ($cfg['ShowSQL'] == true
1291 && (!empty($GLOBALS['sql_query']) ||
!empty($GLOBALS['display_query']))) {
1292 if (!empty($GLOBALS['display_query'])) {
1293 $local_query = $GLOBALS['display_query'];
1295 if ($cfg['SQP']['fmtType'] == 'none' && !empty($GLOBALS['unparsed_sql'])) {
1296 $local_query = $GLOBALS['unparsed_sql'];
1298 $local_query = $GLOBALS['sql_query'];
1301 // Basic url query part
1302 $url_qpart = '?' . PMA_generate_common_url(isset($GLOBALS['db']) ?
$GLOBALS['db'] : '', isset($GLOBALS['table']) ?
$GLOBALS['table'] : '');
1304 // Html format the query to be displayed
1305 // The nl2br function isn't used because its result isn't a valid
1306 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
1307 // If we want to show some sql code it is easiest to create it here
1308 /* SQL-Parser-Analyzer */
1310 if (!empty($GLOBALS['show_as_php'])) {
1311 $new_line = '\'<br />' . "\n" . ' . \' ';
1313 if (isset($new_line)) {
1314 /* SQL-Parser-Analyzer */
1315 $query_base = PMA_sqlAddslashes(htmlspecialchars($local_query), false, false, true);
1316 /* SQL-Parser-Analyzer */
1317 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
1319 $query_base = htmlspecialchars($local_query);
1322 // Parse SQL if needed
1323 if (isset($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1324 $parsed_sql = $GLOBALS['parsed_sql'];
1326 // when the query is large (for example an INSERT of binary
1327 // data), the parser chokes; so avoid parsing the query
1328 if (strlen($query_base) < 1000) {
1329 $parsed_sql = PMA_SQP_parse($query_base);
1334 if (isset($parsed_sql)) {
1335 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1338 // Here we append the LIMIT added for navigation, to
1339 // enable its display. Adding it higher in the code
1340 // to $local_query would create a problem when
1341 // using the Refresh or Edit links.
1343 // Only append it on SELECTs.
1346 * @todo what would be the best to do when someone hits Refresh:
1347 * use the current LIMITs ?
1350 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1351 && isset($GLOBALS['sql_limit_to_append'])) {
1352 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1353 // Need to reparse query
1354 $parsed_sql = PMA_SQP_parse($query_base);
1357 if (!empty($GLOBALS['show_as_php'])) {
1358 $query_base = '$sql = \'' . $query_base;
1359 } elseif (!empty($GLOBALS['validatequery'])) {
1360 $query_base = PMA_validateSQL($query_base);
1362 if (isset($parsed_sql)) {
1363 $query_base = PMA_formatSql($parsed_sql, $query_base);
1367 // Prepares links that may be displayed to edit/explain the query
1368 // (don't go to default pages, we must go to the page
1369 // where the query box is available)
1370 // (also, I don't see why we should check the goto variable)
1372 //if (!isset($GLOBALS['goto'])) {
1373 //$edit_target = (isset($GLOBALS['table'])) ? $cfg['DefaultTabTable'] : $cfg['DefaultTabDatabase'];
1374 $edit_target = isset($GLOBALS['db']) ?
(isset($GLOBALS['table']) ?
'tbl_sql.php' : 'db_sql.php') : 'server_sql.php';
1375 //} elseif ($GLOBALS['goto'] != 'main.php') {
1376 // $edit_target = $GLOBALS['goto'];
1378 // $edit_target = '';
1381 if (isset($cfg['SQLQuery']['Edit'])
1382 && ($cfg['SQLQuery']['Edit'] == true)
1383 && (!empty($edit_target))) {
1385 if ($cfg['EditInWindow'] == true) {
1386 $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($local_query, false) . '\'); return false;';
1391 $edit_link = $edit_target
1393 . '&sql_query=' . urlencode($local_query)
1394 . '&show_query=1#querybox';
1395 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1400 // Want to have the query explained (Mike Beck 2002-05-22)
1401 // but only explain a SELECT (that has not been explained)
1402 /* SQL-Parser-Analyzer */
1403 if (isset($cfg['SQLQuery']['Explain'])
1404 && $cfg['SQLQuery']['Explain'] == true) {
1406 // Detect if we are validating as well
1407 // To preserve the validate uRL data
1408 if (!empty($GLOBALS['validatequery'])) {
1409 $explain_link_validate = '&validatequery=1';
1411 $explain_link_validate = '';
1414 $explain_link = 'import.php'
1416 . $explain_link_validate
1417 . '&sql_query=';
1419 if (preg_match('@^SELECT[[:space:]]+@i', $local_query)) {
1420 $explain_link .= urlencode('EXPLAIN ' . $local_query);
1421 $message = $GLOBALS['strExplain'];
1422 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $local_query)) {
1423 $explain_link .= urlencode(substr($local_query, 8));
1424 $message = $GLOBALS['strNoExplain'];
1428 if (!empty($explain_link)) {
1429 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1435 // Also we would like to get the SQL formed in some nice
1436 // php-code (Mike Beck 2002-05-22)
1437 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1438 && $cfg['SQLQuery']['ShowAsPHP'] == true) {
1439 $php_link = 'import.php'
1441 . '&show_query=1'
1442 . '&sql_query=' . urlencode($local_query)
1443 . '&show_as_php=';
1445 if (!empty($GLOBALS['show_as_php'])) {
1447 $message = $GLOBALS['strNoPhp'];
1450 $message = $GLOBALS['strPhp'];
1452 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1454 if (isset($GLOBALS['show_as_php']) && $GLOBALS['show_as_php'] == '1') {
1458 . '&show_query=1'
1459 . '&sql_query=' . urlencode($local_query);
1460 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1468 if (isset($cfg['SQLQuery']['Refresh'])
1469 && $cfg['SQLQuery']['Refresh']
1470 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $local_query)) {
1472 $refresh_link = 'import.php'
1474 . '&show_query=1'
1475 . (isset($_GET['pos']) ?
'&pos=' . $_GET['pos'] : '')
1476 . '&sql_query=' . urlencode($local_query);
1477 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1482 if (isset($cfg['SQLValidator']['use'])
1483 && $cfg['SQLValidator']['use'] == true
1484 && isset($cfg['SQLQuery']['Validate'])
1485 && $cfg['SQLQuery']['Validate'] == true) {
1486 $validate_link = 'import.php'
1488 . '&show_query=1'
1489 . '&sql_query=' . urlencode($local_query)
1490 . '&validatequery=';
1491 if (!empty($GLOBALS['validatequery'])) {
1492 $validate_link .= '0';
1493 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1495 $validate_link .= '1';
1496 $validate_message = $GLOBALS['strValidateSQL'] ;
1498 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1500 $validate_link = '';
1502 unset($local_query);
1504 // Displays the message
1505 echo '<fieldset class="">' . "\n";
1506 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1507 echo ' ' . $query_base;
1509 //Clean up the end of the PHP
1510 if (!empty($GLOBALS['show_as_php'])) {
1513 echo '</fieldset>' . "\n";
1515 if (!empty($edit_target)) {
1516 echo '<fieldset class="tblFooters">';
1517 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1524 } // end of the 'PMA_showMessage()' function
1528 * Formats $value to byte view
1530 * @param double the value to format
1531 * @param integer the sensitiveness
1532 * @param integer the number of decimals to retain
1534 * @return array the formatted value and its unit
1539 * @version 1.2 - 18 July 2002
1541 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1543 $dh = pow(10, $comma);
1544 $li = pow(10, $limes);
1545 $return_value = $value;
1546 $unit = $GLOBALS['byteUnits'][0];
1548 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1549 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * pow(10, $ex)) {
1550 // use 1024.0 to avoid integer overflow on 64-bit machines
1551 $value = round($value / (pow(1024.0, $d) / $dh)) /$dh;
1552 $unit = $GLOBALS['byteUnits'][$d];
1557 if ($unit != $GLOBALS['byteUnits'][0]) {
1558 $return_value = number_format($value, $comma, $GLOBALS['number_decimal_separator'], $GLOBALS['number_thousands_separator']);
1560 $return_value = number_format($value, 0, $GLOBALS['number_decimal_separator'], $GLOBALS['number_thousands_separator']);
1563 return array($return_value, $unit);
1564 } // end of the 'PMA_formatByteDown' function
1567 * Formats $value to the given length and appends SI prefixes
1568 * $comma is not substracted from the length
1569 * with a $length of 0 no truncation occurs, number is only formated
1570 * to the current locale
1572 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1573 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1574 * echo PMA_formatNumber(-0.003, 6); // -3 m
1575 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1576 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1577 * echo PMA_formatNumber(0, 6); // 0
1579 * @param double $value the value to format
1580 * @param integer $length the max length
1581 * @param integer $comma the number of decimals to retain
1582 * @param boolean $only_down do not reformat numbers below 1
1584 * @return string the formatted value and its unit
1588 * @author staybyte, sebastian mendel
1589 * @version 1.1.0 - 2005-10-27
1591 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1593 if ($length === 0) {
1594 return number_format($value,
1596 $GLOBALS['number_decimal_separator'],
1597 $GLOBALS['number_thousands_separator']);
1600 // this units needs no translation, ISO
1621 // we need at least 3 digits to be displayed
1622 if (3 > $length +
$comma) {
1623 $length = 3 - $comma;
1626 // check for negativ value to retain sign
1629 $value = abs($value);
1634 $dh = pow(10, $comma);
1635 $li = pow(10, $length);
1639 for ($d = 8; $d >= 0; $d--) {
1640 if (isset($units[$d]) && $value >= $li * pow(1000.0, $d-1)) {
1641 $value = round($value / (pow(1000.0, $d) / $dh)) /$dh;
1646 } elseif (!$only_down && (float) $value !== 0.0) {
1647 for ($d = -8; $d <= 8; $d++
) {
1648 if (isset($units[$d]) && $value <= $li * pow(1000.0, $d-1)) {
1649 $value = round($value / (pow(1000.0, $d) / $dh)) /$dh;
1654 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1656 $value = number_format($value,
1658 $GLOBALS['number_decimal_separator'],
1659 $GLOBALS['number_thousands_separator']);
1661 return $sign . $value . ' ' . $unit;
1662 } // end of the 'PMA_formatNumber' function
1665 * Extracts ENUM / SET options from a type definition string
1667 * @param string The column type definition
1669 * @return array The options or
1670 * boolean false in case of an error.
1674 function PMA_getEnumSetOptions($type_def)
1676 $open = strpos($type_def, '(');
1677 $close = strrpos($type_def, ')');
1678 if (!$open ||
!$close) {
1681 $options = substr($type_def, $open +
2, $close - $open - 3);
1682 $options = explode('\',\'', $options);
1684 } // end of the 'PMA_getEnumSetOptions' function
1687 * Writes localised date
1689 * @param string the current timestamp
1691 * @return string the formatted date
1695 function PMA_localisedDate($timestamp = -1, $format = '')
1697 global $datefmt, $month, $day_of_week;
1699 if ($format == '') {
1703 if ($timestamp == -1) {
1704 $timestamp = time();
1707 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1708 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1710 return strftime($date, $timestamp);
1711 } // end of the 'PMA_localisedDate()' function
1715 * returns a tab for tabbed navigation.
1716 * If the variables $link and $args ar left empty, an inactive tab is created
1718 * @uses array_merge()
1720 * $GLOBALS['strEmpty']
1721 * $GLOBALS['strDrop']
1722 * $GLOBALS['active_page']
1723 * $GLOBALS['PHP_SELF']
1725 * PMA_generate_common_url()
1726 * $GLOBALS['url_query']
1728 * $GLOBALS['cfg']['MainPageIconic']
1729 * $GLOBALS['pmaThemeImage']
1733 * @param array $tab array with all options
1734 * @return string html code for one tab, a link if valid otherwise a span
1737 function PMA_getTab($tab)
1750 $tab = array_merge($defaults, $tab);
1752 // determine additionnal style-class
1753 if (empty($tab['class'])) {
1754 if ($tab['text'] == $GLOBALS['strEmpty']
1755 ||
$tab['text'] == $GLOBALS['strDrop']) {
1756 $tab['class'] = 'caution';
1757 } elseif (!empty($tab['active'])
1758 ||
(isset($GLOBALS['active_page'])
1759 && $GLOBALS['active_page'] == $tab['link'])
1760 ||
basename(PMA_getenv('PHP_SELF')) == $tab['link'])
1762 $tab['class'] = 'active';
1767 if (!empty($tab['link'])) {
1768 $tab['link'] = htmlentities($tab['link']);
1769 $tab['link'] = $tab['link'] . $tab['sep']
1770 .(empty($GLOBALS['url_query']) ?
1771 PMA_generate_common_url() : $GLOBALS['url_query']);
1772 if (!empty($tab['args'])) {
1773 foreach ($tab['args'] as $param => $value) {
1774 $tab['link'] .= '&' . urlencode($param) . '='
1775 . urlencode($value);
1780 // display icon, even if iconic is disabled but the link-text is missing
1781 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1782 && isset($tab['icon'])) {
1783 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1784 .'%1$s" width="16" height="16" alt="%2$s" />%2$s';
1785 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1787 // check to not display an empty link-text
1788 elseif (empty($tab['text'])) {
1790 trigger_error('empty linktext in function ' . __FUNCTION__
. '()',
1794 if (!empty($tab['link'])) {
1795 $out = '<a class="tab' . htmlentities($tab['class']) . '"'
1796 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1797 . $tab['text'] . '</a>';
1799 $out = '<span class="tab' . htmlentities($tab['class']) . '">'
1800 . $tab['text'] . '</span>';
1804 } // end of the 'PMA_getTab()' function
1807 * returns html-code for a tab navigation
1809 * @uses PMA_getTab()
1810 * @uses htmlentities()
1811 * @param array $tabs one element per tab
1812 * @param string $tag_id id used for the html-tag
1813 * @return string html-code for tab-navigation
1815 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1818 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1819 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1821 foreach ($tabs as $tab) {
1822 $tab_navigation .= '<li>' . PMA_getTab($tab) . '</li>' . "\n";
1827 .'<div class="clearfloat"></div>'
1830 return $tab_navigation;
1835 * Displays a link, or a button if the link's URL is too large, to
1836 * accommodate some browsers' limitations
1838 * @param string the URL
1839 * @param string the link message
1840 * @param mixed $tag_params string: js confirmation
1841 * array: additional tag params (f.e. style="")
1842 * @param boolean $new_form we set this to false when we are already in
1843 * a form, to avoid generating nested forms
1845 * @return string the results to be echoed or saved in an array
1847 function PMA_linkOrButton($url, $message, $tag_params = array(),
1848 $new_form = true, $strip_img = false, $target = '')
1850 if (! is_array($tag_params)) {
1852 $tag_params = array();
1854 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1858 if (! empty($target)) {
1859 $tag_params['target'] = htmlentities($target);
1862 $tag_params_strings = array();
1863 foreach ($tag_params as $par_name => $par_value) {
1864 // htmlspecialchars() only on non javascript
1865 $par_value = substr($par_name, 0, 2) == 'on'
1867 : htmlspecialchars($par_value);
1868 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
1871 // previously the limit was set to 2047, it seems 1000 is better
1872 if (strlen($url) <= 1000) {
1873 // no whitespace within an <a> else Safari will make it part of the link
1874 $ret = "\n" . '<a href="' . $url . '" '
1875 . implode(' ', $tag_params_strings) . '>'
1876 . $message . '</a>' . "\n";
1878 // no spaces (linebreaks) at all
1879 // or after the hidden fields
1880 // IE will display them all
1882 // add class=link to submit button
1883 if (empty($tag_params['class'])) {
1884 $tag_params['class'] = 'link';
1887 // decode encoded url separators
1888 $separator = PMA_get_arg_separator();
1889 // on most places separator is still hard coded ...
1890 if ($separator !== '&') {
1891 // ... so always replace & with $separator
1892 $url = str_replace(htmlentities('&'), $separator, $url);
1893 $url = str_replace('&', $separator, $url);
1895 $url = str_replace(htmlentities($separator), $separator, $url);
1898 $url_parts = parse_url($url);
1899 $query_parts = explode($separator, $url_parts['query']);
1901 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
1902 . ' method="post"' . $target . ' style="display: inline;">';
1904 $subname_close = '';
1907 $query_parts[] = 'redirect=' . $url_parts['path'];
1908 if (empty($GLOBALS['subform_counter'])) {
1909 $GLOBALS['subform_counter'] = 0;
1911 $GLOBALS['subform_counter']++
;
1913 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
1914 $subname_close = ']';
1915 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
1917 foreach ($query_parts as $query_pair) {
1918 list($eachvar, $eachval) = explode('=', $query_pair);
1919 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
1920 . $subname_close . '" value="'
1921 . htmlspecialchars(urldecode($eachval)) . '" />';
1924 if (stristr($message, '<img')) {
1926 $message = trim(strip_tags($message));
1927 $ret .= '<input type="submit"' . $submit_name . ' '
1928 . implode(' ', $tag_params_strings)
1929 . ' value="' . htmlspecialchars($message) . '" />';
1931 $ret .= '<input type="image"' . $submit_name . ' '
1932 . implode(' ', $tag_params_strings)
1933 . ' src="' . preg_replace(
1934 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
1935 . ' value="' . htmlspecialchars(
1936 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
1941 $message = trim(strip_tags($message));
1942 $ret .= '<input type="submit"' . $submit_name . ' '
1943 . implode(' ', $tag_params_strings)
1944 . ' value="' . htmlspecialchars($message) . '" />';
1949 } // end if... else...
1952 } // end of the 'PMA_linkOrButton()' function
1956 * Returns a given timespan value in a readable format.
1958 * @param int the timespan
1960 * @return string the formatted value
1962 function PMA_timespanFormat($seconds)
1964 $return_string = '';
1965 $days = floor($seconds / 86400);
1967 $seconds -= $days * 86400;
1969 $hours = floor($seconds / 3600);
1970 if ($days > 0 ||
$hours > 0) {
1971 $seconds -= $hours * 3600;
1973 $minutes = floor($seconds / 60);
1974 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
1975 $seconds -= $minutes * 60;
1977 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
1981 * Takes a string and outputs each character on a line for itself. Used
1982 * mainly for horizontalflipped display mode.
1983 * Takes care of special html-characters.
1984 * Fulfills todo-item
1985 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
1987 * @param string The string
1988 * @param string The Separator (defaults to "<br />\n")
1991 * @author Garvin Hicking <me@supergarv.de>
1992 * @return string The flipped string
1994 function PMA_flipstring($string, $Separator = "<br />\n")
1996 $format_string = '';
1999 for ($i = 0; $i < strlen($string); $i++
) {
2000 $char = $string{$i};
2004 $format_string .= $charbuff;
2007 } elseif (!empty($charbuff)) {
2009 } elseif ($char == ';' && !empty($charbuff)) {
2010 $format_string .= $charbuff;
2014 $format_string .= $char;
2018 if ($append && ($i != strlen($string))) {
2019 $format_string .= $Separator;
2023 return $format_string;
2028 * Function added to avoid path disclosures.
2029 * Called by each script that needs parameters, it displays
2030 * an error message and, by default, stops the execution.
2032 * Not sure we could use a strMissingParameter message here,
2033 * would have to check if the error message file is always available
2035 * @param array The names of the parameters needed by the calling
2037 * @param boolean Stop the execution?
2038 * (Set this manually to false in the calling script
2039 * until you know all needed parameters to check).
2040 * @param boolean Whether to include this list in checking for special params.
2041 * @global string path to current script
2042 * @global boolean flag whether any special variable was required
2045 * @author Marc Delisle (lem9@users.sourceforge.net)
2047 function PMA_checkParameters($params, $die = true, $request = true)
2049 global $PHP_SELF, $checked_special;
2051 if (!isset($checked_special)) {
2052 $checked_special = false;
2055 $reported_script_name = basename($PHP_SELF);
2056 $found_error = false;
2057 $error_message = '';
2059 foreach ($params as $param) {
2060 if ($request && $param != 'db' && $param != 'table') {
2061 $checked_special = true;
2064 if (!isset($GLOBALS[$param])) {
2065 $error_message .= $reported_script_name . ': Missing parameter: ' . $param . ' <a href="./Documentation.html#faqmissingparameters" target="documentation"> (FAQ 2.8)</a><br />';
2066 $found_error = true;
2071 * display html meta tags
2073 require_once './libraries/header_meta_style.inc.php';
2074 echo '</head><body><p>' . $error_message . '</p></body></html>';
2082 * Function to generate unique condition for specified row.
2084 * @uses PMA_MYSQL_INT_VERSION
2085 * @uses $GLOBALS['analyzed_sql'][0]
2086 * @uses PMA_DBI_field_flags()
2087 * @uses PMA_backquote()
2088 * @uses PMA_sqlAddslashes()
2091 * @uses preg_replace()
2092 * @param resource $handle current query result
2093 * @param integer $fields_cnt number of fields
2094 * @param array $fields_meta meta information about fields
2095 * @param array $row current row
2098 * @author Michal Cihar (michal@cihar.com)
2099 * @return string calculated condition
2101 function PMA_getUvaCondition($handle, $fields_cnt, $fields_meta, $row)
2105 $uva_nonprimary_condition = '';
2107 for ($i = 0; $i < $fields_cnt; ++
$i) {
2108 $field_flags = PMA_DBI_field_flags($handle, $i);
2109 $meta = $fields_meta[$i];
2111 // do not use an alias in a condition
2112 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
2113 $meta->orgname
= $meta->name
;
2115 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2116 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2117 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2119 // need (string) === (string)
2120 // '' !== 0 but '' == 0
2121 if ((string) $select_expr['alias'] === (string) $meta->name
) {
2122 $meta->orgname
= $select_expr['column'];
2130 // to fix the bug where float fields (primary or not)
2131 // can't be matched because of the imprecision of
2132 // floating comparison, use CONCAT
2133 // (also, the syntax "CONCAT(field) IS NULL"
2134 // that we need on the next "if" will work)
2135 if ($meta->type
== 'real') {
2136 $condition = ' CONCAT(' . PMA_backquote($meta->table
) . '.'
2137 . PMA_backquote($meta->orgname
) . ') ';
2139 // string and blob fields have to be converted using
2140 // the system character set (always utf8) since
2141 // mysql4.1 can use different charset for fields.
2142 if (PMA_MYSQL_INT_VERSION
>= 40100
2143 && ($meta->type
== 'string' ||
$meta->type
== 'blob')) {
2144 $condition = ' CONVERT(' . PMA_backquote($meta->table
) . '.'
2145 . PMA_backquote($meta->orgname
) . ' USING utf8) ';
2147 $condition = ' ' . PMA_backquote($meta->table
) . '.'
2148 . PMA_backquote($meta->orgname
) . ' ';
2150 } // end if... else...
2152 if (!isset($row[$i]) ||
is_null($row[$i])) {
2153 $condition .= 'IS NULL AND';
2155 // timestamp is numeric on some MySQL 4.1
2156 if ($meta->numeric && $meta->type
!= 'timestamp') {
2157 $condition .= '= ' . $row[$i] . ' AND';
2158 } elseif ($meta->type
== 'blob'
2159 // hexify only if this is a true not empty BLOB
2160 && stristr($field_flags, 'BINARY')
2161 && !empty($row[$i])) {
2162 // use a CAST if possible, to avoid problems
2163 // if the field contains wildcard characters % or _
2164 if (PMA_MYSQL_INT_VERSION
< 40002) {
2165 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
2167 $condition .= '= CAST(0x' . bin2hex($row[$i])
2168 . ' AS BINARY) AND';
2171 $condition .= '= \''
2172 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2175 if ($meta->primary_key
> 0) {
2176 $primary_key .= $condition;
2177 } elseif ($meta->unique_key
> 0) {
2178 $unique_key .= $condition;
2180 $uva_nonprimary_condition .= $condition;
2183 // Correction uva 19991216: prefer primary or unique keys
2184 // for condition, but use conjunction of all values if no
2187 $uva_condition = $primary_key;
2188 } elseif ($unique_key) {
2189 $uva_condition = $unique_key;
2191 $uva_condition = $uva_nonprimary_condition;
2194 return preg_replace('|\s?AND$|', '', $uva_condition);
2198 * Function to generate unique condition for specified row.
2200 * @param string name of button element
2201 * @param string class of button element
2202 * @param string name of image element
2203 * @param string text to display
2204 * @param string image to display
2207 * @author Michal Cihar (michal@cihar.com)
2209 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2212 global $pmaThemeImage, $propicon;
2214 /* Opera has trouble with <input type="image"> */
2215 /* IE has trouble with <button> */
2216 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2217 echo '<button class="' . $button_class . '" type="submit"'
2218 .' name="' . $button_name . '" value="' . $text . '"'
2219 .' title="' . $text . '">' . "\n"
2220 .'<img class="icon" src="' . $pmaThemeImage . $image . '"'
2221 .' title="' . $text . '" alt="' . $text . '" width="16"'
2223 .($propicon == 'both' ?
' ' . $text : '') . "\n"
2224 .'</button>' . "\n";
2226 echo '<input type="image" name="' . $image_name . '" value="'
2227 . $text . '" title="' . $text . '" src="' . $pmaThemeImage
2229 . ($propicon == 'both' ?
' ' . $text : '') . "\n";
2234 * Generate a pagination selector for browsing resultsets
2236 * @param string URL for the JavaScript
2237 * @param string Number of rows in the pagination set
2238 * @param string current page number
2239 * @param string number of total pages
2240 * @param string If the number of pages is lower than this
2241 * variable, no pages will be ommitted in
2243 * @param string How many rows at the beginning should always
2245 * @param string How many rows at the end should always
2247 * @param string Percentage of calculation page offsets to
2248 * hop to a next page
2249 * @param string Near the current page, how many pages should
2250 * be considered "nearby" and displayed as
2254 * @author Garvin Hicking (pma@supergarv.de)
2256 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2257 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2260 $gotopage = $GLOBALS['strPageNumber']
2261 . ' <select name="goToPage" onchange="goToUrl(this, \''
2262 . $url . '\');">' . "\n";
2263 if ($nbTotalPage < $showAll) {
2264 $pages = range(1, $nbTotalPage);
2268 // Always show first X pages
2269 for ($i = 1; $i <= $sliceStart; $i++
) {
2273 // Always show last X pages
2274 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2278 // garvin: Based on the number of results we add the specified
2279 // $percent percentate to each page number,
2280 // so that we have a representing page number every now and then to
2281 // immideately jump to specific pages.
2282 // As soon as we get near our currently chosen page ($pageNow -
2283 // $range), every page number will be
2286 $x = $nbTotalPage - $sliceEnd;
2287 $met_boundary = false;
2289 if ($i >= ($pageNow - $range) && $i <= ($pageNow +
$range)) {
2290 // If our pageselector comes near the current page, we use 1
2291 // counter increments
2293 $met_boundary = true;
2295 // We add the percentate increment to our current page to
2296 // hop to the next one in range
2297 $i = $i +
floor($nbTotalPage / $percent);
2299 // Make sure that we do not cross our boundaries.
2300 if ($i > ($pageNow - $range) && !$met_boundary) {
2301 $i = $pageNow - $range;
2305 if ($i > 0 && $i <= $x) {
2310 // Since because of ellipsing of the current page some numbers may be double,
2311 // we unify our array:
2313 $pages = array_unique($pages);
2316 foreach ($pages as $i) {
2317 if ($i == $pageNow) {
2318 $selected = 'selected="selected" style="font-weight: bold"';
2322 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2325 $gotopage .= ' </select>';
2331 * @todo add documentation
2333 function PMA_userDir($dir)
2337 if (substr($dir, -1) != '/') {
2341 return str_replace('%u', $cfg['Server']['user'], $dir);
2345 * returns html code for db link to default db page
2347 * @uses $GLOBALS['cfg']['DefaultTabDatabase']
2348 * @uses $GLOBALS['db']
2349 * @uses $GLOBALS['strJumpToDB']
2350 * @uses PMA_generate_common_url()
2351 * @param string $database
2352 * @return string html link to default db page
2354 function PMA_getDbLink($database = null)
2356 if (!strlen($database)) {
2357 if (!strlen($GLOBALS['db'])) {
2360 $database = $GLOBALS['db'];
2362 $database = PMA_unescape_mysql_wildcards($database);
2365 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2366 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2367 .htmlspecialchars($database) . '</a>';
2373 * @uses PMA_Config::isHttps()
2374 * @uses PMA_Config::getCookiePath()
2377 * @param string $cookie name of cookie to remove
2378 * @return boolean result of setcookie()
2380 function PMA_removeCookie($cookie)
2382 return setcookie($cookie, '', time() - 3600,
2383 PMA_Config
::getCookiePath(), '', PMA_Config
::isHttps());
2387 * sets cookie if value is different from current cokkie value,
2388 * or removes if value is equal to default
2390 * @uses PMA_Config::isHttps()
2391 * @uses PMA_Config::getCookiePath()
2393 * @uses PMA_removeCookie()
2396 * @param string $cookie name of cookie to remove
2397 * @param mixed $value new cookie value
2398 * @param string $default default value
2399 * @return boolean result of setcookie()
2401 function PMA_setCookie($cookie, $value, $default = null)
2403 if (strlen($value) && null !== $default && $value === $default
2404 && isset($_COOKIE[$cookie])) {
2405 // remove cookie, default value is used
2406 return PMA_removeCookie($cookie);
2409 if (! strlen($value) && isset($_COOKIE[$cookie])) {
2410 // remove cookie, value is empty
2411 return PMA_removeCookie($cookie);
2414 if (! isset($_COOKIE[$cookie]) ||
$_COOKIE[$cookie] !== $value) {
2415 // set cookie with new value
2416 return setcookie($cookie, $value, time() +
60*60*24*30,
2417 PMA_Config
::getCookiePath(), '', PMA_Config
::isHttps());
2420 // cookie has already $value as value
2426 * include here only libraries which contain only function definitions
2427 * no code im main()!
2430 * Include URL/hidden inputs generating.
2432 require_once './libraries/url_generating.lib.php';
2437 /******************************************************************************/
2438 /* start procedural code label_start_procedural */
2441 * protect against older PHP versions' bug about GLOBALS overwrite
2442 * (no need to localize this message :))
2443 * but what if script.php?GLOBALS[admin]=1&GLOBALS[_REQUEST]=1 ???
2445 if (isset($_REQUEST['GLOBALS']) ||
isset($_FILES['GLOBALS'])
2446 ||
isset($_SERVER['GLOBALS']) ||
isset($_COOKIE['GLOBALS'])
2447 ||
isset($_ENV['GLOBALS'])) {
2448 die('GLOBALS overwrite attempt');
2452 * Check for numeric keys
2453 * (if register_globals is on, numeric key can be found in $GLOBALS)
2456 foreach ($GLOBALS as $key => $dummy) {
2457 if (is_numeric($key)) {
2458 die('numeric key detected');
2463 * just to be sure there was no import (registering) before here
2464 * we empty the global space
2466 $variables_whitelist = array (
2478 foreach (get_defined_vars() as $key => $value) {
2479 if (! in_array($key, $variables_whitelist)) {
2483 unset($key, $value, $variables_whitelist);
2487 * Subforms - some functions need to be called by form, cause of the limited url
2488 * length, but if this functions inside another form you cannot just open a new
2489 * form - so phpMyAdmin uses 'arrays' inside this form
2493 * ... main form elments ...
2494 * <intput type="hidden" name="subform[action1][id]" value="1" />
2495 * ... other subform data ...
2496 * <intput type="submit" name="usesubform[action1]" value="do action1" />
2497 * ... other subforms ...
2498 * <intput type="hidden" name="subform[actionX][id]" value="X" />
2499 * ... other subform data ...
2500 * <intput type="submit" name="usesubform[actionX]" value="do actionX" />
2501 * ... main form elments ...
2502 * <intput type="submit" name="main_action" value="submit form" />
2506 * so we now check if a subform is submitted
2509 if (isset($_POST['usesubform'])) {
2510 // if a subform is present and should be used
2511 // the rest of the form is deprecated
2512 $subform_id = key($_POST['usesubform']);
2513 $subform = $_POST['subform'][$subform_id];
2515 $_REQUEST = $subform;
2517 * some subforms need another page than the main form, so we will just
2518 * include this page at the end of this script - we use $__redirect to
2521 if (isset($_POST['redirect'])
2522 && $_POST['redirect'] != basename(PMA_getenv('PHP_SELF'))) {
2523 $__redirect = $_POST['redirect'];
2524 unset($_POST['redirect']);
2526 unset($subform_id, $subform);
2528 // end check if a subform is submitted
2530 // remove quotes added by php
2531 if (get_magic_quotes_gpc()) {
2532 PMA_arrayWalkRecursive($_GET, 'stripslashes', true);
2533 PMA_arrayWalkRecursive($_POST, 'stripslashes', true);
2534 PMA_arrayWalkRecursive($_COOKIE, 'stripslashes', true);
2535 PMA_arrayWalkRecursive($_REQUEST, 'stripslashes', true);
2539 * include deprecated grab_globals only if required
2541 if (empty($__redirect) && !defined('PMA_NO_VARIABLES_IMPORT')) {
2542 require './libraries/grab_globals.lib.php';
2546 * include session handling after the globals, to prevent overwriting
2548 require_once './libraries/session.inc.php';
2551 * init some variables LABEL_variables_init
2556 * @global array $GLOBALS['PMA_errors']
2558 $GLOBALS['PMA_errors'] = array();
2561 * holds params to be passed to next page
2562 * @global array $GLOBALS['url_params']
2564 $GLOBALS['url_params'] = array();
2567 * the whitelist for $GLOBALS['goto']
2568 * @global array $goto_whitelist
2570 $goto_whitelist = array(
2571 //'browse_foreigners.php',
2579 'db_importdocsql.php',
2583 'db_operations.php',
2586 //'Documentation.html',
2599 'server_binlog.php',
2600 'server_collations.php',
2601 'server_databases.php',
2602 'server_engines.php',
2603 'server_export.php',
2604 'server_import.php',
2605 'server_privileges.php',
2606 'server_processlist.php',
2608 'server_status.php',
2609 'server_variables.php',
2617 'tbl_move_copy.php',
2618 'tbl_printview.php',
2621 'tbl_operations.php',
2622 'tbl_structure.php',
2625 'tbl_row_action.php',
2628 'transformation_overview.php',
2629 'transformation_wrapper.php',
2631 'user_password.php',
2635 * check $__redirect against whitelist
2637 if (! PMA_checkPageValidity($__redirect, $goto_whitelist)) {
2642 * holds page that should be displayed
2643 * @global string $GLOBALS['goto']
2645 $GLOBALS['goto'] = '';
2646 // Security fix: disallow accessing serious server files via "?goto="
2647 if (PMA_checkPageValidity($_REQUEST['goto'], $goto_whitelist)) {
2648 $GLOBALS['goto'] = $_REQUEST['goto'];
2649 $GLOBALS['url_params']['goto'] = $_REQUEST['goto'];
2651 unset($_REQUEST['goto'], $_GET['goto'], $_POST['goto'], $_COOKIE['goto']);
2656 * @global string $GLOBALS['back']
2658 if (PMA_checkPageValidity($_REQUEST['back'], $goto_whitelist)) {
2659 $GLOBALS['back'] = $_REQUEST['back'];
2661 unset($_REQUEST['back'], $_GET['back'], $_POST['back'], $_COOKIE['back']);
2665 * Check whether user supplied token is valid, if not remove any possibly
2666 * dangerous stuff from request.
2668 * remember that some objects in the session with session_start and __wakeup()
2669 * could access this variables before we reach this point
2670 * f.e. PMA_Config: fontsize
2672 * @todo variables should be handled by their respective owners (objects)
2673 * f.e. lang, server, convcharset, collation_connection in PMA_Config
2675 if (empty($_REQUEST['token']) ||
$_SESSION[' PMA_token '] != $_REQUEST['token']) {
2677 * List of parameters which are allowed from unsafe source
2679 $allow_list = array(
2680 'db', 'table', 'lang', 'server', 'convcharset', 'collation_connection', 'target',
2683 /* Cookie preferences */
2684 'pma_lang', 'pma_charset', 'pma_collation_connection', 'pma_convcharset',
2685 /* Possible login form */
2686 'pma_servername', 'pma_username', 'pma_password',
2689 * Require cleanup functions
2691 require_once('./libraries/cleanup.lib.php');
2695 PMA_remove_request_vars($allow_list);
2701 * @global string $convcharset
2702 * @see select_lang.lib.php
2704 if (isset($_REQUEST['convcharset'])) {
2705 $convcharset = strip_tags($_REQUEST['convcharset']);
2709 * current selected database
2710 * @global string $GLOBALS['db']
2712 $GLOBALS['db'] = '';
2713 if (isset($_REQUEST['db'])) {
2714 // can we strip tags from this?
2715 // only \ and / is not allowed in db names for MySQL
2716 $GLOBALS['db'] = $_REQUEST['db'];
2717 $GLOBALS['url_params']['db'] = $GLOBALS['db'];
2721 * current selected table
2722 * @global string $GLOBALS['table']
2724 $GLOBALS['table'] = '';
2725 if (isset($_REQUEST['table'])) {
2726 // can we strip tags from this?
2727 // only \ and / is not allowed in table names for MySQL
2728 $GLOBALS['table'] = $_REQUEST['table'];
2729 $GLOBALS['url_params']['table'] = $GLOBALS['table'];
2733 * sql query to be executed
2734 * @global string $GLOBALS['sql_query']
2736 if (isset($_REQUEST['sql_query'])) {
2737 $GLOBALS['sql_query'] = $_REQUEST['sql_query'];
2740 //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup
2741 //$_REQUEST['server']; // checked later in this file
2742 //$_REQUEST['lang']; // checked by LABEL_loading_language_file
2746 /******************************************************************************/
2747 /* parsing config file LABEL_parsing_config_file */
2749 if (empty($_SESSION['PMA_Config'])) {
2751 * We really need this one!
2753 if (!function_exists('preg_replace')) {
2754 header('Location: error.php'
2755 . '?lang=' . urlencode($available_languages[$lang][2])
2756 . '&charset=' . urlencode($charset)
2757 . '&dir=' . urlencode($text_dir)
2758 . '&type=' . urlencode($strError)
2759 . '&error=' . urlencode(
2760 strtr(sprintf($strCantLoad, 'pcre'),
2761 array('<br />' => '[br]')))
2768 * @global PMA_Config $_SESSION['PMA_Config']
2770 $_SESSION['PMA_Config'] = new PMA_Config('./config.inc.php');
2772 } elseif (version_compare(phpversion(), '5', 'lt')) {
2774 * @todo move all __wakeup() functionality into session.inc.php
2776 $_SESSION['PMA_Config']->__wakeup();
2779 if (!defined('PMA_MINIMUM_COMMON')) {
2780 $_SESSION['PMA_Config']->checkPmaAbsoluteUri();
2784 * BC - enable backward compatibility
2785 * exports all config settings into $GLOBALS ($GLOBALS['cfg'])
2787 $_SESSION['PMA_Config']->enableBc();
2791 * check https connection
2793 if ($_SESSION['PMA_Config']->get('ForceSSL')
2794 && !$_SESSION['PMA_Config']->get('is_https')) {
2795 PMA_sendHeaderLocation(
2796 preg_replace('/^http/', 'https',
2797 $_SESSION['PMA_Config']->get('PmaAbsoluteUri'))
2798 . PMA_generate_common_url($_GET));
2803 /******************************************************************************/
2804 /* loading language file LABEL_loading_language_file */
2807 * Added messages while developing:
2809 if (file_exists('./lang/added_messages.php')) {
2810 include './lang/added_messages.php';
2814 * Includes the language file if it hasn't been included yet
2816 require './libraries/language.lib.php';
2820 * check for errors occured while loading config
2821 * this check is done here after loading lang files to present errors in locale
2823 if ($_SESSION['PMA_Config']->error_config_file
) {
2824 $GLOBALS['PMA_errors'][] = $strConfigFileError
2826 . ($_SESSION['PMA_Config']->getSource() == './config.inc.php' ?
2827 '<a href="show_config_errors.php"'
2828 .' target="_blank">' . $_SESSION['PMA_Config']->getSource() . '</a>'
2830 '<a href="' . $_SESSION['PMA_Config']->getSource() . '"'
2831 .' target="_blank">' . $_SESSION['PMA_Config']->getSource() . '</a>');
2833 if ($_SESSION['PMA_Config']->error_config_default_file
) {
2834 $GLOBALS['PMA_errors'][] = sprintf($strConfigDefaultFileError,
2835 $_SESSION['PMA_Config']->default_source
);
2837 if ($_SESSION['PMA_Config']->error_pma_uri
) {
2838 $GLOBALS['PMA_errors'][] = sprintf($strPmaUriError);
2843 * @global integer $GLOBALS['server']
2845 $GLOBALS['server'] = 0;
2848 * Servers array fixups.
2849 * $default_server comes from PMA_Config::enableBc()
2850 * @todo merge into PMA_Config
2852 // Do we have some server?
2853 if (!isset($cfg['Servers']) ||
count($cfg['Servers']) == 0) {
2854 // No server => create one with defaults
2855 $cfg['Servers'] = array(1 => $default_server);
2857 // We have server(s) => apply default config
2858 $new_servers = array();
2860 foreach ($cfg['Servers'] as $server_index => $each_server) {
2862 // Detect wrong configuration
2863 if (!is_int($server_index) ||
$server_index < 1) {
2864 $GLOBALS['PMA_errors'][] = sprintf($strInvalidServerIndex, $server_index);
2867 $each_server = array_merge($default_server, $each_server);
2869 // Don't use servers with no hostname
2870 if ($each_server['connect_type'] == 'tcp' && empty($each_server['host'])) {
2871 $GLOBALS['PMA_errors'][] = sprintf($strInvalidServerHostname, $server_index);
2874 // Final solution to bug #582890
2875 // If we are using a socket connection
2876 // and there is nothing in the verbose server name
2877 // or the host field, then generate a name for the server
2878 // in the form of "Server 2", localized of course!
2879 if ($each_server['connect_type'] == 'socket' && empty($each_server['host']) && empty($each_server['verbose'])) {
2880 $each_server['verbose'] = $GLOBALS['strServer'] . $server_index;
2883 $new_servers[$server_index] = $each_server;
2885 $cfg['Servers'] = $new_servers;
2886 unset($new_servers, $server_index, $each_server);
2890 unset($default_server);
2893 /******************************************************************************/
2894 /* setup themes LABEL_theme_setup */
2897 * @global PMA_Theme_Manager $_SESSION['PMA_Theme_Manager']
2899 if (! isset($_SESSION['PMA_Theme_Manager'])) {
2900 $_SESSION['PMA_Theme_Manager'] = new PMA_Theme_Manager
;
2903 * @todo move all __wakeup() functionality into session.inc.php
2905 $_SESSION['PMA_Theme_Manager']->checkConfig();
2908 // for the theme per server feature
2909 if (isset($_REQUEST['server']) && !isset($_REQUEST['set_theme'])) {
2910 $GLOBALS['server'] = $_REQUEST['server'];
2911 $tmp = $_SESSION['PMA_Theme_Manager']->getThemeCookie();
2913 $tmp = $_SESSION['PMA_Theme_Manager']->theme_default
;
2915 $_SESSION['PMA_Theme_Manager']->setActiveTheme($tmp);
2919 * @todo move into PMA_Theme_Manager::__wakeup()
2921 if (isset($_REQUEST['set_theme'])) {
2922 // if user selected a theme
2923 $_SESSION['PMA_Theme_Manager']->setActiveTheme($_REQUEST['set_theme']);
2928 * @global PMA_Theme $_SESSION['PMA_Theme']
2930 $_SESSION['PMA_Theme'] = $_SESSION['PMA_Theme_Manager']->theme
;
2935 * @global string $GLOBALS['theme']
2937 $GLOBALS['theme'] = $_SESSION['PMA_Theme']->getName();
2940 * @global string $GLOBALS['pmaThemePath']
2942 $GLOBALS['pmaThemePath'] = $_SESSION['PMA_Theme']->getPath();
2944 * the theme image path
2945 * @global string $GLOBALS['pmaThemeImage']
2947 $GLOBALS['pmaThemeImage'] = $_SESSION['PMA_Theme']->getImgPath();
2950 * load layout file if exists
2952 if (@file_exists
($_SESSION['PMA_Theme']->getLayoutFile())) {
2953 include $_SESSION['PMA_Theme']->getLayoutFile();
2955 * @todo remove if all themes are update use Navi instead of Left as frame name
2957 if (! isset($GLOBALS['cfg']['NaviWidth'])
2958 && isset($GLOBALS['cfg']['LeftWidth'])) {
2959 $GLOBALS['cfg']['NaviWidth'] = $GLOBALS['cfg']['LeftWidth'];
2963 if (! defined('PMA_MINIMUM_COMMON')) {
2965 * Charset conversion.
2967 require_once './libraries/charset_conversion.lib.php';
2972 require_once './libraries/string.lib.php';
2975 * If no server is selected, make sure that $cfg['Server'] is empty (so
2976 * that nothing will work), and skip server authentication.
2977 * We do NOT exit here, but continue on without logging into any server.
2978 * This way, the welcome page will still come up (with no server info) and
2979 * present a choice of servers in the case that there are multiple servers
2980 * and '$cfg['ServerDefault'] = 0' is set.
2982 if (! empty($_REQUEST['server']) && ! empty($cfg['Servers'][$_REQUEST['server']])) {
2983 $GLOBALS['server'] = $_REQUEST['server'];
2984 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
2986 if (!empty($cfg['Servers'][$cfg['ServerDefault']])) {
2987 $GLOBALS['server'] = $cfg['ServerDefault'];
2988 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
2990 $GLOBALS['server'] = 0;
2991 $cfg['Server'] = array();
2994 $GLOBALS['url_params']['server'] = $GLOBALS['server'];
2997 if (! empty($cfg['Server'])) {
3000 * Loads the proper database interface for this server
3002 require_once './libraries/database_interface.lib.php';
3004 // Gets the authentication library that fits the $cfg['Server'] settings
3005 // and run authentication
3007 // (for a quick check of path disclosure in auth/cookies:)
3008 $coming_from_common = true;
3010 if (!file_exists('./libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php')) {
3011 header('Location: error.php'
3012 . '?lang=' . urlencode($available_languages[$lang][2])
3013 . '&charset=' . urlencode($charset)
3014 . '&dir=' . urlencode($text_dir)
3015 . '&type=' . urlencode($strError)
3016 . '&error=' . urlencode(
3017 $strInvalidAuthMethod . ' '
3018 . $cfg['Server']['auth_type'])
3024 * the required auth type plugin
3026 require_once './libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php';
3028 if (!PMA_auth_check()) {
3031 PMA_auth_set_user();
3034 // Check IP-based Allow/Deny rules as soon as possible to reject the
3036 // Based on mod_access in Apache:
3037 // http://cvs.apache.org/viewcvs.cgi/httpd-2.0/modules/aaa/mod_access.c?rev=1.37&content-type=text/vnd.viewcvs-markup
3038 // Look at: "static int check_dir_access(request_rec *r)"
3039 // Robbat2 - May 10, 2002
3040 if (isset($cfg['Server']['AllowDeny'])
3041 && isset($cfg['Server']['AllowDeny']['order'])) {
3044 * ip based access library
3046 require_once './libraries/ip_allow_deny.lib.php';
3048 $allowDeny_forbidden = false; // default
3049 if ($cfg['Server']['AllowDeny']['order'] == 'allow,deny') {
3050 $allowDeny_forbidden = true;
3051 if (PMA_allowDeny('allow')) {
3052 $allowDeny_forbidden = false;
3054 if (PMA_allowDeny('deny')) {
3055 $allowDeny_forbidden = true;
3057 } elseif ($cfg['Server']['AllowDeny']['order'] == 'deny,allow') {
3058 if (PMA_allowDeny('deny')) {
3059 $allowDeny_forbidden = true;
3061 if (PMA_allowDeny('allow')) {
3062 $allowDeny_forbidden = false;
3064 } elseif ($cfg['Server']['AllowDeny']['order'] == 'explicit') {
3065 if (PMA_allowDeny('allow')
3066 && !PMA_allowDeny('deny')) {
3067 $allowDeny_forbidden = false;
3069 $allowDeny_forbidden = true;
3071 } // end if ... elseif ... elseif
3073 // Ejects the user if banished
3074 if ($allowDeny_forbidden) {
3077 unset($allowDeny_forbidden); //Clean up after you!
3081 if (!$cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') {
3082 $allowDeny_forbidden = true;
3084 unset($allowDeny_forbidden); //Clean up after you!
3087 $bkp_track_err = @ini_set
('track_errors', 1);
3089 // Try to connect MySQL with the control user profile (will be used to
3090 // get the privileges list for the current user but the true user link
3091 // must be open after this one so it would be default one for all the
3093 if ($cfg['Server']['controluser'] != '') {
3094 $controllink = PMA_DBI_connect($cfg['Server']['controluser'],
3095 $cfg['Server']['controlpass'], true);
3097 $controllink = PMA_DBI_connect($cfg['Server']['user'],
3098 $cfg['Server']['password'], true);
3099 } // end if ... else
3101 // Pass #1 of DB-Config to read in master level DB-Config will go here
3102 // Robbat2 - May 11, 2002
3104 // Connects to the server (validates user's login)
3105 $userlink = PMA_DBI_connect($cfg['Server']['user'],
3106 $cfg['Server']['password'], false);
3108 // Pass #2 of DB-Config to read in user level DB-Config will go here
3109 // Robbat2 - May 11, 2002
3111 @ini_set
('track_errors', $bkp_track_err);
3112 unset($bkp_track_err);
3115 * If we auto switched to utf-8 we need to reread messages here
3117 if (defined('PMA_LANG_RELOAD')) {
3118 require './libraries/language.lib.php';
3124 require_once './libraries/sqlparser.lib.php';
3127 * SQL Validator interface code
3129 require_once './libraries/sqlvalidator.lib.php';
3132 * the PMA_List_Database class
3134 require_once './libraries/PMA_List_Database.class.php';
3135 $PMA_List_Database = new PMA_List_Database($userlink, $controllink);
3137 } // end server connecting
3140 * Kanji encoding convert feature appended by Y.Kawada (2002/2/20)
3142 if (@function_exists
('mb_convert_encoding')
3143 && strpos(' ' . $lang, 'ja-')
3144 && file_exists('./libraries/kanji-encoding.lib.php')) {
3145 require_once './libraries/kanji-encoding.lib.php';
3146 define('PMA_MULTIBYTE_ENCODING', 1);
3150 * save some settings in cookies
3151 * @todo should be done in PMA_Config
3153 PMA_setCookie('pma_lang', $GLOBALS['lang']);
3154 PMA_setCookie('pma_charset', $GLOBALS['convcharset']);
3155 PMA_setCookie('pma_collation_connection', $GLOBALS['collation_connection']);
3157 $_SESSION['PMA_Theme_Manager']->setThemeCookie();
3158 } // end if !defined('PMA_MINIMUM_COMMON')
3160 if (!empty($__redirect) && in_array($__redirect, $goto_whitelist)) {
3161 // to handle bug #1388167
3162 if (isset($_GET['is_js_confirmed'])) {
3163 $is_js_confirmed = 1;
3166 * include subform target page
3168 require $__redirect;