Translation update done using Pootle.
[phpmyadmin.git] / tbl_replace.php
blob6ba156de56022c9daf2a2cc2419bcb5f0495b76f
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';
29 $blob_streaming_active = $GLOBALS['PMA_Config']->get('BLOBSTREAMING_PLUGINS_EXIST');
31 // Check parameters
32 PMA_checkParameters(array('db', 'table', 'goto'));
34 PMA_DBI_select_db($GLOBALS['db']);
36 /**
37 * Initializes some variables
39 $goto_include = false;
41 $GLOBALS['js_include'][] = 'makegrid.js';
42 // Needed for generation of Inline Edit anchors
43 $GLOBALS['js_include'][] = 'sql.js';
45 if (isset($_REQUEST['insert_rows']) && is_numeric($_REQUEST['insert_rows']) && $_REQUEST['insert_rows'] != $cfg['InsertRows']) {
46 $cfg['InsertRows'] = $_REQUEST['insert_rows'];
47 $GLOBALS['js_include'][] = 'tbl_change.js';
48 include_once './libraries/header.inc.php';
49 include './tbl_change.php';
50 exit;
53 if (isset($_REQUEST['after_insert'])
54 && in_array($_REQUEST['after_insert'], array('new_insert', 'same_insert', 'edit_next'))) {
55 $url_params['after_insert'] = $_REQUEST['after_insert'];
56 //$GLOBALS['goto'] = 'tbl_change.php';
57 $goto_include = 'tbl_change.php';
59 if (isset($_REQUEST['where_clause'])) {
60 if ($_REQUEST['after_insert'] == 'same_insert') {
61 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
62 $url_params['where_clause'][] = $one_where_clause;
64 } elseif ($_REQUEST['after_insert'] == 'edit_next') {
65 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
66 $local_query = 'SELECT * FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
67 . ' WHERE ' . str_replace('` =', '` >', $one_where_clause)
68 . ' LIMIT 1;';
69 $res = PMA_DBI_query($local_query);
70 $row = PMA_DBI_fetch_row($res);
71 $meta = PMA_DBI_get_fields_meta($res);
72 // must find a unique condition based on unique key,
73 // not a combination of all fields
74 list($unique_condition, $clause_is_unique) = PMA_getUniqueCondition($res, count($meta), $meta, $row, true);
75 if (! empty($unique_condition)) {
76 $_SESSION['edit_next'] = $unique_condition;
78 unset($unique_condition, $clause_is_unique);
82 } elseif (! empty($GLOBALS['goto'])) {
83 if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
84 // this should NOT happen
85 //$GLOBALS['goto'] = false;
86 $goto_include = false;
87 } else {
88 $goto_include = $GLOBALS['goto'];
90 if ($GLOBALS['goto'] == 'db_sql.php' && strlen($GLOBALS['table'])) {
91 $GLOBALS['table'] = '';
95 if (! $goto_include) {
96 if (! strlen($GLOBALS['table'])) {
97 $goto_include = 'db_sql.php';
98 } else {
99 $goto_include = 'tbl_sql.php';
103 // Defines the url to return in case of failure of the query
104 if (isset($_REQUEST['err_url'])) {
105 $err_url = $_REQUEST['err_url'];
106 } else {
107 $err_url = 'tbl_change.php' . PMA_generate_common_url($url_params);
111 * Prepares the update/insert of a row
113 if (isset($_REQUEST['where_clause'])) {
114 // we were editing something => use the WHERE clause
115 $loop_array = (is_array($_REQUEST['where_clause']) ? $_REQUEST['where_clause'] : array($_REQUEST['where_clause']));
116 $using_key = true;
117 $is_insert = ($_REQUEST['submit_type'] == 'insert') || ($_REQUEST['submit_type'] == 'showinsert') || ($_REQUEST['submit_type'] == 'insertignore');
118 $is_insertignore = ($_REQUEST['submit_type'] == 'insertignore');
119 } else {
120 // new row => use indexes
121 $loop_array = array();
122 foreach ($_REQUEST['fields']['multi_edit'] as $key => $dummy) {
123 $loop_array[] = $key;
125 $using_key = false;
126 $is_insert = true;
127 $is_insertignore = false;
130 $query = array();
131 $value_sets = array();
132 $func_no_param = array(
133 'CONNECTION_ID',
134 'CURRENT_USER',
135 'CURDATE',
136 'CURTIME',
137 'DATABASE',
138 'LAST_INSERT_ID',
139 'NOW',
140 'PI',
141 'RAND',
142 'SYSDATE',
143 'UNIX_TIMESTAMP',
144 'USER',
145 'UTC_DATE',
146 'UTC_TIME',
147 'UTC_TIMESTAMP',
148 'UUID',
149 'VERSION',
151 $func_optional_param = array(
152 'RAND',
153 'UNIX_TIMESTAMP',
156 $gis_from_text_functions = array(
157 'GeomFromText',
158 'GeomCollFromText',
159 'LineFromText',
160 'MLineFromText',
161 'PointFromText',
162 'MPointFromText',
163 'PolyFromText',
164 'MPolyFromText',
167 $gis_from_wkb_functions = array(
168 'GeomFromWKB',
169 'GeomCollFromWKB',
170 'LineFromWKB',
171 'MLineFromWKB',
172 'PointFromWKB',
173 'MPointFromWKB',
174 'PolyFromWKB',
175 'MPolyFromWKB',
178 foreach ($loop_array as $rownumber => $where_clause) {
179 // skip fields to be ignored
180 if (! $using_key && isset($_REQUEST['insert_ignore_' . $where_clause])) {
181 continue;
184 // Defines the SET part of the sql query
185 $query_values = array();
187 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
188 $me_fields
189 = isset($_REQUEST['fields']['multi_edit'][$rownumber])
190 ? $_REQUEST['fields']['multi_edit'][$rownumber]
191 : array();
192 $me_fields_name
193 = isset($_REQUEST['fields_name']['multi_edit'][$rownumber])
194 ? $_REQUEST['fields_name']['multi_edit'][$rownumber]
195 : null;
196 $me_fields_prev
197 = isset($_REQUEST['fields_prev']['multi_edit'][$rownumber])
198 ? $_REQUEST['fields_prev']['multi_edit'][$rownumber]
199 : null;
200 $me_funcs
201 = isset($_REQUEST['funcs']['multi_edit'][$rownumber])
202 ? $_REQUEST['funcs']['multi_edit'][$rownumber]
203 : null;
204 $me_fields_type
205 = isset($_REQUEST['fields_type']['multi_edit'][$rownumber])
206 ? $_REQUEST['fields_type']['multi_edit'][$rownumber]
207 : null;
208 $me_fields_null
209 = isset($_REQUEST['fields_null']['multi_edit'][$rownumber])
210 ? $_REQUEST['fields_null']['multi_edit'][$rownumber]
211 : null;
212 $me_fields_null_prev
213 = isset($_REQUEST['fields_null_prev']['multi_edit'][$rownumber])
214 ? $_REQUEST['fields_null_prev']['multi_edit'][$rownumber]
215 : null;
216 $me_auto_increment
217 = isset($_REQUEST['auto_increment']['multi_edit'][$rownumber])
218 ? $_REQUEST['auto_increment']['multi_edit'][$rownumber]
219 : null;
221 // Fetch the current values of a row to use in case we have a protected field
222 // @todo possibly move to ./libraries/tbl_replace_fields.inc.php
223 if ($is_insert && $using_key && isset($me_fields_type) && is_array($me_fields_type) && isset($where_clause)) {
224 $prot_row = PMA_DBI_fetch_single_row('SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';');
227 // When a select field is nullified, it's not present in $_REQUEST
228 // so initialize it; this way, the foreach($me_fields) will process it
229 foreach ($me_fields_name as $key => $val) {
230 if (! isset($me_fields[$key])) {
231 $me_fields[$key] = '';
235 // Iterate in the order of $me_fields_name, not $me_fields, to avoid problems
236 // when inserting multiple entries
237 foreach ($me_fields_name as $key => $field_name) {
238 $val = $me_fields[$key];
240 // Note: $key is an md5 of the fieldname. The actual fieldname is available in $me_fields_name[$key]
242 include './libraries/tbl_replace_fields.inc.php';
244 // for blobstreaming
245 if ($blob_streaming_active) {
246 $remove_blob_repo = isset($_REQUEST['remove_blob_repo_' . $key]) ? $_REQUEST['remove_blob_repo_' . $key] : null;
247 $upload_blob_repo = isset($_REQUEST['upload_blob_repo_' . $key]) ? $_REQUEST['upload_blob_repo_' . $key] : null;
249 // checks if an existing blob repository reference should be removed
250 if (isset($remove_blob_repo) && ! isset($upload_blob_repo)) {
251 $remove_blob_reference = $_REQUEST['remove_blob_ref_' . $key];
252 if (isset($remove_blob_reference)) {
253 $val = "NULL";
257 // checks if this field requires a bs reference attached to it
258 if (isset($upload_blob_repo)) {
259 // get the most recent BLOB reference
260 $bs_reference = PMA_File::getRecentBLOBReference();
262 // if the most recent BLOB reference exists, set it as a field value
263 if (!is_null($bs_reference)) {
264 $val = "'" . PMA_sqlAddSlashes($bs_reference) . "'";
269 if (empty($me_funcs[$key])) {
270 $cur_value = $val;
271 } elseif ('UUID' === $me_funcs[$key]) {
272 /* This way user will know what UUID new row has */
273 $uuid = PMA_DBI_fetch_value('SELECT UUID()');
274 $cur_value = "'" . $uuid . "'";
275 } elseif ((in_array($me_funcs[$key], $gis_from_text_functions)
276 && substr($val, 0, 3) == "'''")
277 || in_array($me_funcs[$key], $gis_from_wkb_functions)
279 // Remove enclosing apostrophes
280 $val = substr($val, 1, strlen($val) - 2);
281 // Remove escaping apostrophes
282 $val = str_replace("''", "'", $val);
283 $cur_value = $me_funcs[$key] . '(' . $val . ')';
284 } elseif (! in_array($me_funcs[$key], $func_no_param)
285 || ($val != "''" && in_array($me_funcs[$key], $func_optional_param))) {
286 $cur_value = $me_funcs[$key] . '(' . $val . ')';
287 } else {
288 $cur_value = $me_funcs[$key] . '()';
291 // i n s e r t
292 if ($is_insert) {
293 // no need to add column into the valuelist
294 if (strlen($cur_value)) {
295 $query_values[] = $cur_value;
296 // first inserted row so prepare the list of fields
297 if (empty($value_sets)) {
298 $query_fields[] = PMA_backquote($me_fields_name[$key]);
302 // u p d a t e
303 } elseif (!empty($me_fields_null_prev[$key])
304 && ! isset($me_fields_null[$key])) {
305 // field had the null checkbox before the update
306 // field no longer has the null checkbox
307 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
308 } elseif (empty($me_funcs[$key])
309 && isset($me_fields_prev[$key])
310 && ("'" . PMA_sqlAddSlashes($me_fields_prev[$key]) . "'" == $val)) {
311 // No change for this column and no MySQL function is used -> next column
312 continue;
313 } elseif (! empty($val)) {
314 // avoid setting a field to NULL when it's already NULL
315 // (field had the null checkbox before the update
316 // field still has the null checkbox)
317 if (empty($me_fields_null_prev[$key])
318 || empty($me_fields_null[$key])) {
319 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
322 } // end foreach ($me_fields as $key => $val)
324 if (count($query_values) > 0) {
325 if ($is_insert) {
326 $value_sets[] = implode(', ', $query_values);
327 } else {
328 // build update query
329 $query[] = 'UPDATE ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
330 . ' SET ' . implode(', ', $query_values) . ' WHERE ' . $where_clause . ($_REQUEST['clause_is_unique'] ? '' : ' LIMIT 1');
334 } // end foreach ($loop_array as $where_clause)
335 unset($me_fields_name, $me_fields_prev, $me_funcs, $me_fields_type, $me_fields_null, $me_fields_null_prev,
336 $me_auto_increment, $cur_value, $key, $val, $loop_array, $where_clause, $using_key,
337 $func_no_param);
340 // Builds the sql query
341 if ($is_insert && count($value_sets) > 0) {
342 if ($is_insertignore) {
343 $insert_command = 'INSERT IGNORE ';
344 } else {
345 $insert_command = 'INSERT ';
347 $query[] = $insert_command . 'INTO ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
348 . ' (' . implode(', ', $query_fields) . ') VALUES (' . implode('), (', $value_sets) . ')';
349 unset($insert_command);
351 unset($query_fields);
352 } elseif (empty($query)) {
353 // No change -> move back to the calling script
355 // Note: logic passes here for inline edit
356 $message = PMA_Message::success(__('No change'));
357 $active_page = $goto_include;
358 if (! $GLOBALS['is_ajax_request'] == true) {
359 include_once './libraries/header.inc.php';
361 include './' . PMA_securePath($goto_include);
362 exit;
364 unset($me_fields, $is_insertignore);
367 * Executes the sql query and get the result, then move back to the calling
368 * page
370 if (! empty($GLOBALS['sql_query'])) {
371 $url_params['sql_query'] = $GLOBALS['sql_query'];
372 $return_to_sql_query = $GLOBALS['sql_query'];
374 $GLOBALS['sql_query'] = implode('; ', $query) . ';';
375 // to ensure that the query is displayed in case of
376 // "insert as new row" and then "insert another new row"
377 $GLOBALS['display_query'] = $GLOBALS['sql_query'];
379 $total_affected_rows = 0;
380 $last_messages = array();
381 $warning_messages = array();
382 $error_messages = array();
384 foreach ($query as $single_query) {
385 if ($_REQUEST['submit_type'] == 'showinsert') {
386 $last_messages[] = PMA_Message::notice(__('Showing SQL query'));
387 continue;
389 if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
390 $result = PMA_DBI_try_query($single_query);
391 } else {
392 $result = PMA_DBI_query($single_query);
395 if (! $result) {
396 $error_messages[] = PMA_Message::sanitize(PMA_DBI_getError());
397 } else {
398 // The next line contains a real assignment, it's not a typo
399 if ($tmp = @PMA_DBI_affected_rows()) {
400 $total_affected_rows += $tmp;
402 unset($tmp);
404 $insert_id = PMA_DBI_insert_id();
405 if ($insert_id != 0) {
406 // insert_id is id of FIRST record inserted in one insert, so if we
407 // inserted multiple rows, we had to increment this
409 if ($total_affected_rows > 0) {
410 $insert_id = $insert_id + $total_affected_rows - 1;
412 $last_message = PMA_Message::notice(__('Inserted row id: %1$d'));
413 $last_message->addParam($insert_id);
414 $last_messages[] = $last_message;
416 PMA_DBI_free_result($result);
417 } // end if
419 foreach (PMA_DBI_get_warnings() as $warning) {
420 $warning_messages[]
421 = PMA_Message::sanitize(
422 $warning['Level'] . ': #' . $warning['Code'] . ' ' . $warning['Message']
426 unset($result);
428 unset($single_query, $query);
430 if ($is_insert && count($value_sets) > 0) {
431 $message = PMA_Message::inserted_rows($total_affected_rows);
432 } else {
433 $message = PMA_Message::affected_rows($total_affected_rows);
436 $message->addMessages($last_messages, '<br />');
438 if (! empty($warning_messages)) {
439 $message->addMessages($warning_messages, '<br />');
440 $message->isError(true);
442 if (! empty($error_messages)) {
443 $message->addMessages($error_messages);
444 $message->isError(true);
446 unset($error_messages, $warning_messages, $total_affected_rows, $last_messages, $last_message);
448 if ($GLOBALS['is_ajax_request'] == true) {
450 * If we are in grid editing, we need to process the relational and
451 * transformed fields, if they were edited. After that, output the correct
452 * link/transformed value and exit
454 * Logic taken from libraries/display_tbl.lib.php
457 if (isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
458 //handle relations work here for updated row.
459 include_once './libraries/relation.lib.php';
461 $map = PMA_getForeigners($db, $table, '', 'both');
463 $rel_fields = array();
464 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
466 // loop for each relation cell
467 foreach ( $rel_fields as $cell_index => $curr_cell_rel_field) {
469 foreach ( $curr_cell_rel_field as $rel_field => $rel_field_value) {
471 $where_comparison = "='" . $rel_field_value . "'";
472 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
474 // Field to display from the foreign table?
475 if (isset($display_field) && strlen($display_field)) {
476 $dispsql = 'SELECT ' . PMA_backquote($display_field)
477 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
478 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
479 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
480 . $where_comparison;
481 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
482 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
483 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
484 } else {
485 //$dispval = __('Link not found');
487 @PMA_DBI_free_result($dispresult);
488 } else {
489 $dispval = '';
490 } // end if... else...
492 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
493 // user chose "relational key" in the display options, so
494 // the title contains the display field
495 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
496 } else {
497 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
500 $_url_params = array(
501 'db' => $map[$rel_field]['foreign_db'],
502 'table' => $map[$rel_field]['foreign_table'],
503 'pos' => '0',
504 'sql_query' => 'SELECT * FROM '
505 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
506 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
507 . $where_comparison
509 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
511 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
512 // user chose "relational display field" in the
513 // display options, so show display field in the cell
514 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
515 } else {
516 // otherwise display data in the cell
517 $output .= htmlspecialchars($rel_field_value);
519 $output .= '</a>';
520 $extra_data['relations'][$cell_index] = $output;
522 } // end of loop for each relation cell
525 if (isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
526 include_once './libraries/transformations.lib.php';
527 //if some posted fields need to be transformed, generate them here.
528 $mime_map = PMA_getMIME($db, $table);
530 if ($mime_map === false) {
531 $mime_map = array();
534 $edited_values = array();
535 parse_str($_REQUEST['transform_fields_list'], $edited_values);
537 foreach ($mime_map as $transformation) {
538 $include_file = PMA_securePath($transformation['transformation']);
539 $column_name = $transformation['column_name'];
541 foreach ($edited_values as $cell_index => $curr_cell_edited_values) {
542 if (isset($curr_cell_edited_values[$column_name])) {
543 $column_data = $curr_cell_edited_values[$column_name];
545 $_url_params = array(
546 'db' => $db,
547 'table' => $table,
548 'where_clause' => $_REQUEST['where_clause'],
549 'transform_key' => $column_name,
552 if (file_exists('./libraries/transformations/' . $include_file)) {
553 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
555 include_once './libraries/transformations/' . $include_file;
557 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
558 $transform_function = 'PMA_transformation_' . $transformfunction_name;
559 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
560 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
564 $extra_data['transformations'][$cell_index] = $transform_function($column_data, $transform_options);
566 } // end of loop for each transformation cell
567 } // end of loop for each $mime_map
570 /**Get the total row count of the table*/
571 $extra_data['row_count'] = PMA_Table::countRecords($_REQUEST['db'], $_REQUEST['table']);
572 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['display_query']);
573 PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
576 if (isset($return_to_sql_query)) {
577 $disp_query = $GLOBALS['sql_query'];
578 $disp_message = $message;
579 unset($message);
580 $GLOBALS['sql_query'] = $return_to_sql_query;
583 $GLOBALS['js_include'][] = 'tbl_change.js';
584 // in case we call sql.php which needs those:
585 $GLOBALS['js_include'][] = 'jquery/jquery-ui-1.8.16.custom.js';
587 $active_page = $goto_include;
590 * If user asked for "and then Insert another new row" we have to remove
591 * WHERE clause information so that tbl_change.php does not go back
592 * to the current record
594 if (isset($_REQUEST['after_insert']) && 'new_insert' == $_REQUEST['after_insert']) {
595 unset($_REQUEST['where_clause']);
599 * Load header.
601 require_once './libraries/header.inc.php';
603 * Load target page.
605 require './' . PMA_securePath($goto_include);
606 exit;