Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / classes / Config.php
blobe7bc22ed1a7576d22a38bd745c31ca5df8785f43
1 <?php
2 /**
3 * Configuration handling.
4 */
6 declare(strict_types=1);
8 namespace PhpMyAdmin;
10 use const DIRECTORY_SEPARATOR;
11 use const E_USER_ERROR;
12 use const PHP_OS;
13 use const PHP_URL_PATH;
14 use const PHP_URL_SCHEME;
15 use const PHP_VERSION_ID;
16 use function array_filter;
17 use function array_flip;
18 use function array_intersect_key;
19 use function array_keys;
20 use function array_merge;
21 use function array_replace_recursive;
22 use function array_slice;
23 use function count;
24 use function define;
25 use function defined;
26 use function error_get_last;
27 use function error_reporting;
28 use function explode;
29 use function fclose;
30 use function file_exists;
31 use function filemtime;
32 use function fileperms;
33 use function fopen;
34 use function fread;
35 use function function_exists;
36 use function gd_info;
37 use function implode;
38 use function ini_get;
39 use function intval;
40 use function is_dir;
41 use function is_int;
42 use function is_numeric;
43 use function is_readable;
44 use function is_string;
45 use function is_writable;
46 use function max;
47 use function mb_strstr;
48 use function mb_strtolower;
49 use function md5;
50 use function min;
51 use function mkdir;
52 use function ob_end_clean;
53 use function ob_get_clean;
54 use function ob_start;
55 use function parse_url;
56 use function preg_match;
57 use function realpath;
58 use function rtrim;
59 use function setcookie;
60 use function sprintf;
61 use function str_replace;
62 use function stripos;
63 use function strlen;
64 use function strpos;
65 use function strtolower;
66 use function substr;
67 use function sys_get_temp_dir;
68 use function time;
69 use function trigger_error;
70 use function trim;
72 /**
73 * Configuration class
75 class Config
77 /** @var string default config source */
78 public $defaultSource = ROOT_PATH . 'libraries/config.default.php';
80 /** @var array default configuration settings */
81 public $default = [];
83 /** @var array configuration settings, without user preferences applied */
84 public $baseSettings = [];
86 /** @var array configuration settings */
87 public $settings = [];
89 /** @var string config source */
90 public $source = '';
92 /** @var int source modification time */
93 public $sourceMtime = 0;
95 /** @var int */
96 public $defaultSourceMtime = 0;
98 /** @var int */
99 public $setMtime = 0;
101 /** @var bool */
102 public $errorConfigFile = false;
104 /** @var bool */
105 public $errorConfigDefaultFile = false;
107 /** @var array */
108 public $defaultServer = [];
111 * @var bool whether init is done or not
112 * set this to false to force some initial checks
113 * like checking for required functions
115 public $done = false;
118 * @param string $source source to read config from
120 public function __construct(?string $source = null)
122 $this->settings = ['is_setup' => false];
124 // functions need to refresh in case of config file changed goes in
125 // PhpMyAdmin\Config::load()
126 $this->load($source);
128 // other settings, independent from config file, comes in
129 $this->checkSystem();
131 $this->baseSettings = $this->settings;
135 * sets system and application settings
137 public function checkSystem(): void
139 $this->set('PMA_VERSION', '5.1.0-rc1');
140 /* Major version */
141 $this->set(
142 'PMA_MAJOR_VERSION',
143 implode('.', array_slice(explode('.', $this->get('PMA_VERSION'), 3), 0, 2))
146 $this->checkWebServerOs();
147 $this->checkWebServer();
148 $this->checkGd2();
149 $this->checkClient();
150 $this->checkUpload();
151 $this->checkUploadSize();
152 $this->checkOutputCompression();
156 * whether to use gzip output compression or not
158 public function checkOutputCompression(): void
160 // If zlib output compression is set in the php configuration file, no
161 // output buffering should be run
162 if (ini_get('zlib.output_compression')) {
163 $this->set('OBGzip', false);
166 // enable output-buffering (if set to 'auto')
167 if (strtolower((string) $this->get('OBGzip')) !== 'auto') {
168 return;
171 $this->set('OBGzip', true);
175 * Sets the client platform based on user agent
177 * @param string $user_agent the user agent
179 private function setClientPlatform(string $user_agent): void
181 if (mb_strstr($user_agent, 'Win')) {
182 $this->set('PMA_USR_OS', 'Win');
183 } elseif (mb_strstr($user_agent, 'Mac')) {
184 $this->set('PMA_USR_OS', 'Mac');
185 } elseif (mb_strstr($user_agent, 'Linux')) {
186 $this->set('PMA_USR_OS', 'Linux');
187 } elseif (mb_strstr($user_agent, 'Unix')) {
188 $this->set('PMA_USR_OS', 'Unix');
189 } elseif (mb_strstr($user_agent, 'OS/2')) {
190 $this->set('PMA_USR_OS', 'OS/2');
191 } else {
192 $this->set('PMA_USR_OS', 'Other');
197 * Determines platform (OS), browser and version of the user
198 * Based on a phpBuilder article:
200 * @see http://www.phpbuilder.net/columns/tim20000821.php
202 public function checkClient(): void
204 if (Core::getenv('HTTP_USER_AGENT')) {
205 $HTTP_USER_AGENT = Core::getenv('HTTP_USER_AGENT');
206 } else {
207 $HTTP_USER_AGENT = '';
210 // 1. Platform
211 $this->setClientPlatform($HTTP_USER_AGENT);
213 // 2. browser and version
214 // (must check everything else before Mozilla)
216 $is_mozilla = preg_match(
217 '@Mozilla/([0-9]\.[0-9]{1,2})@',
218 $HTTP_USER_AGENT,
219 $mozilla_version
222 if (preg_match(
223 '@Opera(/| )([0-9]\.[0-9]{1,2})@',
224 $HTTP_USER_AGENT,
225 $log_version
226 )) {
227 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
228 $this->set('PMA_USR_BROWSER_AGENT', 'OPERA');
229 } elseif (preg_match(
230 '@(MS)?IE ([0-9]{1,2}\.[0-9]{1,2})@',
231 $HTTP_USER_AGENT,
232 $log_version
233 )) {
234 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
235 $this->set('PMA_USR_BROWSER_AGENT', 'IE');
236 } elseif (preg_match(
237 '@Trident/(7)\.0@',
238 $HTTP_USER_AGENT,
239 $log_version
240 )) {
241 $this->set('PMA_USR_BROWSER_VER', intval($log_version[1]) + 4);
242 $this->set('PMA_USR_BROWSER_AGENT', 'IE');
243 } elseif (preg_match(
244 '@OmniWeb/([0-9]{1,3})@',
245 $HTTP_USER_AGENT,
246 $log_version
247 )) {
248 $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
249 $this->set('PMA_USR_BROWSER_AGENT', 'OMNIWEB');
250 // Konqueror 2.2.2 says Konqueror/2.2.2
251 // Konqueror 3.0.3 says Konqueror/3
252 } elseif (preg_match(
253 '@(Konqueror/)(.*)(;)@',
254 $HTTP_USER_AGENT,
255 $log_version
256 )) {
257 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
258 $this->set('PMA_USR_BROWSER_AGENT', 'KONQUEROR');
259 // must check Chrome before Safari
260 } elseif ($is_mozilla
261 && preg_match('@Chrome/([0-9.]*)@', $HTTP_USER_AGENT, $log_version)
263 $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
264 $this->set('PMA_USR_BROWSER_AGENT', 'CHROME');
265 // newer Safari
266 } elseif ($is_mozilla
267 && preg_match('@Version/(.*) Safari@', $HTTP_USER_AGENT, $log_version)
269 $this->set(
270 'PMA_USR_BROWSER_VER',
271 $log_version[1]
273 $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
274 // older Safari
275 } elseif ($is_mozilla
276 && preg_match('@Safari/([0-9]*)@', $HTTP_USER_AGENT, $log_version)
278 $this->set(
279 'PMA_USR_BROWSER_VER',
280 $mozilla_version[1] . '.' . $log_version[1]
282 $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
283 // Firefox
284 } elseif (! mb_strstr($HTTP_USER_AGENT, 'compatible')
285 && preg_match('@Firefox/([\w.]+)@', $HTTP_USER_AGENT, $log_version)
287 $this->set(
288 'PMA_USR_BROWSER_VER',
289 $log_version[1]
291 $this->set('PMA_USR_BROWSER_AGENT', 'FIREFOX');
292 } elseif (preg_match('@rv:1\.9(.*)Gecko@', $HTTP_USER_AGENT)) {
293 $this->set('PMA_USR_BROWSER_VER', '1.9');
294 $this->set('PMA_USR_BROWSER_AGENT', 'GECKO');
295 } elseif ($is_mozilla) {
296 $this->set('PMA_USR_BROWSER_VER', $mozilla_version[1]);
297 $this->set('PMA_USR_BROWSER_AGENT', 'MOZILLA');
298 } else {
299 $this->set('PMA_USR_BROWSER_VER', 0);
300 $this->set('PMA_USR_BROWSER_AGENT', 'OTHER');
305 * Whether GD2 is present
307 public function checkGd2(): void
309 if ($this->get('GD2Available') === 'yes') {
310 $this->set('PMA_IS_GD2', 1);
312 return;
315 if ($this->get('GD2Available') === 'no') {
316 $this->set('PMA_IS_GD2', 0);
318 return;
321 if (! function_exists('imagecreatetruecolor')) {
322 $this->set('PMA_IS_GD2', 0);
324 return;
327 if (function_exists('gd_info')) {
328 $gd_nfo = gd_info();
329 if (mb_strstr($gd_nfo['GD Version'], '2.')) {
330 $this->set('PMA_IS_GD2', 1);
331 } else {
332 $this->set('PMA_IS_GD2', 0);
334 } else {
335 $this->set('PMA_IS_GD2', 0);
340 * Whether the Web server php is running on is IIS
342 public function checkWebServer(): void
344 // some versions return Microsoft-IIS, some Microsoft/IIS
345 // we could use a preg_match() but it's slower
346 if (Core::getenv('SERVER_SOFTWARE')
347 && stripos(Core::getenv('SERVER_SOFTWARE'), 'Microsoft') !== false
348 && stripos(Core::getenv('SERVER_SOFTWARE'), 'IIS') !== false
350 $this->set('PMA_IS_IIS', 1);
351 } else {
352 $this->set('PMA_IS_IIS', 0);
357 * Whether the os php is running on is windows or not
359 public function checkWebServerOs(): void
361 // Default to Unix or Equiv
362 $this->set('PMA_IS_WINDOWS', false);
363 // If PHP_OS is defined then continue
364 if (! defined('PHP_OS')) {
365 return;
368 if (stripos(PHP_OS, 'win') !== false && stripos(PHP_OS, 'darwin') === false) {
369 // Is it some version of Windows
370 $this->set('PMA_IS_WINDOWS', true);
371 } elseif (stripos(PHP_OS, 'OS/2') !== false) {
372 // Is it OS/2 (No file permissions like Windows)
373 $this->set('PMA_IS_WINDOWS', true);
378 * loads default values from default source
380 * @return bool success
382 public function loadDefaults(): bool
384 global $isConfigLoading;
386 /** @var array<string,mixed> $cfg */
387 $cfg = [];
388 if (! @file_exists($this->defaultSource)) {
389 $this->errorConfigDefaultFile = true;
391 return false;
393 $canUseErrorReporting = Util::isErrorReportingAvailable();
394 $oldErrorReporting = null;
395 if ($canUseErrorReporting) {
396 $oldErrorReporting = error_reporting(0);
399 ob_start();
400 $isConfigLoading = true;
401 $eval_result = include $this->defaultSource;
402 $isConfigLoading = false;
403 ob_end_clean();
405 if ($canUseErrorReporting) {
406 error_reporting($oldErrorReporting);
409 if ($eval_result === false) {
410 $this->errorConfigDefaultFile = true;
412 return false;
415 $this->defaultSourceMtime = filemtime($this->defaultSource);
417 $this->defaultServer = $cfg['Servers'][1];
418 unset($cfg['Servers']);
420 $this->default = $cfg;
421 $this->settings = array_replace_recursive($this->settings, $cfg);
423 $this->errorConfigDefaultFile = false;
425 return true;
429 * loads configuration from $source, usually the config file
430 * should be called on object creation
432 * @param string $source config file
434 public function load(?string $source = null): bool
436 global $isConfigLoading;
438 $this->loadDefaults();
440 if ($source !== null) {
441 $this->setSource($source);
444 if (! $this->checkConfigSource()) {
445 return false;
448 $cfg = [];
451 * Parses the configuration file, we throw away any errors or
452 * output.
454 $canUseErrorReporting = Util::isErrorReportingAvailable();
455 $oldErrorReporting = null;
456 if ($canUseErrorReporting) {
457 $oldErrorReporting = error_reporting(0);
460 ob_start();
461 $isConfigLoading = true;
462 $eval_result = include $this->getSource();
463 $isConfigLoading = false;
464 ob_end_clean();
466 if ($canUseErrorReporting) {
467 error_reporting($oldErrorReporting);
470 if ($eval_result === false) {
471 $this->errorConfigFile = true;
472 } else {
473 $this->errorConfigFile = false;
474 $this->sourceMtime = filemtime($this->getSource());
478 * Ignore keys with / as we do not use these
480 * These can be confusing for user configuration layer as it
481 * flatten array using / and thus don't see difference between
482 * $cfg['Export/method'] and $cfg['Export']['method'], while rest
483 * of the code uses the setting only in latter form.
485 * This could be removed once we consistently handle both values
486 * in the functional code as well.
488 * It could use array_filter(...ARRAY_FILTER_USE_KEY), but it's not
489 * supported on PHP 5.5 and HHVM.
491 $matched_keys = array_filter(
492 array_keys($cfg),
493 static function ($key) {
494 return strpos($key, '/') === false;
498 $cfg = array_intersect_key($cfg, array_flip($matched_keys));
500 $this->settings = array_replace_recursive($this->settings, $cfg);
502 return true;
506 * Sets the connection collation
508 private function setConnectionCollation(): void
510 global $dbi;
512 $collation_connection = $this->get('DefaultConnectionCollation');
513 if (empty($collation_connection)
514 || $collation_connection == $GLOBALS['collation_connection']
516 return;
519 $dbi->setCollation($collation_connection);
523 * Loads user preferences and merges them with current config
524 * must be called after control connection has been established
526 public function loadUserPreferences(): void
528 $userPreferences = new UserPreferences();
529 // index.php should load these settings, so that phpmyadmin.css.php
530 // will have everything available in session cache
531 $server = $GLOBALS['server'] ?? (! empty($GLOBALS['cfg']['ServerDefault'])
532 ? $GLOBALS['cfg']['ServerDefault']
533 : 0);
534 $cache_key = 'server_' . $server;
535 if ($server > 0 && ! defined('PMA_MINIMUM_COMMON')) {
536 $config_mtime = max($this->defaultSourceMtime, $this->sourceMtime);
537 // cache user preferences, use database only when needed
538 if (! isset($_SESSION['cache'][$cache_key]['userprefs'])
539 || $_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime
541 $prefs = $userPreferences->load();
542 $_SESSION['cache'][$cache_key]['userprefs']
543 = $userPreferences->apply($prefs['config_data']);
544 $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime'];
545 $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type'];
546 $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime;
548 } elseif ($server == 0
549 || ! isset($_SESSION['cache'][$cache_key]['userprefs'])
551 $this->set('user_preferences', false);
553 return;
555 $config_data = $_SESSION['cache'][$cache_key]['userprefs'];
556 // type is 'db' or 'session'
557 $this->set(
558 'user_preferences',
559 $_SESSION['cache'][$cache_key]['userprefs_type']
561 $this->set(
562 'user_preferences_mtime',
563 $_SESSION['cache'][$cache_key]['userprefs_mtime']
566 // load config array
567 $this->settings = array_replace_recursive($this->settings, $config_data);
568 $GLOBALS['cfg'] = array_replace_recursive($GLOBALS['cfg'], $config_data);
569 if (defined('PMA_MINIMUM_COMMON')) {
570 return;
573 // settings below start really working on next page load, but
574 // changes are made only in index.php so everything is set when
575 // in frames
577 // save theme
578 /** @var ThemeManager $tmanager */
579 $tmanager = ThemeManager::getInstance();
580 if ($tmanager->getThemeCookie() || isset($_REQUEST['set_theme'])) {
581 if ((! isset($config_data['ThemeDefault'])
582 && $tmanager->theme->getId() !== 'original')
583 || isset($config_data['ThemeDefault'])
584 && $config_data['ThemeDefault'] != $tmanager->theme->getId()
586 // new theme was set in common.inc.php
587 $this->setUserValue(
588 null,
589 'ThemeDefault',
590 $tmanager->theme->getId(),
591 'original'
594 } else {
595 // no cookie - read default from settings
596 if ($tmanager->theme !== null
597 && $this->settings['ThemeDefault'] != $tmanager->theme->getId()
598 && $tmanager->checkTheme($this->settings['ThemeDefault'])
600 $tmanager->setActiveTheme($this->settings['ThemeDefault']);
601 $tmanager->setThemeCookie();
605 // save language
606 if ($this->issetCookie('pma_lang') || isset($_POST['lang'])) {
607 if ((! isset($config_data['lang'])
608 && $GLOBALS['lang'] !== 'en')
609 || isset($config_data['lang'])
610 && $GLOBALS['lang'] != $config_data['lang']
612 $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en');
614 } else {
615 // read language from settings
616 if (isset($config_data['lang'])) {
617 $language = LanguageManager::getInstance()->getLanguage(
618 $config_data['lang']
620 if ($language !== false) {
621 $language->activate();
622 $this->setCookie('pma_lang', $language->getCode());
627 // set connection collation
628 $this->setConnectionCollation();
632 * Sets config value which is stored in user preferences (if available)
633 * or in a cookie.
635 * If user preferences are not yet initialized, option is applied to
636 * global config and added to a update queue, which is processed
637 * by {@link loadUserPreferences()}
639 * @param string|null $cookie_name can be null
640 * @param string $cfg_path configuration path
641 * @param string $new_cfg_value new value
642 * @param string|null $default_value default value
644 * @return true|Message
646 public function setUserValue(
647 ?string $cookie_name,
648 string $cfg_path,
649 $new_cfg_value,
650 $default_value = null
652 $userPreferences = new UserPreferences();
653 $result = true;
654 // use permanent user preferences if possible
655 $prefs_type = $this->get('user_preferences');
656 if ($prefs_type) {
657 if ($default_value === null) {
658 $default_value = Core::arrayRead($cfg_path, $this->default);
660 $result = $userPreferences->persistOption($cfg_path, $new_cfg_value, $default_value);
662 if ($prefs_type !== 'db' && $cookie_name) {
663 // fall back to cookies
664 if ($default_value === null) {
665 $default_value = Core::arrayRead($cfg_path, $this->settings);
667 $this->setCookie($cookie_name, $new_cfg_value, $default_value);
669 Core::arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value);
670 Core::arrayWrite($cfg_path, $this->settings, $new_cfg_value);
672 return $result;
676 * Reads value stored by {@link setUserValue()}
678 * @param string $cookie_name cookie name
679 * @param mixed $cfg_value config value
681 * @return mixed
683 public function getUserValue(string $cookie_name, $cfg_value)
685 $cookie_exists = ! empty($this->getCookie($cookie_name));
686 $prefs_type = $this->get('user_preferences');
687 if ($prefs_type === 'db') {
688 // permanent user preferences value exists, remove cookie
689 if ($cookie_exists) {
690 $this->removeCookie($cookie_name);
692 } elseif ($cookie_exists) {
693 return $this->getCookie($cookie_name);
696 // return value from $cfg array
697 return $cfg_value;
701 * set source
703 * @param string $source source
705 public function setSource(string $source): void
707 $this->source = trim($source);
711 * check config source
713 * @return bool whether source is valid or not
715 public function checkConfigSource(): bool
717 if (! $this->getSource()) {
718 // no configuration file set at all
719 return false;
722 if (! @file_exists($this->getSource())) {
723 $this->sourceMtime = 0;
725 return false;
728 if (! @is_readable($this->getSource())) {
729 // manually check if file is readable
730 // might be bug #3059806 Supporting running from CIFS/Samba shares
732 $contents = false;
733 $handle = @fopen($this->getSource(), 'r');
734 if ($handle !== false) {
735 $contents = @fread($handle, 1); // reading 1 byte is enough to test
736 fclose($handle);
738 if ($contents === false) {
739 $this->sourceMtime = 0;
740 Core::fatalError(
741 sprintf(
742 function_exists('__')
743 ? __('Existing configuration file (%s) is not readable.')
744 : 'Existing configuration file (%s) is not readable.',
745 $this->getSource()
749 return false;
753 return true;
757 * verifies the permissions on config file (if asked by configuration)
758 * (must be called after config.inc.php has been merged)
760 public function checkPermissions(): void
762 // Check for permissions (on platforms that support it):
763 if (! $this->get('CheckConfigurationPermissions') || ! @file_exists($this->getSource())) {
764 return;
767 $perms = @fileperms($this->getSource());
768 if ($perms === false || (! ($perms & 2))) {
769 return;
772 // This check is normally done after loading configuration
773 $this->checkWebServerOs();
774 if ($this->get('PMA_IS_WINDOWS') === true) {
775 return;
778 $this->sourceMtime = 0;
779 Core::fatalError(
781 'Wrong permissions on configuration file, '
782 . 'should not be world writable!'
788 * Checks for errors
789 * (must be called after config.inc.php has been merged)
791 public function checkErrors(): void
793 if ($this->errorConfigDefaultFile) {
794 Core::fatalError(
795 sprintf(
796 __('Could not load default configuration from: %1$s'),
797 $this->defaultSource
802 if (! $this->errorConfigFile) {
803 return;
806 $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
807 . '[br][br]'
808 . __(
809 'This usually means there is a syntax error in it, '
810 . 'please check any errors shown below.'
812 . '[br][br]'
813 . '[conferr]';
814 trigger_error($error, E_USER_ERROR);
818 * returns specific config setting
820 * @param string $setting config setting
822 * @return mixed|null value
824 public function get(string $setting)
826 if (isset($this->settings[$setting])) {
827 return $this->settings[$setting];
830 return null;
834 * sets configuration variable
836 * @param string $setting configuration option
837 * @param mixed $value new value for configuration option
839 public function set(string $setting, $value): void
841 if (isset($this->settings[$setting])
842 && $this->settings[$setting] === $value
844 return;
847 $this->settings[$setting] = $value;
848 $this->setMtime = time();
852 * returns source for current config
854 * @return string config source
856 public function getSource(): string
858 return $this->source;
862 * returns a unique value to force a CSS reload if either the config
863 * or the theme changes
865 * @return int Summary of unix timestamps, to be unique on theme parameters
866 * change
868 public function getThemeUniqueValue(): int
870 global $PMA_Theme;
872 return (int) (
873 $this->sourceMtime +
874 $this->defaultSourceMtime +
875 $this->get('user_preferences_mtime') +
876 ($PMA_Theme->mtimeInfo ?? 0) +
877 ($PMA_Theme->filesizeInfo ?? 0)
882 * checks if upload is enabled
884 public function checkUpload(): void
886 if (! ini_get('file_uploads')) {
887 $this->set('enable_upload', false);
889 return;
892 $this->set('enable_upload', true);
893 // if set "php_admin_value file_uploads Off" in httpd.conf
894 // ini_get() also returns the string "Off" in this case:
895 if (strtolower((string) ini_get('file_uploads')) !== 'off') {
896 return;
899 $this->set('enable_upload', false);
903 * Maximum upload size as limited by PHP
904 * Used with permission from Moodle (https://moodle.org/) by Martin Dougiamas
906 * this section generates $max_upload_size in bytes
908 public function checkUploadSize(): void
910 $fileSize = ini_get('upload_max_filesize');
912 if (! $fileSize) {
913 $fileSize = '5M';
916 $size = Core::getRealSize($fileSize);
917 $postSize = ini_get('post_max_size');
919 if ($postSize) {
920 $size = min($size, Core::getRealSize($postSize));
923 $this->set('max_upload_size', $size);
927 * Checks if protocol is https
929 * This function checks if the https protocol on the active connection.
931 public function isHttps(): bool
933 if ($this->get('is_https') !== null) {
934 return $this->get('is_https');
937 $url = $this->get('PmaAbsoluteUri');
939 $is_https = false;
940 if (! empty($url) && parse_url($url, PHP_URL_SCHEME) === 'https') {
941 $is_https = true;
942 } elseif (strtolower(Core::getenv('HTTP_SCHEME')) === 'https') {
943 $is_https = true;
944 } elseif (strtolower(Core::getenv('HTTPS')) === 'on') {
945 $is_https = true;
946 } elseif (strtolower(substr(Core::getenv('REQUEST_URI'), 0, 6)) === 'https:') {
947 $is_https = true;
948 } elseif (strtolower(Core::getenv('HTTP_HTTPS_FROM_LB')) === 'on') {
949 // A10 Networks load balancer
950 $is_https = true;
951 } elseif (strtolower(Core::getenv('HTTP_FRONT_END_HTTPS')) === 'on') {
952 $is_https = true;
953 } elseif (strtolower(Core::getenv('HTTP_X_FORWARDED_PROTO')) === 'https') {
954 $is_https = true;
955 } elseif (strtolower(Core::getenv('HTTP_CLOUDFRONT_FORWARDED_PROTO')) === 'https') {
956 // Amazon CloudFront, issue #15621
957 $is_https = true;
958 } elseif (Util::getProtoFromForwardedHeader(Core::getenv('HTTP_FORWARDED')) === 'https') {
959 // RFC 7239 Forwarded header
960 $is_https = true;
961 } elseif (Core::getenv('SERVER_PORT') == 443) {
962 $is_https = true;
965 $this->set('is_https', $is_https);
967 return $is_https;
971 * Get phpMyAdmin root path
973 public function getRootPath(): string
975 static $cookie_path = null;
977 if ($cookie_path !== null && ! defined('TESTSUITE')) {
978 return $cookie_path;
981 $url = $this->get('PmaAbsoluteUri');
983 if (! empty($url)) {
984 $path = parse_url($url, PHP_URL_PATH);
985 if (! empty($path)) {
986 if (substr($path, -1) !== '/') {
987 return $path . '/';
990 return $path;
994 $parsedUrlPath = parse_url($GLOBALS['PMA_PHP_SELF'], PHP_URL_PATH);
996 $parts = explode(
997 '/',
998 rtrim(str_replace('\\', '/', $parsedUrlPath), '/')
1001 /* Remove filename */
1002 if (substr($parts[count($parts) - 1], -4) === '.php') {
1003 $parts = array_slice($parts, 0, count($parts) - 1);
1006 /* Remove extra path from javascript calls */
1007 if (defined('PMA_PATH_TO_BASEDIR')) {
1008 $parts = array_slice($parts, 0, count($parts) - 1);
1011 $parts[] = '';
1013 return implode('/', $parts);
1017 * enables backward compatibility
1019 public function enableBc(): void
1021 $GLOBALS['cfg'] = $this->settings;
1022 $GLOBALS['default_server'] = $this->defaultServer;
1023 unset($this->defaultServer);
1024 $GLOBALS['is_upload'] = $this->get('enable_upload');
1025 $GLOBALS['max_upload_size'] = $this->get('max_upload_size');
1026 $GLOBALS['is_https'] = $this->get('is_https');
1028 $defines = [
1029 'PMA_VERSION',
1030 'PMA_MAJOR_VERSION',
1031 'PMA_THEME_VERSION',
1032 'PMA_THEME_GENERATION',
1033 'PMA_IS_WINDOWS',
1034 'PMA_IS_GD2',
1035 'PMA_USR_OS',
1036 'PMA_USR_BROWSER_VER',
1037 'PMA_USR_BROWSER_AGENT',
1040 foreach ($defines as $define) {
1041 if (defined($define)) {
1042 continue;
1045 define($define, $this->get($define));
1050 * removes cookie
1052 * @param string $cookieName name of cookie to remove
1054 * @return bool result of setcookie()
1056 public function removeCookie(string $cookieName): bool
1058 $httpCookieName = $this->getCookieName($cookieName);
1060 if ($this->issetCookie($cookieName)) {
1061 unset($_COOKIE[$httpCookieName]);
1063 if (defined('TESTSUITE')) {
1064 return true;
1067 return setcookie(
1068 $httpCookieName,
1070 time() - 3600,
1071 $this->getRootPath(),
1073 $this->isHttps()
1078 * sets cookie if value is different from current cookie value,
1079 * or removes if value is equal to default
1081 * @param string $cookie name of cookie to remove
1082 * @param string $value new cookie value
1083 * @param string $default default value
1084 * @param int $validity validity of cookie in seconds (default is one month)
1085 * @param bool $httponly whether cookie is only for HTTP (and not for scripts)
1087 * @return bool result of setcookie()
1089 public function setCookie(
1090 string $cookie,
1091 string $value,
1092 ?string $default = null,
1093 ?int $validity = null,
1094 bool $httponly = true
1095 ): bool {
1096 global $cfg;
1098 if (strlen($value) > 0 && $default !== null && $value === $default
1100 // default value is used
1101 if ($this->issetCookie($cookie)) {
1102 // remove cookie
1103 return $this->removeCookie($cookie);
1106 return false;
1109 if (strlen($value) === 0 && $this->issetCookie($cookie)) {
1110 // remove cookie, value is empty
1111 return $this->removeCookie($cookie);
1114 $httpCookieName = $this->getCookieName($cookie);
1116 if (! $this->issetCookie($cookie) || $this->getCookie($cookie) !== $value) {
1117 // set cookie with new value
1118 /* Calculate cookie validity */
1119 if ($validity === null) {
1120 /* Valid for one month */
1121 $validity = time() + 2592000;
1122 } elseif ($validity == 0) {
1123 /* Valid for session */
1124 $validity = 0;
1125 } else {
1126 $validity = time() + $validity;
1128 if (defined('TESTSUITE')) {
1129 $_COOKIE[$httpCookieName] = $value;
1131 return true;
1134 if (PHP_VERSION_ID < 70300) {
1135 return setcookie(
1136 $httpCookieName,
1137 $value,
1138 $validity,
1139 $this->getRootPath() . '; samesite=' . $cfg['CookieSameSite'],
1141 $this->isHttps(),
1142 $httponly
1145 $optionalParams = [
1146 'expires' => $validity,
1147 'path' => $this->getRootPath(),
1148 'domain' => '',
1149 'secure' => $this->isHttps(),
1150 'httponly' => $httponly,
1151 'samesite' => $cfg['CookieSameSite'],
1154 return setcookie(
1155 $httpCookieName,
1156 $value,
1157 $optionalParams
1161 // cookie has already $value as value
1162 return true;
1166 * get cookie
1168 * @param string $cookieName The name of the cookie to get
1170 * @return mixed|null result of getCookie()
1172 public function getCookie(string $cookieName)
1174 if (isset($_COOKIE[$this->getCookieName($cookieName)])) {
1175 return $_COOKIE[$this->getCookieName($cookieName)];
1178 return null;
1182 * Get the real cookie name
1184 * @param string $cookieName The name of the cookie
1186 public function getCookieName(string $cookieName): string
1188 return $cookieName . ( $this->isHttps() ? '_https' : '' );
1192 * isset cookie
1194 * @param string $cookieName The name of the cookie to check
1196 * @return bool result of issetCookie()
1198 public function issetCookie(string $cookieName): bool
1200 return isset($_COOKIE[$this->getCookieName($cookieName)]);
1204 * Error handler to catch fatal errors when loading configuration
1205 * file
1207 public static function fatalErrorHandler(): void
1209 global $isConfigLoading;
1211 if (! isset($isConfigLoading) || ! $isConfigLoading) {
1212 return;
1215 $error = error_get_last();
1216 if ($error === null) {
1217 return;
1220 Core::fatalError(
1221 sprintf(
1222 'Failed to load phpMyAdmin configuration (%s:%s): %s',
1223 Error::relPath($error['file']),
1224 $error['line'],
1225 $error['message']
1231 * Wrapper for footer/header rendering
1233 * @param string $filename File to check and render
1234 * @param string $id Div ID
1236 private static function renderCustom(string $filename, string $id): string
1238 $retval = '';
1239 if (@file_exists($filename)) {
1240 $retval .= '<div id="' . $id . '">';
1241 ob_start();
1242 include $filename;
1243 $retval .= ob_get_clean();
1244 $retval .= '</div>';
1247 return $retval;
1251 * Renders user configured footer
1253 public static function renderFooter(): string
1255 return self::renderCustom(CUSTOM_FOOTER_FILE, 'pma_footer');
1259 * Renders user configured footer
1261 public static function renderHeader(): string
1263 return self::renderCustom(CUSTOM_HEADER_FILE, 'pma_header');
1267 * Returns temporary dir path
1269 * @param string $name Directory name
1271 public function getTempDir(string $name): ?string
1273 static $temp_dir = [];
1275 if (isset($temp_dir[$name]) && ! defined('TESTSUITE')) {
1276 return $temp_dir[$name];
1279 $path = $this->get('TempDir');
1280 if (empty($path)) {
1281 $path = null;
1282 } else {
1283 $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
1284 if (! @is_dir($path)) {
1285 @mkdir($path, 0770, true);
1287 if (! @is_dir($path) || ! @is_writable($path)) {
1288 $path = null;
1292 $temp_dir[$name] = $path;
1294 return $path;
1298 * Returns temporary directory
1300 public function getUploadTempDir(): ?string
1302 // First try configured temp dir
1303 // Fallback to PHP upload_tmp_dir
1304 $dirs = [
1305 $this->getTempDir('upload'),
1306 ini_get('upload_tmp_dir'),
1307 sys_get_temp_dir(),
1310 foreach ($dirs as $dir) {
1311 if (! empty($dir) && @is_writable($dir)) {
1312 return realpath($dir);
1316 return null;
1320 * Selects server based on request parameters.
1322 public function selectServer(): int
1324 $request = empty($_REQUEST['server']) ? 0 : $_REQUEST['server'];
1327 * Lookup server by name
1328 * (see FAQ 4.8)
1330 if (! is_numeric($request)) {
1331 foreach ($this->settings['Servers'] as $i => $server) {
1332 $verboseToLower = mb_strtolower($server['verbose']);
1333 $serverToLower = mb_strtolower($request);
1334 if ($server['host'] == $request
1335 || $server['verbose'] == $request
1336 || $verboseToLower == $serverToLower
1337 || md5($verboseToLower) === $serverToLower
1339 $request = $i;
1340 break;
1343 if (is_string($request)) {
1344 $request = 0;
1349 * If no server is selected, make sure that $this->settings['Server'] is empty (so
1350 * that nothing will work), and skip server authentication.
1351 * We do NOT exit here, but continue on without logging into any server.
1352 * This way, the welcome page will still come up (with no server info) and
1353 * present a choice of servers in the case that there are multiple servers
1354 * and '$this->settings['ServerDefault'] = 0' is set.
1357 if (is_numeric($request) && ! empty($request) && ! empty($this->settings['Servers'][$request])) {
1358 $server = $request;
1359 $this->settings['Server'] = $this->settings['Servers'][$server];
1360 } else {
1361 if (! empty($this->settings['Servers'][$this->settings['ServerDefault']])) {
1362 $server = $this->settings['ServerDefault'];
1363 $this->settings['Server'] = $this->settings['Servers'][$server];
1364 } else {
1365 $server = 0;
1366 $this->settings['Server'] = [];
1370 return (int) $server;
1374 * Checks whether Servers configuration is valid and possibly apply fixups.
1376 public function checkServers(): void
1378 // Do we have some server?
1379 if (! isset($this->settings['Servers']) || count($this->settings['Servers']) === 0) {
1380 // No server => create one with defaults
1381 $this->settings['Servers'] = [1 => $this->defaultServer];
1382 } else {
1383 // We have server(s) => apply default configuration
1384 $new_servers = [];
1386 foreach ($this->settings['Servers'] as $server_index => $each_server) {
1387 // Detect wrong configuration
1388 if (! is_int($server_index) || $server_index < 1) {
1389 trigger_error(
1390 sprintf(__('Invalid server index: %s'), $server_index),
1391 E_USER_ERROR
1395 $each_server = array_merge($this->defaultServer, $each_server);
1397 // Final solution to bug #582890
1398 // If we are using a socket connection
1399 // and there is nothing in the verbose server name
1400 // or the host field, then generate a name for the server
1401 // in the form of "Server 2", localized of course!
1402 if (empty($each_server['host']) && empty($each_server['verbose'])) {
1403 $each_server['verbose'] = sprintf(__('Server %d'), $server_index);
1406 $new_servers[$server_index] = $each_server;
1408 $this->settings['Servers'] = $new_servers;
1413 * Return connection parameters for the database server
1415 * @param int $mode Connection mode on of CONNECT_USER, CONNECT_CONTROL
1416 * or CONNECT_AUXILIARY.
1417 * @param array|null $server Server information like host/port/socket/persistent
1419 * @return array user, host and server settings array
1421 public static function getConnectionParams(int $mode, ?array $server = null): array
1423 global $cfg;
1425 $user = null;
1426 $password = null;
1428 if ($mode == DatabaseInterface::CONNECT_USER) {
1429 $user = $cfg['Server']['user'];
1430 $password = $cfg['Server']['password'];
1431 $server = $cfg['Server'];
1432 } elseif ($mode == DatabaseInterface::CONNECT_CONTROL) {
1433 $user = $cfg['Server']['controluser'];
1434 $password = $cfg['Server']['controlpass'];
1436 $server = [];
1438 if (! empty($cfg['Server']['controlhost'])) {
1439 $server['host'] = $cfg['Server']['controlhost'];
1440 } else {
1441 $server['host'] = $cfg['Server']['host'];
1443 // Share the settings if the host is same
1444 if ($server['host'] == $cfg['Server']['host']) {
1445 $shared = [
1446 'port',
1447 'socket',
1448 'compress',
1449 'ssl',
1450 'ssl_key',
1451 'ssl_cert',
1452 'ssl_ca',
1453 'ssl_ca_path',
1454 'ssl_ciphers',
1455 'ssl_verify',
1457 foreach ($shared as $item) {
1458 if (! isset($cfg['Server'][$item])) {
1459 continue;
1462 $server[$item] = $cfg['Server'][$item];
1465 // Set configured port
1466 if (! empty($cfg['Server']['controlport'])) {
1467 $server['port'] = $cfg['Server']['controlport'];
1469 // Set any configuration with control_ prefix
1470 foreach ($cfg['Server'] as $key => $val) {
1471 if (substr($key, 0, 8) !== 'control_') {
1472 continue;
1475 $server[substr($key, 8)] = $val;
1477 } else {
1478 if ($server === null) {
1479 return [
1480 null,
1481 null,
1482 null,
1485 if (isset($server['user'])) {
1486 $user = $server['user'];
1488 if (isset($server['password'])) {
1489 $password = $server['password'];
1493 // Perform sanity checks on some variables
1494 $server['port'] = empty($server['port']) ? 0 : (int) $server['port'];
1496 if (empty($server['socket'])) {
1497 $server['socket'] = null;
1499 if (empty($server['host'])) {
1500 $server['host'] = 'localhost';
1502 if (! isset($server['ssl'])) {
1503 $server['ssl'] = false;
1505 if (! isset($server['compress'])) {
1506 $server['compress'] = false;
1509 return [
1510 $user,
1511 $password,
1512 $server,
1517 * Get LoginCookieValidity from preferences cache.
1519 * No generic solution for loading preferences from cache as some settings
1520 * need to be kept for processing in loadUserPreferences().
1522 * @see loadUserPreferences()
1524 public function getLoginCookieValidityFromCache(int $server): void
1526 global $cfg;
1528 $cacheKey = 'server_' . $server;
1530 if (! isset($_SESSION['cache'][$cacheKey]['userprefs']['LoginCookieValidity'])) {
1531 return;
1534 $value = $_SESSION['cache'][$cacheKey]['userprefs']['LoginCookieValidity'];
1535 $this->set('LoginCookieValidity', $value);
1536 $cfg['LoginCookieValidity'] = $value;