Clear display on session timeout even when unsaved changes are pending.
[openemr.git] / phpmyadmin / libraries / common.inc.php
blob773e8a32001b11fd37e58869ccec66a19ac2f065
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.5.0', 'lt')) {
46 die('PHP 5.5+ 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 * Set utf-8 encoding for PHP
102 ini_set('default_charset', 'utf-8');
103 mb_internal_encoding('utf-8');
106 * the PMA_Theme class
108 require './libraries/Theme.class.php';
111 * the PMA_Theme_Manager class
113 require './libraries/Theme_Manager.class.php';
116 * the PMA_Config class
118 require './libraries/Config.class.php';
121 * the relation lib, tracker needs it
123 require './libraries/relation.lib.php';
126 * the PMA_Tracker class
128 require './libraries/Tracker.class.php';
131 * the PMA_Table class
133 require './libraries/Table.class.php';
136 * the PMA_Types class
138 require './libraries/Types.class.php';
140 if (! defined('PMA_MINIMUM_COMMON') || defined('PMA_SETUP')) {
142 * common functions
144 include_once './libraries/Util.class.php';
147 * JavaScript escaping.
149 include_once './libraries/js_escape.lib.php';
152 * Include URL/hidden inputs generating.
154 include_once './libraries/url_generating.lib.php';
157 * Used to generate the page
159 include_once 'libraries/Response.class.php';
162 /******************************************************************************/
163 /* start procedural code label_start_procedural */
166 * PATH_INFO could be compromised if set, so remove it from PHP_SELF
167 * and provide a clean PHP_SELF here
169 $PMA_PHP_SELF = PMA_getenv('PHP_SELF');
170 $_PATH_INFO = PMA_getenv('PATH_INFO');
171 if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
172 $path_info_pos = /*overload*/mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
173 $pathLength = $path_info_pos + /*overload*/mb_strlen($_PATH_INFO);
174 if ($pathLength === /*overload*/mb_strlen($PMA_PHP_SELF)) {
175 $PMA_PHP_SELF = /*overload*/mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
178 $PMA_PHP_SELF = htmlspecialchars($PMA_PHP_SELF);
182 * just to be sure there was no import (registering) before here
183 * we empty the global space (but avoid unsetting $variables_list
184 * and $key in the foreach (), we still need them!)
186 $variables_whitelist = array (
187 'GLOBALS',
188 '_SERVER',
189 '_GET',
190 '_POST',
191 '_REQUEST',
192 '_FILES',
193 '_ENV',
194 '_COOKIE',
195 '_SESSION',
196 'error_handler',
197 'PMA_PHP_SELF',
198 'variables_whitelist',
199 'key',
200 'PMA_String'
203 foreach (get_defined_vars() as $key => $value) {
204 if (! in_array($key, $variables_whitelist)) {
205 unset($$key);
208 unset($key, $value, $variables_whitelist);
212 * Subforms - some functions need to be called by form, cause of the limited URL
213 * length, but if this functions inside another form you cannot just open a new
214 * form - so phpMyAdmin uses 'arrays' inside this form
216 * <code>
217 * <form ...>
218 * ... main form elements ...
219 * <input type="hidden" name="subform[action1][id]" value="1" />
220 * ... other subform data ...
221 * <input type="submit" name="usesubform[action1]" value="do action1" />
222 * ... other subforms ...
223 * <input type="hidden" name="subform[actionX][id]" value="X" />
224 * ... other subform data ...
225 * <input type="submit" name="usesubform[actionX]" value="do actionX" />
226 * ... main form elements ...
227 * <input type="submit" name="main_action" value="submit form" />
228 * </form>
229 * </code>
231 * so we now check if a subform is submitted
233 $__redirect = null;
234 if (isset($_POST['usesubform']) && ! defined('PMA_MINIMUM_COMMON')) {
235 // if a subform is present and should be used
236 // the rest of the form is deprecated
237 $subform_id = key($_POST['usesubform']);
238 $subform = $_POST['subform'][$subform_id];
239 $_POST = $subform;
240 $_REQUEST = $subform;
242 * some subforms need another page than the main form, so we will just
243 * include this page at the end of this script - we use $__redirect to
244 * track this
246 if (isset($_POST['redirect'])
247 && $_POST['redirect'] != basename($PMA_PHP_SELF)
249 $__redirect = $_POST['redirect'];
250 unset($_POST['redirect']);
252 unset($subform_id, $subform);
253 } else {
254 // Note: here we overwrite $_REQUEST so that it does not contain cookies,
255 // because another application for the same domain could have set
256 // a cookie (with a compatible path) that overrides a variable
257 // we expect from GET or POST.
258 // We'll refer to cookies explicitly with the $_COOKIE syntax.
259 $_REQUEST = array_merge($_GET, $_POST);
261 // end check if a subform is submitted
264 * This setting was removed in PHP 5.4, but get_magic_quotes_gpc
265 * always returns False since then.
267 if (get_magic_quotes_gpc()) {
268 PMA_arrayWalkRecursive($_GET, 'stripslashes', true);
269 PMA_arrayWalkRecursive($_POST, 'stripslashes', true);
270 PMA_arrayWalkRecursive($_COOKIE, 'stripslashes', true);
271 PMA_arrayWalkRecursive($_REQUEST, 'stripslashes', true);
275 * check timezone setting
276 * this could produce an E_STRICT - but only once,
277 * if not done here it will produce E_STRICT on every date/time function
278 * (starting with PHP 5.3, this code can produce E_WARNING rather than
279 * E_STRICT)
282 date_default_timezone_set(@date_default_timezone_get());
284 /******************************************************************************/
285 /* parsing configuration file LABEL_parsing_config_file */
288 * We really need this one!
290 if (! function_exists('preg_replace')) {
291 PMA_warnMissingExtension('pcre', true);
295 * JSON is required in several places.
297 if (! function_exists('json_encode')) {
298 PMA_warnMissingExtension('json', true);
302 * @global PMA_Config $GLOBALS['PMA_Config']
303 * force reading of config file, because we removed sensitive values
304 * in the previous iteration
306 $GLOBALS['PMA_Config'] = new PMA_Config(CONFIG_FILE);
308 if (!defined('PMA_MINIMUM_COMMON')) {
309 $GLOBALS['PMA_Config']->checkPmaAbsoluteUri();
313 * BC - enable backward compatibility
314 * exports all configuration settings into $GLOBALS ($GLOBALS['cfg'])
316 $GLOBALS['PMA_Config']->enableBc();
319 * clean cookies on upgrade
320 * when changing something related to PMA cookies, increment the cookie version
322 $pma_cookie_version = 4;
323 if (isset($_COOKIE)) {
324 if (! isset($_COOKIE['pmaCookieVer'])
325 || $_COOKIE['pmaCookieVer'] != $pma_cookie_version
327 // delete all cookies
328 foreach ($_COOKIE as $cookie_name => $tmp) {
329 $GLOBALS['PMA_Config']->removeCookie($cookie_name);
331 $_COOKIE = array();
332 $GLOBALS['PMA_Config']->setCookie('pmaCookieVer', $pma_cookie_version);
338 * check HTTPS connection
340 if ($GLOBALS['PMA_Config']->get('ForceSSL')
341 && ! $GLOBALS['PMA_Config']->detectHttps()
343 require './libraries/select_lang.lib.php';
344 // grab SSL URL
345 $url = $GLOBALS['PMA_Config']->getSSLUri();
346 // Actually redirect
347 PMA_sendHeaderLocation($url . PMA_URL_getCommon($_GET, 'text'));
348 // delete the current session, otherwise we get problems (see bug #2397877)
349 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
350 exit;
355 * include session handling after the globals, to prevent overwriting
357 require './libraries/session.inc.php';
360 * init some variables LABEL_variables_init
364 * holds parameters to be passed to next page
365 * @global array $GLOBALS['url_params']
367 $GLOBALS['url_params'] = array();
370 * the whitelist for $GLOBALS['goto']
371 * @global array $goto_whitelist
373 $goto_whitelist = array(
374 //'browse_foreigners.php',
375 //'changelog.php',
376 //'chk_rel.php',
377 'db_create.php',
378 'db_datadict.php',
379 'db_sql.php',
380 'db_events.php',
381 'db_export.php',
382 'db_importdocsql.php',
383 'db_qbe.php',
384 'db_structure.php',
385 'db_import.php',
386 'db_operations.php',
387 'db_search.php',
388 'db_routines.php',
389 'export.php',
390 'import.php',
391 //'index.php',
392 //'navigation.php',
393 //'license.php',
394 'index.php',
395 'pdf_pages.php',
396 'pdf_schema.php',
397 //'phpinfo.php',
398 'server_binlog.php',
399 'server_collations.php',
400 'server_databases.php',
401 'server_engines.php',
402 'server_export.php',
403 'server_import.php',
404 'server_privileges.php',
405 'server_sql.php',
406 'server_status.php',
407 'server_status_advisor.php',
408 'server_status_monitor.php',
409 'server_status_queries.php',
410 'server_status_variables.php',
411 'server_variables.php',
412 'sql.php',
413 'tbl_addfield.php',
414 'tbl_change.php',
415 'tbl_create.php',
416 'tbl_import.php',
417 'tbl_indexes.php',
418 'tbl_sql.php',
419 'tbl_export.php',
420 'tbl_operations.php',
421 'tbl_structure.php',
422 'tbl_relation.php',
423 'tbl_replace.php',
424 'tbl_row_action.php',
425 'tbl_select.php',
426 'tbl_zoom_select.php',
427 //'themes.php',
428 'transformation_overview.php',
429 'transformation_wrapper.php',
430 'user_password.php',
434 * check $__redirect against whitelist
436 if (! PMA_checkPageValidity($__redirect, $goto_whitelist)) {
437 $__redirect = null;
441 * holds page that should be displayed
442 * @global string $GLOBALS['goto']
444 $GLOBALS['goto'] = '';
445 // Security fix: disallow accessing serious server files via "?goto="
446 if (PMA_checkPageValidity($_REQUEST['goto'], $goto_whitelist)) {
447 $GLOBALS['goto'] = $_REQUEST['goto'];
448 $GLOBALS['url_params']['goto'] = $_REQUEST['goto'];
449 } else {
450 unset($_REQUEST['goto'], $_GET['goto'], $_POST['goto'], $_COOKIE['goto']);
454 * returning page
455 * @global string $GLOBALS['back']
457 if (PMA_checkPageValidity($_REQUEST['back'], $goto_whitelist)) {
458 $GLOBALS['back'] = $_REQUEST['back'];
459 } else {
460 unset($_REQUEST['back'], $_GET['back'], $_POST['back'], $_COOKIE['back']);
464 * Check whether user supplied token is valid, if not remove any possibly
465 * dangerous stuff from request.
467 * remember that some objects in the session with session_start and __wakeup()
468 * could access this variables before we reach this point
469 * f.e. PMA_Config: fontsize
471 * @todo variables should be handled by their respective owners (objects)
472 * f.e. lang, server, collation_connection in PMA_Config
474 $token_mismatch = true;
475 $token_provided = false;
476 if (PMA_isValid($_REQUEST['token'])) {
477 $token_provided = true;
478 $token_mismatch = ! hash_equals($_SESSION[' PMA_token '], $_REQUEST['token']);
481 if ($token_mismatch) {
483 * List of parameters which are allowed from unsafe source
485 $allow_list = array(
486 /* needed for direct access, see FAQ 1.34
487 * also, server needed for cookie login screen (multi-server)
489 'server', 'db', 'table', 'target', 'lang',
490 /* Session ID */
491 'phpMyAdmin',
492 /* Cookie preferences */
493 'pma_lang', 'pma_collation_connection',
494 /* Possible login form */
495 'pma_servername', 'pma_username', 'pma_password',
496 'g-recaptcha-response',
497 /* Needed to send the correct reply */
498 'ajax_request',
499 /* Permit to log out even if there is a token mismatch */
500 'old_usr',
501 /* Permit redirection with token-mismatch in url.php */
502 'url',
503 /* Permit session expiry flag */
504 'session_expired',
505 /* JS loading */
506 'scripts', 'call_done'
509 * Allow changing themes in test/theme.php
511 if (defined('PMA_TEST_THEME')) {
512 $allow_list[] = 'set_theme';
515 * Require cleanup functions
517 include './libraries/cleanup.lib.php';
519 * Do actual cleanup
521 PMA_removeRequestVars($allow_list);
527 * current selected database
528 * @global string $GLOBALS['db']
530 PMA_setGlobalDbOrTable('db');
533 * current selected table
534 * @global string $GLOBALS['table']
536 PMA_setGlobalDbOrTable('table');
539 * Store currently selected recent table.
540 * Affect $GLOBALS['db'] and $GLOBALS['table']
542 if (PMA_isValid($_REQUEST['selected_recent_table'])) {
543 $recent_table = json_decode($_REQUEST['selected_recent_table'], true);
544 $GLOBALS['db'] = $recent_table['db'];
545 $GLOBALS['url_params']['db'] = $GLOBALS['db'];
546 $GLOBALS['table'] = $recent_table['table'];
547 $GLOBALS['url_params']['table'] = $GLOBALS['table'];
551 * SQL query to be executed
552 * @global string $GLOBALS['sql_query']
554 $GLOBALS['sql_query'] = '';
555 if (PMA_isValid($_REQUEST['sql_query'])) {
556 $GLOBALS['sql_query'] = $_REQUEST['sql_query'];
559 //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup
560 //$_REQUEST['server']; // checked later in this file
561 //$_REQUEST['lang']; // checked by LABEL_loading_language_file
563 /******************************************************************************/
564 /* loading language file LABEL_loading_language_file */
567 * lang detection is done here
569 require './libraries/select_lang.lib.php';
571 // Defines the cell alignment values depending on text direction
572 if ($GLOBALS['text_dir'] == 'ltr') {
573 $GLOBALS['cell_align_left'] = 'left';
574 $GLOBALS['cell_align_right'] = 'right';
575 } else {
576 $GLOBALS['cell_align_left'] = 'right';
577 $GLOBALS['cell_align_right'] = 'left';
581 * check for errors occurred while loading configuration
582 * this check is done here after loading language files to present errors in locale
584 $GLOBALS['PMA_Config']->checkPermissions();
586 if ($GLOBALS['PMA_Config']->error_config_file) {
587 $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
588 . '[br][br]'
589 . __(
590 'This usually means there is a syntax error in it, '
591 . 'please check any errors shown below.'
593 . '[br][br]'
594 . '[conferr]';
595 trigger_error($error, E_USER_ERROR);
597 if ($GLOBALS['PMA_Config']->error_config_default_file) {
598 $error = sprintf(
599 __('Could not load default configuration from: %1$s'),
600 $GLOBALS['PMA_Config']->default_source
602 trigger_error($error, E_USER_ERROR);
604 if ($GLOBALS['PMA_Config']->error_pma_uri) {
605 trigger_error(
607 'The [code]$cfg[\'PmaAbsoluteUri\'][/code]'
608 . ' directive MUST be set in your configuration file!'
610 E_USER_ERROR
615 /******************************************************************************/
616 /* setup servers LABEL_setup_servers */
619 * current server
620 * @global integer $GLOBALS['server']
622 $GLOBALS['server'] = 0;
625 * Servers array fixups.
626 * $default_server comes from PMA_Config::enableBc()
627 * @todo merge into PMA_Config
629 // Do we have some server?
630 if (! isset($cfg['Servers']) || count($cfg['Servers']) == 0) {
631 // No server => create one with defaults
632 $cfg['Servers'] = array(1 => $default_server);
633 } else {
634 // We have server(s) => apply default configuration
635 $new_servers = array();
637 foreach ($cfg['Servers'] as $server_index => $each_server) {
639 // Detect wrong configuration
640 if (!is_int($server_index) || $server_index < 1) {
641 trigger_error(
642 sprintf(__('Invalid server index: %s'), $server_index),
643 E_USER_ERROR
647 $each_server = array_merge($default_server, $each_server);
649 // Don't use servers with no hostname
650 if ($each_server['connect_type'] == 'tcp' && empty($each_server['host'])) {
651 trigger_error(
652 sprintf(
654 'Invalid hostname for server %1$s. '
655 . 'Please review your configuration.'
657 $server_index
659 E_USER_ERROR
663 // Final solution to bug #582890
664 // If we are using a socket connection
665 // and there is nothing in the verbose server name
666 // or the host field, then generate a name for the server
667 // in the form of "Server 2", localized of course!
668 if ($each_server['connect_type'] == 'socket'
669 && empty($each_server['host'])
670 && empty($each_server['verbose'])
672 $each_server['verbose'] = sprintf(__('Server %d'), $server_index);
675 $new_servers[$server_index] = $each_server;
677 $cfg['Servers'] = $new_servers;
678 unset($new_servers, $server_index, $each_server);
681 // Cleanup
682 unset($default_server);
685 /******************************************************************************/
686 /* setup themes LABEL_theme_setup */
689 * @global PMA_Theme_Manager $_SESSION['PMA_Theme_Manager']
691 if (! isset($_SESSION['PMA_Theme_Manager'])) {
692 $_SESSION['PMA_Theme_Manager'] = new PMA_Theme_Manager;
693 } else {
695 * @todo move all __wakeup() functionality into session.inc.php
697 $_SESSION['PMA_Theme_Manager']->checkConfig();
700 // for the theme per server feature
701 if (isset($_REQUEST['server']) && ! isset($_REQUEST['set_theme'])) {
702 $GLOBALS['server'] = $_REQUEST['server'];
703 $tmp = $_SESSION['PMA_Theme_Manager']->getThemeCookie();
704 if (empty($tmp)) {
705 $tmp = $_SESSION['PMA_Theme_Manager']->theme_default;
707 $_SESSION['PMA_Theme_Manager']->setActiveTheme($tmp);
708 unset($tmp);
711 * @todo move into PMA_Theme_Manager::__wakeup()
713 if (isset($_REQUEST['set_theme'])) {
714 // if user selected a theme
715 $_SESSION['PMA_Theme_Manager']->setActiveTheme($_REQUEST['set_theme']);
719 * the theme object
720 * @global PMA_Theme $_SESSION['PMA_Theme']
722 $_SESSION['PMA_Theme'] = $_SESSION['PMA_Theme_Manager']->theme;
724 // BC
726 * the active theme
727 * @global string $GLOBALS['theme']
729 $GLOBALS['theme'] = $_SESSION['PMA_Theme']->getName();
731 * the theme path
732 * @global string $GLOBALS['pmaThemePath']
734 $GLOBALS['pmaThemePath'] = $_SESSION['PMA_Theme']->getPath();
736 * the theme image path
737 * @global string $GLOBALS['pmaThemeImage']
739 $GLOBALS['pmaThemeImage'] = $_SESSION['PMA_Theme']->getImgPath();
742 * load layout file if exists
744 if (@file_exists($_SESSION['PMA_Theme']->getLayoutFile())) {
745 include $_SESSION['PMA_Theme']->getLayoutFile();
748 if (! defined('PMA_MINIMUM_COMMON')) {
750 * Character set conversion.
752 include_once './libraries/charset_conversion.lib.php';
755 * Lookup server by name
756 * (see FAQ 4.8)
758 if (! empty($_REQUEST['server'])
759 && is_string($_REQUEST['server'])
760 && ! is_numeric($_REQUEST['server'])
762 foreach ($cfg['Servers'] as $i => $server) {
763 $verboseToLower = /*overload*/mb_strtolower($server['verbose']);
764 $serverToLower = /*overload*/mb_strtolower($_REQUEST['server']);
765 if ($server['host'] == $_REQUEST['server']
766 || $server['verbose'] == $_REQUEST['server']
767 || $verboseToLower == $serverToLower
768 || md5($verboseToLower) == $serverToLower
770 $_REQUEST['server'] = $i;
771 break;
774 if (is_string($_REQUEST['server'])) {
775 unset($_REQUEST['server']);
777 unset($i);
781 * If no server is selected, make sure that $cfg['Server'] is empty (so
782 * that nothing will work), and skip server authentication.
783 * We do NOT exit here, but continue on without logging into any server.
784 * This way, the welcome page will still come up (with no server info) and
785 * present a choice of servers in the case that there are multiple servers
786 * and '$cfg['ServerDefault'] = 0' is set.
789 if (isset($_REQUEST['server'])
790 && (is_string($_REQUEST['server']) || is_numeric($_REQUEST['server']))
791 && ! empty($_REQUEST['server'])
792 && ! empty($cfg['Servers'][$_REQUEST['server']])
794 $GLOBALS['server'] = $_REQUEST['server'];
795 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
796 } else {
797 if (!empty($cfg['Servers'][$cfg['ServerDefault']])) {
798 $GLOBALS['server'] = $cfg['ServerDefault'];
799 $cfg['Server'] = $cfg['Servers'][$GLOBALS['server']];
800 } else {
801 $GLOBALS['server'] = 0;
802 $cfg['Server'] = array();
805 $GLOBALS['url_params']['server'] = $GLOBALS['server'];
808 * Kanji encoding convert feature appended by Y.Kawada (2002/2/20)
810 if (function_exists('mb_convert_encoding')
811 && $lang == 'ja'
813 include_once './libraries/kanji-encoding.lib.php';
814 } // end if
817 * save some settings in cookies
818 * @todo should be done in PMA_Config
820 $GLOBALS['PMA_Config']->setCookie('pma_lang', $GLOBALS['lang']);
821 if (isset($GLOBALS['collation_connection'])) {
822 $GLOBALS['PMA_Config']->setCookie(
823 'pma_collation_connection',
824 $GLOBALS['collation_connection']
828 $_SESSION['PMA_Theme_Manager']->setThemeCookie();
830 if (! empty($cfg['Server'])) {
833 * Loads the proper database interface for this server
835 include_once './libraries/database_interface.inc.php';
837 include_once './libraries/logging.lib.php';
839 // get LoginCookieValidity from preferences cache
840 // no generic solution for loading preferences from cache as some settings
841 // need to be kept for processing in PMA_Config::loadUserPreferences()
842 $cache_key = 'server_' . $GLOBALS['server'];
843 if (isset($_SESSION['cache'][$cache_key]['userprefs']['LoginCookieValidity'])
845 $value
846 = $_SESSION['cache'][$cache_key]['userprefs']['LoginCookieValidity'];
847 $GLOBALS['PMA_Config']->set('LoginCookieValidity', $value);
848 $GLOBALS['cfg']['LoginCookieValidity'] = $value;
849 unset($value);
851 unset($cache_key);
853 // Gets the authentication library that fits the $cfg['Server'] settings
854 // and run authentication
856 // to allow HTTP or http
857 $cfg['Server']['auth_type']
858 = /*overload*/mb_strtolower($cfg['Server']['auth_type']);
861 * the required auth type plugin
863 $auth_class = "Authentication" . ucfirst($cfg['Server']['auth_type']);
864 if (! file_exists(
865 './libraries/plugins/auth/'
866 . $auth_class . '.class.php'
867 )) {
868 PMA_fatalError(
869 __('Invalid authentication method set in configuration:')
870 . ' ' . $cfg['Server']['auth_type']
873 if (isset($_REQUEST['pma_password'])) {
874 $_REQUEST['pma_password'] = substr($_REQUEST['pma_password'], 0, 256);
876 include_once './libraries/plugins/auth/' . $auth_class . '.class.php';
877 // todo: add plugin manager
878 $plugin_manager = null;
879 /** @var AuthenticationPlugin $auth_plugin */
880 $auth_plugin = new $auth_class($plugin_manager);
882 if (! $auth_plugin->authCheck()) {
883 /* Force generating of new session on login */
884 if ($token_provided) {
885 PMA_secureSession();
887 $auth_plugin->auth();
888 } else {
889 $auth_plugin->authSetUser();
892 // Check IP-based Allow/Deny rules as soon as possible to reject the
893 // user based on mod_access in Apache
894 if (isset($cfg['Server']['AllowDeny'])
895 && isset($cfg['Server']['AllowDeny']['order'])
899 * ip based access library
901 include_once './libraries/ip_allow_deny.lib.php';
903 $allowDeny_forbidden = false; // default
904 if ($cfg['Server']['AllowDeny']['order'] == 'allow,deny') {
905 $allowDeny_forbidden = true;
906 if (PMA_allowDeny('allow')) {
907 $allowDeny_forbidden = false;
909 if (PMA_allowDeny('deny')) {
910 $allowDeny_forbidden = true;
912 } elseif ($cfg['Server']['AllowDeny']['order'] == 'deny,allow') {
913 if (PMA_allowDeny('deny')) {
914 $allowDeny_forbidden = true;
916 if (PMA_allowDeny('allow')) {
917 $allowDeny_forbidden = false;
919 } elseif ($cfg['Server']['AllowDeny']['order'] == 'explicit') {
920 if (PMA_allowDeny('allow') && ! PMA_allowDeny('deny')) {
921 $allowDeny_forbidden = false;
922 } else {
923 $allowDeny_forbidden = true;
925 } // end if ... elseif ... elseif
927 // Ejects the user if banished
928 if ($allowDeny_forbidden) {
929 PMA_logUser($cfg['Server']['user'], 'allow-denied');
930 $auth_plugin->authFails();
932 } // end if
934 // is root allowed?
935 if (! $cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') {
936 $allowDeny_forbidden = true;
937 PMA_logUser($cfg['Server']['user'], 'root-denied');
938 $auth_plugin->authFails();
941 // is a login without password allowed?
942 if (! $cfg['Server']['AllowNoPassword']
943 && $cfg['Server']['password'] == ''
945 $login_without_password_is_forbidden = true;
946 PMA_logUser($cfg['Server']['user'], 'empty-denied');
947 $auth_plugin->authFails();
950 // if using TCP socket is not needed
951 if (/*overload*/mb_strtolower($cfg['Server']['connect_type']) == 'tcp') {
952 $cfg['Server']['socket'] = '';
955 // Try to connect MySQL with the control user profile (will be used to
956 // get the privileges list for the current user but the true user link
957 // must be open after this one so it would be default one for all the
958 // scripts)
959 $controllink = false;
960 if ($cfg['Server']['controluser'] != '') {
961 if (! empty($cfg['Server']['controlhost'])
962 || ! empty($cfg['Server']['controlport'])
964 $server_details = array();
965 if (! empty($cfg['Server']['controlhost'])) {
966 $server_details['host'] = $cfg['Server']['controlhost'];
967 } else {
968 $server_details['host'] = $cfg['Server']['host'];
970 if (! empty($cfg['Server']['controlport'])) {
971 $server_details['port'] = $cfg['Server']['controlport'];
972 } elseif ($server_details['host'] == $cfg['Server']['host']) {
973 // Evaluates to true when controlhost == host
974 // or controlhost is not defined (hence it defaults to host)
975 // In such case we can use the value of port.
976 $server_details['port'] = $cfg['Server']['port'];
978 // otherwise we leave the $server_details['port'] unset,
979 // allowing it to take default mysql port
981 $controllink = $GLOBALS['dbi']->connect(
982 $cfg['Server']['controluser'],
983 $cfg['Server']['controlpass'],
984 true,
985 $server_details
987 } else {
988 $controllink = $GLOBALS['dbi']->connect(
989 $cfg['Server']['controluser'],
990 $cfg['Server']['controlpass'],
991 true
996 // Connects to the server (validates user's login)
997 /** @var PMA_DatabaseInterface $userlink */
998 $userlink = $GLOBALS['dbi']->connect(
999 $cfg['Server']['user'], $cfg['Server']['password'], false
1002 // Set timestamp for the session, if required.
1003 if ($cfg['Server']['SessionTimeZone'] != '') {
1004 $sql_query_tz = 'SET ' . PMA_Util::backquote('time_zone') . ' = '
1005 . '\''
1006 . PMA_Util::sqlAddSlashes($cfg['Server']['SessionTimeZone'])
1007 . '\'';
1009 if (! $userlink->query($sql_query_tz)) {
1010 $error_message_tz = sprintf(
1012 'Unable to use timezone %1$s for server %2$d. '
1013 . 'Please check your configuration setting for '
1014 . '[em]$cfg[\'Servers\'][%3$d][\'SessionTimeZone\'][/em]. '
1015 . 'phpMyAdmin is currently using the default time zone '
1016 . 'of the database server.'
1018 $cfg['Servers'][$GLOBALS['server']]['SessionTimeZone'],
1019 $GLOBALS['server'],
1020 $GLOBALS['server']
1023 $GLOBALS['error_handler']->addError(
1024 $error_message_tz,
1025 E_USER_WARNING,
1028 false
1033 if (! $controllink) {
1034 $controllink = $userlink;
1037 $auth_plugin->storeUserCredentials();
1039 /* Log success */
1040 PMA_logUser($cfg['Server']['user']);
1042 if (PMA_MYSQL_INT_VERSION < $cfg['MysqlMinVersion']['internal']) {
1043 PMA_fatalError(
1044 __('You should upgrade to %s %s or later.'),
1045 array('MySQL', $cfg['MysqlMinVersion']['human'])
1050 * Type handling object.
1052 if (PMA_DRIZZLE) {
1053 $GLOBALS['PMA_Types'] = new PMA_Types_Drizzle();
1054 } else {
1055 $GLOBALS['PMA_Types'] = new PMA_Types_MySQL();
1058 if (PMA_DRIZZLE) {
1059 // DisableIS must be set to false for Drizzle, it maps SHOW commands
1060 // to INFORMATION_SCHEMA queries anyway so it's fast on large servers
1061 $cfg['Server']['DisableIS'] = false;
1062 // SHOW OPEN TABLES is not supported by Drizzle
1063 $cfg['SkipLockedTables'] = false;
1067 * Charset information
1069 if (!PMA_DRIZZLE) {
1070 include_once './libraries/mysql_charsets.inc.php';
1072 if (!isset($mysql_charsets)) {
1073 $mysql_charsets = array();
1074 $mysql_collations_flat = array();
1078 * Initializes the SQL parsing library.
1080 include_once SQL_PARSER_AUTOLOAD;
1082 // Loads closest context to this version.
1083 SqlParser\Context::loadClosest(
1084 (PMA_DRIZZLE ? 'Drizzle' : 'MySql') . PMA_MYSQL_INT_VERSION
1087 // Sets the default delimiter (if specified).
1088 if (!empty($_REQUEST['sql_delimiter'])) {
1089 SqlParser\Lexer::$DEFAULT_DELIMITER = $_REQUEST['sql_delimiter'];
1092 // TODO: Set SQL modes too.
1095 * the PMA_List_Database class
1097 include_once './libraries/PMA.php';
1098 $pma = new PMA;
1099 $pma->userlink = $userlink;
1100 $pma->controllink = $controllink;
1103 * some resetting has to be done when switching servers
1105 if (isset($_SESSION['tmpval']['previous_server'])
1106 && $_SESSION['tmpval']['previous_server'] != $GLOBALS['server']
1108 unset($_SESSION['tmpval']['navi_limit_offset']);
1110 $_SESSION['tmpval']['previous_server'] = $GLOBALS['server'];
1112 } else { // end server connecting
1113 // No need to check for 'PMA_BYPASS_GET_INSTANCE' since this execution path
1114 // applies only to initial login
1115 $response = PMA_Response::getInstance();
1116 $response->getHeader()->disableMenuAndConsole();
1117 $response->getFooter()->setMinimal();
1121 * check if profiling was requested and remember it
1122 * (note: when $cfg['ServerDefault'] = 0, constant is not defined)
1124 if (isset($_REQUEST['profiling'])
1125 && PMA_Util::profilingSupported()
1127 $_SESSION['profiling'] = true;
1128 } elseif (isset($_REQUEST['profiling_form'])) {
1129 // the checkbox was unchecked
1130 unset($_SESSION['profiling']);
1133 // load user preferences
1134 $GLOBALS['PMA_Config']->loadUserPreferences();
1137 * Inclusion of profiling scripts is needed on various
1138 * pages like sql, tbl_sql, db_sql, tbl_select
1140 if (! defined('PMA_BYPASS_GET_INSTANCE')) {
1141 $response = PMA_Response::getInstance();
1143 if (isset($_SESSION['profiling'])) {
1144 $header = $response->getHeader();
1145 $scripts = $header->getScripts();
1146 $scripts->addFile('jqplot/jquery.jqplot.js');
1147 $scripts->addFile('jqplot/plugins/jqplot.pieRenderer.js');
1148 $scripts->addFile('jqplot/plugins/jqplot.highlighter.js');
1149 $scripts->addFile('canvg/canvg.js');
1150 $scripts->addFile('jquery/jquery.tablesorter.js');
1154 * There is no point in even attempting to process
1155 * an ajax request if there is a token mismatch
1157 if (isset($response) && $response->isAjax() && $token_mismatch) {
1158 $response->isSuccess(false);
1159 $response->addJSON(
1160 'message',
1161 PMA_Message::error(__('Error: Token mismatch'))
1163 exit;
1165 } else { // end if !defined('PMA_MINIMUM_COMMON')
1166 // load user preferences
1167 $GLOBALS['PMA_Config']->loadUserPreferences();
1170 // remove sensitive values from session
1171 $GLOBALS['PMA_Config']->set('blowfish_secret', '');
1172 $GLOBALS['PMA_Config']->set('Servers', '');
1173 $GLOBALS['PMA_Config']->set('default_server', '');
1175 /* Tell tracker that it can actually work */
1176 PMA_Tracker::enable();
1179 * @global boolean $GLOBALS['is_ajax_request']
1180 * @todo should this be moved to the variables init section above?
1182 * Check if the current request is an AJAX request, and set is_ajax_request
1183 * accordingly. Suppress headers, footers and unnecessary output if set to
1184 * true
1186 if (isset($_REQUEST['ajax_request']) && $_REQUEST['ajax_request'] == true) {
1187 $GLOBALS['is_ajax_request'] = true;
1188 } else {
1189 $GLOBALS['is_ajax_request'] = false;
1192 if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
1193 PMA_fatalError(__("GLOBALS overwrite attempt"));
1197 * protect against possible exploits - there is no need to have so much variables
1199 if (count($_REQUEST) > 1000) {
1200 PMA_fatalError(__('possible exploit'));
1204 * Check for numeric keys
1205 * (if register_globals is on, numeric key can be found in $GLOBALS)
1207 foreach ($GLOBALS as $key => $dummy) {
1208 if (is_numeric($key)) {
1209 PMA_fatalError(__('numeric key detected'));
1212 unset($dummy);
1214 // here, the function does not exist with this configuration:
1215 // $cfg['ServerDefault'] = 0;
1216 $GLOBALS['is_superuser']
1217 = isset($GLOBALS['dbi']) && $GLOBALS['dbi']->isSuperuser();
1219 if (!empty($__redirect) && in_array($__redirect, $goto_whitelist)) {
1221 * include subform target page
1223 include $__redirect;
1224 exit();
1227 // If Zero configuration mode enabled, check PMA tables in current db.
1228 if (! defined('PMA_MINIMUM_COMMON')
1229 && ! empty($GLOBALS['server'])
1230 && isset($GLOBALS['cfg']['ZeroConf'])
1231 && $GLOBALS['cfg']['ZeroConf'] == true
1233 if (! empty($GLOBALS['db'])) {
1234 $cfgRelation = PMA_getRelationsParam();
1235 if (empty($cfgRelation['db'])) {
1236 PMA_fixPMATables($GLOBALS['db'], false);
1239 $cfgRelation = PMA_getRelationsParam();
1240 if (empty($cfgRelation['db'])) {
1241 foreach ($GLOBALS['pma']->databases as $database) {
1242 if ($database == 'phpmyadmin') {
1243 PMA_fixPMATables($database, false);
1249 if (! defined('PMA_MINIMUM_COMMON')) {
1250 include_once 'libraries/config/page_settings.class.php';