/
FormDisplay.php
842 lines (741 loc) · 26.5 KB
/
FormDisplay.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
<?php
/**
* Form management class, displays and processes forms
*
* Explanation of used terms:
* o work_path - original field path, eg. Servers/4/verbose
* o system_path - work_path modified so that it points to the first server,
* eg. Servers/1/verbose
* o translated_path - work_path modified for HTML field name, a path with
* slashes changed to hyphens, eg. Servers-4-verbose
*/
declare(strict_types=1);
namespace PhpMyAdmin\Config;
use PhpMyAdmin\Config;
use PhpMyAdmin\Config\Forms\User\UserFormList;
use PhpMyAdmin\Html\MySQLDocumentation;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\Util;
use function __;
use function array_flip;
use function array_keys;
use function array_search;
use function explode;
use function function_exists;
use function gettype;
use function implode;
use function is_array;
use function is_bool;
use function is_numeric;
use function mb_substr;
use function preg_match;
use function settype;
use function sprintf;
use function str_ends_with;
use function str_replace;
use function str_starts_with;
use function trigger_error;
use function trim;
use const E_USER_WARNING;
/**
* Form management class, displays and processes forms
*/
class FormDisplay
{
/**
* Form list
*
* @var array<string, Form>
*/
private array $forms = [];
/**
* Stores validation errors, indexed by paths
* [ Form_name ] is an array of form errors
* [path] is a string storing error associated with single field
*
* @var mixed[]
*/
private array $errors = [];
/**
* Paths changed so that they can be used as HTML ids, indexed by paths
*
* @var mixed[]
*/
private array $translatedPaths = [];
/**
* Server paths change indexes so we define maps from current server
* path to the first one, indexed by work path
*
* @var mixed[]
*/
private array $systemPaths = [];
/**
* Tells whether forms have been validated
*/
private bool $isValidated = true;
/**
* Dictionary with user preferences keys
*/
private array|null $userprefsKeys = null;
/**
* Dictionary with disallowed user preferences keys
*
* @var mixed[]
*/
private array $userprefsDisallow = [];
private FormDisplayTemplate $formDisplayTemplate;
private bool $isSetupScript;
public function __construct(private ConfigFile $configFile)
{
$this->formDisplayTemplate = new FormDisplayTemplate(Config::getInstance());
$this->isSetupScript = Sanitize::isSetup();
// initialize validators
Validator::getValidators($this->configFile);
}
/**
* Returns {@link ConfigFile} associated with this instance
*/
public function getConfigFile(): ConfigFile
{
return $this->configFile;
}
/**
* Registers form in form manager
*
* @param string $formName Form name
* @param mixed[] $form Form data
* @param int|null $serverId 0 if new server, validation; >= 1 if editing a server
*/
public function registerForm(string $formName, array $form, int|null $serverId = null): void
{
$this->forms[$formName] = new Form($formName, $form, $this->configFile, $serverId);
$this->isValidated = false;
foreach ($this->forms[$formName]->fields as $path) {
$workPath = $serverId === null
? $path
: str_replace('Servers/1/', 'Servers/' . $serverId . '/', $path);
$this->systemPaths[$workPath] = $path;
$this->translatedPaths[$workPath] = str_replace('/', '-', $workPath);
}
}
/**
* Processes forms, returns true on successful save
*
* @param bool $allowPartialSave allows for partial form saving
* on failed validation
* @param bool $checkFormSubmit whether check for $_POST['submit_save']
*/
public function process(bool $allowPartialSave = true, bool $checkFormSubmit = true): bool
{
if ($checkFormSubmit && ! isset($_POST['submit_save'])) {
return false;
}
// save forms
if ($this->forms !== []) {
return $this->save(array_keys($this->forms), $allowPartialSave);
}
return false;
}
/**
* Runs validation for all registered forms
*/
private function validate(): void
{
if ($this->isValidated) {
return;
}
$paths = [];
$values = [];
foreach ($this->forms as $form) {
$paths[] = $form->name;
// collect values and paths
foreach ($form->fields as $path) {
$workPath = array_search($path, $this->systemPaths);
$values[$path] = $this->configFile->getValue($workPath);
$paths[] = $path;
}
}
// run validation
$errors = Validator::validate($this->configFile, $paths, $values, false);
// change error keys from canonical paths to work paths
if (is_array($errors) && $errors !== []) {
$this->errors = [];
foreach ($errors as $path => $errorList) {
$workPath = array_search($path, $this->systemPaths);
// field error
if (! $workPath) {
// form error, fix path
$workPath = $path;
}
$this->errors[$workPath] = $errorList;
}
}
$this->isValidated = true;
}
/**
* Outputs HTML for forms
*
* @param bool $showButtons whether show submit and reset button
* @param string|null $formAction action attribute for the form
* @param mixed[]|null $hiddenFields array of form hidden fields (key: field
* name)
*
* @return string HTML for forms
*/
public function getDisplay(
bool $showButtons = true,
string|null $formAction = null,
array|null $hiddenFields = null,
): string {
$js = [];
$jsDefault = [];
/**
* We do validation on page refresh when browser remembers field values,
* add a field with known value which will be used for checks.
*/
static $hasCheckPageRefresh = false;
if (! $hasCheckPageRefresh) {
$hasCheckPageRefresh = true;
}
$tabs = [];
foreach ($this->forms as $form) {
$tabs[$form->name] = Descriptions::get('Form_' . $form->name);
}
// validate only when we aren't displaying a "new server" form
$isNewServer = false;
foreach ($this->forms as $form) {
if ($form->index === 0) {
$isNewServer = true;
break;
}
}
if (! $isNewServer) {
$this->validate();
}
// user preferences
$this->loadUserprefsInfo();
$validators = Validator::getValidators($this->configFile);
$forms = [];
foreach ($this->forms as $key => $form) {
$this->formDisplayTemplate->group = 0;
$forms[$key] = [
'name' => $form->name,
'descriptions' => [
'name' => Descriptions::get('Form_' . $form->name),
'desc' => Descriptions::get('Form_' . $form->name, 'desc'),
],
'errors' => $this->errors[$form->name] ?? null,
'fields_html' => '',
];
foreach ($form->fields as $field => $path) {
$workPath = array_search($path, $this->systemPaths);
$translatedPath = $this->translatedPaths[$workPath];
// always true/false for user preferences display
// otherwise null
$userPrefsAllow = isset($this->userprefsKeys[$path])
? ! isset($this->userprefsDisallow[$path])
: null;
// display input
$forms[$key]['fields_html'] .= $this->displayFieldInput(
$form,
$field,
$path,
$workPath,
$translatedPath,
$userPrefsAllow,
$jsDefault,
);
// register JS validators for this field
if (! isset($validators[$path])) {
continue;
}
$this->formDisplayTemplate->addJsValidate($translatedPath, $validators[$path], $js);
}
}
return $this->formDisplayTemplate->display([
'action' => $formAction,
'has_check_page_refresh' => $hasCheckPageRefresh,
'hidden_fields' => (array) $hiddenFields,
'tabs' => $tabs,
'forms' => $forms,
'show_buttons' => $showButtons,
'js_array' => $js,
'js_default' => $jsDefault,
]);
}
/**
* Prepares data for input field display and outputs HTML code
*
* @param string $field field name as it appears in $form
* @param string $systemPath field path, eg. Servers/1/verbose
* @param string $workPath work path, eg. Servers/4/verbose
* @param string $translatedPath work path changed so that it can be
* used as XHTML id
* besides the input field
* @param bool|null $userPrefsAllow whether user preferences are enabled
* for this field (null - no support,
* true/false - enabled/disabled)
* @param mixed[] $jsDefault array which stores JavaScript code
* to be displayed
*
* @return string|null HTML for input field
*/
private function displayFieldInput(
Form $form,
string $field,
string $systemPath,
string $workPath,
string $translatedPath,
bool|null $userPrefsAllow,
array &$jsDefault,
): string|null {
$name = Descriptions::get($systemPath);
$description = Descriptions::get($systemPath, 'desc');
$value = $this->configFile->get($workPath);
$valueDefault = $this->configFile->getDefault($systemPath);
$valueIsDefault = false;
if ($value === null || $value === $valueDefault) {
$value = $valueDefault;
$valueIsDefault = true;
}
$opts = [
'doc' => $this->getDocLink($systemPath),
'show_restore_default' => true,
'userprefs_allow' => $userPrefsAllow,
'userprefs_comment' => Descriptions::get($systemPath, 'cmt'),
];
if (isset($form->default[$systemPath])) {
$opts['setvalue'] = (string) $form->default[$systemPath];
}
if (isset($this->errors[$workPath])) {
$opts['errors'] = $this->errors[$workPath];
}
$type = '';
switch ($form->getOptionType($field)) {
case 'string':
$type = 'text';
break;
case 'short_string':
$type = 'short_text';
break;
case 'double':
case 'integer':
$type = 'number_text';
break;
case 'boolean':
$type = 'checkbox';
break;
case 'select':
$type = 'select';
$opts['values'] = $form->getOptionValueList($form->fields[$field]);
break;
case 'array':
$type = 'list';
$value = (array) $value;
$valueDefault = (array) $valueDefault;
break;
case 'group':
// :group:end is changed to :group:end:{unique id} in Form class
$htmlOutput = '';
if (mb_substr($field, 7, 4) !== 'end:') {
$htmlOutput .= $this->formDisplayTemplate->displayGroupHeader(
mb_substr($field, 7),
);
} else {
$this->formDisplayTemplate->displayGroupFooter();
}
return $htmlOutput;
case 'NULL':
trigger_error('Field ' . $systemPath . ' has no type', E_USER_WARNING);
return null;
}
// detect password fields
if (
$type === 'text'
&& (str_ends_with($translatedPath, '-password')
|| str_ends_with($translatedPath, 'pass')
|| str_ends_with($translatedPath, 'Pass'))
) {
$type = 'password';
}
// TrustedProxies requires changes before displaying
if ($systemPath === 'TrustedProxies') {
foreach ($value as $ip => &$v) {
if (preg_match('/^-\d+$/', $ip)) {
continue;
}
$v = $ip . ': ' . $v;
}
}
$this->setComments($systemPath, $opts);
// send default value to form's JS
$jsLine = '';
switch ($type) {
case 'text':
case 'short_text':
case 'number_text':
case 'password':
$jsLine = (string) $valueDefault;
break;
case 'checkbox':
$jsLine = (bool) $valueDefault;
break;
case 'select':
$valueDefaultJs = is_bool($valueDefault)
? (int) $valueDefault
: $valueDefault;
$jsLine = (array) $valueDefaultJs;
break;
case 'list':
$val = $valueDefault;
if (isset($val['wrapper_params'])) {
unset($val['wrapper_params']);
}
$jsLine = implode("\n", $val);
break;
}
$jsDefault[$translatedPath] = $jsLine;
return $this->formDisplayTemplate->displayInput(
$translatedPath,
$name,
$type,
$value,
$description,
$valueIsDefault,
$opts,
);
}
/**
* Displays errors
*
* @return string HTML for errors
*/
public function displayErrors(): string
{
$this->validate();
$htmlOutput = '';
foreach ($this->errors as $systemPath => $errorList) {
if (isset($this->systemPaths[$systemPath])) {
$name = Descriptions::get($this->systemPaths[$systemPath]);
} else {
$name = Descriptions::get('Form_' . $systemPath);
}
$htmlOutput .= $this->formDisplayTemplate->displayErrors($name, $errorList);
}
return $htmlOutput;
}
/**
* Reverts erroneous fields to their default values
*/
public function fixErrors(): void
{
$this->validate();
if ($this->errors === []) {
return;
}
foreach (array_keys($this->errors) as $workPath) {
if (! isset($this->systemPaths[$workPath])) {
continue;
}
$canonicalPath = $this->systemPaths[$workPath];
$this->configFile->set($workPath, $this->configFile->getDefault($canonicalPath));
}
}
/**
* Validates select field and casts $value to correct type
*
* @param string|bool $value Current value
* @param mixed[] $allowed List of allowed values
*/
private function validateSelect(string|bool &$value, array $allowed): bool
{
$valueCmp = is_bool($value)
? (int) $value
: $value;
foreach (array_keys($allowed) as $vk) {
// equality comparison only if both values are numeric or not numeric
// (allows to skip 0 == 'string' equalling to true)
// or identity (for string-string)
if (! ($vk == $value && ! (is_numeric($valueCmp) xor is_numeric($vk))) && $vk !== $value) {
continue;
}
// keep boolean value as boolean
if (! is_bool($value)) {
// phpcs:ignore Generic.PHP.ForbiddenFunctions
settype($value, gettype($vk));
}
return true;
}
return false;
}
/**
* Validates and saves form data to session
*
* @param string[] $forms List of form names.
* @param bool $allowPartialSave Allows for partial form saving on failed validation.
*/
public function save(array $forms, bool $allowPartialSave = true): bool
{
$result = true;
$values = [];
$toSave = [];
$isSetupScript = Config::getInstance()->get('is_setup');
if ($isSetupScript) {
$this->loadUserprefsInfo();
}
$this->errors = [];
foreach ($forms as $formName) {
if (! isset($this->forms[$formName])) {
continue;
}
$form = $this->forms[$formName];
// get current server id
$changeIndex = $form->index === 0
? $this->configFile->getServerCount() + 1
: false;
// grab POST values
foreach ($form->fields as $field => $systemPath) {
$workPath = array_search($systemPath, $this->systemPaths);
$key = $this->translatedPaths[$workPath];
$type = (string) $form->getOptionType($field);
// skip groups
if ($type === 'group') {
continue;
}
// ensure the value is set
if (! isset($_POST[$key])) {
// checkboxes aren't set by browsers if they're off
if ($type !== 'boolean') {
$this->errors[$form->name][] = sprintf(
__('Missing data for %s'),
'<i>' . Descriptions::get($systemPath) . '</i>',
);
$result = false;
continue;
}
$_POST[$key] = false;
}
// user preferences allow/disallow
if ($isSetupScript && isset($this->userprefsKeys[$systemPath])) {
if (isset($this->userprefsDisallow[$systemPath], $_POST[$key . '-userprefs-allow'])) {
unset($this->userprefsDisallow[$systemPath]);
} elseif (! isset($_POST[$key . '-userprefs-allow'])) {
$this->userprefsDisallow[$systemPath] = true;
}
}
// cast variables to correct type
switch ($type) {
case 'double':
$_POST[$key] = Util::requestString($_POST[$key]);
$_POST[$key] = (float) $_POST[$key];
break;
case 'boolean':
case 'integer':
if ($_POST[$key] !== '') {
$_POST[$key] = Util::requestString($_POST[$key]);
// phpcs:ignore Generic.PHP.ForbiddenFunctions
settype($_POST[$key], $type);
}
break;
case 'select':
$successfullyValidated = $this->validateSelect(
$_POST[$key],
$form->getOptionValueList($systemPath),
);
if (! $successfullyValidated) {
$this->errors[$workPath][] = __('Incorrect value!');
$result = false;
// "continue" for the $form->fields foreach-loop
continue 2;
}
break;
case 'string':
case 'short_string':
$_POST[$key] = Util::requestString($_POST[$key]);
break;
case 'array':
// eliminate empty values and ensure we have an array
$postValues = is_array($_POST[$key])
? $_POST[$key]
: explode("\n", $_POST[$key]);
$_POST[$key] = [];
$this->fillPostArrayParameters($postValues, $key);
break;
}
// now we have value with proper type
$values[$systemPath] = $_POST[$key];
if ($changeIndex !== false) {
$workPath = str_replace(
'Servers/' . $form->index . '/',
'Servers/' . $changeIndex . '/',
$workPath,
);
}
$toSave[$workPath] = $systemPath;
}
}
// save forms
if (! $allowPartialSave && $this->errors !== []) {
// don't look for non-critical errors
$this->validate();
return $result;
}
foreach ($toSave as $workPath => $path) {
// TrustedProxies requires changes before saving
if ($path === 'TrustedProxies') {
$proxies = [];
$i = 0;
foreach ($values[$path] as $value) {
$matches = [];
$match = preg_match('/^(.+):(?:[ ]?)(\\w+)$/', $value, $matches);
if ($match) {
// correct 'IP: HTTP header' pair
$ip = trim($matches[1]);
$proxies[$ip] = trim($matches[2]);
} else {
// save also incorrect values
$proxies['-' . $i] = $value;
$i++;
}
}
$values[$path] = $proxies;
}
$this->configFile->set($workPath, $values[$path], $path);
}
if ($isSetupScript) {
$this->configFile->set(
'UserprefsDisallow',
array_keys($this->userprefsDisallow),
);
}
// don't look for non-critical errors
$this->validate();
return $result;
}
/**
* Tells whether form validation failed
*/
public function hasErrors(): bool
{
return $this->errors !== [];
}
/**
* Returns link to documentation
*
* @param string $path Path to documentation
*/
public function getDocLink(string $path): string
{
if (str_starts_with($path, 'Import') || str_starts_with($path, 'Export')) {
return '';
}
return MySQLDocumentation::getDocumentationLink(
'config',
'cfg_' . $this->getOptName($path),
$this->isSetupScript ? '../' : './',
);
}
/**
* Changes path so it can be used in URLs
*
* @param string $path Path
*/
private function getOptName(string $path): string
{
return str_replace(['Servers/1/', '/'], ['Servers/', '_'], $path);
}
/**
* Fills out {@link userprefs_keys} and {@link userprefs_disallow}
*/
private function loadUserprefsInfo(): void
{
if ($this->userprefsKeys !== null) {
return;
}
$this->userprefsKeys = array_flip(UserFormList::getFields());
// read real config for user preferences display
$config = Config::getInstance();
$userPrefsDisallow = $config->get('is_setup')
? $this->configFile->get('UserprefsDisallow', [])
: $config->settings['UserprefsDisallow'];
$this->userprefsDisallow = array_flip($userPrefsDisallow ?? []);
}
/**
* Sets field comments and warnings based on current environment
*
* @param string $systemPath Path to settings
* @param mixed[] $opts Chosen options
*/
private function setComments(string $systemPath, array &$opts): void
{
// RecodingEngine - mark unavailable types
if ($systemPath === 'RecodingEngine') {
$comment = '';
if (! function_exists('iconv')) {
$opts['values']['iconv'] .= ' (' . __('unavailable') . ')';
$comment = sprintf(
__('"%s" requires %s extension'),
'iconv',
'iconv',
);
}
/* mbstring is always there thanks to polyfill */
$opts['comment'] = $comment;
$opts['comment_warning'] = true;
}
// ZipDump, GZipDump, BZipDump - check function availability
if ($systemPath === 'ZipDump' || $systemPath === 'GZipDump' || $systemPath === 'BZipDump') {
$comment = '';
$funcs = [
'ZipDump' => ['zip_open', 'gzcompress'],
'GZipDump' => ['gzopen', 'gzencode'],
'BZipDump' => ['bzopen', 'bzcompress'],
];
if (! function_exists($funcs[$systemPath][0])) {
$comment = sprintf(
__(
'Compressed import will not work due to missing function %s.',
),
$funcs[$systemPath][0],
);
}
if (! function_exists($funcs[$systemPath][1])) {
$comment .= ($comment !== '' ? '; ' : '') . sprintf(
__(
'Compressed export will not work due to missing function %s.',
),
$funcs[$systemPath][1],
);
}
$opts['comment'] = $comment;
$opts['comment_warning'] = true;
}
$config = Config::getInstance();
if ($config->get('is_setup')) {
return;
}
if ($systemPath !== 'MaxDbList' && $systemPath !== 'MaxTableList' && $systemPath !== 'QueryHistoryMax') {
return;
}
$opts['comment'] = sprintf(
__('maximum %s'),
$config->settings[$systemPath],
);
}
/**
* Copy items of an array to $_POST variable
*
* @param mixed[] $postValues List of parameters
* @param string $key Array key
*/
private function fillPostArrayParameters(array $postValues, string $key): void
{
foreach ($postValues as $v) {
$v = Util::requestString($v);
if ($v === '') {
continue;
}
$_POST[$key][] = $v;
}
}
}