Translated using Weblate (Portuguese)
[phpmyadmin.git] / src / UserPreferences.php
blob5acfcedd1fab21033549d674c7a9e24da044ec0c
1 <?php
3 declare(strict_types=1);
5 namespace PhpMyAdmin;
7 use PhpMyAdmin\Config\ConfigFile;
8 use PhpMyAdmin\Config\Forms\User\UserFormList;
9 use PhpMyAdmin\ConfigStorage\Relation;
10 use PhpMyAdmin\Dbal\ConnectionType;
11 use PhpMyAdmin\Identifiers\DatabaseName;
13 use function __;
14 use function array_flip;
15 use function array_merge;
16 use function htmlspecialchars;
17 use function http_build_query;
18 use function is_array;
19 use function is_int;
20 use function is_numeric;
21 use function is_string;
22 use function json_decode;
23 use function json_encode;
24 use function str_contains;
25 use function time;
26 use function urlencode;
28 /**
29 * Functions for displaying user preferences pages
31 class UserPreferences
33 private readonly Config $config;
35 public function __construct(
36 private readonly DatabaseInterface $dbi,
37 private readonly Relation $relation,
38 private readonly Template $template,
39 ) {
40 $this->config = Config::getInstance();
43 /**
44 * Common initialization for user preferences modification pages
46 * @param ConfigFile $cf Config file instance
48 public function pageInit(ConfigFile $cf): void
50 $formsAllKeys = UserFormList::getFields();
51 $cf->resetConfigData(); // start with a clean instance
52 $cf->setAllowedKeys($formsAllKeys);
53 $cf->setCfgUpdateReadMapping(
54 ['Server/hide_db' => 'Servers/1/hide_db', 'Server/only_db' => 'Servers/1/only_db'],
56 $cf->updateWithGlobalConfig($this->config->settings);
59 /**
60 * Loads user preferences
62 * Returns an array:
63 * * config_data - path => value pairs
64 * * mtime - last modification time
65 * * type - 'db' (config read from pmadb) or 'session' (read from user session)
67 * @psalm-return array{config_data: mixed[], mtime: int, type: 'session'|'db'}
69 public function load(): array
71 $relationParameters = $this->relation->getRelationParameters();
72 if ($relationParameters->userPreferencesFeature === null) {
73 // no pmadb table, use session storage
74 if (! isset($_SESSION['userconfig']) || ! is_array($_SESSION['userconfig'])) {
75 $_SESSION['userconfig'] = ['db' => [], 'ts' => time()];
78 $configData = $_SESSION['userconfig']['db'] ?? null;
79 $timestamp = $_SESSION['userconfig']['ts'] ?? null;
81 return [
82 'config_data' => is_array($configData) ? $configData : [],
83 'mtime' => is_int($timestamp) ? $timestamp : time(),
84 'type' => 'session',
88 // load configuration from pmadb
89 $queryTable = Util::backquote($relationParameters->userPreferencesFeature->database) . '.'
90 . Util::backquote($relationParameters->userPreferencesFeature->userConfig);
91 $query = 'SELECT `config_data`, UNIX_TIMESTAMP(`timevalue`) ts'
92 . ' FROM ' . $queryTable
93 . ' WHERE `username` = '
94 . $this->dbi->quoteString((string) $relationParameters->user);
95 $row = $this->dbi->fetchSingleRow($query, DatabaseInterface::FETCH_ASSOC, ConnectionType::ControlUser);
96 if (! is_array($row) || ! isset($row['config_data']) || ! isset($row['ts'])) {
97 return ['config_data' => [], 'mtime' => time(), 'type' => 'db'];
100 $configData = is_string($row['config_data']) ? json_decode($row['config_data'], true) : [];
102 return [
103 'config_data' => is_array($configData) ? $configData : [],
104 'mtime' => is_numeric($row['ts']) ? (int) $row['ts'] : time(),
105 'type' => 'db',
110 * Saves user preferences
112 * @param mixed[] $configArray configuration array
114 * @return true|Message
116 public function save(array $configArray): bool|Message
118 $relationParameters = $this->relation->getRelationParameters();
119 $cacheKey = 'server_' . Current::$server;
120 if (
121 $relationParameters->userPreferencesFeature === null
122 || $relationParameters->user === null
123 || $relationParameters->db === null
125 // no pmadb table, use session storage
126 $_SESSION['userconfig'] = ['db' => $configArray, 'ts' => time()];
127 if (isset($_SESSION['cache'][$cacheKey]['userprefs'])) {
128 unset($_SESSION['cache'][$cacheKey]['userprefs']);
131 return true;
134 // save configuration to pmadb
135 $queryTable = Util::backquote($relationParameters->userPreferencesFeature->database) . '.'
136 . Util::backquote($relationParameters->userPreferencesFeature->userConfig);
137 $query = 'SELECT `username` FROM ' . $queryTable
138 . ' WHERE `username` = '
139 . $this->dbi->quoteString($relationParameters->user);
141 $hasConfig = $this->dbi->fetchValue($query, 0, ConnectionType::ControlUser);
142 $configData = json_encode($configArray);
143 if ($hasConfig) {
144 $query = 'UPDATE ' . $queryTable
145 . ' SET `timevalue` = NOW(), `config_data` = '
146 . $this->dbi->quoteString($configData)
147 . ' WHERE `username` = '
148 . $this->dbi->quoteString($relationParameters->user);
149 } else {
150 $query = 'INSERT INTO ' . $queryTable
151 . ' (`username`, `timevalue`,`config_data`) '
152 . 'VALUES ('
153 . $this->dbi->quoteString($relationParameters->user) . ', NOW(), '
154 . $this->dbi->quoteString($configData) . ')';
157 if (isset($_SESSION['cache'][$cacheKey]['userprefs'])) {
158 unset($_SESSION['cache'][$cacheKey]['userprefs']);
161 if (! $this->dbi->tryQuery($query, ConnectionType::ControlUser)) {
162 $message = Message::error(__('Could not save configuration'));
163 $message->addMessage(
164 Message::error($this->dbi->getError(ConnectionType::ControlUser)),
165 '<br><br>',
167 if (! $this->hasAccessToDatabase($relationParameters->db)) {
169 * When phpMyAdmin cached the configuration storage parameters, it checked if the database can be
170 * accessed, so if it could not be accessed anymore, then the cache must be cleared as it's out of date.
172 $message->addMessage(Message::error(htmlspecialchars(
173 __('The phpMyAdmin configuration storage database could not be accessed.'),
174 )), '<br><br>');
177 return $message;
180 return true;
183 private function hasAccessToDatabase(DatabaseName $database): bool
185 $query = 'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '
186 . $this->dbi->quoteString($database->getName());
187 if ($this->config->selectedServer['DisableIS']) {
188 $query = 'SHOW DATABASES LIKE '
189 . $this->dbi->quoteString(
190 $this->dbi->escapeMysqlWildcards($database->getName()),
194 return (bool) $this->dbi->fetchSingleRow($query, 'ASSOC', ConnectionType::ControlUser);
198 * Returns a user preferences array filtered by $cfg['UserprefsDisallow']
199 * (exclude list) and keys from user preferences form (allow list)
201 * @param mixed[] $configData path => value pairs
203 * @return mixed[]
205 public function apply(array $configData): array
207 $cfg = [];
208 $excludeList = array_flip($this->config->settings['UserprefsDisallow']);
209 $allowList = array_flip(UserFormList::getFields());
210 // allow some additional fields which are custom handled
211 $allowList['ThemeDefault'] = true;
212 $allowList['lang'] = true;
213 $allowList['Server/hide_db'] = true;
214 $allowList['Server/only_db'] = true;
215 $allowList['2fa'] = true;
216 foreach ($configData as $path => $value) {
217 if (! isset($allowList[$path]) || isset($excludeList[$path])) {
218 continue;
221 Core::arrayWrite($path, $cfg, $value);
224 return $cfg;
228 * Updates one user preferences option (loads and saves to database).
230 * No validation is done!
232 * @param string $path configuration
233 * @param mixed $value value
234 * @param mixed $defaultValue default value
236 * @return true|Message
238 public function persistOption(string $path, mixed $value, mixed $defaultValue): bool|Message
240 $prefs = $this->load();
241 if ($value === $defaultValue) {
242 if (! isset($prefs['config_data'][$path])) {
243 return true;
246 unset($prefs['config_data'][$path]);
247 } else {
248 $prefs['config_data'][$path] = $value;
251 return $this->save($prefs['config_data']);
255 * Redirects after saving new user preferences
257 * @param string $fileName Filename
258 * @param mixed[]|null $params URL parameters
259 * @param string|null $hash Hash value
261 public function redirect(
262 string $fileName,
263 array|null $params = null,
264 string|null $hash = null,
265 ): void {
266 // redirect
267 $urlParams = ['saved' => 1];
268 if (is_array($params)) {
269 $urlParams = array_merge($params, $urlParams);
272 if ($hash !== null && $hash !== '') {
273 $hash = '#' . urlencode($hash);
276 ResponseRenderer::getInstance()->redirect(
277 './' . $fileName . Url::getCommonRaw($urlParams, ! str_contains($fileName, '?') ? '?' : '&') . $hash,
282 * Shows form which allows to quickly load
283 * settings stored in browser's local storage
285 public function autoloadGetHeader(): string
287 if (isset($_REQUEST['prefs_autoload']) && $_REQUEST['prefs_autoload'] === 'hide') {
288 $_SESSION['userprefs_autoload'] = true;
290 return '';
293 $returnUrl = '?' . http_build_query($_GET, '', '&');
295 return $this->template->render('preferences/autoload', [
296 'hidden_inputs' => Url::getHiddenInputs(),
297 'return_url' => $returnUrl,