Passed
Push — master ( 598f07...e683f3 )
by Maurício
08:21 queued 13s
created

InsertEdit::getGisFromWKBFunctions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 17
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 22
rs 9.7
ccs 0
cts 0
cp 0
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpMyAdmin;
6
7
use PhpMyAdmin\ConfigStorage\Relation;
8
use PhpMyAdmin\Dbal\ResultInterface;
9
use PhpMyAdmin\Html\Generator;
10
use PhpMyAdmin\Plugins\TransformationsPlugin;
11
use PhpMyAdmin\Utils\Gis;
12
13
use function __;
14
use function array_fill;
15
use function array_key_exists;
16
use function array_keys;
17
use function array_merge;
18
use function array_values;
19
use function bin2hex;
20
use function class_exists;
21
use function count;
22
use function current;
23
use function date;
24
use function explode;
25
use function htmlspecialchars;
26
use function implode;
27
use function in_array;
28
use function is_array;
29
use function is_file;
30
use function is_string;
31
use function max;
32
use function mb_stripos;
33
use function mb_strlen;
34
use function mb_strstr;
35
use function md5;
36
use function method_exists;
37
use function min;
38
use function password_hash;
39
use function preg_match;
40
use function preg_replace;
41
use function str_contains;
42
use function str_replace;
43
use function stripcslashes;
44
use function stripslashes;
45
use function strlen;
46
use function substr;
47
use function time;
48
use function trim;
49
50
use const ENT_COMPAT;
51
use const PASSWORD_DEFAULT;
52
53
class InsertEdit
54
{
55
    /** @var DatabaseInterface */
56
    private $dbi;
57
58
    /** @var Relation */
59
    private $relation;
60
61
    /** @var Transformations */
62
    private $transformations;
63
64
    /** @var FileListing */
65
    private $fileListing;
66
67
    /** @var Template */
68
    private $template;
69
70
    private const FUNC_OPTIONAL_PARAM = [
71
        'RAND',
72
        'UNIX_TIMESTAMP',
73
    ];
74
75
    private const FUNC_NO_PARAM = [
76
        'CONNECTION_ID',
77
        'CURRENT_USER',
78
        'CURDATE',
79
        'CURTIME',
80
        'CURRENT_DATE',
81
        'CURRENT_TIME',
82
        'DATABASE',
83
        'LAST_INSERT_ID',
84 196
        'NOW',
85
        'PI',
86 196
        'RAND',
87 196
        'SYSDATE',
88 196
        'UNIX_TIMESTAMP',
89 196
        'USER',
90 196
        'UTC_DATE',
91 49
        'UTC_TIME',
92
        'UTC_TIMESTAMP',
93
        'UUID',
94
        'UUID_SHORT',
95
        'VERSION',
96
    ];
97
98
    public function __construct(
99
        DatabaseInterface $dbi,
100
        Relation $relation,
101
        Transformations $transformations,
102
        FileListing $fileListing,
103
        Template $template
104 4
    ) {
105
        $this->dbi = $dbi;
106
        $this->relation = $relation;
107
        $this->transformations = $transformations;
108
        $this->fileListing = $fileListing;
109
        $this->template = $template;
110
    }
111 1
112 1
    /**
113 1
     * Retrieve form parameters for insert/edit form
114 4
     *
115 1
     * @param string     $db               name of the database
116 4
     * @param string     $table            name of the table
117
     * @param array|null $whereClauses     where clauses
118 4
     * @param array      $whereClauseArray array of where clauses
119 4
     * @param string     $errorUrl         error url
120 4
     *
121
     * @return array<string, string> array of insert/edit form parameters
122
     */
123
    public function getFormParametersForInsertForm(
124 4
        $db,
125 4
        $table,
126
        ?array $whereClauses,
127
        array $whereClauseArray,
128 4
        $errorUrl
129
    ): array {
130
        $formParams = [
131
            'db' => $db,
132
            'table' => $table,
133
            'goto' => $GLOBALS['goto'],
134
            'err_url' => $errorUrl,
135
            'sql_query' => $_POST['sql_query'] ?? '',
136
        ];
137
        if (isset($whereClauses)) {
138 8
            foreach ($whereClauseArray as $keyId => $whereClause) {
139
                $formParams['where_clause[' . $keyId . ']'] = trim($whereClause);
140 8
            }
141 4
        }
142
143
        if (isset($_POST['clause_is_unique'])) {
144 8
            $formParams['clause_is_unique'] = $_POST['clause_is_unique'];
145 4
        }
146
147
        return $formParams;
148 8
    }
149
150
    /**
151
     * Creates array of where clauses
152
     *
153
     * @param string[]|string|null $whereClause where clause
154
     *
155
     * @return string[] whereClauseArray array of where clauses
156
     */
157
    private function getWhereClauseArray($whereClause): array
158
    {
159
        if ($whereClause === null) {
160 8
            return [];
161
        }
162
163
        if (is_array($whereClause)) {
164
            return $whereClause;
165 8
        }
166 8
167 8
        return [$whereClause];
168 8
    }
169 8
170 2
    /**
171 8
     * Analysing where clauses array
172 8
     *
173 2
     * @param string[] $whereClauseArray array of where clauses
174 8
     * @param string   $table            name of the table
175 8
     * @param string   $db               name of the database
176
     *
177 8
     * @return array<int, string[]|ResultInterface[]|array<string, string|null>[]|bool>
178 8
     * @phpstan-return array{string[], ResultInterface[], array<string, string|null>[], bool}
179 2
     */
180 2
    private function analyzeWhereClauses(
181 2
        array $whereClauseArray,
182 2
        $table,
183 2
        $db
184
    ): array {
185 8
        $rows = [];
186 8
        $result = [];
187
        $whereClauses = [];
188
        $foundUniqueKey = false;
189
        foreach ($whereClauseArray as $keyId => $whereClause) {
190
            $localQuery = 'SELECT * FROM '
191
                . Util::backquote($db) . '.'
192
                . Util::backquote($table)
193 8
                . ' WHERE ' . $whereClause . ';';
194 2
            $result[$keyId] = $this->dbi->query($localQuery);
195 2
            $rows[$keyId] = $result[$keyId]->fetchAssoc();
196 2
197
            $whereClauses[$keyId] = str_replace('\\', '\\\\', $whereClause);
198
            $hasUniqueCondition = $this->showEmptyResultMessageOrSetUniqueCondition(
199
                $rows,
200
                $keyId,
201
                $whereClauseArray,
202
                $localQuery,
203
                $result
204
            );
205
            if (! $hasUniqueCondition) {
206
                continue;
207
            }
208
209 12
            $foundUniqueKey = true;
210
        }
211
212
        return [
213
            $whereClauses,
214
            $result,
215
            $rows,
216
            $foundUniqueKey,
217 12
        ];
218 8
    }
219 8
220 8
    /**
221 8
     * Show message for empty result or set the unique_condition
222 2
     *
223
     * @param array             $rows             MySQL returned rows
224
     * @param string            $keyId            ID in current key
225
     * @param array             $whereClauseArray array of where clauses
226
     * @param string            $localQuery       query performed
227
     * @param ResultInterface[] $result           MySQL result handle
228
     */
229
    private function showEmptyResultMessageOrSetUniqueCondition(
230 8
        array $rows,
231
        $keyId,
232
        array $whereClauseArray,
233 8
        $localQuery,
234
        array $result
235 8
    ): bool {
236 8
        // No row returned
237 2
        if (! $rows[$keyId]) {
238 8
            unset($rows[$keyId], $whereClauseArray[$keyId]);
239 2
            ResponseRenderer::getInstance()->addHTML(
240
                Generator::getMessage(
241
                    __('MySQL returned an empty result set (i.e. zero rows).'),
242 8
                    $localQuery
243
                )
244
            );
245
            /**
246
             * @todo not sure what should be done at this point, but we must not
247
             * exit if we want the message to be displayed
248
             */
249
250
            return false;
251
        }
252
253 20
        $meta = $this->dbi->getFieldsMeta($result[$keyId]);
254
255 20
        [$uniqueCondition] = Util::getUniqueCondition(
256 20
            count($meta),
257 20
            $meta,
258
            $rows[$keyId],
259
            true
260 20
        );
261
262
        return (bool) $uniqueCondition;
263 20
    }
264 5
265
    /**
266
     * No primary key given, just load first row
267
     *
268
     * @param string $table name of the table
269
     * @param string $db    name of the database
270
     *
271
     * @return array<int, ResultInterface|false[]>
272
     * @phpstan-return array{ResultInterface, false[]}
273
     */
274
    private function loadFirstRow($table, $db): array
275
    {
276 4
        $result = $this->dbi->query(
277
            'SELECT * FROM ' . Util::backquote($db)
278
            . '.' . Util::backquote($table) . ' LIMIT 1;'
279
        );
280 4
        // Can be a string on some old configuration storage settings
281 4
        $rows = array_fill(0, (int) $GLOBALS['cfg']['InsertRows'], false);
282
283
        return [
284 4
            $result,
285 4
            $rows,
286
        ];
287
    }
288 4
289
    /**
290
     * Add some url parameters
291
     *
292
     * @param array $urlParams        containing $db and $table as url parameters
293
     * @param array $whereClauseArray where clauses array
294
     *
295
     * @return array Add some url parameters to $url_params array and return it
296
     */
297
    public function urlParamsInEditMode(
298
        array $urlParams,
299
        array $whereClauseArray
300 16
    ): array {
301
        foreach ($whereClauseArray as $whereClause) {
302 16
            $urlParams['where_clause'] = trim($whereClause);
303
        }
304 16
305 16
        if (! empty($_POST['sql_query'])) {
306 16
            $urlParams['sql_query'] = $_POST['sql_query'];
307 16
        }
308 16
309 16
        return $urlParams;
310 16
    }
311 16
312 16
    /**
313
     * Show type information or function selectors in Insert/Edit
314
     *
315 16
     * @param string $which     function|type
316 16
     * @param array  $urlParams containing url parameters
317
     * @param bool   $isShow    whether to show the element in $which
318 16
     *
319 4
     * @return string an HTML snippet
320 4
     */
321 4
    public function showTypeOrFunction($which, array $urlParams, $isShow): string
322 1
    {
323
        $params = [];
324
325 16
        switch ($which) {
326 16
            case 'function':
327 16
                $params['ShowFunctionFields'] = ($isShow ? 0 : 1);
328 16
                $params['ShowFieldTypesInDataEditView'] = $GLOBALS['cfg']['ShowFieldTypesInDataEditView'];
329 4
                break;
330
            case 'type':
331
                $params['ShowFieldTypesInDataEditView'] = ($isShow ? 0 : 1);
332
                $params['ShowFunctionFields'] = $GLOBALS['cfg']['ShowFunctionFields'];
333
                break;
334
        }
335
336
        $params['goto'] = Url::getFromRoute('/sql');
337
        $thisUrlParams = array_merge($urlParams, $params);
338
339 16
        if (! $isShow) {
340
            return ' : <a href="' . Url::getFromRoute('/table/change') . '" data-post="'
341 16
                . Url::getCommon($thisUrlParams, '', false) . '">'
342 16
                . $this->showTypeOrFunctionLabel($which)
343 16
                . '</a>';
344
        }
345 16
346 16
        return '<th><a href="' . Url::getFromRoute('/table/change') . '" data-post="'
347
            . Url::getCommon($thisUrlParams, '', false)
348
            . '" title="' . __('Hide') . '">'
349
            . $this->showTypeOrFunctionLabel($which)
350
            . '</a></th>';
351
    }
352
353
    /**
354
     * Show type information or function selectors labels in Insert/Edit
355
     *
356
     * @param string $which function|type
357
     *
358
     * @return string an HTML snippet
359
     */
360
    private function showTypeOrFunctionLabel($which): string
361 16
    {
362
        switch ($which) {
363
            case 'function':
364
                return __('Function');
365
366 16
            case 'type':
367
                return __('Type');
368 16
        }
369 16
370 16
        return '';
371 16
    }
372 4
373
    /**
374 16
     * Analyze the table column array
375
     *
376
     * @param array $column        description of column in given table
377
     * @param array $commentsMap   comments for every column that has a comment
378 16
     * @param bool  $timestampSeen whether a timestamp has been seen
379 4
     *
380
     * @return array                   description of column in given table
381 16
     */
382
    private function analyzeTableColumnsArray(
383
        array $column,
384
        array $commentsMap,
385
        $timestampSeen
386
    ) {
387 16
        $column['Field_md5'] = md5($column['Field']);
388 4
        // True_Type contains only the type (stops at first bracket)
389
        $column['True_Type'] = preg_replace('@\(.*@s', '', $column['Type']);
390 16
        $column['len'] = preg_match('@float|double@', $column['Type']) ? 100 : -1;
391
        $column['Field_title'] = $this->getColumnTitle($column, $commentsMap);
392
        $column['is_binary'] = $this->isColumn(
393
            $column,
394
            [
395
                'binary',
396 16
                'varbinary',
397 16
            ]
398 16
        );
399 16
        $column['is_blob'] = $this->isColumn(
400
            $column,
401 16
            [
402
                'blob',
403
                'tinyblob',
404
                'mediumblob',
405
                'longblob',
406
            ]
407
        );
408
        $column['is_char'] = $this->isColumn(
409
            $column,
410
            [
411
                'char',
412 20
                'varchar',
413
            ]
414 20
        );
415
416 4
        [
417 4
            $column['pma_type'],
418
            $column['wrap'],
419
            $column['first_timestamp'],
420 20
        ] = $this->getEnumSetAndTimestampColumns($column, $timestampSeen);
421
422
        return $column;
423
    }
424
425
    /**
426
     * Retrieve the column title
427
     *
428
     * @param array $column      description of column in given table
429
     * @param array $commentsMap comments for every column that has a comment
430
     *
431 20
     * @return string              column title
432
     */
433 20
    private function getColumnTitle(array $column, array $commentsMap): string
434 20
    {
435 8
        if (isset($commentsMap[$column['Field']])) {
436
            return '<span style="border-bottom: 1px dashed black;" title="'
437
                . htmlspecialchars($commentsMap[$column['Field']]) . '">'
438
                . htmlspecialchars($column['Field']) . '</span>';
439 20
        }
440
441
        return htmlspecialchars($column['Field']);
442
    }
443
444
    /**
445
     * check whether the column is of a certain type
446
     * the goal is to ensure that types such as "enum('one','two','binary',..)"
447
     * or "enum('one','two','varbinary',..)" are not categorized as binary
448
     *
449
     * @param array    $column description of column in given table
450
     * @param string[] $types  the types to verify
451 20
     */
452
    public function isColumn(array $column, array $types): bool
453 20
    {
454 20
        foreach ($types as $oneType) {
455
            if (mb_stripos($column['Type'], $oneType) === 0) {
456 4
                return true;
457
            }
458
        }
459
460
        return false;
461 20
    }
462
463 4
    /**
464
     * Retrieve set, enum, timestamp table columns
465
     *
466
     * @param array $column        description of column in given table
467
     * @param bool  $timestampSeen whether a timestamp has been seen
468 20
     *
469
     * @return array $column['pma_type'], $column['wrap'], $column['first_timestamp']
470 4
     * @psalm-return array{0: mixed, 1: string, 2: bool}
471 1
     */
472 1
    private function getEnumSetAndTimestampColumns(array $column, $timestampSeen)
473
    {
474
        switch ($column['True_Type']) {
475
            case 'set':
476
                return [
477 20
                    'set',
478 5
                    '',
479
                    false,
480
                ];
481
482
            case 'enum':
483
                return [
484
                    'enum',
485
                    '',
486
                    false,
487
                ];
488
489
            case 'timestamp':
490
                return [
491 16
                    $column['Type'],
492
                    ' text-nowrap',
493
                    ! $timestampSeen, // can only occur once per table
494
                ];
495
496 16
            default:
497 16
                return [
498 4
                    $column['Type'],
499 4
                    ' text-nowrap',
500
                    false,
501 4
                ];
502
        }
503 16
    }
504 4
505 16
    /**
506
     * Retrieve the nullify code for the null column
507 4
     *
508 12
     * @param array $column      description of column in given table
509
     * @param array $foreigners  keys into foreign fields
510
     * @param array $foreignData data about the foreign keys
511
     */
512 12
    private function getNullifyCodeForNullColumn(
513
        array $column,
514
        array $foreigners,
515 16
        array $foreignData
516
    ): string {
517
        $foreigner = $this->relation->searchColumnInForeigners($foreigners, $column['Field']);
518
        if (mb_strstr($column['True_Type'], 'enum')) {
519
            if (mb_strlen((string) $column['Type']) > 20) {
520
                $nullifyCode = '1';
521
            } else {
522
                $nullifyCode = '2';
523
            }
524
        } elseif (mb_strstr($column['True_Type'], 'set')) {
525
            $nullifyCode = '3';
526
        } elseif ($foreigner && $foreignData['foreign_link'] == false) {
527
            // foreign key in a drop-down
528
            $nullifyCode = '4';
529
        } elseif ($foreigner && $foreignData['foreign_link'] == true) {
530
            // foreign key with a browsing icon
531
            $nullifyCode = '6';
532
        } else {
533
            $nullifyCode = '5';
534
        }
535
536 8
        return $nullifyCode;
537
    }
538
539
    /**
540
     * Get HTML textarea for insert form
541
     *
542
     * @param array  $column              column information
543
     * @param string $backupField         hidden input field
544
     * @param string $columnNameAppendix  the name attribute
545
     * @param string $onChangeClause      onchange clause for fields
546
     * @param int    $tabindex            tab index
547
     * @param int    $tabindexForValue    offset for the values tabindex
548
     * @param int    $idindex             id index
549 8
     * @param string $textDir             text direction
550 8
     * @param string $specialCharsEncoded replaced char if the string starts
551 8
     *                                      with a \r\n pair (0x0d0a) add an extra \n
552
     * @param string $dataType            the html5 data-* attribute type
553 8
     * @param bool   $readOnly            is column read only or not
554
     *
555
     * @return string                       an html snippet
556
     */
557
    private function getTextarea(
558 8
        array $column,
559 8
        $backupField,
560 8
        $columnNameAppendix,
561 8
        $onChangeClause,
562 8
        $tabindex,
563
        $tabindexForValue,
564
        $idindex,
565
        $textDir,
566
        $specialCharsEncoded,
567
        $dataType,
568 8
        $readOnly
569 2
    ): string {
570 2
        $theClass = '';
571 8
        $textAreaRows = $GLOBALS['cfg']['TextareaRows'];
572 8
        $textareaCols = $GLOBALS['cfg']['TextareaCols'];
573 2
574 2
        if ($column['is_char']) {
575 2
            /**
576 2
             * @todo clarify the meaning of the "textfield" class and explain
577 8
             *       why character columns have the "char" class instead
578 8
             */
579 2
            $theClass = 'char charField';
580 2
            $textAreaRows = $GLOBALS['cfg']['CharTextareaRows'];
581 2
            $textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
582
            $extractedColumnspec = Util::extractColumnSpec($column['Type']);
583
            $maxlength = $extractedColumnspec['spec_in_brackets'];
584
        } elseif ($GLOBALS['cfg']['LongtextDoubleTextarea'] && mb_strstr($column['pma_type'], 'longtext')) {
585
            $textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
586
            $textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
587
        }
588
589
        return $backupField . "\n"
590
            . '<textarea name="fields' . $columnNameAppendix . '"'
591
            . ' class="' . $theClass . '"'
592 4
            . ($readOnly ? ' readonly="readonly"' : '')
593
            . (isset($maxlength) ? ' data-maxlength="' . $maxlength . '"' : '')
594 4
            . ' rows="' . $textAreaRows . '"'
595 4
            . ' cols="' . $textareaCols . '"'
596 4
            . ' dir="' . $textDir . '"'
597 1
            . ' id="field_' . $idindex . '_3"'
598 4
            . ($onChangeClause ? ' ' . $onChangeClause : '')
599
            . ' tabindex="' . ($tabindex + $tabindexForValue) . '"'
600
            . ' data-type="' . $dataType . '">'
601
            . $specialCharsEncoded
602 4
            . '</textarea>';
603
    }
604
605
    /**
606
     * Get column values
607
     *
608
     * @param string[] $enum_set_values
609
     *
610
     * @return array column values as an associative array
611
     * @psalm-return list<array{html: string, plain: string}>
612
     */
613 4
    private function getColumnEnumValues(array $enum_set_values): array
614
    {
615
        $values = [];
616
        foreach ($enum_set_values as $val) {
617 4
            $values[] = [
618 4
                'plain' => $val,
619 4
                'html' => htmlspecialchars($val),
620 4
            ];
621 1
        }
622 4
623
        return $values;
624
    }
625
626 4
    /**
627
     * Retrieve column 'set' value and select size
628
     *
629
     * @param array    $column          description of column in given table
630 4
     * @param string[] $enum_set_values
631 4
     *
632
     * @return array $column['values'], $column['select_size']
633
     */
634
    private function getColumnSetValueAndSelectSize(
635
        array $column,
636
        array $enum_set_values
637
    ): array {
638
        if (! isset($column['values'])) {
639
            $column['values'] = [];
640
            foreach ($enum_set_values as $val) {
641
                $column['values'][] = [
642
                    'plain' => $val,
643
                    'html' => htmlspecialchars($val),
644
                ];
645
            }
646
647
            $column['select_size'] = min(4, count($column['values']));
648
        }
649
650
        return [
651 20
            $column['values'],
652
            $column['select_size'],
653
        ];
654
    }
655
656
    /**
657
     * Get HTML input type
658
     *
659
     * @param array  $column             description of column in given table
660
     * @param string $columnNameAppendix the name attribute
661
     * @param string $specialChars       special characters
662
     * @param int    $fieldsize          html field size
663 20
     * @param string $onChangeClause     onchange clause for fields
664
     * @param int    $tabindex           tab index
665 20
     * @param int    $tabindexForValue   offset for the values tabindex
666 20
     * @param int    $idindex            id index
667 4
     * @param string $dataType           the html5 data-* attribute type
668 20
     * @param bool   $readOnly           is column read only or not
669
     *
670 20
     * @return string                       an html snippet
671 12
     */
672
    private function getHtmlInput(
673
        array $column,
674
        $columnNameAppendix,
675 20
        $specialChars,
676 20
        $fieldsize,
677
        $onChangeClause,
678
        $tabindex,
679
        $tabindexForValue,
680
        $idindex,
681
        $dataType,
682
        $readOnly
683
    ): string {
684
        $theClass = 'textfield';
685
        // verify True_Type which does not contain the parentheses and length
686
        if (! $readOnly) {
687
            if ($column['True_Type'] === 'date') {
688 5
                $theClass .= ' datefield';
689 5
            } elseif ($column['True_Type'] === 'time') {
690 20
                $theClass .= ' timefield';
691
            } elseif ($column['True_Type'] === 'datetime' || $column['True_Type'] === 'timestamp') {
692 20
                $theClass .= ' datetimefield';
693 20
            }
694 20
        }
695 5
696 5
        $inputMinMax = '';
697 20
        if (in_array($column['True_Type'], $this->dbi->types->getIntegerTypes())) {
698 5
            $extractedColumnspec = Util::extractColumnSpec($column['Type']);
699
            $isUnsigned = $extractedColumnspec['unsigned'];
700
            $minMaxValues = $this->dbi->types->getIntegerRange($column['True_Type'], ! $isUnsigned);
701
            $inputMinMax = 'min="' . $minMaxValues[0] . '" '
702
                . 'max="' . $minMaxValues[1] . '"';
703
            $dataType = 'INT';
704
        }
705
706
        // do not use the 'date' or 'time' types here; they have no effect on some
707
        // browsers and create side effects (see bug #4218)
708
        return '<input type="text"'
709
            . ' name="fields' . $columnNameAppendix . '"'
710
            . ' value="' . $specialChars . '" size="' . $fieldsize . '"'
711
            . (isset($column['is_char']) && $column['is_char']
712
                ? ' data-maxlength="' . $fieldsize . '"'
713
                : '')
714
            . ($readOnly ? ' readonly="readonly"' : '')
715
            . ($inputMinMax ? ' ' . $inputMinMax : '')
716
            . ' data-type="' . $dataType . '"'
717
            . ' class="' . $theClass . '" ' . $onChangeClause
718
            . ' tabindex="' . ($tabindex + $tabindexForValue) . '"'
719
            . ' id="field_' . $idindex . '_3">';
720
    }
721
722
    /**
723
     * Get HTML select option for upload
724
     *
725
     * @param string $vkey         [multi_edit]['row_id']
726
     * @param string $fieldHashMd5 array index as an MD5 to avoid having special characters
727
     *
728
     * @return string an HTML snippet
729
     */
730
    private function getSelectOptionForUpload(string $vkey, string $fieldHashMd5): string
731
    {
732
        $files = $this->fileListing->getFileSelectOptions(
733
            Util::userDir((string) ($GLOBALS['cfg']['UploadDir'] ?? ''))
734
        );
735
736
        if ($files === false) {
0 ignored issues
show
introduced by
The condition $files === false is always true.
Loading history...
737
            return '<span style="color:red">' . __('Error') . '</span><br>' . "\n"
738
                . __('The directory you set for upload work cannot be reached.') . "\n";
739
        }
740
741
        if ($files === '') {
742
            return '';
743 4
        }
744
745
        return "<br>\n"
746
            . '<i>' . __('Or') . '</i> '
747
            . __('web server upload directory:') . '<br>' . "\n"
748
            . '<select size="1" name="fields_uploadlocal'
749
            . $vkey . '[' . $fieldHashMd5 . ']">' . "\n"
750 1
            . '<option value="" selected="selected"></option>' . "\n"
751 1
            . $files
752
            . '</select>' . "\n";
753
    }
754
755
    /**
756
     * Retrieve the maximum upload file size
757 4
     *
758 4
     * @param string $pma_type           column type
759 4
     * @param int    $biggestMaxFileSize biggest max file size for uploading
760
     *
761
     * @return array an html snippet and $biggest_max_file_size
762 4
     * @psalm-return array{non-empty-string, int}
763
     */
764
    private function getMaxUploadSize(string $pma_type, $biggestMaxFileSize): array
765 4
    {
766 4
        // find maximum upload size, based on field type
767
        /**
768
         * @todo with functions this is not so easy, as you can basically
769
         * process any data with function like MD5
770 4
         */
771 1
        $maxFieldSizes = [
772
            'tinyblob' => 256,
773
            'blob' => 65536,
774
            'mediumblob' => 16777216,
775
            'longblob' => 4294967296,// yeah, really
776
        ];
777
778
        $thisFieldMaxSize = (int) $GLOBALS['config']->get('max_upload_size'); // from PHP max
779
        if ($thisFieldMaxSize > $maxFieldSizes[$pma_type]) {
780
            $thisFieldMaxSize = $maxFieldSizes[$pma_type];
781
        }
782
783
        $htmlOutput = Util::getFormattedMaximumUploadSize($thisFieldMaxSize) . "\n";
784
        // do not generate here the MAX_FILE_SIZE, because we should
785
        // put only one in the form to accommodate the biggest field
786
        if ($thisFieldMaxSize > $biggestMaxFileSize) {
787
            $biggestMaxFileSize = $thisFieldMaxSize;
788
        }
789
790
        return [
791
            $htmlOutput,
792
            $biggestMaxFileSize,
793
        ];
794
    }
795
796
    /**
797
     * Get HTML for the Value column of other datatypes
798
     * (here, "column" is used in the sense of HTML column in HTML table)
799
     *
800 16
     * @param array  $column              description of column in given table
801
     * @param string $defaultCharEditing  default char editing mode which is stored
802
     *                                       in the config.inc.php script
803
     * @param string $backupField         hidden input field
804
     * @param string $columnNameAppendix  the name attribute
805
     * @param string $onChangeClause      onchange clause for fields
806
     * @param int    $tabindex            tab index
807
     * @param string $specialChars        special characters
808
     * @param int    $tabindexForValue    offset for the values tabindex
809
     * @param int    $idindex             id index
810
     * @param string $textDir             text direction
811
     * @param string $specialCharsEncoded replaced char if the string starts
812
     *                                      with a \r\n pair (0x0d0a) add an extra \n
813
     * @param string $data                data to edit
814
     * @param array  $extractedColumnspec associative array containing type,
815
     *                                      spec_in_brackets and possibly
816
     *                                      enum_set_values (another array)
817 16
     * @param bool   $readOnly            is column read only or not
818 16
     *
819
     * @return string an html snippet
820 16
     */
821 13
    private function getValueColumnForOtherDatatypes(
822 16
        array $column,
823 4
        $defaultCharEditing,
824 4
        $backupField,
825 1
        $columnNameAppendix,
826 1
        $onChangeClause,
827 1
        $tabindex,
828 1
        $specialChars,
829 1
        $tabindexForValue,
830 1
        $idindex,
831 1
        $textDir,
832 1
        $specialCharsEncoded,
833 1
        $data,
834 1
        array $extractedColumnspec,
835 1
        $readOnly
836
    ): string {
837
        // HTML5 data-* attribute data-type
838 16
        $dataType = $this->dbi->types->getTypeClass($column['True_Type']);
839 4
        $fieldsize = $this->getColumnSize($column, $extractedColumnspec['spec_in_brackets']);
840 4
841 4
        $isTextareaRequired = $column['is_char']
842 4
            && ($GLOBALS['cfg']['CharEditing'] === 'textarea' || str_contains($data, "\n"));
843 4
        if ($isTextareaRequired) {
844 4
            $GLOBALS['cfg']['CharEditing'] = $defaultCharEditing;
845 4
            $htmlField = $this->getTextarea(
846 4
                $column,
847 4
                $backupField,
848 4
                $columnNameAppendix,
849
                $onChangeClause,
850
                $tabindex,
851
                $tabindexForValue,
852 16
                $idindex,
853 4
                $textDir,
854 4
                $specialCharsEncoded,
855 4
                $dataType,
856 4
                $readOnly
857 4
            );
858
        } else {
859
            $htmlField = $this->getHtmlInput(
860
                $column,
861
                $columnNameAppendix,
862
                $specialChars,
863
                $fieldsize,
864
                $onChangeClause,
865
                $tabindex,
866
                $tabindexForValue,
867
                $idindex,
868
                $dataType,
869 20
                $readOnly
870
            );
871 20
        }
872 8
873 8
        return $this->template->render('table/insert/value_column_for_other_datatype', [
874
            'html_field' => $htmlField,
875
            'backup_field' => $backupField,
876
            'is_textarea' => $isTextareaRequired,
877
            'columnNameAppendix' => $columnNameAppendix,
878 8
            'column' => $column,
879
        ]);
880
    }
881
882
    /**
883
     * Get the field size
884
     *
885
     * @param array  $column         description of column in given table
886 20
     * @param string $specInBrackets text in brackets inside column definition
887
     *
888
     * @return int field size
889 20
     */
890 20
    private function getColumnSize(array $column, string $specInBrackets): int
891 20
    {
892
        if ($column['is_char']) {
893
            $fieldsize = (int) $specInBrackets;
894
            if ($fieldsize > $GLOBALS['cfg']['MaxSizeForInputField']) {
895
                /**
896
                 * This case happens for CHAR or VARCHAR columns which have
897
                 * a size larger than the maximum size for input field.
898
                 */
899
                $GLOBALS['cfg']['CharEditing'] = 'textarea';
900
            }
901
        } else {
902
            /**
903
             * This case happens for example for INT or DATE columns;
904
             * in these situations, the value returned in $column['len']
905 4
             * seems appropriate.
906
             */
907
            $fieldsize = $column['len'];
908
        }
909
910
        return min(
911 4
            max($fieldsize, $GLOBALS['cfg']['MinSizeForInputField']),
912 1
            $GLOBALS['cfg']['MaxSizeForInputField']
913 1
        );
914 1
    }
915 1
916 4
    /**
917 4
     * get html for continue insertion form
918 4
     *
919 4
     * @param string $table            name of the table
920
     * @param string $db               name of the database
921
     * @param array  $whereClauseArray array of where clauses
922
     * @param string $errorUrl         error url
923
     *
924
     * @return string                   an html snippet
925
     */
926
    public function getContinueInsertionForm(
927
        $table,
928 4
        $db,
929
        array $whereClauseArray,
930 4
        $errorUrl
931 4
    ): string {
932
        return $this->template->render('table/insert/continue_insertion_form', [
933
            'db' => $db,
934 4
            'table' => $table,
935 4
            'where_clause_array' => $whereClauseArray,
936
            'err_url' => $errorUrl,
937
            'goto' => $GLOBALS['goto'],
938
            'sql_query' => $_POST['sql_query'] ?? null,
939
            'has_where_clause' => isset($_POST['where_clause']),
940 4
            'insert_rows_default' => $GLOBALS['cfg']['InsertRows'],
941
        ]);
942 4
    }
943 4
944 4
    /**
945
     * @param string[]|string|null $whereClause
946
     *
947
     * @psalm-pure
948 4
     */
949
    public static function isWhereClauseNumeric($whereClause): bool
950
    {
951
        if ($whereClause === null) {
952
            return false;
953
        }
954
955
        if (! is_array($whereClause)) {
956
            $whereClause = [$whereClause];
957
        }
958 12
959
        // If we have just numeric primary key, we can also edit next
960 12
        // we are looking for `table_name`.`field_name` = numeric_value
961 12
        foreach ($whereClause as $clause) {
962
            // preg_match() returns 1 if there is a match
963 12
            $isNumeric = preg_match('@^[\s]*`[^`]*`[\.]`[^`]*` = [0-9]+@', $clause) === 1;
964 12
            if ($isNumeric) {
965
                return true;
966
            }
967 12
        }
968 12
969
        return false;
970
    }
971 12
972
    /**
973 12
     * Get table head and table foot for insert row table
974 3
     *
975 3
     * @param array $urlParams url parameters
976
     *
977
     * @return string           an html snippet
978
     */
979
    private function getHeadAndFootOfInsertRowTable(array $urlParams): string
980
    {
981
        $type = '';
982
        $function = '';
983
984
        if ($GLOBALS['cfg']['ShowFieldTypesInDataEditView']) {
985
            $type = $this->showTypeOrFunction('type', $urlParams, true);
986
        }
987
988
        if ($GLOBALS['cfg']['ShowFunctionFields']) {
989
            $function = $this->showTypeOrFunction('function', $urlParams, true);
990
        }
991
992
        $template = new Template();
993
994 4
        return $template->render('table/insert/get_head_and_foot_of_insert_row_table', [
995
            'type' => $type,
996
            'function' => $function,
997
        ]);
998
    }
999
1000
    /**
1001
     * Prepares the field value and retrieve special chars, backup field and data array
1002 4
     *
1003 4
     * @param array  $currentRow          a row of the table
1004 4
     * @param array  $column              description of column in given table
1005
     * @param array  $extractedColumnspec associative array containing type,
1006 4
     *                                      spec_in_brackets and possibly
1007 4
     *                                      enum_set_values (another array)
1008 4
     * @param array  $gisDataTypes        list of GIS data types
1009 4
     * @param string $columnNameAppendix  string to append to column name in input
1010 4
     * @param bool   $asIs                use the data as is, used in repopulating
1011 4
     *
1012 4
     * @return array $real_null_value, $data, $special_chars, $backup_field,
1013 4
     *               $special_chars_encoded
1014 4
     */
1015 4
    private function getSpecialCharsAndBackupFieldForExistingRow(
1016 4
        array $currentRow,
1017
        array $column,
1018
        array $extractedColumnspec,
1019 4
        array $gisDataTypes,
1020 4
        $columnNameAppendix,
1021 4
        $asIs
1022 4
    ) {
1023
        $specialCharsEncoded = '';
1024
        $data = null;
1025
        $realNullValue = false;
1026
        // (we are editing)
1027
        if (! isset($currentRow[$column['Field']])) {
1028 4
            $realNullValue = true;
1029
            $currentRow[$column['Field']] = '';
1030 4
            $specialChars = '';
1031
            $data = $currentRow[$column['Field']];
1032 4
        } elseif ($column['True_Type'] === 'bit') {
1033 4
            $specialChars = $asIs
1034
                ? $currentRow[$column['Field']]
1035
                : Util::printableBitValue(
1036 4
                    (int) $currentRow[$column['Field']],
1037 4
                    (int) $extractedColumnspec['spec_in_brackets']
1038
                );
1039 4
        } elseif (
1040
            (substr($column['True_Type'], 0, 9) === 'timestamp'
1041
                || $column['True_Type'] === 'datetime'
1042 4
                || $column['True_Type'] === 'time')
1043
            && (str_contains($currentRow[$column['Field']], '.'))
1044
        ) {
1045
            $currentRow[$column['Field']] = $asIs
1046 4
                ? $currentRow[$column['Field']]
1047
                : Util::addMicroseconds($currentRow[$column['Field']]);
1048 4
            $specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT);
1049
        } elseif (in_array($column['True_Type'], $gisDataTypes)) {
1050
            // Convert gis data to Well Know Text format
1051
            $currentRow[$column['Field']] = $asIs
1052
                ? $currentRow[$column['Field']]
1053 4
                : Gis::convertToWellKnownText($currentRow[$column['Field']], true);
1054 4
            $specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT);
1055 4
        } else {
1056
            // special binary "characters"
1057
            if ($column['is_binary'] || ($column['is_blob'] && $GLOBALS['cfg']['ProtectBinary'] !== 'all')) {
1058
                $currentRow[$column['Field']] = $asIs
1059
                    ? $currentRow[$column['Field']]
1060
                    : bin2hex($currentRow[$column['Field']]);
1061
            }
1062
1063 1
            $specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT);
