Translated using Weblate (Portuguese)
[phpmyadmin.git] / src / UserPreferences.php
blob1fe533f73b7f98f360ae140570cb0fb91692ce58
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\Dbal\DatabaseInterface;
12 use PhpMyAdmin\Identifiers\DatabaseName;
14 use function __;
15 use function array_flip;
16 use function array_merge;
17 use function htmlspecialchars;
18 use function http_build_query;
19 use function is_array;
20 use function is_int;
21 use function is_numeric;
22 use function is_string;
23 use function json_decode;
24 use function json_encode;
25 use function str_contains;
26 use function time;
27 use function urlencode;
29 /**
30 * Functions for displaying user preferences pages
32 class UserPreferences
34 private readonly Config $config;
36 public function __construct(
37 private readonly DatabaseInterface $dbi,
38 private readonly Relation $relation,
39 private readonly Template $template,
40 ) {
41 $this->config = Config::getInstance();
44 /**
45 * Common initialization for user preferences modification pages
47 * @param ConfigFile $cf Config file instance
49 public function pageInit(ConfigFile $cf): void
51 $formsAllKeys = UserFormList::getFields();
52 $cf->resetConfigData(); // start with a clean instance
53 $cf->setAllowedKeys($formsAllKeys);
54 $cf->setCfgUpdateReadMapping(
55 ['Server/hide_db' => 'Servers/1/hide_db', 'Server/only_db' => 'Servers/1/only_db'],
57 $cf->updateWithGlobalConfig($this->config->settings);
60 /**
61 * Loads user preferences
63 * Returns an array:
64 * * config_data - path => value pairs
65 * * mtime - last modification time
66 * * type - 'db' (config read from pmadb) or 'session' (read from user session)
68 * @psalm-return array{config_data: mixed[], mtime: int, type: 'session'|'db'}
70 public function load(): array
72 $relationParameters = $this->relation->getRelationParameters();
73 if ($relationParameters->userPreferencesFeature === null) {
74 // no pmadb table, use session storage
75 if (! isset($_SESSION['userconfig']) || ! is_array($_SESSION['userconfig'])) {
76 $_SESSION['userconfig'] = ['db' => [], 'ts' => time()];
79 $configData = $_SESSION['userconfig']['db'] ?? null;
80 $timestamp = $_SESSION['userconfig']['ts'] ?? null;
82 return [
83 'config_data' => is_array($configData) ? $configData : [],
84 'mtime' => is_int($timestamp) ? $timestamp : time(),
85 'type' => 'session',
89 // load configuration from pmadb
90 $queryTable = Util::backquote($relationParameters->userPreferencesFeature->database) . '.'
91 . Util::backquote($relationParameters->userPreferencesFeature->userConfig);
92 $query = 'SELECT `config_data`, UNIX_TIMESTAMP(`timevalue`) ts'
93 . ' FROM ' . $queryTable
94 . ' WHERE `username` = '
95 . $this->dbi->quoteString((string) $relationParameters->user);
96 $row = $this->dbi->fetchSingleRow($query, DatabaseInterface::FETCH_ASSOC, ConnectionType::ControlUser);
97 if ($row === [] || ! isset($row['config_data']) || ! isset($row['ts'])) {
98 return ['config_data' => [], 'mtime' => time(), 'type' => 'db'];
101 $configData = is_string($row['config_data']) ? json_decode($row['config_data'], true) : [];
103 return [
104 'config_data' => is_array($configData) ? $configData : [],
105 'mtime' => is_numeric($row['ts']) ? (int) $row['ts'] : time(),
106 'type' => 'db',
111 * Saves user preferences
113 * @param mixed[] $configArray configuration array
115 public function save(array $configArray): true|Message
117 $relationParameters = $this->relation->getRelationParameters();
118 $cacheKey = 'server_' . Current::$server;
119 if (
120 $relationParameters->userPreferencesFeature === null
121 || $relationParameters->user === null
122 || $relationParameters->db === null
124 // no pmadb table, use session storage
125 $_SESSION['userconfig'] = ['db' => $configArray, 'ts' => time()];
126 if (isset($_SESSION['cache'][$cacheKey]['userprefs'])) {
127 unset($_SESSION['cache'][$cacheKey]['userprefs']);
130 return true;
133 // save configuration to pmadb
134 $queryTable = Util::backquote($relationParameters->userPreferencesFeature->database) . '.'
135 . Util::backquote($relationParameters->userPreferencesFeature->userConfig);
136 $query = 'SELECT `username` FROM ' . $queryTable
137 . ' WHERE `username` = '
138 . $this->dbi->quoteString($relationParameters->user);
140 $hasConfig = $this->dbi->fetchValue($query, 0, ConnectionType::ControlUser);
141 $configData = json_encode($configArray);
142 if ($hasConfig) {
143 $query = 'UPDATE ' . $queryTable
144 . ' SET `timevalue` = NOW(), `config_data` = '
145 . $this->dbi->quoteString($configData)
146 . ' WHERE `username` = '
147 . $this->dbi->quoteString($relationParameters->user);
148 } else {
149 $query = 'INSERT INTO ' . $queryTable
150 . ' (`username`, `timevalue`,`config_data`) '
151 . 'VALUES ('
152 . $this->dbi->quoteString($relationParameters->user) . ', NOW(), '
153 . $this->dbi->quoteString($configData) . ')';
156 if (isset($_SESSION['cache'][$cacheKey]['userprefs'])) {
157 unset($_SESSION['cache'][$cacheKey]['userprefs']);
160 if (! $this->dbi->tryQuery($query, ConnectionType::ControlUser)) {
161 $message = Message::error(__('Could not save configuration'));
162 $message->addMessage(
163 Message::error($this->dbi->getError(ConnectionType::ControlUser)),
164 '<br><br>',
166 if (! $this->hasAccessToDatabase($relationParameters->db)) {
168 * When phpMyAdmin cached the configuration storage parameters, it checked if the database can be
169 * accessed, so if it could not be accessed anymore, then the cache must be cleared as it's out of date.
171 $message->addMessage(Message::error(htmlspecialchars(
172 __('The phpMyAdmin configuration storage database could not be accessed.'),
173 )), '<br><br>');
176 return $message;
179 return true;
182 private function hasAccessToDatabase(DatabaseName $database): bool
184 $query = 'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '
185 . $this->dbi->quoteString($database->getName());
186 if ($this->config->selectedServer['DisableIS']) {
187 $query = 'SHOW DATABASES LIKE '
188 . $this->dbi->quoteString(
189 $this->dbi->escapeMysqlWildcards($database->getName()),
193 return $this->dbi->fetchSingleRow($query, 'ASSOC', ConnectionType::ControlUser) !== [];
197 * Returns a user preferences array filtered by $cfg['UserprefsDisallow']
198 * (exclude list) and keys from user preferences form (allow list)
200 * @param mixed[] $configData path => value pairs
202 * @return mixed[]
204 public function apply(array $configData): array
206 $cfg = [];
207 $excludeList = array_flip($this->config->settings['UserprefsDisallow']);
208 $allowList = array_flip(UserFormList::getFields());
209 // allow some additional fields which are custom handled
210 $allowList['ThemeDefault'] = true;
211 $allowList['lang'] = true;
212 $allowList['Server/hide_db'] = true;
213 $allowList['Server/only_db'] = true;
214 $allowList['2fa'] = true;
215 foreach ($configData as $path => $value) {
216 if (! isset($allowList[$path]) || isset($excludeList[$path])) {
217 continue;
220 Core::arrayWrite($path, $cfg, $value);
223 return $cfg;
227 * Updates one user preferences option (loads and saves to database).
229 * No validation is done!
231 * @param string $path configuration
232 * @param mixed $value value
233 * @param mixed $defaultValue default value
235 public function persistOption(string $path, mixed $value, mixed $defaultValue): true|Message
237 $prefs = $this->load();
238 if ($value === $defaultValue) {
239 if (! isset($prefs['config_data'][$path])) {
240 return true;
243 unset($prefs['config_data'][$path]);
244 } else {
245 $prefs['config_data'][$path] = $value;
248 return $this->save($prefs['config_data']);
252 * Redirects after saving new user preferences
254 * @param string $fileName Filename
255 * @param mixed[]|null $params URL parameters
256 * @param string|null $hash Hash value
258 public function redirect(
259 string $fileName,
260 array|null $params = null,
261 string|null $hash = null,
262 ): void {
263 // redirect
264 $urlParams = ['saved' => 1];
265 if (is_array($params)) {
266 $urlParams = array_merge($params, $urlParams);
269 if ($hash !== null && $hash !== '') {
270 $hash = '#' . urlencode($hash);
273 ResponseRenderer::getInstance()->redirect(
274 './' . $fileName . Url::getCommonRaw($urlParams, ! str_contains($fileName, '?') ? '?' : '&') . $hash,
279 * Shows form which allows to quickly load
280 * settings stored in browser's local storage
282 public function autoloadGetHeader(): string
284 if (isset($_REQUEST['prefs_autoload']) && $_REQUEST['prefs_autoload'] === 'hide') {
285 $_SESSION['userprefs_autoload'] = true;
287 return '';
290 $returnUrl = '?' . http_build_query($_GET, '', '&');
292 return $this->template->render('preferences/autoload', [
293 'hidden_inputs' => Url::getHiddenInputs(),
294 'return_url' => $returnUrl,