Translated using Weblate.
[phpmyadmin.git] / tbl_replace.php
blob28e7fbe38bc2a27d968215b08b055a30afa61231
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * manipulation of table data like inserting, replacing and updating
6 * usally called as form action from tbl_change.php to insert or update table rows
9 * @todo 'edit_next' tends to not work as expected if used ... at least there is no order by
10 * it needs the original query and the row number and than replace the LIMIT clause
11 * @package PhpMyAdmin
14 /**
15 * do not import request variable into global scope
17 * cannot be used as long as it could happen that the $goto file that is included
18 * at the end of this script is not updated to work without imported request variables
20 * @todo uncomment this if all possible included files to rely on import request variables
21 if (! defined('PMA_NO_VARIABLES_IMPORT')) {
22 define('PMA_NO_VARIABLES_IMPORT', true);
25 /**
26 * Gets some core libraries
28 require_once './libraries/common.inc.php';
30 // Check parameters
31 PMA_checkParameters(array('db', 'table', 'goto'));
33 PMA_DBI_select_db($GLOBALS['db']);
35 /**
36 * Initializes some variables
38 $goto_include = false;
40 $GLOBALS['js_include'][] = 'makegrid.js';
41 // Needed for generation of Inline Edit anchors
42 $GLOBALS['js_include'][] = 'sql.js';
44 if (isset($_REQUEST['insert_rows'])
45 && is_numeric($_REQUEST['insert_rows'])
46 && $_REQUEST['insert_rows'] != $cfg['InsertRows']
47 ) {
48 $cfg['InsertRows'] = $_REQUEST['insert_rows'];
49 $GLOBALS['js_include'][] = 'tbl_change.js';
50 include_once './libraries/header.inc.php';
51 include './tbl_change.php';
52 exit;
55 if (isset($_REQUEST['after_insert'])
56 && in_array($_REQUEST['after_insert'], array('new_insert', 'same_insert', 'edit_next'))
57 ) {
58 $url_params['after_insert'] = $_REQUEST['after_insert'];
59 //$GLOBALS['goto'] = 'tbl_change.php';
60 $goto_include = 'tbl_change.php';
62 if (isset($_REQUEST['where_clause'])) {
63 if ($_REQUEST['after_insert'] == 'same_insert') {
64 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
65 $url_params['where_clause'][] = $one_where_clause;
67 } elseif ($_REQUEST['after_insert'] == 'edit_next') {
68 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
69 $local_query = 'SELECT * FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
70 . ' WHERE ' . str_replace('` =', '` >', $one_where_clause)
71 . ' LIMIT 1;';
72 $res = PMA_DBI_query($local_query);
73 $row = PMA_DBI_fetch_row($res);
74 $meta = PMA_DBI_get_fields_meta($res);
75 // must find a unique condition based on unique key,
76 // not a combination of all fields
77 list($unique_condition, $clause_is_unique) = PMA_getUniqueCondition($res, count($meta), $meta, $row, true);
78 if (! empty($unique_condition)) {
79 $_SESSION['edit_next'] = $unique_condition;
81 unset($unique_condition, $clause_is_unique);
85 } elseif (! empty($GLOBALS['goto'])) {
86 if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
87 // this should NOT happen
88 //$GLOBALS['goto'] = false;
89 $goto_include = false;
90 } else {
91 $goto_include = $GLOBALS['goto'];
93 if ($GLOBALS['goto'] == 'db_sql.php' && strlen($GLOBALS['table'])) {
94 $GLOBALS['table'] = '';
98 if (! $goto_include) {
99 if (! strlen($GLOBALS['table'])) {
100 $goto_include = 'db_sql.php';
101 } else {
102 $goto_include = 'tbl_sql.php';
106 // Defines the url to return in case of failure of the query
107 if (isset($_REQUEST['err_url'])) {
108 $err_url = $_REQUEST['err_url'];
109 } else {
110 $err_url = 'tbl_change.php' . PMA_generate_common_url($url_params);
114 * Prepares the update/insert of a row
116 if (isset($_REQUEST['where_clause'])) {
117 // we were editing something => use the WHERE clause
118 $loop_array = (is_array($_REQUEST['where_clause']) ? $_REQUEST['where_clause'] : array($_REQUEST['where_clause']));
119 $using_key = true;
120 $is_insert = $_REQUEST['submit_type'] == 'insert'
121 || $_REQUEST['submit_type'] == 'showinsert'
122 || $_REQUEST['submit_type'] == 'insertignore';
123 $is_insertignore = $_REQUEST['submit_type'] == 'insertignore';
124 } else {
125 // new row => use indexes
126 $loop_array = array();
127 foreach ($_REQUEST['fields']['multi_edit'] as $key => $dummy) {
128 $loop_array[] = $key;
130 $using_key = false;
131 $is_insert = true;
132 $is_insertignore = false;
135 $query = array();
136 $value_sets = array();
137 $func_no_param = array(
138 'CONNECTION_ID',
139 'CURRENT_USER',
140 'CURDATE',
141 'CURTIME',
142 'DATABASE',
143 'LAST_INSERT_ID',
144 'NOW',
145 'PI',
146 'RAND',
147 'SYSDATE',
148 'UNIX_TIMESTAMP',
149 'USER',
150 'UTC_DATE',
151 'UTC_TIME',
152 'UTC_TIMESTAMP',
153 'UUID',
154 'VERSION',
156 $func_optional_param = array(
157 'RAND',
158 'UNIX_TIMESTAMP',
161 $gis_from_text_functions = array(
162 'GeomFromText',
163 'GeomCollFromText',
164 'LineFromText',
165 'MLineFromText',
166 'PointFromText',
167 'MPointFromText',
168 'PolyFromText',
169 'MPolyFromText',
172 $gis_from_wkb_functions = array(
173 'GeomFromWKB',
174 'GeomCollFromWKB',
175 'LineFromWKB',
176 'MLineFromWKB',
177 'PointFromWKB',
178 'MPointFromWKB',
179 'PolyFromWKB',
180 'MPolyFromWKB',
183 foreach ($loop_array as $rownumber => $where_clause) {
184 // skip fields to be ignored
185 if (! $using_key && isset($_REQUEST['insert_ignore_' . $where_clause])) {
186 continue;
189 // Defines the SET part of the sql query
190 $query_values = array();
192 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
193 $me_fields
194 = isset($_REQUEST['fields']['multi_edit'][$rownumber])
195 ? $_REQUEST['fields']['multi_edit'][$rownumber]
196 : array();
197 $me_fields_name
198 = isset($_REQUEST['fields_name']['multi_edit'][$rownumber])
199 ? $_REQUEST['fields_name']['multi_edit'][$rownumber]
200 : null;
201 $me_fields_prev
202 = isset($_REQUEST['fields_prev']['multi_edit'][$rownumber])
203 ? $_REQUEST['fields_prev']['multi_edit'][$rownumber]
204 : null;
205 $me_funcs
206 = isset($_REQUEST['funcs']['multi_edit'][$rownumber])
207 ? $_REQUEST['funcs']['multi_edit'][$rownumber]
208 : null;
209 $me_fields_type
210 = isset($_REQUEST['fields_type']['multi_edit'][$rownumber])
211 ? $_REQUEST['fields_type']['multi_edit'][$rownumber]
212 : null;
213 $me_fields_null
214 = isset($_REQUEST['fields_null']['multi_edit'][$rownumber])
215 ? $_REQUEST['fields_null']['multi_edit'][$rownumber]
216 : null;
217 $me_fields_null_prev
218 = isset($_REQUEST['fields_null_prev']['multi_edit'][$rownumber])
219 ? $_REQUEST['fields_null_prev']['multi_edit'][$rownumber]
220 : null;
221 $me_auto_increment
222 = isset($_REQUEST['auto_increment']['multi_edit'][$rownumber])
223 ? $_REQUEST['auto_increment']['multi_edit'][$rownumber]
224 : null;
226 // Fetch the current values of a row to use in case we have a protected field
227 // @todo possibly move to ./libraries/tbl_replace_fields.inc.php
228 if ($is_insert
229 && $using_key && isset($me_fields_type)
230 && is_array($me_fields_type) && isset($where_clause)
232 $prot_row = PMA_DBI_fetch_single_row('SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';');
235 // When a select field is nullified, it's not present in $_REQUEST
236 // so initialize it; this way, the foreach($me_fields) will process it
237 foreach ($me_fields_name as $key => $val) {
238 if (! isset($me_fields[$key])) {
239 $me_fields[$key] = '';
243 // Iterate in the order of $me_fields_name, not $me_fields, to avoid problems
244 // when inserting multiple entries
245 foreach ($me_fields_name as $key => $field_name) {
246 $val = $me_fields[$key];
248 // Note: $key is an md5 of the fieldname. The actual fieldname is available in $me_fields_name[$key]
250 include './libraries/tbl_replace_fields.inc.php';
252 if (empty($me_funcs[$key])) {
253 $cur_value = $val;
254 } elseif ('UUID' === $me_funcs[$key]) {
255 /* This way user will know what UUID new row has */
256 $uuid = PMA_DBI_fetch_value('SELECT UUID()');
257 $cur_value = "'" . $uuid . "'";
258 } elseif ((in_array($me_funcs[$key], $gis_from_text_functions)
259 && substr($val, 0, 3) == "'''")
260 || in_array($me_funcs[$key], $gis_from_wkb_functions)
262 // Remove enclosing apostrophes
263 $val = substr($val, 1, strlen($val) - 2);
264 // Remove escaping apostrophes
265 $val = str_replace("''", "'", $val);
266 $cur_value = $me_funcs[$key] . '(' . $val . ')';
267 } elseif (! in_array($me_funcs[$key], $func_no_param)
268 || ($val != "''" && in_array($me_funcs[$key], $func_optional_param))) {
269 $cur_value = $me_funcs[$key] . '(' . $val . ')';
270 } else {
271 $cur_value = $me_funcs[$key] . '()';
274 // i n s e r t
275 if ($is_insert) {
276 // no need to add column into the valuelist
277 if (strlen($cur_value)) {
278 $query_values[] = $cur_value;
279 // first inserted row so prepare the list of fields
280 if (empty($value_sets)) {
281 $query_fields[] = PMA_backquote($me_fields_name[$key]);
285 // u p d a t e
286 } elseif (!empty($me_fields_null_prev[$key])
287 && ! isset($me_fields_null[$key])) {
288 // field had the null checkbox before the update
289 // field no longer has the null checkbox
290 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
291 } elseif (empty($me_funcs[$key])
292 && isset($me_fields_prev[$key])
293 && ("'" . PMA_sqlAddSlashes($me_fields_prev[$key]) . "'" == $val)) {
294 // No change for this column and no MySQL function is used -> next column
295 continue;
296 } elseif (! empty($val)) {
297 // avoid setting a field to NULL when it's already NULL
298 // (field had the null checkbox before the update
299 // field still has the null checkbox)
300 if (empty($me_fields_null_prev[$key])
301 || empty($me_fields_null[$key])
303 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
306 } // end foreach ($me_fields as $key => $val)
308 if (count($query_values) > 0) {
309 if ($is_insert) {
310 $value_sets[] = implode(', ', $query_values);
311 } else {
312 // build update query
313 $query[] = 'UPDATE ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
314 . ' SET ' . implode(', ', $query_values)
315 . ' WHERE ' . $where_clause . ($_REQUEST['clause_is_unique'] ? '' : ' LIMIT 1');
319 } // end foreach ($loop_array as $where_clause)
320 unset($me_fields_name, $me_fields_prev, $me_funcs, $me_fields_type, $me_fields_null, $me_fields_null_prev,
321 $me_auto_increment, $cur_value, $key, $val, $loop_array, $where_clause, $using_key,
322 $func_no_param);
325 // Builds the sql query
326 if ($is_insert && count($value_sets) > 0) {
327 if ($is_insertignore) {
328 $insert_command = 'INSERT IGNORE ';
329 } else {
330 $insert_command = 'INSERT ';
332 $query[] = $insert_command . 'INTO ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
333 . ' (' . implode(', ', $query_fields) . ') VALUES (' . implode('), (', $value_sets) . ')';
334 unset($insert_command);
336 unset($query_fields);
337 } elseif (empty($query)) {
338 // No change -> move back to the calling script
340 // Note: logic passes here for inline edit
341 $message = PMA_Message::success(__('No change'));
342 $active_page = $goto_include;
343 if (! $GLOBALS['is_ajax_request'] == true) {
344 include_once './libraries/header.inc.php';
346 include './' . PMA_securePath($goto_include);
347 exit;
349 unset($me_fields, $is_insertignore);
352 * Executes the sql query and get the result, then move back to the calling
353 * page
355 if (! empty($GLOBALS['sql_query'])) {
356 $url_params['sql_query'] = $GLOBALS['sql_query'];
357 $return_to_sql_query = $GLOBALS['sql_query'];
359 $GLOBALS['sql_query'] = implode('; ', $query) . ';';
360 // to ensure that the query is displayed in case of
361 // "insert as new row" and then "insert another new row"
362 $GLOBALS['display_query'] = $GLOBALS['sql_query'];
364 $total_affected_rows = 0;
365 $last_messages = array();
366 $warning_messages = array();
367 $error_messages = array();
369 foreach ($query as $single_query) {
370 if ($_REQUEST['submit_type'] == 'showinsert') {
371 $last_messages[] = PMA_Message::notice(__('Showing SQL query'));
372 continue;
374 if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
375 $result = PMA_DBI_try_query($single_query);
376 } else {
377 $result = PMA_DBI_query($single_query);
380 if (! $result) {
381 $error_messages[] = PMA_Message::sanitize(PMA_DBI_getError());
382 } else {
383 // The next line contains a real assignment, it's not a typo
384 if ($tmp = @PMA_DBI_affected_rows()) {
385 $total_affected_rows += $tmp;
387 unset($tmp);
389 $insert_id = PMA_DBI_insert_id();
390 if ($insert_id != 0) {
391 // insert_id is id of FIRST record inserted in one insert, so if we
392 // inserted multiple rows, we had to increment this
394 if ($total_affected_rows > 0) {
395 $insert_id = $insert_id + $total_affected_rows - 1;
397 $last_message = PMA_Message::notice(__('Inserted row id: %1$d'));
398 $last_message->addParam($insert_id);
399 $last_messages[] = $last_message;
401 PMA_DBI_free_result($result);
402 } // end if
404 foreach (PMA_DBI_get_warnings() as $warning) {
405 $warning_messages[]
406 = PMA_Message::sanitize(
407 $warning['Level'] . ': #' . $warning['Code'] . ' ' . $warning['Message']
411 unset($result);
413 unset($single_query, $query);
415 if ($is_insert && count($value_sets) > 0) {
416 $message = PMA_Message::inserted_rows($total_affected_rows);
417 } else {
418 $message = PMA_Message::affected_rows($total_affected_rows);
421 $message->addMessages($last_messages, '<br />');
423 if (! empty($warning_messages)) {
424 $message->addMessages($warning_messages, '<br />');
425 $message->isError(true);
427 if (! empty($error_messages)) {
428 $message->addMessages($error_messages);
429 $message->isError(true);
431 unset($error_messages, $warning_messages, $total_affected_rows, $last_messages, $last_message);
433 if ($GLOBALS['is_ajax_request'] == true) {
435 * If we are in grid editing, we need to process the relational and
436 * transformed fields, if they were edited. After that, output the correct
437 * link/transformed value and exit
439 * Logic taken from libraries/display_tbl.lib.php
442 if (isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
443 //handle relations work here for updated row.
444 include_once './libraries/relation.lib.php';
446 $map = PMA_getForeigners($db, $table, '', 'both');
448 $rel_fields = array();
449 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
451 // loop for each relation cell
452 foreach ( $rel_fields as $cell_index => $curr_cell_rel_field) {
454 foreach ( $curr_cell_rel_field as $rel_field => $rel_field_value) {
456 $where_comparison = "='" . $rel_field_value . "'";
457 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
459 // Field to display from the foreign table?
460 if (isset($display_field) && strlen($display_field)) {
461 $dispsql = 'SELECT ' . PMA_backquote($display_field)
462 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
463 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
464 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
465 . $where_comparison;
466 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
467 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
468 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
469 } else {
470 //$dispval = __('Link not found');
472 @PMA_DBI_free_result($dispresult);
473 } else {
474 $dispval = '';
475 } // end if... else...
477 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
478 // user chose "relational key" in the display options, so
479 // the title contains the display field
480 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
481 } else {
482 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
485 $_url_params = array(
486 'db' => $map[$rel_field]['foreign_db'],
487 'table' => $map[$rel_field]['foreign_table'],
488 'pos' => '0',
489 'sql_query' => 'SELECT * FROM '
490 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
491 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field']) . $where_comparison
493 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
495 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
496 // user chose "relational display field" in the
497 // display options, so show display field in the cell
498 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
499 } else {
500 // otherwise display data in the cell
501 $output .= htmlspecialchars($rel_field_value);
503 $output .= '</a>';
504 $extra_data['relations'][$cell_index] = $output;
506 } // end of loop for each relation cell
509 if (isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
510 include_once './libraries/transformations.lib.php';
511 //if some posted fields need to be transformed, generate them here.
512 $mime_map = PMA_getMIME($db, $table);
514 if ($mime_map === false) {
515 $mime_map = array();
518 $edited_values = array();
519 parse_str($_REQUEST['transform_fields_list'], $edited_values);
521 foreach ($mime_map as $transformation) {
522 $include_file = PMA_securePath($transformation['transformation']);
523 $column_name = $transformation['column_name'];
525 foreach ($edited_values as $cell_index => $curr_cell_edited_values) {
526 if (isset($curr_cell_edited_values[$column_name])) {
527 $column_data = $curr_cell_edited_values[$column_name];
529 $_url_params = array(
530 'db' => $db,
531 'table' => $table,
532 'where_clause' => $_REQUEST['where_clause'],
533 'transform_key' => $column_name,
536 if (file_exists('./libraries/transformations/' . $include_file)) {
537 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
539 include_once './libraries/transformations/' . $include_file;
541 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
542 $transform_function = 'PMA_transformation_' . $transformfunction_name;
543 $transform_options = PMA_transformation_getOptions(
544 isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''
546 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
550 $extra_data['transformations'][$cell_index] = $transform_function($column_data, $transform_options);
552 } // end of loop for each transformation cell
553 } // end of loop for each $mime_map
556 /**Get the total row count of the table*/
557 $extra_data['row_count'] = PMA_Table::countRecords($_REQUEST['db'], $_REQUEST['table']);
558 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['display_query']);
559 PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
562 if (isset($return_to_sql_query)) {
563 $disp_query = $GLOBALS['sql_query'];
564 $disp_message = $message;
565 unset($message);
566 $GLOBALS['sql_query'] = $return_to_sql_query;
569 $GLOBALS['js_include'][] = 'tbl_change.js';
570 // in case we call sql.php which needs those:
571 $GLOBALS['js_include'][] = 'jquery/jquery-ui-1.8.16.custom.js';
573 $active_page = $goto_include;
576 * If user asked for "and then Insert another new row" we have to remove
577 * WHERE clause information so that tbl_change.php does not go back
578 * to the current record
580 if (isset($_REQUEST['after_insert']) && 'new_insert' == $_REQUEST['after_insert']) {
581 unset($_REQUEST['where_clause']);
585 * Load header.
587 require_once './libraries/header.inc.php';
589 * Load target page.
591 require './' . PMA_securePath($goto_include);
592 exit;