Translated using Weblate (Czech)
[phpmyadmin.git] / libraries / common.inc.php
blob8ec80a9638108274cd47114ecef129c291d245df
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 use PhpMyAdmin\Config;
35 use PhpMyAdmin\Core;
36 use PhpMyAdmin\DatabaseInterface;
37 use PhpMyAdmin\ErrorHandler;
38 use PhpMyAdmin\LanguageManager;
39 use PhpMyAdmin\Logging;
40 use PhpMyAdmin\Message;
41 use PhpMyAdmin\Plugins\AuthenticationPlugin;
42 use PhpMyAdmin\Response;
43 use PhpMyAdmin\Session;
44 use PhpMyAdmin\ThemeManager;
45 use PhpMyAdmin\Tracker;
46 use PhpMyAdmin\Util;
48 /**
49 * block attempts to directly run this script
51 if (getcwd() == dirname(__FILE__)) {
52 die('Attack stopped');
55 /**
56 * Minimum PHP version; can't call Core::fatalError() which uses a
57 * PHP 5 function, so cannot easily localize this message.
59 if (version_compare(PHP_VERSION, '5.5.0', 'lt')) {
60 die(
61 'PHP 5.5+ is required. <br /> Currently installed version is: '
62 . phpversion()
66 /**
67 * for verification in all procedural scripts under libraries
69 define('PHPMYADMIN', true);
71 /**
72 * Load vendor configuration.
74 require_once './libraries/vendor_config.php';
76 /**
77 * Load hash polyfill.
79 require_once './libraries/hash.lib.php';
81 /**
82 * Activate autoloader
84 if (! @is_readable(AUTOLOAD_FILE)) {
85 die(
86 'File <tt>' . AUTOLOAD_FILE . '</tt> missing or not readable. <br />'
87 . 'Most likely you did not run Composer to '
88 . '<a href="https://docs.phpmyadmin.net/en/latest/setup.html#installing-from-git">install library files</a>.'
91 require_once AUTOLOAD_FILE;
93 /**
94 * Load gettext functions.
96 PhpMyAdmin\MoTranslator\Loader::loadFunctions();
98 /**
99 * initialize the error handler
101 $GLOBALS['error_handler'] = new ErrorHandler();
104 * Warning about missing PHP extensions.
106 Core::checkExtensions();
109 * Configure required PHP settings.
111 Core::configure();
113 /******************************************************************************/
114 /* start procedural code label_start_procedural */
116 Core::cleanupPathInfo();
118 /******************************************************************************/
119 /* parsing configuration file LABEL_parsing_config_file */
122 * @global Config $GLOBALS['PMA_Config']
123 * force reading of config file, because we removed sensitive values
124 * in the previous iteration
126 $GLOBALS['PMA_Config'] = new Config(CONFIG_FILE);
129 * include session handling after the globals, to prevent overwriting
131 if (! defined('PMA_NO_SESSION')) {
132 Session::setUp($GLOBALS['PMA_Config'], $GLOBALS['error_handler']);
136 * init some variables LABEL_variables_init
140 * holds parameters to be passed to next page
141 * @global array $GLOBALS['url_params']
143 $GLOBALS['url_params'] = array();
146 * holds page that should be displayed
147 * @global string $GLOBALS['goto']
149 $GLOBALS['goto'] = '';
150 // Security fix: disallow accessing serious server files via "?goto="
151 if (Core::checkPageValidity($_REQUEST['goto'])) {
152 $GLOBALS['goto'] = $_REQUEST['goto'];
153 $GLOBALS['url_params']['goto'] = $_REQUEST['goto'];
154 } else {
155 $GLOBALS['PMA_Config']->removeCookie('goto');
156 unset($_REQUEST['goto'], $_GET['goto'], $_POST['goto']);
160 * returning page
161 * @global string $GLOBALS['back']
163 if (Core::checkPageValidity($_REQUEST['back'])) {
164 $GLOBALS['back'] = $_REQUEST['back'];
165 } else {
166 $GLOBALS['PMA_Config']->removeCookie('back');
167 unset($_REQUEST['back'], $_GET['back'], $_POST['back']);
171 * Check whether user supplied token is valid, if not remove any possibly
172 * dangerous stuff from request.
174 * remember that some objects in the session with session_start and __wakeup()
175 * could access this variables before we reach this point
176 * f.e. PhpMyAdmin\Config: fontsize
178 * Check for token mismatch only if the Request method is POST
179 * GET Requests would never have token and therefore checking
180 * mis-match does not make sense
182 * @todo variables should be handled by their respective owners (objects)
183 * f.e. lang, server in PhpMyAdmin\Config
186 $token_mismatch = true;
187 $token_provided = false;
189 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
190 if (Core::isValid($_POST['token'])) {
191 $token_provided = true;
192 $token_mismatch = ! @hash_equals($_SESSION[' PMA_token '], $_POST['token']);
195 if ($token_mismatch) {
196 /* Warn in case the mismatch is result of failed setting of session cookie */
197 if (isset($_POST['set_session']) && $_POST['set_session'] != session_id()) {
198 trigger_error(
200 'Failed to set session cookie. Maybe you are using '
201 . 'HTTP instead of HTTPS to access phpMyAdmin.'
203 E_USER_ERROR
207 * We don't allow any POST operation parameters if the token is mismatched
208 * or is not provided
210 $whitelist = array('ajax_request');
211 PhpMyAdmin\Sanitize::removeRequestVars($whitelist);
217 * current selected database
218 * @global string $GLOBALS['db']
220 Core::setGlobalDbOrTable('db');
223 * current selected table
224 * @global string $GLOBALS['table']
226 Core::setGlobalDbOrTable('table');
229 * Store currently selected recent table.
230 * Affect $GLOBALS['db'] and $GLOBALS['table']
232 if (Core::isValid($_REQUEST['selected_recent_table'])) {
233 $recent_table = json_decode($_REQUEST['selected_recent_table'], true);
235 $GLOBALS['db']
236 = (array_key_exists('db', $recent_table) && is_string($recent_table['db'])) ?
237 $recent_table['db'] : '';
238 $GLOBALS['url_params']['db'] = $GLOBALS['db'];
240 $GLOBALS['table']
241 = (array_key_exists('table', $recent_table) && is_string($recent_table['table'])) ?
242 $recent_table['table'] : '';
243 $GLOBALS['url_params']['table'] = $GLOBALS['table'];
247 * SQL query to be executed
248 * @global string $GLOBALS['sql_query']
250 $GLOBALS['sql_query'] = '';
251 if (Core::isValid($_POST['sql_query'])) {
252 $GLOBALS['sql_query'] = $_POST['sql_query'];
255 //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup
256 //$_REQUEST['server']; // checked later in this file
257 //$_REQUEST['lang']; // checked by LABEL_loading_language_file
259 /******************************************************************************/
260 /* loading language file LABEL_loading_language_file */
263 * lang detection is done here
265 $language = LanguageManager::getInstance()->selectLanguage();
266 $language->activate();
269 * check for errors occurred while loading configuration
270 * this check is done here after loading language files to present errors in locale
272 $GLOBALS['PMA_Config']->checkPermissions();
273 $GLOBALS['PMA_Config']->checkErrors();
275 /* Check server configuration */
276 Core::checkConfiguration();
278 /* Check request for possible attacks */
279 Core::checkRequest();
281 /******************************************************************************/
282 /* setup servers LABEL_setup_servers */
284 $GLOBALS['PMA_Config']->checkServers();
287 * current server
288 * @global integer $GLOBALS['server']
290 $GLOBALS['server'] = $GLOBALS['PMA_Config']->selectServer();
291 $GLOBALS['url_params']['server'] = $GLOBALS['server'];
294 * BC - enable backward compatibility
295 * exports all configuration settings into $GLOBALS ($GLOBALS['cfg'])
297 $GLOBALS['PMA_Config']->enableBc();
299 /******************************************************************************/
300 /* setup themes LABEL_theme_setup */
302 ThemeManager::initializeTheme();
304 if (! defined('PMA_MINIMUM_COMMON')) {
306 * save some settings in cookies
307 * @todo should be done in PhpMyAdmin\Config
309 $GLOBALS['PMA_Config']->setCookie('pma_lang', $GLOBALS['lang']);
311 ThemeManager::getInstance()->setThemeCookie();
313 if (! empty($cfg['Server'])) {
316 * Loads the proper database interface for this server
318 DatabaseInterface::load();
320 // get LoginCookieValidity from preferences cache
321 // no generic solution for loading preferences from cache as some settings
322 // need to be kept for processing in
323 // PhpMyAdmin\Config::loadUserPreferences()
324 $cache_key = 'server_' . $GLOBALS['server'];
325 if (isset($_SESSION['cache'][$cache_key]['userprefs']['LoginCookieValidity'])
327 $value
328 = $_SESSION['cache'][$cache_key]['userprefs']['LoginCookieValidity'];
329 $GLOBALS['PMA_Config']->set('LoginCookieValidity', $value);
330 $GLOBALS['cfg']['LoginCookieValidity'] = $value;
331 unset($value);
333 unset($cache_key);
335 // Gets the authentication library that fits the $cfg['Server'] settings
336 // and run authentication
339 * the required auth type plugin
341 $auth_class = 'PhpMyAdmin\\Plugins\\Auth\\Authentication' . ucfirst(strtolower($cfg['Server']['auth_type']));
342 if (! @class_exists($auth_class)) {
343 Core::fatalError(
344 __('Invalid authentication method set in configuration:')
345 . ' ' . $cfg['Server']['auth_type']
348 if (isset($_POST['pma_password']) && strlen($_POST['pma_password']) > 256) {
349 $_POST['pma_password'] = substr($_POST['pma_password'], 0, 256);
351 $auth_plugin = new $auth_class();
353 $auth_plugin->authenticate();
355 // Try to connect MySQL with the control user profile (will be used to
356 // get the privileges list for the current user but the true user link
357 // must be open after this one so it would be default one for all the
358 // scripts)
359 $controllink = false;
360 if ($cfg['Server']['controluser'] != '') {
361 $controllink = $GLOBALS['dbi']->connect(
362 DatabaseInterface::CONNECT_CONTROL
366 // Connects to the server (validates user's login)
367 /** @var DatabaseInterface $userlink */
368 $userlink = $GLOBALS['dbi']->connect(DatabaseInterface::CONNECT_USER);
370 if ($userlink === false) {
371 $auth_plugin->showFailure('mysql-denied');
374 if (! $controllink) {
376 * Open separate connection for control queries, this is needed
377 * to avoid problems with table locking used in main connection
378 * and phpMyAdmin issuing queries to configuration storage, which
379 * is not locked by that time.
381 $controllink = $GLOBALS['dbi']->connect(
382 DatabaseInterface::CONNECT_USER,
383 null,
384 DatabaseInterface::CONNECT_CONTROL
388 $auth_plugin->rememberCredentials();
390 $auth_plugin->checkTwoFactor();
392 /* Log success */
393 Logging::logUser($cfg['Server']['user']);
395 if ($GLOBALS['dbi']->getVersion() < $cfg['MysqlMinVersion']['internal']) {
396 Core::fatalError(
397 __('You should upgrade to %s %s or later.'),
398 array('MySQL', $cfg['MysqlMinVersion']['human'])
402 // Sets the default delimiter (if specified).
403 if (!empty($_REQUEST['sql_delimiter'])) {
404 PhpMyAdmin\SqlParser\Lexer::$DEFAULT_DELIMITER = $_REQUEST['sql_delimiter'];
407 // TODO: Set SQL modes too.
409 } else { // end server connecting
410 $response = Response::getInstance();
411 $response->getHeader()->disableMenuAndConsole();
412 $response->getFooter()->setMinimal();
416 * check if profiling was requested and remember it
417 * (note: when $cfg['ServerDefault'] = 0, constant is not defined)
419 if (isset($_REQUEST['profiling'])
420 && Util::profilingSupported()
422 $_SESSION['profiling'] = true;
423 } elseif (isset($_REQUEST['profiling_form'])) {
424 // the checkbox was unchecked
425 unset($_SESSION['profiling']);
429 * Inclusion of profiling scripts is needed on various
430 * pages like sql, tbl_sql, db_sql, tbl_select
432 $response = Response::getInstance();
433 if (isset($_SESSION['profiling'])) {
434 $scripts = $response->getHeader()->getScripts();
435 $scripts->addFile('chart.js');
436 $scripts->addFile('vendor/jqplot/jquery.jqplot.js');
437 $scripts->addFile('vendor/jqplot/plugins/jqplot.pieRenderer.js');
438 $scripts->addFile('vendor/jqplot/plugins/jqplot.highlighter.js');
439 $scripts->addFile('vendor/jquery/jquery.tablesorter.js');
443 * There is no point in even attempting to process
444 * an ajax request if there is a token mismatch
446 if ($response->isAjax() && $_SERVER['REQUEST_METHOD'] == 'POST' && $token_mismatch) {
447 $response->setRequestStatus(false);
448 $response->addJSON(
449 'message',
450 Message::error(__('Error: Token mismatch'))
452 exit;
456 // load user preferences
457 $GLOBALS['PMA_Config']->loadUserPreferences();
459 /* Tell tracker that it can actually work */
460 Tracker::enable();
462 if (! defined('PMA_MINIMUM_COMMON')
463 && ! empty($GLOBALS['server'])
464 && isset($GLOBALS['cfg']['ZeroConf'])
465 && $GLOBALS['cfg']['ZeroConf'] == true
467 $GLOBALS['dbi']->postConnectControl();