Translated using Weblate (Lithuanian)
[phpmyadmin.git] / tbl_replace.php
blob8e6ac7620231cd94573752d6cc61cac07e77497d
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Manipulation of table data like inserting, replacing and updating
6 * Usually called as form action from tbl_change.php to insert or update table rows
8 * @todo 'edit_next' tends to not work as expected if used ...
9 * at least there is no order by it needs the original query
10 * and the row number and than replace the LIMIT clause
12 * @package PhpMyAdmin
14 declare(strict_types=1);
16 use PhpMyAdmin\Core;
17 use PhpMyAdmin\DatabaseInterface;
18 use PhpMyAdmin\File;
19 use PhpMyAdmin\InsertEdit;
20 use PhpMyAdmin\Message;
21 use PhpMyAdmin\Plugins\IOTransformationsPlugin;
22 use PhpMyAdmin\Relation;
23 use PhpMyAdmin\Response;
24 use PhpMyAdmin\Table;
25 use PhpMyAdmin\Transformations;
26 use PhpMyAdmin\Util;
28 if (! defined('ROOT_PATH')) {
29 define('ROOT_PATH', __DIR__ . DIRECTORY_SEPARATOR);
32 global $containerBuilder, $db, $table, $url_params;
34 require_once ROOT_PATH . 'libraries/common.inc.php';
36 /** @var Response $response */
37 $response = $containerBuilder->get(Response::class);
39 /** @var DatabaseInterface $dbi */
40 $dbi = $containerBuilder->get(DatabaseInterface::class);
42 // Check parameters
43 Util::checkParameters(['db', 'table', 'goto']);
45 $dbi->selectDb($db);
47 /**
48 * Initializes some variables
50 $goto_include = false;
52 $header = $response->getHeader();
53 $scripts = $header->getScripts();
54 $scripts->addFile('makegrid.js');
55 // Needed for generation of Inline Edit anchors
56 $scripts->addFile('sql.js');
57 $scripts->addFile('indexes.js');
58 $scripts->addFile('gis_data_editor.js');
60 /** @var Relation $relation */
61 $relation = $containerBuilder->get('relation');
62 /** @var Transformations $transformations */
63 $transformations = $containerBuilder->get('transformations');
64 /** @var InsertEdit $insertEdit */
65 $insertEdit = $containerBuilder->get('insert_edit');
67 // check whether insert row mode, if so include tbl_change.php
68 $insertEdit->isInsertRow();
70 $after_insert_actions = [
71 'new_insert',
72 'same_insert',
73 'edit_next',
75 if (isset($_POST['after_insert'])
76 && in_array($_POST['after_insert'], $after_insert_actions)
77 ) {
78 $url_params['after_insert'] = $_POST['after_insert'];
79 if (isset($_POST['where_clause'])) {
80 foreach ($_POST['where_clause'] as $one_where_clause) {
81 if ($_POST['after_insert'] == 'same_insert') {
82 $url_params['where_clause'][] = $one_where_clause;
83 } elseif ($_POST['after_insert'] == 'edit_next') {
84 $insertEdit->setSessionForEditNext($one_where_clause);
89 //get $goto_include for different cases
90 $goto_include = $insertEdit->getGotoInclude($goto_include);
92 // Defines the url to return in case of failure of the query
93 $err_url = $insertEdit->getErrorUrl($url_params);
95 /**
96 * Prepares the update/insert of a row
98 list($loop_array, $using_key, $is_insert, $is_insertignore)
99 = $insertEdit->getParamsForUpdateOrInsert();
101 $query = [];
102 $value_sets = [];
103 $func_no_param = [
104 'CONNECTION_ID',
105 'CURRENT_USER',
106 'CURDATE',
107 'CURTIME',
108 'CURRENT_DATE',
109 'CURRENT_TIME',
110 'DATABASE',
111 'LAST_INSERT_ID',
112 'NOW',
113 'PI',
114 'RAND',
115 'SYSDATE',
116 'UNIX_TIMESTAMP',
117 'USER',
118 'UTC_DATE',
119 'UTC_TIME',
120 'UTC_TIMESTAMP',
121 'UUID',
122 'UUID_SHORT',
123 'VERSION',
125 $func_optional_param = [
126 'RAND',
127 'UNIX_TIMESTAMP',
130 $gis_from_text_functions = [
131 'GeomFromText',
132 'GeomCollFromText',
133 'LineFromText',
134 'MLineFromText',
135 'PointFromText',
136 'MPointFromText',
137 'PolyFromText',
138 'MPolyFromText',
141 $gis_from_wkb_functions = [];
142 if ($dbi->getVersion() >= 50600) {
143 $gis_from_wkb_functions = [
144 'ST_GeomFromText',
145 'ST_GeomCollFromText',
146 'ST_LineFromText',
147 'ST_MLineFromText',
148 'ST_PointFromText',
149 'ST_MPointFromText',
150 'ST_PolyFromText',
151 'ST_MPolyFromText',
155 //if some posted fields need to be transformed.
156 $mime_map = $transformations->getMime($db, $table);
157 if ($mime_map === false) {
158 $mime_map = [];
161 $query_fields = [];
162 $insert_errors = [];
163 $row_skipped = false;
164 $unsaved_values = [];
165 foreach ($loop_array as $rownumber => $where_clause) {
166 // skip fields to be ignored
167 if (! $using_key && isset($_POST['insert_ignore_' . $where_clause])) {
168 continue;
171 // Defines the SET part of the sql query
172 $query_values = [];
174 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
175 $multi_edit_columns
176 = isset($_POST['fields']['multi_edit'][$rownumber])
177 ? $_POST['fields']['multi_edit'][$rownumber]
178 : [];
179 $multi_edit_columns_name
180 = isset($_POST['fields_name']['multi_edit'][$rownumber])
181 ? $_POST['fields_name']['multi_edit'][$rownumber]
182 : [];
183 $multi_edit_columns_prev
184 = isset($_POST['fields_prev']['multi_edit'][$rownumber])
185 ? $_POST['fields_prev']['multi_edit'][$rownumber]
186 : null;
187 $multi_edit_funcs
188 = isset($_POST['funcs']['multi_edit'][$rownumber])
189 ? $_POST['funcs']['multi_edit'][$rownumber]
190 : null;
191 $multi_edit_salt
192 = isset($_POST['salt']['multi_edit'][$rownumber])
193 ? $_POST['salt']['multi_edit'][$rownumber]
194 : null;
195 $multi_edit_columns_type
196 = isset($_POST['fields_type']['multi_edit'][$rownumber])
197 ? $_POST['fields_type']['multi_edit'][$rownumber]
198 : null;
199 $multi_edit_columns_null
200 = isset($_POST['fields_null']['multi_edit'][$rownumber])
201 ? $_POST['fields_null']['multi_edit'][$rownumber]
202 : null;
203 $multi_edit_columns_null_prev
204 = isset($_POST['fields_null_prev']['multi_edit'][$rownumber])
205 ? $_POST['fields_null_prev']['multi_edit'][$rownumber]
206 : null;
207 $multi_edit_auto_increment
208 = isset($_POST['auto_increment']['multi_edit'][$rownumber])
209 ? $_POST['auto_increment']['multi_edit'][$rownumber]
210 : null;
211 $multi_edit_virtual
212 = isset($_POST['virtual']['multi_edit'][$rownumber])
213 ? $_POST['virtual']['multi_edit'][$rownumber]
214 : null;
216 // When a select field is nullified, it's not present in $_POST
217 // so initialize it; this way, the foreach($multi_edit_columns) will process it
218 foreach ($multi_edit_columns_name as $key => $val) {
219 if (! isset($multi_edit_columns[$key])) {
220 $multi_edit_columns[$key] = '';
224 // Iterate in the order of $multi_edit_columns_name,
225 // not $multi_edit_columns, to avoid problems
226 // when inserting multiple entries
227 $insert_fail = false;
228 foreach ($multi_edit_columns_name as $key => $column_name) {
229 $current_value = $multi_edit_columns[$key];
230 // Note: $key is an md5 of the fieldname. The actual fieldname is
231 // available in $multi_edit_columns_name[$key]
233 $file_to_insert = new File();
234 $file_to_insert->checkTblChangeForm((string) $key, (string) $rownumber);
236 $possibly_uploaded_val = $file_to_insert->getContent();
237 if ($possibly_uploaded_val !== false) {
238 $current_value = $possibly_uploaded_val;
240 // Apply Input Transformation if defined
241 if (! empty($mime_map[$column_name])
242 && ! empty($mime_map[$column_name]['input_transformation'])
244 $filename = 'libraries/classes/Plugins/Transformations/'
245 . $mime_map[$column_name]['input_transformation'];
246 if (is_file($filename)) {
247 $classname = $transformations->getClassName($filename);
248 if (class_exists($classname)) {
249 /** @var IOTransformationsPlugin $transformation_plugin */
250 $transformation_plugin = new $classname();
251 $transformation_options = $transformations->getOptions(
252 $mime_map[$column_name]['input_transformation_options']
254 $current_value = $transformation_plugin->applyTransformation(
255 $current_value,
256 $transformation_options
258 // check if transformation was successful or not
259 // and accordingly set error messages & insert_fail
260 if (method_exists($transformation_plugin, 'isSuccess')
261 && ! $transformation_plugin->isSuccess()
263 $insert_fail = true;
264 $row_skipped = true;
265 $insert_errors[] = sprintf(
266 __('Row: %1$s, Column: %2$s, Error: %3$s'),
267 $rownumber,
268 $column_name,
269 $transformation_plugin->getError()
276 if ($file_to_insert->isError()) {
277 $insert_errors[] = $file_to_insert->getError();
279 // delete $file_to_insert temporary variable
280 $file_to_insert->cleanUp();
282 $current_value = $insertEdit->getCurrentValueForDifferentTypes(
283 $possibly_uploaded_val,
284 $key,
285 $multi_edit_columns_type,
286 $current_value,
287 $multi_edit_auto_increment,
288 $rownumber,
289 $multi_edit_columns_name,
290 $multi_edit_columns_null,
291 $multi_edit_columns_null_prev,
292 $is_insert,
293 $using_key,
294 $where_clause,
295 $table,
296 $multi_edit_funcs
299 $current_value_as_an_array = $insertEdit->getCurrentValueAsAnArrayForMultipleEdit(
300 $multi_edit_funcs,
301 $multi_edit_salt,
302 $gis_from_text_functions,
303 $current_value,
304 $gis_from_wkb_functions,
305 $func_optional_param,
306 $func_no_param,
307 $key
310 if (! isset($multi_edit_virtual) || ! isset($multi_edit_virtual[$key])) {
311 list($query_values, $query_fields)
312 = $insertEdit->getQueryValuesForInsertAndUpdateInMultipleEdit(
313 $multi_edit_columns_name,
314 $multi_edit_columns_null,
315 $current_value,
316 $multi_edit_columns_prev,
317 $multi_edit_funcs,
318 $is_insert,
319 $query_values,
320 $query_fields,
321 $current_value_as_an_array,
322 $value_sets,
323 $key,
324 $multi_edit_columns_null_prev
327 if (isset($multi_edit_columns_null[$key])) {
328 $multi_edit_columns[$key] = null;
330 } //end of foreach
332 // temporarily store rows not inserted
333 // so that they can be populated again.
334 if ($insert_fail) {
335 $unsaved_values[$rownumber] = $multi_edit_columns;
337 if (! $insert_fail && count($query_values) > 0) {
338 if ($is_insert) {
339 $value_sets[] = implode(', ', $query_values);
340 } else {
341 // build update query
342 $query[] = 'UPDATE ' . Util::backquote($table)
343 . ' SET ' . implode(', ', $query_values)
344 . ' WHERE ' . $where_clause
345 . ($_POST['clause_is_unique'] ? '' : ' LIMIT 1');
348 } // end foreach ($loop_array as $where_clause)
349 unset(
350 $multi_edit_columns_name,
351 $multi_edit_columns_prev,
352 $multi_edit_funcs,
353 $multi_edit_columns_type,
354 $multi_edit_columns_null,
355 $func_no_param,
356 $multi_edit_auto_increment,
357 $current_value_as_an_array,
358 $key,
359 $current_value,
360 $loop_array,
361 $where_clause,
362 $using_key,
363 $multi_edit_columns_null_prev,
364 $insert_fail
367 // Builds the sql query
368 if ($is_insert && count($value_sets) > 0) {
369 $query = $insertEdit->buildSqlQuery($is_insertignore, $query_fields, $value_sets);
370 } elseif (empty($query) && ! isset($_POST['preview_sql']) && ! $row_skipped) {
371 // No change -> move back to the calling script
373 // Note: logic passes here for inline edit
374 $message = Message::success(__('No change'));
375 // Avoid infinite recursion
376 if ($goto_include == 'tbl_replace.php') {
377 $goto_include = 'tbl_change.php';
379 $active_page = $goto_include;
380 include ROOT_PATH . Core::securePath($goto_include);
381 exit;
383 unset($multi_edit_columns, $is_insertignore);
385 // If there is a request for SQL previewing.
386 if (isset($_POST['preview_sql'])) {
387 Core::previewSQL($query);
391 * Executes the sql query and get the result, then move back to the calling
392 * page
394 list ($url_params, $total_affected_rows, $last_messages, $warning_messages,
395 $error_messages, $return_to_sql_query)
396 = $insertEdit->executeSqlQuery($url_params, $query);
398 if ($is_insert && (count($value_sets) > 0 || $row_skipped)) {
399 $message = Message::getMessageForInsertedRows(
400 $total_affected_rows
402 $unsaved_values = array_values($unsaved_values);
403 } else {
404 $message = Message::getMessageForAffectedRows(
405 $total_affected_rows
408 if ($row_skipped) {
409 $goto_include = 'tbl_change.php';
410 $message->addMessagesString($insert_errors, '<br>');
411 $message->isError(true);
414 $message->addMessages($last_messages, '<br>');
416 if (! empty($warning_messages)) {
417 $message->addMessagesString($warning_messages, '<br>');
418 $message->isError(true);
420 if (! empty($error_messages)) {
421 $message->addMessagesString($error_messages);
422 $message->isError(true);
424 unset(
425 $error_messages,
426 $warning_messages,
427 $total_affected_rows,
428 $last_messages,
429 $last_message,
430 $row_skipped,
431 $insert_errors
435 * The following section only applies to grid editing.
436 * However, verifying isAjax() is not enough to ensure we are coming from
437 * grid editing. If we are coming from the Edit or Copy link in Browse mode,
438 * ajax_page_request is present in the POST parameters.
440 if ($response->isAjax() && ! isset($_POST['ajax_page_request'])) {
442 * If we are in grid editing, we need to process the relational and
443 * transformed fields, if they were edited. After that, output the correct
444 * link/transformed value and exit
446 if (isset($_POST['rel_fields_list']) && $_POST['rel_fields_list'] != '') {
447 $map = $relation->getForeigners($db, $table, '', 'both');
449 $relation_fields = [];
450 parse_str($_POST['rel_fields_list'], $relation_fields);
452 // loop for each relation cell
453 /** @var array $relation_fields */
454 foreach ($relation_fields as $cell_index => $curr_rel_field) {
455 foreach ($curr_rel_field as $relation_field => $relation_field_value) {
456 $where_comparison = "='" . $relation_field_value . "'";
457 $dispval = $insertEdit->getDisplayValueForForeignTableColumn(
458 $where_comparison,
459 $map,
460 $relation_field
463 $extra_data['relations'][$cell_index]
464 = $insertEdit->getLinkForRelationalDisplayField(
465 $map,
466 $relation_field,
467 $where_comparison,
468 $dispval,
469 $relation_field_value
472 } // end of loop for each relation cell
474 if (isset($_POST['do_transformations'])
475 && $_POST['do_transformations'] == true
477 $edited_values = [];
478 parse_str($_POST['transform_fields_list'], $edited_values);
480 if (! isset($extra_data)) {
481 $extra_data = [];
483 $transformation_types = [
484 "input_transformation",
485 "transformation",
487 foreach ($mime_map as $transformation) {
488 $column_name = $transformation['column_name'];
489 foreach ($transformation_types as $type) {
490 $file = Core::securePath($transformation[$type]);
491 $extra_data = $insertEdit->transformEditedValues(
492 $db,
493 $table,
494 $transformation,
495 $edited_values,
496 $file,
497 $column_name,
498 $extra_data,
499 $type
502 } // end of loop for each $mime_map
505 // Need to check the inline edited value can be truncated by MySQL
506 // without informing while saving
507 $column_name = $_POST['fields_name']['multi_edit'][0][0];
509 $insertEdit->verifyWhetherValueCanBeTruncatedAndAppendExtraData(
510 $db,
511 $table,
512 $column_name,
513 $extra_data
516 /**Get the total row count of the table*/
517 $_table = new Table($_POST['table'], $_POST['db']);
518 $extra_data['row_count'] = $_table->countRecords();
520 $extra_data['sql_query'] = Util::getMessage(
521 $message,
522 $GLOBALS['display_query']
525 $response->setRequestStatus($message->isSuccess());
526 $response->addJSON('message', $message);
527 $response->addJSON($extra_data);
528 exit;
531 if (! empty($return_to_sql_query)) {
532 $disp_query = $GLOBALS['sql_query'];
533 $disp_message = $message;
534 unset($message);
535 $GLOBALS['sql_query'] = $return_to_sql_query;
538 $scripts->addFile('vendor/jquery/additional-methods.js');
539 $scripts->addFile('table/change.js');
541 $active_page = $goto_include;
544 * If user asked for "and then Insert another new row" we have to remove
545 * WHERE clause information so that tbl_change.php does not go back
546 * to the current record
548 if (isset($_POST['after_insert']) && 'new_insert' == $_POST['after_insert']) {
549 unset($_POST['where_clause']);
553 * Load target page.
555 require ROOT_PATH . Core::securePath($goto_include);
556 exit;