Merge remote-tracking branch 'origin/master'
[phpmyadmin/gandalfml.git] / sql.php
blobeb6dc5269724b1938c222a0990ce754a63c844d5
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * @todo we must handle the case if sql.php is called directly with a query
5 * that returns 0 rows - to prevent cyclic redirects or includes
6 * @package phpMyAdmin
7 */
9 /**
10 * Gets some core libraries
12 require_once './libraries/common.inc.php';
13 require_once './libraries/Table.class.php';
14 require_once './libraries/check_user_privileges.lib.php';
15 require_once './libraries/bookmark.lib.php';
17 $GLOBALS['js_include'][] = 'jquery/jquery-ui-1.8.custom.js';
18 $GLOBALS['js_include'][] = 'pMap.js';
20 /**
21 * Defines the url to return to in case of error in a sql statement
23 // Security checkings
24 if (! empty($goto)) {
25 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
26 if (! @file_exists('./' . $is_gotofile)) {
27 unset($goto);
28 } else {
29 $is_gotofile = ($is_gotofile == $goto);
31 } else {
32 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
33 $is_gotofile = true;
34 } // end if
36 if (!isset($err_url)) {
37 $err_url = (!empty($back) ? $back : $goto)
38 . '?' . PMA_generate_common_url($db)
39 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
40 } // end if
42 // Coming from a bookmark dialog
43 if (isset($fields['query'])) {
44 $sql_query = $fields['query'];
47 // This one is just to fill $db
48 if (isset($fields['dbase'])) {
49 $db = $fields['dbase'];
52 /**
53 * During inline edit, if we have a relational field, show the dropdown for it
55 * Logic taken from libraries/display_tbl_lib.php
57 * This doesn't seem to be the right place to do this, but I can't think of any
58 * better place either.
60 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
61 require_once 'libraries/relation.lib.php';
63 $column = $_REQUEST['column'];
64 $foreigners = PMA_getForeigners($db, $table, $column);
66 $display_field = PMA_getDisplayField($foreigners[$column][foreign_db], $foreigners[$column][foreign_table]);
68 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
70 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
71 && (isset($display_field) && strlen($display_field)
72 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
73 $curr_value = $_REQUEST['relation_key_or_display_column'];
74 } else {
75 $curr_value = $_REQUEST['curr_value'];
77 if ($foreignData['disp_row'] == null) {
78 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
79 $_url_params = array(
80 'db' => $db,
81 'table' => $table,
82 'field' => $column
85 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
86 . ' target="_blank" class="browse_foreign" '
87 .'>' . __('Browse foreign values') . '</a>';
89 else {
90 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
91 $dropdown = '<select>' . $dropdown . '</select>';
94 $extra_data['dropdown'] = $dropdown;
95 PMA_ajaxResponse(NULL, true, $extra_data);
98 /**
99 * Just like above, find possible values for enum fields during inline edit.
101 * Logic taken from libraries/display_tbl_lib.php
103 if(isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
104 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
106 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
108 $search = array('enum', '(', ')', "'");
110 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
112 $dropdown = '<option value="">&nbsp;</option>';
113 foreach($values as $value) {
114 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
115 if($value == $_REQUEST['curr_value']) {
116 $dropdown .= ' selected="selected"';
118 $dropdown .= '>' . $value . '</option>';
121 $dropdown = '<select>' . $dropdown . '</select>';
123 $extra_data['dropdown'] = $dropdown;
124 PMA_ajaxResponse(NULL, true, $extra_data);
128 * Find possible values for set fields during inline edit.
130 if(isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
131 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
133 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
135 $selected_values = explode(',', $_REQUEST['curr_value']);
137 $search = array('set', '(', ')', "'");
138 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
140 $select = '';
141 foreach($values as $value) {
142 $select .= '<option value="' . htmlspecialchars($value) . '"';
143 if(in_array($value, $selected_values, true)) {
144 $select .= ' selected="selected"';
146 $select .= '>' . $value . '</option>';
149 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
150 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
152 $extra_data['select'] = $select;
153 PMA_ajaxResponse(NULL, true, $extra_data);
155 // Default to browse if no query set and we have table
156 // (needed for browsing from DefaultTabTable)
157 if (empty($sql_query) && strlen($table) && strlen($db)) {
158 require_once './libraries/bookmark.lib.php';
159 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
160 'label', FALSE, TRUE);
162 if (! empty($book_sql_query)) {
163 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
164 $GLOBALS['using_bookmark_message']->addParam($table);
165 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
166 $sql_query = $book_sql_query;
167 } else {
168 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
170 unset($book_sql_query);
172 // set $goto to what will be displayed if query returns 0 rows
173 $goto = 'tbl_structure.php';
174 } else {
175 // Now we can check the parameters
176 PMA_checkParameters(array('sql_query'));
179 // instead of doing the test twice
180 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
181 $sql_query);
184 * Check rights in case of DROP DATABASE
186 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
187 * but since a malicious user may pass this variable by url/form, we don't take
188 * into account this case.
190 if (!defined('PMA_CHK_DROP')
191 && !$cfg['AllowUserDropDatabase']
192 && $is_drop_database
193 && !$is_superuser) {
194 require_once './libraries/header.inc.php';
195 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
196 } // end if
198 require_once './libraries/display_tbl.lib.php';
199 PMA_displayTable_checkConfigParams();
202 * Need to find the real end of rows?
204 if (isset($find_real_end) && $find_real_end) {
205 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
206 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
211 * Bookmark add
213 if (isset($store_bkm)) {
214 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
215 // go back to sql.php to redisplay query; do not use &amp; in this case:
216 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
217 } // end if
220 * Parse and analyze the query
222 require_once './libraries/parse_analyze.lib.php';
225 * Sets or modifies the $goto variable if required
227 if ($goto == 'sql.php') {
228 $is_gotofile = false;
229 $goto = 'sql.php?'
230 . PMA_generate_common_url($db, $table)
231 . '&amp;sql_query=' . urlencode($sql_query);
232 } // end if
236 * Go back to further page if table should not be dropped
238 if (isset($btnDrop) && $btnDrop == __('No')) {
239 if (!empty($back)) {
240 $goto = $back;
242 if ($is_gotofile) {
243 if (strpos($goto, 'db_') === 0 && strlen($table)) {
244 $table = '';
246 $active_page = $goto;
247 require './' . PMA_securePath($goto);
248 } else {
249 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
251 exit();
252 } // end if
256 * Displays the confirm page if required
258 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
259 * with js) because possible security issue is not so important here: at most,
260 * the confirm message isn't displayed.
262 * Also bypassed if only showing php code.or validating a SQL query
264 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
265 // if we are coming from a "Create PHP code" or a "Without PHP Code"
266 // dialog, we won't execute the query anyway, so don't confirm
267 || isset($GLOBALS['show_as_php'])
268 || !empty($GLOBALS['validatequery'])) {
269 $do_confirm = false;
270 } else {
271 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
274 if ($do_confirm) {
275 $stripped_sql_query = $sql_query;
276 require_once './libraries/header.inc.php';
277 if ($is_drop_database) {
278 echo '<h1 class="warning">' . __('You are about to DESTROY a complete database!') . '</h1>';
280 echo '<form action="sql.php" method="post">' . "\n"
281 .PMA_generate_common_hidden_inputs($db, $table);
283 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
284 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
285 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
286 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
287 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
288 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
289 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
290 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
291 <?php
292 echo '<fieldset class="confirmation">' . "\n"
293 .' <legend>' . __('Do you really want to ') . '</legend>'
294 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
295 .'</fieldset>' . "\n"
296 .'<fieldset class="tblFooters">' . "\n";
298 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
299 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
300 <?php
301 echo '</fieldset>' . "\n"
302 . '</form>' . "\n";
305 * Displays the footer and exit
307 require './libraries/footer.inc.php';
308 } // end if $do_confirm
311 // Defines some variables
312 // A table has to be created, renamed, dropped -> navi frame should be reloaded
314 * @todo use the parser/analyzer
317 if (empty($reload)
318 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
319 $reload = 1;
322 // SK -- Patch: $is_group added for use in calculation of total number of
323 // rows.
324 // $is_count is changed for more correct "LIMIT" clause
325 // appending in queries like
326 // "SELECT COUNT(...) FROM ... GROUP BY ..."
329 * @todo detect all this with the parser, to avoid problems finding
330 * those strings in comments or backquoted identifiers
333 $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = $is_replace = false;
334 if ($is_select) { // see line 141
335 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
336 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
337 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
338 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
339 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
340 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
341 $is_explain = true;
342 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
343 $is_delete = true;
344 $is_affected = true;
345 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
346 $is_insert = true;
347 $is_affected = true;
348 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
349 $is_replace = true;
351 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
352 $is_affected = true;
353 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
354 $is_show = true;
355 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
356 $is_maint = true;
359 // Do append a "LIMIT" clause?
360 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
361 && ! ($is_count || $is_export || $is_func || $is_analyse)
362 && isset($analyzed_sql[0]['queryflags']['select_from'])
363 && ! isset($analyzed_sql[0]['queryflags']['offset'])
364 && empty($analyzed_sql[0]['limit_clause'])
366 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
368 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
370 * @todo pretty printing of this modified query
372 if (isset($display_query)) {
373 // if the analysis of the original query revealed that we found
374 // a section_after_limit, we now have to analyze $display_query
375 // to display it correctly
377 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
378 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
379 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
383 } else {
384 $full_sql_query = $sql_query;
385 } // end if...else
387 if (strlen($db)) {
388 PMA_DBI_select_db($db);
391 // E x e c u t e t h e q u e r y
393 // Only if we didn't ask to see the php code (mikebeck)
394 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
395 unset($result);
396 $num_rows = 0;
397 } else {
398 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
399 PMA_DBI_query('SET PROFILING=1;');
402 // Measure query time.
403 $querytime_before = array_sum(explode(' ', microtime()));
405 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
407 $querytime_after = array_sum(explode(' ', microtime()));
409 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
411 // Displays an error message if required and stop parsing the script
412 if ($error = PMA_DBI_getError()) {
413 if ($is_gotofile) {
414 if (strpos($goto, 'db_') === 0 && strlen($table)) {
415 $table = '';
417 $active_page = $goto;
418 $message = PMA_Message::rawError($error);
420 if( $GLOBALS['is_ajax_request'] == true) {
421 PMA_ajaxResponse($message, false);
425 * Go to target path.
427 require './' . PMA_securePath($goto);
428 } else {
429 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
430 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
431 : $err_url;
432 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
434 exit;
436 unset($error);
438 // Gets the number of rows affected/returned
439 // (This must be done immediately after the query because
440 // mysql_affected_rows() reports about the last query done)
442 if (!$is_affected) {
443 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
444 } elseif (!isset($num_rows)) {
445 $num_rows = @PMA_DBI_affected_rows();
448 // Grabs the profiling results
449 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
450 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
453 // Checks if the current database has changed
454 // This could happen if the user sends a query like "USE `database`;"
456 * commented out auto-switching to active database - really required?
457 * bug #1814718 win: table list disappears (mixed case db names)
458 * https://sourceforge.net/support/tracker.php?aid=1814718
459 * @todo RELEASE test and comit or rollback before release
460 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
461 if ($db !== $current_db) {
462 $db = $current_db;
463 $reload = 1;
465 unset($current_db);
468 // tmpfile remove after convert encoding appended by Y.Kawada
469 if (function_exists('PMA_kanji_file_conv')
470 && (isset($textfile) && file_exists($textfile))) {
471 unlink($textfile);
474 // Counts the total number of rows for the same 'SELECT' query without the
475 // 'LIMIT' clause that may have been programatically added
477 if (empty($sql_limit_to_append)) {
478 $unlim_num_rows = $num_rows;
479 // if we did not append a limit, set this to get a correct
480 // "Showing rows..." message
481 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
482 } elseif ($is_select) {
484 // c o u n t q u e r y
486 // If we are "just browsing", there is only one table,
487 // and no WHERE clause (or just 'WHERE 1 '),
488 // we do a quick count (which uses MaxExactCount) because
489 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
491 // However, do not count again if we did it previously
492 // due to $find_real_end == true
494 if (!$is_group
495 && !isset($analyzed_sql[0]['queryflags']['union'])
496 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
497 && (empty($analyzed_sql[0]['where_clause'])
498 || $analyzed_sql[0]['where_clause'] == '1 ')
499 && !isset($find_real_end)
502 // "j u s t b r o w s i n g"
503 $unlim_num_rows = PMA_Table::countRecords($db, $table);
505 } else { // n o t " j u s t b r o w s i n g "
507 // add select expression after the SQL_CALC_FOUND_ROWS
509 // for UNION, just adding SQL_CALC_FOUND_ROWS
510 // after the first SELECT works.
512 // take the left part, could be:
513 // SELECT
514 // (SELECT
515 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
516 $count_query .= ' SQL_CALC_FOUND_ROWS ';
517 // add everything that was after the first SELECT
518 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
519 // ensure there is no semicolon at the end of the
520 // count query because we'll probably add
521 // a LIMIT 1 clause after it
522 $count_query = rtrim($count_query);
523 $count_query = rtrim($count_query, ';');
525 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
526 // long delays. Returned count will be complete anyway.
527 // (but a LIMIT would disrupt results in an UNION)
529 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
530 $count_query .= ' LIMIT 1';
533 // run the count query
535 PMA_DBI_try_query($count_query);
536 // if (mysql_error()) {
537 // void.
538 // I tried the case
539 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
540 // UNION (SELECT `User`, `Host`, "%" AS "Db",
541 // `Select_priv`
542 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
543 // and although the generated count_query is wrong
544 // the SELECT FOUND_ROWS() work! (maybe it gets the
545 // count from the latest query that worked)
547 // another case where the count_query is wrong:
548 // SELECT COUNT(*), f1 from t1 group by f1
549 // and you click to sort on count(*)
550 // }
551 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
552 } // end else "just browsing"
554 } else { // not $is_select
555 $unlim_num_rows = 0;
556 } // end rows total count
558 // if a table or database gets dropped, check column comments.
559 if (isset($purge) && $purge == '1') {
561 * Cleanup relations.
563 require_once './libraries/relation_cleanup.lib.php';
565 if (strlen($table) && strlen($db)) {
566 PMA_relationsCleanupTable($db, $table);
567 } elseif (strlen($db)) {
568 PMA_relationsCleanupDatabase($db);
569 } else {
570 // VOID. No DB/Table gets deleted.
571 } // end if relation-stuff
572 } // end if ($purge)
574 // If a column gets dropped, do relation magic.
575 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
576 require_once './libraries/relation_cleanup.lib.php';
577 PMA_relationsCleanupColumn($db, $table, $dropped_column);
579 } // end if column was dropped
580 } // end else "didn't ask to see php code"
582 // No rows returned -> move back to the calling page
583 if (0 == $num_rows || $is_affected) {
584 if ($is_delete) {
585 $message = PMA_Message::deleted_rows($num_rows);
586 } elseif ($is_insert) {
587 if ($is_replace) {
588 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
589 $message = PMA_Message::affected_rows($num_rows);
590 } else {
591 $message = PMA_Message::inserted_rows($num_rows);
593 $insert_id = PMA_DBI_insert_id();
594 if ($insert_id != 0) {
595 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
596 $message->addMessage('[br]');
597 // need to use a temporary because the Message class
598 // currently supports adding parameters only to the first
599 // message
600 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
601 $_inserted->addParam($insert_id + $num_rows - 1);
602 $message->addMessage($_inserted);
604 } elseif ($is_affected) {
605 $message = PMA_Message::affected_rows($num_rows);
607 // Ok, here is an explanation for the !$is_select.
608 // The form generated by sql_query_form.lib.php
609 // and db_sql.php has many submit buttons
610 // on the same form, and some confusion arises from the
611 // fact that $message_to_show is sent for every case.
612 // The $message_to_show containing a success message and sent with
613 // the form should not have priority over errors
614 } elseif (!empty($message_to_show) && !$is_select) {
615 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
616 } elseif (!empty($GLOBALS['show_as_php'])) {
617 $message = PMA_Message::success(__('Showing as PHP code'));
618 } elseif (isset($GLOBALS['show_as_php'])) {
619 /* User disable showing as PHP, query is only displayed */
620 $message = PMA_Message::notice(__('Showing SQL query'));
621 } elseif (!empty($GLOBALS['validatequery'])) {
622 $message = PMA_Message::notice(__('Validated SQL'));
623 } else {
624 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
627 if (isset($GLOBALS['querytime'])) {
628 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
629 $_querytime->addParam($GLOBALS['querytime']);
630 $message->addMessage('(');
631 $message->addMessage($_querytime);
632 $message->addMessage(')');
635 if( $GLOBALS['is_ajax_request'] == true) {
638 * If we are in inline editing, we need to process the relational and
639 * transformed fields, if they were edited. After that, output the correct
640 * link/transformed value and exit
642 * Logic taken from libraries/display_tbl.lib.php
645 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
646 //handle relations work here for updated row.
647 require_once './libraries/relation.lib.php';
649 $map = PMA_getForeigners($db, $table, '', 'both');
651 $rel_fields = array();
652 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
654 foreach( $rel_fields as $rel_field => $rel_field_value) {
656 $where_comparison = "='" . $rel_field_value . "'";
657 $_url_params = array(
658 'db' => $map[$rel_field]['foreign_db'],
659 'table' => $map[$rel_field]['foreign_table'],
660 'pos' => '0',
661 'sql_query' => 'SELECT * FROM '
662 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
663 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
664 . $where_comparison
667 $extra_data['relations'][$rel_field] = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '">';
668 $extra_data['relations'][$rel_field] .= '</a>';
672 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
673 require_once './libraries/transformations.lib.php';
674 //if some posted fields need to be transformed, generate them here.
675 $mime_map = PMA_getMIME($db, $table);
677 if ($mime_map === FALSE) {
678 $mime_map = array();
681 $edited_values = array();
682 parse_str($_REQUEST['transform_fields_list'], $edited_values);
684 foreach($mime_map as $transformation) {
685 $include_file = $transformation['transformation'];
686 $column_name = $transformation['column_name'];
687 $column_data = $edited_values[$column_name];
689 $_url_params = array(
690 'db' => $db,
691 'table' => $table,
692 'where_clause' => $_REQUEST['where_clause'],
693 'transform_key' => $column_name,
696 if (file_exists('./libraries/transformations/' . $include_file)) {
697 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
699 require_once './libraries/transformations/' . $include_file;
701 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
702 $transform_function = 'PMA_transformation_' . $transformfunction_name;
703 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
704 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
708 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
712 if ($cfg['ShowSQL']) {
713 $extra_data['result_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
715 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
716 $extra_data['reload'] = 1;
717 $extra_data['db'] = $GLOBALS['db'];
719 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
722 if ($is_gotofile) {
723 $goto = PMA_securePath($goto);
724 // Checks for a valid target script
725 $is_db = $is_table = false;
726 if (isset($_REQUEST['purge'])) {
727 $table = '';
728 unset($url_params['table']);
730 include 'libraries/db_table_exists.lib.php';
732 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
733 if (strlen($table)) {
734 $table = '';
736 $goto = 'db_sql.php';
738 if (strpos($goto, 'db_') === 0 && ! $is_db) {
739 if (strlen($db)) {
740 $db = '';
742 $goto = 'main.php';
744 // Loads to target script
745 if ($goto != 'main.php') {
746 require_once './libraries/header.inc.php';
748 $active_page = $goto;
749 require './' . $goto;
750 } else {
751 // avoid a redirect loop when last record was deleted
752 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
753 $goto = str_replace('sql.php','tbl_structure.php',$goto);
755 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
756 } // end else
757 exit();
758 } // end no rows returned
760 // At least one row is returned -> displays a table with results
761 else {
762 //If we are retrieving the full value of a truncated field or the original
763 // value of a transformed field, show it here and exit
764 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
765 $row = PMA_DBI_fetch_row($result);
766 $extra_data = array();
767 $extra_data['value'] = $row[0];
768 PMA_ajaxResponse(NULL, true, $extra_data);
771 // Displays the headers
772 if (isset($show_query)) {
773 unset($show_query);
775 if (isset($printview) && $printview == '1') {
776 require_once './libraries/header_printview.inc.php';
777 } else {
779 $GLOBALS['js_include'][] = 'functions.js';
780 $GLOBALS['js_include'][] = 'sql.js';
782 unset($message);
784 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
785 if (strlen($table)) {
786 require './libraries/tbl_common.php';
787 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
788 require './libraries/tbl_info.inc.php';
789 require './libraries/tbl_links.inc.php';
790 } elseif (strlen($db)) {
791 require './libraries/db_common.inc.php';
792 require './libraries/db_info.inc.php';
793 } else {
794 require './libraries/server_common.inc.php';
795 require './libraries/server_links.inc.php';
798 else {
799 require_once './libraries/header.inc.php';
800 //we don't need to buffer the output in PMA_showMessage here.
801 //set a global variable and check against it in the function
802 $GLOBALS['buffer_message'] = false;
806 if (strlen($db)) {
807 $cfgRelation = PMA_getRelationsParam();
810 // Gets the list of fields properties
811 if (isset($result) && $result) {
812 $fields_meta = PMA_DBI_get_fields_meta($result);
813 $fields_cnt = count($fields_meta);
816 if( ! $GLOBALS['is_ajax_request']) {
817 //begin the sqlqueryresults div here. container div
818 echo '<div id="sqlqueryresults"';
819 if ($GLOBALS['cfg']['AjaxEnable']) {
820 echo ' class="ajax"';
822 echo '>';
825 // Display previous update query (from tbl_replace)
826 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
827 PMA_showMessage($disp_message, $disp_query, 'success');
830 if (isset($profiling_results)) {
831 PMA_profilingResults($profiling_results, true);
834 // Displays the results in a table
835 if (empty($disp_mode)) {
836 // see the "PMA_setDisplayMode()" function in
837 // libraries/display_tbl.lib.php
838 $disp_mode = 'urdr111101';
841 // hide edit and delete links for information_schema
842 if ($db == 'information_schema') {
843 $disp_mode = 'nnnn110111';
846 if (isset($label)) {
847 $message = PMA_message::success(__('Bookmark %s created'));
848 $message->addParam($label);
849 $message->display();
852 PMA_displayTable($result, $disp_mode, $analyzed_sql);
853 PMA_DBI_free_result($result);
855 // BEGIN INDEX CHECK See if indexes should be checked.
856 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
857 foreach ($selected as $idx => $tbl_name) {
858 $check = PMA_Index::findDuplicates($tbl_name, $db);
859 if (! empty($check)) {
860 printf(__('Problems with indexes of table `%s`'), $tbl_name);
861 echo $check;
864 } // End INDEX CHECK
866 // Bookmark support if required
867 if ($disp_mode[7] == '1'
868 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
869 && !empty($sql_query)) {
870 echo "\n";
872 $goto = 'sql.php?'
873 . PMA_generate_common_url($db, $table)
874 . '&amp;sql_query=' . urlencode($sql_query)
875 . '&amp;id_bookmark=1';
878 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
879 <?php echo PMA_generate_common_hidden_inputs(); ?>
880 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
881 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
882 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
883 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
884 <fieldset>
885 <legend><?php
886 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
887 . __('Bookmark this SQL query');
889 </legend>
891 <div class="formelement">
892 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
893 <input type="text" id="fields_label_" name="fields[label]" value="" />
894 </div>
896 <div class="formelement">
897 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
898 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
899 </div>
901 <div class="clearfloat"></div>
902 </fieldset>
903 <fieldset class="tblFooters">
904 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
905 </fieldset>
906 </form>
907 <?php
908 } // end bookmark support
910 // Do print the page if required
911 if (isset($printview) && $printview == '1') {
913 <script type="text/javascript">
914 //<![CDATA[
915 // Do print the page
916 window.onload = function()
918 if (typeof(window.print) != 'undefined') {
919 window.print();
922 //]]>
923 </script>
924 <?php
925 } // end print case
927 if( $GLOBALS['is_ajax_request'] != true) {
928 echo '</div>'; // end sqlqueryresults div
930 } // end rows returned
933 * Displays the footer
935 if(!isset($_REQUEST['table_maintenance'])) {
936 require './libraries/footer.inc.php';