bug #3449659 [navi] Fast filter broken with table tree
[phpmyadmin/madhuracj.git] / sql.php
blob6b2628aca693fc2eb79c3e2c5034b09e19169bab
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="error">' . __('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 $unlim_num_rows = 0;
398 } else {
399 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
400 PMA_DBI_query('SET PROFILING=1;');
403 // Measure query time.
404 $querytime_before = array_sum(explode(' ', microtime()));
406 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
408 $querytime_after = array_sum(explode(' ', microtime()));
410 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
412 // Displays an error message if required and stop parsing the script
413 if ($error = PMA_DBI_getError()) {
414 if ($is_gotofile) {
415 if (strpos($goto, 'db_') === 0 && strlen($table)) {
416 $table = '';
418 $active_page = $goto;
419 $message = PMA_Message::rawError($error);
421 if( $GLOBALS['is_ajax_request'] == true) {
422 PMA_ajaxResponse($message, false);
426 * Go to target path.
428 require './' . PMA_securePath($goto);
429 } else {
430 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
431 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
432 : $err_url;
433 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
435 exit;
437 unset($error);
439 // Gets the number of rows affected/returned
440 // (This must be done immediately after the query because
441 // mysql_affected_rows() reports about the last query done)
443 if (!$is_affected) {
444 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
445 } elseif (!isset($num_rows)) {
446 $num_rows = @PMA_DBI_affected_rows();
449 // Grabs the profiling results
450 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
451 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
454 // Checks if the current database has changed
455 // This could happen if the user sends a query like "USE `database`;"
457 * commented out auto-switching to active database - really required?
458 * bug #1814718 win: table list disappears (mixed case db names)
459 * https://sourceforge.net/support/tracker.php?aid=1814718
460 * @todo RELEASE test and comit or rollback before release
461 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
462 if ($db !== $current_db) {
463 $db = $current_db;
464 $reload = 1;
466 unset($current_db);
469 // tmpfile remove after convert encoding appended by Y.Kawada
470 if (function_exists('PMA_kanji_file_conv')
471 && (isset($textfile) && file_exists($textfile))) {
472 unlink($textfile);
475 // Counts the total number of rows for the same 'SELECT' query without the
476 // 'LIMIT' clause that may have been programatically added
478 if (empty($sql_limit_to_append)) {
479 $unlim_num_rows = $num_rows;
480 // if we did not append a limit, set this to get a correct
481 // "Showing rows..." message
482 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
483 } elseif ($is_select) {
485 // c o u n t q u e r y
487 // If we are "just browsing", there is only one table,
488 // and no WHERE clause (or just 'WHERE 1 '),
489 // we do a quick count (which uses MaxExactCount) because
490 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
492 // However, do not count again if we did it previously
493 // due to $find_real_end == true
495 if (!$is_group
496 && !isset($analyzed_sql[0]['queryflags']['union'])
497 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
498 && (empty($analyzed_sql[0]['where_clause'])
499 || $analyzed_sql[0]['where_clause'] == '1 ')
500 && !isset($find_real_end)
503 // "j u s t b r o w s i n g"
504 $unlim_num_rows = PMA_Table::countRecords($db, $table);
506 } else { // n o t " j u s t b r o w s i n g "
508 // add select expression after the SQL_CALC_FOUND_ROWS
510 // for UNION, just adding SQL_CALC_FOUND_ROWS
511 // after the first SELECT works.
513 // take the left part, could be:
514 // SELECT
515 // (SELECT
516 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
517 $count_query .= ' SQL_CALC_FOUND_ROWS ';
518 // add everything that was after the first SELECT
519 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
520 // ensure there is no semicolon at the end of the
521 // count query because we'll probably add
522 // a LIMIT 1 clause after it
523 $count_query = rtrim($count_query);
524 $count_query = rtrim($count_query, ';');
526 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
527 // long delays. Returned count will be complete anyway.
528 // (but a LIMIT would disrupt results in an UNION)
530 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
531 $count_query .= ' LIMIT 1';
534 // run the count query
536 PMA_DBI_try_query($count_query);
537 // if (mysql_error()) {
538 // void.
539 // I tried the case
540 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
541 // UNION (SELECT `User`, `Host`, "%" AS "Db",
542 // `Select_priv`
543 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
544 // and although the generated count_query is wrong
545 // the SELECT FOUND_ROWS() work! (maybe it gets the
546 // count from the latest query that worked)
548 // another case where the count_query is wrong:
549 // SELECT COUNT(*), f1 from t1 group by f1
550 // and you click to sort on count(*)
551 // }
552 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
553 } // end else "just browsing"
555 } else { // not $is_select
556 $unlim_num_rows = 0;
557 } // end rows total count
559 // if a table or database gets dropped, check column comments.
560 if (isset($purge) && $purge == '1') {
562 * Cleanup relations.
564 require_once './libraries/relation_cleanup.lib.php';
566 if (strlen($table) && strlen($db)) {
567 PMA_relationsCleanupTable($db, $table);
568 } elseif (strlen($db)) {
569 PMA_relationsCleanupDatabase($db);
570 } else {
571 // VOID. No DB/Table gets deleted.
572 } // end if relation-stuff
573 } // end if ($purge)
575 // If a column gets dropped, do relation magic.
576 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
577 require_once './libraries/relation_cleanup.lib.php';
578 PMA_relationsCleanupColumn($db, $table, $dropped_column);
580 } // end if column was dropped
581 } // end else "didn't ask to see php code"
583 // No rows returned -> move back to the calling page
584 if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
585 if ($is_delete) {
586 $message = PMA_Message::deleted_rows($num_rows);
587 } elseif ($is_insert) {
588 if ($is_replace) {
589 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
590 $message = PMA_Message::affected_rows($num_rows);
591 } else {
592 $message = PMA_Message::inserted_rows($num_rows);
594 $insert_id = PMA_DBI_insert_id();
595 if ($insert_id != 0) {
596 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
597 $message->addMessage('[br]');
598 // need to use a temporary because the Message class
599 // currently supports adding parameters only to the first
600 // message
601 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
602 $_inserted->addParam($insert_id + $num_rows - 1);
603 $message->addMessage($_inserted);
605 } elseif ($is_affected) {
606 $message = PMA_Message::affected_rows($num_rows);
608 // Ok, here is an explanation for the !$is_select.
609 // The form generated by sql_query_form.lib.php
610 // and db_sql.php has many submit buttons
611 // on the same form, and some confusion arises from the
612 // fact that $message_to_show is sent for every case.
613 // The $message_to_show containing a success message and sent with
614 // the form should not have priority over errors
615 } elseif (!empty($message_to_show) && !$is_select) {
616 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
617 } elseif (!empty($GLOBALS['show_as_php'])) {
618 $message = PMA_Message::success(__('Showing as PHP code'));
619 } elseif (isset($GLOBALS['show_as_php'])) {
620 /* User disable showing as PHP, query is only displayed */
621 $message = PMA_Message::notice(__('Showing SQL query'));
622 } elseif (!empty($GLOBALS['validatequery'])) {
623 $message = PMA_Message::notice(__('Validated SQL'));
624 } else {
625 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
628 if (isset($GLOBALS['querytime'])) {
629 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
630 $_querytime->addParam($GLOBALS['querytime']);
631 $message->addMessage('(');
632 $message->addMessage($_querytime);
633 $message->addMessage(')');
636 if( $GLOBALS['is_ajax_request'] == true) {
639 * If we are in inline editing, we need to process the relational and
640 * transformed fields, if they were edited. After that, output the correct
641 * link/transformed value and exit
643 * Logic taken from libraries/display_tbl.lib.php
646 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
647 //handle relations work here for updated row.
648 require_once './libraries/relation.lib.php';
650 $map = PMA_getForeigners($db, $table, '', 'both');
652 $rel_fields = array();
653 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
655 foreach( $rel_fields as $rel_field => $rel_field_value) {
657 $where_comparison = "='" . $rel_field_value . "'";
658 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
660 // Field to display from the foreign table?
661 if (isset($display_field) && strlen($display_field)) {
662 $dispsql = 'SELECT ' . PMA_backquote($display_field)
663 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
664 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
665 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
666 . $where_comparison;
667 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
668 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
669 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
670 } else {
671 //$dispval = __('Link not found');
673 @PMA_DBI_free_result($dispresult);
674 } else {
675 $dispval = '';
676 } // end if... else...
678 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
679 // user chose "relational key" in the display options, so
680 // the title contains the display field
681 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
682 } else {
683 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
686 $_url_params = array(
687 'db' => $map[$rel_field]['foreign_db'],
688 'table' => $map[$rel_field]['foreign_table'],
689 'pos' => '0',
690 'sql_query' => 'SELECT * FROM '
691 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
692 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
693 . $where_comparison
695 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
697 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
698 // user chose "relational display field" in the
699 // display options, so show display field in the cell
700 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
701 } else {
702 // otherwise display data in the cell
703 $output .= htmlspecialchars($rel_field_value);
705 $output .= '</a>';
706 $extra_data['relations'][$rel_field] = $output;
710 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
711 require_once './libraries/transformations.lib.php';
712 //if some posted fields need to be transformed, generate them here.
713 $mime_map = PMA_getMIME($db, $table);
715 if ($mime_map === FALSE) {
716 $mime_map = array();
719 $edited_values = array();
720 parse_str($_REQUEST['transform_fields_list'], $edited_values);
722 foreach($mime_map as $transformation) {
723 $include_file = PMA_securePath($transformation['transformation']);
724 $column_name = $transformation['column_name'];
725 $column_data = $edited_values[$column_name];
727 $_url_params = array(
728 'db' => $db,
729 'table' => $table,
730 'where_clause' => $_REQUEST['where_clause'],
731 'transform_key' => $column_name,
734 if (file_exists('./libraries/transformations/' . $include_file)) {
735 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
737 require_once './libraries/transformations/' . $include_file;
739 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
740 $transform_function = 'PMA_transformation_' . $transformfunction_name;
741 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
742 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
746 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
750 if ($cfg['ShowSQL']) {
751 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
753 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
754 $extra_data['reload'] = 1;
755 $extra_data['db'] = $GLOBALS['db'];
757 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
760 if ($is_gotofile) {
761 $goto = PMA_securePath($goto);
762 // Checks for a valid target script
763 $is_db = $is_table = false;
764 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
765 $table = '';
766 unset($url_params['table']);
768 include 'libraries/db_table_exists.lib.php';
770 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
771 if (strlen($table)) {
772 $table = '';
774 $goto = 'db_sql.php';
776 if (strpos($goto, 'db_') === 0 && ! $is_db) {
777 if (strlen($db)) {
778 $db = '';
780 $goto = 'main.php';
782 // Loads to target script
783 if ($goto != 'main.php') {
784 require_once './libraries/header.inc.php';
786 $active_page = $goto;
787 require './' . $goto;
788 } else {
789 // avoid a redirect loop when last record was deleted
790 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
791 $goto = str_replace('sql.php','tbl_structure.php',$goto);
793 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
794 } // end else
795 exit();
796 } // end no rows returned
798 // At least one row is returned -> displays a table with results
799 else {
800 //If we are retrieving the full value of a truncated field or the original
801 // value of a transformed field, show it here and exit
802 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
803 $row = PMA_DBI_fetch_row($result);
804 $extra_data = array();
805 $extra_data['value'] = $row[0];
806 PMA_ajaxResponse(NULL, true, $extra_data);
809 // Displays the headers
810 if (isset($show_query)) {
811 unset($show_query);
813 if (isset($printview) && $printview == '1') {
814 require_once './libraries/header_printview.inc.php';
815 } else {
817 $GLOBALS['js_include'][] = 'functions.js';
818 $GLOBALS['js_include'][] = 'sql.js';
820 unset($message);
822 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
823 if (strlen($table)) {
824 require './libraries/tbl_common.php';
825 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
826 require './libraries/tbl_info.inc.php';
827 require './libraries/tbl_links.inc.php';
828 } elseif (strlen($db)) {
829 require './libraries/db_common.inc.php';
830 require './libraries/db_info.inc.php';
831 } else {
832 require './libraries/server_common.inc.php';
833 require './libraries/server_links.inc.php';
836 else {
837 require_once './libraries/header.inc.php';
838 //we don't need to buffer the output in PMA_showMessage here.
839 //set a global variable and check against it in the function
840 $GLOBALS['buffer_message'] = false;
844 if (strlen($db)) {
845 $cfgRelation = PMA_getRelationsParam();
848 // Gets the list of fields properties
849 if (isset($result) && $result) {
850 $fields_meta = PMA_DBI_get_fields_meta($result);
851 $fields_cnt = count($fields_meta);
854 if( ! $GLOBALS['is_ajax_request']) {
855 //begin the sqlqueryresults div here. container div
856 echo '<div id="sqlqueryresults"';
857 if ($GLOBALS['cfg']['AjaxEnable']) {
858 echo ' class="ajax"';
860 echo '>';
863 // Display previous update query (from tbl_replace)
864 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
865 PMA_showMessage($disp_message, $disp_query, 'success');
868 if (isset($profiling_results)) {
869 PMA_profilingResults($profiling_results, true);
872 // Displays the results in a table
873 if (empty($disp_mode)) {
874 // see the "PMA_setDisplayMode()" function in
875 // libraries/display_tbl.lib.php
876 $disp_mode = 'urdr111101';
879 // hide edit and delete links for information_schema
880 if ($db == 'information_schema') {
881 $disp_mode = 'nnnn110111';
884 if (isset($label)) {
885 $message = PMA_message::success(__('Bookmark %s created'));
886 $message->addParam($label);
887 $message->display();
890 PMA_displayTable($result, $disp_mode, $analyzed_sql);
891 PMA_DBI_free_result($result);
893 // BEGIN INDEX CHECK See if indexes should be checked.
894 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
895 foreach ($selected as $idx => $tbl_name) {
896 $check = PMA_Index::findDuplicates($tbl_name, $db);
897 if (! empty($check)) {
898 printf(__('Problems with indexes of table `%s`'), $tbl_name);
899 echo $check;
902 } // End INDEX CHECK
904 // Bookmark support if required
905 if ($disp_mode[7] == '1'
906 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
907 && !empty($sql_query)) {
908 echo "\n";
910 $goto = 'sql.php?'
911 . PMA_generate_common_url($db, $table)
912 . '&amp;sql_query=' . urlencode($sql_query)
913 . '&amp;id_bookmark=1';
916 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
917 <?php echo PMA_generate_common_hidden_inputs(); ?>
918 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
919 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
920 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
921 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
922 <fieldset>
923 <legend><?php
924 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
925 . __('Bookmark this SQL query');
927 </legend>
929 <div class="formelement">
930 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
931 <input type="text" id="fields_label_" name="fields[label]" value="" />
932 </div>
934 <div class="formelement">
935 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
936 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
937 </div>
939 <div class="clearfloat"></div>
940 </fieldset>
941 <fieldset class="tblFooters">
942 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
943 </fieldset>
944 </form>
945 <?php
946 } // end bookmark support
948 // Do print the page if required
949 if (isset($printview) && $printview == '1') {
951 <script type="text/javascript">
952 //<![CDATA[
953 // Do print the page
954 window.onload = function()
956 if (typeof(window.print) != 'undefined') {
957 window.print();
960 //]]>
961 </script>
962 <?php
963 } // end print case
965 if( $GLOBALS['is_ajax_request'] != true) {
966 echo '</div>'; // end sqlqueryresults div
968 } // end rows returned
971 * Displays the footer
973 if(!isset($_REQUEST['table_maintenance'])) {
974 require './libraries/footer.inc.php';