no longer used
[phpmyadmin/crack.git] / libraries / common.lib.php
blob94eb0a5b6261fb420b191ef3edc633b12565eb34
1 <?php
2 /* $Id$ */
3 // vim: expandtab sw=4 ts=4 sts=4:
5 /**
6 * Misc stuff and functions used by almost all the scripts.
7 * Among other things, it contains the advanced authentication work.
8 */
10 /**
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
28 * LABEL_theme_setup
29 * - setting up themes
31 * - load of mysql extension (if necessary) label_loading_mysql
32 * - loading of an authentication library label_
33 * - db connection
34 * - authentication work
35 * - load of the libraries/defines_mysql.lib.php library to get the MySQL
36 * release number
39 /**
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);
48 } else {
49 error_reporting($old_error_reporting);
51 unset($old_error_reporting);
54 /**
55 * Avoid object cloning errors
58 @ini_set('zend.ze1_compatibility_mode',false);
61 /******************************************************************************/
62 /* definition of functions LABEL_definition_of_functions */
63 /**
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
72 * @access public
73 * @author Marc Delisle (lem9@users.sourceforge.net)
75 function PMA_securePath($path)
77 // change .. to .
78 $path = preg_replace('@\.\.*@', '.', $path);
80 return $path;
81 } // end function
83 /**
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()
97 * @uses is_array()
98 * @uses implode()
99 * @uses strstr()
100 * @uses explode()
101 * @return array db list
103 function PMA_getDbList()
105 if (empty($GLOBALS['dblist'])) {
106 PMA_availableDatabases();
108 $dblist = $GLOBALS['dblist'];
109 $dbgroups = array();
110 $parts = array();
111 foreach ($dblist as $key => $db) {
112 // garvin: Get comments from PMA comments table
113 $db_tooltip = '';
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);
129 } else {
130 $group = $db;
131 $disp_name_cut = $db;
134 $disp_name = $db;
135 if ($db_tooltip && $GLOBALS['cfg']['ShowTooltipAliasDB']) {
136 $disp_name = $db_tooltip;
137 $disp_name_cut = $db_tooltip;
138 $db_tooltip = $db;
141 $dbgroups[$group][$db] = array(
142 'name' => $db,
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)
149 return $dbgroups;
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
162 // and EN
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>'
166 ."\n";
167 foreach ($dblist as $group => $dbs) {
168 if (count($dbs) > 1) {
169 $return .= '<optgroup label="' . htmlspecialchars($group)
170 . '">' . "\n";
171 // wether display db_name cuted by the group part
172 $cut = true;
173 } else {
174 // .. or full
175 $cut = false;
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>';
192 return $return;
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);
206 if ($tables) {
207 $num_tables = PMA_DBI_num_rows($tables);
208 PMA_DBI_free_result($tables);
209 } else {
210 $num_tables = 0;
213 return $num_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
230 * @access private
232 function PMA_safe_db_list($only_db_check, $controllink, $dblist_cnt, $userlink,
233 $cfg, $dblist)
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.
246 if (!$dblist_cnt) {
247 $auth_query = 'SELECT User, Select_priv '
248 . 'FROM mysql.user '
249 . 'WHERE User = \'' . PMA_sqlAddslashes($cfg['Server']['user']) . '\'';
250 $rs = PMA_DBI_try_query($auth_query, $controllink);
251 } // end
254 // Access to "mysql" db allowed and dblist still empty -> gets the
255 // usable db list
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
268 // expressions.
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
277 // lines:
278 // the 1st is the only line intact from before
279 // correction,
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'] == '%') {
289 $uva_mydbs['%'] = 1;
290 break;
292 // loic1: avoid multiple entries for dbs
293 if (!isset($uva_mydbs[$row['Db']])) {
294 $uva_mydbs[$row['Db']] = 1;
296 } // end while
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];
303 } // end while
304 } else {
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) {
308 $dblist[] = $uva_db;
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)) {
320 $dblist[] = $uva_db;
321 break;
323 } // end while
324 } // end if ... elseif ...
325 } // end while
326 } // end else
327 PMA_DBI_free_result($uva_alldbs);
328 unset($uva_mydbs);
329 } // end if
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'];
339 } // end while
340 PMA_DBI_free_result($rs);
341 } // end if
342 } // end if
343 } // end building available dbs from the "mysql" db
345 return $dblist;
349 * Converts numbers like 10M into bytes
351 * @param string $size
352 * @return integer $size
354 function get_real_size($size = 0)
356 if (!$size) {
357 return 0;
359 $scan['MB'] = 1048576;
360 $scan['Mb'] = 1048576;
361 $scan['M'] = 1048576;
362 $scan['m'] = 1048576;
363 $scan['KB'] = 1024;
364 $scan['Kb'] = 1024;
365 $scan['K'] = 1024;
366 $scan['k'] = 1024;
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];
372 break;
375 return $size;
376 } // end function get_real_size()
379 * loads php module
381 * @uses PHP_OS
382 * @uses extension_loaded()
383 * @uses ini_get()
384 * @uses function_exists()
385 * @uses ob_start()
386 * @uses phpinfo()
387 * @uses strip_tags()
388 * @uses ob_get_contents()
389 * @uses ob_end_clean()
390 * @uses preg_match()
391 * @uses strtoupper()
392 * @uses substr()
393 * @uses dl()
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)) {
402 return true;
405 if (null === $dl_allowed) {
406 if (!@ini_get('safe_mode')
407 && @ini_get('enable_dl')
408 && @function_exists('dl')) {
409 ob_start();
410 phpinfo(INFO_GENERAL); /* Only general info */
411 $a = strip_tags(ob_get_contents());
412 ob_end_clean();
413 if (preg_match('@Thread Safety[[:space:]]*enabled@', $a)) {
414 if (preg_match('@Server API[[:space:]]*\(CGI\|CLI\)@', $a)) {
415 $dl_allowed = true;
416 } else {
417 $dl_allowed = false;
419 } else {
420 $dl_allowed = true;
422 } else {
423 $dl_allowed = false;
427 if (!$dl_allowed) {
428 return false;
431 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
432 $module_file = 'php_' . $module . '.dll';
433 } else {
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()
450 * @uses is_array()
451 * @uses call_user_func_array()
452 * @param array array to merge
453 * @param array array to merge
454 * @param array ...
455 * @return array merged array
457 function PMA_array_merge_recursive()
459 switch(func_num_args()) {
460 case 0 :
461 return false;
462 break;
463 case 1 :
464 // when does that happen?
465 return func_get_arg(0);
466 break;
467 case 2 :
468 $args = func_get_args();
469 if (!is_array($args[0]) || !is_array($args[1])) {
470 return $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],
475 $value2);
476 } else {
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) {
482 unset($args[0]);
484 $args[0][$key2] = $value2;
487 return $args[0];
488 break;
489 default :
490 $args = func_get_args();
491 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
492 array_shift($args);
493 return call_user_func_array('PMA_array_merge_recursive', $args);
494 break;
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);
509 } else {
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)
521 * @uses in_array()
522 * @uses urldecode()
523 * @uses substr()
524 * @uses strpos()
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)) {
532 return false;
535 if (in_array($page, $whitelist)) {
536 return true;
537 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
538 return true;
539 } else {
540 $_page = urldecode($page);
541 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
542 return true;
545 return false;
549 * include here only libraries which contain only function definitions
550 * no code im main()!
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" />';
576 } else {
577 return $alternate;
582 * Displays the maximum size for an upload
584 * @param integer the size
586 * @return string the message
588 * @access public
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
604 * @access public
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
626 * @access public
628 function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
630 if ($is_like) {
631 $a_string = str_replace('\\', '\\\\\\\\', $a_string);
632 } else {
633 $a_string = str_replace('\\', '\\\\', $a_string);
636 if ($crlf) {
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);
642 if ($php_code) {
643 $a_string = str_replace('\'', '\\\'', $a_string);
644 } else {
645 $a_string = str_replace('\'', '\'\'', $a_string);
648 return $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
661 * @access public
663 function PMA_escape_mysql_wildcards($name)
665 $name = str_replace('_', '\\_', $name);
666 $name = str_replace('%', '\\%', $name);
668 return $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
677 * @access public
679 function PMA_unescape_mysql_wildcards($name)
681 $name = str_replace('\\_', '_', $name);
682 $name = str_replace('\\%', '%', $name);
684 return $name;
685 } // end of the 'PMA_unescape_mysql_wildcards()' function
688 * format sql strings
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
697 * @access public
699 * @author Robin Johnson <robbat2@users.sourceforge.net>
701 function PMA_formatSql($parsed_sql, $unparsed_sql = '')
703 global $cfg;
705 // Check that we actually have a valid set of parsed data
706 // well, not quite
707 // first check for the SQL parser having hit an error
708 if (PMA_SQP_isError()) {
709 return $parsed_sql;
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"
717 . '</pre>';
718 return $formatted_sql;
721 $formatted_sql = '';
723 switch ($cfg['SQP']['fmtType']) {
724 case 'none':
725 if ($unparsed_sql != '') {
726 $formatted_sql = "<pre>\n" . PMA_SQP_formatNone(array('raw' => $unparsed_sql)) . "\n</pre>";
727 } else {
728 $formatted_sql = PMA_SQP_formatNone($parsed_sql);
730 break;
731 case 'html':
732 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'color');
733 break;
734 case 'text':
735 //$formatted_sql = PMA_SQP_formatText($parsed_sql);
736 $formatted_sql = PMA_SQP_formatHtml($parsed_sql, 'text');
737 break;
738 default:
739 break;
740 } // end switch
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
755 * @access public
757 function PMA_showMySQLDocu($chapter, $link, $big_icon = false)
759 global $cfg;
761 if ($cfg['MySQLManualType'] == 'none' || empty($cfg['MySQLManualBase'])) {
762 return '';
765 // Fixup for newly used names:
766 $chapter = str_replace('_', '-', strtolower($chapter));
767 $link = str_replace('_', '-', strtolower($link));
769 switch ($cfg['MySQLManualType']) {
770 case 'chapters':
771 if (empty($chapter)) {
772 $chapter = 'index';
774 $url = $cfg['MySQLManualBase'] . '/' . $chapter . '.html#' . $link;
775 break;
776 case 'big':
777 $url = $cfg['MySQLManualBase'] . '#' . $link;
778 break;
779 case 'searchable':
780 if (empty($link)) {
781 $link = 'index';
783 $url = $cfg['MySQLManualBase'] . '/' . $link . '.html';
784 break;
785 case 'viewable':
786 default:
787 if (empty($link)) {
788 $link = 'index';
790 $mysql = '5.0';
791 if (defined('PMA_MYSQL_INT_VERSION')) {
792 if (PMA_MYSQL_INT_VERSION < 50000) {
793 $mysql = '4.1';
794 } elseif (PMA_MYSQL_INT_VERSION >= 50100) {
795 $mysql = '5.1';
796 } elseif (PMA_MYSQL_INT_VERSION >= 50000) {
797 $mysql = '5.0';
800 $url = $cfg['MySQLManualBase'] . '/' . $mysql . '/en/' . $link . '.html';
801 break;
804 if ($big_icon) {
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>';
808 } else {
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
818 * @access public
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
837 * @access public
839 function PMA_mysqlDie($error_message = '', $the_query = '',
840 $is_modify_link = true, $back_url = '',
841 $exit = true)
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) == '') {
860 $formatted_sql = '';
861 } else {
862 $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query);
864 // ---
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
869 // username/password
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";
878 // ---
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)) {
885 if (isset($table)) {
886 $doedit_goto = '<a href="tbl_properties.php?' . PMA_generate_common_url($db, $table) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
887 } else {
888 $doedit_goto = '<a href="db_details.php?' . PMA_generate_common_url($db) . '&amp;sql_query=' . urlencode($the_query) . '&amp;show_query=1">';
890 if ($GLOBALS['cfg']['PropertiesIconic']) {
891 echo $doedit_goto
892 . '<img class="icon" src=" '. $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" alt="' . $GLOBALS['strEdit'] .'" />'
893 . '</a>';
894 } else {
895 echo ' ['
896 . $doedit_goto . $GLOBALS['strEdit'] . '</a>'
897 . ']' . "\n";
899 } // end if
900 echo ' </p>' . "\n"
901 .' <p>' . "\n"
902 .' ' . $formatted_sql . "\n"
903 .' </p>' . "\n";
904 } // end if
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)
913 echo '<p>' . "\n"
914 . ' <strong>' . $GLOBALS['strMySQLSaid'] . '</strong>'
915 . PMA_showMySQLDocu('Error-returns', 'Error-returns')
916 . "\n"
917 . '</p>' . "\n";
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(' ', '&nbsp;&nbsp;', $error_message);
924 // Replace TAB-characters with their HTML-counterpart
925 $error_message = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $error_message);
926 // Replace linebreaks
927 $error_message = nl2br($error_message);
929 echo '<code>' . "\n"
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
940 // get table name
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];
948 // get fields
949 $error_fields = array();
950 preg_match('@\(([^\)]+)\)@i', $the_query, $error_fields);
951 $error_fields = explode(',', $error_fields[1]);
953 // duplicate value
954 $duplicate_value = array();
955 preg_match('@\'([^\']+)\'@i', $tmp_mysql_error, $duplicate_value);
956 $duplicate_value = $duplicate_value[1];
958 $sql = '
959 SELECT *
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"
970 .' </form>' . "\n";
971 unset($sql);
972 } // end of show duplicate entry
974 echo '</div>';
975 echo '<fieldset class="tblFooters">';
977 if (!empty($back_url) && $exit) {
978 $goto_back_url='<a href="' . (strstr($back_url, '?') ? $back_url . '&amp;no_history=true' : $back_url . '?no_history=true') . '">';
979 echo '[ ' . $goto_back_url . $GLOBALS['strBack'] . '</a> ]';
981 echo ' </fieldset>' . "\n\n";
982 if ($exit) {
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
996 * @access private
998 function PMA_convert_using($string, $mode='unquoted')
1000 if ($mode == 'quoted') {
1001 $possible_quote = "'";
1002 } else {
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 . ")";
1009 } else {
1010 $converted_string = $possible_quote . $string . $possible_quote;
1012 return $converted_string;
1013 } // end function
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";
1042 } else {
1043 if (SID) {
1044 if (strpos($uri, '?') === false) {
1045 header('Location: ' . $uri . '?' . SID);
1046 } else {
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) {
1051 $separator = ';';
1052 } elseif (strlen($php_arg_separator_input) > 0) {
1053 $separator = $php_arg_separator_input{0};
1054 } else {
1055 $separator = '&';
1057 header('Location: ' . $uri . $separator . SID);
1059 } else {
1060 session_write_close();
1061 if (PMA_IS_IIS) {
1062 header('Refresh: 0; ' . $uri);
1063 } else {
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 = '')
1083 global $dblist;
1084 global $num_dbs;
1085 global $cfg;
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]);
1093 } // end if
1094 } // end for
1095 } // end if
1096 // 2. Allowed database list is empty -> gets the list of all databases
1097 // on the server
1098 elseif (empty($cfg['Server']['only_db'])) {
1099 $dblist = PMA_DBI_get_dblist(); // needed? or PMA_mysqlDie('', 'SHOW DATABASES;', false, $error_url);
1100 } // end else
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']) {
1108 natsort($dblist);
1111 return true;
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()
1123 * @uses count()
1124 * @uses array_merge
1125 * @uses uksort()
1126 * @uses strstr()
1127 * @uses explode()
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) {
1143 return $tables;
1146 $default = array(
1147 'Name' => '',
1148 'Rows' => 0,
1149 'Comment' => '',
1150 'disp_name' => '',
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
1164 // in this case.
1166 // set this because PMA_Table::countRecords() can use it
1167 $tbl_is_view = PMA_Table::isView($db, $table['Name']);
1169 if ($tbl_is_view) {
1170 $table['Rows'] = PMA_Table::countRecords($db, $table['Name'],
1171 $return = true);
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;
1183 $i = 0;
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;
1199 unset($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;
1203 } else {
1204 $group[$group_name]['tab' . $sep . 'count']++;
1206 $group =& $group[$group_name];
1207 $i++;
1209 } else {
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'];
1222 } else {
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
1238 * these names.
1240 * @param mixed the database, table or field name to "backquote" or
1241 * array of it
1242 * @param boolean a flag to bypass this function (used by dump
1243 * functions)
1245 * @return mixed the "backquoted" database, table or field name if the
1246 * current MySQL release is >= 3.23.6, the original one
1247 * else
1249 * @access public
1251 function PMA_backquote($a_name, $do_it = true)
1253 // '0' is also empty for php :-(
1254 if ($do_it
1255 && isset($a_name) && !empty($a_name) && $a_name != '*') {
1257 if (is_array($a_name)) {
1258 $result = array();
1259 foreach ($a_name as $key => $val) {
1260 $result[$key] = '`' . $val . '`';
1262 return $result;
1263 } else {
1264 return '`' . $a_name . '`';
1266 } else {
1267 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
1282 * @access public
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
1304 * @access public
1306 function PMA_whichCrlf()
1308 $the_crlf = "\n";
1310 // The 'PMA_USR_OS' constant is defined in "./libraries/defines.lib.php"
1311 // Win case
1312 if (PMA_USR_OS == 'Win') {
1313 $the_crlf = "\r\n";
1315 // Mac case
1316 elseif (PMA_USR_OS == 'Mac') {
1317 $the_crlf = "\r";
1319 // Others
1320 else {
1321 $the_crlf = "\n";
1324 return $the_crlf;
1325 } // end of the 'PMA_whichCrlf()' function
1328 * Reloads navigation if needed.
1330 * @global mixed configuration
1331 * @global bool whether to reload
1333 * @access public
1335 function PMA_reloadNavigation()
1337 global $cfg;
1339 // Reloads the navigation frame via JavaScript if required
1340 if (isset($GLOBALS['reload']) && $GLOBALS['reload']) {
1341 echo "\n";
1342 $reload_url = './left.php?' . PMA_generate_common_url((isset($GLOBALS['db']) ? $GLOBALS['db'] : ''), '', '&');
1344 <script type="text/javascript" language="javascript">
1345 //<![CDATA[
1346 if (typeof(window.parent) != 'undefined'
1347 && typeof(window.parent.frames[0]) != 'undefined') {
1348 window.parent.goTo('<?php echo $reload_url; ?>');
1350 //]]>
1351 </script>
1352 <?php
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
1364 * @access public
1366 function PMA_showMessage($message)
1368 global $cfg;
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) . '\'');
1376 if ($result) {
1377 $tbl_status = PMA_DBI_fetch_assoc($result);
1378 $tooltip = (empty($tbl_status['Comment']))
1379 ? ''
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);
1384 echo "\n";
1386 <script type="text/javascript" language="javascript">
1387 //<![CDATA[
1388 window.parent.updateTableTitle('<?php echo $uni_tbl; ?>', '<?php echo PMA_jsFormat($tooltip, false); ?>');
1389 //]]>
1390 </script>
1391 <?php
1392 } // end if
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) . '\'');
1400 if ($result) {
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']));
1409 unset($tbl_status);
1411 <br />
1412 <div align="<?php echo $GLOBALS['cell_align_left']; ?>">
1413 <?php
1414 if (!empty($GLOBALS['show_error_header'])) {
1416 <div class="error">
1417 <h1><?php echo $GLOBALS['strError']; ?></h1>
1418 <?php
1421 echo $message;
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'])) {
1428 echo '</div>';
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" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
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);
1451 } else {
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'];
1458 } else {
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);
1466 // Analyze it
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);
1492 } else {
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'];
1508 //} else {
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;';
1518 } else {
1519 $onclick = '';
1522 $edit_link = $edit_target
1523 . $url_qpart
1524 . '&amp;sql_query=' . urlencode($local_query)
1525 . '&amp;show_query=1#querybox';
1526 $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
1527 } else {
1528 $edit_link = '';
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 = '&amp;validatequery=1';
1541 } else {
1542 $explain_link_validate = '';
1545 $explain_link = 'import.php'
1546 . $url_qpart
1547 . $explain_link_validate
1548 . '&amp;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'];
1556 } else {
1557 $explain_link = '';
1559 if (!empty($explain_link)) {
1560 $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
1562 } else {
1563 $explain_link = '';
1564 } //show explain
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'
1571 . $url_qpart
1572 . '&amp;show_query=1'
1573 . '&amp;sql_query=' . urlencode($local_query)
1574 . '&amp;show_as_php=';
1576 if (!empty($GLOBALS['show_as_php'])) {
1577 $php_link .= '0';
1578 $message = $GLOBALS['strNoPhp'];
1579 } else {
1580 $php_link .= '1';
1581 $message = $GLOBALS['strPhp'];
1583 $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
1585 if (isset($GLOBALS['show_as_php']) && $GLOBALS['show_as_php'] == '1') {
1586 $runquery_link
1587 = 'import.php'
1588 . $url_qpart
1589 . '&amp;show_query=1'
1590 . '&amp;sql_query=' . urlencode($local_query);
1591 $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
1594 } else {
1595 $php_link = '';
1596 } //show as php
1598 // Refresh query
1599 if (isset($cfg['SQLQuery']['Refresh'])
1600 && $cfg['SQLQuery']['Refresh']
1601 && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $local_query)) {
1603 $refresh_link = 'import.php'
1604 . $url_qpart
1605 . '&amp;show_query=1'
1606 . (isset($_GET['pos']) ? '&amp;pos=' . $_GET['pos'] : '')
1607 . '&amp;sql_query=' . urlencode($local_query);
1608 $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
1609 } else {
1610 $refresh_link = '';
1611 } //show as php
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'
1618 . $url_qpart
1619 . '&amp;show_query=1'
1620 . '&amp;sql_query=' . urlencode($local_query)
1621 . '&amp;validatequery=';
1622 if (!empty($GLOBALS['validatequery'])) {
1623 $validate_link .= '0';
1624 $validate_message = $GLOBALS['strNoValidateSQL'] ;
1625 } else {
1626 $validate_link .= '1';
1627 $validate_message = $GLOBALS['strValidateSQL'] ;
1629 $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
1630 } else {
1631 $validate_link = '';
1632 } //validator
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'])) {
1642 echo '\';';
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;
1649 echo '</fieldset>';
1653 </div><br />
1654 <?php
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
1667 * @access public
1669 * @author staybyte
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];
1683 break 1;
1684 } // end if
1685 } // end for
1687 if ($unit != $GLOBALS['byteUnits'][0]) {
1688 $return_value = number_format($value, $comma, $GLOBALS['number_decimal_separator'], $GLOBALS['number_thousands_separator']);
1689 } else {
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
1701 * <code>
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
1708 * </code>
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
1716 * @access public
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,
1725 $comma,
1726 $GLOBALS['number_decimal_separator'],
1727 $GLOBALS['number_thousands_separator']);
1730 // this units needs no translation, ISO
1731 $units = array(
1732 -8 => 'y',
1733 -7 => 'z',
1734 -6 => 'a',
1735 -5 => 'f',
1736 -4 => 'p',
1737 -3 => 'n',
1738 -2 => '&micro;',
1739 -1 => 'm',
1740 0 => ' ',
1741 1 => 'k',
1742 2 => 'M',
1743 3 => 'G',
1744 4 => 'T',
1745 5 => 'P',
1746 6 => 'E',
1747 7 => 'Z',
1748 8 => 'Y'
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
1757 if ($value < 0) {
1758 $sign = '-';
1759 $value = abs($value);
1760 } else {
1761 $sign = '';
1764 $dh = pow(10, $comma);
1765 $li = pow(10, $length);
1766 $unit = $units[0];
1768 if ($value >= 1) {
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;
1772 $unit = $units[$d];
1773 break 1;
1774 } // end if
1775 } // end for
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;
1780 $unit = $units[$d];
1781 break 1;
1782 } // end if
1783 } // end for
1784 } // end if ($value >= 1) elseif (!$only_down && (float) $value !== 0.0)
1786 $value = number_format($value,
1787 $comma,
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.
1802 * @author rabus
1804 function PMA_getEnumSetOptions($type_def)
1806 $open = strpos($type_def, '(');
1807 $close = strrpos($type_def, ')');
1808 if (!$open || !$close) {
1809 return false;
1811 $options = substr($type_def, $open + 2, $close - $open - 3);
1812 $options = explode('\',\'', $options);
1813 return $options;
1814 } // end of the 'PMA_getEnumSetOptions' function
1817 * Writes localised date
1819 * @param string the current timestamp
1821 * @return string the formatted date
1823 * @access public
1825 function PMA_localisedDate($timestamp = -1, $format = '')
1827 global $datefmt, $month, $day_of_week;
1829 if ($format == '') {
1830 $format = $datefmt;
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()
1849 * basename()
1850 * $GLOBALS['strEmpty']
1851 * $GLOBALS['strDrop']
1852 * $GLOBALS['active_page']
1853 * $GLOBALS['PHP_SELF']
1854 * htmlentities()
1855 * PMA_generate_common_url()
1856 * $GLOBALS['url_query']
1857 * urlencode()
1858 * $GLOBALS['cfg']['MainPageIconic']
1859 * $GLOBALS['pmaThemeImage']
1860 * sprintf()
1861 * trigger_error()
1862 * E_USER_NOTICE
1863 * @param array $tab array with all options
1864 * @return string html code for one tab, a link if valid otherwise a span
1865 * @access public
1867 function PMA_getTab($tab)
1869 // default values
1870 $defaults = array(
1871 'text' => '',
1872 'class' => '',
1873 'active' => false,
1874 'link' => '',
1875 'sep' => '?',
1876 'attr' => '',
1877 'args' => '',
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';
1896 // build the link
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'] .= '&amp;' . 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'])) {
1919 $tab['text'] = '?';
1920 trigger_error('empty linktext in function ' . __FUNCTION__ . '()',
1921 E_USER_NOTICE);
1924 if (!empty($tab['link'])) {
1925 $out = '<a class="tab' . htmlentities($tab['class']) . '"'
1926 .' href="' . $tab['link'] . '" ' . $tab['attr'] . '>'
1927 . $tab['text'] . '</a>';
1928 } else {
1929 $out = '<span class="tab' . htmlentities($tab['class']) . '">'
1930 . $tab['text'] . '</span>';
1933 return $out;
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')
1947 $tab_navigation =
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";
1955 $tab_navigation .=
1956 '</ul>' . "\n"
1957 .'<div class="clearfloat"></div>'
1958 .'</div>' . "\n";
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)) {
1981 $tmp = $tag_params;
1982 $tag_params = array();
1983 if (!empty($tmp)) {
1984 $tag_params['onclick'] = 'return confirmLink(this, \'' . $tmp . '\')';
1986 unset($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'
1996 ? $par_value
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";
2007 } else {
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('&amp;', '&', $url);
2017 $url_parts = parse_url($url);
2018 $query_parts = explode('&', $url_parts['query']);
2019 if ($new_form) {
2020 $ret = '<form action="' . $url_parts['path'] . '" class="link"'
2021 . ' method="post"' . $target . ' style="display: inline;">';
2022 $subname_open = '';
2023 $subname_close = '';
2024 $submit_name = '';
2025 } else {
2026 $query_parts[] = 'redirect=' . $url_parts['path'];
2027 if (empty($GLOBALS['subform_counter'])) {
2028 $GLOBALS['subform_counter'] = 0;
2030 $GLOBALS['subform_counter']++;
2031 $ret = '';
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)) . '" />';
2041 } // end while
2043 if (stristr($message, '<img')) {
2044 if ($strip_img) {
2045 $message = trim(strip_tags($message));
2046 $ret .= '<input type="submit"' . $submit_name . ' '
2047 . implode(' ', $tag_params_strings)
2048 . ' value="' . htmlspecialchars($message) . '" />';
2049 } else {
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',
2056 $message))
2057 . '" />';
2059 } else {
2060 $message = trim(strip_tags($message));
2061 $ret .= '<input type="submit"' . $submit_name . ' '
2062 . implode(' ', $tag_params_strings)
2063 . ' value="' . htmlspecialchars($message) . '" />';
2065 if ($new_form) {
2066 $ret .= '</form>';
2068 } // end if... else...
2070 return $ret;
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);
2085 if ($days > 0) {
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")
2109 * @access public
2110 * @author Garvin Hicking <me@supergarv.de>
2111 * @return string The flipped string
2113 function PMA_flipstring($string, $Separator = "<br />\n")
2115 $format_string = '';
2116 $charbuff = false;
2118 for ($i = 0; $i < strlen($string); $i++) {
2119 $char = $string{$i};
2120 $append = false;
2122 if ($char == '&') {
2123 $format_string .= $charbuff;
2124 $charbuff = $char;
2125 $append = true;
2126 } elseif (!empty($charbuff)) {
2127 $charbuff .= $char;
2128 } elseif ($char == ';' && !empty($charbuff)) {
2129 $format_string .= $charbuff;
2130 $charbuff = false;
2131 $append = true;
2132 } else {
2133 $format_string .= $char;
2134 $append = true;
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
2155 * script.
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
2163 * @access public
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;
2188 if ($found_error) {
2189 require_once './libraries/header_meta_style.inc.php';
2190 echo '</head><body><p>' . $error_message . '</p></body></html>';
2191 if ($die) {
2192 exit();
2195 } // end function
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()
2205 * @uses stristr()
2206 * @uses bin2hex()
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
2213 * @access public
2214 * @author Michal Cihar (michal@cihar.com)
2215 * @return string calculated condition
2217 function PMA_getUvaCondition($handle, $fields_cnt, $fields_meta, $row)
2219 $primary_key = '';
2220 $unique_key = '';
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']
2234 as $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'];
2239 break;
2240 } // end if
2241 } // end foreach
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) . ') ';
2254 } else {
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) ';
2262 } else {
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';
2270 } else {
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';
2282 } else {
2283 $condition .= '= CAST(0x' . bin2hex($row[$i])
2284 . ' AS BINARY) AND';
2286 } else {
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;
2297 } // end for
2299 // Correction uva 19991216: prefer primary or unique keys
2300 // for condition, but use conjunction of all values if no
2301 // primary key
2302 if ($primary_key) {
2303 $uva_condition = $primary_key;
2304 } elseif ($unique_key) {
2305 $uva_condition = $unique_key;
2306 } else {
2307 $uva_condition = $uva_nonprimary_condition;
2310 return preg_replace('|\s?AND$|', '', $uva_condition);
2311 } // end function
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
2322 * @access public
2323 * @author Michal Cihar (michal@cihar.com)
2325 function PMA_buttonOrImage($button_name, $button_class, $image_name, $text,
2326 $image)
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"'
2338 .' height="16" />'
2339 .($propicon == 'both' ? '&nbsp;' . $text : '') . "\n"
2340 .'</button>' . "\n";
2341 } else {
2342 echo '<input type="image" name="' . $image_name . '" value="'
2343 . $text . '" title="' . $text . '" src="' . $pmaThemeImage
2344 . $image . '" />'
2345 . ($propicon == 'both' ? '&nbsp;' . $text : '') . "\n";
2347 } // end function
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
2358 * pagination
2359 * @param string How many rows at the beginning should always
2360 * be shown?
2361 * @param string How many rows at the end should always
2362 * be shown?
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
2367 * well?
2369 * @access public
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,
2374 $range = 10)
2376 $gotopage = $GLOBALS['strPageNumber']
2377 . ' <select name="goToPage" onchange="goToUrl(this, \''
2378 . $url . '\');">' . "\n";
2379 if ($nbTotalPage < $showAll) {
2380 $pages = range(1, $nbTotalPage);
2381 } else {
2382 $pages = array();
2384 // Always show first X pages
2385 for ($i = 1; $i <= $sliceStart; $i++) {
2386 $pages[] = $i;
2389 // Always show last X pages
2390 for ($i = $nbTotalPage - $sliceEnd; $i <= $nbTotalPage; $i++) {
2391 $pages[] = $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
2400 // shown.
2401 $i = $sliceStart;
2402 $x = $nbTotalPage - $sliceEnd;
2403 $met_boundary = false;
2404 while ($i <= $x) {
2405 if ($i >= ($pageNow - $range) && $i <= ($pageNow + $range)) {
2406 // If our pageselector comes near the current page, we use 1
2407 // counter increments
2408 $i++;
2409 $met_boundary = true;
2410 } else {
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) {
2422 $pages[] = $i;
2426 // Since because of ellipsing of the current page some numbers may be double,
2427 // we unify our array:
2428 sort($pages);
2429 $pages = array_unique($pages);
2432 foreach ($pages as $i) {
2433 if ($i == $pageNow) {
2434 $selected = 'selected="selected" style="font-weight: bold"';
2435 } else {
2436 $selected = '';
2438 $gotopage .= ' <option ' . $selected . ' value="' . (($i - 1) * $rows) . '">' . $i . '</option>' . "\n";
2441 $gotopage .= ' </select>';
2443 return $gotopage;
2444 } // end function
2447 * @TODO add documentation
2449 function PMA_userDir($dir)
2451 global $cfg;
2453 if (substr($dir, -1) != '/') {
2454 $dir .= '/';
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'])) {
2474 return '';
2476 $database = $GLOBALS['db'];
2477 } else {
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>';
2487 * removes cookie
2489 * @uses $GLOBALS['cookie_path']
2490 * @uses $GLOBALS['is_https']
2491 * @uses setcookie()
2492 * @uses time()
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']
2508 * @uses $_COOKIE
2509 * @uses PMA_removeCookie()
2510 * @uses setcookie()
2511 * @uses time()
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
2536 return true;
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 (
2571 'GLOBALS',
2572 '_SERVER',
2573 '_GET',
2574 '_POST',
2575 '_REQUEST',
2576 '_FILES',
2577 '_ENV',
2578 '_COOKIE',
2579 '_SESSION',
2582 foreach (get_defined_vars() as $key => $value) {
2583 if (!in_array($key, $variables_whitelist)) {
2584 unset($$key);
2587 unset($key, $value);
2591 * check if a subform is submitted
2593 $__redirect = null;
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];
2599 $_POST = $subform;
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',
2645 //'calendar.php',
2646 //'changelog.php',
2647 //'chk_rel.php',
2648 'db_create.php',
2649 'db_datadict.php',
2650 'db_details.php',
2651 'db_details_export.php',
2652 'db_details_importdocsql.php',
2653 'db_details_qbe.php',
2654 'db_details_structure.php',
2655 'db_import.php',
2656 'db_operations.php',
2657 'db_printview.php',
2658 'db_search.php',
2659 //'Documentation.html',
2660 //'error.php',
2661 'export.php',
2662 'import.php',
2663 //'index.php',
2664 //'left.php',
2665 //'license.php',
2666 'main.php',
2667 'pdf_pages.php',
2668 'pdf_schema.php',
2669 //'phpinfo.php',
2670 'querywindow.php',
2671 //'readme.php',
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',
2680 'server_sql.php',
2681 'server_status.php',
2682 'server_variables.php',
2683 'sql.php',
2684 'tbl_addfield.php',
2685 'tbl_alter.php',
2686 'tbl_change.php',
2687 'tbl_create.php',
2688 'tbl_import.php',
2689 'tbl_indexes.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',
2696 'tbl_relation.php',
2697 'tbl_replace.php',
2698 'tbl_row_action.php',
2699 'tbl_select.php',
2700 //'themes.php',
2701 'transformation_overview.php',
2702 'transformation_wrapper.php',
2703 'translators.html',
2704 'user_password.php',
2708 * check $__redirect against whitelist
2710 if (! PMA_checkPageValidity($__redirect, $goto_whitelist)) {
2711 $__redirect = null;
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'];
2721 } else {
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'];
2731 } else {
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'];
2751 } else {
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'];
2763 } else {
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]')))
2796 . '&' . SID
2798 exit();
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();
2811 // BC
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));
2824 exit;
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
2849 . '<br /><br />'
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);
2874 } else {
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);
2907 // Cleanup
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();
2930 // BC
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';
2949 * String handling
2951 require_once './libraries/string.lib.php';
2954 * @var array database list
2956 $dblist = array();
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']];
2969 } else {
2970 if (!empty($cfg['Servers'][$cfg['ServerDefault']])) {
2971 $GLOBALS['server'] = $cfg['ServerDefault'];
2972 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
2973 } else {
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'])
3003 . '&' . SID
3005 exit();
3007 require_once './libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php';
3008 if (!PMA_auth_check()) {
3009 PMA_auth();
3010 } else {
3011 PMA_auth_set_user();
3014 // Check IP-based Allow/Deny rules as soon as possible to reject the
3015 // user
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;
3045 } else {
3046 $allowDeny_forbidden = true;
3048 } // end if ... elseif ... elseif
3050 // Ejects the user if banished
3051 if ($allowDeny_forbidden) {
3052 PMA_auth_fails();
3054 unset($allowDeny_forbidden); //Clean up after you!
3055 } // end if
3057 // is root allowed?
3058 if (!$cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') {
3059 $allowDeny_forbidden = true;
3060 PMA_auth_fails();
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'];
3068 } else {
3069 $dblist[] = $cfg['Server']['only_db'];
3071 } // end if
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
3078 // scripts)
3079 if ($cfg['Server']['controluser'] != '') {
3080 $controllink = PMA_DBI_connect($cfg['Server']['controluser'],
3081 $cfg['Server']['controlpass'], true);
3082 } else {
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);
3101 * SQL Parser code
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);
3113 if ($dblist_cnt) {
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;
3131 continue;
3132 } elseif ($dblist[$i] == '*') {
3133 // We don't want more than one asterisk inside our 'only_db'.
3134 continue;
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;
3149 unset($error_code);
3151 // Debug
3152 // elseif (PMA_DBI_getError($controllink)) {
3153 // PMA_mysqlDie(PMA_DBI_getError($controllink), $local_query, false);
3154 // }
3155 while ($row = @PMA_DBI_fetch_row($rs)) {
3156 $true_dblist[] = $row[0];
3157 } // end while
3158 if ($rs) {
3159 PMA_DBI_free_result($rs);
3161 } else {
3162 $true_dblist[] = str_replace('\\_', '_',
3163 str_replace('\\%', '%', $dblist[$i]));
3164 } // end if... else...
3165 } // end for
3166 $dblist = $true_dblist;
3167 unset($true_dblist, $i, $dbl_val);
3168 $only_db_check = true;
3169 } // end if
3171 // 'only_db' is empty for the current user...
3172 else {
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);
3191 } // end if
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;
3210 exit();