Update SQL parser to 4.2.3
[phpmyadmin.git] / libraries / Config.php
blob6280e562062fe72dcde4c36b8b443117baf995bf
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Configuration handling.
6 * @package PhpMyAdmin
7 */
8 namespace PMA\libraries;
10 use DirectoryIterator;
11 use PMA\libraries\URL;
12 use PMA\libraries\ThemeManager;
14 /**
15 * Indication for error handler (see end of this file).
17 $GLOBALS['pma_config_loading'] = false;
19 /**
20 * Configuration class
22 * @package PhpMyAdmin
24 class Config
26 /**
27 * @var string default config source
29 var $default_source = './libraries/config.default.php';
31 /**
32 * @var array default configuration settings
34 var $default = array();
36 /**
37 * @var array configuration settings, without user preferences applied
39 var $base_settings = array();
41 /**
42 * @var array configuration settings
44 var $settings = array();
46 /**
47 * @var string config source
49 var $source = '';
51 /**
52 * @var int source modification time
54 var $source_mtime = 0;
55 var $default_source_mtime = 0;
56 var $set_mtime = 0;
58 /**
59 * @var boolean
61 var $error_config_file = false;
63 /**
64 * @var boolean
66 var $error_config_default_file = false;
68 /**
69 * @var array
71 var $default_server = array();
73 /**
74 * @var boolean whether init is done or not
75 * set this to false to force some initial checks
76 * like checking for required functions
78 var $done = false;
80 /**
81 * constructor
83 * @param string $source source to read config from
85 public function __construct($source = null)
87 $this->settings = array();
89 // functions need to refresh in case of config file changed goes in
90 // PMA\libraries\Config::load()
91 $this->load($source);
93 // other settings, independent from config file, comes in
94 $this->checkSystem();
96 $this->base_settings = $this->settings;
99 /**
100 * sets system and application settings
102 * @return void
104 public function checkSystem()
106 $this->set('PMA_VERSION', '4.7.5-dev');
108 * @deprecated
110 $this->set('PMA_THEME_VERSION', 2);
112 * @deprecated
114 $this->set('PMA_THEME_GENERATION', 2);
116 $this->checkWebServerOs();
117 $this->checkWebServer();
118 $this->checkGd2();
119 $this->checkClient();
120 $this->checkUpload();
121 $this->checkUploadSize();
122 $this->checkOutputCompression();
126 * whether to use gzip output compression or not
128 * @return void
130 public function checkOutputCompression()
132 // If zlib output compression is set in the php configuration file, no
133 // output buffering should be run
134 if (@ini_get('zlib.output_compression')) {
135 $this->set('OBGzip', false);
138 // enable output-buffering (if set to 'auto')
139 if (strtolower($this->get('OBGzip')) == 'auto') {
140 $this->set('OBGzip', true);
145 * Sets the client platform based on user agent
147 * @param string $user_agent the user agent
149 * @return void
151 private function _setClientPlatform($user_agent)
153 if (mb_strstr($user_agent, 'Win')) {
154 $this->set('PMA_USR_OS', 'Win');
155 } elseif (mb_strstr($user_agent, 'Mac')) {
156 $this->set('PMA_USR_OS', 'Mac');
157 } elseif (mb_strstr($user_agent, 'Linux')) {
158 $this->set('PMA_USR_OS', 'Linux');
159 } elseif (mb_strstr($user_agent, 'Unix')) {
160 $this->set('PMA_USR_OS', 'Unix');
161 } elseif (mb_strstr($user_agent, 'OS/2')) {
162 $this->set('PMA_USR_OS', 'OS/2');
163 } else {
164 $this->set('PMA_USR_OS', 'Other');
169 * Determines platform (OS), browser and version of the user
170 * Based on a phpBuilder article:
172 * @see http://www.phpbuilder.net/columns/tim20000821.php
174 * @return void
176 public function checkClient()
178 if (PMA_getenv('HTTP_USER_AGENT')) {
179 $HTTP_USER_AGENT = PMA_getenv('HTTP_USER_AGENT');
180 } else {
181 $HTTP_USER_AGENT = '';
184 // 1. Platform
185 $this->_setClientPlatform($HTTP_USER_AGENT);
187 // 2. browser and version
188 // (must check everything else before Mozilla)
190 $is_mozilla = preg_match(
191 '@Mozilla/([0-9]\.[0-9]{1,2})@',
192 $HTTP_USER_AGENT,
193 $mozilla_version
196 if (preg_match(
197 '@Opera(/| )([0-9]\.[0-9]{1,2})@',
198 $HTTP_USER_AGENT,
199 $log_version
200 )) {
201 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
202 $this->set('PMA_USR_BROWSER_AGENT', 'OPERA');
203 } elseif (preg_match(
204 '@(MS)?IE ([0-9]{1,2}\.[0-9]{1,2})@',
205 $HTTP_USER_AGENT,
206 $log_version
207 )) {
208 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
209 $this->set('PMA_USR_BROWSER_AGENT', 'IE');
210 } elseif (preg_match(
211 '@Trident/(7)\.0@',
212 $HTTP_USER_AGENT,
213 $log_version
214 )) {
215 $this->set('PMA_USR_BROWSER_VER', intval($log_version[1]) + 4);
216 $this->set('PMA_USR_BROWSER_AGENT', 'IE');
217 } elseif (preg_match(
218 '@OmniWeb/([0-9]{1,3})@',
219 $HTTP_USER_AGENT,
220 $log_version
221 )) {
222 $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
223 $this->set('PMA_USR_BROWSER_AGENT', 'OMNIWEB');
224 // Konqueror 2.2.2 says Konqueror/2.2.2
225 // Konqueror 3.0.3 says Konqueror/3
226 } elseif (preg_match(
227 '@(Konqueror/)(.*)(;)@',
228 $HTTP_USER_AGENT,
229 $log_version
230 )) {
231 $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
232 $this->set('PMA_USR_BROWSER_AGENT', 'KONQUEROR');
233 // must check Chrome before Safari
234 } elseif ($is_mozilla
235 && preg_match('@Chrome/([0-9.]*)@', $HTTP_USER_AGENT, $log_version)
237 $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
238 $this->set('PMA_USR_BROWSER_AGENT', 'CHROME');
239 // newer Safari
240 } elseif ($is_mozilla
241 && preg_match('@Version/(.*) Safari@', $HTTP_USER_AGENT, $log_version)
243 $this->set(
244 'PMA_USR_BROWSER_VER', $log_version[1]
246 $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
247 // older Safari
248 } elseif ($is_mozilla
249 && preg_match('@Safari/([0-9]*)@', $HTTP_USER_AGENT, $log_version)
251 $this->set(
252 'PMA_USR_BROWSER_VER', $mozilla_version[1] . '.' . $log_version[1]
254 $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
255 // Firefox
256 } elseif (! mb_strstr($HTTP_USER_AGENT, 'compatible')
257 && preg_match('@Firefox/([\w.]+)@', $HTTP_USER_AGENT, $log_version)
259 $this->set(
260 'PMA_USR_BROWSER_VER', $log_version[1]
262 $this->set('PMA_USR_BROWSER_AGENT', 'FIREFOX');
263 } elseif (preg_match('@rv:1\.9(.*)Gecko@', $HTTP_USER_AGENT)) {
264 $this->set('PMA_USR_BROWSER_VER', '1.9');
265 $this->set('PMA_USR_BROWSER_AGENT', 'GECKO');
266 } elseif ($is_mozilla) {
267 $this->set('PMA_USR_BROWSER_VER', $mozilla_version[1]);
268 $this->set('PMA_USR_BROWSER_AGENT', 'MOZILLA');
269 } else {
270 $this->set('PMA_USR_BROWSER_VER', 0);
271 $this->set('PMA_USR_BROWSER_AGENT', 'OTHER');
276 * Whether GD2 is present
278 * @return void
280 public function checkGd2()
282 if ($this->get('GD2Available') == 'yes') {
283 $this->set('PMA_IS_GD2', 1);
284 return;
287 if ($this->get('GD2Available') == 'no') {
288 $this->set('PMA_IS_GD2', 0);
289 return;
292 if (!@function_exists('imagecreatetruecolor')) {
293 $this->set('PMA_IS_GD2', 0);
294 return;
297 if (@function_exists('gd_info')) {
298 $gd_nfo = gd_info();
299 if (mb_strstr($gd_nfo["GD Version"], '2.')) {
300 $this->set('PMA_IS_GD2', 1);
301 } else {
302 $this->set('PMA_IS_GD2', 0);
304 } else {
305 $this->set('PMA_IS_GD2', 0);
310 * Whether the Web server php is running on is IIS
312 * @return void
314 public function checkWebServer()
316 // some versions return Microsoft-IIS, some Microsoft/IIS
317 // we could use a preg_match() but it's slower
318 if (PMA_getenv('SERVER_SOFTWARE')
319 && stristr(PMA_getenv('SERVER_SOFTWARE'), 'Microsoft')
320 && stristr(PMA_getenv('SERVER_SOFTWARE'), 'IIS')
322 $this->set('PMA_IS_IIS', 1);
323 } else {
324 $this->set('PMA_IS_IIS', 0);
329 * Whether the os php is running on is windows or not
331 * @return void
333 public function checkWebServerOs()
335 // Default to Unix or Equiv
336 $this->set('PMA_IS_WINDOWS', 0);
337 // If PHP_OS is defined then continue
338 if (defined('PHP_OS')) {
339 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
340 // Is it some version of Windows
341 $this->set('PMA_IS_WINDOWS', 1);
342 } elseif (stristr(PHP_OS, 'OS/2')) {
343 // Is it OS/2 (No file permissions like Windows)
344 $this->set('PMA_IS_WINDOWS', 1);
350 * detects if Git revision
352 * @return boolean
354 public function isGitRevision()
356 if (!$this->get('ShowGitRevision')) {
357 return false;
360 // caching
361 if (isset($_SESSION['is_git_revision'])) {
362 if ($_SESSION['is_git_revision']) {
363 $this->set('PMA_VERSION_GIT', 1);
365 return $_SESSION['is_git_revision'];
367 // find out if there is a .git folder
368 $git_folder = '.git';
369 if (! @file_exists($git_folder)
370 || ! @file_exists($git_folder . '/config')
372 $_SESSION['is_git_revision'] = false;
373 return false;
375 $_SESSION['is_git_revision'] = true;
376 return true;
380 * detects Git revision, if running inside repo
382 * @return void
384 public function checkGitRevision()
386 // find out if there is a .git folder
387 $git_folder = '.git';
388 if (! $this->isGitRevision()) {
389 return;
392 if (! $ref_head = @file_get_contents($git_folder . '/HEAD')) {
393 return;
396 $branch = false;
397 // are we on any branch?
398 if (strstr($ref_head, '/')) {
399 // remove ref: prefix
400 $ref_head = substr(trim($ref_head), 5);
401 if (substr($ref_head, 0, 11) === 'refs/heads/') {
402 $branch = substr($ref_head, 11);
403 } else {
404 $branch = basename($ref_head);
407 $ref_file = $git_folder . '/' . $ref_head;
408 if (@file_exists($ref_file)) {
409 $hash = @file_get_contents($ref_file);
410 if (! $hash) {
411 return;
413 $hash = trim($hash);
414 } else {
415 // deal with packed refs
416 $packed_refs = @file_get_contents($git_folder . '/packed-refs');
417 if (! $packed_refs) {
418 return;
420 // split file to lines
421 $ref_lines = explode("\n", $packed_refs);
422 foreach ($ref_lines as $line) {
423 // skip comments
424 if ($line[0] == '#') {
425 continue;
427 // parse line
428 $parts = explode(' ', $line);
429 // care only about named refs
430 if (count($parts) != 2) {
431 continue;
433 // have found our ref?
434 if ($parts[1] == $ref_head) {
435 $hash = $parts[0];
436 break;
439 if (! isset($hash)) {
440 // Could not find ref
441 return;
444 } else {
445 $hash = trim($ref_head);
448 $commit = false;
449 if (! preg_match('/^[0-9a-f]{40}$/i', $hash)) {
450 $commit = false;
451 } elseif (isset($_SESSION['PMA_VERSION_COMMITDATA_' . $hash])) {
452 $commit = $_SESSION['PMA_VERSION_COMMITDATA_' . $hash];
453 } elseif (function_exists('gzuncompress')) {
454 $git_file_name = $git_folder . '/objects/'
455 . substr($hash, 0, 2) . '/' . substr($hash, 2);
456 if (@file_exists($git_file_name) ) {
457 if (! $commit = @file_get_contents($git_file_name)) {
458 return;
460 $commit = explode("\0", gzuncompress($commit), 2);
461 $commit = explode("\n", $commit[1]);
462 $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
463 } else {
464 $pack_names = array();
465 // work with packed data
466 $packs_file = $git_folder . '/objects/info/packs';
467 if (@file_exists($packs_file)
468 && $packs = @file_get_contents($packs_file)
470 // File exists. Read it, parse the file to get the names of the
471 // packs. (to look for them in .git/object/pack directory later)
472 foreach (explode("\n", $packs) as $line) {
473 // skip blank lines
474 if (strlen(trim($line)) == 0) {
475 continue;
477 // skip non pack lines
478 if ($line[0] != 'P') {
479 continue;
481 // parse names
482 $pack_names[] = substr($line, 2);
484 } else {
485 // '.git/objects/info/packs' file can be missing
486 // (atlease in mysGit)
487 // File missing. May be we can look in the .git/object/pack
488 // directory for all the .pack files and use that list of
489 // files instead
490 $dirIterator = new DirectoryIterator(
491 $git_folder . '/objects/pack'
493 foreach ($dirIterator as $file_info) {
494 $file_name = $file_info->getFilename();
495 // if this is a .pack file
496 if ($file_info->isFile() && substr($file_name, -5) == '.pack'
498 $pack_names[] = $file_name;
502 $hash = strtolower($hash);
503 foreach ($pack_names as $pack_name) {
504 $index_name = str_replace('.pack', '.idx', $pack_name);
506 // load index
507 $index_data = @file_get_contents(
508 $git_folder . '/objects/pack/' . $index_name
510 if (! $index_data) {
511 continue;
513 // check format
514 if (substr($index_data, 0, 4) != "\377tOc") {
515 continue;
517 // check version
518 $version = unpack('N', substr($index_data, 4, 4));
519 if ($version[1] != 2) {
520 continue;
522 // parse fanout table
523 $fanout = unpack(
524 "N*",
525 substr($index_data, 8, 256 * 4)
528 // find where we should search
529 $firstbyte = intval(substr($hash, 0, 2), 16);
530 // array is indexed from 1 and we need to get
531 // previous entry for start
532 if ($firstbyte == 0) {
533 $start = 0;
534 } else {
535 $start = $fanout[$firstbyte];
537 $end = $fanout[$firstbyte + 1];
539 // stupid linear search for our sha
540 $found = false;
541 $offset = 8 + (256 * 4);
542 for ($position = $start; $position < $end; $position++) {
543 $sha = strtolower(
544 bin2hex(
545 substr($index_data, $offset + ($position * 20), 20)
548 if ($sha == $hash) {
549 $found = true;
550 break;
553 if (! $found) {
554 continue;
556 // read pack offset
557 $offset = 8 + (256 * 4) + (24 * $fanout[256]);
558 $pack_offset = unpack(
559 'N',
560 substr($index_data, $offset + ($position * 4), 4)
562 $pack_offset = $pack_offset[1];
564 // open pack file
565 $pack_file = fopen(
566 $git_folder . '/objects/pack/' . $pack_name, 'rb'
568 if ($pack_file === false) {
569 continue;
571 // seek to start
572 fseek($pack_file, $pack_offset);
574 // parse header
575 $header = ord(fread($pack_file, 1));
576 $type = ($header >> 4) & 7;
577 $hasnext = ($header & 128) >> 7;
578 $size = $header & 0xf;
579 $offset = 4;
581 while ($hasnext) {
582 $byte = ord(fread($pack_file, 1));
583 $size |= ($byte & 0x7f) << $offset;
584 $hasnext = ($byte & 128) >> 7;
585 $offset += 7;
588 // we care only about commit objects
589 if ($type != 1) {
590 continue;
593 // read data
594 $commit = fread($pack_file, $size);
595 $commit = gzuncompress($commit);
596 $commit = explode("\n", $commit);
597 $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
598 fclose($pack_file);
603 // check if commit exists in Github
604 if ($commit !== false
605 && isset($_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash])
607 $is_remote_commit = $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash];
608 } else {
609 $link = 'https://www.phpmyadmin.net/api/commit/' . $hash . '/';
610 $is_found = Util::httpRequest($link, "GET");
611 switch($is_found) {
612 case false:
613 $is_remote_commit = false;
614 $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = false;
615 break;
616 case null:
617 // no remote link for now, but don't cache this as Github is down
618 $is_remote_commit = false;
619 break;
620 default:
621 $is_remote_commit = true;
622 $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = true;
623 if ($commit === false) {
624 // if no local commit data, try loading from Github
625 $commit_json = json_decode($is_found);
627 break;
631 $is_remote_branch = false;
632 if ($is_remote_commit && $branch !== false) {
633 // check if branch exists in Github
634 if (isset($_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash])) {
635 $is_remote_branch = $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash];
636 } else {
637 $link = 'https://www.phpmyadmin.net/api/tree/' . $branch . '/';
638 $is_found = Util::httpRequest($link, "GET", true);
639 switch($is_found) {
640 case true:
641 $is_remote_branch = true;
642 $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = true;
643 break;
644 case false:
645 $is_remote_branch = false;
646 $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = false;
647 break;
648 case null:
649 // no remote link for now, but don't cache this as Github is down
650 $is_remote_branch = false;
651 break;
656 if ($commit !== false) {
657 $author = array('name' => '', 'email' => '', 'date' => '');
658 $committer = array('name' => '', 'email' => '', 'date' => '');
660 do {
661 $dataline = array_shift($commit);
662 $datalinearr = explode(' ', $dataline, 2);
663 $linetype = $datalinearr[0];
664 if (in_array($linetype, array('author', 'committer'))) {
665 $user = $datalinearr[1];
666 preg_match('/([^<]+)<([^>]+)> ([0-9]+)( [^ ]+)?/', $user, $user);
667 $user2 = array(
668 'name' => trim($user[1]),
669 'email' => trim($user[2]),
670 'date' => date('Y-m-d H:i:s', $user[3]));
671 if (isset($user[4])) {
672 $user2['date'] .= $user[4];
674 $$linetype = $user2;
676 } while ($dataline != '');
677 $message = trim(implode(' ', $commit));
679 } elseif (isset($commit_json) && isset($commit_json->author) && isset($commit_json->committer)) {
680 $author = array(
681 'name' => $commit_json->author->name,
682 'email' => $commit_json->author->email,
683 'date' => $commit_json->author->date);
684 $committer = array(
685 'name' => $commit_json->committer->name,
686 'email' => $commit_json->committer->email,
687 'date' => $commit_json->committer->date);
688 $message = trim($commit_json->message);
689 } else {
690 return;
693 $this->set('PMA_VERSION_GIT', 1);
694 $this->set('PMA_VERSION_GIT_COMMITHASH', $hash);
695 $this->set('PMA_VERSION_GIT_BRANCH', $branch);
696 $this->set('PMA_VERSION_GIT_MESSAGE', $message);
697 $this->set('PMA_VERSION_GIT_AUTHOR', $author);
698 $this->set('PMA_VERSION_GIT_COMMITTER', $committer);
699 $this->set('PMA_VERSION_GIT_ISREMOTECOMMIT', $is_remote_commit);
700 $this->set('PMA_VERSION_GIT_ISREMOTEBRANCH', $is_remote_branch);
704 * loads default values from default source
706 * @return boolean success
708 public function loadDefaults()
710 $cfg = array();
711 if (! @file_exists($this->default_source)) {
712 $this->error_config_default_file = true;
713 return false;
715 $old_error_reporting = error_reporting(0);
716 ob_start();
717 $GLOBALS['pma_config_loading'] = true;
718 $eval_result = include $this->default_source;
719 $GLOBALS['pma_config_loading'] = false;
720 ob_end_clean();
721 error_reporting($old_error_reporting);
723 if ($eval_result === false) {
724 $this->error_config_default_file = true;
725 return false;
728 $this->default_source_mtime = filemtime($this->default_source);
730 $this->default_server = $cfg['Servers'][1];
731 unset($cfg['Servers']);
733 $this->default = $cfg;
734 $this->settings = array_replace_recursive($this->settings, $cfg);
736 $this->error_config_default_file = false;
738 return true;
742 * loads configuration from $source, usually the config file
743 * should be called on object creation
745 * @param string $source config file
747 * @return bool
749 public function load($source = null)
751 $this->loadDefaults();
753 if (null !== $source) {
754 $this->setSource($source);
758 * We check and set the font size at this point, to make the font size
759 * selector work also for users without a config.inc.php
761 $this->checkFontsize();
763 if (! $this->checkConfigSource()) {
764 // even if no config file, set collation_connection
765 $this->checkCollationConnection();
766 return false;
769 $cfg = array();
772 * Parses the configuration file, we throw away any errors or
773 * output.
775 $old_error_reporting = error_reporting(0);
776 ob_start();
777 $GLOBALS['pma_config_loading'] = true;
778 $eval_result = include $this->getSource();
779 $GLOBALS['pma_config_loading'] = false;
780 ob_end_clean();
781 error_reporting($old_error_reporting);
783 if ($eval_result === false) {
784 $this->error_config_file = true;
785 } else {
786 $this->error_config_file = false;
787 $this->source_mtime = filemtime($this->getSource());
791 * Ignore keys with / as we do not use these
793 * These can be confusing for user configuration layer as it
794 * flatten array using / and thus don't see difference between
795 * $cfg['Export/method'] and $cfg['Export']['method'], while rest
796 * of thre code uses the setting only in latter form.
798 * This could be removed once we consistently handle both values
799 * in the functional code as well.
801 * It could use array_filter(...ARRAY_FILTER_USE_KEY), but it's not
802 * supported on PHP 5.5 and HHVM.
804 $matched_keys = array_filter(
805 array_keys($cfg),
806 function ($key) {return strpos($key, '/') === false;}
809 $cfg = array_intersect_key($cfg, array_flip($matched_keys));
812 * Backward compatibility code
814 if (!empty($cfg['DefaultTabTable'])) {
815 $cfg['DefaultTabTable'] = str_replace(
816 '_properties',
818 str_replace(
819 'tbl_properties.php',
820 'tbl_sql.php',
821 $cfg['DefaultTabTable']
825 if (!empty($cfg['DefaultTabDatabase'])) {
826 $cfg['DefaultTabDatabase'] = str_replace(
827 '_details',
829 str_replace(
830 'db_details.php',
831 'db_sql.php',
832 $cfg['DefaultTabDatabase']
837 $this->settings = array_replace_recursive($this->settings, $cfg);
839 // Handling of the collation must be done after merging of $cfg
840 // (from config.inc.php) so that $cfg['DefaultConnectionCollation']
841 // can have an effect.
842 $this->checkCollationConnection();
844 return true;
848 * Saves the connection collation
850 * @param array $config_data configuration data from user preferences
852 * @return void
854 private function _saveConnectionCollation($config_data)
856 // just to shorten the lines
857 $collation = 'collation_connection';
858 if (isset($GLOBALS[$collation])
859 && (isset($_COOKIE['pma_collation_connection'])
860 || isset($_POST[$collation]))
862 if ((! isset($config_data[$collation])
863 && $GLOBALS[$collation] != 'utf8_general_ci')
864 || isset($config_data[$collation])
865 && $GLOBALS[$collation] != $config_data[$collation]
867 $this->setUserValue(
868 null,
869 $collation,
870 $GLOBALS[$collation],
871 'utf8_general_ci'
874 } else {
875 // read collation from settings
876 if (isset($config_data[$collation])) {
877 $GLOBALS[$collation]
878 = $config_data[$collation];
879 $this->setCookie(
880 'pma_collation_connection',
881 $GLOBALS[$collation]
888 * Loads user preferences and merges them with current config
889 * must be called after control connection has been established
891 * @return void
893 public function loadUserPreferences()
895 // index.php should load these settings, so that phpmyadmin.css.php
896 // will have everything available in session cache
897 $server = isset($GLOBALS['server'])
898 ? $GLOBALS['server']
899 : (!empty($GLOBALS['cfg']['ServerDefault'])
900 ? $GLOBALS['cfg']['ServerDefault']
901 : 0);
902 $cache_key = 'server_' . $server;
903 if ($server > 0 && !defined('PMA_MINIMUM_COMMON')) {
904 $config_mtime = max($this->default_source_mtime, $this->source_mtime);
905 // cache user preferences, use database only when needed
906 if (! isset($_SESSION['cache'][$cache_key]['userprefs'])
907 || $_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime
909 // load required libraries
910 include_once './libraries/user_preferences.lib.php';
911 $prefs = PMA_loadUserprefs();
912 $_SESSION['cache'][$cache_key]['userprefs']
913 = PMA_applyUserprefs($prefs['config_data']);
914 $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime'];
915 $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type'];
916 $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime;
918 } elseif ($server == 0
919 || ! isset($_SESSION['cache'][$cache_key]['userprefs'])
921 $this->set('user_preferences', false);
922 return;
924 $config_data = $_SESSION['cache'][$cache_key]['userprefs'];
925 // type is 'db' or 'session'
926 $this->set(
927 'user_preferences',
928 $_SESSION['cache'][$cache_key]['userprefs_type']
930 $this->set(
931 'user_preferences_mtime',
932 $_SESSION['cache'][$cache_key]['userprefs_mtime']
935 // backup some settings
936 $org_fontsize = '';
937 if (isset($this->settings['fontsize'])) {
938 $org_fontsize = $this->settings['fontsize'];
940 // load config array
941 $this->settings = array_replace_recursive($this->settings, $config_data);
942 $GLOBALS['cfg'] = array_replace_recursive($GLOBALS['cfg'], $config_data);
943 if (defined('PMA_MINIMUM_COMMON')) {
944 return;
947 // settings below start really working on next page load, but
948 // changes are made only in index.php so everything is set when
949 // in frames
951 // save theme
952 /** @var ThemeManager $tmanager */
953 $tmanager = ThemeManager::getInstance();
954 if ($tmanager->getThemeCookie() || isset($_REQUEST['set_theme'])) {
955 if ((! isset($config_data['ThemeDefault'])
956 && $tmanager->theme->getId() != 'original')
957 || isset($config_data['ThemeDefault'])
958 && $config_data['ThemeDefault'] != $tmanager->theme->getId()
960 // new theme was set in common.inc.php
961 $this->setUserValue(
962 null,
963 'ThemeDefault',
964 $tmanager->theme->getId(),
965 'original'
968 } else {
969 // no cookie - read default from settings
970 if ($this->settings['ThemeDefault'] != $tmanager->theme->getId()
971 && $tmanager->checkTheme($this->settings['ThemeDefault'])
973 $tmanager->setActiveTheme($this->settings['ThemeDefault']);
974 $tmanager->setThemeCookie();
978 // save font size
979 if ((! isset($config_data['fontsize'])
980 && $org_fontsize != '82%')
981 || isset($config_data['fontsize'])
982 && $org_fontsize != $config_data['fontsize']
984 $this->setUserValue(null, 'fontsize', $org_fontsize, '82%');
987 // save language
988 if (isset($_COOKIE['pma_lang']) || isset($_POST['lang'])) {
989 if ((! isset($config_data['lang'])
990 && $GLOBALS['lang'] != 'en')
991 || isset($config_data['lang'])
992 && $GLOBALS['lang'] != $config_data['lang']
994 $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en');
996 } else {
997 // read language from settings
998 if (isset($config_data['lang'])) {
999 $language = LanguageManager::getInstance()->getLanguage(
1000 $config_data['lang']
1002 if ($language !== false) {
1003 $language->activate();
1004 $this->setCookie('pma_lang', $language->getCode());
1009 // save connection collation
1010 $this->_saveConnectionCollation($config_data);
1014 * Sets config value which is stored in user preferences (if available)
1015 * or in a cookie.
1017 * If user preferences are not yet initialized, option is applied to
1018 * global config and added to a update queue, which is processed
1019 * by {@link loadUserPreferences()}
1021 * @param string $cookie_name can be null
1022 * @param string $cfg_path configuration path
1023 * @param mixed $new_cfg_value new value
1024 * @param mixed $default_value default value
1026 * @return void
1028 public function setUserValue($cookie_name, $cfg_path, $new_cfg_value,
1029 $default_value = null
1031 // use permanent user preferences if possible
1032 $prefs_type = $this->get('user_preferences');
1033 if ($prefs_type) {
1034 include_once './libraries/user_preferences.lib.php';
1035 if ($default_value === null) {
1036 $default_value = PMA_arrayRead($cfg_path, $this->default);
1038 PMA_persistOption($cfg_path, $new_cfg_value, $default_value);
1040 if ($prefs_type != 'db' && $cookie_name) {
1041 // fall back to cookies
1042 if ($default_value === null) {
1043 $default_value = PMA_arrayRead($cfg_path, $this->settings);
1045 $this->setCookie($cookie_name, $new_cfg_value, $default_value);
1047 PMA_arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value);
1048 PMA_arrayWrite($cfg_path, $this->settings, $new_cfg_value);
1052 * Reads value stored by {@link setUserValue()}
1054 * @param string $cookie_name cookie name
1055 * @param mixed $cfg_value config value
1057 * @return mixed
1059 public function getUserValue($cookie_name, $cfg_value)
1061 $cookie_exists = isset($_COOKIE) && !empty($_COOKIE[$cookie_name]);
1062 $prefs_type = $this->get('user_preferences');
1063 if ($prefs_type == 'db') {
1064 // permanent user preferences value exists, remove cookie
1065 if ($cookie_exists) {
1066 $this->removeCookie($cookie_name);
1068 } else if ($cookie_exists) {
1069 return $_COOKIE[$cookie_name];
1071 // return value from $cfg array
1072 return $cfg_value;
1076 * set source
1078 * @param string $source source
1080 * @return void
1082 public function setSource($source)
1084 $this->source = trim($source);
1088 * check config source
1090 * @return boolean whether source is valid or not
1092 public function checkConfigSource()
1094 if (! $this->getSource()) {
1095 // no configuration file set at all
1096 return false;
1099 if (! @file_exists($this->getSource())) {
1100 $this->source_mtime = 0;
1101 return false;
1104 if (! @is_readable($this->getSource())) {
1105 // manually check if file is readable
1106 // might be bug #3059806 Supporting running from CIFS/Samba shares
1108 $contents = false;
1109 $handle = @fopen($this->getSource(), 'r');
1110 if ($handle !== false) {
1111 $contents = @fread($handle, 1); // reading 1 byte is enough to test
1112 fclose($handle);
1114 if ($contents === false) {
1115 $this->source_mtime = 0;
1116 PMA_fatalError(
1117 sprintf(
1118 function_exists('__')
1119 ? __('Existing configuration file (%s) is not readable.')
1120 : 'Existing configuration file (%s) is not readable.',
1121 $this->getSource()
1124 return false;
1128 return true;
1132 * verifies the permissions on config file (if asked by configuration)
1133 * (must be called after config.inc.php has been merged)
1135 * @return void
1137 public function checkPermissions()
1139 // Check for permissions (on platforms that support it):
1140 if ($this->get('CheckConfigurationPermissions') && @file_exists($this->getSource())) {
1141 $perms = @fileperms($this->getSource());
1142 if (!($perms === false) && ($perms & 2)) {
1143 // This check is normally done after loading configuration
1144 $this->checkWebServerOs();
1145 if ($this->get('PMA_IS_WINDOWS') == 0) {
1146 $this->source_mtime = 0;
1147 PMA_fatalError(
1149 'Wrong permissions on configuration file, '
1150 . 'should not be world writable!'
1159 * Checks for errors
1160 * (must be called after config.inc.php has been merged)
1162 * @return void
1164 public function checkErrors()
1166 if ($this->error_config_default_file) {
1167 PMA_fatalError(
1168 sprintf(
1169 __('Could not load default configuration from: %1$s'),
1170 $this->default_source
1175 if ($this->error_config_file) {
1176 $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
1177 . '[br][br]'
1178 . __(
1179 'This usually means there is a syntax error in it, '
1180 . 'please check any errors shown below.'
1182 . '[br][br]'
1183 . '[conferr]';
1184 trigger_error($error, E_USER_ERROR);
1189 * returns specific config setting
1191 * @param string $setting config setting
1193 * @return mixed value
1195 public function get($setting)
1197 if (isset($this->settings[$setting])) {
1198 return $this->settings[$setting];
1200 return null;
1204 * sets configuration variable
1206 * @param string $setting configuration option
1207 * @param mixed $value new value for configuration option
1209 * @return void
1211 public function set($setting, $value)
1213 if (! isset($this->settings[$setting])
1214 || $this->settings[$setting] !== $value
1216 $this->settings[$setting] = $value;
1217 $this->set_mtime = time();
1222 * returns source for current config
1224 * @return string config source
1226 public function getSource()
1228 return $this->source;
1232 * returns a unique value to force a CSS reload if either the config
1233 * or the theme changes
1234 * must also check the pma_fontsize cookie in case there is no
1235 * config file
1237 * @return int Summary of unix timestamps and fontsize,
1238 * to be unique on theme parameters change
1240 public function getThemeUniqueValue()
1242 if (null !== $this->get('fontsize')) {
1243 $fontsize = intval($this->get('fontsize'));
1244 } elseif (isset($_COOKIE['pma_fontsize'])) {
1245 $fontsize = intval($_COOKIE['pma_fontsize']);
1246 } else {
1247 $fontsize = 0;
1249 return (
1250 $fontsize +
1251 $this->source_mtime +
1252 $this->default_source_mtime +
1253 $this->get('user_preferences_mtime') +
1254 $_SESSION['PMA_Theme']->mtime_info +
1255 $_SESSION['PMA_Theme']->filesize_info);
1259 * Sets collation_connection based on user preference. First is checked
1260 * value from request, then cookies with fallback to default.
1262 * After setting it here, cookie is set in common.inc.php to persist
1263 * the selection.
1265 * @todo check validity of collation string
1267 * @return void
1269 public function checkCollationConnection()
1271 if (! empty($_REQUEST['collation_connection'])) {
1272 $collation = htmlspecialchars(
1273 strip_tags($_REQUEST['collation_connection'])
1275 } elseif (! empty($_COOKIE['pma_collation_connection'])) {
1276 $collation = htmlspecialchars(
1277 strip_tags($_COOKIE['pma_collation_connection'])
1279 } else {
1280 $collation = $this->get('DefaultConnectionCollation');
1282 $this->set('collation_connection', $collation);
1286 * checks for font size configuration, and sets font size as requested by user
1288 * @return void
1290 public function checkFontsize()
1292 $new_fontsize = '';
1294 if (isset($_GET['set_fontsize'])) {
1295 $new_fontsize = $_GET['set_fontsize'];
1296 } elseif (isset($_POST['set_fontsize'])) {
1297 $new_fontsize = $_POST['set_fontsize'];
1298 } elseif (isset($_COOKIE['pma_fontsize'])) {
1299 $new_fontsize = $_COOKIE['pma_fontsize'];
1302 if (preg_match('/^[0-9.]+(px|em|pt|\%)$/', $new_fontsize)) {
1303 $this->set('fontsize', $new_fontsize);
1304 } elseif (! $this->get('fontsize')) {
1305 // 80% would correspond to the default browser font size
1306 // of 16, but use 82% to help read the monoface font
1307 $this->set('fontsize', '82%');
1310 $this->setCookie('pma_fontsize', $this->get('fontsize'), '82%');
1314 * checks if upload is enabled
1316 * @return void
1318 public function checkUpload()
1320 if (!ini_get('file_uploads')) {
1321 $this->set('enable_upload', false);
1322 return;
1325 $this->set('enable_upload', true);
1326 // if set "php_admin_value file_uploads Off" in httpd.conf
1327 // ini_get() also returns the string "Off" in this case:
1328 if ('off' == strtolower(ini_get('file_uploads'))) {
1329 $this->set('enable_upload', false);
1334 * Maximum upload size as limited by PHP
1335 * Used with permission from Moodle (https://moodle.org/) by Martin Dougiamas
1337 * this section generates $max_upload_size in bytes
1339 * @return void
1341 public function checkUploadSize()
1343 if (! $filesize = ini_get('upload_max_filesize')) {
1344 $filesize = "5M";
1347 if ($postsize = ini_get('post_max_size')) {
1348 $this->set(
1349 'max_upload_size',
1350 min(PMA_getRealSize($filesize), PMA_getRealSize($postsize))
1352 } else {
1353 $this->set('max_upload_size', PMA_getRealSize($filesize));
1358 * Checks if protocol is https
1360 * This function checks if the https protocol on the active connection.
1362 * @return bool
1364 public function isHttps()
1367 if (null !== $this->get('is_https')) {
1368 return $this->get('is_https');
1371 $url = $this->get('PmaAbsoluteUri');
1373 $is_https = false;
1374 if (! empty($url) && parse_url($url, PHP_URL_SCHEME) === 'https') {
1375 $is_https = true;
1376 } elseif (strtolower(PMA_getenv('HTTP_SCHEME')) == 'https') {
1377 $is_https = true;
1378 } elseif (strtolower(PMA_getenv('HTTPS')) == 'on') {
1379 $is_https = true;
1380 } elseif (substr(strtolower(PMA_getenv('REQUEST_URI')), 0, 6) == 'https:') {
1381 $is_https = true;
1382 } elseif (strtolower(PMA_getenv('HTTP_HTTPS_FROM_LB')) == 'on') {
1383 // A10 Networks load balancer
1384 $is_https = true;
1385 } elseif (strtolower(PMA_getenv('HTTP_FRONT_END_HTTPS')) == 'on') {
1386 $is_https = true;
1387 } elseif (strtolower(PMA_getenv('HTTP_X_FORWARDED_PROTO')) == 'https') {
1388 $is_https = true;
1389 } elseif (PMA_getenv('SERVER_PORT') == 443) {
1390 $is_https = true;
1393 $this->set('is_https', $is_https);
1395 return $is_https;
1399 * Get phpMyAdmin root path
1401 * @return string
1403 public function getRootPath()
1405 static $cookie_path = null;
1407 if (null !== $cookie_path && !defined('TESTSUITE')) {
1408 return $cookie_path;
1411 $url = $this->get('PmaAbsoluteUri');
1413 if (! empty($url)) {
1414 $path = parse_url($url, PHP_URL_PATH);
1415 if (! empty($path)) {
1416 if (substr($path, -1) != '/') {
1417 return $path . '/';
1419 return $path;
1423 $parsed_url = parse_url($GLOBALS['PMA_PHP_SELF']);
1425 $parts = explode(
1426 '/',
1427 rtrim(str_replace('\\', '/', $parsed_url['path']), '/')
1430 /* Remove filename */
1431 if (substr($parts[count($parts) - 1], -4) == '.php') {
1432 $parts = array_slice($parts, 0, count($parts) - 1);
1435 /* Remove extra path from javascript calls */
1436 if (defined('PMA_PATH_TO_BASEDIR')) {
1437 $parts = array_slice($parts, 0, count($parts) - 1);
1440 $parts[] = '';
1442 return implode('/', $parts);
1446 * enables backward compatibility
1448 * @return void
1450 public function enableBc()
1452 $GLOBALS['cfg'] = $this->settings;
1453 $GLOBALS['default_server'] = $this->default_server;
1454 unset($this->default_server);
1455 $GLOBALS['collation_connection'] = $this->get('collation_connection');
1456 $GLOBALS['is_upload'] = $this->get('enable_upload');
1457 $GLOBALS['max_upload_size'] = $this->get('max_upload_size');
1458 $GLOBALS['is_https'] = $this->get('is_https');
1460 $defines = array(
1461 'PMA_VERSION',
1462 'PMA_THEME_VERSION',
1463 'PMA_THEME_GENERATION',
1464 'PMA_IS_WINDOWS',
1465 'PMA_IS_GD2',
1466 'PMA_USR_OS',
1467 'PMA_USR_BROWSER_VER',
1468 'PMA_USR_BROWSER_AGENT'
1471 foreach ($defines as $define) {
1472 if (! defined($define)) {
1473 define($define, $this->get($define));
1479 * returns options for font size selection
1481 * @param string $current_size current selected font size with unit
1483 * @return array selectable font sizes
1485 protected static function getFontsizeOptions($current_size = '82%')
1487 $unit = preg_replace('/[0-9.]*/', '', $current_size);
1488 $value = preg_replace('/[^0-9.]*/', '', $current_size);
1490 $factors = array();
1491 $options = array();
1492 $options["$value"] = $value . $unit;
1494 if ($unit === '%') {
1495 $factors[] = 1;
1496 $factors[] = 5;
1497 $factors[] = 10;
1498 $options['100'] = '100%';
1499 } elseif ($unit === 'em') {
1500 $factors[] = 0.05;
1501 $factors[] = 0.2;
1502 $factors[] = 1;
1503 } elseif ($unit === 'pt') {
1504 $factors[] = 0.5;
1505 $factors[] = 2;
1506 } elseif ($unit === 'px') {
1507 $factors[] = 1;
1508 $factors[] = 5;
1509 $factors[] = 10;
1510 } else {
1511 //unknown font size unit
1512 $factors[] = 0.05;
1513 $factors[] = 0.2;
1514 $factors[] = 1;
1515 $factors[] = 5;
1516 $factors[] = 10;
1519 foreach ($factors as $key => $factor) {
1520 $option_inc = $value + $factor;
1521 $option_dec = $value - $factor;
1522 while (count($options) < 21) {
1523 $options["$option_inc"] = $option_inc . $unit;
1524 if ($option_dec > $factors[0]) {
1525 $options["$option_dec"] = $option_dec . $unit;
1527 $option_inc += $factor;
1528 $option_dec -= $factor;
1529 if (isset($factors[$key + 1])
1530 && $option_inc >= $value + $factors[$key + 1]
1532 break;
1536 ksort($options);
1537 return $options;
1541 * returns html selectbox for font sizes
1543 * @return string html selectbox
1545 protected static function getFontsizeSelection()
1547 $current_size = $GLOBALS['PMA_Config']->get('fontsize');
1548 // for the case when there is no config file (this is supported)
1549 if (empty($current_size)) {
1550 if (isset($_COOKIE['pma_fontsize'])) {
1551 $current_size = htmlspecialchars($_COOKIE['pma_fontsize']);
1552 } else {
1553 $current_size = '82%';
1556 $options = Config::getFontsizeOptions($current_size);
1558 $return = '<label for="select_fontsize">' . __('Font size')
1559 . ':</label>' . "\n"
1560 . '<select name="set_fontsize" id="select_fontsize"'
1561 . ' class="autosubmit">' . "\n";
1562 foreach ($options as $option) {
1563 $return .= '<option value="' . $option . '"';
1564 if ($option == $current_size) {
1565 $return .= ' selected="selected"';
1567 $return .= '>' . $option . '</option>' . "\n";
1569 $return .= '</select>';
1571 return $return;
1575 * return complete font size selection form
1577 * @return string html selectbox
1579 public static function getFontsizeForm()
1581 return '<form name="form_fontsize_selection" id="form_fontsize_selection"'
1582 . ' method="get" action="index.php" class="disableAjax">' . "\n"
1583 . URL::getHiddenInputs() . "\n"
1584 . Config::getFontsizeSelection() . "\n"
1585 . '</form>';
1589 * removes cookie
1591 * @param string $cookie name of cookie to remove
1593 * @return boolean result of setcookie()
1595 public function removeCookie($cookie)
1597 if (defined('TESTSUITE')) {
1598 if (isset($_COOKIE[$cookie])) {
1599 unset($_COOKIE[$cookie]);
1601 return true;
1603 return setcookie(
1604 $cookie,
1606 time() - 3600,
1607 $this->getRootPath(),
1609 $this->isHttps()
1614 * sets cookie if value is different from current cookie value,
1615 * or removes if value is equal to default
1617 * @param string $cookie name of cookie to remove
1618 * @param mixed $value new cookie value
1619 * @param string $default default value
1620 * @param int $validity validity of cookie in seconds (default is one month)
1621 * @param bool $httponly whether cookie is only for HTTP (and not for scripts)
1623 * @return boolean result of setcookie()
1625 public function setCookie($cookie, $value, $default = null,
1626 $validity = null, $httponly = true
1628 if (strlen($value) > 0 && null !== $default && $value === $default
1630 // default value is used
1631 if (isset($_COOKIE[$cookie])) {
1632 // remove cookie
1633 return $this->removeCookie($cookie);
1635 return false;
1638 if (strlen($value) === 0 && isset($_COOKIE[$cookie])) {
1639 // remove cookie, value is empty
1640 return $this->removeCookie($cookie);
1643 if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) {
1644 // set cookie with new value
1645 /* Calculate cookie validity */
1646 if ($validity === null) {
1647 /* Valid for one month */
1648 $validity = time() + 2592000;
1649 } elseif ($validity == 0) {
1650 /* Valid for session */
1651 $validity = 0;
1652 } else {
1653 $validity = time() + $validity;
1655 if (defined('TESTSUITE')) {
1656 $_COOKIE[$cookie] = $value;
1657 return true;
1659 return setcookie(
1660 $cookie,
1661 $value,
1662 $validity,
1663 $this->getRootPath(),
1665 $this->isHttps(),
1666 $httponly
1670 // cookie has already $value as value
1671 return true;
1676 * Error handler to catch fatal errors when loading configuration
1677 * file
1680 * PMA_Config_fatalErrorHandler
1681 * @return void
1683 public static function fatalErrorHandler()
1685 if (!isset($GLOBALS['pma_config_loading'])
1686 || !$GLOBALS['pma_config_loading']
1688 return;
1691 $error = error_get_last();
1692 if ($error === null) {
1693 return;
1696 PMA_fatalError(
1697 sprintf(
1698 'Failed to load phpMyAdmin configuration (%s:%s): %s',
1699 Error::relPath($error['file']),
1700 $error['line'],
1701 $error['message']
1707 * Wrapper for footer/header rendering
1709 * @param string $filename File to check and render
1710 * @param string $id Div ID
1712 * @return string
1714 private static function _renderCustom($filename, $id)
1716 $retval = '';
1717 if (@file_exists($filename)) {
1718 $retval .= '<div id="' . $id . '">';
1719 ob_start();
1720 include $filename;
1721 $retval .= ob_get_contents();
1722 ob_end_clean();
1723 $retval .= '</div>';
1725 return $retval;
1729 * Renders user configured footer
1731 * @return string
1733 public static function renderFooter()
1735 return self::_renderCustom(CUSTOM_FOOTER_FILE, 'pma_footer');
1739 * Renders user configured footer
1741 * @return string
1743 public static function renderHeader()
1745 return self::_renderCustom(CUSTOM_HEADER_FILE, 'pma_header');
1749 if (!defined('TESTSUITE')) {
1750 register_shutdown_function(array('PMA\libraries\Config', 'fatalErrorHandler'));