1064 1
1065 4
            //We need to duplicate the first \n or otherwise we will lose
1066
            //the first newline entered in a VARCHAR or TEXT column
1067
            $specialCharsEncoded = Util::duplicateFirstNewline($specialChars);
1068 4
1069 1
            $data = $currentRow[$column['Field']];
1070 1
        }
1071 1
1072 1
        //when copying row, it is useful to empty auto-increment column
1073
        // to prevent duplicate key error
1074
        if (isset($_POST['default_action']) && $_POST['default_action'] === 'insert') {
1075
            if ($column['Key'] === 'PRI' && str_contains($column['Extra'], 'auto_increment')) {
1076
                $data = $specialCharsEncoded = $specialChars = null;
1077
            }
1078
        }
1079
1080
        // If a timestamp field value is not included in an update
1081
        // statement MySQL auto-update it to the current timestamp;
1082
        // however, things have changed since MySQL 4.1, so
1083
        // it's better to set a fields_prev in this situation
1084
        $backupField = '<input type="hidden" name="fields_prev'
1085 16
            . $columnNameAppendix . '" value="'
1086
            . htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT) . '">';
1087
1088 16
        return [
1089 12
            $realNullValue,
1090 12
            $specialCharsEncoded,
1091 12
            $specialChars,
1092
            $data,
1093 8
            $backupField,
1094 8
        ];
