Added missing question mark in the URL
[phpmyadmin/crack.git] / sql.php
blob4fc59d21bfb0060e2b11ad8dc47c7c79d8b27a03
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'][] = 'tbl_change.js';
20 // required for GIS editor loaded via AJAX
21 $GLOBALS['js_include'][] = 'gis_data_editor.js';
22 $GLOBALS['js_include'][] = 'jquery/jquery.svg.js';
23 $GLOBALS['js_include'][] = 'jquery/jquery.mousewheel.js';
24 $GLOBALS['js_include'][] = 'jquery/jquery.event.drag-2.0.min.js';
25 $GLOBALS['js_include'][] = 'tbl_gis_visualization.js';
26 $GLOBALS['js_include'][] = 'openlayers/OpenLayers.js';
27 $GLOBALS['js_include'][] = 'OpenStreetMap.js';
29 if (isset($_SESSION['profiling'])) {
30 $GLOBALS['js_include'][] = 'highcharts/highcharts.js';
31 /* Files required for chart exporting */
32 $GLOBALS['js_include'][] = 'highcharts/exporting.js';
33 $GLOBALS['js_include'][] = 'canvg/canvg.js';
34 $GLOBALS['js_include'][] = 'canvg/rgbcolor.js';
37 /**
38 * Defines the url to return to in case of error in a sql statement
40 // Security checkings
41 if (! empty($goto)) {
42 $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
43 if (! @file_exists('./' . $is_gotofile)) {
44 unset($goto);
45 } else {
46 $is_gotofile = ($is_gotofile == $goto);
48 } else {
49 $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
50 $is_gotofile = true;
51 } // end if
53 if (! isset($err_url)) {
54 $err_url = (!empty($back) ? $back : $goto)
55 . '?' . PMA_generate_common_url($db)
56 . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&amp;table=' . urlencode($table) : '');
57 } // end if
59 // Coming from a bookmark dialog
60 if (isset($fields['query'])) {
61 $sql_query = $fields['query'];
64 // This one is just to fill $db
65 if (isset($fields['dbase'])) {
66 $db = $fields['dbase'];
69 /**
70 * During inline edit, if we have a relational field, show the dropdown for it
72 * Logic taken from libraries/display_tbl_lib.php
74 * This doesn't seem to be the right place to do this, but I can't think of any
75 * better place either.
77 if (isset($_REQUEST['get_relational_values']) && $_REQUEST['get_relational_values'] == true) {
78 require_once 'libraries/relation.lib.php';
80 $column = $_REQUEST['column'];
81 $foreigners = PMA_getForeigners($db, $table, $column);
83 $display_field = PMA_getDisplayField($foreigners[$column]['foreign_db'], $foreigners[$column]['foreign_table']);
85 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
87 if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
88 && (isset($display_field) && strlen($display_field)
89 && (isset($_REQUEST['relation_key_or_display_column']) && $_REQUEST['relation_key_or_display_column']))) {
90 $curr_value = $_REQUEST['relation_key_or_display_column'];
91 } else {
92 $curr_value = $_REQUEST['curr_value'];
94 if ($foreignData['disp_row'] == null) {
95 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
96 $_url_params = array(
97 'db' => $db,
98 'table' => $table,
99 'field' => $column
102 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
103 . ' target="_blank" class="browse_foreign" '
104 .'>' . __('Browse foreign values') . '</a>';
106 else {
107 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $curr_value, $cfg['ForeignKeyMaxLimit']);
108 $dropdown = '<select>' . $dropdown . '</select>';
111 $extra_data['dropdown'] = $dropdown;
112 PMA_ajaxResponse(NULL, true, $extra_data);
116 * Just like above, find possible values for enum fields during inline edit.
118 * Logic taken from libraries/display_tbl_lib.php
120 if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
121 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
123 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
125 $search = array('enum', '(', ')', "'");
127 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
129 $dropdown = '<option value="">&nbsp;</option>';
130 foreach ($values as $value) {
131 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
132 if ($value == $_REQUEST['curr_value']) {
133 $dropdown .= ' selected="selected"';
135 $dropdown .= '>' . $value . '</option>';
138 $dropdown = '<select>' . $dropdown . '</select>';
140 $extra_data['dropdown'] = $dropdown;
141 PMA_ajaxResponse(NULL, true, $extra_data);
145 * Find possible values for set fields during inline edit.
147 if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
148 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
150 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
152 $selected_values = explode(',', $_REQUEST['curr_value']);
154 $search = array('set', '(', ')', "'");
155 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
157 $select = '';
158 foreach ($values as $value) {
159 $select .= '<option value="' . htmlspecialchars($value) . '"';
160 if (in_array($value, $selected_values, true)) {
161 $select .= ' selected="selected"';
163 $select .= '>' . $value . '</option>';
166 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
167 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
169 $extra_data['select'] = $select;
170 PMA_ajaxResponse(NULL, true, $extra_data);
174 * Check ajax request to set the column order
176 if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
177 $pmatable = new PMA_Table($table, $db);
179 // set column order
180 $col_order = explode(',', $_REQUEST['col_order']);
181 $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_ORDER, $col_order, $_REQUEST['table_create_time']);
183 // set column visibility
184 $col_visib = explode(',', $_REQUEST['col_visib']);
185 $retval &= $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
187 PMA_ajaxResponse(NULL, ($retval == true));
190 // Default to browse if no query set and we have table
191 // (needed for browsing from DefaultTabTable)
192 if (empty($sql_query) && strlen($table) && strlen($db)) {
193 require_once './libraries/bookmark.lib.php';
194 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddSlashes($table) . '\'',
195 'label', false, true);
197 if (! empty($book_sql_query)) {
198 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
199 $GLOBALS['using_bookmark_message']->addParam($table);
200 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
201 $sql_query = $book_sql_query;
202 } else {
203 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
205 unset($book_sql_query);
207 // set $goto to what will be displayed if query returns 0 rows
208 $goto = 'tbl_structure.php';
209 } else {
210 // Now we can check the parameters
211 PMA_checkParameters(array('sql_query'));
214 // instead of doing the test twice
215 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
216 $sql_query);
219 * Check rights in case of DROP DATABASE
221 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
222 * but since a malicious user may pass this variable by url/form, we don't take
223 * into account this case.
225 if (!defined('PMA_CHK_DROP')
226 && !$cfg['AllowUserDropDatabase']
227 && $is_drop_database
228 && !$is_superuser) {
229 require_once './libraries/header.inc.php';
230 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
231 } // end if
233 require_once './libraries/display_tbl.lib.php';
234 PMA_displayTable_checkConfigParams();
237 * Need to find the real end of rows?
239 if (isset($find_real_end) && $find_real_end) {
240 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
241 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
246 * Bookmark add
248 if (isset($store_bkm)) {
249 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
250 // go back to sql.php to redisplay query; do not use &amp; in this case:
251 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
252 } // end if
255 * Parse and analyze the query
257 require_once './libraries/parse_analyze.lib.php';
260 * Sets or modifies the $goto variable if required
262 if ($goto == 'sql.php') {
263 $is_gotofile = false;
264 $goto = 'sql.php?'
265 . PMA_generate_common_url($db, $table)
266 . '&amp;sql_query=' . urlencode($sql_query);
267 } // end if
271 * Go back to further page if table should not be dropped
273 if (isset($btnDrop) && $btnDrop == __('No')) {
274 if (!empty($back)) {
275 $goto = $back;
277 if ($is_gotofile) {
278 if (strpos($goto, 'db_') === 0 && strlen($table)) {
279 $table = '';
281 $active_page = $goto;
282 require './' . PMA_securePath($goto);
283 } else {
284 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
286 exit();
287 } // end if
291 * Displays the confirm page if required
293 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
294 * with js) because possible security issue is not so important here: at most,
295 * the confirm message isn't displayed.
297 * Also bypassed if only showing php code.or validating a SQL query
299 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
300 // if we are coming from a "Create PHP code" or a "Without PHP Code"
301 // dialog, we won't execute the query anyway, so don't confirm
302 || isset($GLOBALS['show_as_php'])
303 || !empty($GLOBALS['validatequery'])) {
304 $do_confirm = false;
305 } else {
306 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
309 if ($do_confirm) {
310 $stripped_sql_query = $sql_query;
311 require_once './libraries/header.inc.php';
312 if ($is_drop_database) {
313 echo '<h1 class="error">' . __('You are about to DESTROY a complete database!') . '</h1>';
315 echo '<form action="sql.php" method="post">' . "\n"
316 .PMA_generate_common_hidden_inputs($db, $table);
318 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
319 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
320 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
321 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
322 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
323 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
324 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
325 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
326 <?php
327 echo '<fieldset class="confirmation">' . "\n"
328 .' <legend>' . __('Do you really want to ') . '</legend>'
329 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
330 .'</fieldset>' . "\n"
331 .'<fieldset class="tblFooters">' . "\n";
333 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
334 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
335 <?php
336 echo '</fieldset>' . "\n"
337 . '</form>' . "\n";
340 * Displays the footer and exit
342 require './libraries/footer.inc.php';
343 } // end if $do_confirm
346 // Defines some variables
347 // A table has to be created, renamed, dropped -> navi frame should be reloaded
349 * @todo use the parser/analyzer
352 if (empty($reload)
353 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
354 $reload = 1;
357 // SK -- Patch: $is_group added for use in calculation of total number of
358 // rows.
359 // $is_count is changed for more correct "LIMIT" clause
360 // appending in queries like
361 // "SELECT COUNT(...) FROM ... GROUP BY ..."
364 * @todo detect all this with the parser, to avoid problems finding
365 * those strings in comments or backquoted identifiers
368 $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;
369 if ($is_select) { // see line 141
370 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
371 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
372 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
373 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
374 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
375 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
376 $is_explain = true;
377 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
378 $is_delete = true;
379 $is_affected = true;
380 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
381 $is_insert = true;
382 $is_affected = true;
383 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
384 $is_replace = true;
386 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
387 $is_affected = true;
388 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
389 $is_show = true;
390 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
391 $is_maint = true;
394 // assign default full_sql_query
395 $full_sql_query = $sql_query;
397 // Handle remembered sorting order, only for single table query
398 if ($GLOBALS['cfg']['RememberSorting']
399 && ! ($is_count || $is_export || $is_func || $is_analyse)
400 && count($analyzed_sql[0]['select_expr']) == 0
401 && isset($analyzed_sql[0]['queryflags']['select_from'])
402 && count($analyzed_sql[0]['table_ref']) == 1
404 $pmatable = new PMA_Table($table, $db);
405 if (empty($analyzed_sql[0]['order_by_clause'])) {
406 $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
407 if ($sorted_col) {
408 // retrieve the remembered sorting order for current table
409 $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
410 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . $sql_order_to_append . $analyzed_sql[0]['section_after_limit'];
412 // update the $analyzed_sql
413 $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
414 $analyzed_sql[0]['order_by_clause'] = $sorted_col;
416 } else {
417 // store the remembered table into session
418 $pmatable->setUiProp(PMA_Table::PROP_SORTED_COLUMN, $analyzed_sql[0]['order_by_clause']);
422 // Do append a "LIMIT" clause?
423 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
424 && ! ($is_count || $is_export || $is_func || $is_analyse)
425 && isset($analyzed_sql[0]['queryflags']['select_from'])
426 && ! isset($analyzed_sql[0]['queryflags']['offset'])
427 && empty($analyzed_sql[0]['limit_clause'])
429 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
431 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
433 * @todo pretty printing of this modified query
435 if (isset($display_query)) {
436 // if the analysis of the original query revealed that we found
437 // a section_after_limit, we now have to analyze $display_query
438 // to display it correctly
440 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
441 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
442 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
448 if (strlen($db)) {
449 PMA_DBI_select_db($db);
452 // E x e c u t e t h e q u e r y
454 // Only if we didn't ask to see the php code (mikebeck)
455 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
456 unset($result);
457 $num_rows = 0;
458 } else {
459 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
460 PMA_DBI_query('SET PROFILING=1;');
463 // Measure query time.
464 $querytime_before = array_sum(explode(' ', microtime()));
466 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
468 // If a stored procedure was called, there may be more results that are
469 // queued up and waiting to be flushed from the buffer. So let's do that.
470 while (true) {
471 if (! PMA_DBI_more_results()) {
472 break;
474 PMA_DBI_next_result();
477 $querytime_after = array_sum(explode(' ', microtime()));
479 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
481 // Displays an error message if required and stop parsing the script
482 if ($error = PMA_DBI_getError()) {
483 if ($is_gotofile) {
484 if (strpos($goto, 'db_') === 0 && strlen($table)) {
485 $table = '';
487 $active_page = $goto;
488 $message = PMA_Message::rawError($error);
490 if ($GLOBALS['is_ajax_request'] == true) {
491 PMA_ajaxResponse($message, false);
495 * Go to target path.
497 require './' . PMA_securePath($goto);
498 } else {
499 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
500 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
501 : $err_url;
502 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
504 exit;
506 unset($error);
508 // Gets the number of rows affected/returned
509 // (This must be done immediately after the query because
510 // mysql_affected_rows() reports about the last query done)
512 if (!$is_affected) {
513 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
514 } elseif (! isset($num_rows)) {
515 $num_rows = @PMA_DBI_affected_rows();
518 // Grabs the profiling results
519 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
520 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
523 // Checks if the current database has changed
524 // This could happen if the user sends a query like "USE `database`;"
526 * commented out auto-switching to active database - really required?
527 * bug #1814718 win: table list disappears (mixed case db names)
528 * https://sourceforge.net/support/tracker.php?aid=1814718
529 * @todo RELEASE test and comit or rollback before release
530 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
531 if ($db !== $current_db) {
532 $db = $current_db;
533 $reload = 1;
535 unset($current_db);
538 // tmpfile remove after convert encoding appended by Y.Kawada
539 if (function_exists('PMA_kanji_file_conv')
540 && (isset($textfile) && file_exists($textfile))) {
541 unlink($textfile);
544 // Counts the total number of rows for the same 'SELECT' query without the
545 // 'LIMIT' clause that may have been programatically added
547 if (empty($sql_limit_to_append)) {
548 $unlim_num_rows = $num_rows;
549 // if we did not append a limit, set this to get a correct
550 // "Showing rows..." message
551 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
552 } elseif ($is_select) {
554 // c o u n t q u e r y
556 // If we are "just browsing", there is only one table,
557 // and no WHERE clause (or just 'WHERE 1 '),
558 // we do a quick count (which uses MaxExactCount) because
559 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
561 // However, do not count again if we did it previously
562 // due to $find_real_end == true
564 if (!$is_group
565 && ! isset($analyzed_sql[0]['queryflags']['union'])
566 && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
567 && (empty($analyzed_sql[0]['where_clause'])
568 || $analyzed_sql[0]['where_clause'] == '1 ')
569 && ! isset($find_real_end)
572 // "j u s t b r o w s i n g"
573 $unlim_num_rows = PMA_Table::countRecords($db, $table);
575 } else { // n o t " j u s t b r o w s i n g "
577 // add select expression after the SQL_CALC_FOUND_ROWS
579 // for UNION, just adding SQL_CALC_FOUND_ROWS
580 // after the first SELECT works.
582 // take the left part, could be:
583 // SELECT
584 // (SELECT
585 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
586 $count_query .= ' SQL_CALC_FOUND_ROWS ';
587 // add everything that was after the first SELECT
588 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
589 // ensure there is no semicolon at the end of the
590 // count query because we'll probably add
591 // a LIMIT 1 clause after it
592 $count_query = rtrim($count_query);
593 $count_query = rtrim($count_query, ';');
595 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
596 // long delays. Returned count will be complete anyway.
597 // (but a LIMIT would disrupt results in an UNION)
599 if (! isset($analyzed_sql[0]['queryflags']['union'])) {
600 $count_query .= ' LIMIT 1';
603 // run the count query
605 PMA_DBI_try_query($count_query);
606 // if (mysql_error()) {
607 // void.
608 // I tried the case
609 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
610 // UNION (SELECT `User`, `Host`, "%" AS "Db",
611 // `Select_priv`
612 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
613 // and although the generated count_query is wrong
614 // the SELECT FOUND_ROWS() work! (maybe it gets the
615 // count from the latest query that worked)
617 // another case where the count_query is wrong:
618 // SELECT COUNT(*), f1 from t1 group by f1
619 // and you click to sort on count(*)
620 // }
621 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
622 } // end else "just browsing"
624 } else { // not $is_select
625 $unlim_num_rows = 0;
626 } // end rows total count
628 // if a table or database gets dropped, check column comments.
629 if (isset($purge) && $purge == '1') {
631 * Cleanup relations.
633 require_once './libraries/relation_cleanup.lib.php';
635 if (strlen($table) && strlen($db)) {
636 PMA_relationsCleanupTable($db, $table);
637 } elseif (strlen($db)) {
638 PMA_relationsCleanupDatabase($db);
639 } else {
640 // VOID. No DB/Table gets deleted.
641 } // end if relation-stuff
642 } // end if ($purge)
644 // If a column gets dropped, do relation magic.
645 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
646 require_once './libraries/relation_cleanup.lib.php';
647 PMA_relationsCleanupColumn($db, $table, $dropped_column);
649 } // end if column was dropped
650 } // end else "didn't ask to see php code"
652 // No rows returned -> move back to the calling page
653 if (0 == $num_rows || $is_affected) {
654 if ($is_delete) {
655 $message = PMA_Message::deleted_rows($num_rows);
656 } elseif ($is_insert) {
657 if ($is_replace) {
658 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
659 $message = PMA_Message::affected_rows($num_rows);
660 } else {
661 $message = PMA_Message::inserted_rows($num_rows);
663 $insert_id = PMA_DBI_insert_id();
664 if ($insert_id != 0) {
665 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
666 $message->addMessage('[br]');
667 // need to use a temporary because the Message class
668 // currently supports adding parameters only to the first
669 // message
670 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
671 $_inserted->addParam($insert_id + $num_rows - 1);
672 $message->addMessage($_inserted);
674 } elseif ($is_affected) {
675 $message = PMA_Message::affected_rows($num_rows);
677 // Ok, here is an explanation for the !$is_select.
678 // The form generated by sql_query_form.lib.php
679 // and db_sql.php has many submit buttons
680 // on the same form, and some confusion arises from the
681 // fact that $message_to_show is sent for every case.
682 // The $message_to_show containing a success message and sent with
683 // the form should not have priority over errors
684 } elseif (!empty($message_to_show) && !$is_select) {
685 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
686 } elseif (!empty($GLOBALS['show_as_php'])) {
687 $message = PMA_Message::success(__('Showing as PHP code'));
688 } elseif (isset($GLOBALS['show_as_php'])) {
689 /* User disable showing as PHP, query is only displayed */
690 $message = PMA_Message::notice(__('Showing SQL query'));
691 } elseif (!empty($GLOBALS['validatequery'])) {
692 $message = PMA_Message::notice(__('Validated SQL'));
693 } else {
694 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
697 if (isset($GLOBALS['querytime'])) {
698 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
699 $_querytime->addParam($GLOBALS['querytime']);
700 $message->addMessage('(');
701 $message->addMessage($_querytime);
702 $message->addMessage(')');
705 if ($GLOBALS['is_ajax_request'] == true) {
708 * If we are in inline editing, we need to process the relational and
709 * transformed fields, if they were edited. After that, output the correct
710 * link/transformed value and exit
712 * Logic taken from libraries/display_tbl.lib.php
715 if (isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
716 //handle relations work here for updated row.
717 require_once './libraries/relation.lib.php';
719 $map = PMA_getForeigners($db, $table, '', 'both');
721 $rel_fields = array();
722 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
724 foreach ( $rel_fields as $rel_field => $rel_field_value) {
726 $where_comparison = "='" . $rel_field_value . "'";
727 $display_field = PMA_getDisplayField($map[$rel_field]['foreign_db'], $map[$rel_field]['foreign_table']);
729 // Field to display from the foreign table?
730 if (isset($display_field) && strlen($display_field)) {
731 $dispsql = 'SELECT ' . PMA_backquote($display_field)
732 . ' FROM ' . PMA_backquote($map[$rel_field]['foreign_db'])
733 . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
734 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
735 . $where_comparison;
736 $dispresult = PMA_DBI_try_query($dispsql, null, PMA_DBI_QUERY_STORE);
737 if ($dispresult && PMA_DBI_num_rows($dispresult) > 0) {
738 list($dispval) = PMA_DBI_fetch_row($dispresult, 0);
739 } else {
740 //$dispval = __('Link not found');
742 @PMA_DBI_free_result($dispresult);
743 } else {
744 $dispval = '';
745 } // end if... else...
747 if ('K' == $_SESSION['tmp_user_values']['relational_display']) {
748 // user chose "relational key" in the display options, so
749 // the title contains the display field
750 $title = (! empty($dispval))? ' title="' . htmlspecialchars($dispval) . '"' : '';
751 } else {
752 $title = ' title="' . htmlspecialchars($rel_field_value) . '"';
755 $_url_params = array(
756 'db' => $map[$rel_field]['foreign_db'],
757 'table' => $map[$rel_field]['foreign_table'],
758 'pos' => '0',
759 'sql_query' => 'SELECT * FROM '
760 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
761 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
762 . $where_comparison
764 $output = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '"' . $title . '>';
766 if ('D' == $_SESSION['tmp_user_values']['relational_display']) {
767 // user chose "relational display field" in the
768 // display options, so show display field in the cell
769 $output .= (!empty($dispval)) ? htmlspecialchars($dispval) : '';
770 } else {
771 // otherwise display data in the cell
772 $output .= htmlspecialchars($rel_field_value);
774 $output .= '</a>';
775 $extra_data['relations'][$rel_field] = $output;
779 if (isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
780 require_once './libraries/transformations.lib.php';
781 //if some posted fields need to be transformed, generate them here.
782 $mime_map = PMA_getMIME($db, $table);
784 if ($mime_map === false) {
785 $mime_map = array();
788 $edited_values = array();
789 parse_str($_REQUEST['transform_fields_list'], $edited_values);
791 foreach($mime_map as $transformation) {
792 $include_file = PMA_securePath($transformation['transformation']);
793 $column_name = $transformation['column_name'];
794 $column_data = $edited_values[$column_name];
796 $_url_params = array(
797 'db' => $db,
798 'table' => $table,
799 'where_clause' => $_REQUEST['where_clause'],
800 'transform_key' => $column_name,
803 if (file_exists('./libraries/transformations/' . $include_file)) {
804 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
806 require_once './libraries/transformations/' . $include_file;
808 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
809 $transform_function = 'PMA_transformation_' . $transformfunction_name;
810 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
811 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
815 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
819 if ($cfg['ShowSQL']) {
820 $extra_data['sql_query'] = PMA_showMessage($message, $GLOBALS['sql_query'], 'success');
822 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
823 $extra_data['reload'] = 1;
824 $extra_data['db'] = $GLOBALS['db'];
826 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
829 if ($is_gotofile) {
830 $goto = PMA_securePath($goto);
831 // Checks for a valid target script
832 $is_db = $is_table = false;
833 if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
834 $table = '';
835 unset($url_params['table']);
837 include 'libraries/db_table_exists.lib.php';
839 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
840 if (strlen($table)) {
841 $table = '';
843 $goto = 'db_sql.php';
845 if (strpos($goto, 'db_') === 0 && ! $is_db) {
846 if (strlen($db)) {
847 $db = '';
849 $goto = 'main.php';
851 // Loads to target script
852 if ($goto != 'main.php') {
853 require_once './libraries/header.inc.php';
855 $active_page = $goto;
856 require './' . $goto;
857 } else {
858 // avoid a redirect loop when last record was deleted
859 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
860 $goto = str_replace('sql.php','tbl_structure.php',$goto);
862 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
863 } // end else
864 exit();
865 } // end no rows returned
867 // At least one row is returned -> displays a table with results
868 else {
869 //If we are retrieving the full value of a truncated field or the original
870 // value of a transformed field, show it here and exit
871 if ($GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
872 $row = PMA_DBI_fetch_row($result);
873 $extra_data = array();
874 $extra_data['value'] = $row[0];
875 PMA_ajaxResponse(NULL, true, $extra_data);
878 // Displays the headers
879 if (isset($show_query)) {
880 unset($show_query);
882 if (isset($printview) && $printview == '1') {
883 require_once './libraries/header_printview.inc.php';
884 } else {
886 $GLOBALS['js_include'][] = 'functions.js';
887 $GLOBALS['js_include'][] = 'makegrid.js';
888 $GLOBALS['js_include'][] = 'sql.js';
890 unset($message);
892 if (! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
893 if (strlen($table)) {
894 require './libraries/tbl_common.php';
895 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
896 require './libraries/tbl_info.inc.php';
897 require './libraries/tbl_links.inc.php';
898 } elseif (strlen($db)) {
899 require './libraries/db_common.inc.php';
900 require './libraries/db_info.inc.php';
901 } else {
902 require './libraries/server_common.inc.php';
903 require './libraries/server_links.inc.php';
906 else {
907 require_once './libraries/header.inc.php';
908 //we don't need to buffer the output in PMA_showMessage here.
909 //set a global variable and check against it in the function
910 $GLOBALS['buffer_message'] = false;
914 if (strlen($db)) {
915 $cfgRelation = PMA_getRelationsParam();
918 // Gets the list of fields properties
919 if (isset($result) && $result) {
920 $fields_meta = PMA_DBI_get_fields_meta($result);
921 $fields_cnt = count($fields_meta);
924 if (! $GLOBALS['is_ajax_request']) {
925 //begin the sqlqueryresults div here. container div
926 echo '<div id="sqlqueryresults"';
927 if ($GLOBALS['cfg']['AjaxEnable']) {
928 echo ' class="ajax"';
930 echo '>';
933 // Display previous update query (from tbl_replace)
934 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
935 PMA_showMessage($disp_message, $disp_query, 'success');
938 if (isset($profiling_results)) {
939 // pma_token/url_query needed for chart export
941 <script type="text/javascript">
942 pma_token = '<?php echo $_SESSION[' PMA_token ']; ?>';
943 url_query = '<?php echo isset($url_query)?$url_query:PMA_generate_common_url($db);?>';
944 $(document).ready(makeProfilingChart);
945 </script>
946 <?php
947 echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
948 echo '<div style="float: left;">';
949 echo '<table>' . "\n";
950 echo ' <tr>' . "\n";
951 echo ' <th>' . __('Status') . PMA_showMySQLDocu('general-thread-states','general-thread-states') . '</th>' . "\n";
952 echo ' <th>' . __('Time') . '</th>' . "\n";
953 echo ' </tr>' . "\n";
955 $chart_json = Array();
956 foreach ($profiling_results as $one_result) {
957 echo ' <tr>' . "\n";
958 echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
959 echo '<td align="right">' . (PMA_formatNumber($one_result['Duration'],3,1)) . 's</td>' . "\n";
960 $chart_json[ucwords($one_result['Status'])] = $one_result['Duration'];
963 echo '</table>' . "\n";
964 echo '</div>';
965 //require_once './libraries/chart.lib.php';
966 echo '<div id="profilingchart" style="display:none;">';
967 //PMA_chart_profiling($profiling_results);
968 echo json_encode($chart_json);
969 echo '</div>';
970 echo '</fieldset>' . "\n";
973 // Displays the results in a table
974 if (empty($disp_mode)) {
975 // see the "PMA_setDisplayMode()" function in
976 // libraries/display_tbl.lib.php
977 $disp_mode = 'urdr111101';
980 // hide edit and delete links for information_schema
981 if ($db == 'information_schema') {
982 $disp_mode = 'nnnn110111';
985 if (isset($label)) {
986 $message = PMA_message::success(__('Bookmark %s created'));
987 $message->addParam($label);
988 $message->display();
991 PMA_displayTable($result, $disp_mode, $analyzed_sql);
992 PMA_DBI_free_result($result);
994 // BEGIN INDEX CHECK See if indexes should be checked.
995 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
996 foreach ($selected as $idx => $tbl_name) {
997 $check = PMA_Index::findDuplicates($tbl_name, $db);
998 if (! empty($check)) {
999 printf(__('Problems with indexes of table `%s`'), $tbl_name);
1000 echo $check;
1003 } // End INDEX CHECK
1005 // Bookmark support if required
1006 if ($disp_mode[7] == '1'
1007 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
1008 && !empty($sql_query)) {
1009 echo "\n";
1011 $goto = 'sql.php?'
1012 . PMA_generate_common_url($db, $table)
1013 . '&amp;sql_query=' . urlencode($sql_query)
1014 . '&amp;id_bookmark=1';
1017 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
1018 <?php echo PMA_generate_common_hidden_inputs(); ?>
1019 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
1020 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
1021 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
1022 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
1023 <fieldset>
1024 <legend><?php
1025 echo PMA_getIcon('b_bookmark.png', __('Bookmark this SQL query'));
1027 </legend>
1029 <div class="formelement">
1030 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
1031 <input type="text" id="fields_label_" name="fields[label]" value="" />
1032 </div>
1034 <div class="formelement">
1035 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
1036 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
1037 </div>
1039 <div class="clearfloat"></div>
1040 </fieldset>
1041 <fieldset class="tblFooters">
1042 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
1043 </fieldset>
1044 </form>
1045 <?php
1046 } // end bookmark support
1048 // Do print the page if required
1049 if (isset($printview) && $printview == '1') {
1051 <script type="text/javascript">
1052 //<![CDATA[
1053 // Do print the page
1054 window.onload = function()
1056 if (typeof(window.print) != 'undefined') {
1057 window.print();
1060 //]]>
1061 </script>
1062 <?php
1063 } // end print case
1065 if ($GLOBALS['is_ajax_request'] != true) {
1066 echo '</div>'; // end sqlqueryresults div
1068 } // end rows returned
1071 * Displays the footer
1073 if (! isset($_REQUEST['table_maintenance'])) {
1074 require './libraries/footer.inc.php';