UPDATE 4.4.0.0
[phpmyadmin.git] / libraries / common.inc.php
blobc1476de7264b5fe7b581b70c80ba61f2daca9d26
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Misc stuff and REQUIRED by ALL the scripts.
5 * MUST be included by every script
7 * Among other things, it contains the advanced authentication work.
9 * Order of sections for common.inc.php:
11 * the authentication libraries must be before the connection to db
13 * ... so the required order is:
15 * LABEL_variables_init
16 * - initialize some variables always needed
17 * LABEL_parsing_config_file
18 * - parsing of the configuration file
19 * LABEL_loading_language_file
20 * - loading language file
21 * LABEL_setup_servers
22 * - check and setup configured servers
23 * LABEL_theme_setup
24 * - setting up themes
26 * - load of MySQL extension (if necessary)
27 * - loading of an authentication library
28 * - db connection
29 * - authentication work
31 * @package PhpMyAdmin
34 /**
35 * block attempts to directly run this script
37 if (getcwd() == dirname(__FILE__)) {
38 die('Attack stopped');
41 /**
42 * Minimum PHP version; can't call PMA_fatalError() which uses a
43 * PHP 5 function, so cannot easily localize this message.
45 if (version_compare(PHP_VERSION, '5.3.0', 'lt')) {
46 die('PHP 5.3+ is required');
49 /**
50 * for verification in all procedural scripts under libraries
52 define('PHPMYADMIN', true);
55 /**
56 * String handling (security)
58 require_once './libraries/String.class.php';
59 $PMA_String = new PMA_String();
61 /**
62 * the error handler
64 require './libraries/Error_Handler.class.php';
66 /**
67 * initialize the error handler
69 $GLOBALS['error_handler'] = new PMA_Error_Handler();
71 /**
72 * This setting was removed in PHP 5.4. But at this point PMA_PHP_INT_VERSION
73 * is not yet defined so we use another way to find out the PHP version.
75 if (version_compare(phpversion(), '5.4', 'lt')) {
76 /**
77 * Avoid problems with magic_quotes_runtime
79 @ini_set('magic_quotes_runtime', 'false');
82 /**
83 * core functions
85 require './libraries/core.lib.php';
87 /**
88 * Input sanitizing
90 require './libraries/sanitizing.lib.php';
92 /**
93 * Warning about mbstring.
95 if (! function_exists('mb_detect_encoding')) {
96 PMA_warnMissingExtension('mbstring', $fatal = true);
99 /**
100 * the PMA_Theme class
102 require './libraries/Theme.class.php';
105 * the PMA_Theme_Manager class
107 require './libraries/Theme_Manager.class.php';
110 * the PMA_Config class
112 require './libraries/Config.class.php';
115 * the relation lib, tracker needs it
117 require './libraries/relation.lib.php';
120 * the PMA_Tracker class
122 require './libraries/Tracker.class.php';
125 * the PMA_Table class
127 require './libraries/Table.class.php';
130 * the PMA_Types class
132 require './libraries/Types.class.php';
134 if (! defined('PMA_MINIMUM_COMMON')) {
136 * common functions
138 include_once './libraries/Util.class.php';
141 * JavaScript escaping.
143 include_once './libraries/js_escape.lib.php';
146 * Include URL/hidden inputs generating.
148 include_once './libraries/url_generating.lib.php';
151 * Used to generate the page
153 include_once 'libraries/Response.class.php';
156 /******************************************************************************/
157 /* start procedural code label_start_procedural */
160 * PATH_INFO could be compromised if set, so remove it from PHP_SELF
161 * and provide a clean PHP_SELF here
163 $PMA_PHP_SELF = PMA_getenv('PHP_SELF');
164 $_PATH_INFO = PMA_getenv('PATH_INFO');
165 if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
166 $path_info_pos = /*overload*/mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
167 $pathLength = $path_info_pos + /*overload*/mb_strlen($_PATH_INFO);
168 if ($pathLength === /*overload*/mb_strlen($PMA_PHP_SELF)) {
169 $PMA_PHP_SELF = /*overload*/mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
172 $PMA_PHP_SELF = htmlspecialchars($PMA_PHP_SELF);
176 * just to be sure there was no import (registering) before here
177 * we empty the global space (but avoid unsetting $variables_list
178 * and $key in the foreach (), we still need them!)
180 $variables_whitelist = array (
181 'GLOBALS',
182 '_SERVER',
183 '_GET',
184 '_POST',
185 '_REQUEST',
186 '_FILES',
187 '_ENV',
188 '_COOKIE',
189 '_SESSION',
190 'error_handler',
191 'PMA_PHP_SELF',
192 'variables_whitelist',
193 'key',
194 'PMA_String'
197 foreach (get_defined_vars() as $key => $value) {
198 if (! in_array($key, $variables_whitelist)) {
199 unset($$key);
202 unset($key, $value, $variables_whitelist);
206 * Subforms - some functions need to be called by form, cause of the limited URL
207 * length, but if this functions inside another form you cannot just open a new
208 * form - so phpMyAdmin uses 'arrays' inside this form
210 * <code>
211 * <form ...>
212 * ... main form elements ...
213 * <input type="hidden" name="subform[action1][id]" value="1" />
214 * ... other subform data ...
215 * <input type="submit" name="usesubform[action1]" value="do action1" />
216 * ... other subforms ...
217 * <input type="hidden" name="subform[actionX][id]" value="X" />
218 * ... other subform data ...
219 * <input type="submit" name="usesubform[actionX]" value="do actionX" />
220 * ... main form elements ...
221 * <input type="submit" name="main_action" value="submit form" />
222 * </form>
223 * </code>
225 * so we now check if a subform is submitted
227 $__redirect = null;
228 if (isset($_POST['usesubform'])) {
229 // if a subform is present and should be used
230 // the rest of the form is deprecated
231 $subform_id = key($_POST['usesubform']);
232 $subform = $_POST['subform'][$subform_id];
233 $_POST = $subform;
234 $_REQUEST = $subform;
236 * some subforms need another page than the main form, so we will just
237 * include this page at the end of this script - we use $__redirect to
238 * track this
240 if (isset($_POST['redirect'])
241 && $_POST['redirect'] != basename($PMA_PHP_SELF)
243 $__redirect = $_POST['redirect'];
244 unset($_POST['redirect']);
246 unset($subform_id, $subform);
247 } else {
248 // Note: here we overwrite $_REQUEST so that it does not contain cookies,
249 // because another application for the same domain could have set
250 // a cookie (with a compatible path) that overrides a variable
251 // we expect from GET or POST.
252 // We'll refer to cookies explicitly with the $_COOKIE syntax.
253 $_REQUEST = array_merge($_GET, $_POST);
255 // end check if a subform is submitted
258 * This setting was removed in PHP 5.4, but get_magic_quotes_gpc
259 * always returns False since then.
261 if (get_magic_quotes_gpc()) {
262 PMA_arrayWalkRecursive($_GET, 'stripslashes', true);
263 PMA_arrayWalkRecursive($_POST, 'stripslashes', true);
264 PMA_arrayWalkRecursive($_COOKIE, 'stripslashes', true);
265 PMA_arrayWalkRecursive($_REQUEST, 'stripslashes', true);
269 * check timezone setting
270 * this could produce an E_STRICT - but only once,
271 * if not done here it will produce E_STRICT on every date/time function
272 * (starting with PHP 5.3, this code can produce E_WARNING rather than
273 * E_STRICT)
276 date_default_timezone_set(@date_default_timezone_get());
278 /******************************************************************************/
279 /* parsing configuration file LABEL_parsing_config_file */
282 * We really need this one!
284 if (! function_exists('preg_replace')) {
285 PMA_warnMissingExtension('pcre', true);
289 * JSON is required in several places.
291 if (! function_exists('json_encode')) {
292 PMA_warnMissingExtension('json', true);
296 * @global PMA_Config $GLOBALS['PMA_Config']
297 * force reading of config file, because we removed sensitive values
298 * in the previous iteration
300 $GLOBALS['PMA_Config'] = new PMA_Config(CONFIG_FILE);
302 if (!defined('PMA_MINIMUM_COMMON')) {
303 $GLOBALS['PMA_Config']->checkPmaAbsoluteUri();
307 * BC - enable backward compatibility
308 * exports all configuration settings into $GLOBALS ($GLOBALS['cfg'])
310 $GLOBALS['PMA_Config']->enableBc();
313 * clean cookies on upgrade
314 * when changing something related to PMA cookies, increment the cookie version
316 $pma_cookie_version = 4;
317 if (isset($_COOKIE)
318 && (isset($_COOKIE['pmaCookieVer'])
319 && $_COOKIE['pmaCookieVer'] < $pma_cookie_version)
321 // delete all cookies
322 foreach ($_COOKIE as $cookie_name => $tmp) {
323 $GLOBALS['PMA_Config']->removeCookie($cookie_name);
325 $_COOKIE = array();
326 $GLOBALS['PMA_Config']->setCookie('pmaCookieVer', $pma_cookie_version);
331 * check HTTPS connection
333 if ($GLOBALS['PMA_Config']->get('ForceSSL')
334 && ! $GLOBALS['PMA_Config']->get('is_https')
336 // grab SSL URL
337 $url = $GLOBALS['PMA_Config']->getSSLUri();
338 // Actually redirect
339 PMA_sendHeaderLocation($url . PMA_URL_getCommon($_GET, 'text'));
340 // delete the current session, otherwise we get problems (see bug #2397877)
341 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
342 exit;
347 * include session handling after the globals, to prevent overwriting
349 require './libraries/session.inc.php';
352 * init some variables LABEL_variables_init
356 * holds parameters to be passed to next page
357 * @global array $GLOBALS['url_params']
359 $GLOBALS['url_params'] = array();
362 * the whitelist for $GLOBALS['goto']
363 * @global array $goto_whitelist
365 $goto_whitelist = array(
366 //'browse_foreigners.php',
367 //'changelog.php',
368 //'chk_rel.php',
369 'db_create.php',
370 'db_datadict.php',
371 'db_sql.php',
372 'db_events.php',
373 'db_export.php',
374 'db_importdocsql.php',
375 'db_qbe.php',
376 'db_structure.php',
377 'db_import.php',
378 'db_operations.php',
379 'db_printview.php',
380 'db_search.php',
381 'db_routines.php',
382 'export.php',
383 'import.php',
384 //'index.php',
385 //'navigation.php',
386 //'license.php',
387 'index.php',
388 'pdf_pages.php',
389 'pdf_schema.php',
390 //'phpinfo.php',
391 'server_binlog.php',
392 'server_collations.php',
393 'server_databases.php',
394 'server_engines.php',
395 'server_export.php',
396 'server_import.php',
397 'server_privileges.php',
398 'server_sql.php',
399 'server_status.php',
400 'server_status_advisor.php',
401 'server_status_monitor.php',
402 'server_status_queries.php',
403 'server_status_variables.php',
404 'server_variables.php',
405 'sql.php',
406 'tbl_addfield.php',
407 'tbl_change.php',
408 'tbl_create.php',
409 'tbl_import.php',
410 'tbl_indexes.php',
411 'tbl_printview.php',
412 'tbl_sql.php',
413 'tbl_export.php',
414 'tbl_operations.php',
415 'tbl_structure.php',
416 'tbl_relation.php',
417 'tbl_replace.php',
418 'tbl_row_action.php',
419 'tbl_select.php',
420 'tbl_zoom_select.php',
421 //'themes.php',
422 'transformation_overview.php',
423 'transformation_wrapper.php',
424 'user_password.php',
428 * check $__redirect against whitelist
430 if (! PMA_checkPageValidity($__redirect, $goto_whitelist)) {
431 $__redirect = null;
435 * holds page that should be displayed
436 * @global string $GLOBALS['goto']
438 $GLOBALS['goto'] = '';
439 // Security fix: disallow accessing serious server files via "?goto="
440 if (PMA_checkPageValidity($_REQUEST['goto'], $goto_whitelist)) {
441 $GLOBALS['goto'] = $_REQUEST['goto'];
442 $GLOBALS['url_params']['goto'] = $_REQUEST['goto'];
443 } else {
444 unset($_REQUEST['goto'], $_GET['goto'], $_POST['goto'], $_COOKIE['goto']);
448 * returning page
449 * @global string $GLOBALS['back']
451 if (PMA_checkPageValidity($_REQUEST['back'], $goto_whitelist)) {
452 $GLOBALS['back'] = $_REQUEST['back'];
453 } else {
454 unset($_REQUEST['back'], $_GET['back'], $_POST['back'], $_COOKIE['back']);
458 * Check whether user supplied token is valid, if not remove any possibly
459 * dangerous stuff from request.
461 * remember that some objects in the session with session_start and __wakeup()
462 * could access this variables before we reach this point
463 * f.e. PMA_Config: fontsize
465 * @todo variables should be handled by their respective owners (objects)
466 * f.e. lang, server, collation_connection in PMA_Config
468 $token_mismatch = true;
469 $token_provided = false;
470 if (PMA_isValid($_REQUEST['token'])) {
471 $token_provided = true;
472 $token_mismatch = ($_SESSION[' PMA_token '] != $_REQUEST['token']);
475 if ($token_mismatch) {
477 * List of parameters which are allowed from unsafe source
479 $allow_list = array(
480 /* needed for direct access, see FAQ 1.34
481 * also, server needed for cookie login screen (multi-server)
483 'server', 'db', 'table', 'target', 'lang',
484 /* Session ID */
485 'phpMyAdmin',
486 /* Cookie preferences */
487 'pma_lang', 'pma_collation_connection',
488 /* Possible login form */
489 'pma_servername', 'pma_username', 'pma_password',
490 'recaptcha_challenge_field', 'recaptcha_response_field',
491 /* Needed to send the correct reply */
492 'ajax_request',
493 /* Permit to log out even if there is a token mismatch */
494 'old_usr',
495 /* Permit redirection with token-mismatch in url.php */
496 'url',
497 /* Permit session expiry flag */
498 'session_expired'
501 * Allow changing themes in test/theme.php
503 if (defined('PMA_TEST_THEME')) {
504 $allow_list[] = 'set_theme';
507 * Require cleanup functions
509 include './libraries/cleanup.lib.php';
511 * Do actual cleanup
513 PMA_removeRequestVars($allow_list);
519 * current selected database
520 * @global string $GLOBALS['db']
522 PMA_setGlobalDbOrTable('db');
525 * current selected table
526 * @global string $GLOBALS['table']
528 PMA_setGlobalDbOrTable('table');
531 * Store currently selected recent table.
532 * Affect $GLOBALS['db'] and $GLOBALS['table']
534 if (PMA_isValid($_REQUEST['selected_recent_table'])) {
535 $recent_table = json_decode($_REQUEST['selected_recent_table'], true);
536 $GLOBALS['db'] = $recent_table['db'];
537 $GLOBALS['url_params']['db'] = $GLOBALS['db'];
538 $GLOBALS['table'] = $recent_table['table'];
539 $GLOBALS['url_params']['table'] = $GLOBALS['table'];
543 * SQL query to be executed
544 * @global string $GLOBALS['sql_query']
546 $GLOBALS['sql_query'] = '';
547 if (PMA_isValid($_REQUEST['sql_query'])) {
548 $GLOBALS['sql_query'] = $_REQUEST['sql_query'];
551 //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup
552 //$_REQUEST['server']; // checked later in this file
553 //$_REQUEST['lang']; // checked by LABEL_loading_language_file
555 /******************************************************************************/
556 /* loading language file LABEL_loading_language_file */
559 * lang detection is done here
561 require './libraries/select_lang.lib.php';
563 // Defines the cell alignment values depending on text direction
564 if ($GLOBALS['text_dir'] == 'ltr') {
565 $GLOBALS['cell_align_left'] = 'left';
566 $GLOBALS['cell_align_right'] = 'right';
567 } else {
568 $GLOBALS['cell_align_left'] = 'right';
569 $GLOBALS['cell_align_right'] = 'left';
573 * check for errors occurred while loading configuration
574 * this check is done here after loading language files to present errors in locale
576 $GLOBALS['PMA_Config']->checkPermissions();
578 if ($GLOBALS['PMA_Config']->error_config_file) {
579 $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
580 . '[br][br]'
581 . __('This usually means there is a syntax error in it, please check any errors shown below.')
582 . '[br][br]'
583 . '[conferr]';
584 trigger_error($error, E_USER_ERROR);
586 if ($GLOBALS['PMA_Config']->error_config_default_file) {
587 $error = sprintf(
588 __('Could not load default configuration from: %1$s'),
589 $GLOBALS['PMA_Config']->default_source
591 trigger_error($error, E_USER_ERROR);
593 if ($GLOBALS['PMA_Config']->error_pma_uri) {
594 trigger_error(
596 'The [code]$cfg[\'PmaAbsoluteUri\'][/code]'
597 . ' directive MUST be set in your configuration file!'
599 E_USER_ERROR
604 /******************************************************************************/
605 /* setup servers LABEL_setup_servers */
608 * current server
609 * @global integer $GLOBALS['server']
611 $GLOBALS['server'] = 0;
614 * Servers array fixups.
615 * $default_server comes from PMA_Config::enableBc()
616 * @todo merge into PMA_Config
618 // Do we have some server?
619 if (! isset($cfg['Servers']) || count($cfg['Servers']) == 0) {
620 // No server => create one with defaults
621 $cfg['Servers'] = array(1 => $default_server);
622 } else {
623 // We have server(s) => apply default configuration
624 $new_servers = array();
626 foreach ($cfg['Servers'] as $server_index => $each_server) {
628 // Detect wrong configuration
629 if (!is_int($server_index) || $server_index < 1) {
630 trigger_error(
631 sprintf(__('Invalid server index: %s'), $server_index),
632 E_USER_ERROR
636 $each_server = array_merge($default_server, $each_server);
638 // Don't use servers with no hostname
639 if ($each_server['connect_type'] == 'tcp' && empty($each_server['host'])) {
640 trigger_error(
641 sprintf(
642 __('Invalid hostname for server %1$s. Please review your configuration.'),
643 $server_index
645 E_USER_ERROR
649 // Final solution to bug #582890
650 // If we are using a socket connection
651 // and there is nothing in the verbose server name
652 // or the host field, then generate a name for the server
653 // in the form of "Server 2", localized of course!
654 if ($each_server['connect_type'] == 'socket'
655 && empty($each_server['host'])
656 && empty($each_server['verbose'])
658 $each_server['verbose'] = sprintf(__('Server %d'), $server_index);
661 $new_servers[$server_index] = $each_server;
663 $cfg['Servers'] = $new_servers;
664 unset($new_servers, $server_index, $each_server);
667 // Cleanup
668 unset($default_server);
671 /******************************************************************************/
672 /* setup themes LABEL_theme_setup */
675 * @global PMA_Theme_Manager $_SESSION['PMA_Theme_Manager']
677 if (! isset($_SESSION['PMA_Theme_Manager'])) {
678 $_SESSION['PMA_Theme_Manager'] = new PMA_Theme_Manager;
679 } else {
681 * @todo move all __wakeup() functionality into session.inc.php
683 $_SESSION['PMA_Theme_Manager']->checkConfig();
686 // for the theme per server feature
687 if (isset($_REQUEST['server']) && ! isset($_REQUEST['set_theme'])) {
688 $GLOBALS['server'] = $_REQUEST['server'];
689 $tmp = $_SESSION['PMA_Theme_Manager']->getThemeCookie();
690 if (empty($tmp)) {
691 $tmp = $_SESSION['PMA_Theme_Manager']->theme_default;
693 $_SESSION['PMA_Theme_Manager']->setActiveTheme($tmp);
694 unset($tmp);
697 * @todo move into PMA_Theme_Manager::__wakeup()
699 if (isset($_REQUEST['set_theme'])) {
700 // if user selected a theme
701 $_SESSION['PMA_Theme_Manager']->setActiveTheme($_REQUEST['set_theme']);
705 * the theme object
706 * @global PMA_Theme $_SESSION['PMA_Theme']
708 $_SESSION['PMA_Theme'] = $_SESSION['PMA_Theme_Manager']->theme;
710 // BC
712 * the active theme
713 * @global string $GLOBALS['theme']
715 $GLOBALS['theme'] = $_SESSION['PMA_Theme']->getName();
717 * the theme path
718 * @global string $GLOBALS['pmaThemePath']
720 $GLOBALS['pmaThemePath'] = $_SESSION['PMA_Theme']->getPath();
722 * the theme image path
723 * @global string $GLOBALS['pmaThemeImage']
725 $GLOBALS['pmaThemeImage'] = $_SESSION['PMA_Theme']->getImgPath();
728 * load layout file if exists
730 if (@file_exists($_SESSION['PMA_Theme']->getLayoutFile())) {
731 include $_SESSION['PMA_Theme']->getLayoutFile();
734 if (! defined('PMA_MINIMUM_COMMON')) {
736 * Character set conversion.
738 include_once './libraries/charset_conversion.lib.php';
741 * Lookup server by name
742 * (see FAQ 4.8)
744 if (! empty($_REQUEST['server'])
745 && is_string($_REQUEST['server'])
746 && ! is_numeric($_REQUEST['server'])
748 foreach ($cfg['Servers'] as $i => $server) {
749 $verboseToLower = /*overload*/mb_strtolower($server['verbose']);
750 $serverToLower = /*overload*/mb_strtolower($_REQUEST['server']);
751 if ($server['host'] == $_REQUEST['server']
752 || $server['verbose'] == $_REQUEST['server']
753 || $verboseToLower == $serverToLower
754 || md5($verboseToLower) == $serverToLower
756 $_REQUEST['server'] = $i;
757 break;
760 if (is_string($_REQUEST['server'])) {
761 unset($_REQUEST['server']);
763 unset($i);
767 * If no server is selected, make sure that $cfg['Server'] is empty (so
768 * that nothing will work), and skip server authentication.
769 * We do NOT exit here, but continue on without logging into any server.
770 * This way, the welcome page will still come up (with no server info) and
771 * present a choice of servers in the case that there are multiple servers
772 * and '$cfg['ServerDefault'] = 0' is set.
775 if (isset($_REQUEST['server'])
776 && (is_string($_REQUEST['server']) || is_numeric($_REQUEST['server']))
777 && ! empty($_REQUEST['server'])
778 && ! empty($cfg['Servers'][$_REQUEST['server']])
780 $GLOBALS['server'] = $_REQUEST['server'];
781 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
782 } else {
783 if (!empty($cfg['Servers'][$cfg['ServerDefault']])) {
784 $GLOBALS['server'] = $cfg['ServerDefault'];
785 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
786 } else {
787 $GLOBALS['server'] = 0;
788 $cfg['Server'] = array();
791 $GLOBALS['url_params']['server'] = $GLOBALS['server'];
794 * Kanji encoding convert feature appended by Y.Kawada (2002/2/20)
796 if (function_exists('mb_convert_encoding')
797 && $lang == 'ja'
799 include_once './libraries/kanji-encoding.lib.php';
800 } // end if
803 * save some settings in cookies
804 * @todo should be done in PMA_Config
806 $GLOBALS['PMA_Config']->setCookie('pma_lang', $GLOBALS['lang']);
807 if (isset($GLOBALS['collation_connection'])) {
808 $GLOBALS['PMA_Config']->setCookie(
809 'pma_collation_connection',
810 $GLOBALS['collation_connection']
814 $_SESSION['PMA_Theme_Manager']->setThemeCookie();
816 if (! empty($cfg['Server'])) {
819 * Loads the proper database interface for this server
821 include_once './libraries/database_interface.inc.php';
823 include_once './libraries/logging.lib.php';
825 // get LoginCookieValidity from preferences cache
826 // no generic solution for loading preferences from cache as some settings
827 // need to be kept for processing in PMA_Config::loadUserPreferences()
828 $cache_key = 'server_' . $GLOBALS['server'];
829 if (isset($_SESSION['cache'][$cache_key]['userprefs']['LoginCookieValidity'])
831 $value
832 = $_SESSION['cache'][$cache_key]['userprefs']['LoginCookieValidity'];
833 $GLOBALS['PMA_Config']->set('LoginCookieValidity', $value);
834 $GLOBALS['cfg']['LoginCookieValidity'] = $value;
835 unset($value);
837 unset($cache_key);
839 // Gets the authentication library that fits the $cfg['Server'] settings
840 // and run authentication
842 // to allow HTTP or http
843 $cfg['Server']['auth_type']
844 = /*overload*/mb_strtolower($cfg['Server']['auth_type']);
847 * the required auth type plugin
849 $auth_class = "Authentication" . ucfirst($cfg['Server']['auth_type']);
850 if (! file_exists(
851 './libraries/plugins/auth/'
852 . $auth_class . '.class.php'
853 )) {
854 PMA_fatalError(
855 __('Invalid authentication method set in configuration:')
856 . ' ' . $cfg['Server']['auth_type']
859 if (isset($_REQUEST['pma_password'])) {
860 $_REQUEST['pma_password'] = substr($_REQUEST['pma_password'], 0, 256);
862 include_once './libraries/plugins/auth/' . $auth_class . '.class.php';
863 // todo: add plugin manager
864 $plugin_manager = null;
865 $auth_plugin = new $auth_class($plugin_manager);
867 if (! $auth_plugin->authCheck()) {
868 /* Force generating of new session on login */
869 PMA_secureSession();
870 $auth_plugin->auth();
871 } else {
872 $auth_plugin->authSetUser();
875 // Check IP-based Allow/Deny rules as soon as possible to reject the
876 // user based on mod_access in Apache
877 if (isset($cfg['Server']['AllowDeny'])
878 && isset($cfg['Server']['AllowDeny']['order'])
882 * ip based access library
884 include_once './libraries/ip_allow_deny.lib.php';
886 $allowDeny_forbidden = false; // default
887 if ($cfg['Server']['AllowDeny']['order'] == 'allow,deny') {
888 $allowDeny_forbidden = true;
889 if (PMA_allowDeny('allow')) {
890 $allowDeny_forbidden = false;
892 if (PMA_allowDeny('deny')) {
893 $allowDeny_forbidden = true;
895 } elseif ($cfg['Server']['AllowDeny']['order'] == 'deny,allow') {
896 if (PMA_allowDeny('deny')) {
897 $allowDeny_forbidden = true;
899 if (PMA_allowDeny('allow')) {
900 $allowDeny_forbidden = false;
902 } elseif ($cfg['Server']['AllowDeny']['order'] == 'explicit') {
903 if (PMA_allowDeny('allow') && ! PMA_allowDeny('deny')) {
904 $allowDeny_forbidden = false;
905 } else {
906 $allowDeny_forbidden = true;
908 } // end if ... elseif ... elseif
910 // Ejects the user if banished
911 if ($allowDeny_forbidden) {
912 PMA_logUser($cfg['Server']['user'], 'allow-denied');
913 $auth_plugin->authFails();
915 } // end if
917 // is root allowed?
918 if (! $cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') {
919 $allowDeny_forbidden = true;
920 PMA_logUser($cfg['Server']['user'], 'root-denied');
921 $auth_plugin->authFails();
924 // is a login without password allowed?
925 if (! $cfg['Server']['AllowNoPassword']
926 && $cfg['Server']['password'] == ''
928 $login_without_password_is_forbidden = true;
929 PMA_logUser($cfg['Server']['user'], 'empty-denied');
930 $auth_plugin->authFails();
933 // if using TCP socket is not needed
934 if (/*overload*/mb_strtolower($cfg['Server']['connect_type']) == 'tcp') {
935 $cfg['Server']['socket'] = '';
938 // Try to connect MySQL with the control user profile (will be used to
939 // get the privileges list for the current user but the true user link
940 // must be open after this one so it would be default one for all the
941 // scripts)
942 $controllink = false;
943 if ($cfg['Server']['controluser'] != '') {
944 if (! empty($cfg['Server']['controlhost'])
945 || ! empty($cfg['Server']['controlport'])
947 $server_details = array();
948 if (! empty($cfg['Server']['controlhost'])) {
949 $server_details['host'] = $cfg['Server']['controlhost'];
950 } else {
951 $server_details['host'] = $cfg['Server']['host'];
953 if (! empty($cfg['Server']['controlport'])) {
954 $server_details['port'] = $cfg['Server']['controlport'];
955 } elseif ($server_details['host'] == $cfg['Server']['host']) {
956 // Evaluates to true when controlhost == host
957 // or controlhost is not defined (hence it defaults to host)
958 // In such case we can use the value of port.
959 $server_details['port'] = $cfg['Server']['port'];
961 // otherwise we leave the $server_details['port'] unset,
962 // allowing it to take default mysql port
964 $controllink = $GLOBALS['dbi']->connect(
965 $cfg['Server']['controluser'],
966 $cfg['Server']['controlpass'],
967 true,
968 $server_details
970 } else {
971 $controllink = $GLOBALS['dbi']->connect(
972 $cfg['Server']['controluser'],
973 $cfg['Server']['controlpass'],
974 true
979 // Connects to the server (validates user's login)
980 $userlink = $GLOBALS['dbi']->connect(
981 $cfg['Server']['user'], $cfg['Server']['password'], false
984 // Set timestamp for the session, if required.
985 if ($cfg['Server']['SessionTimeZone'] != '') {
986 $sql_query_tz = 'SET ' . PMA_Util::backquote('time_zone') . ' = '
987 . '\'' . PMA_Util::sqlAddSlashes($cfg['Server']['SessionTimeZone']) . '\'';
989 if(! $userlink->query($sql_query_tz)) {
990 $error_message_tz = sprintf(__('Unable to use timezone %1$s for server %2$d. '
991 . 'Please check your configuration setting for '
992 . '[em]$cfg[\'Servers\'][%3$d][\'SessionTimeZone\'][/em]. '
993 . 'phpMyAdmin is currently using the default time zone of the database server.'),
994 $cfg['Servers'][$GLOBALS['server']]['SessionTimeZone'],
995 $GLOBALS['server'],
996 $GLOBALS['server']
999 $GLOBALS['error_handler']->addError(
1000 $error_message_tz,
1001 E_USER_WARNING,
1004 false
1009 if (! $controllink) {
1010 $controllink = $userlink;
1013 $auth_plugin->storeUserCredentials();
1015 /* Log success */
1016 PMA_logUser($cfg['Server']['user']);
1018 if (PMA_MYSQL_INT_VERSION < 50500) {
1019 PMA_fatalError(
1020 __('You should upgrade to %s %s or later.'),
1021 array('MySQL', '5.5.0')
1026 * Type handling object.
1028 if (PMA_DRIZZLE) {
1029 $GLOBALS['PMA_Types'] = new PMA_Types_Drizzle();
1030 } else {
1031 $GLOBALS['PMA_Types'] = new PMA_Types_MySQL();
1034 if (PMA_DRIZZLE) {
1035 // DisableIS must be set to false for Drizzle, it maps SHOW commands
1036 // to INFORMATION_SCHEMA queries anyway so it's fast on large servers
1037 $cfg['Server']['DisableIS'] = false;
1038 // SHOW OPEN TABLES is not supported by Drizzle
1039 $cfg['SkipLockedTables'] = false;
1043 * SQL Parser code
1045 include_once './libraries/sqlparser.lib.php';
1048 * the PMA_List_Database class
1050 include_once './libraries/PMA.php';
1051 $pma = new PMA;
1052 $pma->userlink = $userlink;
1053 $pma->controllink = $controllink;
1056 * some resetting has to be done when switching servers
1058 if (isset($_SESSION['tmpval']['previous_server'])
1059 && $_SESSION['tmpval']['previous_server'] != $GLOBALS['server']
1061 unset($_SESSION['tmpval']['navi_limit_offset']);
1063 $_SESSION['tmpval']['previous_server'] = $GLOBALS['server'];
1065 } else { // end server connecting
1066 // No need to check for 'PMA_BYPASS_GET_INSTANCE' since this execution path
1067 // applies only to initial login
1068 $response = PMA_Response::getInstance();
1069 $response->getHeader()->disableMenuAndConsole();
1070 $response->getFooter()->setMinimal();
1074 * check if profiling was requested and remember it
1075 * (note: when $cfg['ServerDefault'] = 0, constant is not defined)
1077 if (isset($_REQUEST['profiling'])
1078 && PMA_Util::profilingSupported()
1080 $_SESSION['profiling'] = true;
1081 } elseif (isset($_REQUEST['profiling_form'])) {
1082 // the checkbox was unchecked
1083 unset($_SESSION['profiling']);
1086 * Inclusion of profiling scripts is needed on various
1087 * pages like sql, tbl_sql, db_sql, tbl_select
1089 if (! defined('PMA_BYPASS_GET_INSTANCE')) {
1090 $response = PMA_Response::getInstance();
1092 if (isset($_SESSION['profiling'])) {
1093 $header = $response->getHeader();
1094 $scripts = $header->getScripts();
1095 $scripts->addFile('jqplot/jquery.jqplot.js');
1096 $scripts->addFile('jqplot/plugins/jqplot.pieRenderer.js');
1097 $scripts->addFile('jqplot/plugins/jqplot.highlighter.js');
1098 $scripts->addFile('canvg/canvg.js');
1099 $scripts->addFile('jquery/jquery.tablesorter.js');
1103 * There is no point in even attempting to process
1104 * an ajax request if there is a token mismatch
1106 if (isset($response) && $response->isAjax() && $token_mismatch) {
1107 $response->isSuccess(false);
1108 $response->addJSON(
1109 'message',
1110 PMA_Message::error(__('Error: Token mismatch'))
1112 exit;
1114 } // end if !defined('PMA_MINIMUM_COMMON')
1116 // load user preferences
1117 $GLOBALS['PMA_Config']->loadUserPreferences();
1119 // remove sensitive values from session
1120 $GLOBALS['PMA_Config']->set('blowfish_secret', '');
1121 $GLOBALS['PMA_Config']->set('Servers', '');
1122 $GLOBALS['PMA_Config']->set('default_server', '');
1124 /* Tell tracker that it can actually work */
1125 PMA_Tracker::enable();
1128 * @global boolean $GLOBALS['is_ajax_request']
1129 * @todo should this be moved to the variables init section above?
1131 * Check if the current request is an AJAX request, and set is_ajax_request
1132 * accordingly. Suppress headers, footers and unnecessary output if set to
1133 * true
1135 if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) {
1136 $GLOBALS['is_ajax_request'] = true;
1137 } else {
1138 $GLOBALS['is_ajax_request'] = false;
1141 if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
1142 PMA_fatalError(__("GLOBALS overwrite attempt"));
1146 * protect against possible exploits - there is no need to have so much variables
1148 if (count($_REQUEST) > 1000) {
1149 PMA_fatalError(__('possible exploit'));
1153 * Check for numeric keys
1154 * (if register_globals is on, numeric key can be found in $GLOBALS)
1156 foreach ($GLOBALS as $key => $dummy) {
1157 if (is_numeric($key)) {
1158 PMA_fatalError(__('numeric key detected'));
1161 unset($dummy);
1163 // here, the function does not exist with this configuration:
1164 // $cfg['ServerDefault'] = 0;
1165 $GLOBALS['is_superuser']
1166 = isset($GLOBALS['dbi']) && $GLOBALS['dbi']->isSuperuser();
1168 if (!empty($__redirect) && in_array($__redirect, $goto_whitelist)) {
1170 * include subform target page
1172 include $__redirect;
1173 exit();
1176 // If Zero configuration mode enabled, check PMA tables in current db.
1177 if (! defined('PMA_MINIMUM_COMMON')
1178 && isset($GLOBALS['cfg']['ZeroConf'])
1179 && $GLOBALS['cfg']['ZeroConf'] == true
1181 if (! empty($GLOBALS['db'])) {
1182 $cfgRelation = PMA_getRelationsParam();
1183 if (empty($cfgRelation['db'])) {
1184 PMA_fixPMATables($GLOBALS['db'], false);