1095
    }
1096
1097 16
    /**
1098
     * display default values
1099 16
     *
1100 4
     * @param array $column description of column in given table
1101 16
     *
1102 4
     * @return array $real_null_value, $data, $special_chars,
1103 16
     *               $backup_field, $special_chars_encoded
1104
     * @psalm-return array{bool, mixed, string, string, string}
1105 16
     */
1106 8
    private function getSpecialCharsAndBackupFieldForInsertingMode(
1107 8
        array $column
1108
    ) {
1109 12
        if (! isset($column['Default'])) {
1110
            $column['Default'] = '';
1111
            $realNullValue = true;
1112 16
            $data = '';
1113
        } else {
1114
            $realNullValue = false;
1115 16
            $data = $column['Default'];
1116 4
        }
1117 4
1118 4
        $trueType = $column['True_Type'];
1119 4
1120
        if ($trueType === 'bit') {
1121
            $specialChars = Util::convertBitDefaultValue($column['Default']);
1122
        } elseif (substr($trueType, 0, 9) === 'timestamp' || $trueType === 'datetime' || $trueType === 'time') {
1123
            $specialChars = Util::addMicroseconds($column['Default']);
1124
        } elseif ($trueType === 'binary' || $trueType === 'varbinary') {
1125
            $specialChars = bin2hex($column['Default']);
1126
        } elseif (substr($trueType, -4) === 'text') {
1127
            $textDefault = substr($column['Default'], 1, -1);
1128
            $specialChars = stripcslashes($textDefault !== false ? $textDefault : $column['Default']);
1129 4
        } else {
1130
            $specialChars = htmlspecialchars($column['Default']);
1131 4
        }
1132
1133 4
        $specialCharsEncoded = Util::duplicateFirstNewline($specialChars);
1134
1135 4
        return [
1136 4
            $realNullValue,
1137 4
            $data,
1138 4
            $specialChars,
1139 4
            '',
1140 4
            $specialCharsEncoded,
1141
        ];
1142
    }
