Merge branch 'master' of ssh://phpmyadmin.git.sourceforge.net/gitroot/phpmyadmin...
[phpmyadmin/srajbr.git] / sql.php
blob41f1ec6a8f212fd8664ad4138b3332c531690333
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 $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
68 if ($foreignData['disp_row'] == null) {
69 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
70 $_url_params = array(
71 'db' => $db,
72 'table' => $table,
73 'field' => $column
76 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
77 . ' target="_blank" class="browse_foreign" '
78 .'>' . __('Browse foreign values') . '</a>';
80 else {
81 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $_REQUEST['curr_value'], $cfg['ForeignKeyMaxLimit']);
82 $dropdown = '<select>' . $dropdown . '</select>';
85 $extra_data['dropdown'] = $dropdown;
86 PMA_ajaxResponse(NULL, true, $extra_data);
89 /**
90 * Just like above, find possible values for enum fields during inline edit.
92 * Logic taken from libraries/display_tbl_lib.php
94 if(isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
95 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
97 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
99 $search = array('enum', '(', ')', "'");
101 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
103 $dropdown = '<option value="">&nbsp;</option>';
104 foreach($values as $value) {
105 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
106 if($value == $_REQUEST['curr_value']) {
107 $dropdown .= ' selected="selected"';
109 $dropdown .= '>' . $value . '</option>';
112 $dropdown = '<select>' . $dropdown . '</select>';
114 $extra_data['dropdown'] = $dropdown;
115 PMA_ajaxResponse(NULL, true, $extra_data);
119 * Find possible values for set fields during inline edit.
121 if(isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
122 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
124 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
126 $selected_values = explode(',', $_REQUEST['curr_value']);
128 $search = array('set', '(', ')', "'");
129 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
131 $select = '';
132 foreach($values as $value) {
133 $select .= '<option value="' . htmlspecialchars($value) . '"';
134 if(in_array($value, $selected_values, true)) {
135 $select .= ' selected="selected"';
137 $select .= '>' . $value . '</option>';
140 $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
141 $select = '<select multiple="multiple" size="' . $select_size . '">' . $select . '</select>';
143 $extra_data['select'] = $select;
144 PMA_ajaxResponse(NULL, true, $extra_data);
146 // Default to browse if no query set and we have table
147 // (needed for browsing from DefaultTabTable)
148 if (empty($sql_query) && strlen($table) && strlen($db)) {
149 require_once './libraries/bookmark.lib.php';
150 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
151 'label', FALSE, TRUE);
153 if (! empty($book_sql_query)) {
154 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
155 $GLOBALS['using_bookmark_message']->addParam($table);
156 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
157 $sql_query = $book_sql_query;
158 } else {
159 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
161 unset($book_sql_query);
163 // set $goto to what will be displayed if query returns 0 rows
164 $goto = 'tbl_structure.php';
165 } else {
166 // Now we can check the parameters
167 PMA_checkParameters(array('sql_query'));
170 // instead of doing the test twice
171 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
172 $sql_query);
175 * Check rights in case of DROP DATABASE
177 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
178 * but since a malicious user may pass this variable by url/form, we don't take
179 * into account this case.
181 if (!defined('PMA_CHK_DROP')
182 && !$cfg['AllowUserDropDatabase']
183 && $is_drop_database
184 && !$is_superuser) {
185 require_once './libraries/header.inc.php';
186 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
187 } // end if
189 require_once './libraries/display_tbl.lib.php';
190 PMA_displayTable_checkConfigParams();
193 * Need to find the real end of rows?
195 if (isset($find_real_end) && $find_real_end) {
196 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
197 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
202 * Bookmark add
204 if (isset($store_bkm)) {
205 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
206 // go back to sql.php to redisplay query; do not use &amp; in this case:
207 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
208 } // end if
211 * Parse and analyze the query
213 require_once './libraries/parse_analyze.lib.php';
216 * Sets or modifies the $goto variable if required
218 if ($goto == 'sql.php') {
219 $is_gotofile = false;
220 $goto = 'sql.php?'
221 . PMA_generate_common_url($db, $table)
222 . '&amp;sql_query=' . urlencode($sql_query);
223 } // end if
227 * Go back to further page if table should not be dropped
229 if (isset($btnDrop) && $btnDrop == __('No')) {
230 if (!empty($back)) {
231 $goto = $back;
233 if ($is_gotofile) {
234 if (strpos($goto, 'db_') === 0 && strlen($table)) {
235 $table = '';
237 $active_page = $goto;
238 require './' . PMA_securePath($goto);
239 } else {
240 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
242 exit();
243 } // end if
247 * Displays the confirm page if required
249 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
250 * with js) because possible security issue is not so important here: at most,
251 * the confirm message isn't displayed.
253 * Also bypassed if only showing php code.or validating a SQL query
255 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
256 // if we are coming from a "Create PHP code" or a "Without PHP Code"
257 // dialog, we won't execute the query anyway, so don't confirm
258 || isset($GLOBALS['show_as_php'])
259 || !empty($GLOBALS['validatequery'])) {
260 $do_confirm = false;
261 } else {
262 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
265 if ($do_confirm) {
266 $stripped_sql_query = $sql_query;
267 require_once './libraries/header.inc.php';
268 if ($is_drop_database) {
269 echo '<h1 class="warning">' . __('You are about to DESTROY a complete database!') . '</h1>';
271 echo '<form action="sql.php" method="post">' . "\n"
272 .PMA_generate_common_hidden_inputs($db, $table);
274 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
275 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
276 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
277 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
278 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
279 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
280 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
281 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
282 <?php
283 echo '<fieldset class="confirmation">' . "\n"
284 .' <legend>' . __('Do you really want to ') . '</legend>'
285 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
286 .'</fieldset>' . "\n"
287 .'<fieldset class="tblFooters">' . "\n";
289 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
290 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
291 <?php
292 echo '</fieldset>' . "\n"
293 . '</form>' . "\n";
296 * Displays the footer and exit
298 require './libraries/footer.inc.php';
299 } // end if $do_confirm
302 // Defines some variables
303 // A table has to be created, renamed, dropped -> navi frame should be reloaded
305 * @todo use the parser/analyzer
308 if (empty($reload)
309 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
310 $reload = 1;
313 // SK -- Patch: $is_group added for use in calculation of total number of
314 // rows.
315 // $is_count is changed for more correct "LIMIT" clause
316 // appending in queries like
317 // "SELECT COUNT(...) FROM ... GROUP BY ..."
320 * @todo detect all this with the parser, to avoid problems finding
321 * those strings in comments or backquoted identifiers
324 $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;
325 if ($is_select) { // see line 141
326 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
327 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
328 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
329 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
330 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
331 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
332 $is_explain = true;
333 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
334 $is_delete = true;
335 $is_affected = true;
336 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
337 $is_insert = true;
338 $is_affected = true;
339 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
340 $is_replace = true;
342 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
343 $is_affected = true;
344 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
345 $is_show = true;
346 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
347 $is_maint = true;
350 // Do append a "LIMIT" clause?
351 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
352 && ! ($is_count || $is_export || $is_func || $is_analyse)
353 && isset($analyzed_sql[0]['queryflags']['select_from'])
354 && ! isset($analyzed_sql[0]['queryflags']['offset'])
355 && empty($analyzed_sql[0]['limit_clause'])
357 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
359 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
361 * @todo pretty printing of this modified query
363 if (isset($display_query)) {
364 // if the analysis of the original query revealed that we found
365 // a section_after_limit, we now have to analyze $display_query
366 // to display it correctly
368 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
369 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
370 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
374 } else {
375 $full_sql_query = $sql_query;
376 } // end if...else
378 if (strlen($db)) {
379 PMA_DBI_select_db($db);
382 // E x e c u t e t h e q u e r y
384 // Only if we didn't ask to see the php code (mikebeck)
385 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
386 unset($result);
387 $num_rows = 0;
388 } else {
389 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
390 PMA_DBI_query('SET PROFILING=1;');
393 // Measure query time.
394 $querytime_before = array_sum(explode(' ', microtime()));
396 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
398 $querytime_after = array_sum(explode(' ', microtime()));
400 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
402 // Displays an error message if required and stop parsing the script
403 if ($error = PMA_DBI_getError()) {
404 if ($is_gotofile) {
405 if (strpos($goto, 'db_') === 0 && strlen($table)) {
406 $table = '';
408 $active_page = $goto;
409 $message = PMA_Message::rawError($error);
411 if( $GLOBALS['is_ajax_request'] == true) {
412 PMA_ajaxResponse($message, false);
416 * Go to target path.
418 require './' . PMA_securePath($goto);
419 } else {
420 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
421 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
422 : $err_url;
423 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
425 exit;
427 unset($error);
429 // Gets the number of rows affected/returned
430 // (This must be done immediately after the query because
431 // mysql_affected_rows() reports about the last query done)
433 if (!$is_affected) {
434 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
435 } elseif (!isset($num_rows)) {
436 $num_rows = @PMA_DBI_affected_rows();
439 // Grabs the profiling results
440 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
441 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
444 // Checks if the current database has changed
445 // This could happen if the user sends a query like "USE `database`;"
447 * commented out auto-switching to active database - really required?
448 * bug #1814718 win: table list disappears (mixed case db names)
449 * https://sourceforge.net/support/tracker.php?aid=1814718
450 * @todo RELEASE test and comit or rollback before release
451 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
452 if ($db !== $current_db) {
453 $db = $current_db;
454 $reload = 1;
456 unset($current_db);
459 // tmpfile remove after convert encoding appended by Y.Kawada
460 if (function_exists('PMA_kanji_file_conv')
461 && (isset($textfile) && file_exists($textfile))) {
462 unlink($textfile);
465 // Counts the total number of rows for the same 'SELECT' query without the
466 // 'LIMIT' clause that may have been programatically added
468 if (empty($sql_limit_to_append)) {
469 $unlim_num_rows = $num_rows;
470 // if we did not append a limit, set this to get a correct
471 // "Showing rows..." message
472 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
473 } elseif ($is_select) {
475 // c o u n t q u e r y
477 // If we are "just browsing", there is only one table,
478 // and no WHERE clause (or just 'WHERE 1 '),
479 // we do a quick count (which uses MaxExactCount) because
480 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
482 // However, do not count again if we did it previously
483 // due to $find_real_end == true
485 if (!$is_group
486 && !isset($analyzed_sql[0]['queryflags']['union'])
487 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
488 && (empty($analyzed_sql[0]['where_clause'])
489 || $analyzed_sql[0]['where_clause'] == '1 ')
490 && !isset($find_real_end)
493 // "j u s t b r o w s i n g"
494 $unlim_num_rows = PMA_Table::countRecords($db, $table);
496 } else { // n o t " j u s t b r o w s i n g "
498 // add select expression after the SQL_CALC_FOUND_ROWS
500 // for UNION, just adding SQL_CALC_FOUND_ROWS
501 // after the first SELECT works.
503 // take the left part, could be:
504 // SELECT
505 // (SELECT
506 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
507 $count_query .= ' SQL_CALC_FOUND_ROWS ';
508 // add everything that was after the first SELECT
509 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
510 // ensure there is no semicolon at the end of the
511 // count query because we'll probably add
512 // a LIMIT 1 clause after it
513 $count_query = rtrim($count_query);
514 $count_query = rtrim($count_query, ';');
516 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
517 // long delays. Returned count will be complete anyway.
518 // (but a LIMIT would disrupt results in an UNION)
520 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
521 $count_query .= ' LIMIT 1';
524 // run the count query
526 PMA_DBI_try_query($count_query);
527 // if (mysql_error()) {
528 // void.
529 // I tried the case
530 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
531 // UNION (SELECT `User`, `Host`, "%" AS "Db",
532 // `Select_priv`
533 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
534 // and although the generated count_query is wrong
535 // the SELECT FOUND_ROWS() work! (maybe it gets the
536 // count from the latest query that worked)
538 // another case where the count_query is wrong:
539 // SELECT COUNT(*), f1 from t1 group by f1
540 // and you click to sort on count(*)
541 // }
542 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
543 } // end else "just browsing"
545 } else { // not $is_select
546 $unlim_num_rows = 0;
547 } // end rows total count
549 // if a table or database gets dropped, check column comments.
550 if (isset($purge) && $purge == '1') {
552 * Cleanup relations.
554 require_once './libraries/relation_cleanup.lib.php';
556 if (strlen($table) && strlen($db)) {
557 PMA_relationsCleanupTable($db, $table);
558 } elseif (strlen($db)) {
559 PMA_relationsCleanupDatabase($db);
560 } else {
561 // VOID. No DB/Table gets deleted.
562 } // end if relation-stuff
563 } // end if ($purge)
565 // If a column gets dropped, do relation magic.
566 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
567 require_once './libraries/relation_cleanup.lib.php';
568 PMA_relationsCleanupColumn($db, $table, $dropped_column);
570 } // end if column was dropped
571 } // end else "didn't ask to see php code"
573 // No rows returned -> move back to the calling page
574 if (0 == $num_rows || $is_affected) {
575 if ($is_delete) {
576 $message = PMA_Message::deleted_rows($num_rows);
577 } elseif ($is_insert) {
578 if ($is_replace) {
579 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
580 $message = PMA_Message::affected_rows($num_rows);
581 } else {
582 $message = PMA_Message::inserted_rows($num_rows);
584 $insert_id = PMA_DBI_insert_id();
585 if ($insert_id != 0) {
586 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
587 $message->addMessage('[br]');
588 // need to use a temporary because the Message class
589 // currently supports adding parameters only to the first
590 // message
591 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
592 $_inserted->addParam($insert_id + $num_rows - 1);
593 $message->addMessage($_inserted);
595 } elseif ($is_affected) {
596 $message = PMA_Message::affected_rows($num_rows);
598 // Ok, here is an explanation for the !$is_select.
599 // The form generated by sql_query_form.lib.php
600 // and db_sql.php has many submit buttons
601 // on the same form, and some confusion arises from the
602 // fact that $message_to_show is sent for every case.
603 // The $message_to_show containing a success message and sent with
604 // the form should not have priority over errors
605 } elseif (!empty($message_to_show) && !$is_select) {
606 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
607 } elseif (!empty($GLOBALS['show_as_php'])) {
608 $message = PMA_Message::success(__('Showing as PHP code'));
609 } elseif (isset($GLOBALS['show_as_php'])) {
610 /* User disable showing as PHP, query is only displayed */
611 $message = PMA_Message::notice(__('Showing SQL query'));
612 } elseif (!empty($GLOBALS['validatequery'])) {
613 $message = PMA_Message::notice(__('Validated SQL'));
614 } else {
615 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
618 if (isset($GLOBALS['querytime'])) {
619 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
620 $_querytime->addParam($GLOBALS['querytime']);
621 $message->addMessage('(');
622 $message->addMessage($_querytime);
623 $message->addMessage(')');
626 if( $GLOBALS['is_ajax_request'] == true) {
629 * If we are in inline editing, we need to process the relational and
630 * transformed fields, if they were edited. After that, output the correct
631 * link/transformed value and exit
633 * Logic taken from libraries/display_tbl.lib.php
636 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
637 //handle relations work here for updated row.
638 require_once './libraries/relation.lib.php';
640 $map = PMA_getForeigners($db, $table, '', 'both');
642 $rel_fields = array();
643 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
645 foreach( $rel_fields as $rel_field => $rel_field_value) {
647 $where_comparison = "='" . $rel_field_value . "'";
648 $_url_params = array(
649 'db' => $map[$rel_field]['foreign_db'],
650 'table' => $map[$rel_field]['foreign_table'],
651 'pos' => '0',
652 'sql_query' => 'SELECT * FROM '
653 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
654 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
655 . $where_comparison
658 $extra_data['relations'][$rel_field] = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '">';
659 $extra_data['relations'][$rel_field] .= '</a>';
663 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
664 require_once './libraries/transformations.lib.php';
665 //if some posted fields need to be transformed, generate them here.
666 $mime_map = PMA_getMIME($db, $table);
668 if ($mime_map === FALSE) {
669 $mime_map = array();
672 $edited_values = array();
673 parse_str($_REQUEST['transform_fields_list'], $edited_values);
675 foreach($mime_map as $transformation) {
676 $include_file = $transformation['transformation'];
677 $column_name = $transformation['column_name'];
678 $column_data = $edited_values[$column_name];
680 $_url_params = array(
681 'db' => $db,
682 'table' => $table,
683 'where_clause' => $_REQUEST['where_clause'],
684 'transform_key' => $column_name,
687 if (file_exists('./libraries/transformations/' . $include_file)) {
688 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
690 require_once './libraries/transformations/' . $include_file;
692 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
693 $transform_function = 'PMA_transformation_' . $transformfunction_name;
694 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
695 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
699 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
703 if(isset($GLOBALS['display_query'])) {
704 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
706 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
707 $extra_data['reload'] = 1;
708 $extra_data['db'] = $GLOBALS['db'];
710 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
713 if ($is_gotofile) {
714 $goto = PMA_securePath($goto);
715 // Checks for a valid target script
716 $is_db = $is_table = false;
717 if (isset($_REQUEST['purge'])) {
718 $table = '';
719 unset($url_params['table']);
721 include 'libraries/db_table_exists.lib.php';
723 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
724 if (strlen($table)) {
725 $table = '';
727 $goto = 'db_sql.php';
729 if (strpos($goto, 'db_') === 0 && ! $is_db) {
730 if (strlen($db)) {
731 $db = '';
733 $goto = 'main.php';
735 // Loads to target script
736 if ($goto != 'main.php') {
737 require_once './libraries/header.inc.php';
739 $active_page = $goto;
740 require './' . $goto;
741 } else {
742 // avoid a redirect loop when last record was deleted
743 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
744 $goto = str_replace('sql.php','tbl_structure.php',$goto);
746 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
747 } // end else
748 exit();
749 } // end no rows returned
751 // At least one row is returned -> displays a table with results
752 else {
753 //If we are retrieving the full value of a truncated field or the original
754 // value of a transformed field, show it here and exit
755 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
756 $row = PMA_DBI_fetch_row($result);
757 $extra_data = array();
758 $extra_data['value'] = $row[0];
759 PMA_ajaxResponse(NULL, true, $extra_data);
762 // Displays the headers
763 if (isset($show_query)) {
764 unset($show_query);
766 if (isset($printview) && $printview == '1') {
767 require_once './libraries/header_printview.inc.php';
768 } else {
770 $GLOBALS['js_include'][] = 'functions.js';
771 $GLOBALS['js_include'][] = 'sql.js';
773 unset($message);
775 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
776 if (strlen($table)) {
777 require './libraries/tbl_common.php';
778 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
779 require './libraries/tbl_info.inc.php';
780 require './libraries/tbl_links.inc.php';
781 } elseif (strlen($db)) {
782 require './libraries/db_common.inc.php';
783 require './libraries/db_info.inc.php';
784 } else {
785 require './libraries/server_common.inc.php';
786 require './libraries/server_links.inc.php';
789 else {
790 require_once './libraries/header.inc.php';
791 //we don't need to buffer the output in PMA_showMessage here.
792 //set a global variable and check against it in the function
793 $GLOBALS['buffer_message'] = false;
797 if (strlen($db)) {
798 $cfgRelation = PMA_getRelationsParam();
801 // Gets the list of fields properties
802 if (isset($result) && $result) {
803 $fields_meta = PMA_DBI_get_fields_meta($result);
804 $fields_cnt = count($fields_meta);
807 if( ! $GLOBALS['is_ajax_request']) {
808 //begin the sqlqueryresults div here. container div
809 echo '<div id="sqlqueryresults"';
810 if ($GLOBALS['cfg']['AjaxEnable']) {
811 echo ' class="ajax"';
813 echo '>';
816 // Display previous update query (from tbl_replace)
817 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
818 PMA_showMessage($disp_message, $disp_query, 'success');
821 if (isset($profiling_results)) {
822 PMA_profilingResults($profiling_results, true);
825 // Displays the results in a table
826 if (empty($disp_mode)) {
827 // see the "PMA_setDisplayMode()" function in
828 // libraries/display_tbl.lib.php
829 $disp_mode = 'urdr111101';
832 // hide edit and delete links for information_schema
833 if ($db == 'information_schema') {
834 $disp_mode = 'nnnn110111';
837 if (isset($label)) {
838 $message = PMA_message::success(__('Bookmark %s created'));
839 $message->addParam($label);
840 $message->display();
843 PMA_displayTable($result, $disp_mode, $analyzed_sql);
844 PMA_DBI_free_result($result);
846 // BEGIN INDEX CHECK See if indexes should be checked.
847 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
848 foreach ($selected as $idx => $tbl_name) {
849 $check = PMA_Index::findDuplicates($tbl_name, $db);
850 if (! empty($check)) {
851 printf(__('Problems with indexes of table `%s`'), $tbl_name);
852 echo $check;
855 } // End INDEX CHECK
857 // Bookmark support if required
858 if ($disp_mode[7] == '1'
859 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
860 && !empty($sql_query)) {
861 echo "\n";
863 $goto = 'sql.php?'
864 . PMA_generate_common_url($db, $table)
865 . '&amp;sql_query=' . urlencode($sql_query)
866 . '&amp;id_bookmark=1';
869 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
870 <?php echo PMA_generate_common_hidden_inputs(); ?>
871 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
872 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
873 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
874 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
875 <fieldset>
876 <legend><?php
877 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
878 . __('Bookmark this SQL query');
880 </legend>
882 <div class="formelement">
883 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
884 <input type="text" id="fields_label_" name="fields[label]" value="" />
885 </div>
887 <div class="formelement">
888 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
889 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
890 </div>
892 <div class="clearfloat"></div>
893 </fieldset>
894 <fieldset class="tblFooters">
895 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
896 </fieldset>
897 </form>
898 <?php
899 } // end bookmark support
901 // Do print the page if required
902 if (isset($printview) && $printview == '1') {
904 <script type="text/javascript">
905 //<![CDATA[
906 // Do print the page
907 window.onload = function()
909 if (typeof(window.print) != 'undefined') {
910 window.print();
913 //]]>
914 </script>
915 <?php
916 } // end print case
918 if( $GLOBALS['is_ajax_request'] != true) {
919 echo '</div>'; // end sqlqueryresults div
921 } // end rows returned
924 * Displays the footer
926 require './libraries/footer.inc.php';