3 * set of functions with the insert/edit features in pma
6 declare(strict_types
=1);
10 use PhpMyAdmin\ConfigStorage\Relation
;
11 use PhpMyAdmin\Dbal\ResultInterface
;
12 use PhpMyAdmin\Html\Generator
;
13 use PhpMyAdmin\Plugins\TransformationsPlugin
;
14 use PhpMyAdmin\Utils\Gis
;
17 use function array_fill
;
18 use function array_key_exists
;
19 use function array_keys
;
20 use function array_merge
;
21 use function array_values
;
23 use function class_exists
;
28 use function htmlspecialchars
;
30 use function in_array
;
31 use function is_array
;
33 use function is_string
;
35 use function mb_stripos
;
36 use function mb_strlen
;
37 use function mb_strstr
;
38 use function mb_substr
;
40 use function method_exists
;
42 use function password_hash
;
43 use function preg_match
;
44 use function preg_replace
;
45 use function str_contains
;
46 use function str_replace
;
47 use function stripcslashes
;
48 use function stripslashes
;
55 use const PASSWORD_DEFAULT
;
58 * PhpMyAdmin\InsertEdit class
63 * DatabaseInterface instance
65 * @var DatabaseInterface
72 /** @var Transformations */
73 private $transformations;
75 /** @var FileListing */
82 * @param DatabaseInterface $dbi DatabaseInterface instance
84 public function __construct(DatabaseInterface
$dbi)
87 $this->relation
= new Relation($this->dbi
);
88 $this->transformations
= new Transformations();
89 $this->fileListing
= new FileListing();
90 $this->template
= new Template();
94 * Retrieve form parameters for insert/edit form
96 * @param string $db name of the database
97 * @param string $table name of the table
98 * @param array|null $whereClauses where clauses
99 * @param array $whereClauseArray array of where clauses
100 * @param string $errorUrl error url
102 * @return array array of insert/edit form parameters
104 public function getFormParametersForInsertForm(
107 ?
array $whereClauses,
108 array $whereClauseArray,
114 'goto' => $GLOBALS['goto'],
115 'err_url' => $errorUrl,
116 'sql_query' => $_POST['sql_query'] ??
'',
118 if (isset($whereClauses)) {
119 foreach ($whereClauseArray as $keyId => $whereClause) {
120 $formParams['where_clause[' . $keyId . ']'] = trim($whereClause);
124 if (isset($_POST['clause_is_unique'])) {
125 $formParams['clause_is_unique'] = $_POST['clause_is_unique'];
132 * Creates array of where clauses
134 * @param array|string|null $whereClause where clause
136 * @return array whereClauseArray array of where clauses
138 private function getWhereClauseArray($whereClause): array
140 if ($whereClause === null) {
144 if (is_array($whereClause)) {
148 return [0 => $whereClause];
152 * Analysing where clauses array
154 * @param array $whereClauseArray array of where clauses
155 * @param string $table name of the table
156 * @param string $db name of the database
158 * @return array $where_clauses, $result, $rows, $found_unique_key
160 private function analyzeWhereClauses(
161 array $whereClauseArray,
168 $foundUniqueKey = false;
169 foreach ($whereClauseArray as $keyId => $whereClause) {
170 $localQuery = 'SELECT * FROM '
171 . Util
::backquote($db) . '.'
172 . Util
::backquote($table)
173 . ' WHERE ' . $whereClause . ';';
174 $result[$keyId] = $this->dbi
->query($localQuery);
175 $rows[$keyId] = $result[$keyId]->fetchAssoc();
177 $whereClauses[$keyId] = str_replace('\\', '\\\\', $whereClause);
178 $hasUniqueCondition = $this->showEmptyResultMessageOrSetUniqueCondition(
185 if (! $hasUniqueCondition) {
189 $foundUniqueKey = true;
201 * Show message for empty result or set the unique_condition
203 * @param array $rows MySQL returned rows
204 * @param string $keyId ID in current key
205 * @param array $whereClauseArray array of where clauses
206 * @param string $localQuery query performed
207 * @param ResultInterface[] $result MySQL result handle
209 private function showEmptyResultMessageOrSetUniqueCondition(
212 array $whereClauseArray,
217 if (! $rows[$keyId]) {
218 unset($rows[$keyId], $whereClauseArray[$keyId]);
219 ResponseRenderer
::getInstance()->addHTML(
220 Generator
::getMessage(
221 __('MySQL returned an empty result set (i.e. zero rows).'),
226 * @todo not sure what should be done at this point, but we must not
227 * exit if we want the message to be displayed
233 $meta = $this->dbi
->getFieldsMeta($result[$keyId]);
235 [$uniqueCondition] = Util
::getUniqueCondition(
242 return (bool) $uniqueCondition;
246 * No primary key given, just load first row
248 * @param string $table name of the table
249 * @param string $db name of the database
251 * @return array containing $result and $rows arrays
253 private function loadFirstRow($table, $db)
255 $result = $this->dbi
->query(
256 'SELECT * FROM ' . Util
::backquote($db)
257 . '.' . Util
::backquote($table) . ' LIMIT 1;'
259 // Can be a string on some old configuration storage settings
260 $rows = array_fill(0, (int) $GLOBALS['cfg']['InsertRows'], false);
269 * Add some url parameters
271 * @param array $urlParams containing $db and $table as url parameters
272 * @param array $whereClauseArray where clauses array
274 * @return array Add some url parameters to $url_params array and return it
276 public function urlParamsInEditMode(
278 array $whereClauseArray
280 foreach ($whereClauseArray as $whereClause) {
281 $urlParams['where_clause'] = trim($whereClause);
284 if (! empty($_POST['sql_query'])) {
285 $urlParams['sql_query'] = $_POST['sql_query'];
292 * Show type information or function selectors in Insert/Edit
294 * @param string $which function|type
295 * @param array $urlParams containing url parameters
296 * @param bool $isShow whether to show the element in $which
298 * @return string an HTML snippet
300 public function showTypeOrFunction($which, array $urlParams, $isShow): string
306 $params['ShowFunctionFields'] = ($isShow ?
0 : 1);
307 $params['ShowFieldTypesInDataEditView'] = $GLOBALS['cfg']['ShowFieldTypesInDataEditView'];
310 $params['ShowFieldTypesInDataEditView'] = ($isShow ?
0 : 1);
311 $params['ShowFunctionFields'] = $GLOBALS['cfg']['ShowFunctionFields'];
315 $params['goto'] = Url
::getFromRoute('/sql');
316 $thisUrlParams = array_merge($urlParams, $params);
319 return ' : <a href="' . Url
::getFromRoute('/table/change') . '" data-post="'
320 . Url
::getCommon($thisUrlParams, '', false) . '">'
321 . $this->showTypeOrFunctionLabel($which)
325 return '<th><a href="' . Url
::getFromRoute('/table/change') . '" data-post="'
326 . Url
::getCommon($thisUrlParams, '', false)
327 . '" title="' . __('Hide') . '">'
328 . $this->showTypeOrFunctionLabel($which)
333 * Show type information or function selectors labels in Insert/Edit
335 * @param string $which function|type
337 * @return string an HTML snippet
339 private function showTypeOrFunctionLabel($which): string
343 return __('Function');
353 * Analyze the table column array
355 * @param array $column description of column in given table
356 * @param array $commentsMap comments for every column that has a comment
357 * @param bool $timestampSeen whether a timestamp has been seen
359 * @return array description of column in given table
361 private function analyzeTableColumnsArray(
366 $column['Field_md5'] = md5($column['Field']);
367 // True_Type contains only the type (stops at first bracket)
368 $column['True_Type'] = preg_replace('@\(.*@s', '', $column['Type']);
369 $column['len'] = preg_match('@float|double@', $column['Type']) ?
100 : -1;
370 $column['Field_title'] = $this->getColumnTitle($column, $commentsMap);
371 $column['is_binary'] = $this->isColumn(
378 $column['is_blob'] = $this->isColumn(
387 $column['is_char'] = $this->isColumn(
398 $column['first_timestamp'],
399 ] = $this->getEnumSetAndTimestampColumns($column, $timestampSeen);
405 * Retrieve the column title
407 * @param array $column description of column in given table
408 * @param array $commentsMap comments for every column that has a comment
410 * @return string column title
412 private function getColumnTitle(array $column, array $commentsMap): string
414 if (isset($commentsMap[$column['Field']])) {
415 return '<span style="border-bottom: 1px dashed black;" title="'
416 . htmlspecialchars($commentsMap[$column['Field']]) . '">'
417 . htmlspecialchars($column['Field']) . '</span>';
420 return htmlspecialchars($column['Field']);
424 * check whether the column is of a certain type
425 * the goal is to ensure that types such as "enum('one','two','binary',..)"
426 * or "enum('one','two','varbinary',..)" are not categorized as binary
428 * @param array $column description of column in given table
429 * @param string[] $types the types to verify
431 public function isColumn(array $column, array $types): bool
433 foreach ($types as $oneType) {
434 if (mb_stripos($column['Type'], $oneType) === 0) {
443 * Retrieve set, enum, timestamp table columns
445 * @param array $column description of column in given table
446 * @param bool $timestampSeen whether a timestamp has been seen
448 * @return array $column['pma_type'], $column['wrap'], $column['first_timestamp']
449 * @psalm-return array{0: mixed, 1: string, 2: bool}
451 private function getEnumSetAndTimestampColumns(array $column, $timestampSeen)
453 switch ($column['True_Type']) {
472 ! $timestampSeen, // can only occur once per table
485 * Retrieve the nullify code for the null column
487 * @param array $column description of column in given table
488 * @param array $foreigners keys into foreign fields
489 * @param array $foreignData data about the foreign keys
491 private function getNullifyCodeForNullColumn(
496 $foreigner = $this->relation
->searchColumnInForeigners($foreigners, $column['Field']);
497 if (mb_strstr($column['True_Type'], 'enum')) {
498 if (mb_strlen((string) $column['Type']) > 20) {
503 } elseif (mb_strstr($column['True_Type'], 'set')) {
505 } elseif ($foreigner && $foreignData['foreign_link'] == false) {
506 // foreign key in a drop-down
508 } elseif ($foreigner && $foreignData['foreign_link'] == true) {
509 // foreign key with a browsing icon
519 * Get HTML textarea for insert form
521 * @param array $column column information
522 * @param string $backupField hidden input field
523 * @param string $columnNameAppendix the name attribute
524 * @param string $onChangeClause onchange clause for fields
525 * @param int $tabindex tab index
526 * @param int $tabindexForValue offset for the values tabindex
527 * @param int $idindex id index
528 * @param string $textDir text direction
529 * @param string $specialCharsEncoded replaced char if the string starts
530 * with a \r\n pair (0x0d0a) add an extra \n
531 * @param string $dataType the html5 data-* attribute type
532 * @param bool $readOnly is column read only or not
534 * @return string an html snippet
536 private function getTextarea(
545 $specialCharsEncoded,
550 $textAreaRows = $GLOBALS['cfg']['TextareaRows'];
551 $textareaCols = $GLOBALS['cfg']['TextareaCols'];
553 if ($column['is_char']) {
555 * @todo clarify the meaning of the "textfield" class and explain
556 * why character columns have the "char" class instead
558 $theClass = 'char charField';
559 $textAreaRows = $GLOBALS['cfg']['CharTextareaRows'];
560 $textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
561 $extractedColumnspec = Util
::extractColumnSpec($column['Type']);
562 $maxlength = $extractedColumnspec['spec_in_brackets'];
563 } elseif ($GLOBALS['cfg']['LongtextDoubleTextarea'] && mb_strstr($column['pma_type'], 'longtext')) {
564 $textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
565 $textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
568 return $backupField . "\n"
569 . '<textarea name="fields' . $columnNameAppendix . '"'
570 . ' class="' . $theClass . '"'
571 . ($readOnly ?
' readonly="readonly"' : '')
572 . (isset($maxlength) ?
' data-maxlength="' . $maxlength . '"' : '')
573 . ' rows="' . $textAreaRows . '"'
574 . ' cols="' . $textareaCols . '"'
575 . ' dir="' . $textDir . '"'
576 . ' id="field_' . $idindex . '_3"'
577 . ($onChangeClause ?
' ' . $onChangeClause : '')
578 . ' tabindex="' . ($tabindex +
$tabindexForValue) . '"'
579 . ' data-type="' . $dataType . '">'
580 . $specialCharsEncoded
587 * @param string[] $enum_set_values
589 * @return array column values as an associative array
590 * @psalm-return list<array{html: string, plain: string}>
592 private function getColumnEnumValues(array $enum_set_values): array
595 foreach ($enum_set_values as $val) {
598 'html' => htmlspecialchars($val),
606 * Retrieve column 'set' value and select size
608 * @param array $column description of column in given table
609 * @param string[] $enum_set_values
611 * @return array $column['values'], $column['select_size']
613 private function getColumnSetValueAndSelectSize(
615 array $enum_set_values
617 if (! isset($column['values'])) {
618 $column['values'] = [];
619 foreach ($enum_set_values as $val) {
620 $column['values'][] = [
622 'html' => htmlspecialchars($val),
626 $column['select_size'] = min(4, count($column['values']));
631 $column['select_size'],
636 * Get HTML input type
638 * @param array $column description of column in given table
639 * @param string $columnNameAppendix the name attribute
640 * @param string $specialChars special characters
641 * @param int $fieldsize html field size
642 * @param string $onChangeClause onchange clause for fields
643 * @param int $tabindex tab index
644 * @param int $tabindexForValue offset for the values tabindex
645 * @param int $idindex id index
646 * @param string $dataType the html5 data-* attribute type
647 * @param bool $readOnly is column read only or not
649 * @return string an html snippet
651 private function getHtmlInput(
663 $theClass = 'textfield';
664 // verify True_Type which does not contain the parentheses and length
666 if ($column['True_Type'] === 'date') {
667 $theClass .= ' datefield';
668 } elseif ($column['True_Type'] === 'time') {
669 $theClass .= ' timefield';
670 } elseif ($column['True_Type'] === 'datetime' ||
$column['True_Type'] === 'timestamp') {
671 $theClass .= ' datetimefield';
676 if (in_array($column['True_Type'], $this->dbi
->types
->getIntegerTypes())) {
677 $extractedColumnspec = Util
::extractColumnSpec($column['Type']);
678 $isUnsigned = $extractedColumnspec['unsigned'];
679 $minMaxValues = $this->dbi
->types
->getIntegerRange($column['True_Type'], ! $isUnsigned);
680 $inputMinMax = 'min="' . $minMaxValues[0] . '" '
681 . 'max="' . $minMaxValues[1] . '"';
685 // do not use the 'date' or 'time' types here; they have no effect on some
686 // browsers and create side effects (see bug #4218)
687 return '<input type="text"'
688 . ' name="fields' . $columnNameAppendix . '"'
689 . ' value="' . $specialChars . '" size="' . $fieldsize . '"'
690 . (isset($column['is_char']) && $column['is_char']
691 ?
' data-maxlength="' . $fieldsize . '"'
693 . ($readOnly ?
' readonly="readonly"' : '')
694 . ($inputMinMax ?
' ' . $inputMinMax : '')
695 . ' data-type="' . $dataType . '"'
696 . ' class="' . $theClass . '" ' . $onChangeClause
697 . ' tabindex="' . ($tabindex +
$tabindexForValue) . '"'
698 . ' id="field_' . $idindex . '_3">';
702 * Get HTML select option for upload
704 * @param string $vkey [multi_edit]['row_id']
705 * @param string $fieldHashMd5 array index as an MD5 to avoid having special characters
707 * @return string an HTML snippet
709 private function getSelectOptionForUpload(string $vkey, string $fieldHashMd5): string
711 $files = $this->fileListing
->getFileSelectOptions(
712 Util
::userDir((string) ($GLOBALS['cfg']['UploadDir'] ??
''))
715 if ($files === false) {
716 return '<span style="color:red">' . __('Error') . '</span><br>' . "\n"
717 . __('The directory you set for upload work cannot be reached.') . "\n";
725 . '<i>' . __('Or') . '</i> '
726 . __('web server upload directory:') . '<br>' . "\n"
727 . '<select size="1" name="fields_uploadlocal'
728 . $vkey . '[' . $fieldHashMd5 . ']">' . "\n"
729 . '<option value="" selected="selected"></option>' . "\n"
731 . '</select>' . "\n";
735 * Retrieve the maximum upload file size
737 * @param string $pma_type column type
738 * @param int $biggestMaxFileSize biggest max file size for uploading
740 * @return array an html snippet and $biggest_max_file_size
741 * @psalm-return array{non-empty-string, int}
743 private function getMaxUploadSize(string $pma_type, $biggestMaxFileSize): array
745 // find maximum upload size, based on field type
747 * @todo with functions this is not so easy, as you can basically
748 * process any data with function like MD5
753 'mediumblob' => 16777216,
754 'longblob' => 4294967296,// yeah, really
757 $thisFieldMaxSize = (int) $GLOBALS['config']->get('max_upload_size'); // from PHP max
758 if ($thisFieldMaxSize > $maxFieldSizes[$pma_type]) {
759 $thisFieldMaxSize = $maxFieldSizes[$pma_type];
762 $htmlOutput = Util
::getFormattedMaximumUploadSize($thisFieldMaxSize) . "\n";
763 // do not generate here the MAX_FILE_SIZE, because we should
764 // put only one in the form to accommodate the biggest field
765 if ($thisFieldMaxSize > $biggestMaxFileSize) {
766 $biggestMaxFileSize = $thisFieldMaxSize;
776 * Get HTML for the Value column of other datatypes
777 * (here, "column" is used in the sense of HTML column in HTML table)
779 * @param array $column description of column in given table
780 * @param string $defaultCharEditing default char editing mode which is stored
781 * in the config.inc.php script
782 * @param string $backupField hidden input field
783 * @param string $columnNameAppendix the name attribute
784 * @param string $onChangeClause onchange clause for fields
785 * @param int $tabindex tab index
786 * @param string $specialChars special characters
787 * @param int $tabindexForValue offset for the values tabindex
788 * @param int $idindex id index
789 * @param string $textDir text direction
790 * @param string $specialCharsEncoded replaced char if the string starts
791 * with a \r\n pair (0x0d0a) add an extra \n
792 * @param string $data data to edit
793 * @param array $extractedColumnspec associative array containing type,
794 * spec_in_brackets and possibly
795 * enum_set_values (another array)
796 * @param bool $readOnly is column read only or not
798 * @return string an html snippet
800 private function getValueColumnForOtherDatatypes(
811 $specialCharsEncoded,
813 array $extractedColumnspec,
816 // HTML5 data-* attribute data-type
817 $dataType = $this->dbi
->types
->getTypeClass($column['True_Type']);
818 $fieldsize = $this->getColumnSize($column, $extractedColumnspec['spec_in_brackets']);
820 $isTextareaRequired = $column['is_char']
821 && ($GLOBALS['cfg']['CharEditing'] === 'textarea' ||
str_contains($data, "\n"));
822 if ($isTextareaRequired) {
823 $GLOBALS['cfg']['CharEditing'] = $defaultCharEditing;
824 $htmlField = $this->getTextarea(
833 $specialCharsEncoded,
838 $htmlField = $this->getHtmlInput(
852 return $this->template
->render('table/insert/value_column_for_other_datatype', [
853 'html_field' => $htmlField,
854 'backup_field' => $backupField,
855 'is_textarea' => $isTextareaRequired,
856 'columnNameAppendix' => $columnNameAppendix,
864 * @param array $column description of column in given table
865 * @param string $specInBrackets text in brackets inside column definition
867 * @return int field size
869 private function getColumnSize(array $column, string $specInBrackets): int
871 if ($column['is_char']) {
872 $fieldsize = (int) $specInBrackets;
873 if ($fieldsize > $GLOBALS['cfg']['MaxSizeForInputField']) {
875 * This case happens for CHAR or VARCHAR columns which have
876 * a size larger than the maximum size for input field.
878 $GLOBALS['cfg']['CharEditing'] = 'textarea';
882 * This case happens for example for INT or DATE columns;
883 * in these situations, the value returned in $column['len']
886 $fieldsize = $column['len'];
890 max($fieldsize, $GLOBALS['cfg']['MinSizeForInputField']),
891 $GLOBALS['cfg']['MaxSizeForInputField']
896 * get html for continue insertion form
898 * @param string $table name of the table
899 * @param string $db name of the database
900 * @param array $whereClauseArray array of where clauses
901 * @param string $errorUrl error url
903 * @return string an html snippet
905 public function getContinueInsertionForm(
908 array $whereClauseArray,
911 return $this->template
->render('table/insert/continue_insertion_form', [
914 'where_clause_array' => $whereClauseArray,
915 'err_url' => $errorUrl,
916 'goto' => $GLOBALS['goto'],
917 'sql_query' => $_POST['sql_query'] ??
null,
918 'has_where_clause' => isset($_POST['where_clause']),
919 'insert_rows_default' => $GLOBALS['cfg']['InsertRows'],
924 * @param string[]|string|null $whereClause
928 public static function isWhereClauseNumeric($whereClause): bool
930 if ($whereClause === null) {
934 if (! is_array($whereClause)) {
935 $whereClause = [$whereClause];
938 // If we have just numeric primary key, we can also edit next
939 // we are looking for `table_name`.`field_name` = numeric_value
940 foreach ($whereClause as $clause) {
941 // preg_match() returns 1 if there is a match
942 $isNumeric = preg_match('@^[\s]*`[^`]*`[\.]`[^`]*` = [0-9]+@', $clause) === 1;
952 * Get table head and table foot for insert row table
954 * @param array $urlParams url parameters
956 * @return string an html snippet
958 private function getHeadAndFootOfInsertRowTable(array $urlParams): string
963 if ($GLOBALS['cfg']['ShowFieldTypesInDataEditView']) {
964 $type = $this->showTypeOrFunction('type', $urlParams, true);
967 if ($GLOBALS['cfg']['ShowFunctionFields']) {
968 $function = $this->showTypeOrFunction('function', $urlParams, true);
971 $template = new Template();
973 return $template->render('table/insert/get_head_and_foot_of_insert_row_table', [
975 'function' => $function,
980 * Prepares the field value and retrieve special chars, backup field and data array
982 * @param array $currentRow a row of the table
983 * @param array $column description of column in given table
984 * @param array $extractedColumnspec associative array containing type,
985 * spec_in_brackets and possibly
986 * enum_set_values (another array)
987 * @param array $gisDataTypes list of GIS data types
988 * @param string $columnNameAppendix string to append to column name in input
989 * @param bool $asIs use the data as is, used in repopulating
991 * @return array $real_null_value, $data, $special_chars, $backup_field,
992 * $special_chars_encoded
994 private function getSpecialCharsAndBackupFieldForExistingRow(
997 array $extractedColumnspec,
1002 $specialCharsEncoded = '';
1004 $realNullValue = false;
1006 if (! isset($currentRow[$column['Field']])) {
1007 $realNullValue = true;
1008 $currentRow[$column['Field']] = '';
1010 $data = $currentRow[$column['Field']];
1011 } elseif ($column['True_Type'] === 'bit') {
1012 $specialChars = $asIs
1013 ?
$currentRow[$column['Field']]
1014 : Util
::printableBitValue(
1015 (int) $currentRow[$column['Field']],
1016 (int) $extractedColumnspec['spec_in_brackets']
1019 (substr($column['True_Type'], 0, 9) === 'timestamp'
1020 ||
$column['True_Type'] === 'datetime'
1021 ||
$column['True_Type'] === 'time')
1022 && (str_contains($currentRow[$column['Field']], '.'))
1024 $currentRow[$column['Field']] = $asIs
1025 ?
$currentRow[$column['Field']]
1026 : Util
::addMicroseconds($currentRow[$column['Field']]);
1027 $specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT
);
1028 } elseif (in_array($column['True_Type'], $gisDataTypes)) {
1029 // Convert gis data to Well Know Text format
1030 $currentRow[$column['Field']] = $asIs
1031 ?
$currentRow[$column['Field']]
1032 : Gis
::convertToWellKnownText($currentRow[$column['Field']], true);
1033 $specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT
);
1035 // special binary "characters"
1036 if ($column['is_binary'] ||
($column['is_blob'] && $GLOBALS['cfg']['ProtectBinary'] !== 'all')) {
1037 $currentRow[$column['Field']] = $asIs
1038 ?
$currentRow[$column['Field']]
1039 : bin2hex($currentRow[$column['Field']]);
1042 $specialChars = htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT
);
1044 //We need to duplicate the first \n or otherwise we will lose
1045 //the first newline entered in a VARCHAR or TEXT column
1046 $specialCharsEncoded = Util
::duplicateFirstNewline($specialChars);
1048 $data = $currentRow[$column['Field']];
1051 //when copying row, it is useful to empty auto-increment column
1052 // to prevent duplicate key error
1053 if (isset($_POST['default_action']) && $_POST['default_action'] === 'insert') {
1054 if ($column['Key'] === 'PRI' && str_contains($column['Extra'], 'auto_increment')) {
1055 $data = $specialCharsEncoded = $specialChars = null;
1059 // If a timestamp field value is not included in an update
1060 // statement MySQL auto-update it to the current timestamp;
1061 // however, things have changed since MySQL 4.1, so
1062 // it's better to set a fields_prev in this situation
1063 $backupField = '<input type="hidden" name="fields_prev'
1064 . $columnNameAppendix . '" value="'
1065 . htmlspecialchars($currentRow[$column['Field']], ENT_COMPAT
) . '">';
1069 $specialCharsEncoded,
1077 * display default values
1079 * @param array $column description of column in given table
1081 * @return array $real_null_value, $data, $special_chars,
1082 * $backup_field, $special_chars_encoded
1083 * @psalm-return array{bool, mixed, string, string, string}
1085 private function getSpecialCharsAndBackupFieldForInsertingMode(
1088 if (! isset($column['Default'])) {
1089 $column['Default'] = '';
1090 $realNullValue = true;
1093 $realNullValue = false;
1094 $data = $column['Default'];
1097 $trueType = $column['True_Type'];
1099 if ($trueType === 'bit') {
1100 $specialChars = Util
::convertBitDefaultValue($column['Default']);
1101 } elseif (substr($trueType, 0, 9) === 'timestamp' ||
$trueType === 'datetime' ||
$trueType === 'time') {
1102 $specialChars = Util
::addMicroseconds($column['Default']);
1103 } elseif ($trueType === 'binary' ||
$trueType === 'varbinary') {
1104 $specialChars = bin2hex($column['Default']);
1105 } elseif (substr($trueType, -4) === 'text') {
1106 $textDefault = substr($column['Default'], 1, -1);
1107 $specialChars = stripcslashes($textDefault !== false ?
$textDefault : $column['Default']);
1109 $specialChars = htmlspecialchars($column['Default']);
1112 $specialCharsEncoded = Util
::duplicateFirstNewline($specialChars);
1119 $specialCharsEncoded,
1124 * Prepares the update/insert of a row
1126 * @return array $loop_array, $using_key, $is_insert, $is_insertignore
1127 * @psalm-return array{array, bool, bool, bool}
1129 public function getParamsForUpdateOrInsert()
1131 if (isset($_POST['where_clause'])) {
1132 // we were editing something => use the WHERE clause
1133 $loopArray = is_array($_POST['where_clause'])
1134 ?
$_POST['where_clause']
1135 : [$_POST['where_clause']];
1137 $isInsert = isset($_POST['submit_type'])
1138 && ($_POST['submit_type'] === 'insert'
1139 ||
$_POST['submit_type'] === 'showinsert'
1140 ||
$_POST['submit_type'] === 'insertignore');
1142 // new row => use indexes
1144 if (! empty($_POST['fields'])) {
1145 $loopArray = array_keys($_POST['fields']['multi_edit']);
1152 $isInsertIgnore = isset($_POST['submit_type'])
1153 && $_POST['submit_type'] === 'insertignore';
1164 * set $_SESSION for edit_next
1166 * @param string $oneWhereClause one where clause from where clauses array
1168 public function setSessionForEditNext($oneWhereClause): void
1170 $localQuery = 'SELECT * FROM ' . Util
::backquote($GLOBALS['db'])
1171 . '.' . Util
::backquote($GLOBALS['table']) . ' WHERE '
1172 . str_replace('` =', '` >', $oneWhereClause) . ' LIMIT 1;';
1174 $res = $this->dbi
->query($localQuery);
1175 $row = $res->fetchRow();
1176 $meta = $this->dbi
->getFieldsMeta($res);
1177 // must find a unique condition based on unique key,
1178 // not a combination of all fields
1179 [$uniqueCondition] = Util
::getUniqueCondition(
1185 if (! $uniqueCondition) {
1189 $_SESSION['edit_next'] = $uniqueCondition;
1193 * set $goto_include variable for different cases and retrieve like,
1194 * if $GLOBALS['goto'] empty, if $goto_include previously not defined
1195 * and new_insert, same_insert, edit_next
1197 * @param string|false $gotoInclude store some script for include, otherwise it is
1200 public function getGotoInclude($gotoInclude): string
1207 if (isset($_POST['after_insert']) && in_array($_POST['after_insert'], $validOptions)) {
1208 return '/table/change';
1211 if (! empty($GLOBALS['goto'])) {
1212 if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
1213 // this should NOT happen
1214 //$GLOBALS['goto'] = false;
1215 if ($GLOBALS['goto'] === 'index.php?route=/sql') {
1216 $gotoInclude = '/sql';
1218 $gotoInclude = false;
1221 $gotoInclude = $GLOBALS['goto'];
1224 if ($GLOBALS['goto'] === 'index.php?route=/database/sql' && strlen($GLOBALS['table']) > 0) {
1225 $GLOBALS['table'] = '';
1229 if (! $gotoInclude) {
1230 if (strlen($GLOBALS['table']) === 0) {
1231 $gotoInclude = '/database/sql';
1233 $gotoInclude = '/table/sql';
1237 return $gotoInclude;
1241 * Defines the url to return in case of failure of the query
1243 * @param array $urlParams url parameters
1245 * @return string error url for query failure
1247 public function getErrorUrl(array $urlParams)
1249 if (isset($_POST['err_url'])) {
1250 return $_POST['err_url'];
1253 return Url
::getFromRoute('/table/change', $urlParams);
1257 * Builds the sql query
1259 * @param bool $isInsertIgnore $_POST['submit_type'] === 'insertignore'
1260 * @param array $queryFields column names array
1261 * @param array $valueSets array of query values
1263 * @return array of query
1264 * @psalm-return array{string}
1266 public function buildSqlQuery(bool $isInsertIgnore, array $queryFields, array $valueSets)
1268 if ($isInsertIgnore) {
1269 $insertCommand = 'INSERT IGNORE ';
1271 $insertCommand = 'INSERT ';
1275 $insertCommand . 'INTO '
1276 . Util
::backquote($GLOBALS['table'])
1277 . ' (' . implode(', ', $queryFields) . ') VALUES ('
1278 . implode('), (', $valueSets) . ')',
1283 * Executes the sql query and get the result, then move back to the calling page
1285 * @param array $urlParams url parameters array
1286 * @param array $query built query from buildSqlQuery()
1288 * @return array $url_params, $total_affected_rows, $last_messages
1289 * $warning_messages, $error_messages, $return_to_sql_query
1291 public function executeSqlQuery(array $urlParams, array $query)
1293 $returnToSqlQuery = '';
1294 if (! empty($GLOBALS['sql_query'])) {
1295 $urlParams['sql_query'] = $GLOBALS['sql_query'];
1296 $returnToSqlQuery = $GLOBALS['sql_query'];
1299 $GLOBALS['sql_query'] = implode('; ', $query) . ';';
1300 // to ensure that the query is displayed in case of
1301 // "insert as new row" and then "insert another new row"
1302 $GLOBALS['display_query'] = $GLOBALS['sql_query'];
1304 $totalAffectedRows = 0;
1306 $warningMessages = [];
1307 $errorMessages = [];
1309 foreach ($query as $singleQuery) {
1310 if (isset($_POST['submit_type']) && $_POST['submit_type'] === 'showinsert') {
1311 $lastMessages[] = Message
::notice(__('Showing SQL query'));
1315 if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
1316 $result = $this->dbi
->tryQuery($singleQuery);
1318 $result = $this->dbi
->query($singleQuery);
1322 $errorMessages[] = $this->dbi
->getError();
1324 $totalAffectedRows +
= $this->dbi
->affectedRows();
1326 $insertId = $this->dbi
->insertId();
1328 // insert_id is id of FIRST record inserted in one insert, so if we
1329 // inserted multiple rows, we had to increment this
1331 if ($totalAffectedRows > 0) {
1332 $insertId +
= $totalAffectedRows - 1;
1335 $lastMessage = Message
::notice(__('Inserted row id: %1$d'));
1336 $lastMessage->addParam($insertId);
1337 $lastMessages[] = $lastMessage;
1341 $warningMessages = $this->getWarningMessages();
1355 * get the warning messages array
1359 private function getWarningMessages(): array
1361 $warningMessages = [];
1362 foreach ($this->dbi
->getWarnings() as $warning) {
1363 $warningMessages[] = htmlspecialchars((string) $warning);
1366 return $warningMessages;
1370 * Column to display from the foreign table?
1372 * @param string $whereComparison string that contain relation field value
1373 * @param array $map all Relations to foreign tables for a given
1374 * table or optionally a given column in a table
1375 * @param string $relationField relation field
1377 * @return string display value from the foreign table
1379 public function getDisplayValueForForeignTableColumn(
1384 $foreigner = $this->relation
->searchColumnInForeigners($map, $relationField);
1386 if (! is_array($foreigner)) {
1390 $displayField = $this->relation
->getDisplayField($foreigner['foreign_db'], $foreigner['foreign_table']);
1391 // Field to display from the foreign table?
1392 if (is_string($displayField) && strlen($displayField) > 0) {
1393 $dispsql = 'SELECT ' . Util
::backquote($displayField)
1394 . ' FROM ' . Util
::backquote($foreigner['foreign_db'])
1395 . '.' . Util
::backquote($foreigner['foreign_table'])
1396 . ' WHERE ' . Util
::backquote($foreigner['foreign_field'])
1398 $dispresult = $this->dbi
->tryQuery($dispsql);
1399 if ($dispresult && $dispresult->numRows() > 0) {
1400 return (string) $dispresult->fetchValue();
1408 * Display option in the cell according to user choices
1410 * @param array $map all Relations to foreign tables for a given
1411 * table or optionally a given column in a table
1412 * @param string $relationField relation field
1413 * @param string $whereComparison string that contain relation field value
1414 * @param string $dispval display value from the foreign table
1415 * @param string $relationFieldValue relation field value
1417 * @return string HTML <a> tag
1419 public function getLinkForRelationalDisplayField(
1426 $foreigner = $this->relation
->searchColumnInForeigners($map, $relationField);
1428 if (! is_array($foreigner)) {
1432 if ($_SESSION['tmpval']['relational_display'] === 'K') {
1433 // user chose "relational key" in the display options, so
1434 // the title contains the display field
1436 ?
' title="' . htmlspecialchars($dispval) . '"'
1439 $title = ' title="' . htmlspecialchars($relationFieldValue) . '"';
1442 $sqlQuery = 'SELECT * FROM '
1443 . Util
::backquote($foreigner['foreign_db'])
1444 . '.' . Util
::backquote($foreigner['foreign_table'])
1445 . ' WHERE ' . Util
::backquote($foreigner['foreign_field'])
1448 'db' => $foreigner['foreign_db'],
1449 'table' => $foreigner['foreign_table'],
1451 'sql_signature' => Core
::signSqlQuery($sqlQuery),
1452 'sql_query' => $sqlQuery,
1454 $output = '<a href="' . Url
::getFromRoute('/sql', $urlParams) . '"' . $title . '>';
1456 if ($_SESSION['tmpval']['relational_display'] === 'D') {
1457 // user chose "relational display field" in the
1458 // display options, so show display field in the cell
1459 $output .= htmlspecialchars($dispval);
1461 // otherwise display data in the cell
1462 $output .= htmlspecialchars($relationFieldValue);
1471 * Transform edited values
1473 * @param string $db db name
1474 * @param string $table table name
1475 * @param array $transformation mimetypes for all columns of a table
1476 * [field_name][field_key]
1477 * @param array $editedValues transform columns list and new values
1478 * @param string $file file containing the transformation plugin
1479 * @param string $columnName column name
1480 * @param array $extraData extra data array
1481 * @param string $type the type of transformation
1485 public function transformEditedValues(
1488 array $transformation,
1489 array &$editedValues,
1495 $includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
1496 if (is_file(ROOT_PATH
. $includeFile)) {
1497 // $cfg['SaveCellsAtOnce'] = true; JS code sends an array
1498 $whereClause = is_array($_POST['where_clause']) ?
$_POST['where_clause'][0] : $_POST['where_clause'];
1502 'where_clause_sign' => Core
::signSqlQuery($whereClause),
1503 'where_clause' => $whereClause,
1504 'transform_key' => $columnName,
1506 $transformOptions = $this->transformations
->getOptions($transformation[$type . '_options'] ??
'');
1507 $transformOptions['wrapper_link'] = Url
::getCommon($urlParams);
1508 $transformOptions['wrapper_params'] = $urlParams;
1509 $className = $this->transformations
->getClassName($includeFile);
1510 if (class_exists($className)) {
1511 /** @var TransformationsPlugin $transformationPlugin */
1512 $transformationPlugin = new $className();
1514 foreach ($editedValues as $cellIndex => $currCellEditedValues) {
1515 if (! isset($currCellEditedValues[$columnName])) {
1519 $extraData['transformations'][$cellIndex] = $transformationPlugin->applyTransformation(
1520 $currCellEditedValues[$columnName],
1523 $editedValues[$cellIndex][$columnName] = $extraData['transformations'][$cellIndex];
1532 * Get current value in multi edit mode
1534 * @param array $multiEditFuncs multiple edit functions array
1535 * @param array $multiEditSalt multiple edit array with encryption salt
1536 * @param array $gisFromTextFunctions array that contains gis from text functions
1537 * @param string $currentValue current value in the column
1538 * @param array $gisFromWkbFunctions initially $val is $multi_edit_columns[$key]
1539 * @param array $funcOptionalParam array('RAND','UNIX_TIMESTAMP')
1540 * @param array $funcNoParam array of set of string
1541 * @param string $key an md5 of the column name
1543 public function getCurrentValueAsAnArrayForMultipleEdit(
1546 $gisFromTextFunctions,
1548 $gisFromWkbFunctions,
1553 if (empty($multiEditFuncs[$key])) {
1554 return $currentValue;
1557 if ($multiEditFuncs[$key] === 'PHP_PASSWORD_HASH') {
1559 * @see https://github.com/vimeo/psalm/issues/3350
1561 * @psalm-suppress InvalidArgument
1563 $hash = password_hash($currentValue, PASSWORD_DEFAULT
);
1565 return "'" . $hash . "'";
1568 if ($multiEditFuncs[$key] === 'UUID') {
1569 /* This way user will know what UUID new row has */
1570 $uuid = (string) $this->dbi
->fetchValue('SELECT UUID()');
1572 return "'" . $uuid . "'";
1576 in_array($multiEditFuncs[$key], $gisFromTextFunctions)
1577 ||
in_array($multiEditFuncs[$key], $gisFromWkbFunctions)
1579 // Remove enclosing apostrophes
1580 $currentValue = mb_substr($currentValue, 1, -1);
1581 // Remove escaping apostrophes
1582 $currentValue = str_replace("''", "'", $currentValue);
1583 // Remove backslash-escaped apostrophes
1584 $currentValue = str_replace("\'", "'", $currentValue);
1586 return $multiEditFuncs[$key] . '(' . $currentValue . ')';
1590 ! in_array($multiEditFuncs[$key], $funcNoParam)
1591 ||
($currentValue != "''"
1592 && in_array($multiEditFuncs[$key], $funcOptionalParam))
1595 (isset($multiEditSalt[$key])
1596 && ($multiEditFuncs[$key] === 'AES_ENCRYPT'
1597 ||
$multiEditFuncs[$key] === 'AES_DECRYPT'))
1598 ||
(! empty($multiEditSalt[$key])
1599 && ($multiEditFuncs[$key] === 'DES_ENCRYPT'
1600 ||
$multiEditFuncs[$key] === 'DES_DECRYPT'
1601 ||
$multiEditFuncs[$key] === 'ENCRYPT'))
1603 return $multiEditFuncs[$key] . '(' . $currentValue . ",'"
1604 . $this->dbi
->escapeString($multiEditSalt[$key]) . "')";
1607 return $multiEditFuncs[$key] . '(' . $currentValue . ')';
1610 return $multiEditFuncs[$key] . '()';
1614 * Get query values array and query fields array for insert and update in multi edit
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
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
1631 * @return array[] ($query_values, $query_fields)
1633 public function getQueryValuesForInsertAndUpdateInMultipleEdit(
1634 $multiEditColumnsName,
1635 $multiEditColumnsNull,
1637 $multiEditColumnsPrev,
1642 $currentValueAsAnArray,
1645 $multiEditColumnsNullPrev
1649 // no need to add column into the valuelist
1650 if (strlen($currentValueAsAnArray) > 0) {
1651 $queryValues[] = $currentValueAsAnArray;
1652 // first inserted row so prepare the list of fields
1653 if (empty($valueSets)) {
1654 $queryFields[] = Util
::backquote($multiEditColumnsName[$key]);
1657 } elseif (! empty($multiEditColumnsNullPrev[$key]) && ! isset($multiEditColumnsNull[$key])) {
1660 // field had the null checkbox before the update
1661 // field no longer has the null checkbox
1662 $queryValues[] = Util
::backquote($multiEditColumnsName[$key])
1663 . ' = ' . $currentValueAsAnArray;
1665 ! (empty($multiEditFuncs[$key])
1666 && isset($multiEditColumnsPrev[$key])
1667 && (($currentValue === "'" . $this->dbi
->escapeString($multiEditColumnsPrev[$key]) . "'")
1668 ||
($currentValue === '0x' . $multiEditColumnsPrev[$key])))
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 if (empty($multiEditColumnsNullPrev[$key]) ||
empty($multiEditColumnsNull[$key])) {
1675 $queryValues[] = Util
::backquote($multiEditColumnsName[$key])
1676 . ' = ' . $currentValueAsAnArray;
1687 * Get the current column value in the form for different data types
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 * @param array $multiEditFuncs multiple edit functions array
1704 * @return string current column value in the form
1706 public function getCurrentValueForDifferentTypes(
1707 $possiblyUploadedVal,
1709 ?
array $multiEditColumnsType,
1711 ?
array $multiEditAutoIncrement,
1713 $multiEditColumnsName,
1714 $multiEditColumnsNull,
1715 $multiEditColumnsNullPrev,
1722 if ($possiblyUploadedVal !== false) {
1723 return $possiblyUploadedVal;
1726 if (! empty($multiEditFuncs[$key])) {
1727 return "'" . $this->dbi
->escapeString($currentValue) . "'";
1730 // c o l u m n v a l u e i n t h e f o r m
1731 $type = $multiEditColumnsType[$key] ??
'';
1733 if ($type !== 'protected' && $type !== 'set' && strlen($currentValue) === 0) {
1734 // best way to avoid problems in strict mode
1735 // (works also in non-strict mode)
1736 $currentValue = "''";
1737 if (isset($multiEditAutoIncrement, $multiEditAutoIncrement[$key])) {
1738 $currentValue = 'NULL';
1740 } elseif ($type === 'set') {
1741 $currentValue = "''";
1742 if (! empty($_POST['fields']['multi_edit'][$rownumber][$key])) {
1743 $currentValue = implode(',', $_POST['fields']['multi_edit'][$rownumber][$key]);
1745 . $this->dbi
->escapeString($currentValue) . "'";
1747 } elseif ($type === 'protected') {
1748 // Fetch the current values of a row to use in case we have a protected field
1752 && is_array($multiEditColumnsType) && $whereClause
1754 $protectedRow = $this->dbi
->fetchSingleRow(
1755 'SELECT * FROM ' . Util
::backquote($table)
1756 . ' WHERE ' . $whereClause . ';'
1760 // here we are in protected mode (asked in the config)
1761 // so tbl_change has put this special value in the
1762 // columns array, so we do not change the column value
1763 // but we can still handle column upload
1765 // when in UPDATE mode, do not alter field's contents. When in INSERT
1766 // mode, insert empty field because no values were submitted.
1767 // If protected blobs where set, insert original fields content.
1769 if (! empty($protectedRow[$multiEditColumnsName[$key]])) {
1770 $currentValue = '0x'
1771 . bin2hex($protectedRow[$multiEditColumnsName[$key]]);
1773 } elseif ($type === 'hex') {
1774 if (substr($currentValue, 0, 2) != '0x') {
1775 $currentValue = '0x' . $currentValue;
1777 } elseif ($type === 'bit') {
1778 $currentValue = (string) preg_replace('/[^01]/', '0', $currentValue);
1779 $currentValue = "b'" . $this->dbi
->escapeString($currentValue) . "'";
1781 ! ($type === 'datetime' ||
$type === 'timestamp' ||
$type === 'date')
1782 ||
($currentValue !== 'CURRENT_TIMESTAMP'
1783 && $currentValue !== 'current_timestamp()')
1785 $currentValue = "'" . $this->dbi
->escapeString($currentValue)
1789 // Was the Null checkbox checked for this field?
1790 // (if there is a value, we ignore the Null checkbox: this could
1791 // be possible if Javascript is disabled in the browser)
1792 if (! empty($multiEditColumnsNull[$key]) && ($currentValue == "''" ||
$currentValue == '')) {
1793 $currentValue = 'NULL';
1796 // The Null checkbox was unchecked for this field
1798 empty($currentValue)
1799 && ! empty($multiEditColumnsNullPrev[$key])
1800 && ! isset($multiEditColumnsNull[$key])
1802 $currentValue = "''";
1805 return $currentValue;
1809 * Check whether inline edited value can be truncated or not,
1810 * and add additional parameters for extra_data array if needed
1812 * @param string $db Database name
1813 * @param string $table Table name
1814 * @param string $columnName Column name
1815 * @param array $extraData Extra data for ajax response
1817 public function verifyWhetherValueCanBeTruncatedAndAppendExtraData(
1823 $extraData['isNeedToRecheck'] = false;
1825 $sqlForRealValue = 'SELECT ' . Util
::backquote($table) . '.'
1826 . Util
::backquote($columnName)
1827 . ' FROM ' . Util
::backquote($db) . '.'
1828 . Util
::backquote($table)
1829 . ' WHERE ' . $_POST['where_clause'][0];
1831 $result = $this->dbi
->tryQuery($sqlForRealValue);
1837 $fieldsMeta = $this->dbi
->getFieldsMeta($result);
1838 $meta = $fieldsMeta[0];
1839 $newValue = $result->fetchValue();
1841 if ($newValue === false) {
1845 if ($meta->isTimeType()) {
1846 $newValue = Util
::addMicroseconds($newValue);
1847 } elseif ($meta->isBinary()) {
1848 $newValue = '0x' . bin2hex($newValue);
1851 $extraData['isNeedToRecheck'] = true;
1852 $extraData['truncatableFieldValue'] = $newValue;
1856 * Function to get the columns of a table
1858 * @param string $db current db
1859 * @param string $table current table
1863 public function getTableColumns($db, $table)
1865 $this->dbi
->selectDb($db);
1867 return array_values($this->dbi
->getColumns($db, $table, true));
1871 * Function to determine Insert/Edit rows
1873 * @param string|null $whereClause where clause
1874 * @param string $db current database
1875 * @param string $table current table
1879 public function determineInsertOrEdit($whereClause, $db, $table): array
1881 if (isset($_POST['where_clause'])) {
1882 $whereClause = $_POST['where_clause'];
1885 if (isset($_SESSION['edit_next'])) {
1886 $whereClause = $_SESSION['edit_next'];
1887 unset($_SESSION['edit_next']);
1888 $afterInsert = 'edit_next';
1891 if (isset($_POST['ShowFunctionFields'])) {
1892 $GLOBALS['cfg']['ShowFunctionFields'] = $_POST['ShowFunctionFields'];
1895 if (isset($_POST['ShowFieldTypesInDataEditView'])) {
1896 $GLOBALS['cfg']['ShowFieldTypesInDataEditView'] = $_POST['ShowFieldTypesInDataEditView'];
1899 if (isset($_POST['after_insert'])) {
1900 $afterInsert = $_POST['after_insert'];
1903 if (isset($whereClause)) {
1905 $insertMode = false;
1906 $whereClauseArray = $this->getWhereClauseArray($whereClause);
1907 [$whereClauses, $result, $rows, $foundUniqueKey] = $this->analyzeWhereClauses(
1915 $whereClause = null;
1916 [$result, $rows] = $this->loadFirstRow($table, $db);
1917 $whereClauses = null;
1918 $whereClauseArray = [];
1919 $foundUniqueKey = false;
1922 // Copying a row - fetched data will be inserted as a new row,
1923 // therefore the where clause is needless.
1924 if (isset($_POST['default_action']) && $_POST['default_action'] === 'insert') {
1925 $whereClause = $whereClauses = null;
1936 $afterInsert ??
null,
1941 * Function to get comments for the table columns
1943 * @param string $db current database
1944 * @param string $table current table
1946 * @return array comments for columns
1948 public function getCommentsMap($db, $table): array
1950 if ($GLOBALS['cfg']['ShowPropertyComments']) {
1951 return $this->relation
->getComments($db, $table);
1958 * Function to get html for the gis editor div
1960 public function getHtmlForGisEditor(): string
1962 return '<div id="gis_editor"></div><div id="popup_background"></div><br>';
1966 * Function to get html for the ignore option in insert mode
1968 * @param int $rowId row id
1969 * @param bool $checked ignore option is checked or not
1971 public function getHtmlForIgnoreOption($rowId, $checked = true): string
1973 return '<input type="checkbox"'
1974 . ($checked ?
' checked="checked"' : '')
1975 . ' name="insert_ignore_' . $rowId . '"'
1976 . ' id="insert_ignore_' . $rowId . '">'
1977 . '<label for="insert_ignore_' . $rowId . '">'
1979 . '</label><br>' . "\n";
1983 * Function to get html for the insert edit form header
1985 * @param bool $hasBlobField whether has blob field
1986 * @param bool $isUpload whether is upload
1988 public function getHtmlForInsertEditFormHeader($hasBlobField, $isUpload): string
1990 $template = new Template();
1992 return $template->render('table/insert/get_html_for_insert_edit_form_header', [
1993 'has_blob_field' => $hasBlobField,
1994 'is_upload' => $isUpload,
1999 * Function to get html for each insert/edit column
2001 * @param array $column column
2002 * @param int $columnNumber column index in table_columns
2003 * @param array $commentsMap comments map
2004 * @param bool $timestampSeen whether timestamp seen
2005 * @param ResultInterface $currentResult current result
2006 * @param string $chgEvtHandler javascript change event handler
2007 * @param string $jsvkey javascript validation key
2008 * @param string $vkey validation key
2009 * @param bool $insertMode whether insert mode
2010 * @param array $currentRow current row
2011 * @param int $oRows row offset
2012 * @param int $tabindex tab index
2013 * @param int $columnsCnt columns count
2014 * @param bool $isUpload whether upload
2015 * @param array $foreigners foreigners
2016 * @param int $tabindexForValue tab index offset for value
2017 * @param string $table table
2018 * @param string $db database
2019 * @param int $rowId row id
2020 * @param int $biggestMaxFileSize biggest max file size
2021 * @param string $defaultCharEditing default char editing mode which is stored in the config.inc.php script
2022 * @param string $textDir text direction
2023 * @param array $repopulate the data to be repopulated
2024 * @param array $columnMime the mime information of column
2025 * @param string $whereClause the where clause
2029 private function getHtmlForInsertEditFormColumn(
2034 ResultInterface
$currentResult,
2049 $biggestMaxFileSize,
2050 $defaultCharEditing,
2058 if (! isset($column['processed'])) {
2059 $column = $this->analyzeTableColumnsArray($column, $commentsMap, $timestampSeen);
2063 /** @var string $fieldHashMd5 */
2064 $fieldHashMd5 = $column['Field_md5'];
2065 if ($repopulate && array_key_exists($fieldHashMd5, $currentRow)) {
2066 $currentRow[$column['Field']] = $repopulate[$fieldHashMd5];
2070 $extractedColumnspec = Util
::extractColumnSpec($column['Type']);
2072 if ($column['len'] === -1) {
2073 $column['len'] = $this->dbi
->getFieldsMeta($currentResult)[$columnNumber]->length
;
2074 // length is unknown for geometry fields,
2075 // make enough space to edit very simple WKTs
2076 if ($column['len'] === -1) {
2077 $column['len'] = 30;
2081 //Call validation when the form submitted...
2082 $onChangeClause = $chgEvtHandler
2083 . "=\"return verificationsAfterFieldChange('"
2084 . Sanitize
::escapeJsString($fieldHashMd5) . "', '"
2085 . Sanitize
::escapeJsString($jsvkey) . "','" . $column['pma_type'] . "')\"";
2087 // Use an MD5 as an array index to avoid having special characters
2088 // in the name attribute (see bug #1746964 )
2089 $columnNameAppendix = $vkey . '[' . $fieldHashMd5 . ']';
2091 if ($column['Type'] === 'datetime' && $column['Null'] !== 'YES' && ! isset($column['Default']) && $insertMode) {
2092 $column['Default'] = date('Y-m-d H:i:s', time());
2095 // Get a list of GIS data types.
2096 $gisDataTypes = Gis
::getDataTypes();
2098 // Prepares the field value
2103 $specialCharsEncoded,
2107 ] = $this->getSpecialCharsAndBackupFieldForExistingRow(
2110 $extractedColumnspec,
2112 $columnNameAppendix,
2116 // (we are inserting)
2117 // display default values
2119 if (isset($repopulate[$fieldHashMd5])) {
2120 $tmp['Default'] = $repopulate[$fieldHashMd5];
2128 $specialCharsEncoded,
2129 ] = $this->getSpecialCharsAndBackupFieldForInsertingMode($tmp);
2133 $idindex = ($oRows * $columnsCnt) +
$columnNumber +
1;
2134 $tabindex = $idindex;
2136 // The function column
2137 // -------------------
2138 $foreignData = $this->relation
->getForeignData($foreigners, $column['Field'], false, '', '');
2139 $isColumnBinary = $this->isColumnBinary($column, $isUpload);
2140 $functionOptions = '';
2142 if ($GLOBALS['cfg']['ShowFunctionFields']) {
2143 $functionOptions = Generator
::getFunctionsForField($column, $insertMode, $foreignData);
2146 // nullify code is needed by the js nullify() function to be able to generate calls to nullify() in jQuery
2147 $nullifyCode = $this->getNullifyCodeForNullColumn($column, $foreigners, $foreignData);
2149 // The value column (depends on type)
2151 // See bug #1667887 for the reason why we don't use the maxlength
2154 //add data attributes "no of decimals" and "data type"
2156 $type = current(explode('(', $column['pma_type']));
2157 if (preg_match('/\(([^()]+)\)/', $column['pma_type'], $match)) {
2158 $match[0] = trim($match[0], '()');
2159 $noDecimals = $match[0];
2162 // Check input transformation of column
2163 $transformedHtml = '';
2164 if (! empty($columnMime['input_transformation'])) {
2165 $file = $columnMime['input_transformation'];
2166 $includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
2167 if (is_file(ROOT_PATH
. $includeFile)) {
2168 $className = $this->transformations
->getClassName($includeFile);
2169 if (class_exists($className)) {
2170 $transformationPlugin = new $className();
2171 $transformationOptions = $this->transformations
->getOptions(
2172 $columnMime['input_transformation_options']
2177 'transform_key' => $column['Field'],
2178 'where_clause_sign' => Core
::signSqlQuery($whereClause),
2179 'where_clause' => $whereClause,
2181 $transformationOptions['wrapper_link'] = Url
::getCommon($urlParams);
2182 $transformationOptions['wrapper_params'] = $urlParams;
2184 if (isset($currentRow[$column['Field']])) {
2185 $currentValue = $currentRow[$column['Field']];
2188 if (method_exists($transformationPlugin, 'getInputHtml')) {
2189 $transformedHtml = $transformationPlugin->getInputHtml(
2192 $columnNameAppendix,
2193 $transformationOptions,
2202 if (method_exists($transformationPlugin, 'getScripts')) {
2203 $GLOBALS['plugin_scripts'] = array_merge(
2204 $GLOBALS['plugin_scripts'],
2205 $transformationPlugin->getScripts()
2213 $foreignDropdown = '';
2215 $textAreaRows = $GLOBALS['cfg']['TextareaRows'];
2216 $textareaCols = $GLOBALS['cfg']['TextareaCols'];
2218 $enumSelectedValue = '';
2219 $columnSetValues = [];
2221 $isColumnProtectedBlob = false;
2223 $blobValueUnit = '';
2225 $selectOptionForUpload = '';
2226 $inputFieldHtml = '';
2227 if (empty($transformedHtml)) {
2228 if (is_array($foreignData['disp_row'])) {
2229 $foreignDropdown = $this->relation
->foreignDropdown(
2230 $foreignData['disp_row'],
2231 $foreignData['foreign_field'],
2232 $foreignData['foreign_display'],
2234 $GLOBALS['cfg']['ForeignKeyMaxLimit']
2238 $dataType = $this->dbi
->types
->getTypeClass($column['True_Type']);
2240 if ($column['is_char']) {
2241 $textAreaRows = max($GLOBALS['cfg']['CharTextareaRows'], 7);
2242 $textareaCols = $GLOBALS['cfg']['CharTextareaCols'];
2243 $maxlength = $extractedColumnspec['spec_in_brackets'];
2244 } elseif ($GLOBALS['cfg']['LongtextDoubleTextarea'] && mb_strstr($column['pma_type'], 'longtext')) {
2245 $textAreaRows = $GLOBALS['cfg']['TextareaRows'] * 2;
2246 $textareaCols = $GLOBALS['cfg']['TextareaCols'] * 2;
2249 if ($column['pma_type'] === 'enum') {
2250 if (! isset($column['values'])) {
2251 $column['values'] = $this->getColumnEnumValues($extractedColumnspec['enum_set_values']);
2254 foreach ($column['values'] as $enumValue) {
2256 $data == $enumValue['plain'] ||
($data == ''
2257 && (! isset($_POST['where_clause']) ||
$column['Null'] !== 'YES')
2258 && isset($column['Default']) && $enumValue['plain'] == $column['Default'])
2260 $enumSelectedValue = $enumValue['plain'];
2264 } elseif ($column['pma_type'] === 'set') {
2265 [$columnSetValues, $setSelectSize] = $this->getColumnSetValueAndSelectSize(
2267 $extractedColumnspec['enum_set_values']
2269 } elseif ($column['is_binary'] ||
$column['is_blob']) {
2270 $isColumnProtectedBlob = ($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'])
2271 ||
($GLOBALS['cfg']['ProtectBinary'] === 'all')
2272 ||
($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && ! $column['is_blob']);
2273 if ($isColumnProtectedBlob && isset($data)) {
2274 $blobSize = Util
::formatByteDown(mb_strlen(stripslashes($data)), 3, 1);
2275 if ($blobSize !== null) {
2276 [$blobValue, $blobValueUnit] = $blobSize;
2280 if ($isUpload && $column['is_blob']) {
2281 [$maxUploadSize] = $this->getMaxUploadSize($column['pma_type'], $biggestMaxFileSize);
2284 if (! empty($GLOBALS['cfg']['UploadDir'])) {
2285 $selectOptionForUpload = $this->getSelectOptionForUpload($vkey, $fieldHashMd5);
2289 ! $isColumnProtectedBlob
2290 && ! ($column['is_blob'] ||
($column['len'] > $GLOBALS['cfg']['LimitChars']))
2292 $inputFieldHtml = $this->getHtmlInput(
2294 $columnNameAppendix,
2296 min(max($column['len'], 4), $GLOBALS['cfg']['LimitChars']),
2306 $columnValue = $this->getValueColumnForOtherDatatypes(
2308 $defaultCharEditing,
2310 $columnNameAppendix,
2317 $specialCharsEncoded,
2319 $extractedColumnspec,
2325 return $this->template
->render('table/insert/column_row', [
2328 'column' => $column,
2330 'show_field_types_in_data_edit_view' => $GLOBALS['cfg']['ShowFieldTypesInDataEditView'],
2331 'show_function_fields' => $GLOBALS['cfg']['ShowFunctionFields'],
2332 'is_column_binary' => $isColumnBinary,
2333 'function_options' => $functionOptions,
2334 'read_only' => $readOnly,
2335 'nullify_code' => $nullifyCode,
2336 'real_null_value' => $realNullValue,
2337 'id_index' => $idindex,
2339 'decimals' => $noDecimals,
2340 'special_chars' => $specialChars,
2341 'transformed_value' => $transformedHtml,
2342 'value' => $columnValue,
2343 'is_value_foreign_link' => $foreignData['foreign_link'] === true,
2344 'backup_field' => $backupField,
2346 'gis_data_types' => $gisDataTypes,
2347 'foreign_dropdown' => $foreignDropdown,
2348 'data_type' => $dataType,
2349 'textarea_cols' => $textareaCols,
2350 'textarea_rows' => $textAreaRows,
2351 'text_dir' => $textDir,
2352 'max_length' => $maxlength,
2353 'longtext_double_textarea' => $GLOBALS['cfg']['LongtextDoubleTextarea'],
2354 'enum_selected_value' => $enumSelectedValue,
2355 'set_values' => $columnSetValues,
2356 'set_select_size' => $setSelectSize,
2357 'is_column_protected_blob' => $isColumnProtectedBlob,
2358 'blob_value' => $blobValue,
2359 'blob_value_unit' => $blobValueUnit,
2360 'is_upload' => $isUpload,
2361 'max_upload_size' => $maxUploadSize,
2362 'select_option_for_upload' => $selectOptionForUpload,
2363 'limit_chars' => $GLOBALS['cfg']['LimitChars'],
2364 'input_field_html' => $inputFieldHtml,
2368 private function isColumnBinary(array $column, bool $isUpload): bool
2370 if (! $GLOBALS['cfg']['ShowFunctionFields']) {
2374 return ($GLOBALS['cfg']['ProtectBinary'] === 'blob' && $column['is_blob'] && ! $isUpload)
2375 ||
($GLOBALS['cfg']['ProtectBinary'] === 'all' && $column['is_binary'])
2376 ||
($GLOBALS['cfg']['ProtectBinary'] === 'noblob' && $column['is_binary']);
2380 * Function to get html for each insert/edit row
2382 * @param array $urlParams url parameters
2383 * @param array[] $tableColumns table columns
2384 * @param array $commentsMap comments map
2385 * @param bool $timestampSeen whether timestamp seen
2386 * @param ResultInterface $currentResult current result
2387 * @param string $chgEvtHandler javascript change event handler
2388 * @param string $jsvkey javascript validation key
2389 * @param string $vkey validation key
2390 * @param bool $insertMode whether insert mode
2391 * @param array $currentRow current row
2392 * @param int $oRows row offset
2393 * @param int $tabindex tab index
2394 * @param int $columnsCnt columns count
2395 * @param bool $isUpload whether upload
2396 * @param array $foreigners foreigners
2397 * @param int $tabindexForValue tab index offset for value
2398 * @param string $table table
2399 * @param string $db database
2400 * @param int $rowId row id
2401 * @param int $biggestMaxFileSize biggest max file size
2402 * @param string $textDir text direction
2403 * @param array $repopulate the data to be repopulated
2404 * @param array $whereClauseArray the array of where clauses
2408 public function getHtmlForInsertEditRow(
2410 array $tableColumns,
2413 ResultInterface
$currentResult,
2428 $biggestMaxFileSize,
2431 array $whereClauseArray
2433 $htmlOutput = $this->getHeadAndFootOfInsertRowTable($urlParams)
2436 //store the default value for CharEditing
2437 $defaultCharEditing = $GLOBALS['cfg']['CharEditing'];
2438 $mimeMap = $this->transformations
->getMime($db, $table);
2440 if (isset($whereClauseArray[$rowId])) {
2441 $whereClause = $whereClauseArray[$rowId];
2444 for ($columnNumber = 0; $columnNumber < $columnsCnt; $columnNumber++
) {
2445 $tableColumn = $tableColumns[$columnNumber];
2447 if (isset($mimeMap[$tableColumn['Field']])) {
2448 $columnMime = $mimeMap[$tableColumn['Field']];
2454 'VIRTUAL GENERATED',
2457 if (in_array($tableColumn['Extra'], $virtual)) {
2461 $htmlOutput .= $this->getHtmlForInsertEditFormColumn(
2481 $biggestMaxFileSize,
2482 $defaultCharEditing,
2492 return $htmlOutput . ' </tbody>'
2493 . '</table></div><br>'
2494 . '<div class="clearfloat"></div>';