1143 4
1144 4
    /**
1145 4
     * Prepares the update/insert of a row
1146
     *
1147
     * @return array $loop_array, $using_key, $is_insert, $is_insertignore
1148 4
     * @psalm-return array{array, bool, bool, bool}
1149 4
     */
1150
    public function getParamsForUpdateOrInsert()
1151
    {
1152 4
        if (isset($_POST['where_clause'])) {
1153 4
            // we were editing something => use the WHERE clause
1154
            $loopArray = is_array($_POST['where_clause'])
1155
                ? $_POST['where_clause']
1156 4
                : [$_POST['where_clause']];
1157 1
            $usingKey = true;
1158 1
            $isInsert = isset($_POST['submit_type'])
1159 1
                && ($_POST['submit_type'] === 'insert'
1160
                    || $_POST['submit_type'] === 'showinsert'
1161
                    || $_POST['submit_type'] === 'insertignore');
1162
        } else {
1163
            // new row => use indexes
1164
            $loopArray = [];
1165
            if (! empty($_POST['fields'])) {
1166
                $loopArray = array_keys($_POST['fields']['multi_edit']);
1167
            }
1168 4
1169
            $usingKey = false;
1170 4
            $isInsert = true;
1171 4
        }
1172 4
1173
        $isInsertIgnore = isset($_POST['submit_type'])
1174 4
            && $_POST['submit_type'] === 'insertignore';
1175 4
1176 4
        return [
1177
            $loopArray,
1178
            $usingKey,
1179 4
            $isInsert,
1180 4
            $isInsertIgnore,
1181 1
        ];
1182 1
    }
1183 1
1184
    /**
1185 4
     * set $_SESSION for edit_next
1186
     *
1187
     * @param string $oneWhereClause one where clause from where clauses array
1188
     */
1189 4
    public function setSessionForEditNext($oneWhereClause): void
1190 1
    {
1191
        $localQuery = 'SELECT * FROM ' . Util::backquote($GLOBALS['db'])
1192
            . '.' . Util::backquote($GLOBALS['table']) . ' WHERE '
1193
            . str_replace('` =', '` >', $oneWhereClause) . ' LIMIT 1;';
1194
1195
        $res = $this->dbi->query($localQuery);
1196
        $row = $res->fetchRow();
1197
        $meta = $this->dbi->getFieldsMeta($res);
1198
        // must find a unique condition based on unique key,
1199
        // not a combination of all fields
1200 4
        [$uniqueCondition] = Util::getUniqueCondition(
1201
            count($meta),
1202 1
            $meta,
1203 1
            $row,
1204
            true
1205
        );
1206
        if (! $uniqueCondition) {
1207 4
            return;
1208 4
        }
1209
1210
        $_SESSION['edit_next'] = $uniqueCondition;
1211 4
    }
1212 4
1213
    /**
1214
     * set $goto_include variable for different cases and retrieve like,
1215 4
     * if $GLOBALS['goto'] empty, if $goto_include previously not defined
1216
     * and new_insert, same_insert, edit_next
1217
     *
1218 4
     * @param string|false $gotoInclude store some script for include, otherwise it is
1219
     *                                   boolean false
1220
     */
1221
    public function getGotoInclude($gotoInclude): string
1222
    {
1223
        $validOptions = [
1224 4
            'new_insert',
1225 4
            'same_insert',
1226
            'edit_next',
1227
        ];
1228
        if (isset($_POST['after_insert']) && in_array($_POST['after_insert'], $validOptions)) {
1229 4
            return '/table/change';
1230 4
        }
1231 4
1232
        if (! empty($GLOBALS['goto'])) {
1233 4
            if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
1234
                // this should NOT happen
1235
                //$GLOBALS['goto'] = false;
1236
                if ($GLOBALS['goto'] === 'index.php?route=/sql') {
1237 4
                    $gotoInclude = '/sql';
1238
                } else {
1239
                    $gotoInclude = false;
1240
                }
1241
            } else {
1242
                $gotoInclude = $GLOBALS['goto'];
1243
            }
1244
1245
            if ($GLOBALS['goto'] === 'index.php?route=/database/sql' && strlen($GLOBALS['table']) > 0) {
1246
                $GLOBALS['table'] = '';
1247 4
            }
1248
        }
1249 4
1250 4
        if (! $gotoInclude) {
1251
            if (strlen($GLOBALS['table']) === 0) {
1252
                $gotoInclude = '/database/sql';
1253 4
            } else {
1254
                $gotoInclude = '/table/sql';
1255
            }
1256
        }
1257
1258
        return $gotoInclude;
1259
    }
1260
1261
    /**
1262
     * Defines the url to return in case of failure of the query
1263
     *
1264
     * @param array $urlParams url parameters
1265
     *
1266 4
     * @return string           error url for query failure
1267
     */
1268 4
    public function getErrorUrl(array $urlParams)
1269 4
    {
1270
        if (isset($_POST['err_url'])) {
1271 4
            return $_POST['err_url'];
1272
        }
1273
1274
        return Url::getFromRoute('/table/change', $urlParams);
1275 4
    }
1276 4
1277 4
    /**
1278 4
     * Builds the sql query
1279
     *
1280
     * @param bool  $isInsertIgnore $_POST['submit_type'] === 'insertignore'
1281
     * @param array $queryFields    column names array
1282
     * @param array $valueSets      array of query values
1283
     *
1284
     * @return array of query
1285
     * @psalm-return array{string}
1286
     */
1287
    public function buildSqlQuery(bool $isInsertIgnore, array $queryFields, array $valueSets)
1288
    {
1289
        if ($isInsertIgnore) {
1290
            $insertCommand = 'INSERT IGNORE ';
1291 8
        } else {
1292
            $insertCommand = 'INSERT ';
1293 8
        }
1294 8
1295 8
        return [
1296 8
            $insertCommand . 'INTO '
1297
            . Util::backquote($GLOBALS['table'])
1298
            . ' (' . implode(', ', $queryFields) . ') VALUES ('
1299 8
            . implode('), (', $valueSets) . ')',
1300
        ];
1301
    }
1302 8
1303
    /**
1304 8
     * Executes the sql query and get the result, then move back to the calling page
1305 8
     *
1306 8
     * @param array $urlParams url parameters array
1307 8
     * @param array $query     built query from buildSqlQuery()
1308
     *
1309 8
     * @return array $url_params, $total_affected_rows, $last_messages
1310 8
     *               $warning_messages, $error_messages, $return_to_sql_query
1311
     */
1312
    public function executeSqlQuery(array $urlParams, array $query)
1313
    {
1314
        $returnToSqlQuery = '';
1315 8
        if (! empty($GLOBALS['sql_query'])) {
1316 4
            $urlParams['sql_query'] = $GLOBALS['sql_query'];
1317
            $returnToSqlQuery = $GLOBALS['sql_query'];
1318 4
        }
1319
1320
        $GLOBALS['sql_query'] = implode('; ', $query) . ';';
1321 8
        // to ensure that the query is displayed in case of
1322
        // "insert as new row" and then "insert another new row"
1323
        $GLOBALS['display_query'] = $GLOBALS['sql_query'];
1324 8
1325
        $totalAffectedRows = 0;
1326 8
        $lastMessages = [];
1327 8
        $warningMessages = [];
1328
        $errorMessages = [];
1329
1330
        foreach ($query as $singleQuery) {
1331
            if (isset($_POST['submit_type']) && $_POST['submit_type'] === 'showinsert') {
1332
                $lastMessages[] = Message::notice(__('Showing SQL query'));
1333
                continue;
1334
            }
1335
1336
            if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
1337
                $result = $this->dbi->tryQuery($singleQuery);
1338
            } else {
1339
                $result = $this->dbi->query($singleQuery);
1340
            }
1341 8
1342
            if (! $result) {
1343
                $errorMessages[] = $this->dbi->getError();
1344
            } else {
1345 8
                $totalAffectedRows += $this->dbi->affectedRows();
1346 2
1347 2
                $insertId = $this->dbi->insertId();
1348 2
                if ($insertId) {
1349 2
                    // insert_id is id of FIRST record inserted in one insert, so if we
1350 2
                    // inserted multiple rows, we had to increment this
1351
1352
                    if ($totalAffectedRows > 0) {
1353
                        $insertId += $totalAffectedRows - 1;
1354
                    }
1355
1356
                    $lastMessage = Message::notice(__('Inserted row id: %1$d'));
1357
                    $lastMessage->addParam($insertId);
1358
                    $lastMessages[] = $lastMessage;
1359 12
                }
1360
            }
1361 12
1362 12
            $warningMessages = $this->getWarningMessages();
1363 4
        }
