Minor improvement to prior commit.
[openemr.git] / phpmyadmin / tbl_replace.php
blob00d37a335e9aefbaf339a732800ad15832733343
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
15 /**
16 * Gets some core libraries
18 require_once 'libraries/common.inc.php';
20 /**
21 * functions implementation for this script
23 require_once 'libraries/insert_edit.lib.php';
24 require_once 'libraries/transformations.lib.php';
26 // Check parameters
27 PMA_Util::checkParameters(array('db', 'table', 'goto'));
29 $GLOBALS['dbi']->selectDb($GLOBALS['db']);
31 /**
32 * Initializes some variables
34 $goto_include = false;
36 $response = PMA_Response::getInstance();
37 $header = $response->getHeader();
38 $scripts = $header->getScripts();
39 $scripts->addFile('makegrid.js');
40 // Needed for generation of Inline Edit anchors
41 $scripts->addFile('sql.js');
42 $scripts->addFile('indexes.js');
43 $scripts->addFile('gis_data_editor.js');
45 // check whether insert row mode, if so include tbl_change.php
46 PMA_isInsertRow();
48 $after_insert_actions = array('new_insert', 'same_insert', 'edit_next');
49 if (isset($_REQUEST['after_insert'])
50 && in_array($_REQUEST['after_insert'], $after_insert_actions)
51 ) {
52 $url_params['after_insert'] = $_REQUEST['after_insert'];
53 if (isset($_REQUEST['where_clause'])) {
54 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
55 if ($_REQUEST['after_insert'] == 'same_insert') {
56 $url_params['where_clause'][] = $one_where_clause;
57 } elseif ($_REQUEST['after_insert'] == 'edit_next') {
58 PMA_setSessionForEditNext($one_where_clause);
63 //get $goto_include for different cases
64 $goto_include = PMA_getGotoInclude($goto_include);
66 // Defines the url to return in case of failure of the query
67 $err_url = PMA_getErrorUrl($url_params);
69 /**
70 * Prepares the update/insert of a row
72 list($loop_array, $using_key, $is_insert, $is_insertignore)
73 = PMA_getParamsForUpdateOrInsert();
75 $query = array();
76 $value_sets = array();
77 $func_no_param = array(
78 'CONNECTION_ID',
79 'CURRENT_USER',
80 'CURDATE',
81 'CURTIME',
82 'CURRENT_DATE',
83 'CURRENT_TIME',
84 'DATABASE',
85 'LAST_INSERT_ID',
86 'NOW',
87 'PI',
88 'RAND',
89 'SYSDATE',
90 'UNIX_TIMESTAMP',
91 'USER',
92 'UTC_DATE',
93 'UTC_TIME',
94 'UTC_TIMESTAMP',
95 'UUID',
96 'UUID_SHORT',
97 'VERSION',
99 $func_optional_param = array(
100 'RAND',
101 'UNIX_TIMESTAMP',
104 $gis_from_text_functions = array(
105 'GeomFromText',
106 'GeomCollFromText',
107 'LineFromText',
108 'MLineFromText',
109 'PointFromText',
110 'MPointFromText',
111 'PolyFromText',
112 'MPolyFromText',
115 $gis_from_wkb_functions = array(
116 'GeomFromWKB',
117 'GeomCollFromWKB',
118 'LineFromWKB',
119 'MLineFromWKB',
120 'PointFromWKB',
121 'MPointFromWKB',
122 'PolyFromWKB',
123 'MPolyFromWKB',
126 // to create an object of PMA_File class
127 require_once './libraries/File.class.php';
129 //if some posted fields need to be transformed.
130 $mime_map = PMA_getMIME($GLOBALS['db'], $GLOBALS['table']);
131 if ($mime_map === false) {
132 $mime_map = array();
135 $query_fields = array();
136 $insert_errors = array();
137 $row_skipped = false;
138 $unsaved_values = array();
139 foreach ($loop_array as $rownumber => $where_clause) {
140 // skip fields to be ignored
141 if (! $using_key && isset($_REQUEST['insert_ignore_' . $where_clause])) {
142 continue;
145 // Defines the SET part of the sql query
146 $query_values = array();
148 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
149 $multi_edit_columns
150 = isset($_REQUEST['fields']['multi_edit'][$rownumber])
151 ? $_REQUEST['fields']['multi_edit'][$rownumber]
152 : array();
153 $multi_edit_columns_name
154 = isset($_REQUEST['fields_name']['multi_edit'][$rownumber])
155 ? $_REQUEST['fields_name']['multi_edit'][$rownumber]
156 : array();
157 $multi_edit_columns_prev
158 = isset($_REQUEST['fields_prev']['multi_edit'][$rownumber])
159 ? $_REQUEST['fields_prev']['multi_edit'][$rownumber]
160 : null;
161 $multi_edit_funcs
162 = isset($_REQUEST['funcs']['multi_edit'][$rownumber])
163 ? $_REQUEST['funcs']['multi_edit'][$rownumber]
164 : null;
165 $multi_edit_salt
166 = isset($_REQUEST['salt']['multi_edit'][$rownumber])
167 ? $_REQUEST['salt']['multi_edit'][$rownumber]
168 :null;
169 $multi_edit_columns_type
170 = isset($_REQUEST['fields_type']['multi_edit'][$rownumber])
171 ? $_REQUEST['fields_type']['multi_edit'][$rownumber]
172 : null;
173 $multi_edit_columns_null
174 = isset($_REQUEST['fields_null']['multi_edit'][$rownumber])
175 ? $_REQUEST['fields_null']['multi_edit'][$rownumber]
176 : null;
177 $multi_edit_columns_null_prev
178 = isset($_REQUEST['fields_null_prev']['multi_edit'][$rownumber])
179 ? $_REQUEST['fields_null_prev']['multi_edit'][$rownumber]
180 : null;
181 $multi_edit_auto_increment
182 = isset($_REQUEST['auto_increment']['multi_edit'][$rownumber])
183 ? $_REQUEST['auto_increment']['multi_edit'][$rownumber]
184 : null;
186 // When a select field is nullified, it's not present in $_REQUEST
187 // so initialize it; this way, the foreach($multi_edit_columns) will process it
188 foreach ($multi_edit_columns_name as $key => $val) {
189 if (! isset($multi_edit_columns[$key])) {
190 $multi_edit_columns[$key] = '';
194 // Iterate in the order of $multi_edit_columns_name,
195 // not $multi_edit_columns, to avoid problems
196 // when inserting multiple entries
197 $insert_fail = false;
198 foreach ($multi_edit_columns_name as $key => $column_name) {
199 $current_value = $multi_edit_columns[$key];
200 // Note: $key is an md5 of the fieldname. The actual fieldname is
201 // available in $multi_edit_columns_name[$key]
203 $file_to_insert = new PMA_File();
204 $file_to_insert->checkTblChangeForm($key, $rownumber);
206 $possibly_uploaded_val = $file_to_insert->getContent();
207 if ($possibly_uploaded_val !== false) {
208 $current_value = $possibly_uploaded_val;
210 // Apply Input Transformation if defined
211 if (!empty($mime_map[$column_name])
212 && !empty($mime_map[$column_name]['input_transformation'])
214 $filename = 'libraries/plugins/transformations/'
215 . $mime_map[$column_name]['input_transformation'];
216 if (is_file($filename)) {
217 include_once $filename;
218 $classname = PMA_getTransformationClassName(
219 $mime_map[$column_name]['input_transformation']
221 /** @var IOTransformationsPlugin $transformation_plugin */
222 $transformation_plugin = new $classname();
223 $transformation_options = PMA_Transformation_getOptions(
224 $mime_map[$column_name]['input_transformation_options']
226 $current_value = $transformation_plugin->applyTransformation(
227 $current_value, $transformation_options
229 // check if transformation was successful or not
230 // and accordingly set error messages & insert_fail
231 if (method_exists($transformation_plugin, 'isSuccess')
232 && !$transformation_plugin->isSuccess()
234 $insert_fail = true;
235 $row_skipped = true;
236 $insert_errors[] = sprintf(
237 __('Row: %1$s, Column: %2$s, Error: %3$s'),
238 $rownumber, $column_name,
239 $transformation_plugin->getError()
245 if ($file_to_insert->isError()) {
246 $message .= $file_to_insert->getError();
248 // delete $file_to_insert temporary variable
249 $file_to_insert->cleanUp();
251 $current_value = PMA_getCurrentValueForDifferentTypes(
252 $possibly_uploaded_val, $key, $multi_edit_columns_type,
253 $current_value, $multi_edit_auto_increment,
254 $rownumber, $multi_edit_columns_name, $multi_edit_columns_null,
255 $multi_edit_columns_null_prev, $is_insert,
256 $using_key, $where_clause, $table
259 $current_value_as_an_array = PMA_getCurrentValueAsAnArrayForMultipleEdit(
260 $multi_edit_funcs,
261 $multi_edit_salt, $gis_from_text_functions, $current_value,
262 $gis_from_wkb_functions, $func_optional_param, $func_no_param, $key
265 list($query_values, $query_fields)
266 = PMA_getQueryValuesForInsertAndUpdateInMultipleEdit(
267 $multi_edit_columns_name, $multi_edit_columns_null, $current_value,
268 $multi_edit_columns_prev, $multi_edit_funcs, $is_insert,
269 $query_values, $query_fields, $current_value_as_an_array,
270 $value_sets, $key, $multi_edit_columns_null_prev
272 if (isset($multi_edit_columns_null[$key])) {
273 $multi_edit_columns[$key] = null;
275 } //end of foreach
277 // temporarily store rows not inserted
278 // so that they can be populated again.
279 if ($insert_fail) {
280 $unsaved_values[$rownumber] = $multi_edit_columns;
282 if (!$insert_fail && count($query_values) > 0) {
283 if ($is_insert) {
284 $value_sets[] = implode(', ', $query_values);
285 } else {
286 // build update query
287 $query[] = 'UPDATE ' . PMA_Util::backquote($GLOBALS['table'])
288 . ' SET ' . implode(', ', $query_values)
289 . ' WHERE ' . $where_clause
290 . ($_REQUEST['clause_is_unique'] ? '' : ' LIMIT 1');
293 } // end foreach ($loop_array as $where_clause)
294 unset($multi_edit_columns_name, $multi_edit_columns_prev, $multi_edit_funcs,
295 $multi_edit_columns_type, $multi_edit_columns_null, $func_no_param,
296 $multi_edit_auto_increment, $current_value_as_an_array, $key, $current_value,
297 $loop_array, $where_clause, $using_key, $multi_edit_columns_null_prev,
298 $insert_fail);
300 // Builds the sql query
301 if ($is_insert && count($value_sets) > 0) {
302 $query = PMA_buildSqlQuery($is_insertignore, $query_fields, $value_sets);
303 } elseif (empty($query) && ! isset($_REQUEST['preview_sql']) && !$row_skipped) {
304 // No change -> move back to the calling script
306 // Note: logic passes here for inline edit
307 $message = PMA_Message::success(__('No change'));
308 $active_page = $goto_include;
309 include '' . PMA_securePath($goto_include);
310 exit;
312 unset($multi_edit_columns, $is_insertignore);
314 // If there is a request for SQL previewing.
315 if (isset($_REQUEST['preview_sql'])) {
316 PMA_previewSQL($query);
320 * Executes the sql query and get the result, then move back to the calling
321 * page
323 list ($url_params, $total_affected_rows, $last_messages, $warning_messages,
324 $error_messages, $return_to_sql_query)
325 = PMA_executeSqlQuery($url_params, $query);
327 if ($is_insert && (count($value_sets) > 0 || $row_skipped)) {
328 $message = PMA_Message::getMessageForInsertedRows($total_affected_rows);
329 $unsaved_values = array_values($unsaved_values);
330 } else {
331 $message = PMA_Message::getMessageForAffectedRows($total_affected_rows);
333 if ($row_skipped) {
334 $goto_include = 'tbl_change.php';
335 $message->addMessages($insert_errors, '<br />');
336 $message->isError(true);
339 $message->addMessages($last_messages, '<br />');
341 if (! empty($warning_messages)) {
342 $message->addMessages($warning_messages, '<br />');
343 $message->isError(true);
345 if (! empty($error_messages)) {
346 $message->addMessages($error_messages);
347 $message->isError(true);
349 unset(
350 $error_messages, $warning_messages, $total_affected_rows,
351 $last_messages, $last_message, $row_skipped, $insert_errors
355 * The following section only applies to grid editing.
356 * However, verifying isAjax() is not enough to ensure we are coming from
357 * grid editing. If we are coming from the Edit or Copy link in Browse mode,
358 * ajax_page_request is present in the POST parameters.
360 if ($response->isAjax() && ! isset($_POST['ajax_page_request'])) {
362 * If we are in grid editing, we need to process the relational and
363 * transformed fields, if they were edited. After that, output the correct
364 * link/transformed value and exit
366 * Logic taken from libraries/DisplayResults.class.php
369 if (isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
371 $map = PMA_getForeigners($db, $table, '', 'both');
373 $relation_fields = array();
374 parse_str($_REQUEST['rel_fields_list'], $relation_fields);
376 // loop for each relation cell
377 /** @var array $relation_fields */
378 foreach ($relation_fields as $cell_index => $curr_rel_field) {
379 foreach ($curr_rel_field as $relation_field => $relation_field_value) {
380 $where_comparison = "='" . $relation_field_value . "'";
381 $dispval = PMA_getDisplayValueForForeignTableColumn(
382 $where_comparison, $map, $relation_field
385 $extra_data['relations'][$cell_index]
386 = PMA_getLinkForRelationalDisplayField(
387 $map, $relation_field, $where_comparison,
388 $dispval, $relation_field_value
391 } // end of loop for each relation cell
393 if (isset($_REQUEST['do_transformations'])
394 && $_REQUEST['do_transformations'] == true
396 $edited_values = array();
397 parse_str($_REQUEST['transform_fields_list'], $edited_values);
399 if (! isset($extra_data)) {
400 $extra_data = array();
402 $transformation_types = array(
403 "input_transformation",
404 "transformation"
406 foreach ($mime_map as $transformation) {
407 $column_name = $transformation['column_name'];
408 foreach ($transformation_types as $type) {
409 $file = PMA_securePath($transformation[$type]);
410 $extra_data = PMA_transformEditedValues(
411 $db, $table, $transformation, $edited_values, $file,
412 $column_name, $extra_data, $type
415 } // end of loop for each $mime_map
418 // Need to check the inline edited value can be truncated by MySQL
419 // without informing while saving
420 $column_name = $_REQUEST['fields_name']['multi_edit'][0][0];
422 PMA_verifyWhetherValueCanBeTruncatedAndAppendExtraData(
423 $db, $table, $column_name, $extra_data
426 /**Get the total row count of the table*/
427 $_table = new PMA_Table($_REQUEST['table'], $_REQUEST['db']);
428 $extra_data['row_count'] = $_table->countRecords();
430 $extra_data['sql_query']
431 = PMA_Util::getMessage($message, $GLOBALS['display_query']);
433 $response = PMA_Response::getInstance();
434 $response->isSuccess($message->isSuccess());
435 $response->addJSON('message', $message);
436 $response->addJSON($extra_data);
437 exit;
440 if (! empty($return_to_sql_query)) {
441 $disp_query = $GLOBALS['sql_query'];
442 $disp_message = $message;
443 unset($message);
444 $GLOBALS['sql_query'] = $return_to_sql_query;
447 $scripts->addFile('tbl_change.js');
448 $scripts->addFile('big_ints.js');
450 $active_page = $goto_include;
453 * If user asked for "and then Insert another new row" we have to remove
454 * WHERE clause information so that tbl_change.php does not go back
455 * to the current record
457 if (isset($_REQUEST['after_insert']) && 'new_insert' == $_REQUEST['after_insert']) {
458 unset($_REQUEST['where_clause']);
462 * Load target page.
464 require '' . PMA_securePath($goto_include);
465 exit;