-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathInsertEdit.php
More file actions
1881 lines (1676 loc) · 66.8 KB
/
InsertEdit.php
File metadata and controls
1881 lines (1676 loc) · 66.8 KB
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace PhpMyAdmin;
use PhpMyAdmin\ConfigStorage\Foreigners;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Dbal\DatabaseInterface;
use PhpMyAdmin\Dbal\ResultInterface;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\I18n\LanguageManager;
use PhpMyAdmin\Plugins\IOTransformationsPlugin;
use PhpMyAdmin\Plugins\TransformationsInterface;
use PhpMyAdmin\Utils\Gis;
use function __;
use function array_fill;
use function array_key_exists;
use function array_merge;
use function array_values;
use function bin2hex;
use function count;
use function htmlspecialchars;
use function implode;
use function in_array;
use function is_array;
use function is_numeric;
use function is_string;
use function json_encode;
use function max;
use function mb_stripos;
use function mb_strlen;
use function min;
use function password_hash;
use function preg_match;
use function preg_replace;
use function str_contains;
use function str_replace;
use function str_starts_with;
use function stripslashes;
use function trim;
use const ENT_COMPAT;
use const PASSWORD_DEFAULT;
class InsertEdit
{
private const FUNC_OPTIONAL_PARAM = ['NOW', 'RAND', 'UNIX_TIMESTAMP'];
private const FUNC_NO_PARAM = [
'CONNECTION_ID',
'CURRENT_USER',
'CURDATE',
'CURTIME',
'CURRENT_DATE',
'CURRENT_TIME',
'DATABASE',
'LAST_INSERT_ID',
'NOW',
'PI',
'RAND',
'SYSDATE',
'UNIX_TIMESTAMP',
'USER',
'UTC_DATE',
'UTC_TIME',
'UTC_TIMESTAMP',
'UUID',
'UUID_SHORT',
'VERSION',
];
private int $rowOffset = 0;
private int $fieldIndex = 0;
/** @var string[] */
public static array $pluginScripts = [];
public function __construct(
private readonly DatabaseInterface $dbi,
private readonly Relation $relation,
private readonly Transformations $transformations,
private readonly FileListing $fileListing,
private readonly Template $template,
private readonly Config $config,
private readonly ResponseRenderer $responseRenderer,
) {
}
/**
* Retrieve form parameters for insert/edit form
*
* @param string $db name of the database
* @param string $table name of the table
* @param string[] $whereClauseArray
*
* @return array<string, string> array of insert/edit form parameters
*/
public function getFormParametersForInsertForm(
string $db,
string $table,
array $whereClauseArray,
string $errorUrl,
): array {
$formParams = [
'db' => $db,
'table' => $table,
'goto' => UrlParams::$goto,
'err_url' => $errorUrl,
'sql_query' => $_POST['sql_query'] ?? '',
];
if ($formParams['sql_query'] === '' && isset($_GET['sql_query'], $_GET['sql_signature'])) {
if (Core::checkSqlQuerySignature($_GET['sql_query'], $_GET['sql_signature'])) {
$formParams['sql_query'] = $_GET['sql_query'];
}
}
foreach ($whereClauseArray as $keyId => $whereClause) {
$formParams['where_clause[' . $keyId . ']'] = trim($whereClause);
}
if (isset($_POST['clause_is_unique'])) {
$formParams['clause_is_unique'] = $_POST['clause_is_unique'];
} elseif (isset($_GET['clause_is_unique'])) {
$formParams['clause_is_unique'] = $_GET['clause_is_unique'];
}
return $formParams;
}
/**
* Analysing where clauses array
*
* @param string[] $whereClauseArray array of where clauses
* @param string $table name of the table
* @param string $db name of the database
*
* @return array{ResultInterface[], array<string|null>[], bool}
*/
private function analyzeWhereClauses(
array $whereClauseArray,
string $table,
string $db,
): array {
$rows = [];
$result = [];
$foundUniqueKey = false;
foreach ($whereClauseArray as $keyId => $whereClause) {
$localQuery = 'SELECT * FROM '
. Util::backquote($db) . '.'
. Util::backquote($table)
. ' WHERE ' . $whereClause . ';';
$result[$keyId] = $this->dbi->query($localQuery);
$rows[$keyId] = $result[$keyId]->fetchAssoc();
if ($rows[$keyId] === []) {
$this->responseRenderer->addHTML(
Generator::getMessage(
__('MySQL returned an empty result set (i.e. zero rows).'),
$localQuery,
),
);
/**
* @todo not sure what should be done at this point, but we must not
* exit if we want the message to be displayed
*/
continue;
}
if (! $this->hasUniqueCondition($rows[$keyId], $result[$keyId])) {
continue;
}
$foundUniqueKey = true;
}
return [$result, $rows, $foundUniqueKey];
}
/** @param array<string|null> $row */
private function hasUniqueCondition(array $row, ResultInterface $result): bool
{
$meta = $this->dbi->getFieldsMeta($result);
return (bool) (new UniqueCondition($meta, $row, true))->getWhereClause();
}
/**
* No primary key given, just load first row
*/
private function loadFirstRow(string $table, string $db): ResultInterface
{
return $this->dbi->query(
'SELECT * FROM ' . Util::backquote($db)
. '.' . Util::backquote($table) . ' LIMIT 1;',
);
}
/** @return never[][] */
private function getInsertRows(): array
{
return array_fill(0, $this->config->config->InsertRows, []);
}
/**
* Show type information or function selectors in Insert/Edit
*
* @param string $which function|type
* @param array<string, bool|int|string> $urlParams containing url parameters
* @param bool $isShow whether to show the element in $which
*
* @return string an HTML snippet
*/
public function showTypeOrFunction(string $which, array $urlParams, bool $isShow): string
{
$params = [];
switch ($which) {
case 'function':
$params['ShowFunctionFields'] = $isShow ? 0 : 1;
$params['ShowFieldTypesInDataEditView'] = $this->config->config->ShowFieldTypesInDataEditView;
break;
case 'type':
$params['ShowFieldTypesInDataEditView'] = $isShow ? 0 : 1;
$params['ShowFunctionFields'] = $this->config->config->ShowFunctionFields;
break;
}
$params['goto'] = Url::getFromRoute('/sql');
$thisUrlParams = array_merge($urlParams, $params);
if (! $isShow) {
return ' : <a href="' . Url::getFromRoute('/table/change') . '" data-post="'
. Url::getCommon($thisUrlParams, '', false) . '">'
. $this->showTypeOrFunctionLabel($which)
. '</a>';
}
return '<th><a href="' . Url::getFromRoute('/table/change') . '" data-post="'
. Url::getCommon($thisUrlParams, '', false)
. '" title="' . __('Hide') . '">'
. $this->showTypeOrFunctionLabel($which)
. '</a></th>';
}
/**
* Show type information or function selectors labels in Insert/Edit
*
* @param string $which function|type
*
* @return string an HTML snippet
*/
private function showTypeOrFunctionLabel(string $which): string
{
return match ($which) {
'function' => __('Function'),
'type' => __('Type'),
default => '',
};
}
/**
* Retrieve the column title
*
* @param string $fieldName name of the column
* @param string[] $commentsMap comments for every column that has a comment
*
* @return string column title
*/
private function getColumnTitle(string $fieldName, array $commentsMap): string
{
if (isset($commentsMap[$fieldName])) {
return '<span style="border-bottom: 1px dashed black;" title="'
. htmlspecialchars($commentsMap[$fieldName]) . '">'
. htmlspecialchars($fieldName) . '</span>';
}
return htmlspecialchars($fieldName);
}
/**
* check whether the column is of a certain type
* the goal is to ensure that types such as "enum('one','two','binary',..)"
* or "enum('one','two','varbinary',..)" are not categorized as binary
*
* @param string $columnType column type as specified in the column definition
* @param string[] $types the types to verify
*/
public function isColumn(string $columnType, array $types): bool
{
foreach ($types as $oneType) {
if (mb_stripos($columnType, $oneType) === 0) {
return true;
}
}
return false;
}
/**
* Retrieve the nullify code for the null column
*
* @param InsertEditColumn $column description of column in given table
*/
private function getNullifyCodeForNullColumn(
InsertEditColumn $column,
Foreigners $foreigners,
bool $foreignLink,
): string {
if ($column->trueType === 'enum') {
return mb_strlen($column->type) > 20 ? '1' : '2';
}
if ($column->trueType === 'set') {
return '3';
}
if ($this->relation->searchColumnInForeigners($foreigners, $column->field) !== false) {
return $foreignLink ? '6' : '4';
}
return '5';
}
/**
* Get HTML textarea for insert form
*
* @param InsertEditColumn $column column information
* @param string $backupField hidden input field
* @param string $columnNameAppendix the name attribute
* @param string $onChangeClause onchange clause for fields
* @param TypeClass $dataType the html5 data-* attribute type
*
* @return string an html snippet
*/
private function getTextarea(
InsertEditColumn $column,
string $backupField,
string $columnNameAppendix,
string $onChangeClause,
string $formattedDefaultValue,
TypeClass $dataType,
): string {
$theClass = '';
$textAreaRows = $this->config->config->TextareaRows;
$textareaCols = $this->config->config->TextareaCols;
if ($column->isChar) {
/**
* @todo clarify the meaning of the "textfield" class and explain
* why character columns have the "char" class instead
*/
$theClass = 'charField';
$textAreaRows = $this->config->config->CharTextareaRows;
$textareaCols = $this->config->config->CharTextareaCols;
$extractedColumnspec = Util::extractColumnSpec($column->type);
$maxlength = $extractedColumnspec['spec_in_brackets'];
} elseif ($this->config->config->LongtextDoubleTextarea && $column->trueType === 'longtext') {
$textAreaRows = $this->config->config->TextareaRows * 2;
$textareaCols = $this->config->config->TextareaCols * 2;
}
//We need to duplicate the first \n or otherwise we will lose
//the first newline entered in a VARCHAR or TEXT column
$specialCharsEncoded = Util::duplicateFirstNewline($formattedDefaultValue);
return $backupField . "\n"
. '<textarea name="fields' . $columnNameAppendix . '"'
. ' class="' . $theClass . '"'
. (isset($maxlength) ? ' data-maxlength="' . $maxlength . '"' : '')
. ' rows="' . $textAreaRows . '"'
. ' cols="' . $textareaCols . '"'
. ' dir="' . LanguageManager::$textDirection->value . '"'
. ' id="field_' . $this->fieldIndex . '_3"'
. ($onChangeClause !== '' ? ' onchange="' . htmlspecialchars($onChangeClause, ENT_COMPAT) . '"' : '')
. ' tabindex="' . $this->fieldIndex . '"'
. ' data-type="' . $dataType->value . '">'
. htmlspecialchars($specialCharsEncoded, ENT_COMPAT)
. '</textarea>';
}
/** @return object{isInteger: bool, minValue: string, maxValue: string} */
private function getIntegerRange(InsertEditColumn $column): object
{
$minValue = '';
$maxValue = '';
$isInteger = in_array($column->trueType, $this->dbi->types->getIntegerTypes(), true);
if ($isInteger) {
$extractedColumnSpec = Util::extractColumnSpec($column->type);
$isUnsigned = $extractedColumnSpec['unsigned'];
$minMaxValues = $this->dbi->types->getIntegerRange($column->trueType, ! $isUnsigned);
$minValue = $minMaxValues[0];
$maxValue = $minMaxValues[1];
}
return new class ($isInteger, $minValue, $maxValue) {
public function __construct(
public readonly bool $isInteger,
public readonly string $minValue,
public readonly string $maxValue,
) {
}
};
}
/**
* Get HTML select option for upload
*
* @param string $vkey [multi_edit]['row_id']
* @param string $fieldHashMd5 array index as an MD5 to avoid having special characters
*
* @return string an HTML snippet
*/
private function getSelectOptionForUpload(string $vkey, string $fieldHashMd5): string
{
$files = $this->fileListing->getFileSelectOptions(
Util::userDir($this->config->selectedServer['user'], $this->config->config->UploadDir),
);
if ($files === false) {
return '<span style="color:red">' . __('Error') . '</span><br>' . "\n"
. __('The directory you set for upload work cannot be reached.') . "\n";
}
if ($files === '') {
return '';
}
return "<br>\n"
. '<i>' . __('Or') . '</i> '
. __('web server upload directory:') . '<br>' . "\n"
. '<select size="1" name="fields_uploadlocal'
. $vkey . '[' . $fieldHashMd5 . ']">' . "\n"
. '<option value="" selected></option>' . "\n"
. $files
. '</select>' . "\n";
}
/**
* Retrieve the maximum upload file size
*/
private function getMaxUploadSize(string $type): string
{
// find maximum upload size, based on field type
/**
* @todo with functions this is not so easy, as you can basically
* process any data with function like MD5
*/
$maxFieldSize = match ($type) {
'tinyblob' => 256,
'blob' => 65536,
'mediumblob' => 16777216,
'longblob' => 4294967296,// yeah, really
};
$thisFieldMaxSize = Util::getUploadSizeInBytes();
return Util::getFormattedMaximumUploadSize(min($thisFieldMaxSize, $maxFieldSize)) . "\n";
}
/**
* Get HTML for the Value column of other datatypes
* (here, "column" is used in the sense of HTML column in HTML table)
*
* @param InsertEditColumn $column description of column in given table
* @param string $defaultCharEditing default char editing mode which is stored
* in the config.inc.php script
* @param string $backupField hidden input field
* @param string $columnNameAppendix the name attribute
* @param string $onChangeClause onchange clause for fields
* @param string $data data to edit
*
* @return string an html snippet
*/
private function getValueColumnForOtherDatatypes(
InsertEditColumn $column,
string $defaultCharEditing,
string $backupField,
string $columnNameAppendix,
string $onChangeClause,
string $formattedDefaultValue,
string $data,
string $specInBrackets,
): string {
// HTML5 data-* attribute data-type
$dataType = $this->dbi->types->getTypeClass($column->trueType);
$fieldsize = $this->getColumnSize($column, $specInBrackets);
$input = [];
$textareaHtml = '';
$isTextareaRequired = $column->isChar
&& ($this->config->config->CharEditing === 'textarea' || str_contains($data, "\n"));
if ($isTextareaRequired) {
$this->config->set('CharEditing', $defaultCharEditing);
$textareaHtml = $this->getTextarea(
$column,
$backupField,
$columnNameAppendix,
$onChangeClause,
$formattedDefaultValue,
$dataType,
);
} else {
$integerRange = $this->getIntegerRange($column);
$input = [
'value' => $formattedDefaultValue,
'size' => $fieldsize,
'is_char' => $column->isChar,
'is_integer' => $integerRange->isInteger,
'min' => $integerRange->minValue,
'max' => $integerRange->maxValue,
'data_type' => $dataType->value,
'on_change_clause' => $onChangeClause,
'field_index' => $this->fieldIndex,
];
}
return $this->template->render('table/insert/value_column_for_other_datatype', [
'input' => $input,
'textarea_html' => $textareaHtml,
'backup_field' => $backupField,
'is_textarea' => $isTextareaRequired,
'column_name_appendix' => $columnNameAppendix,
'extra' => $column->extra,
'true_type' => $column->trueType,
]);
}
/**
* Get the field size
*
* @param InsertEditColumn $column description of column in given table
* @param string $specInBrackets text in brackets inside column definition
*
* @return int field size
*/
private function getColumnSize(InsertEditColumn $column, string $specInBrackets): int
{
if ($column->isChar) {
$fieldsize = (int) $specInBrackets;
if ($fieldsize > $this->config->config->MaxSizeForInputField) {
/**
* This case happens for CHAR or VARCHAR columns which have
* a size larger than the maximum size for input field.
*/
$this->config->set('CharEditing', 'textarea');
}
} else {
/**
* This case happens for example for INT or DATE columns;
* in these situations, the value returned in $column['len']
* seems appropriate.
*/
$fieldsize = $column->length;
}
return min(
max($fieldsize, $this->config->config->MinSizeForInputField),
$this->config->config->MaxSizeForInputField,
);
}
/**
* get html for continue insertion form
*
* @param string $table name of the table
* @param string $db name of the database
* @param string[] $whereClauseArray
*
* @return string an html snippet
*/
public function getContinueInsertionForm(
string $table,
string $db,
array $whereClauseArray,
string $errorUrl,
): string {
return $this->template->render('table/insert/continue_insertion_form', [
'db' => $db,
'table' => $table,
'where_clause_array' => $whereClauseArray,
'err_url' => $errorUrl,
'goto' => UrlParams::$goto,
'sql_query' => $_POST['sql_query'] ?? null,
'has_where_clause' => isset($_POST['where_clause']),
'insert_rows_default' => $this->config->config->InsertRows,
]);
}
/**
* @param string[]|string|null $whereClause
*
* @psalm-pure
*/
public static function isWhereClauseNumeric(array|string|null $whereClause): bool
{
if ($whereClause === null) {
return false;
}
if (! is_array($whereClause)) {
$whereClause = [$whereClause];
}
// If we have just numeric primary key, we can also edit next
// we are looking for `table_name`.`field_name` = numeric_value
foreach ($whereClause as $clause) {
// preg_match() returns 1 if there is a match
$isNumeric = preg_match('@^[\s]*`[^`]*`[\.]`[^`]*` = [0-9]+@', $clause) === 1;
if ($isNumeric) {
return true;
}
}
return false;
}
/**
* Get table head and table foot for insert row table
*
* @param array<string, bool|int|string> $urlParams url parameters
*
* @return string an html snippet
*/
private function getHeadAndFootOfInsertRowTable(array $urlParams): string
{
$type = '';
$function = '';
if ($this->config->config->ShowFieldTypesInDataEditView) {
$type = $this->showTypeOrFunction('type', $urlParams, true);
}
if ($this->config->config->ShowFunctionFields) {
$function = $this->showTypeOrFunction('function', $urlParams, true);
}
$template = new Template($this->config);
return $template->render('table/insert/get_head_and_foot_of_insert_row_table', [
'type' => $type,
'function' => $function,
]);
}
/**
* Prepares the field value and retrieve special chars, backup field and data array
*
* @param array<string|null> $currentRow a row of the table
* @param InsertEditColumn $column description of column in given table
* @param string $columnNameAppendix string to append to column name in input
* @param bool $asIs use the data as is, used in repopulating
*
* @return array{bool, string, string, string}
*/
private function getDefaultValueAndBackupFieldForExistingRow(
array $currentRow,
InsertEditColumn $column,
string $specInBrackets,
string $columnNameAppendix,
bool $asIs,
): array {
$data = '';
$realNullValue = false;
$currentValue = $currentRow[$column->field] ?? null;
// (we are editing)
if ($currentValue === null) {
$realNullValue = true;
$currentValue = '';
$formattedDefaultValue = '';
$data = '';
} elseif ($column->trueType === 'bit') {
$formattedDefaultValue = $asIs
? $currentValue
: Util::printableBitValue((int) $currentValue, (int) $specInBrackets);
} elseif (
in_array($column->trueType, ['timestamp', 'datetime', 'time'], true)
&& str_contains($currentValue, '.')
) {
$currentValue = $asIs
? $currentValue
: Util::addMicroseconds($currentValue);
$formattedDefaultValue = $currentValue;
} elseif (in_array($column->trueType, Gis::getDataTypes(), true)) {
// Convert gis data to Well Know Text format
$currentValue = $asIs
? $currentValue
: Gis::convertToWellKnownText($currentValue, true);
$formattedDefaultValue = $currentValue;
} else {
// special binary "characters"
if ($column->isBinary || ($column->isBlob && $this->config->config->ProtectBinary !== 'all')) {
$currentValue = $asIs
? $currentValue
: bin2hex($currentValue);
}
$formattedDefaultValue = $currentValue;
$data = $currentValue;
}
/** @var string $defaultAction */
$defaultAction = $_POST['default_action'] ?? $_GET['default_action'] ?? '';
if (
$defaultAction === 'insert'
&& $column->key === 'PRI'
&& str_contains($column->extra, 'auto_increment')
) {
// When copying row, it is useful to empty auto-increment column to prevent duplicate key error.
$data = $formattedDefaultValue = '';
}
// If a timestamp field value is not included in an update
// statement MySQL auto-update it to the current timestamp;
// however, things have changed since MySQL 4.1, so
// it's better to set a fields_prev in this situation
$backupField = '<input type="hidden" name="fields_prev'
. $columnNameAppendix . '" value="'
. htmlspecialchars($currentValue, ENT_COMPAT) . '">';
return [$realNullValue, $formattedDefaultValue, $data, $backupField];
}
/**
* display default values
*/
private function getDefaultValue(
string|null $defaultValue,
string $trueType,
): string {
if ($defaultValue === null) {
$defaultValue = '';
}
if ($trueType === 'bit') {
return Util::convertBitDefaultValue($defaultValue);
}
if (in_array($trueType, ['timestamp', 'datetime', 'time'], true)) {
return Util::addMicroseconds($defaultValue);
}
if ($trueType === 'binary' || $trueType === 'varbinary') {
return bin2hex($defaultValue);
}
return $defaultValue;
}
/**
* set $_SESSION for edit_next
*
* @param string $oneWhereClause one where clause from where clauses array
*/
public function setSessionForEditNext(string $oneWhereClause): void
{
$localQuery = 'SELECT * FROM ' . Util::backquote(Current::$database)
. '.' . Util::backquote(Current::$table) . ' WHERE '
. str_replace('` =', '` >', $oneWhereClause) . ' LIMIT 1;';
$res = $this->dbi->query($localQuery);
$row = $res->fetchRow();
$meta = $this->dbi->getFieldsMeta($res);
// must find a unique condition based on unique key,
// not a combination of all fields
$uniqueCondition = (new UniqueCondition($meta, $row, true))->getWhereClause();
if ($uniqueCondition === '') {
return;
}
$_SESSION['edit_next'] = $uniqueCondition;
}
/**
* set $goto_include variable for different cases and retrieve like,
* if UrlParams::$goto empty, if $goto_include previously not defined
* and new_insert, same_insert, edit_next
*
* @param string|false $gotoInclude store some script for include, otherwise it is
* boolean false
*/
public function getGotoInclude(string|false $gotoInclude): string
{
$validOptions = ['new_insert', 'same_insert', 'edit_next'];
if (isset($_POST['after_insert']) && in_array($_POST['after_insert'], $validOptions, true)) {
return '/table/change';
}
if (UrlParams::$goto !== '') {
if (preg_match('@^[a-z_]+\.php$@', UrlParams::$goto) !== 1) {
// this should NOT happen
//UrlParams::$goto = false;
$gotoInclude = str_contains(UrlParams::$goto, 'index.php?route=/sql') ? '/sql' : false;
} else {
$gotoInclude = UrlParams::$goto;
}
if (UrlParams::$goto === 'index.php?route=/database/sql' && Current::$table !== '') {
Current::$table = '';
}
}
if (! $gotoInclude) {
$gotoInclude = Current::$table === '' ? '/database/sql' : '/table/sql';
}
return $gotoInclude;
}
/**
* Defines the url to return in case of failure of the query
*
* @param mixed[] $urlParams url parameters
*
* @return string error url for query failure
*/
public function getErrorUrl(array $urlParams): string
{
return $_POST['err_url'] ?? Url::getFromRoute('/table/change', $urlParams);
}
/**
* Executes the sql query and get the result, then move back to the calling page
*
* @param string[] $query built query from buildSqlQuery()
*
* @return array{int, Message[], string[], string[]}
*/
public function executeSqlQuery(array $query): array
{
Current::$sqlQuery = implode('; ', $query) . ';';
// to ensure that the query is displayed in case of
// "insert as new row" and then "insert another new row"
Current::$displayQuery = Current::$sqlQuery;
$totalAffectedRows = 0;
$lastMessages = [];
$warningMessages = [];
$errorMessages = [];
foreach ($query as $singleQuery) {
if (isset($_POST['submit_type']) && $_POST['submit_type'] === 'showinsert') {
$lastMessages[] = Message::notice(__('Showing SQL query'));
continue;
}
if ($this->config->config->IgnoreMultiSubmitErrors) {
$result = $this->dbi->tryQuery($singleQuery);
} else {
$result = $this->dbi->query($singleQuery);
}
if (! $result) {
$errorMessages[] = $this->dbi->getError();
} else {
$totalAffectedRows += (int) $this->dbi->affectedRows();
$insertId = $this->dbi->insertId();
if ($insertId !== 0) {
// insert_id is id of FIRST record inserted in one insert, so if we
// inserted multiple rows, we had to increment this
if ($totalAffectedRows > 0) {
$insertId += $totalAffectedRows - 1;
}
$lastMessage = Message::notice(__('Inserted row id: %1$d'));
$lastMessage->addParam($insertId);
$lastMessages[] = $lastMessage;
}
}
$warningMessages = $this->getWarningMessages();
}
return [$totalAffectedRows, $lastMessages, $warningMessages, $errorMessages];
}
/**
* get the warning messages array
*
* @return string[]
*/
private function getWarningMessages(): array
{
$warningMessages = [];
foreach ($this->dbi->getWarnings() as $warning) {
$warningMessages[] = htmlspecialchars((string) $warning);
}
return $warningMessages;
}
/**
* Column to display from the foreign table?
*
* @param string $whereComparison string that contain relation field value
* @param string $relationField relation field
*
* @return string display value from the foreign table
*/
public function getDisplayValueForForeignTableColumn(
string $whereComparison,
Foreigners $foreigners,
string $relationField,
): string {
$foreigner = $this->relation->searchColumnInForeigners($foreigners, $relationField);
if (! is_array($foreigner)) {
return '';
}
$displayField = $this->relation->getDisplayField($foreigner['foreign_db'], $foreigner['foreign_table']);
// Field to display from the foreign table?
if ($displayField !== '') {
$dispsql = 'SELECT ' . Util::backquote($displayField)
. ' FROM ' . Util::backquote($foreigner['foreign_db'])
. '.' . Util::backquote($foreigner['foreign_table'])
. ' WHERE ' . Util::backquote($foreigner['foreign_field'])
. $whereComparison;
$dispresult = $this->dbi->tryQuery($dispsql);
if ($dispresult && $dispresult->numRows() > 0) {
return (string) $dispresult->fetchValue();
}
}
return '';
}
/**
* Display option in the cell according to user choices
*
* @param string $relationField relation field
* @param string $whereComparison string that contain relation field value
* @param string $dispval display value from the foreign table
* @param string $relationFieldValue relation field value
*
* @return string HTML <a> tag
*/
public function getLinkForRelationalDisplayField(
Foreigners $foreigners,
string $relationField,
string $whereComparison,
string $dispval,
string $relationFieldValue,
): string {
$foreigner = $this->relation->searchColumnInForeigners($foreigners, $relationField);
if (! is_array($foreigner)) {
return '';
}
if ($_SESSION['tmpval']['relational_display'] === 'K') {
// user chose "relational key" in the display options, so
// the title contains the display field
$title = $dispval !== ''
? ' title="' . htmlspecialchars($dispval) . '"'
: '';
} else {
$title = ' title="' . htmlspecialchars($relationFieldValue) . '"';
}
$sqlQuery = 'SELECT * FROM '
. Util::backquote($foreigner['foreign_db'])
. '.' . Util::backquote($foreigner['foreign_table'])
. ' WHERE ' . Util::backquote($foreigner['foreign_field'])
. $whereComparison;
$urlParams = [
'db' => $foreigner['foreign_db'],
'table' => $foreigner['foreign_table'],
'pos' => '0',
'sql_signature' => Core::signSqlQuery($sqlQuery),
'sql_query' => $sqlQuery,
];
$output = '<a href="' . Url::getFromRoute('/sql', $urlParams) . '"' . $title . '>';
if ($_SESSION['tmpval']['relational_display'] === 'D') {
// user chose "relational display field" in the
// display options, so show display field in the cell
$output .= htmlspecialchars($dispval);
} else {
// otherwise display data in the cell
$output .= htmlspecialchars($relationFieldValue);
}
$output .= '</a>';
return $output;
}
/**
* Transform edited values
*
* @param string $db db name
* @param string $table table name
* @param string[][] $editedValues transform columns list and new values
* @param string $file file containing the transformation plugin