1364
1365
        return [
1366 12
            $urlParams,
1367
            $totalAffectedRows,
1368
            $lastMessages,
1369
            $warningMessages,
1370
            $errorMessages,
1371
            $returnToSqlQuery,
1372
        ];
1373
    }
1374
1375
    /**
1376
     * get the warning messages array
1377
     *
1378
     * @return string[]
1379 4
     */
1380
    private function getWarningMessages(): array
1381
    {
1382
        $warningMessages = [];
1383
        foreach ($this->dbi->getWarnings() as $warning) {
1384 4
            $warningMessages[] = htmlspecialchars((string) $warning);
1385
        }
1386 4
1387
        return $warningMessages;
1388
    }
1389
1390 4
    /**
1391
     * Column to display from the foreign table?
1392 4
     *
1393 4
     * @param string $whereComparison string that contain relation field value
1394 4
     * @param array  $map             all Relations to foreign tables for a given
1395 4
     *                                             table or optionally a given column in a table
1396 4
     * @param string $relationField   relation field
1397 1
     *
1398 4
     * @return string display value from the foreign table
1399 4
     */
1400 4
    public function getDisplayValueForForeignTableColumn(
1401
        $whereComparison,
1402
        array $map,
1403
        $relationField
1404
    ) {
1405
        $foreigner = $this->relation->searchColumnInForeigners($map, $relationField);
1406
1407
        if (! is_array($foreigner)) {
1408
            return '';
1409
        }
1410
1411
        $displayField = $this->relation->getDisplayField($foreigner['foreign_db'], $foreigner['foreign_table']);
1412
        // Field to display from the foreign table?
1413
        if (is_string($displayField) && strlen($displayField) > 0) {
1414
            $dispsql = 'SELECT ' . Util::backquote($displayField)
1415
                . ' FROM ' . Util::backquote($foreigner['foreign_db'])
1416
                . '.' . Util::backquote($foreigner['foreign_table'])
1417
                . ' WHERE ' . Util::backquote($foreigner['foreign_field'])
1418
                . $whereComparison;
1419 4
            $dispresult = $this->dbi->tryQuery($dispsql);
1420
            if ($dispresult && $dispresult->numRows() > 0) {
1421
                return (string) $dispresult->fetchValue();
1422
            }
1423
        }
1424
1425
        return '';
1426 4
    }
1427
1428 4
    /**
1429
     * Display option in the cell according to user choices
1430
     *
1431
     * @param array  $map                all Relations to foreign tables for a given
1432 4
     *                                                   table or optionally a given column in a table
1433
     * @param string $relationField      relation field
1434
     * @param string $whereComparison    string that contain relation field value
1435 4
     * @param string $dispval            display value from the foreign table
1436 4
     * @param string $relationFieldValue relation field value
1437 3
     *
1438
     * @return string HTML <a> tag
1439 4
     */
1440
    public function getLinkForRelationalDisplayField(
1441
        array $map,
1442 1
        $relationField,
1443 4
        $whereComparison,
1444 4
        $dispval,
1445 4
        $relationFieldValue
1446 1
    ): string {
1447 1
        $foreigner = $this->relation->searchColumnInForeigners($map, $relationField);
1448 4
1449 4
        if (! is_array($foreigner)) {
1450 1
            return '';
1451 4
        }
1452 1
1453
        if ($_SESSION['tmpval']['relational_display'] === 'K') {
1454 4
            // user chose "relational key" in the display options, so
1455
            // the title contains the display field
1456 4
            $title = $dispval
1457
                ? ' title="' . htmlspecialchars($dispval) . '"'
1458
                : '';
1459 4
        } else {
1460
            $title = ' title="' . htmlspecialchars($relationFieldValue) . '"';
1461
        }
1462 4
1463
        $sqlQuery = 'SELECT * FROM '
1464
            . Util::backquote($foreigner['foreign_db'])
1465 4
            . '.' . Util::backquote($foreigner['foreign_table'])
1466
            . ' WHERE ' . Util::backquote($foreigner['foreign_field'])
1467 4
            . $whereComparison;
1468
        $urlParams = [
1469
            'db' => $foreigner['foreign_db'],
1470
            'table' => $foreigner['foreign_table'],
1471
            'pos' => '0',
1472
            'sql_signature' => Core::signSqlQuery($sqlQuery),
1473
            'sql_query' => $sqlQuery,
1474
        ];
1475
        $output = '<a href="' . Url::getFromRoute('/sql', $urlParams) . '"' . $title . '>';
1476
1477
        if ($_SESSION['tmpval']['relational_display'] === 'D') {
1478
            // user chose "relational display field" in the
1479
            // display options, so show display field in the cell
1480
            $output .= htmlspecialchars($dispval);
1481
        } else {
1482
            // otherwise display data in the cell
1483
            $output .= htmlspecialchars($relationFieldValue);
1484
        }
1485 4
1486
        $output .= '</a>';
1487
1488
        return $output;
1489
    }
1490
1491
    /**
1492
     * Transform edited values
1493
     *
1494
     * @param string $db             db name
1495 4
     * @param string $table          table name
1496 4
     * @param array  $transformation mimetypes for all columns of a table
1497
     *                                [field_name][field_key]
1498 4
     * @param array  $editedValues   transform columns list and new values
1499 1
     * @param string $file           file containing the transformation plugin
1500 1
     * @param string $columnName     column name
1501 1
     * @param array  $extraData      extra data array
1502 4
     * @param string $type           the type of transformation
1503 1
     *
1504 1
     * @return array
1505
     */
1506 4
    public function transformEditedValues(
1507 4
        $db,
1508 4
        $table,
1509 4
        array $transformation,
1510 4
        array &$editedValues,
1511
        $file,
1512 4
        $columnName,
1513
        array $extraData,
1514 4
        $type
1515 4
    ) {
1516
        $includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
1517
        if (is_file(ROOT_PATH . $includeFile)) {
1518
            // $cfg['SaveCellsAtOnce'] = true; JS code sends an array
1519 4
            $whereClause = is_array($_POST['where_clause']) ? $_POST['where_clause'][0] : $_POST['where_clause'];
1520 4
            $urlParams = [
1521 1
                'db' => $db,
1522
                'table' => $table,
1523 4
                'where_clause_sign' => Core::signSqlQuery($whereClause),
1524
                'where_clause' => $whereClause,
1525
                'transform_key' => $columnName,
1526
            ];
1527
            $transformOptions = $this->transformations->getOptions($transformation[$type . '_options'] ?? '');
1528 4
            $transformOptions['wrapper_link'] = Url::getCommon($urlParams);
1529
            $transformOptions['wrapper_params'] = $urlParams;
1530
            $className = $this->transformations->getClassName($includeFile);
1531
            if (class_exists($className)) {
1532
                /** @var TransformationsPlugin $transformationPlugin */
1533
                $transformationPlugin = new $className();
1534
1535
                foreach ($editedValues as $cellIndex => $currCellEditedValues) {
1536
                    if (! isset($currCellEditedValues[$columnName])) {
1537
                        continue;
1538
                    }
1539
1540
                    $extraData['transformations'][$cellIndex] = $transformationPlugin->applyTransformation(
1541
                        $currCellEditedValues[$columnName],
1542
                        $transformOptions
1543 4
                    );
1544
                    $editedValues[$cellIndex][$columnName] = $extraData['transformations'][$cellIndex];
1545
                }
1546
            }
1547
        }
1548
1549
        return $extraData;
1550
    }
1551
1552
    /**
1553 4
     * Get current value in multi edit mode
1554 4
     *
1555
     * @param string  $multiEditFunction multiple edit functions array
1556
     * @param ?string $multiEditSalt     multiple edit array with encryption salt
1557 4
     * @param string  $currentValue      current value in the column
1558
     */
