Fix broken characters
[phpmyadmin/ammaryasirr.git] / tbl_replace.php
blob40d0ad48d6bb9cdaf50d5dd61dcff5e9e56b2f00
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 * @uses PMA_checkParameters()
12 * @uses PMA_DBI_select_db()
13 * @uses PMA_DBI_query()
14 * @uses PMA_DBI_fetch_row()
15 * @uses PMA_DBI_get_fields_meta()
16 * @uses PMA_DBI_free_result()
17 * @uses PMA_DBI_try_query()
18 * @uses PMA_DBI_getError()
19 * @uses PMA_DBI_affected_rows()
20 * @uses PMA_DBI_insert_id()
21 * @uses PMA_backquote()
22 * @uses PMA_getUniqueCondition()
23 * @uses PMA_sqlAddslashes()
24 * @uses PMA_securePath()
25 * @uses PMA_sendHeaderLocation()
26 * @uses str_replace()
27 * @uses count()
28 * @uses file_exists()
29 * @uses strlen()
30 * @uses str_replace()
31 * @uses preg_replace()
32 * @uses is_array()
33 * @uses $GLOBALS['db']
34 * @uses $GLOBALS['table']
35 * @uses $GLOBALS['goto']
36 * @uses $GLOBALS['sql_query']
37 * @uses PMA_File::getRecentBLOBReference()
38 * @package phpMyAdmin
41 /**
42 * do not import request variable into global scope
44 * cannot be used as long as it could happen that the $goto file that is included
45 * at the end of this script is not updated to work without imported request variables
47 * @todo uncomment this if all possible included files to rely on import request variables
48 if (! defined('PMA_NO_VARIABLES_IMPORT')) {
49 define('PMA_NO_VARIABLES_IMPORT', true);
52 /**
53 * Gets some core libraries
55 require_once './libraries/common.inc.php';
56 $blob_streaming_active = $GLOBALS['PMA_Config']->get('BLOBSTREAMING_PLUGINS_EXIST');
58 // Check parameters
59 PMA_checkParameters(array('db', 'table', 'goto'));
61 PMA_DBI_select_db($GLOBALS['db']);
63 /**
64 * Initializes some variables
66 $goto_include = false;
68 // Needed for generation of Inline Edit anchors
69 $GLOBALS['js_include'][] = 'sql.js';
71 if (isset($_REQUEST['insert_rows']) && is_numeric($_REQUEST['insert_rows']) && $_REQUEST['insert_rows'] != $cfg['InsertRows']) {
72 $cfg['InsertRows'] = $_REQUEST['insert_rows'];
73 $GLOBALS['js_include'][] = 'tbl_change.js';
74 require_once './libraries/header.inc.php';
75 require './tbl_change.php';
76 exit;
79 if (isset($_REQUEST['after_insert'])
80 && in_array($_REQUEST['after_insert'], array('new_insert', 'same_insert', 'edit_next'))) {
81 $url_params['after_insert'] = $_REQUEST['after_insert'];
82 //$GLOBALS['goto'] = 'tbl_change.php';
83 $goto_include = 'tbl_change.php';
85 if (isset($_REQUEST['where_clause'])) {
86 if ($_REQUEST['after_insert'] == 'same_insert') {
87 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
88 $url_params['where_clause'][] = $one_where_clause;
90 } elseif ($_REQUEST['after_insert'] == 'edit_next') {
91 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
92 $local_query = 'SELECT * FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
93 . ' WHERE ' . str_replace('` =', '` >', $one_where_clause)
94 . ' LIMIT 1;';
95 $res = PMA_DBI_query($local_query);
96 $row = PMA_DBI_fetch_row($res);
97 $meta = PMA_DBI_get_fields_meta($res);
98 // must find a unique condition based on unique key,
99 // not a combination of all fields
100 list($unique_condition, $clause_is_unique) = PMA_getUniqueCondition($res, count($meta), $meta, $row, true);
101 if (! empty($unique_condition)) {
102 $_SESSION['edit_next'] = $unique_condition;
104 unset($unique_condition, $clause_is_unique);
108 } elseif (! empty($GLOBALS['goto'])) {
109 if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
110 // this should NOT happen
111 //$GLOBALS['goto'] = false;
112 $goto_include = false;
113 } else {
114 $goto_include = $GLOBALS['goto'];
116 if ($GLOBALS['goto'] == 'db_sql.php' && strlen($GLOBALS['table'])) {
117 $GLOBALS['table'] = '';
121 if (! $goto_include) {
122 if (! strlen($GLOBALS['table'])) {
123 $goto_include = 'db_sql.php';
124 } else {
125 $goto_include = 'tbl_sql.php';
129 // Defines the url to return in case of failure of the query
130 if (isset($_REQUEST['err_url'])) {
131 $err_url = $_REQUEST['err_url'];
132 } else {
133 $err_url = 'tbl_change.php' . PMA_generate_common_url($url_params);
137 * Prepares the update/insert of a row
139 if (isset($_REQUEST['where_clause'])) {
140 // we were editing something => use the WHERE clause
141 $loop_array = (is_array($_REQUEST['where_clause']) ? $_REQUEST['where_clause'] : array($_REQUEST['where_clause']));
142 $using_key = true;
143 $is_insert = ($_REQUEST['submit_type'] == 'insert') || ($_REQUEST['submit_type'] == 'showinsert') || ($_REQUEST['submit_type'] == 'insertignore');
144 $is_insertignore = ($_REQUEST['submit_type'] == 'insertignore');
145 } else {
146 // new row => use indexes
147 $loop_array = array();
148 foreach ($_REQUEST['fields']['multi_edit'] as $key => $dummy) {
149 $loop_array[] = $key;
151 $using_key = false;
152 $is_insert = true;
153 $is_insertignore = false;
156 $query = array();
157 $value_sets = array();
158 $func_no_param = array(
159 'NOW',
160 'CURDATE',
161 'CURTIME',
162 'UTC_DATE',
163 'UTC_TIME',
164 'UTC_TIMESTAMP',
165 'UNIX_TIMESTAMP',
166 'RAND',
167 'USER',
168 'LAST_INSERT_ID',
169 'UUID',
170 'CURRENT_USER',
173 foreach ($loop_array as $rownumber => $where_clause) {
174 // skip fields to be ignored
175 if (! $using_key && isset($_REQUEST['insert_ignore_' . $where_clause])) {
176 continue;
179 // Defines the SET part of the sql query
180 $query_values = array();
182 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
183 $me_fields =
184 isset($_REQUEST['fields']['multi_edit'][$rownumber])
185 ? $_REQUEST['fields']['multi_edit'][$rownumber]
186 : array();
187 $me_fields_name =
188 isset($_REQUEST['fields_name']['multi_edit'][$rownumber])
189 ? $_REQUEST['fields_name']['multi_edit'][$rownumber]
190 : null;
191 $me_fields_prev =
192 isset($_REQUEST['fields_prev']['multi_edit'][$rownumber])
193 ? $_REQUEST['fields_prev']['multi_edit'][$rownumber]
194 : null;
195 $me_funcs =
196 isset($_REQUEST['funcs']['multi_edit'][$rownumber])
197 ? $_REQUEST['funcs']['multi_edit'][$rownumber]
198 : null;
199 $me_fields_type =
200 isset($_REQUEST['fields_type']['multi_edit'][$rownumber])
201 ? $_REQUEST['fields_type']['multi_edit'][$rownumber]
202 : null;
203 $me_fields_null =
204 isset($_REQUEST['fields_null']['multi_edit'][$rownumber])
205 ? $_REQUEST['fields_null']['multi_edit'][$rownumber]
206 : null;
207 $me_fields_null_prev =
208 isset($_REQUEST['fields_null_prev']['multi_edit'][$rownumber])
209 ? $_REQUEST['fields_null_prev']['multi_edit'][$rownumber]
210 : null;
211 $me_auto_increment =
212 isset($_REQUEST['auto_increment']['multi_edit'][$rownumber])
213 ? $_REQUEST['auto_increment']['multi_edit'][$rownumber]
214 : null;
216 // Fetch the current values of a row to use in case we have a protected field
217 // @todo possibly move to ./libraries/tbl_replace_fields.inc.php
218 if ($is_insert && $using_key && isset($me_fields_type) && is_array($me_fields_type) && isset($where_clause)) {
219 $prot_row = PMA_DBI_fetch_single_row('SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';');
221 foreach ($me_fields as $key => $val) {
223 // Note: $key is an md5 of the fieldname. The actual fieldname is available in $me_fields_name[$key]
225 require './libraries/tbl_replace_fields.inc.php';
227 // for blobstreaming
228 if ($blob_streaming_active) {
229 $remove_blob_repo = isset($_REQUEST['remove_blob_repo_' . $key]) ? $_REQUEST['remove_blob_repo_' . $key] : NULL;
230 $upload_blob_repo = isset($_REQUEST['upload_blob_repo_' . $key]) ? $_REQUEST['upload_blob_repo_' . $key] : NULL;
232 // checks if an existing blob repository reference should be removed
233 if (isset($remove_blob_repo) && ! isset($upload_blob_repo)) {
234 $remove_blob_reference = $_REQUEST['remove_blob_ref_' . $key];
235 if (isset($remove_blob_reference)) {
236 $val = "NULL";
240 // checks if this field requires a bs reference attached to it
241 if (isset($upload_blob_repo)) {
242 // get the most recent BLOB reference
243 $bs_reference = PMA_File::getRecentBLOBReference();
245 // if the most recent BLOB reference exists, set it as a field value
246 if (!is_null($bs_reference)) {
247 $val = "'" . PMA_sqlAddslashes($bs_reference) . "'";
252 if (empty($me_funcs[$key])) {
253 $cur_value = $val;
254 } elseif ('UNIX_TIMESTAMP' === $me_funcs[$key] && $val != "''") {
255 $cur_value = $me_funcs[$key] . '(' . $val . ')';
256 } elseif ('UUID' === $me_funcs[$key]) {
257 /* This way user will know what UUID new row has */
258 $uuid = PMA_DBI_fetch_value('SELECT UUID()');
259 $cur_value = "'" . $uuid . "'";
260 } elseif (in_array($me_funcs[$key], $func_no_param)) {
261 $cur_value = $me_funcs[$key] . '()';
262 } else {
263 $cur_value = $me_funcs[$key] . '(' . $val . ')';
266 // i n s e r t
267 if ($is_insert) {
268 // no need to add column into the valuelist
269 if (strlen($cur_value)) {
270 $query_values[] = $cur_value;
271 // first inserted row so prepare the list of fields
272 if (empty($value_sets)) {
273 $query_fields[] = PMA_backquote($me_fields_name[$key]);
277 // u p d a t e
278 } elseif (!empty($me_fields_null_prev[$key])
279 && !isset($me_fields_null[$key])) {
280 // field had the null checkbox before the update
281 // field no longer has the null checkbox
282 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
283 } elseif (empty($me_funcs[$key])
284 && isset($me_fields_prev[$key])
285 && ("'" . PMA_sqlAddslashes($me_fields_prev[$key]) . "'" == $val)) {
286 // No change for this column and no MySQL function is used -> next column
287 continue;
288 } elseif (! empty($val)) {
289 // avoid setting a field to NULL when it's already NULL
290 // (field had the null checkbox before the update
291 // field still has the null checkbox)
292 if (!(! empty($me_fields_null_prev[$key])
293 && isset($me_fields_null[$key]))) {
294 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
297 } // end foreach ($me_fields as $key => $val)
299 if (count($query_values) > 0) {
300 if ($is_insert) {
301 $value_sets[] = implode(', ', $query_values);
302 } else {
303 // build update query
304 $query[] = 'UPDATE ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
305 . ' SET ' . implode(', ', $query_values) . ' WHERE ' . $where_clause . ($_REQUEST['clause_is_unique'] ? '' : ' LIMIT 1');
309 } // end foreach ($loop_array as $where_clause)
310 unset($me_fields_name, $me_fields_prev, $me_funcs, $me_fields_type, $me_fields_null, $me_fields_null_prev,
311 $me_auto_increment, $cur_value, $key, $val, $loop_array, $where_clause, $using_key,
312 $func_no_param);
315 // Builds the sql query
316 if ($is_insert && count($value_sets) > 0) {
317 if ($is_insertignore) {
318 $insert_command = 'INSERT IGNORE ';
319 } else {
320 $insert_command = 'INSERT ';
322 $query[] = $insert_command . 'INTO ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
323 . ' (' . implode(', ', $query_fields) . ') VALUES (' . implode('), (', $value_sets) . ')';
324 unset($insert_command);
326 unset($query_fields);
327 } elseif (empty($query)) {
328 // No change -> move back to the calling script
330 // Note: logic passes here for inline edit
331 $message = PMA_Message::success(__('No change'));
332 $active_page = $goto_include;
333 if(! $GLOBALS['is_ajax_request'] == true) {
334 require_once './libraries/header.inc.php';
336 require './' . PMA_securePath($goto_include);
337 exit;
339 unset($me_fields, $is_insertignore);
342 * Executes the sql query and get the result, then move back to the calling
343 * page
345 if (! empty($GLOBALS['sql_query'])) {
346 $url_params['sql_query'] = $GLOBALS['sql_query'];
347 $return_to_sql_query = $GLOBALS['sql_query'];
349 $GLOBALS['sql_query'] = implode('; ', $query) . ';';
350 // to ensure that the query is displayed in case of
351 // "insert as new row" and then "insert another new row"
352 $GLOBALS['display_query'] = $GLOBALS['sql_query'];
354 $total_affected_rows = 0;
355 $last_messages = array();
356 $warning_messages = array();
357 $error_messages = array();
359 foreach ($query as $single_query) {
360 if ($_REQUEST['submit_type'] == 'showinsert') {
361 $last_messages[] = PMA_Message::notice(__('Showing SQL query'));
362 continue;
364 if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
365 $result = PMA_DBI_try_query($single_query);
366 } else {
367 $result = PMA_DBI_query($single_query);
370 if (! $result) {
371 $error_messages[] = PMA_DBI_getError();
372 } else {
373 // The next line contains a real assignment, it's not a typo
374 if ($tmp = @PMA_DBI_affected_rows()) {
375 $total_affected_rows += $tmp;
377 unset($tmp);
379 $insert_id = PMA_DBI_insert_id();
380 if ($insert_id != 0) {
381 // insert_id is id of FIRST record inserted in one insert, so if we
382 // inserted multiple rows, we had to increment this
384 if ($total_affected_rows > 0) {
385 $insert_id = $insert_id + $total_affected_rows - 1;
387 $last_message = PMA_Message::notice(__('Inserted row id: %1$d'));
388 $last_message->addParam($insert_id);
389 $last_messages[] = $last_message;
391 PMA_DBI_free_result($result);
392 } // end if
394 foreach (PMA_DBI_get_warnings() as $warning) {
395 $warning_messages[] = $warning['Level'] . ': #' . $warning['Code']
396 . ' ' . $warning['Message'];
399 unset($result);
401 unset($single_query, $query);
403 if ($is_insert && count($value_sets) > 0) {
404 $message = PMA_Message::inserted_rows($total_affected_rows);
405 } else {
406 $message = PMA_Message::affected_rows($total_affected_rows);
409 $message->addMessages($last_messages, '<br />');
411 if (! empty($warning_messages)) {
413 * @todo use a <div class="error"> in PMA_showMessage() for this part of
414 * the message
416 $message->addMessages($warning_messages, '<br />');
417 $message->isError(true);
419 if (! empty($error_messages)) {
420 $message->addMessages($error_messages);
421 $message->isError(true);
423 unset($error_messages, $warning_messages, $total_affected_rows, $last_messages, $last_message);
425 if($GLOBALS['is_ajax_request'] == true) {
427 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
428 PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
431 if (isset($return_to_sql_query)) {
432 $disp_query = $GLOBALS['sql_query'];
433 $disp_message = $message;
434 unset($message);
435 $GLOBALS['sql_query'] = $return_to_sql_query;
438 $GLOBALS['js_include'][] = 'tbl_change.js';
439 // in case we call sql.php which needs those:
440 $GLOBALS['js_include'][] = 'jquery/jquery-ui-1.8.custom.js';
442 $active_page = $goto_include;
445 * If user asked for "and then Insert another new row" we have to remove
446 * WHERE clause information so that tbl_change.php does not go back
447 * to the current record
449 if (isset($_REQUEST['after_insert']) && 'new_insert' == $_REQUEST['after_insert']) {
450 unset($_REQUEST['where_clause']);
454 * Load header.
456 require_once './libraries/header.inc.php';
458 * Load target page.
460 require './' . PMA_securePath($goto_include);
461 exit;