2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Configuration handling.
10 use DirectoryIterator
;
13 use PhpMyAdmin\LanguageManager
;
14 use PhpMyAdmin\ThemeManager
;
16 use PhpMyAdmin\UserPreferences
;
18 use PhpMyAdmin\Utils\HttpRequest
;
21 * Indication for error handler (see end of this file).
23 $GLOBALS['pma_config_loading'] = false;
33 * @var string default config source
35 var $default_source = './libraries/config.default.php';
38 * @var array default configuration settings
40 var $default = array();
43 * @var array configuration settings, without user preferences applied
45 var $base_settings = array();
48 * @var array configuration settings
50 var $settings = array();
53 * @var string config source
58 * @var int source modification time
60 var $source_mtime = 0;
61 var $default_source_mtime = 0;
67 var $error_config_file = false;
72 var $error_config_default_file = false;
77 var $default_server = array();
80 * @var boolean whether init is done or not
81 * set this to false to force some initial checks
82 * like checking for required functions
87 * @var UserPreferences
89 private $userPreferences;
94 * @param string $source source to read config from
96 public function __construct($source = null)
98 $this->settings
= array('is_setup' => false);
100 // functions need to refresh in case of config file changed goes in
101 // PhpMyAdmin\Config::load()
102 $this->load($source);
104 // other settings, independent from config file, comes in
105 $this->checkSystem();
107 $this->base_settings
= $this->settings
;
109 $this->userPreferences
= new UserPreferences();
113 * sets system and application settings
117 public function checkSystem()
119 $this->set('PMA_VERSION', '4.9.2-dev');
123 implode('.', array_slice(explode('.', $this->get('PMA_VERSION'), 3), 0, 2))
126 $this->checkWebServerOs();
127 $this->checkWebServer();
129 $this->checkClient();
130 $this->checkUpload();
131 $this->checkUploadSize();
132 $this->checkOutputCompression();
136 * whether to use gzip output compression or not
140 public function checkOutputCompression()
142 // If zlib output compression is set in the php configuration file, no
143 // output buffering should be run
144 if (ini_get('zlib.output_compression')) {
145 $this->set('OBGzip', false);
148 // enable output-buffering (if set to 'auto')
149 if (strtolower($this->get('OBGzip')) == 'auto') {
150 $this->set('OBGzip', true);
155 * Sets the client platform based on user agent
157 * @param string $user_agent the user agent
161 private function _setClientPlatform($user_agent)
163 if (mb_strstr($user_agent, 'Win')) {
164 $this->set('PMA_USR_OS', 'Win');
165 } elseif (mb_strstr($user_agent, 'Mac')) {
166 $this->set('PMA_USR_OS', 'Mac');
167 } elseif (mb_strstr($user_agent, 'Linux')) {
168 $this->set('PMA_USR_OS', 'Linux');
169 } elseif (mb_strstr($user_agent, 'Unix')) {
170 $this->set('PMA_USR_OS', 'Unix');
171 } elseif (mb_strstr($user_agent, 'OS/2')) {
172 $this->set('PMA_USR_OS', 'OS/2');
174 $this->set('PMA_USR_OS', 'Other');
179 * Determines platform (OS), browser and version of the user
180 * Based on a phpBuilder article:
182 * @see http://www.phpbuilder.net/columns/tim20000821.php
186 public function checkClient()
188 if (Core
::getenv('HTTP_USER_AGENT')) {
189 $HTTP_USER_AGENT = Core
::getenv('HTTP_USER_AGENT');
191 $HTTP_USER_AGENT = '';
195 $this->_setClientPlatform($HTTP_USER_AGENT);
197 // 2. browser and version
198 // (must check everything else before Mozilla)
200 $is_mozilla = preg_match(
201 '@Mozilla/([0-9]\.[0-9]{1,2})@',
207 '@Opera(/| )([0-9]\.[0-9]{1,2})@',
211 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
212 $this->set('PMA_USR_BROWSER_AGENT', 'OPERA');
213 } elseif (preg_match(
214 '@(MS)?IE ([0-9]{1,2}\.[0-9]{1,2})@',
218 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
219 $this->set('PMA_USR_BROWSER_AGENT', 'IE');
220 } elseif (preg_match(
225 $this->set('PMA_USR_BROWSER_VER', intval($log_version[1]) +
4);
226 $this->set('PMA_USR_BROWSER_AGENT', 'IE');
227 } elseif (preg_match(
228 '@OmniWeb/([0-9]{1,3})@',
232 $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
233 $this->set('PMA_USR_BROWSER_AGENT', 'OMNIWEB');
234 // Konqueror 2.2.2 says Konqueror/2.2.2
235 // Konqueror 3.0.3 says Konqueror/3
236 } elseif (preg_match(
237 '@(Konqueror/)(.*)(;)@',
241 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
242 $this->set('PMA_USR_BROWSER_AGENT', 'KONQUEROR');
243 // must check Chrome before Safari
244 } elseif ($is_mozilla
245 && preg_match('@Chrome/([0-9.]*)@', $HTTP_USER_AGENT, $log_version)
247 $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
248 $this->set('PMA_USR_BROWSER_AGENT', 'CHROME');
250 } elseif ($is_mozilla
251 && preg_match('@Version/(.*) Safari@', $HTTP_USER_AGENT, $log_version)
254 'PMA_USR_BROWSER_VER', $log_version[1]
256 $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
258 } elseif ($is_mozilla
259 && preg_match('@Safari/([0-9]*)@', $HTTP_USER_AGENT, $log_version)
262 'PMA_USR_BROWSER_VER', $mozilla_version[1] . '.' . $log_version[1]
264 $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
266 } elseif (! mb_strstr($HTTP_USER_AGENT, 'compatible')
267 && preg_match('@Firefox/([\w.]+)@', $HTTP_USER_AGENT, $log_version)
270 'PMA_USR_BROWSER_VER', $log_version[1]
272 $this->set('PMA_USR_BROWSER_AGENT', 'FIREFOX');
273 } elseif (preg_match('@rv:1\.9(.*)Gecko@', $HTTP_USER_AGENT)) {
274 $this->set('PMA_USR_BROWSER_VER', '1.9');
275 $this->set('PMA_USR_BROWSER_AGENT', 'GECKO');
276 } elseif ($is_mozilla) {
277 $this->set('PMA_USR_BROWSER_VER', $mozilla_version[1]);
278 $this->set('PMA_USR_BROWSER_AGENT', 'MOZILLA');
280 $this->set('PMA_USR_BROWSER_VER', 0);
281 $this->set('PMA_USR_BROWSER_AGENT', 'OTHER');
286 * Whether GD2 is present
290 public function checkGd2()
292 if ($this->get('GD2Available') == 'yes') {
293 $this->set('PMA_IS_GD2', 1);
297 if ($this->get('GD2Available') == 'no') {
298 $this->set('PMA_IS_GD2', 0);
302 if (!function_exists('imagecreatetruecolor')) {
303 $this->set('PMA_IS_GD2', 0);
307 if (function_exists('gd_info')) {
309 if (mb_strstr($gd_nfo["GD Version"], '2.')) {
310 $this->set('PMA_IS_GD2', 1);
312 $this->set('PMA_IS_GD2', 0);
315 $this->set('PMA_IS_GD2', 0);
320 * Whether the Web server php is running on is IIS
324 public function checkWebServer()
326 // some versions return Microsoft-IIS, some Microsoft/IIS
327 // we could use a preg_match() but it's slower
328 if (Core
::getenv('SERVER_SOFTWARE')
329 && stristr(Core
::getenv('SERVER_SOFTWARE'), 'Microsoft')
330 && stristr(Core
::getenv('SERVER_SOFTWARE'), 'IIS')
332 $this->set('PMA_IS_IIS', 1);
334 $this->set('PMA_IS_IIS', 0);
339 * Whether the os php is running on is windows or not
343 public function checkWebServerOs()
345 // Default to Unix or Equiv
346 $this->set('PMA_IS_WINDOWS', 0);
347 // If PHP_OS is defined then continue
348 if (defined('PHP_OS')) {
349 if (stristr(PHP_OS
, 'win') && !stristr(PHP_OS
, 'darwin')) {
350 // Is it some version of Windows
351 $this->set('PMA_IS_WINDOWS', 1);
352 } elseif (stristr(PHP_OS
, 'OS/2')) {
353 // Is it OS/2 (No file permissions like Windows)
354 $this->set('PMA_IS_WINDOWS', 1);
360 * detects if Git revision
361 * @param string &$git_location (optional) verified git directory
364 public function isGitRevision(&$git_location = NULL)
367 if (! $this->get('ShowGitRevision')) {
373 isset($_SESSION['is_git_revision'])
374 && array_key_exists('git_location', $_SESSION)
376 // Define location using cached value
377 $git_location = $_SESSION['git_location'];
378 return $_SESSION['is_git_revision'];
381 // find out if there is a .git folder
382 // or a .git file (--separate-git-dir)
385 if (@is_file
($git . '/config')) {
386 $git_location = $git;
388 $_SESSION['git_location'] = null;
389 $_SESSION['is_git_revision'] = false;
392 } elseif (is_file($git)) {
393 $contents = file_get_contents($git);
395 // Matches expected format
396 if (! preg_match('/^gitdir: (.*)$/',
397 $contents, $gitmatch)) {
398 $_SESSION['git_location'] = null;
399 $_SESSION['is_git_revision'] = false;
402 if (@is_dir
($gitmatch[1])) {
403 //Detected git external folder location
404 $git_location = $gitmatch[1];
406 $_SESSION['git_location'] = null;
407 $_SESSION['is_git_revision'] = false;
412 $_SESSION['git_location'] = null;
413 $_SESSION['is_git_revision'] = false;
416 // Define session for caching
417 $_SESSION['git_location'] = $git_location;
418 $_SESSION['is_git_revision'] = true;
423 * detects Git revision, if running inside repo
427 public function checkGitRevision()
429 // find out if there is a .git folder
431 if (! $this->isGitRevision($git_folder)) {
432 $this->set('PMA_VERSION_GIT', 0);
436 if (! $ref_head = @file_get_contents
($git_folder . '/HEAD')) {
437 $this->set('PMA_VERSION_GIT', 0);
441 if ($common_dir_contents = @file_get_contents
($git_folder . '/commondir')) {
442 $git_folder = $git_folder . DIRECTORY_SEPARATOR
. trim($common_dir_contents);
446 // are we on any branch?
447 if (strstr($ref_head, '/')) {
448 // remove ref: prefix
449 $ref_head = substr(trim($ref_head), 5);
450 if (substr($ref_head, 0, 11) === 'refs/heads/') {
451 $branch = substr($ref_head, 11);
453 $branch = basename($ref_head);
456 $ref_file = $git_folder . '/' . $ref_head;
457 if (@file_exists
($ref_file)) {
458 $hash = @file_get_contents
($ref_file);
460 $this->set('PMA_VERSION_GIT', 0);
465 // deal with packed refs
466 $packed_refs = @file_get_contents
($git_folder . '/packed-refs');
467 if (! $packed_refs) {
468 $this->set('PMA_VERSION_GIT', 0);
471 // split file to lines
472 $ref_lines = explode("\n", $packed_refs);
473 foreach ($ref_lines as $line) {
475 if ($line[0] == '#') {
479 $parts = explode(' ', $line);
480 // care only about named refs
481 if (count($parts) != 2) {
484 // have found our ref?
485 if ($parts[1] == $ref_head) {
490 if (! isset($hash)) {
491 $this->set('PMA_VERSION_GIT', 0);
492 // Could not find ref
497 $hash = trim($ref_head);
501 if (! preg_match('/^[0-9a-f]{40}$/i', $hash)) {
503 } elseif (isset($_SESSION['PMA_VERSION_COMMITDATA_' . $hash])) {
504 $commit = $_SESSION['PMA_VERSION_COMMITDATA_' . $hash];
505 } elseif (function_exists('gzuncompress')) {
506 $git_file_name = $git_folder . '/objects/'
507 . substr($hash, 0, 2) . '/' . substr($hash, 2);
508 if (@file_exists
($git_file_name) ) {
509 if (! $commit = @file_get_contents
($git_file_name)) {
510 $this->set('PMA_VERSION_GIT', 0);
513 $commit = explode("\0", gzuncompress($commit), 2);
514 $commit = explode("\n", $commit[1]);
515 $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
517 $pack_names = array();
518 // work with packed data
519 $packs_file = $git_folder . '/objects/info/packs';
520 if (@file_exists
($packs_file)
521 && $packs = @file_get_contents
($packs_file)
523 // File exists. Read it, parse the file to get the names of the
524 // packs. (to look for them in .git/object/pack directory later)
525 foreach (explode("\n", $packs) as $line) {
527 if (strlen(trim($line)) == 0) {
530 // skip non pack lines
531 if ($line[0] != 'P') {
535 $pack_names[] = substr($line, 2);
538 // '.git/objects/info/packs' file can be missing
539 // (atlease in mysGit)
540 // File missing. May be we can look in the .git/object/pack
541 // directory for all the .pack files and use that list of
543 $dirIterator = new DirectoryIterator(
544 $git_folder . '/objects/pack'
546 foreach ($dirIterator as $file_info) {
547 $file_name = $file_info->getFilename();
548 // if this is a .pack file
549 if ($file_info->isFile() && substr($file_name, -5) == '.pack'
551 $pack_names[] = $file_name;
555 $hash = strtolower($hash);
556 foreach ($pack_names as $pack_name) {
557 $index_name = str_replace('.pack', '.idx', $pack_name);
560 $index_data = @file_get_contents
(
561 $git_folder . '/objects/pack/' . $index_name
567 if (substr($index_data, 0, 4) != "\377tOc") {
571 $version = unpack('N', substr($index_data, 4, 4));
572 if ($version[1] != 2) {
575 // parse fanout table
578 substr($index_data, 8, 256 * 4)
581 // find where we should search
582 $firstbyte = intval(substr($hash, 0, 2), 16);
583 // array is indexed from 1 and we need to get
584 // previous entry for start
585 if ($firstbyte == 0) {
588 $start = $fanout[$firstbyte];
590 $end = $fanout[$firstbyte +
1];
592 // stupid linear search for our sha
594 $offset = 8 +
(256 * 4);
595 for ($position = $start; $position < $end; $position++
) {
598 substr($index_data, $offset +
($position * 20), 20)
610 $offset = 8 +
(256 * 4) +
(24 * $fanout[256]);
611 $pack_offset = unpack(
613 substr($index_data, $offset +
($position * 4), 4)
615 $pack_offset = $pack_offset[1];
619 $git_folder . '/objects/pack/' . $pack_name, 'rb'
621 if ($pack_file === false) {
625 fseek($pack_file, $pack_offset);
628 $header = ord(fread($pack_file, 1));
629 $type = ($header >> 4) & 7;
630 $hasnext = ($header & 128) >> 7;
631 $size = $header & 0xf;
635 $byte = ord(fread($pack_file, 1));
636 $size |
= ($byte & 0x7f) << $offset;
637 $hasnext = ($byte & 128) >> 7;
641 // we care only about commit objects
647 $commit = fread($pack_file, $size);
648 $commit = gzuncompress($commit);
649 $commit = explode("\n", $commit);
650 $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
656 $httpRequest = new HttpRequest();
658 // check if commit exists in Github
659 if ($commit !== false
660 && isset($_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash])
662 $is_remote_commit = $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash];
664 $link = 'https://www.phpmyadmin.net/api/commit/' . $hash . '/';
665 $is_found = $httpRequest->create($link, 'GET');
668 $is_remote_commit = false;
669 $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = false;
672 // no remote link for now, but don't cache this as Github is down
673 $is_remote_commit = false;
676 $is_remote_commit = true;
677 $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = true;
678 if ($commit === false) {
679 // if no local commit data, try loading from Github
680 $commit_json = json_decode($is_found);
686 $is_remote_branch = false;
687 if ($is_remote_commit && $branch !== false) {
688 // check if branch exists in Github
689 if (isset($_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash])) {
690 $is_remote_branch = $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash];
692 $link = 'https://www.phpmyadmin.net/api/tree/' . $branch . '/';
693 $is_found = $httpRequest->create($link, 'GET', true);
696 $is_remote_branch = true;
697 $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = true;
700 $is_remote_branch = false;
701 $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = false;
704 // no remote link for now, but don't cache this as Github is down
705 $is_remote_branch = false;
711 if ($commit !== false) {
712 $author = array('name' => '', 'email' => '', 'date' => '');
713 $committer = array('name' => '', 'email' => '', 'date' => '');
716 $dataline = array_shift($commit);
717 $datalinearr = explode(' ', $dataline, 2);
718 $linetype = $datalinearr[0];
719 if (in_array($linetype, array('author', 'committer'))) {
720 $user = $datalinearr[1];
721 preg_match('/([^<]+)<([^>]+)> ([0-9]+)( [^ ]+)?/', $user, $user);
723 'name' => trim($user[1]),
724 'email' => trim($user[2]),
725 'date' => date('Y-m-d H:i:s', $user[3]));
726 if (isset($user[4])) {
727 $user2['date'] .= $user[4];
731 } while ($dataline != '');
732 $message = trim(implode(' ', $commit));
734 } elseif (isset($commit_json) && isset($commit_json->author
) && isset($commit_json->committer
) && isset($commit_json->message
)) {
736 'name' => $commit_json->author
->name
,
737 'email' => $commit_json->author
->email
,
738 'date' => $commit_json->author
->date
);
740 'name' => $commit_json->committer
->name
,
741 'email' => $commit_json->committer
->email
,
742 'date' => $commit_json->committer
->date
);
743 $message = trim($commit_json->message
);
745 $this->set('PMA_VERSION_GIT', 0);
749 $this->set('PMA_VERSION_GIT', 1);
750 $this->set('PMA_VERSION_GIT_COMMITHASH', $hash);
751 $this->set('PMA_VERSION_GIT_BRANCH', $branch);
752 $this->set('PMA_VERSION_GIT_MESSAGE', $message);
753 $this->set('PMA_VERSION_GIT_AUTHOR', $author);
754 $this->set('PMA_VERSION_GIT_COMMITTER', $committer);
755 $this->set('PMA_VERSION_GIT_ISREMOTECOMMIT', $is_remote_commit);
756 $this->set('PMA_VERSION_GIT_ISREMOTEBRANCH', $is_remote_branch);
760 * loads default values from default source
762 * @return boolean success
764 public function loadDefaults()
767 if (! @file_exists
($this->default_source
)) {
768 $this->error_config_default_file
= true;
771 $old_error_reporting = error_reporting(0);
773 $GLOBALS['pma_config_loading'] = true;
774 $eval_result = include $this->default_source
;
775 $GLOBALS['pma_config_loading'] = false;
777 error_reporting($old_error_reporting);
779 if ($eval_result === false) {
780 $this->error_config_default_file
= true;
784 $this->default_source_mtime
= filemtime($this->default_source
);
786 $this->default_server
= $cfg['Servers'][1];
787 unset($cfg['Servers']);
789 $this->default = $cfg;
790 $this->settings
= array_replace_recursive($this->settings
, $cfg);
792 $this->error_config_default_file
= false;
798 * loads configuration from $source, usually the config file
799 * should be called on object creation
801 * @param string $source config file
805 public function load($source = null)
807 $this->loadDefaults();
809 if (null !== $source) {
810 $this->setSource($source);
813 if (! $this->checkConfigSource()) {
820 * Parses the configuration file, we throw away any errors or
823 $old_error_reporting = error_reporting(0);
825 $GLOBALS['pma_config_loading'] = true;
826 $eval_result = include $this->getSource();
827 $GLOBALS['pma_config_loading'] = false;
829 error_reporting($old_error_reporting);
831 if ($eval_result === false) {
832 $this->error_config_file
= true;
834 $this->error_config_file
= false;
835 $this->source_mtime
= filemtime($this->getSource());
839 * Ignore keys with / as we do not use these
841 * These can be confusing for user configuration layer as it
842 * flatten array using / and thus don't see difference between
843 * $cfg['Export/method'] and $cfg['Export']['method'], while rest
844 * of thre code uses the setting only in latter form.
846 * This could be removed once we consistently handle both values
847 * in the functional code as well.
849 * It could use array_filter(...ARRAY_FILTER_USE_KEY), but it's not
850 * supported on PHP 5.5 and HHVM.
852 $matched_keys = array_filter(
854 function ($key) {return strpos($key, '/') === false;}
857 $cfg = array_intersect_key($cfg, array_flip($matched_keys));
860 * Backward compatibility code
862 if (!empty($cfg['DefaultTabTable'])) {
863 $cfg['DefaultTabTable'] = str_replace(
867 'tbl_properties.php',
869 $cfg['DefaultTabTable']
873 if (!empty($cfg['DefaultTabDatabase'])) {
874 $cfg['DefaultTabDatabase'] = str_replace(
880 $cfg['DefaultTabDatabase']
885 $this->settings
= array_replace_recursive($this->settings
, $cfg);
891 * Sets the connection collation
895 private function _setConnectionCollation()
897 $collation_connection = $this->get('DefaultConnectionCollation');
898 if (! empty($collation_connection)
899 && $collation_connection != $GLOBALS['collation_connection']
901 $GLOBALS['dbi']->setCollation($collation_connection);
906 * Loads user preferences and merges them with current config
907 * must be called after control connection has been established
911 public function loadUserPreferences()
913 // index.php should load these settings, so that phpmyadmin.css.php
914 // will have everything available in session cache
915 $server = isset($GLOBALS['server'])
917 : (!empty($GLOBALS['cfg']['ServerDefault'])
918 ?
$GLOBALS['cfg']['ServerDefault']
920 $cache_key = 'server_' . $server;
921 if ($server > 0 && !defined('PMA_MINIMUM_COMMON')) {
922 $config_mtime = max($this->default_source_mtime
, $this->source_mtime
);
923 // cache user preferences, use database only when needed
924 if (! isset($_SESSION['cache'][$cache_key]['userprefs'])
925 ||
$_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime
927 $prefs = $this->userPreferences
->load();
928 $_SESSION['cache'][$cache_key]['userprefs']
929 = $this->userPreferences
->apply($prefs['config_data']);
930 $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime'];
931 $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type'];
932 $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime;
934 } elseif ($server == 0
935 ||
! isset($_SESSION['cache'][$cache_key]['userprefs'])
937 $this->set('user_preferences', false);
940 $config_data = $_SESSION['cache'][$cache_key]['userprefs'];
941 // type is 'db' or 'session'
944 $_SESSION['cache'][$cache_key]['userprefs_type']
947 'user_preferences_mtime',
948 $_SESSION['cache'][$cache_key]['userprefs_mtime']
952 $this->settings
= array_replace_recursive($this->settings
, $config_data);
953 $GLOBALS['cfg'] = array_replace_recursive($GLOBALS['cfg'], $config_data);
954 if (defined('PMA_MINIMUM_COMMON')) {
958 // settings below start really working on next page load, but
959 // changes are made only in index.php so everything is set when
963 /** @var ThemeManager $tmanager */
964 $tmanager = ThemeManager
::getInstance();
965 if ($tmanager->getThemeCookie() ||
isset($_REQUEST['set_theme'])) {
966 if ((! isset($config_data['ThemeDefault'])
967 && $tmanager->theme
->getId() != 'original')
968 ||
isset($config_data['ThemeDefault'])
969 && $config_data['ThemeDefault'] != $tmanager->theme
->getId()
971 // new theme was set in common.inc.php
975 $tmanager->theme
->getId(),
980 // no cookie - read default from settings
981 if ($this->settings
['ThemeDefault'] != $tmanager->theme
->getId()
982 && $tmanager->checkTheme($this->settings
['ThemeDefault'])
984 $tmanager->setActiveTheme($this->settings
['ThemeDefault']);
985 $tmanager->setThemeCookie();
990 if (isset($_COOKIE['pma_lang']) ||
isset($_POST['lang'])) {
991 if ((! isset($config_data['lang'])
992 && $GLOBALS['lang'] != 'en')
993 ||
isset($config_data['lang'])
994 && $GLOBALS['lang'] != $config_data['lang']
996 $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en');
999 // read language from settings
1000 if (isset($config_data['lang'])) {
1001 $language = LanguageManager
::getInstance()->getLanguage(
1002 $config_data['lang']
1004 if ($language !== false) {
1005 $language->activate();
1006 $this->setCookie('pma_lang', $language->getCode());
1011 // set connection collation
1012 $this->_setConnectionCollation();
1016 * Sets config value which is stored in user preferences (if available)
1019 * If user preferences are not yet initialized, option is applied to
1020 * global config and added to a update queue, which is processed
1021 * by {@link loadUserPreferences()}
1023 * @param string $cookie_name can be null
1024 * @param string $cfg_path configuration path
1025 * @param mixed $new_cfg_value new value
1026 * @param mixed $default_value default value
1028 * @return true|PhpMyAdmin\Message
1030 public function setUserValue($cookie_name, $cfg_path, $new_cfg_value,
1031 $default_value = null
1034 // use permanent user preferences if possible
1035 $prefs_type = $this->get('user_preferences');
1037 if ($default_value === null) {
1038 $default_value = Core
::arrayRead($cfg_path, $this->default);
1040 $result = $this->userPreferences
->persistOption($cfg_path, $new_cfg_value, $default_value);
1042 if ($prefs_type != 'db' && $cookie_name) {
1043 // fall back to cookies
1044 if ($default_value === null) {
1045 $default_value = Core
::arrayRead($cfg_path, $this->settings
);
1047 $this->setCookie($cookie_name, $new_cfg_value, $default_value);
1049 Core
::arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value);
1050 Core
::arrayWrite($cfg_path, $this->settings
, $new_cfg_value);
1055 * Reads value stored by {@link setUserValue()}
1057 * @param string $cookie_name cookie name
1058 * @param mixed $cfg_value config value
1062 public function getUserValue($cookie_name, $cfg_value)
1064 $cookie_exists = isset($_COOKIE) && !empty($_COOKIE[$cookie_name]);
1065 $prefs_type = $this->get('user_preferences');
1066 if ($prefs_type == 'db') {
1067 // permanent user preferences value exists, remove cookie
1068 if ($cookie_exists) {
1069 $this->removeCookie($cookie_name);
1071 } elseif ($cookie_exists) {
1072 return $_COOKIE[$cookie_name];
1074 // return value from $cfg array
1081 * @param string $source source
1085 public function setSource($source)
1087 $this->source
= trim($source);
1091 * check config source
1093 * @return boolean whether source is valid or not
1095 public function checkConfigSource()
1097 if (! $this->getSource()) {
1098 // no configuration file set at all
1102 if (! @file_exists
($this->getSource())) {
1103 $this->source_mtime
= 0;
1107 if (! @is_readable
($this->getSource())) {
1108 // manually check if file is readable
1109 // might be bug #3059806 Supporting running from CIFS/Samba shares
1112 $handle = @fopen
($this->getSource(), 'r');
1113 if ($handle !== false) {
1114 $contents = @fread
($handle, 1); // reading 1 byte is enough to test
1117 if ($contents === false) {
1118 $this->source_mtime
= 0;
1121 function_exists('__')
1122 ?
__('Existing configuration file (%s) is not readable.')
1123 : 'Existing configuration file (%s) is not readable.',
1135 * verifies the permissions on config file (if asked by configuration)
1136 * (must be called after config.inc.php has been merged)
1140 public function checkPermissions()
1142 // Check for permissions (on platforms that support it):
1143 if ($this->get('CheckConfigurationPermissions') && @file_exists
($this->getSource())) {
1144 $perms = @fileperms
($this->getSource());
1145 if (!($perms === false) && ($perms & 2)) {
1146 // This check is normally done after loading configuration
1147 $this->checkWebServerOs();
1148 if ($this->get('PMA_IS_WINDOWS') == 0) {
1149 $this->source_mtime
= 0;
1152 'Wrong permissions on configuration file, '
1153 . 'should not be world writable!'
1163 * (must be called after config.inc.php has been merged)
1167 public function checkErrors()
1169 if ($this->error_config_default_file
) {
1172 __('Could not load default configuration from: %1$s'),
1173 $this->default_source
1178 if ($this->error_config_file
) {
1179 $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
1182 'This usually means there is a syntax error in it, '
1183 . 'please check any errors shown below.'
1187 trigger_error($error, E_USER_ERROR
);
1192 * returns specific config setting
1194 * @param string $setting config setting
1196 * @return mixed value
1198 public function get($setting)
1200 if (isset($this->settings
[$setting])) {
1201 return $this->settings
[$setting];
1207 * sets configuration variable
1209 * @param string $setting configuration option
1210 * @param mixed $value new value for configuration option
1214 public function set($setting, $value)
1216 if (! isset($this->settings
[$setting])
1217 ||
$this->settings
[$setting] !== $value
1219 $this->settings
[$setting] = $value;
1220 $this->set_mtime
= time();
1225 * returns source for current config
1227 * @return string config source
1229 public function getSource()
1231 return $this->source
;
1235 * returns a unique value to force a CSS reload if either the config
1236 * or the theme changes
1238 * @return int Summary of unix timestamps and fontsize,
1239 * to be unique on theme parameters change
1241 public function getThemeUniqueValue()
1243 if (null !== $this->get('FontSize')) {
1244 $fontsize = intval($this->get('FontSize'));
1250 $this->source_mtime +
1251 $this->default_source_mtime +
1252 $this->get('user_preferences_mtime') +
1253 $GLOBALS['PMA_Theme']->mtime_info +
1254 $GLOBALS['PMA_Theme']->filesize_info
);
1258 * checks if upload is enabled
1262 public function checkUpload()
1264 if (!ini_get('file_uploads')) {
1265 $this->set('enable_upload', false);
1269 $this->set('enable_upload', true);
1270 // if set "php_admin_value file_uploads Off" in httpd.conf
1271 // ini_get() also returns the string "Off" in this case:
1272 if ('off' == strtolower(ini_get('file_uploads'))) {
1273 $this->set('enable_upload', false);
1278 * Maximum upload size as limited by PHP
1279 * Used with permission from Moodle (https://moodle.org/) by Martin Dougiamas
1281 * this section generates $max_upload_size in bytes
1285 public function checkUploadSize()
1287 if (! $filesize = ini_get('upload_max_filesize')) {
1291 if ($postsize = ini_get('post_max_size')) {
1294 min(Core
::getRealSize($filesize), Core
::getRealSize($postsize))
1297 $this->set('max_upload_size', Core
::getRealSize($filesize));
1302 * Checks if protocol is https
1304 * This function checks if the https protocol on the active connection.
1308 public function isHttps()
1311 if (null !== $this->get('is_https')) {
1312 return $this->get('is_https');
1315 $url = $this->get('PmaAbsoluteUri');
1318 if (! empty($url) && parse_url($url, PHP_URL_SCHEME
) === 'https') {
1320 } elseif (strtolower(Core
::getenv('HTTP_SCHEME')) == 'https') {
1322 } elseif (strtolower(Core
::getenv('HTTPS')) == 'on') {
1324 } elseif (substr(strtolower(Core
::getenv('REQUEST_URI')), 0, 6) == 'https:') {
1326 } elseif (strtolower(Core
::getenv('HTTP_HTTPS_FROM_LB')) == 'on') {
1327 // A10 Networks load balancer
1329 } elseif (strtolower(Core
::getenv('HTTP_FRONT_END_HTTPS')) == 'on') {
1331 } elseif (strtolower(Core
::getenv('HTTP_X_FORWARDED_PROTO')) == 'https') {
1333 } elseif (Core
::getenv('SERVER_PORT') == 443) {
1337 $this->set('is_https', $is_https);
1343 * Get phpMyAdmin root path
1347 public function getRootPath()
1349 static $cookie_path = null;
1351 if (null !== $cookie_path && !defined('TESTSUITE')) {
1352 return $cookie_path;
1355 $url = $this->get('PmaAbsoluteUri');
1357 if (! empty($url)) {
1358 $path = parse_url($url, PHP_URL_PATH
);
1359 if (! empty($path)) {
1360 if (substr($path, -1) != '/') {
1367 $parsed_url = parse_url($GLOBALS['PMA_PHP_SELF']);
1371 rtrim(str_replace('\\', '/', $parsed_url['path']), '/')
1374 /* Remove filename */
1375 if (substr($parts[count($parts) - 1], -4) == '.php') {
1376 $parts = array_slice($parts, 0, count($parts) - 1);
1379 /* Remove extra path from javascript calls */
1380 if (defined('PMA_PATH_TO_BASEDIR')) {
1381 $parts = array_slice($parts, 0, count($parts) - 1);
1386 return implode('/', $parts);
1390 * enables backward compatibility
1394 public function enableBc()
1396 $GLOBALS['cfg'] = $this->settings
;
1397 $GLOBALS['default_server'] = $this->default_server
;
1398 unset($this->default_server
);
1399 $GLOBALS['is_upload'] = $this->get('enable_upload');
1400 $GLOBALS['max_upload_size'] = $this->get('max_upload_size');
1401 $GLOBALS['is_https'] = $this->get('is_https');
1405 'PMA_MAJOR_VERSION',
1406 'PMA_THEME_VERSION',
1407 'PMA_THEME_GENERATION',
1411 'PMA_USR_BROWSER_VER',
1412 'PMA_USR_BROWSER_AGENT'
1415 foreach ($defines as $define) {
1416 if (! defined($define)) {
1417 define($define, $this->get($define));
1423 * returns options for font size selection
1425 * @param string $current_size current selected font size with unit
1427 * @return array selectable font sizes
1429 protected static function getFontsizeOptions($current_size = '82%')
1431 $unit = preg_replace('/[0-9.]*/', '', $current_size);
1432 $value = preg_replace('/[^0-9.]*/', '', $current_size);
1436 $options["$value"] = $value . $unit;
1438 if ($unit === '%') {
1442 $options['100'] = '100%';
1443 } elseif ($unit === 'em') {
1447 } elseif ($unit === 'pt') {
1450 } elseif ($unit === 'px') {
1455 //unknown font size unit
1463 foreach ($factors as $key => $factor) {
1464 $option_inc = $value +
$factor;
1465 $option_dec = $value - $factor;
1466 while (count($options) < 21) {
1467 $options["$option_inc"] = $option_inc . $unit;
1468 if ($option_dec > $factors[0]) {
1469 $options["$option_dec"] = $option_dec . $unit;
1471 $option_inc +
= $factor;
1472 $option_dec -= $factor;
1473 if (isset($factors[$key +
1])
1474 && $option_inc >= $value +
$factors[$key +
1]
1485 * returns html selectbox for font sizes
1487 * @return string html selectbox
1489 protected static function getFontsizeSelection()
1491 $current_size = $GLOBALS['PMA_Config']->get('FontSize');
1492 // for the case when there is no config file (this is supported)
1493 if (empty($current_size)) {
1494 $current_size = '82%';
1496 $options = Config
::getFontsizeOptions($current_size);
1498 $return = '<label for="select_fontsize">' . __('Font size')
1499 . ':</label>' . "\n"
1500 . '<select name="set_fontsize" id="select_fontsize"'
1501 . ' class="autosubmit">' . "\n";
1502 foreach ($options as $option) {
1503 $return .= '<option value="' . $option . '"';
1504 if ($option == $current_size) {
1505 $return .= ' selected="selected"';
1507 $return .= '>' . $option . '</option>' . "\n";
1509 $return .= '</select>';
1515 * return complete font size selection form
1517 * @return string html selectbox
1519 public static function getFontsizeForm()
1521 return '<form name="form_fontsize_selection" id="form_fontsize_selection"'
1522 . ' method="post" action="index.php" class="disableAjax">' . "\n"
1523 . Url
::getHiddenInputs() . "\n"
1524 . Config
::getFontsizeSelection() . "\n"
1531 * @param string $cookie name of cookie to remove
1533 * @return boolean result of setcookie()
1535 public function removeCookie($cookie)
1537 if (defined('TESTSUITE')) {
1538 if (isset($_COOKIE[$cookie])) {
1539 unset($_COOKIE[$cookie]);
1547 $this->getRootPath(),
1554 * sets cookie if value is different from current cookie value,
1555 * or removes if value is equal to default
1557 * @param string $cookie name of cookie to remove
1558 * @param mixed $value new cookie value
1559 * @param string $default default value
1560 * @param int $validity validity of cookie in seconds (default is one month)
1561 * @param bool $httponly whether cookie is only for HTTP (and not for scripts)
1563 * @return boolean result of setcookie()
1565 public function setCookie($cookie, $value, $default = null,
1566 $validity = null, $httponly = true
1568 if (strlen($value) > 0 && null !== $default && $value === $default
1570 // default value is used
1571 if (isset($_COOKIE[$cookie])) {
1573 return $this->removeCookie($cookie);
1578 if (strlen($value) === 0 && isset($_COOKIE[$cookie])) {
1579 // remove cookie, value is empty
1580 return $this->removeCookie($cookie);
1583 if (! isset($_COOKIE[$cookie]) ||
$_COOKIE[$cookie] !== $value) {
1584 // set cookie with new value
1585 /* Calculate cookie validity */
1586 if ($validity === null) {
1587 /* Valid for one month */
1588 $validity = time() +
2592000;
1589 } elseif ($validity == 0) {
1590 /* Valid for session */
1593 $validity = time() +
$validity;
1595 if (defined('TESTSUITE')) {
1596 $_COOKIE[$cookie] = $value;
1603 $this->getRootPath(),
1610 // cookie has already $value as value
1616 * Error handler to catch fatal errors when loading configuration
1620 * PMA_Config_fatalErrorHandler
1623 public static function fatalErrorHandler()
1625 if (!isset($GLOBALS['pma_config_loading'])
1626 ||
!$GLOBALS['pma_config_loading']
1631 $error = error_get_last();
1632 if ($error === null) {
1638 'Failed to load phpMyAdmin configuration (%s:%s): %s',
1639 Error
::relPath($error['file']),
1647 * Wrapper for footer/header rendering
1649 * @param string $filename File to check and render
1650 * @param string $id Div ID
1654 private static function _renderCustom($filename, $id)
1657 if (@file_exists
($filename)) {
1658 $retval .= '<div id="' . $id . '">';
1661 $retval .= ob_get_contents();
1663 $retval .= '</div>';
1669 * Renders user configured footer
1673 public static function renderFooter()
1675 return self
::_renderCustom(CUSTOM_FOOTER_FILE
, 'pma_footer');
1679 * Renders user configured footer
1683 public static function renderHeader()
1685 return self
::_renderCustom(CUSTOM_HEADER_FILE
, 'pma_header');
1689 * Returns temporary dir path
1691 * @param string $name Directory name
1693 * @return string|null
1695 public function getTempDir($name)
1697 static $temp_dir = array();
1699 if (isset($temp_dir[$name]) && !defined('TESTSUITE')) {
1700 return $temp_dir[$name];
1703 $path = $this->get('TempDir');
1707 $path .= '/' . $name;
1708 if (! @is_dir
($path)) {
1709 @mkdir
($path, 0770, true);
1711 if (! @is_dir
($path) ||
! @is_writable
($path)) {
1716 $temp_dir[$name] = $path;
1721 * Returns temporary directory
1725 public function getUploadTempDir()
1727 // First try configured temp dir
1728 // Fallback to PHP upload_tmp_dir
1730 $this->getTempDir('upload'),
1731 ini_get('upload_tmp_dir'),
1735 foreach ($dirs as $dir) {
1736 if (! empty($dir) && @is_writable
($dir)) {
1737 return realpath($dir);
1745 * Selects server based on request parameters.
1749 public function selectServer() {
1751 $request = empty($_REQUEST['server']) ?
0 : $_REQUEST['server'];
1754 * Lookup server by name
1757 if (! is_numeric($request)) {
1758 foreach ($this->settings
['Servers'] as $i => $server) {
1759 $verboseToLower = mb_strtolower($server['verbose']);
1760 $serverToLower = mb_strtolower($request);
1761 if ($server['host'] == $request
1762 ||
$server['verbose'] == $request
1763 ||
$verboseToLower == $serverToLower
1764 ||
md5($verboseToLower) === $serverToLower
1770 if (is_string($request)) {
1776 * If no server is selected, make sure that $this->settings['Server'] is empty (so
1777 * that nothing will work), and skip server authentication.
1778 * We do NOT exit here, but continue on without logging into any server.
1779 * This way, the welcome page will still come up (with no server info) and
1780 * present a choice of servers in the case that there are multiple servers
1781 * and '$this->settings['ServerDefault'] = 0' is set.
1784 if (is_numeric($request) && ! empty($request) && ! empty($this->settings
['Servers'][$request])) {
1786 $this->settings
['Server'] = $this->settings
['Servers'][$server];
1788 if (!empty($this->settings
['Servers'][$this->settings
['ServerDefault']])) {
1789 $server = $this->settings
['ServerDefault'];
1790 $this->settings
['Server'] = $this->settings
['Servers'][$server];
1793 $this->settings
['Server'] = array();
1801 * Checks whether Servers configuration is valid and possibly apply fixups.
1805 public function checkServers() {
1806 // Do we have some server?
1807 if (! isset($this->settings
['Servers']) ||
count($this->settings
['Servers']) == 0) {
1808 // No server => create one with defaults
1809 $this->settings
['Servers'] = array(1 => $this->default_server
);
1811 // We have server(s) => apply default configuration
1812 $new_servers = array();
1814 foreach ($this->settings
['Servers'] as $server_index => $each_server) {
1816 // Detect wrong configuration
1817 if (!is_int($server_index) ||
$server_index < 1) {
1819 sprintf(__('Invalid server index: %s'), $server_index),
1824 $each_server = array_merge($this->default_server
, $each_server);
1826 // Final solution to bug #582890
1827 // If we are using a socket connection
1828 // and there is nothing in the verbose server name
1829 // or the host field, then generate a name for the server
1830 // in the form of "Server 2", localized of course!
1831 if (empty($each_server['host']) && empty($each_server['verbose'])) {
1832 $each_server['verbose'] = sprintf(__('Server %d'), $server_index);
1835 $new_servers[$server_index] = $each_server;
1837 $this->settings
['Servers'] = $new_servers;
1842 if (!defined('TESTSUITE')) {
1843 register_shutdown_function(array('PhpMyAdmin\Config', 'fatalErrorHandler'));