1559
    public function getCurrentValueAsAnArrayForMultipleEdit(
1560
        string $multiEditFunction,
1561
        ?string $multiEditSalt,
1562
        string $currentValue
1563
    ): string {
1564
        if ($multiEditFunction === 'PHP_PASSWORD_HASH') {
1565
            /**
1566
             * @see https://github.com/vimeo/psalm/issues/3350
1567
             *
1568 4
             * @psalm-suppress InvalidArgument
1569
             */
1570 4
            $hash = password_hash($currentValue, PASSWORD_DEFAULT);
1571
1572 4
            return "'" . $this->dbi->escapeString($hash) . "'";
1573
        }
1574
1575
        if ($multiEditFunction === 'UUID') {
1576 4
            /* This way user will know what UUID new row has */
1577 4
            $uuid = (string) $this->dbi->fetchValue('SELECT UUID()');
1578
1579
            return "'" . $this->dbi->escapeString($uuid) . "'";
1580
        }
1581
1582
        if (
1583
            in_array($multiEditFunction, $this->getGisFromTextFunctions())
1584
            || in_array($multiEditFunction, $this->getGisFromWKBFunctions())
1585
        ) {
1586
            return $multiEditFunction . "('" . $this->dbi->escapeString($currentValue) . "')";
1587
        }
1588
1589
        if (
1590 4
            ! in_array($multiEditFunction, self::FUNC_NO_PARAM)
1591 4
            || ($currentValue !== ''
1592 4
                && in_array($multiEditFunction, self::FUNC_OPTIONAL_PARAM))
1593
        ) {
1594
            if (
1595 4
                (isset($multiEditSalt)
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (IssetNode && $multiEdit...tFunction === 'ENCRYPT', Probably Intended Meaning: IssetNode && ($multiEdit...Function === 'ENCRYPT')
Loading history...
1596 4
                    && ($multiEditFunction === 'AES_ENCRYPT'
1597 4
                        || $multiEditFunction === 'AES_DECRYPT'))
1598 4
                || (! empty($multiEditSalt)
1599
                    && ($multiEditFunction === 'DES_ENCRYPT'
1600
                        || $multiEditFunction === 'DES_DECRYPT'
1601 4
                        || $multiEditFunction === 'ENCRYPT'))
1602
            ) {
1603 4
                return $multiEditFunction . "('" . $this->dbi->escapeString($currentValue) . "','"
1604 4
                    . $this->dbi->escapeString($multiEditSalt) . "')";
1605
            }
1606
1607 4
            return $multiEditFunction . "('" . $this->dbi->escapeString($currentValue) . "')";
1608
        }
1609
1610 4
        return $multiEditFunction . '()';
1611
    }
1612
1613
    /**
1614
     * Get query values array and query fields array for insert and update in multi edit
1615
     *
1616
     * @param array  $multiEditColumnsName     multiple edit columns name array
1617
     * @param array  $multiEditColumnsNull     multiple edit columns null array
1618
     * @param string $currentValue             current value in the column in loop
1619
     * @param array  $multiEditColumnsPrev     multiple edit previous columns array
1620
     * @param array  $multiEditFuncs           multiple edit functions array
1621
     * @param bool   $isInsert                 boolean value whether insert or not
1622
     * @param array  $queryValues              SET part of the sql query
1623
     * @param array  $queryFields              array of query fields
1624
     * @param string $currentValueAsAnArray    current value in the column
1625
     *                                                as an array
1626
     * @param array  $valueSets                array of valu sets
1627
     * @param string $key                      an md5 of the column name
1628
     * @param array  $multiEditColumnsNullPrev array of multiple edit columns
1629
     *                                              null previous
1630
     *
1631
     * @return array[] ($query_values, $query_fields)
1632
     */
1633 4
    public function getQueryValuesForInsertAndUpdateInMultipleEdit(
1634
        $multiEditColumnsName,
1635
        $multiEditColumnsNull,
1636
        $currentValue,
1637
        $multiEditColumnsPrev,
1638
        $multiEditFuncs,
1639
        $isInsert,
1640
        $queryValues,
1641
        $queryFields,
1642
        $currentValueAsAnArray,
1643
        $valueSets,
1644
        $key,
1645
        $multiEditColumnsNullPrev
1646
    ) {
1647
        //  i n s e r t
1648 4
        if ($isInsert) {
1649
            // no need to add column into the valuelist
1650 4
            if (strlen($currentValueAsAnArray) > 0) {
1651 4
                $queryValues[] = $currentValueAsAnArray;
1652
                // first inserted row so prepare the list of fields
1653 4
                if (empty($valueSets)) {
1654 4
                    $queryFields[] = Util::backquote($multiEditColumnsName[$key]);
1655
                }
1656
            }
1657 4
        } elseif (! empty($multiEditColumnsNullPrev[$key]) && ! isset($multiEditColumnsNull[$key])) {
1658
            //  u p d a t e
1659
1660
            // field had the null checkbox before the update
1661
            // field no longer has the null checkbox
1662 4
            $queryValues[] = Util::backquote($multiEditColumnsName[$key])
1663 1
                . ' = ' . $currentValueAsAnArray;
1664
        } elseif (
1665 4
            ! (empty($multiEditFuncs[$key])
1666 4
                && isset($multiEditColumnsPrev[$key])
1667 4
                && (($currentValue === "'" . $this->dbi->escapeString($multiEditColumnsPrev[$key]) . "'")
1668 4
                    || ($currentValue === '0x' . $multiEditColumnsPrev[$key])))
1669 1
            && $currentValue
1670
        ) {
1671
            // avoid setting a field to NULL when it's already NULL
1672
            // (field had the null checkbox before the update
1673
            //  field still has the null checkbox)
1674 4
            if (empty($multiEditColumnsNullPrev[$key]) || empty($multiEditColumnsNull[$key])) {
1675 4
                $queryValues[] = Util::backquote($multiEditColumnsName[$key])
1676 1
                    . ' = ' . $currentValueAsAnArray;
1677
            }
1678
        }
1679
1680
        return [
1681 4
            $queryValues,
1682 1
            $queryFields,
1683
        ];
1684
    }
1685
1686
    /**
1687
     * Get the current column value in the form for different data types
1688
     *
1689
     * @param string|false $possiblyUploadedVal      uploaded file content
1690
     * @param string       $key                      an md5 of the column name
1691
     * @param array|null   $multiEditColumnsType     array of multi edit column types
1692
     * @param string       $currentValue             current column value in the form
1693
     * @param array|null   $multiEditAutoIncrement   multi edit auto increment
1694
     * @param int          $rownumber                index of where clause array
1695
     * @param array        $multiEditColumnsName     multi edit column names array
1696
     * @param array        $multiEditColumnsNull     multi edit columns null array
1697
     * @param array        $multiEditColumnsNullPrev multi edit columns previous null
1698
     * @param bool         $isInsert                 whether insert or not
1699
     * @param bool         $usingKey                 whether editing or new row
1700
     * @param string       $whereClause              where clause
1701
     * @param string       $table                    table name
1702
     *
1703
     * @return string  current column value in the form
1704
     */
1705
    public function getCurrentValueForDifferentTypes(
1706 4
        $possiblyUploadedVal,
1707
        $key,
1708
        ?array $multiEditColumnsType,
1709
        string $currentValue,
1710
        ?array $multiEditAutoIncrement,
1711
        $rownumber,
1712
        $multiEditColumnsName,
1713
        $multiEditColumnsNull,
1714
        $multiEditColumnsNullPrev,
1715
        $isInsert,
1716
        $usingKey,
1717
        $whereClause,
1718
        $table
1719
    ): string {
1720
        if ($possiblyUploadedVal !== false) {
1721
            return $possiblyUploadedVal;
1722 4
        }
1723 4
1724
        // c o l u m n    v a l u e    i n    t h e    f o r m
1725
        $type = $multiEditColumnsType[$key] ?? '';
1726 4
1727
        if ($type !== 'protected' && $type !== 'set' && strlen($currentValue) === 0) {
1728
            // best way to avoid problems in strict mode
1729
            // (works also in non-strict mode)
1730
            $currentValue = "''";
1731 4
            if (isset($multiEditAutoIncrement, $multiEditAutoIncrement[$key])) {
1732
                $currentValue = 'NULL';
1733 4
            }
1734
        } elseif ($type === 'set') {
1735
            $currentValue = "''";
1736 4
            if (! empty($_POST['fields']['multi_edit'][$rownumber][$key])) {
1737 4
                $currentValue = implode(',', $_POST['fields']['multi_edit'][$rownumber][$key]);
1738 4
                $currentValue = "'"
1739
                    . $this->dbi->escapeString($currentValue) . "'";
1740 4
            }
1741 4
        } elseif ($type === 'protected') {
1742 4
            // Fetch the current values of a row to use in case we have a protected field
1743
            if (
1744 1
                $isInsert
1745 3
                && $usingKey
1746
                && is_array($multiEditColumnsType) && $whereClause
1747 4
            ) {
1748
                $protectedRow = $this->dbi->fetchSingleRow(
1749
                    'SELECT * FROM ' . Util::backquote($table)
1750 4
                    . ' WHERE ' . $whereClause . ';'
1751 1
                );
1752 4
            }
1753
1754 4
            // here we are in protected mode (asked in the config)
1755 4
            // so tbl_change has put this special value in the
1756 1
            // columns array, so we do not change the column value
1757
            // but we can still handle column upload
1758
1759
            // when in UPDATE mode, do not alter field's contents. When in INSERT
1760
            // mode, insert empty field because no values were submitted.
1761
            // If protected blobs where set, insert original fields content.
1762
            $currentValue = '';
1763
            if (! empty($protectedRow[$multiEditColumnsName[$key]])) {
1764
                $currentValue = '0x'
1765
                    . bin2hex($protectedRow[$multiEditColumnsName[$key]]);
1766
            }
1767
        } elseif ($type === 'hex') {
1768 4
            if (substr($currentValue, 0, 2) != '0x') {
1769 4
                $currentValue = '0x' . $currentValue;
1770 1
            }
1771 4
        } elseif ($type === 'bit') {
1772
            $currentValue = (string) preg_replace('/[^01]/', '0', $currentValue);
1773 4
            $currentValue = "b'" . $this->dbi->escapeString($currentValue) . "'";
1774
        } elseif (
1775
            ! ($type === 'datetime' || $type === 'timestamp' || $type === 'date')
1776
            || ($currentValue !== 'CURRENT_TIMESTAMP'
1777 4
                && $currentValue !== 'current_timestamp()')
1778 4
        ) {
1779 4
            $currentValue = "'" . $this->dbi->escapeString($currentValue)
1780
                . "'";
1781 4
        }
1782 4
1783 4
        // Was the Null checkbox checked for this field?
1784
        // (if there is a value, we ignore the Null checkbox: this could
1785 4
        // be possible if Javascript is disabled in the browser)
1786 1
        if (! empty($multiEditColumnsNull[$key]) && ($currentValue == "''" || $currentValue == '')) {
1787
            $currentValue = 'NULL';
1788
        }
1789
1790
        // The Null checkbox was unchecked for this field
1791
        if (
1792 4
            empty($currentValue)
1793 4
            && ! empty($multiEditColumnsNullPrev[$key])
1794
            && ! isset($multiEditColumnsNull[$key])
1795
        ) {
1796
            $currentValue = "''";
1797
        }
1798 4
1799 4
        return $currentValue;
1800 4
    }
1801
1802 4
    /**
1803
     * Check whether inline edited value can be truncated or not,
1804
     * and add additional parameters for extra_data array  if needed
1805 4
     *
1806
     * @param string $db         Database name
1807
     * @param string $table      Table name
1808
     * @param string $columnName Column name
1809
     * @param array  $extraData  Extra data for ajax response
1810
     */
1811
    public function verifyWhetherValueCanBeTruncatedAndAppendExtraData(
1812
        $db,
1813
        $table,
1814
        $columnName,
1815
        array &$extraData
1816
    ): void {
1817 4
        $extraData['isNeedToRecheck'] = false;
1818
1819
        $sqlForRealValue = 'SELECT ' . Util::backquote($table) . '.'
1820
            . Util::backquote($columnName)
1821
            . ' FROM ' . Util::backquote($db) . '.'
1822
            . Util::backquote($table)
1823 4
            . ' WHERE ' . $_POST['where_clause'][0];
1824
1825 4
        $result = $this->dbi->tryQuery($sqlForRealValue);
1826 4
1827 4
        if (! $result) {
1828 4
            return;
1829 4
        }
1830
1831 4
        $fieldsMeta = $this->dbi->getFieldsMeta($result);
1832
        $meta = $fieldsMeta[0];
1833 4
        $newValue = $result->fetchValue();
1834
1835
        if ($newValue === false) {
1836
            return;
1837 4
        }
1838 4
1839 4
        if ($meta->isTimeType()) {
1840
            $newValue = Util::addMicroseconds($newValue);
1841 4
        } elseif ($meta->isBinary()) {
1842 4
            $newValue = '0x' . bin2hex($newValue);
1843
        }
1844
1845 4
        $extraData['isNeedToRecheck'] = true;
1846 4
        $extraData['truncatableFieldValue'] = $newValue;
1847 4
    }
1848
1849
    /**
1850
     * Function to get the columns of a table
1851 4
     *
1852 4
     * @param string $db    current db
1853 1
     * @param string $table current table
1854
     *
1855
     * @return array[]
1856
     */
1857
    public function getTableColumns($db, $table)
1858
    {
1859
        $this->dbi->selectDb($db);
1860
1861
        return array_values($this->dbi->getColumns($db, $table, true));
1862
    }
1863 4
1864
    /**
1865 4
     * Function to determine Insert/Edit rows
1866
     *
1867 4
     * @param string[]|string|null $whereClause where clause
1868
     * @param string               $db          current database
1869
     * @param string               $table       current table
1870
     *
1871
     * @return array<int, bool|string[]|string|ResultInterface|ResultInterface[]|null>
1872
     * @phpstan-return array{
1873
     *     bool,
1874
     *     string[]|string|null,
1875
     *     string[],
1876
     *     string[]|null,
1877
     *     ResultInterface[]|ResultInterface,
1878
     *     array<string, string|null>[]|false[],
1879 4
     *     bool,
1880
     *     string|null
1881 4
     * }
1882 4
     */
1883
    public function determineInsertOrEdit($whereClause, $db, $table): array
1884
    {
1885 4
        if (isset($_POST['where_clause'])) {
1886 4
            $whereClause = $_POST['where_clause'];
1887 4
        }
1888 4
1889
        if (isset($_SESSION['edit_next'])) {
1890
            $whereClause = $_SESSION['edit_next'];
1891 4
            unset($_SESSION['edit_next']);
1892 4
            $afterInsert = 'edit_next';
1893
        }
1894
1895 4
        if (isset($_POST['ShowFunctionFields'])) {
1896 4
            $GLOBALS['cfg']['ShowFunctionFields'] = $_POST['ShowFunctionFields'];
1897
        }
1898
1899 4
        if (isset($_POST['ShowFieldTypesInDataEditView'])) {
1900 4
            $GLOBALS['cfg']['ShowFieldTypesInDataEditView'] = $_POST['ShowFieldTypesInDataEditView'];
1901
        }
1902
1903 4
        if (isset($_POST['after_insert'])) {
1904
            $afterInsert = $_POST['after_insert'];
1905 4
        }
1906 4
1907 4
        if (isset($whereClause)) {
1908 1
            // we are editing
1909 1
            $insertMode = false;
1910 1
            $whereClauseArray = $this->getWhereClauseArray($whereClause);
1911
            [$whereClauses, $result, $rows, $foundUniqueKey] = $this->analyzeWhereClauses(
1912
                $whereClauseArray,
1913
                $table,
1914 4
                $db
1915 4
            );
1916 4
        } else {
1917 4
            // we are inserting
1918 4
            $insertMode = true;
1919 4
            $whereClause = null;
1920
            [$result, $rows] = $this->loadFirstRow($table, $db);
1921
            $whereClauses = null;
1922
            $whereClauseArray = [];
1923
            $foundUniqueKey = false;
1924 4
        }
1925 4
1926
        // Copying a row - fetched data will be inserted as a new row,
1927
        // therefore the where clause is needless.
1928
        if (isset($_POST['default_action']) && $_POST['default_action'] === 'insert') {
1929 4
            $whereClause = $whereClauses = null;
1930 1
        }
1931 1
1932 1
        return [
1933 1
            $insertMode,
1934 1
            $whereClause,
1935 1
            $whereClauseArray,
1936 4
            $whereClauses,
1937
            $result,
1938
            $rows,
1939
            $foundUniqueKey,
1940
            $afterInsert ?? null,
1941
        ];
1942
    }
1943
1944
    /**
1945
     * Function to get comments for the table columns
1946
     *
1947
     * @param string $db    current database
1948 4
     * @param string $table current table
1949
     *
1950 4
     * @return array comments for columns
1951 4
     */
1952
    public function getCommentsMap($db, $table): array
1953
    {
1954 4
        if ($GLOBALS['cfg']['ShowPropertyComments']) {
1955
            return $this->relation->getComments($db, $table);
1956
        }
1957
1958
        return [];
1959
    }
1960
1961
    /**
1962
     * Function to get html for the gis editor div
1963
     */
1964
    public function getHtmlForGisEditor(): string
1965
    {
1966
        return '<div id="gis_editor"></div><div id="popup_background"></div><br>';
1967
    }
1968
1969
    /**
1970
     * Function to get html for the ignore option in insert mode
1971 4
     *
1972
     * @param int  $rowId   row id
1973
     * @param bool $checked ignore option is checked or not
1974 4
     */
1975 1
    public function getHtmlForIgnoreOption($rowId, $checked = true): string
1976 1
    {
1977 1
        return '<input type="checkbox"'
1978 4
            . ($checked ? ' checked="checked"' : '')
1979 1
            . ' name="insert_ignore_' . $rowId . '"'
1980
            . ' id="insert_ignore_' . $rowId . '">'
1981
            . '<label for="insert_ignore_' . $rowId . '">'
1982
            . __('Ignore')
1983
            . '</label><br>' . "\n";
1984
    }
1985
1986
    /**
1987
     * Function to get html for the insert edit form header
1988
     *
1989
     * @param bool $hasBlobField whether has blob field
1990
     * @param bool $isUpload     whether is upload
1991
     */
1992
    public function getHtmlForInsertEditFormHeader($hasBlobField, $isUpload): string
1993
    {
1994
        $template = new Template();
1995
1996
        return $template->render('table/insert/get_html_for_insert_edit_form_header', [
1997
            'has_blob_field' => $hasBlobField,
1998
            'is_upload' => $isUpload,
1999
        ]);
2000
    }
2001
2002
    /**
2003
     * Function to get html for each insert/edit column
2004
     *
2005
     * @param array           $column             column
2006
     * @param int             $columnNumber       column index in table_columns
2007
     * @param array           $commentsMap        comments map
2008
     * @param bool            $timestampSeen      whether timestamp seen
2009
     * @param ResultInterface $currentResult      current result
2010
     * @param string          $chgEvtHandler      javascript change event handler
2011
     * @param string          $jsvkey             javascript validation key
2012
     * @param string          $vkey               validation key
2013
     * @param bool            $insertMode         whether insert mode
2014
     * @param array           $currentRow         current row
2015
     * @param int             $oRows              row offset
2016
     * @param int             $tabindex           tab index
2017
     * @param int             $columnsCnt         columns count
2018
     * @param bool            $isUpload           whether upload
2019
     * @param array           $foreigners         foreigners
2020
     * @param int             $tabindexForValue   tab index offset for value
2021
     * @param string          $table              table
2022
     * @param string          $db                 database
2023
     * @param int             $rowId              row id
2024
     * @param int             $biggestMaxFileSize biggest max file size
2025
     * @param string          $defaultCharEditing default char editing mode which is stored in the config.inc.php script
2026
     * @param string          $textDir            text direction
2027
     * @param array           $repopulate         the data to be repopulated
2028
     * @param array           $columnMime         the mime information of column
2029 12
     * @param string          $whereClause        the where clause
2030
     *
2031
     * @return string
2032
     */
2033
    private function getHtmlForInsertEditFormColumn(
2034
        array $column,
2035
        int $columnNumber,
2036
        array $commentsMap,
2037
        $timestampSeen,
2038
        ResultInterface $currentResult,
2039
        $chgEvtHandler,
2040
        $jsvkey,
2041
        $vkey,
2042
        $insertMode,
2043
        array $currentRow,
2044
        $oRows,
2045
        &$tabindex,
2046
        $columnsCnt,
2047
        $isUpload,
2048
        array $foreigners,
2049
        $tabindexForValue,
2050
        $table,
2051
        $db,
2052
        $rowId,
2053
        $biggestMaxFileSize,
2054
        $defaultCharEditing,
2055
        $textDir,
2056 12
        array $repopulate,
2057
        array $columnMime,
2058 12
        $whereClause
2059 12
    ) {
2060
        $readOnly = false;
2061
2062 12
        if (! isset($column['processed'])) {
2063
            $column = $this->analyzeTableColumnsArray($column, $commentsMap, $timestampSeen);
2064 12
        }
2065 12
2066
        $asIs = false;
2067
        /** @var string $fieldHashMd5 */
2068
        $fieldHashMd5 = $column['Field_md5'];
2069
        if ($repopulate && array_key_exists($fieldHashMd5, $currentRow)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $repopulate of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2070 12
            $currentRow[$column['Field']] = $repopulate[$fieldHashMd5];
2071
            $asIs = true;
2072 12
        }
2073 12
2074
        $extractedColumnspec = Util::extractColumnSpec($column['Type']);
2075
2076 12
        if ($column['len'] === -1) {
2077 12
            $column['len'] = $this->dbi->getFieldsMeta($currentResult)[$columnNumber]->length;
2078
            // length is unknown for geometry fields,
2079
            // make enough space to edit very simple WKTs
2080
            if ($column['len'] === -1) {
2081
                $column['len'] = 30;
2082 3
            }
2083 3
        }
2084 12
2085 12
        //Call validation when the form submitted...
2086
        $onChangeClause = $chgEvtHandler
2087
            . "=\"return verificationsAfterFieldChange('"
2088
            . Sanitize::escapeJsString($fieldHashMd5) . "', '"
2089 12
            . Sanitize::escapeJsString($jsvkey) . "','" . $column['pma_type'] . "')\"";
2090
2091 12
        // Use an MD5 as an array index to avoid having special characters
2092 4
        // in the name attribute (see bug #1746964 )
2093
        $columnNameAppendix = $vkey . '[' . $fieldHashMd5 . ']';
2094
2095
        if ($column['Type'] === 'datetime' && $column['Null'] !== 'YES' && ! isset($column['Default']) && $insertMode) {
2096 12
            $column['Default'] = date('Y-m-d H:i:s', time());
2097
        }
2098
2099 12
        // Get a list of GIS data types.
2100
        $gisDataTypes = Gis::getDataTypes();
2101
2102
        // Prepares the field value
2103
        if ($currentRow) {
2104
            // (we are editing)
2105
            [
2106
                $realNullValue,
2107
                $specialCharsEncoded,
2108
                $specialChars,
2109
                $data,
2110
                $backupField,
2111
            ] = $this->getSpecialCharsAndBackupFieldForExistingRow(
2112
                $currentRow,
2113
                $column,
2114
                $extractedColumnspec,
2115
                $gisDataTypes,
2116
                $columnNameAppendix,
2117
                $asIs
2118 12
            );
2119 12
        } else {
2120 4
            // (we are inserting)
2121
            // display default values
2122
            $tmp = $column;
2123
            if (isset($repopulate[$fieldHashMd5])) {
2124
                $tmp['Default'] = $repopulate[$fieldHashMd5];
2125
            }
2126
2127
            [
2128
                $realNullValue,
2129 12
                $data,
2130 12
                $specialChars,
2131
                $backupField,
2132
                $specialCharsEncoded,
2133 12
            ] = $this->getSpecialCharsAndBackupFieldForInsertingMode($tmp);
2134 12
            unset($tmp);
2135
        }
2136
2137
        $idindex = ($oRows * $columnsCnt) + $columnNumber + 1;
2138 12
        $tabindex = $idindex;
2139 12
2140 12
        // The function column
2141
        // -------------------
2142 12
        $foreignData = $this->relation->getForeignData($foreigners, $column['Field'], false, '', '');
2143 12
        $isColumnBinary = $this->isColumnBinary($column, $isUpload);
2144
        $functionOptions = '';
2145
2146
        if ($GLOBALS['cfg']['ShowFunctionFields']) {
2147 12
            $functionOptions = Generator::getFunctionsForField($column, $insertMode, $foreignData);
2148
        }
2149
2150
        // nullify code is needed by the js nullify() function to be able to generate calls to nullify() in jQuery
2151
        $nullifyCode = $this->getNullifyCodeForNullColumn($column, $foreigners, $foreignData);
2152
2153
        // The value column (depends on type)
2154
        // ----------------
2155 12
        // See bug #1667887 for the reason why we don't use the maxlength
2156 12
        // HTML attribute
2157 12
2158 4
        //add data attributes "no of decimals" and "data type"
2159 4
        $noDecimals = 0;
2160
        $type = current(explode('(', $column['pma_type']));
2161
        if (preg_match('/\(([^()]+)\)/', $column['pma_type'], $match)) {
2162
            $match[0] = trim($match[0], '()');
2163 12
            $noDecimals = $match[0];
2164 12
        }
2165 4
2166 4
        // Check input transformation of column
2167 4
        $transformedHtml = '';
2168 4
        if (! empty($columnMime['input_transformation'])) {
2169 4
            $file = $columnMime['input_transformation'];
2170 4
            $includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
2171 4
            if (is_file(ROOT_PATH . $includeFile)) {
2172 4
                $className = $this->transformations->getClassName($includeFile);
2173
                if (class_exists($className)) {
2174 1
                    $transformationPlugin = new $className();
2175 1
                    $transformationOptions = $this->transformations->getOptions(
2176 1
                        $columnMime['input_transformation_options']
2177 4
                    );
2178 4
                    $urlParams = [
2179 1
                        'db' => $db,
2180
                        'table' => $table,
2181 4
                        'transform_key' => $column['Field'],
2182 4
                        'where_clause_sign' => Core::signSqlQuery($whereClause),
2183 4
                        'where_clause' => $whereClause,
2184 4
                    ];
2185
                    $transformationOptions['wrapper_link'] = Url::getCommon($urlParams);
2186
                    $transformationOptions['wrapper_params'] = $urlParams;
2187
                    $currentValue = '';
2188 4
                    if (isset($currentRow[$column['Field']])) {
2189 4
                        $currentValue = $currentRow[$column['Field']];
2190 1
                    }
2191 1
2192 1
                    if (method_exists($transformationPlugin, 'getInputHtml')) {
2193 1
                        $transformedHtml = $transformationPlugin->getInputHtml(
2194 1
                            $column,
2195 1
                            $rowId,
2196 1
                            $columnNameAppendix,
2197 1
                            $transformationOptions,
2198 1
                            $currentValue,
2199
                            $textDir,
2200
                            $tabindex,
2201
                            $tabindexForValue,
2202 4
                            $idindex
2203 4
                        );
2204 4
                    }
2205 4
2206
                    if (method_exists($transformationPlugin, 'getScripts')) {
2207
                        $GLOBALS['plugin_scripts'] = array_merge(
2208
                            $GLOBALS['plugin_scripts'],
2209
                            $transformationPlugin->getScripts()
2210
                        );
2211
                    }
2212 12
                }
2213 12
            }
2214 12
        }
2215 12
2216 12
        $columnValue = '';
2217 12
        $foreignDropdown = '';
2218 12
        $dataType = '';
2219 12
        $textAreaRows = $GLOBALS['cfg']['TextareaRows'];
2220 12
        $textareaCols = $GLOBALS['cfg']['TextareaCols'];
2221 12
        $maxlength = '';
2222 12
        $enumSelectedValue = '';
2223 12
        $columnSetValues = [];
2224 12
        $setSelectSize = 0;
2225 12
        $isColumnProtectedBlob = false;
2226 12
        $blobValue = '';
2227 12
        $blobValueUnit = '';
2228 12
        $maxUploadSize = 0;
2229
        $selectOptionForUpload = '';
2230
        $inputFieldHtml = '';
2231
        if (empty($transformedHtml)) {
2232
            if (is_array($foreignData['disp_row'])) {
2233
                $foreignDropdown = $this->relation->foreignDropdown(
2234
                    $foreignData['disp_row'],
2235
                    $foreignData['foreign_field'],
2236
                    $foreignData['foreign_display'],
2237
                    $data,
2238 12
                    $GLOBALS['cfg']['ForeignKeyMaxLimit']
2239
                );
2240 12
            }
2241
2242
            $dataType = $this->dbi->types->getTypeClass($column['True_Type']);
2243
2244 12
            if ($column['is_char']) {
2245 8
                $textAreaRows = max($GLOBALS['cfg']['CharTextareaRows'], 7);
2246 8
                $textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
2247
                $maxlength = $extractedColumnspec['spec_in_brackets'];
2248
            } elseif ($GLOBALS['cfg']['LongtextDoubleTextarea'] && mb_strstr($column['pma_type'], 'longtext')) {
2249 12
                $textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
2250
                $textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
2251
            }
2252
2253
            if ($column['pma_type'] === 'enum') {
2254
                if (! isset($column['values'])) {
2255
                    $column['values'] = $this->getColumnEnumValues($extractedColumnspec['enum_set_values']);
2256
                }
2257
2258
                foreach ($column['values'] as $enumValue) {
2259
                    if (
2260
                        $data == $enumValue['plain'] || ($data == ''
2261
                            && (! isset($_POST['where_clause']) || $column['Null'] !== 'YES')
2262
                            && isset($column['Default']) && $enumValue['plain'] == $column['Default'])
2263
                    ) {
2264 12
                        $enumSelectedValue = $enumValue['plain'];
2265
                        break;
2266
                    }
2267
                }
2268
            } elseif ($column['pma_type'] === 'set') {
2269 12
                [$columnSetValues, $setSelectSize] = $this->getColumnSetValueAndSelectSize(
2270
                    $column,
2271
                    $extractedColumnspec['enum_set_values']
2272
                );
2273
            } elseif ($column['is_binary'] || $column['is_blob']) {
2274
                $isColumnProtectedBlob = ($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'])
2275
                    || ($GLOBALS['cfg']['ProtectBinary'] === 'all')
2276
                    || ($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && ! $column['is_blob']);
2277
                if ($isColumnProtectedBlob && isset($data)) {
2278
                    $blobSize = Util::formatByteDown(mb_strlen(stripslashes($data)), 3, 1);
2279
                    if ($blobSize !== null) {
0 ignored issues
show
introduced by
The condition $blobSize !== null is always true.
Loading history...
2280
                        [$blobValue, $blobValueUnit] = $blobSize;
2281
                    }
2282
                }
2283
2284
                if ($isUpload && $column['is_blob']) {
2285
                    [$maxUploadSize] = $this->getMaxUploadSize($column['pma_type'], $biggestMaxFileSize);
2286
                }
2287
2288
                if (! empty($GLOBALS['cfg']['UploadDir'])) {
2289
                    $selectOptionForUpload = $this->getSelectOptionForUpload($vkey, $fieldHashMd5);
2290
                }
2291
2292
                if (
2293
                    ! $isColumnProtectedBlob
2294
                    && ! ($column['is_blob'] || ($column['len'] > $GLOBALS['cfg']['LimitChars']))
2295
                ) {
2296
                    $inputFieldHtml = $this->getHtmlInput(
2297
                        $column,
2298
                        $columnNameAppendix,
2299
                        $specialChars,
2300
                        min(max($column['len'], 4), $GLOBALS['cfg']['LimitChars']),
2301
                        $onChangeClause,
2302
                        $tabindex,
2303
                        $tabindexForValue,
2304
                        $idindex,
2305
                        'HEX',
2306 12
                        $readOnly
2307 3
                    );
2308 3
                }
2309 3
            } else {
2310 3
                $columnValue = $this->getValueColumnForOtherDatatypes(
2311 3
                    $column,
2312 3
                    $defaultCharEditing,
2313 3
                    $backupField,
2314 3
                    $columnNameAppendix,
2315 3
                    $onChangeClause,
2316 3
                    $tabindex,
2317 3
                    $specialChars,
2318 3
                    $tabindexForValue,
2319 3
                    $idindex,
2320 3
                    $textDir,
2321
                    $specialCharsEncoded,
2322
                    $data,
2323
                    $extractedColumnspec,
2324
                    $readOnly
2325 12
                );
2326 3
            }
2327 3
        }
2328 3
2329 3
        return $this->template->render('table/insert/column_row', [
2330 12
            'db' => $db,
2331 12
            'table' => $table,
2332 3
            'column' => $column,
2333 3
            'row_id' => $rowId,
2334 3
            'show_field_types_in_data_edit_view' => $GLOBALS['cfg']['ShowFieldTypesInDataEditView'],
2335 3
            'show_function_fields' => $GLOBALS['cfg']['ShowFunctionFields'],
2336 3
            'is_column_binary' => $isColumnBinary,
2337 3
            'function_options' => $functionOptions,
2338 3
            'read_only' => $readOnly,
2339 3
            'nullify_code' => $nullifyCode,
2340 3
            'real_null_value' => $realNullValue,
2341 3
            'id_index' => $idindex,
2342 3
            'type' => $type,
2343 12
            'decimals' => $noDecimals,
2344 3
            'special_chars' => $specialChars,
2345 3
            'transformed_value' => $transformedHtml,
2346 3
            'value' => $columnValue,
2347 3
            'is_value_foreign_link' => $foreignData['foreign_link'] === true,
2348 3
            'backup_field' => $backupField,
2349 3
            'data' => $data,
2350 3
            'gis_data_types' => $gisDataTypes,
2351 3
            'foreign_dropdown' => $foreignDropdown,
2352 3
            'data_type' => $dataType,
2353 12
            'textarea_cols' => $textareaCols,
2354 3
            'textarea_rows' => $textAreaRows,
2355 3
            'text_dir' => $textDir,
2356 3
            'max_length' => $maxlength,
2357 3
            'longtext_double_textarea' => $GLOBALS['cfg']['LongtextDoubleTextarea'],
2358 3
            'enum_selected_value' => $enumSelectedValue,
2359 3
            'set_values' => $columnSetValues,
2360 3
            'set_select_size' => $setSelectSize,
2361 3
            'is_column_protected_blob' => $isColumnProtectedBlob,
2362 3
            'blob_value' => $blobValue,
2363 12
            'blob_value_unit' => $blobValueUnit,
2364 3
            'is_upload' => $isUpload,
2365
            'max_upload_size' => $maxUploadSize,
2366
            'select_option_for_upload' => $selectOptionForUpload,
2367
            'limit_chars' => $GLOBALS['cfg']['LimitChars'],
2368 12
            'input_field_html' => $inputFieldHtml,
2369
        ]);
2370 12
    }
2371
2372
    private function isColumnBinary(array $column, bool $isUpload): bool
2373
    {
2374 12
        if (! $GLOBALS['cfg']['ShowFunctionFields']) {
2375 12
            return false;
2376 12
        }
2377
2378
        return ($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'] && ! $isUpload)
2379
            || ($GLOBALS['cfg']['ProtectBinary'] === 'all' && $column['is_binary'])
2380
            || ($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && $column['is_binary']);
2381
    }
2382
2383
    /**
2384
     * Function to get html for each insert/edit row
2385
     *
2386
     * @param array           $urlParams          url parameters
2387
     * @param array[]         $tableColumns       table columns
2388
     * @param array           $commentsMap        comments map
2389
     * @param bool            $timestampSeen      whether timestamp seen
2390
     * @param ResultInterface $currentResult      current result
2391
     * @param string          $chgEvtHandler      javascript change event handler
2392
     * @param string          $jsvkey             javascript validation key
2393
     * @param string          $vkey               validation key
2394
     * @param bool            $insertMode         whether insert mode
2395
     * @param array           $currentRow         current row
2396
     * @param int             $oRows              row offset
2397
     * @param int             $tabindex           tab index
2398
     * @param int             $columnsCnt         columns count
2399
     * @param bool            $isUpload           whether upload
2400
     * @param array           $foreigners         foreigners
2401
     * @param int             $tabindexForValue   tab index offset for value
2402
     * @param string          $table              table
2403
     * @param string          $db                 database
2404
     * @param int             $rowId              row id
2405
     * @param int             $biggestMaxFileSize biggest max file size
2406
     * @param string          $textDir            text direction
2407
     * @param array           $repopulate         the data to be repopulated
2408 8
     * @param array           $whereClauseArray   the array of where clauses
2409
     *
2410
     * @return string
2411
     */
2412
    public function getHtmlForInsertEditRow(
2413
        array $urlParams,
2414
        array $tableColumns,
2415
        array $commentsMap,
2416
        $timestampSeen,
2417
        ResultInterface $currentResult,
2418
        $chgEvtHandler,
2419
        $jsvkey,
2420
        $vkey,
2421
        $insertMode,
2422
        array $currentRow,
2423
        &$oRows,
2424
        &$tabindex,
2425
        $columnsCnt,
2426
        $isUpload,
2427
        array $foreigners,
2428
        $tabindexForValue,
2429
        $table,
2430
        $db,
2431
        $rowId,
2432
        $biggestMaxFileSize,
2433 8
        $textDir,
2434 2
        array $repopulate,
2435
        array $whereClauseArray
2436
    ) {
2437 8
        $htmlOutput = $this->getHeadAndFootOfInsertRowTable($urlParams)
2438 8
            . '<tbody>';
2439 8
2440 8
        //store the default value for CharEditing
2441 8
        $defaultCharEditing = $GLOBALS['cfg']['CharEditing'];
2442
        $mimeMap = $this->transformations->getMime($db, $table);
2443
        $whereClause = '';
2444 8
        if (isset($whereClauseArray[$rowId])) {
2445 8
            $whereClause = $whereClauseArray[$rowId];
2446 8
        }
2447 8
2448
        for ($columnNumber = 0; $columnNumber < $columnsCnt; $columnNumber++) {
2449
            $tableColumn = $tableColumns[$columnNumber];
2450
            $columnMime = [];
2451 2
            if (isset($mimeMap[$tableColumn['Field']])) {
2452 2
                $columnMime = $mimeMap[$tableColumn['Field']];
2453
            }
2454
2455
            $virtual = [
2456
                'VIRTUAL',
2457 8
                'PERSISTENT',
2458
                'VIRTUAL GENERATED',
2459
                'STORED GENERATED',
2460
            ];
2461 8
            if (in_array($tableColumn['Extra'], $virtual)) {
2462 2
                continue;
2463 2
            }
2464 2
2465 2
            $htmlOutput .= $this->getHtmlForInsertEditFormColumn(
2466 2
                $tableColumn,
2467 2
                $columnNumber,
2468 2
                $commentsMap,
2469 2
                $timestampSeen,
2470 2
                $currentResult,
2471 2
                $chgEvtHandler,
2472 2
                $jsvkey,
2473 2
                $vkey,
2474 2
                $insertMode,
2475 2
                $currentRow,
2476 2
                $oRows,
2477 2
                $tabindex,
2478 2
                $columnsCnt,
2479 2
                $isUpload,
2480 2
                $foreigners,
2481 2
                $tabindexForValue,
2482 2
                $table,
2483 2
                $db,
2484 2
                $rowId,
2485 2
                $biggestMaxFileSize,
2486 2
                $defaultCharEditing,
2487
                $textDir,
2488
                $repopulate,
2489
                $columnMime,
2490 8
                $whereClause
2491
            );
2492 8
        }
2493 2
2494 2
        $oRows++;
2495
2496
        return $htmlOutput . '  </tbody>'
2497
            . '</table></div><br>'
2498
            . '<div class="clearfloat"></div>';
2499
    }
2500
2501
    /**
2502
     * Returns list of function names that accept WKB as text
2503
     *
2504
     * @return string[]
2505
     */
2506
    private function getGisFromTextFunctions(): array
2507
    {
2508
        return $this->dbi->getVersion() >= 50600 ?
2509
        [
2510
            'ST_GeomFromText',
2511
            'ST_GeomCollFromText',
2512
            'ST_LineFromText',
2513
            'ST_MLineFromText',
2514
            'ST_PointFromText',
2515
            'ST_MPointFromText',
2516
            'ST_PolyFromText',
2517
            'ST_MPolyFromText',
2518
        ] :
2519
        [
2520
            'GeomFromText',
2521
            'GeomCollFromText',
2522
            'LineFromText',
2523
            'MLineFromText',
2524
            'PointFromText',
2525
            'MPointFromText',
2526
            'PolyFromText',
2527
            'MPolyFromText',
2528
        ];
2529
    }
2530
2531
    /**
2532
     * Returns list of function names that accept WKB as binary
2533
     *
2534
     * @return string[]
2535
     */
2536
    private function getGisFromWKBFunctions(): array
2537
    {
2538
        return $this->dbi->getVersion() >= 50600 ?
2539
        [
2540
            'ST_GeomFromWKB',
2541
            'ST_GeomCollFromWKB',
2542
            'ST_LineFromWKB',
2543
            'ST_MLineFromWKB',
2544
            'ST_PointFromWKB',
2545
            'ST_MPointFromWKB',
2546
            'ST_PolyFromWKB',
2547
            'ST_MPolyFromWKB',
2548
        ] :
2549
        [
2550
            'GeomFromWKB',
2551
            'GeomCollFromWKB',
2552
            'LineFromWKB',
2553
            'MLineFromWKB',
2554
            'PointFromWKB',
2555
            'MPointFromWKB',
2556
            'PolyFromWKB',
2557
            'MPolyFromWKB',
2558
        ];
2559
    }
2560
}
2561