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 /******************************************************************************/
62 /* definition of functions LABEL_definition_of_functions */
64 * Removes insecure parts in a path; used before include() or
65 * require() when a part of the path comes from an insecure source
66 * like a cookie or form.
68 * @param string The path to check
70 * @return string The secured path
73 * @author Marc Delisle (lem9@users.sourceforge.net)
75 function PMA_securePath($path)
78 $path = preg_replace('@\.\.*@', '.', $path);
84 * returns array with dbs grouped with extended infos
86 * @uses $GLOBALS['dblist'] from PMA_availableDatabases()
87 * @uses $GLOBALS['num_dbs'] from PMA_availableDatabases()
88 * @uses $GLOBALS['cfgRelation']['commwork']
89 * @uses $GLOBALS['cfg']['ShowTooltip']
90 * @uses $GLOBALS['cfg']['LeftFrameDBTree']
91 * @uses $GLOBALS['cfg']['LeftFrameDBSeparator']
92 * @uses $GLOBALS['cfg']['ShowTooltipAliasDB']
93 * @uses PMA_availableDatabases()
94 * @uses PMA_getTableCount()
95 * @uses PMA_getComments()
96 * @uses PMA_availableDatabases()
101 * @return array db list
103 function PMA_getDbList()
105 if (empty($GLOBALS['dblist'])) {
106 PMA_availableDatabases();
108 $dblist = $GLOBALS['dblist'];
111 foreach ($dblist as $key => $db) {
112 // garvin: Get comments from PMA comments table
114 if ($GLOBALS['cfg']['ShowTooltip']
115 && $GLOBALS['cfgRelation']['commwork']) {
116 $_db_tooltip = PMA_getComments($db);
117 if (is_array($_db_tooltip)) {
118 $db_tooltip = implode(' ', $_db_tooltip);
122 if ($GLOBALS['cfg']['LeftFrameDBTree']
123 && $GLOBALS['cfg']['LeftFrameDBSeparator']
124 && strstr($db, $GLOBALS['cfg']['LeftFrameDBSeparator']))
126 $pos = strrpos($db, $GLOBALS['cfg']['LeftFrameDBSeparator']);
127 $group = substr($db, 0, $pos);
128 $disp_name_cut = substr($db, $pos);
131 $disp_name_cut = $db;
135 if ($db_tooltip && $GLOBALS['cfg']['ShowTooltipAliasDB']) {
136 $disp_name = $db_tooltip;
137 $disp_name_cut = $db_tooltip;
141 $dbgroups[$group][$db] = array(
143 'disp_name_cut' => $disp_name_cut,
144 'disp_name' => $disp_name,
145 'comment' => $db_tooltip,
146 'num_tables' => PMA_getTableCount($db),
148 } // end foreach ($dblist as $db)
153 * returns html code for select form element with dbs
155 * @return string html code select
157 function PMA_getHtmlSelectDb($selected = '')
159 $dblist = PMA_getDbList();
160 // TODO: IE can not handle different text directions in select boxes
161 // so, as mostly names will be in english, we set the whole selectbox to LTR
163 $return = '<select name="db" id="lightm_db" xml:lang="en" dir="ltr"'
164 .' onchange="if (this.value != \'\') window.parent.openDb(this.value);">' . "\n"
165 .'<option value="" dir="' . $GLOBALS['text_dir'] . '">(' . $GLOBALS['strDatabases'] . ') ...</option>'
167 foreach ($dblist as $group => $dbs) {
168 if (count($dbs) > 1) {
169 $return .= '<optgroup label="' . htmlspecialchars($group)
171 // wether display db_name cuted by the group part
177 foreach ($dbs as $db) {
178 $return .= '<option value="' . $db['name'] . '"'
179 .' title="' . $db['comment'] . '"';
180 if ($db['name'] == $selected) {
181 $return .= ' selected="selected"';
183 $return .= '>' . ($cut ?
$db['disp_name_cut'] : $db['disp_name'])
184 .' (' . $db['num_tables'] . ')</option>' . "\n";
186 if (count($dbs) > 1) {
187 $return .= '</optgroup>' . "\n";
190 $return .= '</select>';
196 * returns count of tables in given db
198 * @param string $db database to count tables for
199 * @return integer count of tables in $db
201 function PMA_getTableCount($db)
203 $tables = PMA_DBI_try_query(
204 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
205 null, PMA_DBI_QUERY_STORE
);
207 $num_tables = PMA_DBI_num_rows($tables);
208 PMA_DBI_free_result($tables);
218 * Get the complete list of Databases a user can access
220 * @param boolean whether to include check on failed 'only_db' operations
221 * @param resource database handle (superuser)
222 * @param integer amount of databases inside the 'only_db' container
223 * @param resource possible resource from a failed previous query
224 * @param resource database handle (user)
225 * @param array configuration
226 * @param array previous list of databases
228 * @return array all databases a user has access to
232 function PMA_safe_db_list($only_db_check, $controllink, $dblist_cnt, $userlink,
235 if ($only_db_check == false) {
236 // try to get the available dbs list
237 // use userlink by default
238 $dblist = PMA_DBI_get_dblist();
239 $dblist_cnt = count($dblist);
241 // PMA_DBI_get_dblist() relies on the ability to run "SHOW DATABASES".
242 // On servers started with --skip-show-database, this is not possible
243 // so we have here a fallback method, which relies on the controluser
244 // being able to access the "mysql" db, as explained in the doc.
247 $auth_query = 'SELECT User, Select_priv '
249 . 'WHERE User = \'' . PMA_sqlAddslashes($cfg['Server']['user']) . '\'';
250 $rs = PMA_DBI_try_query($auth_query, $controllink);
254 // Access to "mysql" db allowed and dblist still empty -> gets the
256 if (!$dblist_cnt && ($rs && @PMA_DBI_num_rows
($rs))) {
257 $row = PMA_DBI_fetch_assoc($rs);
258 PMA_DBI_free_result($rs);
259 // Correction uva 19991215
260 // Previous code assumed database "mysql" admin table "db" column
261 // "db" contains literal name of user database, and works if so.
262 // Mysql usage generally (and uva usage specifically) allows this
263 // column to contain regular expressions (we have all databases
264 // owned by a given student/faculty/staff beginning with user i.d.
265 // and governed by default by a single set of privileges with
266 // regular expression as key). This breaks previous code.
267 // This maintenance is to fix code to work correctly for regular
269 if ($row['Select_priv'] != 'Y') {
271 // 1. get allowed dbs from the "mysql.db" table
272 // lem9: User can be blank (anonymous user)
273 $local_query = 'SELECT DISTINCT Db FROM mysql.db WHERE Select_priv = \'Y\' AND (User = \'' . PMA_sqlAddslashes($cfg['Server']['user']) . '\' OR User = \'\')';
274 $rs = PMA_DBI_try_query($local_query, $controllink);
275 if ($rs && @PMA_DBI_num_rows
($rs)) {
276 // Will use as associative array of the following 2 code
278 // the 1st is the only line intact from before
280 // the 2nd replaces $dblist[] = $row['Db'];
281 $uva_mydbs = array();
282 // Code following those 2 lines in correction continues
283 // populating $dblist[], as previous code did. But it is
284 // now populated with actual database names instead of
285 // with regular expressions.
286 while ($row = PMA_DBI_fetch_assoc($rs)) {
287 // loic1: all databases cases - part 1
288 if ( !isset($row['Db']) ||
! strlen($row['Db']) ||
$row['Db'] == '%') {
292 // loic1: avoid multiple entries for dbs
293 if (!isset($uva_mydbs[$row['Db']])) {
294 $uva_mydbs[$row['Db']] = 1;
297 PMA_DBI_free_result($rs);
298 $uva_alldbs = PMA_DBI_query('SHOW DATABASES;', $GLOBALS['controllink']);
299 // loic1: all databases cases - part 2
300 if (isset($uva_mydbs['%'])) {
301 while ($uva_row = PMA_DBI_fetch_row($uva_alldbs)) {
302 $dblist[] = $uva_row[0];
305 while ($uva_row = PMA_DBI_fetch_row($uva_alldbs)) {
306 $uva_db = $uva_row[0];
307 if (isset($uva_mydbs[$uva_db]) && $uva_mydbs[$uva_db] == 1) {
309 $uva_mydbs[$uva_db] = 0;
310 } elseif (!isset($dblist[$uva_db])) {
311 foreach ($uva_mydbs as $uva_matchpattern => $uva_value) {
312 // loic1: fixed bad regexp
313 // TODO: db names may contain characters
314 // that are regexp instructions
315 $re = '(^|(\\\\\\\\)+|[^\])';
316 $uva_regex = ereg_replace($re . '%', '\\1.*', ereg_replace($re . '_', '\\1.{1}', $uva_matchpattern));
317 // Fixed db name matching
318 // 2000-08-28 -- Benjamin Gandon
319 if (ereg('^' . $uva_regex . '$', $uva_db)) {
324 } // end if ... elseif ...
327 PMA_DBI_free_result($uva_alldbs);
331 // 2. get allowed dbs from the "mysql.tables_priv" table
332 $local_query = 'SELECT DISTINCT Db FROM mysql.tables_priv WHERE Table_priv LIKE \'%Select%\' AND User = \'' . PMA_sqlAddslashes($cfg['Server']['user']) . '\'';
333 $rs = PMA_DBI_try_query($local_query, $controllink);
334 if ($rs && @PMA_DBI_num_rows
($rs)) {
335 while ($row = PMA_DBI_fetch_assoc($rs)) {
336 if (!in_array($row['Db'], $dblist)) {
337 $dblist[] = $row['Db'];
340 PMA_DBI_free_result($rs);
343 } // end building available dbs from the "mysql" db
349 * Converts numbers like 10M into bytes
351 * @param string $size
352 * @return integer $size
354 function get_real_size($size = 0)
359 $scan['MB'] = 1048576;
360 $scan['Mb'] = 1048576;
361 $scan['M'] = 1048576;
362 $scan['m'] = 1048576;
368 while (list($key) = each($scan)) {
369 if ((strlen($size) > strlen($key))
370 && (substr($size, strlen($size) - strlen($key)) == $key)) {
371 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
376 } // end function get_real_size()
382 * @uses extension_loaded()
384 * @uses function_exists()
388 * @uses ob_get_contents()
389 * @uses ob_end_clean()
394 * @param string $module name if module to load
395 * @return boolean success loading module
397 function PMA_dl($module)
399 static $dl_allowed = null;
401 if (extension_loaded($module)) {
405 if (null === $dl_allowed) {
406 if (!@ini_get
('safe_mode')
407 && @ini_get
('enable_dl')
408 && @function_exists
('dl')) {
410 phpinfo(INFO_GENERAL
); /* Only general info */
411 $a = strip_tags(ob_get_contents());
413 if (preg_match('@Thread Safety[[:space:]]*enabled@', $a)) {
414 if (preg_match('@Server API[[:space:]]*\(CGI\|CLI\)@', $a)) {
431 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
432 $module_file = 'php_' . $module . '.dll';
434 $module_file = $module . '.so';
437 return @dl
($module_file);
441 * merges array recursive like array_merge_recursive() but keyed-values are
442 * always overwritten.
444 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
446 * @see http://php.net/array_merge
447 * @see http://php.net/array_merge_recursive
448 * @uses func_num_args()
449 * @uses func_get_arg()
451 * @uses call_user_func_array()
452 * @param array array to merge
453 * @param array array to merge
455 * @return array merged array
457 function PMA_array_merge_recursive()
459 switch(func_num_args()) {
464 // when does that happen?
465 return func_get_arg(0);
468 $args = func_get_args();
469 if (!is_array($args[0]) ||
!is_array($args[1])) {
472 foreach ($args[1] as $key2 => $value2) {
473 if (isset($args[0][$key2]) && !is_int($key2)) {
474 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
477 // we erase the parent array, otherwise we cannot override a directive that
478 // contains array elements, like this:
479 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
480 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
481 if (is_int($key2) && $key2 == 0) {
484 $args[0][$key2] = $value2;
490 $args = func_get_args();
491 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
493 return call_user_func_array('PMA_array_merge_recursive', $args);
499 * calls $function vor every element in $array recursively
501 * @param array $array array to walk
502 * @param string $function function to call for every array element
504 function PMA_arrayWalkRecursive(&$array, $function)
506 foreach ($array as $key => $value) {
507 if (is_array($value)) {
508 PMA_arrayWalkRecursive($array[$key], $function);
510 $array[$key] = $function($value);
516 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
518 * checks given given $page against given $whitelist and returns true if valid
519 * it ignores optionaly query paramters in $page (script.php?ignored)
525 * @param string &$page page to check
526 * @param array $whitelist whitelist to check page against
527 * @return boolean whether $page is valid or not (in $whitelist or not)
529 function PMA_checkPageValidity(&$page, $whitelist)
531 if (! isset($page)) {
535 if (in_array($page, $whitelist)) {
537 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
540 $_page = urldecode($page);
541 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
549 * include here only libraries which contain only function definitions
552 /* Input sanitizing */
553 require_once './libraries/sanitizing.lib.php';
554 require_once './libraries/Theme.class.php';
555 require_once './libraries/Theme_Manager.class.php';
556 require_once './libraries/Config.class.php';
557 require_once './libraries/Table.class.php';
561 if (!defined('PMA_MINIMUM_COMMON')) {
564 * string PMA_getIcon(string $icon)
566 * @uses $GLOBALS['pmaThemeImage']
567 * @param $icon name of icon
568 * @return html img tag
570 function PMA_getIcon($icon, $alternate = '')
572 if ($GLOBALS['cfg']['PropertiesIconic']) {
573 return '<img src="' . $GLOBALS['pmaThemeImage'] . $icon . '"'
574 . ' title="' . $alternate . '" alt="' . $alternate . '"'
575 . ' class="icon" width="16" height="16" />';
582 * Displays the maximum size for an upload
584 * @param integer the size
586 * @return string the message
590 function PMA_displayMaximumUploadSize($max_upload_size)
592 list($max_size, $max_unit) = PMA_formatByteDown($max_upload_size);
593 return '(' . sprintf($GLOBALS['strMaximumSize'], $max_size, $max_unit) . ')';
597 * Generates a hidden field which should indicate to the browser
598 * the maximum size for upload
600 * @param integer the size
602 * @return string the INPUT field
606 function PMA_generateHiddenMaxFileSize($max_size)
608 return '<input type="hidden" name="MAX_FILE_SIZE" value="' .$max_size . '" />';
612 * Add slashes before "'" and "\" characters so a value containing them can
613 * be used in a sql comparison.
615 * @param string the string to slash
616 * @param boolean whether the string will be used in a 'LIKE' clause
617 * (it then requires two more escaped sequences) or not
618 * @param boolean whether to treat cr/lfs as escape-worthy entities
619 * (converts \n to \\n, \r to \\r)
621 * @param boolean whether this function is used as part of the
622 * "Create PHP code" dialog
624 * @return string the slashed string
628 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
631 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
633 $a_string = str_replace('\\', '\\\\', $a_string);
637 $a_string = str_replace("\n", '\n', $a_string);
638 $a_string = str_replace("\r", '\r', $a_string);
639 $a_string = str_replace("\t", '\t', $a_string);
643 $a_string = str_replace('\'', '\\\'', $a_string);
645 $a_string = str_replace('\'', '\'\'', $a_string);
649 } // end of the 'PMA_sqlAddslashes()' function
653 * Add slashes before "_" and "%" characters for using them in MySQL
654 * database, table and field names.
655 * Note: This function does not escape backslashes!
657 * @param string the string to escape
659 * @return string the escaped string
663 function PMA_escape_mysql_wildcards($name)
665 $name = str_replace('_', '\\_', $name);
666 $name = str_replace('%', '\\%', $name);
669 } // end of the 'PMA_escape_mysql_wildcards()' function
672 * removes slashes before "_" and "%" characters
673 * Note: This function does not unescape backslashes!
675 * @param string $name the string to escape
676 * @return string the escaped string
679 function PMA_unescape_mysql_wildcards($name)
681 $name = str_replace('\\_', '_', $name);
682 $name = str_replace('\\%', '%', $name);
685 } // end of the 'PMA_unescape_mysql_wildcards()' function
690 * @param mixed pre-parsed SQL structure
692 * @return string the formatted sql
694 * @global array the configuration array
695 * @global boolean whether the current statement is a multiple one or not
699 * @author Robin Johnson <robbat2@users.sourceforge.net>
701 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
705 // Check that we actually have a valid set of parsed data
707 // first check for the SQL parser having hit an error
708 if (PMA_SQP_isError()) {
711 // then check for an array
712 if (!is_array($parsed_sql)) {
713 // We don't so just return the input directly
714 // This is intended to be used for when the SQL Parser is turned off
715 $formatted_sql = '<pre>' . "\n"
716 . (($cfg['SQP']['fmtType'] == 'none' && $unparsed_sql != '') ?
$unparsed_sql : $parsed_sql) . "\n"
718 return $formatted_sql;
723 switch ($cfg['SQP']['fmtType']) {
725 if ($unparsed_sql != '') {
726 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
728 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
732 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
735 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
736 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
742 return $formatted_sql;
743 } // end of the "PMA_formatSql()" function
747 * Displays a link to the official MySQL documentation
749 * @param string chapter of "HTML, one page per chapter" documentation
750 * @param string contains name of page/anchor that is being linked
751 * @param bool whether to use big icon (like in left frame)
753 * @return string the html link
757 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
761 if ($cfg['MySQLManualType'] == 'none' ||
empty($cfg['MySQLManualBase'])) {
765 // Fixup for newly used names:
766 $chapter = str_replace('_', '-', strtolower($chapter));
767 $link = str_replace('_', '-', strtolower($link));
769 switch ($cfg['MySQLManualType']) {
771 if (empty($chapter)) {
774 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
777 $url = $cfg['MySQLManualBase'] . '#' . $link;
783 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
791 if (defined('PMA_MYSQL_INT_VERSION')) {
792 if (PMA_MYSQL_INT_VERSION
< 50000) {
794 } elseif (PMA_MYSQL_INT_VERSION
>= 50100) {
796 } elseif (PMA_MYSQL_INT_VERSION
>= 50000) {
800 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/en/' . $link . '.html';
805 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>';
806 } elseif ($GLOBALS['cfg']['ReplaceHelpImg']) {
807 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>';
809 return '[<a href="' . $url . '" target="mysql_doc">' . $GLOBALS['strDocu'] . '</a>]';
811 } // end of the 'PMA_showMySQLDocu()' function
814 * Displays a hint icon, on mouse over show the hint
816 * @param string the error message
820 function PMA_showHint($hint_message)
822 //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) . '\');" />';
823 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;" />';
827 * Displays a MySQL error message in the right frame.
829 * @param string the error message
830 * @param string the sql query that failed
831 * @param boolean whether to show a "modify" link or not
832 * @param string the "back" link url (full path is not required)
833 * @param boolean EXIT the page?
835 * @global array the configuration array
839 function PMA_mysqlDie($error_message = '', $the_query = '',
840 $is_modify_link = true, $back_url = '',
843 global $cfg, $table, $db, $sql_query;
845 require_once './libraries/header.inc.php';
847 if (!$error_message) {
848 $error_message = PMA_DBI_getError();
850 if (!$the_query && !empty($GLOBALS['sql_query'])) {
851 $the_query = $GLOBALS['sql_query'];
854 // --- Added to solve bug #641765
855 // Robbat2 - 12 January 2003, 9:46PM
856 // Revised, Robbat2 - 13 January 2003, 2:59PM
857 if (!function_exists('PMA_SQP_isError') ||
PMA_SQP_isError()) {
858 $formatted_sql = htmlspecialchars($the_query);
859 } elseif (empty($the_query) ||
trim($the_query) == '') {
862 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
865 echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n";
866 echo ' <div class="error"><h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
867 // if the config password is wrong, or the MySQL server does not
868 // respond, do not show the query that would reveal the
870 if (!empty($the_query) && !strstr($the_query, 'connect')) {
871 // --- Added to solve bug #641765
872 // Robbat2 - 12 January 2003, 9:46PM
873 // Revised, Robbat2 - 13 January 2003, 2:59PM
874 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) {
875 echo PMA_SQP_getErrorString() . "\n";
876 echo '<br />' . "\n";
879 // modified to show me the help on sql errors (Michael Keck)
880 echo ' <p><strong>' . $GLOBALS['strSQLQuery'] . ':</strong>' . "\n";
881 if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select
882 echo PMA_showMySQLDocu('SQL-Syntax', 'SELECT');
884 if ($is_modify_link && isset($db)) {
886 $doedit_goto = '<a href="tbl_properties.php?' . PMA_generate_common_url($db, $table) . '&sql_query=' . urlencode($the_query) . '&show_query=1">';
888 $doedit_goto = '<a href="db_details.php?' . PMA_generate_common_url($db) . '&sql_query=' . urlencode($the_query) . '&show_query=1">';
890 if ($GLOBALS['cfg']['PropertiesIconic']) {
892 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
896 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
902 .' ' . $formatted_sql . "\n"
906 $tmp_mysql_error = ''; // for saving the original $error_message
907 if (!empty($error_message)) {
908 $tmp_mysql_error = strtolower($error_message); // save the original $error_message
909 $error_message = htmlspecialchars($error_message);
910 $error_message = preg_replace("@((\015\012)|(\015)|(\012)){3,}@", "\n\n", $error_message);
912 // modified to show me the help on error-returns (Michael Keck)
914 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
915 . PMA_showMySQLDocu('Error-returns', 'Error-returns')
919 // The error message will be displayed within a CODE segment.
920 // To preserve original formatting, but allow wordwrapping, we do a couple of replacements
922 // Replace all non-single blanks with their HTML-counterpart
923 $error_message = str_replace(' ', ' ', $error_message);
924 // Replace TAB-characters with their HTML-counterpart
925 $error_message = str_replace("\t", ' ', $error_message);
926 // Replace linebreaks
927 $error_message = nl2br($error_message);
930 . $error_message . "\n"
931 . '</code><br />' . "\n";
933 // feature request #1036254:
934 // Add a link by MySQL-Error #1062 - Duplicate entry
935 // 2004-10-20 by mkkeck
936 // 2005-01-17 modified by mkkeck bugfix
937 if (substr($error_message, 1, 4) == '1062') {
938 // get the duplicate entry
941 // TODO: what would be the best delimiter, while avoiding
942 // special characters that can become high-ascii after editing,
943 // depending upon which editor is used by the developer?
944 $error_table = array();
945 preg_match('@ALTER\sTABLE\s\`([^\`]+)\`@iu', $the_query, $error_table);
946 $error_table = $error_table[1];
949 $error_fields = array();
950 preg_match('@\(([^\)]+)\)@i', $the_query, $error_fields);
951 $error_fields = explode(',', $error_fields[1]);
954 $duplicate_value = array();
955 preg_match('@\'([^\']+)\'@i', $tmp_mysql_error, $duplicate_value);
956 $duplicate_value = $duplicate_value[1];
960 FROM ' . PMA_backquote($error_table) . '
961 WHERE CONCAT_WS("-", ' . implode(', ', $error_fields) . ')
962 = "' . PMA_sqlAddslashes($duplicate_value) . '"
963 ORDER BY ' . implode(', ', $error_fields);
964 unset($error_table, $error_fields, $duplicate_value);
966 echo ' <form method="post" action="import.php" style="padding: 0; margin: 0">' ."\n"
967 .' <input type="hidden" name="sql_query" value="' . htmlentities($sql) . '" />' . "\n"
968 .' ' . PMA_generate_common_hidden_inputs($db, $table) . "\n"
969 .' <input type="submit" name="submit" value="' . $GLOBALS['strBrowse'] . '" />' . "\n"
972 } // end of show duplicate entry
975 echo '<fieldset class="tblFooters">';
977 if (!empty($back_url) && $exit) {
978 $goto_back_url='<a href="' . (strstr($back_url, '?') ?
$back_url . '&no_history=true' : $back_url . '?no_history=true') . '">';
979 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
981 echo ' </fieldset>' . "\n\n";
983 require_once './libraries/footer.inc.php';
985 } // end of the 'PMA_mysqlDie()' function
988 * Returns a string formatted with CONVERT ... USING
989 * if MySQL supports it
991 * @param string the string itself
992 * @param string the mode: quoted or unquoted (this one by default)
994 * @return the formatted string
998 function PMA_convert_using($string, $mode='unquoted')
1000 if ($mode == 'quoted') {
1001 $possible_quote = "'";
1003 $possible_quote = "";
1006 if (PMA_MYSQL_INT_VERSION
>= 40100) {
1007 list($conn_charset) = explode('_', $GLOBALS['collation_connection']);
1008 $converted_string = "CONVERT(" . $possible_quote . $string . $possible_quote . " USING " . $conn_charset . ")";
1010 $converted_string = $possible_quote . $string . $possible_quote;
1012 return $converted_string;
1016 * Send HTTP header, taking IIS limits into account (600 seems ok)
1018 * @param string $uri the header to send
1019 * @return boolean always true
1021 function PMA_sendHeaderLocation($uri)
1023 if (PMA_IS_IIS
&& strlen($uri) > 600) {
1025 echo '<html><head><title>- - -</title>' . "\n";
1026 echo '<meta http-equiv="expires" content="0">' . "\n";
1027 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
1028 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
1029 echo '<meta http-equiv="Refresh" content="0;url=' .$uri . '">' . "\n";
1030 echo '<script type="text/javascript" language="javascript">' . "\n";
1031 echo '//<![CDATA[' . "\n";
1032 echo 'setTimeout ("window.location = unescape(\'"' . $uri . '"\')",2000); </script>' . "\n";
1033 echo '//]]>' . "\n";
1034 echo '</head>' . "\n";
1035 echo '<body>' . "\n";
1036 echo '<script type="text/javascript" language="javascript">' . "\n";
1037 echo '//<![CDATA[' . "\n";
1038 echo 'document.write (\'<p><a href="' . $uri . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
1039 echo '//]]>' . "\n";
1040 echo '</script></body></html>' . "\n";
1044 if (strpos($uri, '?') === false) {
1045 header('Location: ' . $uri . '?' . SID
);
1047 // use seperators defined by php, but prefer ';'
1048 // as recommended by W3C
1049 $php_arg_separator_input = ini_get('arg_separator.input');
1050 if (strpos($php_arg_separator_input, ';') !== false) {
1052 } elseif (strlen($php_arg_separator_input) > 0) {
1053 $separator = $php_arg_separator_input{0};
1057 header('Location: ' . $uri . $separator . SID
);
1060 session_write_close();
1062 header('Refresh: 0; ' . $uri);
1064 header('Location: ' . $uri);
1071 * Get the list and number of available databases.
1073 * @param string the url to go back to in case of error
1075 * @return boolean always true
1077 * @global array the list of available databases
1078 * @global integer the number of available databases
1079 * @global array current configuration
1081 function PMA_availableDatabases($error_url = '')
1087 // 1. A list of allowed databases has already been defined by the
1088 // authentication process -> gets the available databases list
1089 if (count($dblist)) {
1090 foreach ($dblist as $key => $db) {
1091 if (!@PMA_DBI_select_db
($db) ||
(!empty($GLOBALS['cfg']['Server']['hide_db']) && preg_match('/' . $GLOBALS['cfg']['Server']['hide_db'] . '/', $db))) {
1092 unset($dblist[$key]);
1096 // 2. Allowed database list is empty -> gets the list of all databases
1098 elseif (empty($cfg['Server']['only_db'])) {
1099 $dblist = PMA_DBI_get_dblist(); // needed? or PMA_mysqlDie('', 'SHOW DATABASES;', false, $error_url);
1102 $num_dbs = count($dblist);
1104 // natural order for db list; but do not sort if user asked
1105 // for a specific order with the 'only_db' mechanism
1106 if (!is_array($GLOBALS['cfg']['Server']['only_db'])
1107 && $GLOBALS['cfg']['NaturalOrder']) {
1112 } // end of the 'PMA_availableDatabases()' function
1115 * returns array with tables of given db with extended infomation and grouped
1117 * @uses $GLOBALS['cfg']['LeftFrameTableSeparator']
1118 * @uses $GLOBALS['cfg']['LeftFrameTableLevel']
1119 * @uses $GLOBALS['cfg']['ShowTooltipAliasTB']
1120 * @uses $GLOBALS['cfg']['NaturalOrder']
1121 * @uses PMA_DBI_fetch_result()
1122 * @uses PMA_backquote()
1128 * @param string $db name of db
1129 * return array (rekursive) grouped table list
1131 function PMA_getTableList($db, $tables = null)
1133 $sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
1135 if ( null === $tables ) {
1136 $tables = PMA_DBI_get_tables_full($db);
1137 if ($GLOBALS['cfg']['NaturalOrder']) {
1138 uksort($tables, 'strnatcasecmp');
1142 if (count($tables) < 1) {
1153 $table_groups = array();
1155 foreach ($tables as $table_name => $table) {
1157 // check for correct row count
1158 if (null === $table['Rows']) {
1159 // Do not check exact row count here,
1160 // if row count is invalid possibly the table is defect
1161 // and this would break left frame;
1162 // but we can check row count if this is a view,
1163 // since PMA_Table::countRecords() returns a limited row count
1166 // set this because PMA_Table::countRecords() can use it
1167 $tbl_is_view = PMA_Table
::isView($db, $table['Name']);
1170 $table['Rows'] = PMA_Table
::countRecords($db, $table['Name'],
1175 // in $group we save the reference to the place in $table_groups
1176 // where to store the table info
1177 if ($GLOBALS['cfg']['LeftFrameDBTree']
1178 && $sep && strstr($table_name, $sep))
1180 $parts = explode($sep, $table_name);
1182 $group =& $table_groups;
1184 $group_name_full = '';
1185 while ($i < count($parts) - 1
1186 && $i < $GLOBALS['cfg']['LeftFrameTableLevel']) {
1187 $group_name = $parts[$i] . $sep;
1188 $group_name_full .= $group_name;
1190 if (!isset($group[$group_name])) {
1191 $group[$group_name] = array();
1192 $group[$group_name]['is' . $sep . 'group'] = true;
1193 $group[$group_name]['tab' . $sep . 'count'] = 1;
1194 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
1195 } elseif (!isset($group[$group_name]['is' . $sep . 'group'])) {
1196 $table = $group[$group_name];
1197 $group[$group_name] = array();
1198 $group[$group_name][$group_name] = $table;
1200 $group[$group_name]['is' . $sep . 'group'] = true;
1201 $group[$group_name]['tab' . $sep . 'count'] = 1;
1202 $group[$group_name]['tab' . $sep . 'group'] = $group_name_full;
1204 $group[$group_name]['tab' . $sep . 'count']++
;
1206 $group =& $group[$group_name];
1210 if (!isset($table_groups[$table_name])) {
1211 $table_groups[$table_name] = array();
1213 $group =& $table_groups;
1217 if ($GLOBALS['cfg']['ShowTooltipAliasTB']
1218 && $GLOBALS['cfg']['ShowTooltipAliasTB'] !== 'nested') {
1219 // switch tooltip and name
1220 $table['Comment'] = $table['Name'];
1221 $table['disp_name'] = $table['Comment'];
1223 $table['disp_name'] = $table['Name'];
1226 $group[$table_name] = array_merge($default, $table);
1229 return $table_groups;
1232 /* ----------------------- Set of misc functions ----------------------- */
1236 * Adds backquotes on both sides of a database, table or field name.
1237 * Since MySQL 3.23.6 this allows to use non-alphanumeric characters in
1240 * @param mixed the database, table or field name to "backquote" or
1242 * @param boolean a flag to bypass this function (used by dump
1245 * @return mixed the "backquoted" database, table or field name if the
1246 * current MySQL release is >= 3.23.6, the original one
1251 function PMA_backquote($a_name, $do_it = true)
1253 // '0' is also empty for php :-(
1255 && isset($a_name) && !empty($a_name) && $a_name != '*') {
1257 if (is_array($a_name)) {
1259 foreach ($a_name as $key => $val) {
1260 $result[$key] = '`' . $val . '`';
1264 return '`' . $a_name . '`';
1269 } // end of the 'PMA_backquote()' function
1273 * Format a string so it can be passed to a javascript function.
1274 * This function is used to displays a javascript confirmation box for
1275 * "DROP/DELETE/ALTER" queries.
1277 * @param string the string to format
1278 * @param boolean whether to add backquotes to the string or not
1280 * @return string the formated string
1284 function PMA_jsFormat($a_string = '', $add_backquotes = true)
1286 if (is_string($a_string)) {
1287 $a_string = htmlspecialchars($a_string);
1288 $a_string = str_replace('\\', '\\\\', $a_string);
1289 $a_string = str_replace('\'', '\\\'', $a_string);
1290 $a_string = str_replace('#', '\\#', $a_string);
1291 $a_string = str_replace("\012", '\\\\n', $a_string);
1292 $a_string = str_replace("\015", '\\\\r', $a_string);
1295 return (($add_backquotes) ?
PMA_backquote($a_string) : $a_string);
1296 } // end of the 'PMA_jsFormat()' function
1300 * Defines the <CR><LF> value depending on the user OS.
1302 * @return string the <CR><LF> value to use
1306 function PMA_whichCrlf()
1310 // The 'PMA_USR_OS' constant is defined in "./libraries/defines.lib.php"
1312 if (PMA_USR_OS
== 'Win') {
1316 elseif (PMA_USR_OS
== 'Mac') {
1325 } // end of the 'PMA_whichCrlf()' function
1328 * Reloads navigation if needed.
1330 * @global mixed configuration
1331 * @global bool whether to reload
1335 function PMA_reloadNavigation()
1339 // Reloads the navigation frame via JavaScript if required
1340 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
1342 $reload_url = './left.php?' . PMA_generate_common_url((isset($GLOBALS['db']) ?
$GLOBALS['db'] : ''), '', '&');
1344 <script type
="text/javascript" language
="javascript">
1346 if (typeof(window
.parent
) != 'undefined'
1347 && typeof(window
.parent
.frames
[0]) != 'undefined') {
1348 window
.parent
.goTo('<?php echo $reload_url; ?>');
1353 unset($GLOBALS['reload']);
1358 * Displays a message at the top of the "main" (right) frame
1360 * @param string the message to display
1362 * @global array the configuration array
1366 function PMA_showMessage($message)
1370 // Sanitizes $message
1371 $message = PMA_sanitize($message);
1373 // Corrects the tooltip text via JS if required
1374 if ( isset($GLOBALS['table']) && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
1375 $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
1377 $tbl_status = PMA_DBI_fetch_assoc($result);
1378 $tooltip = (empty($tbl_status['Comment']))
1380 : $tbl_status['Comment'] . ' ';
1381 $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
1382 PMA_DBI_free_result($result);
1383 $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
1386 <script type
="text/javascript" language
="javascript">
1388 window
.parent
.updateTableTitle('<?php echo $uni_tbl; ?>', '<?php echo PMA_jsFormat($tooltip, false); ?>');
1393 } // end if ... elseif
1395 // Checks if the table needs to be repaired after a TRUNCATE query.
1396 if (isset($GLOBALS['table']) && isset($GLOBALS['sql_query'])
1397 && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
1398 if (!isset($tbl_status)) {
1399 $result = @PMA_DBI_try_query
('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
1401 $tbl_status = PMA_DBI_fetch_assoc($result);
1402 PMA_DBI_free_result($result);
1405 if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
1406 PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
1412 <div align
="<?php echo $GLOBALS['cell_align_left']; ?>">
1414 if (!empty($GLOBALS['show_error_header'])) {
1417 <h1
><?php
echo $GLOBALS['strError']; ?
></h1
>
1422 if (isset($GLOBALS['special_message'])) {
1423 echo PMA_sanitize($GLOBALS['special_message']);
1424 unset($GLOBALS['special_message']);
1427 if (!empty($GLOBALS['show_error_header'])) {
1431 if ($cfg['ShowSQL'] == true
1432 && (!empty($GLOBALS['sql_query']) ||
!empty($GLOBALS['display_query']))) {
1433 $local_query = !empty($GLOBALS['display_query']) ?
$GLOBALS['display_query'] : (($cfg['SQP']['fmtType'] == 'none' && isset($GLOBALS['unparsed_sql']) && $GLOBALS['unparsed_sql'] != '') ?
$GLOBALS['unparsed_sql'] : $GLOBALS['sql_query']);
1434 // Basic url query part
1435 $url_qpart = '?' . PMA_generate_common_url(isset($GLOBALS['db']) ?
$GLOBALS['db'] : '', isset($GLOBALS['table']) ?
$GLOBALS['table'] : '');
1437 // Html format the query to be displayed
1438 // The nl2br function isn't used because its result isn't a valid
1439 // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
1440 // If we want to show some sql code it is easiest to create it here
1441 /* SQL-Parser-Analyzer */
1443 if (!empty($GLOBALS['show_as_php'])) {
1444 $new_line = '\'<br />' . "\n" . ' . \' ';
1446 if (isset($new_line)) {
1447 /* SQL-Parser-Analyzer */
1448 $query_base = PMA_sqlAddslashes(htmlspecialchars($local_query), false, false, true);
1449 /* SQL-Parser-Analyzer */
1450 $query_base = preg_replace("@((\015\012)|(\015)|(\012))+@", $new_line, $query_base);
1452 $query_base = $local_query;
1455 // Parse SQL if needed
1456 if (isset($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
1457 $parsed_sql = $GLOBALS['parsed_sql'];
1459 // when the query is large (for example an INSERT of binary
1460 // data), the parser chokes; so avoid parsing the query
1461 if (strlen($query_base) < 1000) {
1462 $parsed_sql = PMA_SQP_parse($query_base);
1467 if (isset($parsed_sql)) {
1468 $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
1471 // Here we append the LIMIT added for navigation, to
1472 // enable its display. Adding it higher in the code
1473 // to $local_query would create a problem when
1474 // using the Refresh or Edit links.
1476 // Only append it on SELECTs.
1478 // FIXME: what would be the best to do when someone
1479 // hits Refresh: use the current LIMITs ?
1481 if (isset($analyzed_display_query[0]['queryflags']['select_from'])
1482 && isset($GLOBALS['sql_limit_to_append'])) {
1483 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
1484 // Need to reparse query
1485 $parsed_sql = PMA_SQP_parse($query_base);
1488 if (!empty($GLOBALS['show_as_php'])) {
1489 $query_base = '$sql = \'' . $query_base;
1490 } elseif (!empty($GLOBALS['validatequery'])) {
1491 $query_base = PMA_validateSQL($query_base);
1493 if (isset($parsed_sql)) {
1494 $query_base = PMA_formatSql($parsed_sql, $query_base);
1498 // Prepares links that may be displayed to edit/explain the query
1499 // (don't go to default pages, we must go to the page
1500 // where the query box is available)
1501 // (also, I don't see why we should check the goto variable)
1503 //if (!isset($GLOBALS['goto'])) {
1504 //$edit_target = (isset($GLOBALS['table'])) ? $cfg['DefaultTabTable'] : $cfg['DefaultTabDatabase'];
1505 $edit_target = isset($GLOBALS['db']) ?
(isset($GLOBALS['table']) ?
'tbl_properties.php' : 'db_details.php') : 'server_sql.php';
1506 //} elseif ($GLOBALS['goto'] != 'main.php') {
1507 // $edit_target = $GLOBALS['goto'];
1509 // $edit_target = '';
1512 if (isset($cfg['SQLQuery']['Edit'])
1513 && ($cfg['SQLQuery']['Edit'] == true)
1514 && (!empty($edit_target))) {
1516 if ($cfg['EditInWindow'] == true) {
1517 $onclick = 'window.parent.focus_querywindow(\'' . urlencode($local_query) . '\'); return false;';
1522 $edit_link = $edit_target
1524 . '&sql_query=' . urlencode($local_query)
1525 . '&show_query=1#querybox';
1526 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1531 // Want to have the query explained (Mike Beck 2002-05-22)
1532 // but only explain a SELECT (that has not been explained)
1533 /* SQL-Parser-Analyzer */
1534 if (isset($cfg['SQLQuery']['Explain'])
1535 && $cfg['SQLQuery']['Explain'] == true) {
1537 // Detect if we are validating as well
1538 // To preserve the validate uRL data
1539 if (!empty($GLOBALS['validatequery'])) {
1540 $explain_link_validate = '&validatequery=1';
1542 $explain_link_validate = '';
1545 $explain_link = 'import.php'
1547 . $explain_link_validate
1548 . '&sql_query=';
1550 if (preg_match('@^SELECT[[:space:]]+@i', $local_query)) {
1551 $explain_link .= urlencode('EXPLAIN ' . $local_query);
1552 $message = $GLOBALS['strExplain'];
1553 } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $local_query)) {
1554 $explain_link .= urlencode(substr($local_query, 8));
1555 $message = $GLOBALS['strNoExplain'];
1559 if (!empty($explain_link)) {
1560 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1566 // Also we would like to get the SQL formed in some nice
1567 // php-code (Mike Beck 2002-05-22)
1568 if (isset($cfg['SQLQuery']['ShowAsPHP'])
1569 && $cfg['SQLQuery']['ShowAsPHP'] == true) {
1570 $php_link = 'import.php'
1572 . '&show_query=1'
1573 . '&sql_query=' . urlencode($local_query)
1574 . '&show_as_php=';
1576 if (!empty($GLOBALS['show_as_php'])) {
1578 $message = $GLOBALS['strNoPhp'];
1581 $message = $GLOBALS['strPhp'];
1583 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1585 if (isset($GLOBALS['show_as_php']) && $GLOBALS['show_as_php'] == '1') {
1589 . '&show_query=1'
1590 . '&sql_query=' . urlencode($local_query);
1591 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1599 if (isset($cfg['SQLQuery']['Refresh'])
1600 && $cfg['SQLQuery']['Refresh']
1601 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $local_query)) {
1603 $refresh_link = 'import.php'
1605 . '&show_query=1'
1606 . (isset($_GET['pos']) ?
'&pos=' . $_GET['pos'] : '')
1607 . '&sql_query=' . urlencode($local_query);
1608 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1613 if (isset($cfg['SQLValidator']['use'])
1614 && $cfg['SQLValidator']['use'] == true
1615 && isset($cfg['SQLQuery']['Validate'])
1616 && $cfg['SQLQuery']['Validate'] == true) {
1617 $validate_link = 'import.php'
1619 . '&show_query=1'
1620 . '&sql_query=' . urlencode($local_query)
1621 . '&validatequery=';
1622 if (!empty($GLOBALS['validatequery'])) {
1623 $validate_link .= '0';
1624 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1626 $validate_link .= '1';
1627 $validate_message = $GLOBALS['strValidateSQL'] ;
1629 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1631 $validate_link = '';
1633 unset($local_query);
1635 // Displays the message
1636 echo '<fieldset class="">' . "\n";
1637 echo ' <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
1638 echo ' ' . $query_base;
1640 //Clean up the end of the PHP
1641 if (!empty($GLOBALS['show_as_php'])) {
1644 echo '</fieldset>' . "\n";
1646 if (!empty($edit_target)) {
1647 echo '<fieldset class="tblFooters">';
1648 echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
1655 } // end of the 'PMA_showMessage()' function
1659 * Formats $value to byte view
1661 * @param double the value to format
1662 * @param integer the sensitiveness
1663 * @param integer the number of decimals to retain
1665 * @return array the formatted value and its unit
1670 * @version 1.2 - 18 July 2002
1672 function PMA_formatByteDown($value, $limes = 6, $comma = 0)
1674 $dh = pow(10, $comma);
1675 $li = pow(10, $limes);
1676 $return_value = $value;
1677 $unit = $GLOBALS['byteUnits'][0];
1679 for ($d = 6, $ex = 15; $d >= 1; $d--, $ex-=3) {
1680 if (isset($GLOBALS['byteUnits'][$d]) && $value >= $li * pow(10, $ex)) {
1681 $value = round($value / (pow(1024, $d) / $dh)) /$dh;
1682 $unit = $GLOBALS['byteUnits'][$d];
1687 if ($unit != $GLOBALS['byteUnits'][0]) {
1688 $return_value = number_format($value, $comma, $GLOBALS['number_decimal_separator'], $GLOBALS['number_thousands_separator']);
1690 $return_value = number_format($value, 0, $GLOBALS['number_decimal_separator'], $GLOBALS['number_thousands_separator']);
1693 return array($return_value, $unit);
1694 } // end of the 'PMA_formatByteDown' function
1697 * Formats $value to the given length and appends SI prefixes
1698 * $comma is not substracted from the length
1699 * with a $length of 0 no truncation occurs, number is only formated
1700 * to the current locale
1702 * echo PMA_formatNumber(123456789, 6); // 123,457 k
1703 * echo PMA_formatNumber(-123456789, 4, 2); // -123.46 M
1704 * echo PMA_formatNumber(-0.003, 6); // -3 m
1705 * echo PMA_formatNumber(0.003, 3, 3); // 0.003
1706 * echo PMA_formatNumber(0.00003, 3, 2); // 0.03 m
1707 * echo PMA_formatNumber(0, 6); // 0
1709 * @param double $value the value to format
1710 * @param integer $length the max length
1711 * @param integer $comma the number of decimals to retain
1712 * @param boolean $only_down do not reformat numbers below 1
1714 * @return string the formatted value and its unit
1718 * @author staybyte, sebastian mendel
1719 * @version 1.1.0 - 2005-10-27
1721 function PMA_formatNumber($value, $length = 3, $comma = 0, $only_down = false)
1723 if ($length === 0) {
1724 return number_format($value,
1726 $GLOBALS['number_decimal_separator'],
1727 $GLOBALS['number_thousands_separator']);
1730 // this units needs no translation, ISO
1751 // we need at least 3 digits to be displayed
1752 if (3 > $length +
$comma) {
1753 $length = 3 - $comma;
1756 // check for negativ value to retain sign
1759 $value = abs($value);
1764 $dh = pow(10, $comma);
1765 $li = pow(10, $length);
1769 for ($d = 8; $d >= 0; $d--) {
1770 if (isset($units[$d]) && $value >= $li * pow(1000, $d-1)) {
1771 $value = round($value / (pow(1000, $d) / $dh)) /$dh;
1776 } elseif (!$only_down && (float) $value !== 0.0) {
1777 for ($d = -8; $d <= 8; $d++
) {
1778 if (isset($units[$d]) && $value <= $li * pow(1000, $d-1)) {
1779 $value = round($value / (pow(1000, $d) / $dh)) /$dh;
1784 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1786 $value = number_format($value,
1788 $GLOBALS['number_decimal_separator'],
1789 $GLOBALS['number_thousands_separator']);
1791 return $sign . $value . ' ' . $unit;
1792 } // end of the 'PMA_formatNumber' function
1795 * Extracts ENUM / SET options from a type definition string
1797 * @param string The column type definition
1799 * @return array The options or
1800 * boolean false in case of an error.
1804 function PMA_getEnumSetOptions($type_def)
1806 $open = strpos($type_def, '(');
1807 $close = strrpos($type_def, ')');
1808 if (!$open ||
!$close) {
1811 $options = substr($type_def, $open +
2, $close - $open - 3);
1812 $options = explode('\',\'', $options);
1814 } // end of the 'PMA_getEnumSetOptions' function
1817 * Writes localised date
1819 * @param string the current timestamp
1821 * @return string the formatted date
1825 function PMA_localisedDate($timestamp = -1, $format = '')
1827 global $datefmt, $month, $day_of_week;
1829 if ($format == '') {
1833 if ($timestamp == -1) {
1834 $timestamp = time();
1837 $date = preg_replace('@%[aA]@', $day_of_week[(int)strftime('%w', $timestamp)], $format);
1838 $date = preg_replace('@%[bB]@', $month[(int)strftime('%m', $timestamp)-1], $date);
1840 return strftime($date, $timestamp);
1841 } // end of the 'PMA_localisedDate()' function
1845 * returns a tab for tabbed navigation.
1846 * If the variables $link and $args ar left empty, an inactive tab is created
1848 * @uses array_merge()
1850 * $GLOBALS['strEmpty']
1851 * $GLOBALS['strDrop']
1852 * $GLOBALS['active_page']
1853 * $GLOBALS['PHP_SELF']
1855 * PMA_generate_common_url()
1856 * $GLOBALS['url_query']
1858 * $GLOBALS['cfg']['MainPageIconic']
1859 * $GLOBALS['pmaThemeImage']
1863 * @param array $tab array with all options
1864 * @return string html code for one tab, a link if valid otherwise a span
1867 function PMA_getTab($tab)
1880 $tab = array_merge($defaults, $tab);
1882 // determine additionnal style-class
1883 if (empty($tab['class'])) {
1884 if ($tab['text'] == $GLOBALS['strEmpty']
1885 ||
$tab['text'] == $GLOBALS['strDrop']) {
1886 $tab['class'] = 'caution';
1887 } elseif (!empty($tab['active'])
1888 ||
(isset($GLOBALS['active_page'])
1889 && $GLOBALS['active_page'] == $tab['link'])
1890 ||
basename(getenv('PHP_SELF')) == $tab['link'])
1892 $tab['class'] = 'active';
1897 if (!empty($tab['link'])) {
1898 $tab['link'] = htmlentities($tab['link']);
1899 $tab['link'] = $tab['link'] . $tab['sep']
1900 .(empty($GLOBALS['url_query']) ?
1901 PMA_generate_common_url() : $GLOBALS['url_query']);
1902 if (!empty($tab['args'])) {
1903 foreach ($tab['args'] as $param => $value) {
1904 $tab['link'] .= '&' . urlencode($param) . '='
1905 . urlencode($value);
1910 // display icon, even if iconic is disabled but the link-text is missing
1911 if (($GLOBALS['cfg']['MainPageIconic'] ||
empty($tab['text']))
1912 && isset($tab['icon'])) {
1913 $image = '<img class="icon" src="' . htmlentities($GLOBALS['pmaThemeImage'])
1914 .'%1$s" width="16" height="16" alt="%2$s" />%2$s';
1915 $tab['text'] = sprintf($image, htmlentities($tab['icon']), $tab['text']);
1917 // check to not display an empty link-text
1918 elseif (empty($tab['text'])) {
1920 trigger_error('empty linktext in function ' . __FUNCTION__
. '()',
1924 if (!empty($tab['link'])) {
1925 $out = '<a class="tab' . htmlentities($tab['class']) . '"'
1926 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1927 . $tab['text'] . '</a>';
1929 $out = '<span class="tab' . htmlentities($tab['class']) . '">'
1930 . $tab['text'] . '</span>';
1934 } // end of the 'PMA_getTab()' function
1937 * returns html-code for a tab navigation
1939 * @uses PMA_getTab()
1940 * @uses htmlentities()
1941 * @param array $tabs one element per tab
1942 * @param string $tag_id id used for the html-tag
1943 * @return string html-code for tab-navigation
1945 function PMA_getTabs($tabs, $tag_id = 'topmenu')
1948 '<div id="' . htmlentities($tag_id) . 'container">' . "\n"
1949 .'<ul id="' . htmlentities($tag_id) . '">' . "\n";
1951 foreach ($tabs as $tab) {
1952 $tab_navigation .= '<li>' . PMA_getTab($tab) . '</li>' . "\n";
1957 .'<div class="clearfloat"></div>'
1960 return $tab_navigation;
1965 * Displays a link, or a button if the link's URL is too large, to
1966 * accommodate some browsers' limitations
1968 * @param string the URL
1969 * @param string the link message
1970 * @param mixed $tag_params string: js confirmation
1971 * array: additional tag params (f.e. style="")
1972 * @param boolean $new_form we set this to false when we are already in
1973 * a form, to avoid generating nested forms
1975 * @return string the results to be echoed or saved in an array
1977 function PMA_linkOrButton($url, $message, $tag_params = array(),
1978 $new_form = true, $strip_img = false, $target = '')
1980 if (! is_array($tag_params)) {
1982 $tag_params = array();
1984 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1988 if (! empty($target)) {
1989 $tag_params['target'] = htmlentities($target);
1992 $tag_params_strings = array();
1993 foreach ($tag_params as $par_name => $par_value) {
1994 // htmlentities() only on non javascript
1995 $par_value = substr($par_name, 0, 2) == 'on'
1997 : htmlentities($par_value);
1998 $tag_params_strings[] = $par_name . '="' . $par_value . '"';
2001 // previously the limit was set to 2047, it seems 1000 is better
2002 if (strlen($url) <= 1000) {
2003 // no whitespace within an <a> else Safari will make it part of the link
2004 $ret = "\n" . '<a href="' . $url . '" '
2005 . implode(' ', $tag_params_strings) . '>'
2006 . $message . '</a>' . "\n";
2008 // no spaces (linebreaks) at all
2009 // or after the hidden fields
2010 // IE will display them all
2012 // add class=link to submit button
2013 if (empty($tag_params['class'])) {
2014 $tag_params['class'] = 'link';
2016 $url = str_replace('&', '&', $url);
2017 $url_parts = parse_url($url);
2018 $query_parts = explode('&', $url_parts['query']);
2020 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
2021 . ' method="post"' . $target . ' style="display: inline;">';
2023 $subname_close = '';
2026 $query_parts[] = 'redirect=' . $url_parts['path'];
2027 if (empty($GLOBALS['subform_counter'])) {
2028 $GLOBALS['subform_counter'] = 0;
2030 $GLOBALS['subform_counter']++
;
2032 $subname_open = 'subform[' . $GLOBALS['subform_counter'] . '][';
2033 $subname_close = ']';
2034 $submit_name = ' name="usesubform[' . $GLOBALS['subform_counter'] . ']"';
2036 foreach ($query_parts as $query_pair) {
2037 list($eachvar, $eachval) = explode('=', $query_pair);
2038 $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
2039 . $subname_close . '" value="'
2040 . htmlspecialchars(urldecode($eachval)) . '" />';
2043 if (stristr($message, '<img')) {
2045 $message = trim(strip_tags($message));
2046 $ret .= '<input type="submit"' . $submit_name . ' '
2047 . implode(' ', $tag_params_strings)
2048 . ' value="' . htmlspecialchars($message) . '" />';
2050 $ret .= '<input type="image"' . $submit_name . ' '
2051 . implode(' ', $tag_params_strings)
2052 . ' src="' . preg_replace(
2053 '/^.*\ssrc="([^"]*)".*$/si', '\1', $message) . '"'
2054 . ' value="' . htmlspecialchars(
2055 preg_replace('/^.*\salt="([^"]*)".*$/si', '\1',
2060 $message = trim(strip_tags($message));
2061 $ret .= '<input type="submit"' . $submit_name . ' '
2062 . implode(' ', $tag_params_strings)
2063 . ' value="' . htmlspecialchars($message) . '" />';
2068 } // end if... else...
2071 } // end of the 'PMA_linkOrButton()' function
2075 * Returns a given timespan value in a readable format.
2077 * @param int the timespan
2079 * @return string the formatted value
2081 function PMA_timespanFormat($seconds)
2083 $return_string = '';
2084 $days = floor($seconds / 86400);
2086 $seconds -= $days * 86400;
2088 $hours = floor($seconds / 3600);
2089 if ($days > 0 ||
$hours > 0) {
2090 $seconds -= $hours * 3600;
2092 $minutes = floor($seconds / 60);
2093 if ($days > 0 ||
$hours > 0 ||
$minutes > 0) {
2094 $seconds -= $minutes * 60;
2096 return sprintf($GLOBALS['timespanfmt'], (string)$days, (string)$hours, (string)$minutes, (string)$seconds);
2100 * Takes a string and outputs each character on a line for itself. Used
2101 * mainly for horizontalflipped display mode.
2102 * Takes care of special html-characters.
2103 * Fulfills todo-item
2104 * http://sf.net/tracker/?func=detail&aid=544361&group_id=23067&atid=377411
2106 * @param string The string
2107 * @param string The Separator (defaults to "<br />\n")
2110 * @author Garvin Hicking <me@supergarv.de>
2111 * @return string The flipped string
2113 function PMA_flipstring($string, $Separator = "<br />\n")
2115 $format_string = '';
2118 for ($i = 0; $i < strlen($string); $i++
) {
2119 $char = $string{$i};
2123 $format_string .= $charbuff;
2126 } elseif (!empty($charbuff)) {
2128 } elseif ($char == ';' && !empty($charbuff)) {
2129 $format_string .= $charbuff;
2133 $format_string .= $char;
2137 if ($append && ($i != strlen($string))) {
2138 $format_string .= $Separator;
2142 return $format_string;
2147 * Function added to avoid path disclosures.
2148 * Called by each script that needs parameters, it displays
2149 * an error message and, by default, stops the execution.
2151 * Not sure we could use a strMissingParameter message here,
2152 * would have to check if the error message file is always available
2154 * @param array The names of the parameters needed by the calling
2156 * @param boolean Stop the execution?
2157 * (Set this manually to false in the calling script
2158 * until you know all needed parameters to check).
2159 * @param boolean Whether to include this list in checking for special params.
2160 * @global string path to current script
2161 * @global boolean flag whether any special variable was required
2164 * @author Marc Delisle (lem9@users.sourceforge.net)
2166 function PMA_checkParameters($params, $die = true, $request = true)
2168 global $PHP_SELF, $checked_special;
2170 if (!isset($checked_special)) {
2171 $checked_special = false;
2174 $reported_script_name = basename($PHP_SELF);
2175 $found_error = false;
2176 $error_message = '';
2178 foreach ($params as $param) {
2179 if ($request && $param != 'db' && $param != 'table') {
2180 $checked_special = true;
2183 if (!isset($GLOBALS[$param])) {
2184 $error_message .= $reported_script_name . ': Missing parameter: ' . $param . ' <a href="./Documentation.html#faqmissingparameters" target="documentation"> (FAQ 2.8)</a><br />';
2185 $found_error = true;
2189 require_once './libraries/header_meta_style.inc.php';
2190 echo '</head><body><p>' . $error_message . '</p></body></html>';
2198 * Function to generate unique condition for specified row.
2200 * @uses PMA_MYSQL_INT_VERSION
2201 * @uses $GLOBALS['analyzed_sql'][0]
2202 * @uses PMA_DBI_field_flags()
2203 * @uses PMA_backquote()
2204 * @uses PMA_sqlAddslashes()
2207 * @uses preg_replace()
2208 * @param resource $handle current query result
2209 * @param integer $fields_cnt number of fields
2210 * @param array $fields_meta meta information about fields
2211 * @param array $row current row
2214 * @author Michal Cihar (michal@cihar.com)
2215 * @return string calculated condition
2217 function PMA_getUvaCondition($handle, $fields_cnt, $fields_meta, $row)
2221 $uva_nonprimary_condition = '';
2223 for ($i = 0; $i < $fields_cnt; ++
$i) {
2224 $field_flags = PMA_DBI_field_flags($handle, $i);
2225 $meta = $fields_meta[$i];
2227 // do not use an alias in a condition
2228 if (! isset($meta->orgname
) ||
! strlen($meta->orgname
)) {
2229 $meta->orgname
= $meta->name
;
2231 if (isset($GLOBALS['analyzed_sql'][0]['select_expr'])
2232 && is_array($GLOBALS['analyzed_sql'][0]['select_expr'])) {
2233 foreach ($GLOBALS['analyzed_sql'][0]['select_expr']
2235 // need (string) === (string)
2236 // '' !== 0 but '' == 0
2237 if ((string) $select_expr['alias'] === (string) $meta->name
) {
2238 $meta->orgname
= $select_expr['column'];
2246 // to fix the bug where float fields (primary or not)
2247 // can't be matched because of the imprecision of
2248 // floating comparison, use CONCAT
2249 // (also, the syntax "CONCAT(field) IS NULL"
2250 // that we need on the next "if" will work)
2251 if ($meta->type
== 'real') {
2252 $condition = ' CONCAT(' . PMA_backquote($meta->table
) . '.'
2253 . PMA_backquote($meta->orgname
) . ') ';
2255 // string and blob fields have to be converted using
2256 // the system character set (always utf8) since
2257 // mysql4.1 can use different charset for fields.
2258 if (PMA_MYSQL_INT_VERSION
>= 40100
2259 && ($meta->type
== 'string' ||
$meta->type
== 'blob')) {
2260 $condition = ' CONVERT(' . PMA_backquote($meta->table
) . '.'
2261 . PMA_backquote($meta->orgname
) . ' USING utf8) ';
2263 $condition = ' ' . PMA_backquote($meta->table
) . '.'
2264 . PMA_backquote($meta->orgname
) . ' ';
2266 } // end if... else...
2268 if (!isset($row[$i]) ||
is_null($row[$i])) {
2269 $condition .= 'IS NULL AND';
2271 // timestamp is numeric on some MySQL 4.1
2272 if ($meta->numeric && $meta->type
!= 'timestamp') {
2273 $condition .= '= ' . $row[$i] . ' AND';
2274 } elseif ($meta->type
== 'blob'
2275 // hexify only if this is a true not empty BLOB
2276 && stristr($field_flags, 'BINARY')
2277 && !empty($row[$i])) {
2278 // use a CAST if possible, to avoid problems
2279 // if the field contains wildcard characters % or _
2280 if (PMA_MYSQL_INT_VERSION
< 40002) {
2281 $condition .= 'LIKE 0x' . bin2hex($row[$i]) . ' AND';
2283 $condition .= '= CAST(0x' . bin2hex($row[$i])
2284 . ' AS BINARY) AND';
2287 $condition .= '= \''
2288 . PMA_sqlAddslashes($row[$i], false, true) . '\' AND';
2291 if ($meta->primary_key
> 0) {
2292 $primary_key .= $condition;
2293 } elseif ($meta->unique_key
> 0) {
2294 $unique_key .= $condition;
2296 $uva_nonprimary_condition .= $condition;
2299 // Correction uva 19991216: prefer primary or unique keys
2300 // for condition, but use conjunction of all values if no
2303 $uva_condition = $primary_key;
2304 } elseif ($unique_key) {
2305 $uva_condition = $unique_key;
2307 $uva_condition = $uva_nonprimary_condition;
2310 return preg_replace('|\s?AND$|', '', $uva_condition);
2314 * Function to generate unique condition for specified row.
2316 * @param string name of button element
2317 * @param string class of button element
2318 * @param string name of image element
2319 * @param string text to display
2320 * @param string image to display
2323 * @author Michal Cihar (michal@cihar.com)
2325 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2328 global $pmaThemeImage, $propicon;
2330 /* Opera has trouble with <input type="image"> */
2331 /* IE has trouble with <button> */
2332 if (PMA_USR_BROWSER_AGENT
!= 'IE') {
2333 echo '<button class="' . $button_class . '" type="submit"'
2334 .' name="' . $button_name . '" value="' . $text . '"'
2335 .' title="' . $text . '">' . "\n"
2336 .'<img class="icon" src="' . $pmaThemeImage . $image . '"'
2337 .' title="' . $text . '" alt="' . $text . '" width="16"'
2339 .($propicon == 'both' ?
' ' . $text : '') . "\n"
2340 .'</button>' . "\n";
2342 echo '<input type="image" name="' . $image_name . '" value="'
2343 . $text . '" title="' . $text . '" src="' . $pmaThemeImage
2345 . ($propicon == 'both' ?
' ' . $text : '') . "\n";
2350 * Generate a pagination selector for browsing resultsets
2352 * @param string URL for the JavaScript
2353 * @param string Number of rows in the pagination set
2354 * @param string current page number
2355 * @param string number of total pages
2356 * @param string If the number of pages is lower than this
2357 * variable, no pages will be ommitted in
2359 * @param string How many rows at the beginning should always
2361 * @param string How many rows at the end should always
2363 * @param string Percentage of calculation page offsets to
2364 * hop to a next page
2365 * @param string Near the current page, how many pages should
2366 * be considered "nearby" and displayed as
2370 * @author Garvin Hicking (pma@supergarv.de)
2372 function PMA_pageselector($url, $rows, $pageNow = 1, $nbTotalPage = 1,
2373 $showAll = 200, $sliceStart = 5, $sliceEnd = 5, $percent = 20,
2376 $gotopage = $GLOBALS['strPageNumber']
2377 . ' <select name="goToPage" onchange="goToUrl(this, \''
2378 . $url . '\');">' . "\n";
2379 if ($nbTotalPage < $showAll) {
2380 $pages = range(1, $nbTotalPage);
2384 // Always show first X pages
2385 for ($i = 1; $i <= $sliceStart; $i++
) {
2389 // Always show last X pages
2390 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++
) {
2394 // garvin: Based on the number of results we add the specified
2395 // $percent percentate to each page number,
2396 // so that we have a representing page number every now and then to
2397 // immideately jump to specific pages.
2398 // As soon as we get near our currently chosen page ($pageNow -
2399 // $range), every page number will be
2402 $x = $nbTotalPage - $sliceEnd;
2403 $met_boundary = false;
2405 if ($i >= ($pageNow - $range) && $i <= ($pageNow +
$range)) {
2406 // If our pageselector comes near the current page, we use 1
2407 // counter increments
2409 $met_boundary = true;
2411 // We add the percentate increment to our current page to
2412 // hop to the next one in range
2413 $i = $i +
floor($nbTotalPage / $percent);
2415 // Make sure that we do not cross our boundaries.
2416 if ($i > ($pageNow - $range) && !$met_boundary) {
2417 $i = $pageNow - $range;
2421 if ($i > 0 && $i <= $x) {
2426 // Since because of ellipsing of the current page some numbers may be double,
2427 // we unify our array:
2429 $pages = array_unique($pages);
2432 foreach ($pages as $i) {
2433 if ($i == $pageNow) {
2434 $selected = 'selected="selected" style="font-weight: bold"';
2438 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2441 $gotopage .= ' </select>';
2447 * @TODO add documentation
2449 function PMA_userDir($dir)
2453 if (substr($dir, -1) != '/') {
2457 return str_replace('%u', $cfg['Server']['user'], $dir);
2461 * returns html code for db link to default db page
2463 * @uses $GLOBALS['cfg']['DefaultTabDatabase']
2464 * @uses $GLOBALS['db']
2465 * @uses $GLOBALS['strJumpToDB']
2466 * @uses PMA_generate_common_url()
2467 * @param string $database
2468 * @return string html link to default db page
2470 function PMA_getDbLink($database = null)
2472 if (!strlen($database)) {
2473 if (!strlen($GLOBALS['db'])) {
2476 $database = $GLOBALS['db'];
2478 $database = PMA_unescape_mysql_wildcards($database);
2481 return '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($database) . '"'
2482 .' title="' . sprintf($GLOBALS['strJumpToDB'], htmlspecialchars($database)) . '">'
2483 .htmlspecialchars($database) . '</a>';
2489 * @uses $GLOBALS['cookie_path']
2490 * @uses $GLOBALS['is_https']
2493 * @param string $cookie name of cookie to remove
2494 * @return boolean result of setcookie()
2496 function PMA_removeCookie($cookie)
2498 return setcookie($cookie, '', time() - 3600,
2499 $GLOBALS['cookie_path'], '', $GLOBALS['is_https']);
2503 * sets cookie if value is different from current cokkie value,
2504 * or removes if value is equal to default
2506 * @uses $GLOBALS['cookie_path']
2507 * @uses $GLOBALS['is_https']
2509 * @uses PMA_removeCookie()
2512 * @param string $cookie name of cookie to remove
2513 * @param mixed $value new cookie value
2514 * @param string $default default value
2515 * @return boolean result of setcookie()
2517 function PMA_setCookie($cookie, $value, $default = null)
2519 if (strlen($value) && null !== $default && $value === $default) {
2520 // remove cookie, default value is used
2521 return PMA_removeCookie($cookie);
2524 if (! strlen($value) && isset($_COOKIE[$cookie])) {
2525 // remove cookie, value is empty
2526 return PMA_removeCookie($cookie);
2529 if (! isset($_COOKIE[$cookie]) ||
$_COOKIE[$cookie] !== $value) {
2530 // set cookie with new value
2531 return setcookie($cookie, $value, time() +
60*60*24*30,
2532 $GLOBALS['cookie_path'], '', $GLOBALS['is_https']);
2535 // cookie has already $value as value
2541 * include here only libraries which contain only function definitions
2542 * no code im main()!
2545 * Include URL/hidden inputs generating.
2547 require_once './libraries/url_generating.lib.php';
2552 /******************************************************************************/
2553 /* start procedural code label_start_procedural */
2556 * protect against older PHP versions' bug about GLOBALS overwrite
2557 * (no need to localize this message :))
2558 * but what if script.php?GLOBALS[admin]=1&GLOBALS[_REQUEST]=1 ???
2560 if (isset($_REQUEST['GLOBALS']) ||
isset($_FILES['GLOBALS'])
2561 ||
isset($_SERVER['GLOBALS']) ||
isset($_COOKIE['GLOBALS'])
2562 ||
isset($_ENV['GLOBALS'])) {
2563 die('GLOBALS overwrite attempt');
2567 * just to be sure there was no import (registering) before here
2568 * we empty the global space
2570 $variables_whitelist = array (
2582 foreach (get_defined_vars() as $key => $value) {
2583 if (!in_array($key, $variables_whitelist)) {
2587 unset($key, $value);
2591 * check if a subform is submitted
2594 if (isset($_POST['usesubform'])) {
2595 // if a subform is present and should be used
2596 // the rest of the form is deprecated
2597 $subform_id = key($_POST['usesubform']);
2598 $subform = $_POST['subform'][$subform_id];
2600 $_REQUEST = $subform;
2601 if (isset($_POST['redirect'])
2602 && $_POST['redirect'] != basename(getenv('PHP_SELF'))) {
2603 $__redirect = $_POST['redirect'];
2604 unset($_POST['redirect']);
2605 } // end if (isset($_POST['redirect']))
2606 unset($subform_id, $subform);
2607 } // end if (isset($_POST['usesubform']))
2608 // end check if a subform is submitted
2610 if (get_magic_quotes_gpc()) {
2611 PMA_arrayWalkRecursive($_GET, 'stripslashes');
2612 PMA_arrayWalkRecursive($_POST, 'stripslashes');
2613 PMA_arrayWalkRecursive($_COOKIE, 'stripslashes');
2614 PMA_arrayWalkRecursive($_REQUEST, 'stripslashes');
2617 require_once './libraries/session.inc.php';
2620 * include deprecated grab_globals only if required
2622 if (empty($__redirect) && !defined('PMA_NO_VARIABLES_IMPORT')) {
2623 require './libraries/grab_globals.lib.php';
2627 * init some variables LABEL_variables_init
2631 * @var array $GLOBALS['PMA_errors'] holds errors
2633 $GLOBALS['PMA_errors'] = array();
2636 * @var array $GLOBALS['url_params'] holds params to be passed to next page
2638 $GLOBALS['url_params'] = array();
2641 * @var array whitelist for $goto
2643 $goto_whitelist = array(
2644 //'browse_foreigners.php',
2651 'db_details_export.php',
2652 'db_details_importdocsql.php',
2653 'db_details_qbe.php',
2654 'db_details_structure.php',
2656 'db_operations.php',
2659 //'Documentation.html',
2672 'server_binlog.php',
2673 'server_collations.php',
2674 'server_databases.php',
2675 'server_engines.php',
2676 'server_export.php',
2677 'server_import.php',
2678 'server_privileges.php',
2679 'server_processlist.php',
2681 'server_status.php',
2682 'server_variables.php',
2690 'tbl_move_copy.php',
2691 'tbl_printview.php',
2692 'tbl_properties.php',
2693 'tbl_properties_export.php',
2694 'tbl_properties_operations.php',
2695 'tbl_properties_structure.php',
2698 'tbl_row_action.php',
2701 'transformation_overview.php',
2702 'transformation_wrapper.php',
2704 'user_password.php',
2708 * check $__redirect against whitelist
2710 if (! PMA_checkPageValidity($__redirect, $goto_whitelist)) {
2715 * @var string $goto holds page that should be displayed
2717 // Security fix: disallow accessing serious server files via "?goto="
2718 if (PMA_checkPageValidity($_REQUEST['goto'], $goto_whitelist)) {
2719 $GLOBALS['goto'] = $_REQUEST['goto'];
2720 $GLOBALS['url_params']['goto'] = $_REQUEST['goto'];
2722 unset($_REQUEST['goto'], $_GET['goto'], $_POST['goto'], $_COOKIE['goto']);
2723 $GLOBALS['goto'] = '';
2727 * @var string $back returning page
2729 if (PMA_checkPageValidity($_REQUEST['back'], $goto_whitelist)) {
2730 $GLOBALS['back'] = $_REQUEST['back'];
2732 unset($_REQUEST['back'], $_GET['back'], $_POST['back'], $_COOKIE['back']);
2736 * @var string $convcharset
2737 * @see also select_lang.lib.php
2739 if (isset($_REQUEST['convcharset'])) {
2740 $convcharset = strip_tags($_REQUEST['convcharset']);
2744 * @var string $db current selected database
2746 if (isset($_REQUEST['db'])) {
2747 // can we strip tags from this?
2748 // only \ and / is not allowed in db names for MySQL
2749 $GLOBALS['db'] = $_REQUEST['db'];
2750 $GLOBALS['url_params']['db'] = $GLOBALS['db'];
2752 $GLOBALS['db'] = '';
2756 * @var string $db current selected database
2758 if (isset($_REQUEST['table'])) {
2759 // can we strip tags from this?
2760 // only \ and / is not allowed in table names for MySQL
2761 $GLOBALS['table'] = $_REQUEST['table'];
2762 $GLOBALS['url_params']['table'] = $GLOBALS['table'];
2764 $GLOBALS['table'] = '';
2768 * @var string $sql_query sql query to be executed
2770 if (isset($_REQUEST['sql_query'])) {
2771 $GLOBALS['sql_query'] = $_REQUEST['sql_query'];
2774 //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup
2775 //$_REQUEST['server']; // checked later in this file
2776 //$_REQUEST['lang']; // checked by LABEL_loading_language_file
2780 /******************************************************************************/
2781 /* parsing config file LABEL_parsing_config_file */
2783 if (empty($_SESSION['PMA_Config'])) {
2785 * We really need this one!
2787 if (!function_exists('preg_replace')) {
2788 header('Location: error.php'
2789 . '?lang=' . urlencode($available_languages[$lang][2])
2790 . '&char=' . urlencode($charset)
2791 . '&dir=' . urlencode($text_dir)
2792 . '&type=' . urlencode($strError)
2793 . '&error=' . urlencode(
2794 strtr(sprintf($strCantLoad, 'pcre'),
2795 array('<br />' => '[br]')))
2801 $_SESSION['PMA_Config'] = new PMA_Config('./config.inc.php');
2803 } elseif (version_compare(phpversion(), '5', 'lt')) {
2804 $_SESSION['PMA_Config']->__wakeup();
2807 if (!defined('PMA_MINIMUM_COMMON')) {
2808 $_SESSION['PMA_Config']->checkPmaAbsoluteUri();
2812 $_SESSION['PMA_Config']->enableBc();
2816 * check https connection
2818 if ($_SESSION['PMA_Config']->get('ForceSSL')
2819 && !$_SESSION['PMA_Config']->get('is_https')) {
2820 PMA_sendHeaderLocation(
2821 preg_replace('/^http/', 'https',
2822 $_SESSION['PMA_Config']->get('PmaAbsoluteUri'))
2823 . PMA_generate_common_url($_GET));
2828 /******************************************************************************/
2829 /* loading language file LABEL_loading_language_file */
2832 * Added messages while developing:
2834 if (file_exists('./lang/added_messages.php')) {
2835 include './lang/added_messages.php';
2839 * Includes the language file if it hasn't been included yet
2841 require_once './libraries/select_lang.lib.php';
2845 * check for errors occured while loading config
2847 if ($_SESSION['PMA_Config']->error_config_file
) {
2848 $GLOBALS['PMA_errors'][] = $strConfigFileError
2850 . ($_SESSION['PMA_Config']->getSource() == './config.inc.php' ?
2851 '<a href="show_config_errors.php"'
2852 .' target="_blank">' . $_SESSION['PMA_Config']->getSource() . '</a>'
2854 '<a href="' . $_SESSION['PMA_Config']->getSource() . '"'
2855 .' target="_blank">' . $_SESSION['PMA_Config']->getSource() . '</a>');
2857 if ($_SESSION['PMA_Config']->error_config_default_file
) {
2858 $GLOBALS['PMA_errors'][] = sprintf($strConfigDefaultFileError,
2859 $_SESSION['PMA_Config']->default_source
);
2861 if ($_SESSION['PMA_Config']->error_pma_uri
) {
2862 $GLOBALS['PMA_errors'][] = sprintf($strPmaUriError);
2866 * Servers array fixups.
2867 * $default_server comes from PMA_Config::enableBc()
2868 * @todo merge into PMA_Config
2870 // Do we have some server?
2871 if (!isset($cfg['Servers']) ||
count($cfg['Servers']) == 0) {
2872 // No server => create one with defaults
2873 $cfg['Servers'] = array(1 => $default_server);
2875 // We have server(s) => apply default config
2876 $new_servers = array();
2878 foreach ($cfg['Servers'] as $server_index => $each_server) {
2880 // Detect wrong configuration
2881 if (!is_int($server_index) ||
$server_index < 1) {
2882 $GLOBALS['PMA_errors'][] = sprintf($strInvalidServerIndex, $server_index);
2885 $each_server = array_merge($default_server, $each_server);
2887 // Don't use servers with no hostname
2888 if ($each_server['connect_type'] == 'tcp' && empty($each_server['host'])) {
2889 $GLOBALS['PMA_errors'][] = sprintf($strInvalidServerHostname, $server_index);
2892 // Final solution to bug #582890
2893 // If we are using a socket connection
2894 // and there is nothing in the verbose server name
2895 // or the host field, then generate a name for the server
2896 // in the form of "Server 2", localized of course!
2897 if ($each_server['connect_type'] == 'socket' && empty($each_server['host']) && empty($each_server['verbose'])) {
2898 $each_server['verbose'] = $GLOBALS['strServer'] . $server_index;
2901 $new_servers[$server_index] = $each_server;
2903 $cfg['Servers'] = $new_servers;
2904 unset($new_servers, $server_index, $each_server);
2908 unset($default_server);
2911 /******************************************************************************/
2912 /* setup themes LABEL_theme_setup */
2914 if (!isset($_SESSION['PMA_Theme_Manager'])) {
2915 $_SESSION['PMA_Theme_Manager'] = new PMA_Theme_Manager
;
2918 if (isset($_REQUEST['set_theme'])) {
2919 // if user submit a theme
2920 $_SESSION['PMA_Theme_Manager']->setActiveTheme($_REQUEST['set_theme']);
2921 } elseif (version_compare(phpversion(), '5', 'lt')) {
2922 $_SESSION['PMA_Theme_Manager']->__wakeup();
2925 $_SESSION['PMA_Theme'] = $_SESSION['PMA_Theme_Manager']->theme
;
2926 if (version_compare(phpversion(), '5', 'lt')) {
2927 $_SESSION['PMA_Theme']->__wakeup();
2931 $GLOBALS['theme'] = $_SESSION['PMA_Theme']->getName();
2932 $GLOBALS['pmaThemePath'] = $_SESSION['PMA_Theme']->getPath();
2933 $GLOBALS['pmaThemeImage'] = $_SESSION['PMA_Theme']->getImgPath();
2936 * load layout file if exists
2938 if (@file_exists
($_SESSION['PMA_Theme']->getLayoutFile())) {
2939 include $_SESSION['PMA_Theme']->getLayoutFile();
2942 if (!defined('PMA_MINIMUM_COMMON')) {
2944 * Charset conversion.
2946 require_once './libraries/charset_conversion.lib.php';
2951 require_once './libraries/string.lib.php';
2954 * @var array database list
2959 * If no server is selected, make sure that $cfg['Server'] is empty (so
2960 * that nothing will work), and skip server authentication.
2961 * We do NOT exit here, but continue on without logging into any server.
2962 * This way, the welcome page will still come up (with no server info) and
2963 * present a choice of servers in the case that there are multiple servers
2964 * and '$cfg['ServerDefault'] = 0' is set.
2966 if (!empty($_REQUEST['server']) && !empty($cfg['Servers'][$_REQUEST['server']])) {
2967 $GLOBALS['server'] = $_REQUEST['server'];
2968 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
2970 if (!empty($cfg['Servers'][$cfg['ServerDefault']])) {
2971 $GLOBALS['server'] = $cfg['ServerDefault'];
2972 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
2974 $GLOBALS['server'] = 0;
2975 $cfg['Server'] = array();
2978 $GLOBALS['url_params']['server'] = $GLOBALS['server'];
2981 if (!empty($cfg['Server'])) {
2984 * Loads the proper database interface for this server
2986 require_once './libraries/database_interface.lib.php';
2988 // Gets the authentication library that fits the $cfg['Server'] settings
2989 // and run authentication
2991 // (for a quick check of path disclosure in auth/cookies:)
2992 $coming_from_common = true;
2994 if (!file_exists('./libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php')) {
2995 header('Location: error.php'
2996 . '?lang=' . urlencode($available_languages[$lang][2])
2997 . '&char=' . urlencode($charset)
2998 . '&dir=' . urlencode($text_dir)
2999 . '&type=' . urlencode($strError)
3000 . '&error=' . urlencode(
3001 $strInvalidAuthMethod . ' '
3002 . $cfg['Server']['auth_type'])
3007 require_once './libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php';
3008 if (!PMA_auth_check()) {
3011 PMA_auth_set_user();
3014 // Check IP-based Allow/Deny rules as soon as possible to reject the
3016 // Based on mod_access in Apache:
3017 // http://cvs.apache.org/viewcvs.cgi/httpd-2.0/modules/aaa/mod_access.c?rev=1.37&content-type=text/vnd.viewcvs-markup
3018 // Look at: "static int check_dir_access(request_rec *r)"
3019 // Robbat2 - May 10, 2002
3020 if (isset($cfg['Server']['AllowDeny'])
3021 && isset($cfg['Server']['AllowDeny']['order'])) {
3023 require_once './libraries/ip_allow_deny.lib.php';
3025 $allowDeny_forbidden = false; // default
3026 if ($cfg['Server']['AllowDeny']['order'] == 'allow,deny') {
3027 $allowDeny_forbidden = true;
3028 if (PMA_allowDeny('allow')) {
3029 $allowDeny_forbidden = false;
3031 if (PMA_allowDeny('deny')) {
3032 $allowDeny_forbidden = true;
3034 } elseif ($cfg['Server']['AllowDeny']['order'] == 'deny,allow') {
3035 if (PMA_allowDeny('deny')) {
3036 $allowDeny_forbidden = true;
3038 if (PMA_allowDeny('allow')) {
3039 $allowDeny_forbidden = false;
3041 } elseif ($cfg['Server']['AllowDeny']['order'] == 'explicit') {
3042 if (PMA_allowDeny('allow')
3043 && !PMA_allowDeny('deny')) {
3044 $allowDeny_forbidden = false;
3046 $allowDeny_forbidden = true;
3048 } // end if ... elseif ... elseif
3050 // Ejects the user if banished
3051 if ($allowDeny_forbidden) {
3054 unset($allowDeny_forbidden); //Clean up after you!
3058 if (!$cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') {
3059 $allowDeny_forbidden = true;
3061 unset($allowDeny_forbidden); //Clean up after you!
3064 // The user can work with only some databases
3065 if (isset($cfg['Server']['only_db']) && $cfg['Server']['only_db'] != '') {
3066 if (is_array($cfg['Server']['only_db'])) {
3067 $dblist = $cfg['Server']['only_db'];
3069 $dblist[] = $cfg['Server']['only_db'];
3073 $bkp_track_err = @ini_set
('track_errors', 1);
3075 // Try to connect MySQL with the control user profile (will be used to
3076 // get the privileges list for the current user but the true user link
3077 // must be open after this one so it would be default one for all the
3079 if ($cfg['Server']['controluser'] != '') {
3080 $controllink = PMA_DBI_connect($cfg['Server']['controluser'],
3081 $cfg['Server']['controlpass'], true);
3083 $controllink = PMA_DBI_connect($cfg['Server']['user'],
3084 $cfg['Server']['password'], true);
3085 } // end if ... else
3087 // Pass #1 of DB-Config to read in master level DB-Config will go here
3088 // Robbat2 - May 11, 2002
3090 // Connects to the server (validates user's login)
3091 $userlink = PMA_DBI_connect($cfg['Server']['user'],
3092 $cfg['Server']['password'], false);
3094 // Pass #2 of DB-Config to read in user level DB-Config will go here
3095 // Robbat2 - May 11, 2002
3097 @ini_set
('track_errors', $bkp_track_err);
3098 unset($bkp_track_err);
3103 require_once './libraries/sqlparser.lib.php';
3106 * SQL Validator interface code
3108 require_once './libraries/sqlvalidator.lib.php';
3110 // if 'only_db' is set for the current user, there is no need to check for
3111 // available databases in the "mysql" db
3112 $dblist_cnt = count($dblist);
3114 $true_dblist = array();
3115 $is_show_dbs = true;
3117 $dblist_asterisk_bool = false;
3118 for ($i = 0; $i < $dblist_cnt; $i++
) {
3120 // The current position
3121 if ($dblist[$i] == '*' && $dblist_asterisk_bool == false) {
3122 $dblist_asterisk_bool = true;
3123 $dblist_full = PMA_safe_db_list(false, $controllink, false,
3124 $userlink, $cfg, $dblist);
3125 foreach ($dblist_full as $dbl_val) {
3126 if (!in_array($dbl_val, $dblist)) {
3127 $true_dblist[] = $dbl_val;
3132 } elseif ($dblist[$i] == '*') {
3133 // We don't want more than one asterisk inside our 'only_db'.
3136 if ($is_show_dbs && ereg('(^|[^\])(_|%)', $dblist[$i])) {
3137 $local_query = 'SHOW DATABASES LIKE \'' . $dblist[$i] . '\'';
3138 // here, a PMA_DBI_query() could fail silently
3139 // if SHOW DATABASES is disabled
3140 $rs = PMA_DBI_try_query($local_query, $controllink);
3142 if ($i == 0 && ! $rs) {
3143 $error_code = substr(PMA_DBI_getError($controllink), 1, 4);
3144 if ($error_code == 1227 ||
$error_code == 1045) {
3145 // "SHOW DATABASES" statement is disabled or not allowed to user
3146 $true_dblist[] = str_replace('\\_', '_', str_replace('\\%', '%', $dblist[$i]));
3147 $is_show_dbs = false;
3152 // elseif (PMA_DBI_getError($controllink)) {
3153 // PMA_mysqlDie(PMA_DBI_getError($controllink), $local_query, false);
3155 while ($row = @PMA_DBI_fetch_row
($rs)) {
3156 $true_dblist[] = $row[0];
3159 PMA_DBI_free_result($rs);
3162 $true_dblist[] = str_replace('\\_', '_',
3163 str_replace('\\%', '%', $dblist[$i]));
3164 } // end if... else...
3166 $dblist = $true_dblist;
3167 unset($true_dblist, $i, $dbl_val);
3168 $only_db_check = true;
3171 // 'only_db' is empty for the current user...
3173 $only_db_check = false;
3174 } // end if (!$dblist_cnt)
3176 if (isset($dblist_full) && !count($dblist_full)) {
3177 $dblist = PMA_safe_db_list($only_db_check, $controllink,
3178 $dblist_cnt, $userlink, $cfg, $dblist);
3180 unset($only_db_check, $dblist_full);
3182 } // end server connecting
3185 // Kanji encoding convert feature appended by Y.Kawada (2002/2/20)
3186 if (@function_exists
('mb_convert_encoding')
3187 && strpos(' ' . $lang, 'ja-')
3188 && file_exists('./libraries/kanji-encoding.lib.php')) {
3189 require_once './libraries/kanji-encoding.lib.php';
3190 define('PMA_MULTIBYTE_ENCODING', 1);
3194 * save some settings in cookies
3196 PMA_setCookie('pma_lang', $GLOBALS['lang']);
3197 PMA_setCookie('pma_charset', $GLOBALS['convcharset']);
3198 PMA_setCookie('pma_collation_connection', $GLOBALS['collation_connection']);
3200 $_SESSION['PMA_Theme_Manager']->setThemeCookie();
3202 } // end if !defined('PMA_MINIMUM_COMMON')
3204 if (!empty($__redirect) && in_array($__redirect, $goto_whitelist)) {
3205 // to handle bug #1388167
3206 if (isset($_GET['is_js_confirmed'])) {
3207 $is_js_confirmed = 1;
3209 require $__redirect;