Bug #3187078 Main page ajax results tiny.
[phpmyadmin-themes.git] / sql.php
blob3655d8754f3e7f2d8c0b0a15b760da355b83af0f
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 = '';
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);
118 // Default to browse if no query set and we have table
119 // (needed for browsing from DefaultTabTable)
120 if (empty($sql_query) && strlen($table) && strlen($db)) {
121 require_once './libraries/bookmark.lib.php';
122 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
123 'label', FALSE, TRUE);
125 if (! empty($book_sql_query)) {
126 $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
127 $GLOBALS['using_bookmark_message']->addParam($table);
128 $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
129 $sql_query = $book_sql_query;
130 } else {
131 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
133 unset($book_sql_query);
135 // set $goto to what will be displayed if query returns 0 rows
136 $goto = 'tbl_structure.php';
137 } else {
138 // Now we can check the parameters
139 PMA_checkParameters(array('sql_query'));
142 // instead of doing the test twice
143 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
144 $sql_query);
147 * Check rights in case of DROP DATABASE
149 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
150 * but since a malicious user may pass this variable by url/form, we don't take
151 * into account this case.
153 if (!defined('PMA_CHK_DROP')
154 && !$cfg['AllowUserDropDatabase']
155 && $is_drop_database
156 && !$is_superuser) {
157 require_once './libraries/header.inc.php';
158 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
159 } // end if
161 require_once './libraries/display_tbl.lib.php';
162 PMA_displayTable_checkConfigParams();
165 * Need to find the real end of rows?
167 if (isset($find_real_end) && $find_real_end) {
168 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
169 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
174 * Bookmark add
176 if (isset($store_bkm)) {
177 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
178 // go back to sql.php to redisplay query; do not use &amp; in this case:
179 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
180 } // end if
183 * Parse and analyze the query
185 require_once './libraries/parse_analyze.lib.php';
188 * Sets or modifies the $goto variable if required
190 if ($goto == 'sql.php') {
191 $is_gotofile = false;
192 $goto = 'sql.php?'
193 . PMA_generate_common_url($db, $table)
194 . '&amp;sql_query=' . urlencode($sql_query);
195 } // end if
199 * Go back to further page if table should not be dropped
201 if (isset($btnDrop) && $btnDrop == __('No')) {
202 if (!empty($back)) {
203 $goto = $back;
205 if ($is_gotofile) {
206 if (strpos($goto, 'db_') === 0 && strlen($table)) {
207 $table = '';
209 $active_page = $goto;
210 require './' . PMA_securePath($goto);
211 } else {
212 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
214 exit();
215 } // end if
219 * Displays the confirm page if required
221 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
222 * with js) because possible security issue is not so important here: at most,
223 * the confirm message isn't displayed.
225 * Also bypassed if only showing php code.or validating a SQL query
227 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
228 // if we are coming from a "Create PHP code" or a "Without PHP Code"
229 // dialog, we won't execute the query anyway, so don't confirm
230 || isset($GLOBALS['show_as_php'])
231 || !empty($GLOBALS['validatequery'])) {
232 $do_confirm = false;
233 } else {
234 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
237 if ($do_confirm) {
238 $stripped_sql_query = $sql_query;
239 require_once './libraries/header.inc.php';
240 if ($is_drop_database) {
241 echo '<h1 class="warning">' . __('You are about to DESTROY a complete database!') . '</h1>';
243 echo '<form action="sql.php" method="post">' . "\n"
244 .PMA_generate_common_hidden_inputs($db, $table);
246 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
247 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
248 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
249 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
250 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
251 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
252 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
253 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
254 <?php
255 echo '<fieldset class="confirmation">' . "\n"
256 .' <legend>' . __('Do you really want to ') . '</legend>'
257 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
258 .'</fieldset>' . "\n"
259 .'<fieldset class="tblFooters">' . "\n";
261 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
262 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
263 <?php
264 echo '</fieldset>' . "\n"
265 . '</form>' . "\n";
268 * Displays the footer and exit
270 require './libraries/footer.inc.php';
271 } // end if $do_confirm
274 // Defines some variables
275 // A table has to be created, renamed, dropped -> navi frame should be reloaded
277 * @todo use the parser/analyzer
280 if (empty($reload)
281 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
282 $reload = 1;
285 // SK -- Patch: $is_group added for use in calculation of total number of
286 // rows.
287 // $is_count is changed for more correct "LIMIT" clause
288 // appending in queries like
289 // "SELECT COUNT(...) FROM ... GROUP BY ..."
292 * @todo detect all this with the parser, to avoid problems finding
293 * those strings in comments or backquoted identifiers
296 $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;
297 if ($is_select) { // see line 141
298 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
299 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
300 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
301 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
302 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
303 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
304 $is_explain = true;
305 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
306 $is_delete = true;
307 $is_affected = true;
308 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
309 $is_insert = true;
310 $is_affected = true;
311 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
312 $is_replace = true;
314 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
315 $is_affected = true;
316 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
317 $is_show = true;
318 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
319 $is_maint = true;
322 // Do append a "LIMIT" clause?
323 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
324 && ! ($is_count || $is_export || $is_func || $is_analyse)
325 && isset($analyzed_sql[0]['queryflags']['select_from'])
326 && ! isset($analyzed_sql[0]['queryflags']['offset'])
327 && empty($analyzed_sql[0]['limit_clause'])
329 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
331 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
333 * @todo pretty printing of this modified query
335 if (isset($display_query)) {
336 // if the analysis of the original query revealed that we found
337 // a section_after_limit, we now have to analyze $display_query
338 // to display it correctly
340 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
341 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
342 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
346 } else {
347 $full_sql_query = $sql_query;
348 } // end if...else
350 if (strlen($db)) {
351 PMA_DBI_select_db($db);
354 // E x e c u t e t h e q u e r y
356 // Only if we didn't ask to see the php code (mikebeck)
357 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
358 unset($result);
359 $num_rows = 0;
360 } else {
361 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
362 PMA_DBI_query('SET PROFILING=1;');
365 // Measure query time.
366 $querytime_before = array_sum(explode(' ', microtime()));
368 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
370 $querytime_after = array_sum(explode(' ', microtime()));
372 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
374 // Displays an error message if required and stop parsing the script
375 if ($error = PMA_DBI_getError()) {
376 if ($is_gotofile) {
377 if (strpos($goto, 'db_') === 0 && strlen($table)) {
378 $table = '';
380 $active_page = $goto;
381 $message = PMA_Message::rawError($error);
383 if( $GLOBALS['is_ajax_request'] == true) {
384 PMA_ajaxResponse($message, false);
388 * Go to target path.
390 require './' . PMA_securePath($goto);
391 } else {
392 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
393 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
394 : $err_url;
395 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
397 exit;
399 unset($error);
401 // Gets the number of rows affected/returned
402 // (This must be done immediately after the query because
403 // mysql_affected_rows() reports about the last query done)
405 if (!$is_affected) {
406 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
407 } elseif (!isset($num_rows)) {
408 $num_rows = @PMA_DBI_affected_rows();
411 // Grabs the profiling results
412 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
413 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
416 // Checks if the current database has changed
417 // This could happen if the user sends a query like "USE `database`;"
419 * commented out auto-switching to active database - really required?
420 * bug #1814718 win: table list disappears (mixed case db names)
421 * https://sourceforge.net/support/tracker.php?aid=1814718
422 * @todo RELEASE test and comit or rollback before release
423 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
424 if ($db !== $current_db) {
425 $db = $current_db;
426 $reload = 1;
428 unset($current_db);
431 // tmpfile remove after convert encoding appended by Y.Kawada
432 if (function_exists('PMA_kanji_file_conv')
433 && (isset($textfile) && file_exists($textfile))) {
434 unlink($textfile);
437 // Counts the total number of rows for the same 'SELECT' query without the
438 // 'LIMIT' clause that may have been programatically added
440 if (empty($sql_limit_to_append)) {
441 $unlim_num_rows = $num_rows;
442 // if we did not append a limit, set this to get a correct
443 // "Showing rows..." message
444 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
445 } elseif ($is_select) {
447 // c o u n t q u e r y
449 // If we are "just browsing", there is only one table,
450 // and no WHERE clause (or just 'WHERE 1 '),
451 // we do a quick count (which uses MaxExactCount) because
452 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
454 // However, do not count again if we did it previously
455 // due to $find_real_end == true
457 if (!$is_group
458 && !isset($analyzed_sql[0]['queryflags']['union'])
459 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
460 && (empty($analyzed_sql[0]['where_clause'])
461 || $analyzed_sql[0]['where_clause'] == '1 ')
462 && !isset($find_real_end)
465 // "j u s t b r o w s i n g"
466 $unlim_num_rows = PMA_Table::countRecords($db, $table);
468 } else { // n o t " j u s t b r o w s i n g "
470 // add select expression after the SQL_CALC_FOUND_ROWS
472 // for UNION, just adding SQL_CALC_FOUND_ROWS
473 // after the first SELECT works.
475 // take the left part, could be:
476 // SELECT
477 // (SELECT
478 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
479 $count_query .= ' SQL_CALC_FOUND_ROWS ';
480 // add everything that was after the first SELECT
481 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
482 // ensure there is no semicolon at the end of the
483 // count query because we'll probably add
484 // a LIMIT 1 clause after it
485 $count_query = rtrim($count_query);
486 $count_query = rtrim($count_query, ';');
488 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
489 // long delays. Returned count will be complete anyway.
490 // (but a LIMIT would disrupt results in an UNION)
492 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
493 $count_query .= ' LIMIT 1';
496 // run the count query
498 PMA_DBI_try_query($count_query);
499 // if (mysql_error()) {
500 // void.
501 // I tried the case
502 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
503 // UNION (SELECT `User`, `Host`, "%" AS "Db",
504 // `Select_priv`
505 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
506 // and although the generated count_query is wrong
507 // the SELECT FOUND_ROWS() work! (maybe it gets the
508 // count from the latest query that worked)
510 // another case where the count_query is wrong:
511 // SELECT COUNT(*), f1 from t1 group by f1
512 // and you click to sort on count(*)
513 // }
514 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
515 } // end else "just browsing"
517 } else { // not $is_select
518 $unlim_num_rows = 0;
519 } // end rows total count
521 // if a table or database gets dropped, check column comments.
522 if (isset($purge) && $purge == '1') {
524 * Cleanup relations.
526 require_once './libraries/relation_cleanup.lib.php';
528 if (strlen($table) && strlen($db)) {
529 PMA_relationsCleanupTable($db, $table);
530 } elseif (strlen($db)) {
531 PMA_relationsCleanupDatabase($db);
532 } else {
533 // VOID. No DB/Table gets deleted.
534 } // end if relation-stuff
535 } // end if ($purge)
537 // If a column gets dropped, do relation magic.
538 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
539 require_once './libraries/relation_cleanup.lib.php';
540 PMA_relationsCleanupColumn($db, $table, $dropped_column);
542 } // end if column was dropped
543 } // end else "didn't ask to see php code"
545 // No rows returned -> move back to the calling page
546 if (0 == $num_rows || $is_affected) {
547 if ($is_delete) {
548 $message = PMA_Message::deleted_rows($num_rows);
549 } elseif ($is_insert) {
550 if ($is_replace) {
551 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
552 $message = PMA_Message::affected_rows($num_rows);
553 } else {
554 $message = PMA_Message::inserted_rows($num_rows);
556 $insert_id = PMA_DBI_insert_id();
557 if ($insert_id != 0) {
558 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
559 $message->addMessage('[br]');
560 // need to use a temporary because the Message class
561 // currently supports adding parameters only to the first
562 // message
563 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
564 $_inserted->addParam($insert_id + $num_rows - 1);
565 $message->addMessage($_inserted);
567 } elseif ($is_affected) {
568 $message = PMA_Message::affected_rows($num_rows);
570 // Ok, here is an explanation for the !$is_select.
571 // The form generated by sql_query_form.lib.php
572 // and db_sql.php has many submit buttons
573 // on the same form, and some confusion arises from the
574 // fact that $message_to_show is sent for every case.
575 // The $message_to_show containing a success message and sent with
576 // the form should not have priority over errors
577 } elseif (!empty($message_to_show) && !$is_select) {
578 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
579 } elseif (!empty($GLOBALS['show_as_php'])) {
580 $message = PMA_Message::success(__('Showing as PHP code'));
581 } elseif (isset($GLOBALS['show_as_php'])) {
582 /* User disable showing as PHP, query is only displayed */
583 $message = PMA_Message::notice(__('Showing SQL query'));
584 } elseif (!empty($GLOBALS['validatequery'])) {
585 $message = PMA_Message::notice(__('Validated SQL'));
586 } else {
587 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
590 if (isset($GLOBALS['querytime'])) {
591 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
592 $_querytime->addParam($GLOBALS['querytime']);
593 $message->addMessage('(');
594 $message->addMessage($_querytime);
595 $message->addMessage(')');
598 if( $GLOBALS['is_ajax_request'] == true) {
601 * If we are in inline editing, we need to process the relational and
602 * transformed fields, if they were edited. After that, output the correct
603 * link/transformed value and exit
605 * Logic taken from libraries/display_tbl.lib.php
608 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
609 //handle relations work here for updated row.
610 require_once './libraries/relation.lib.php';
612 $map = PMA_getForeigners($db, $table, '', 'both');
614 $rel_fields = array();
615 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
617 foreach( $rel_fields as $rel_field => $rel_field_value) {
619 $where_comparison = '=' . $rel_field_value;
620 $_url_params = array(
621 'db' => $map[$rel_field]['foreign_db'],
622 'table' => $map[$rel_field]['foreign_table'],
623 'pos' => '0',
624 'sql_query' => 'SELECT * FROM '
625 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
626 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
627 . $where_comparison
630 $extra_data['relations'][$rel_field] = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '">';
631 $extra_data['relations'][$rel_field] .= '</a>';
635 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
636 require_once './libraries/transformations.lib.php';
637 //if some posted fields need to be transformed, generate them here.
638 $mime_map = PMA_getMIME($db, $table);
640 if ($mime_map === FALSE) {
641 $mime_map = array();
644 $edited_values = array();
645 parse_str($_REQUEST['transform_fields_list'], $edited_values);
647 foreach($mime_map as $transformation) {
648 $include_file = $transformation['transformation'];
649 $column_name = $transformation['column_name'];
650 $column_data = $edited_values[$column_name];
652 $_url_params = array(
653 'db' => $db,
654 'table' => $table,
655 'where_clause' => $_REQUEST['where_clause'],
656 'transform_key' => $column_name,
659 if (file_exists('./libraries/transformations/' . $include_file)) {
660 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
662 require_once './libraries/transformations/' . $include_file;
664 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
665 $transform_function = 'PMA_transformation_' . $transformfunction_name;
666 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
667 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
671 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
675 if(isset($GLOBALS['display_query'])) {
676 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
678 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
679 $extra_data['reload'] = 1;
680 $extra_data['db'] = $GLOBALS['db'];
682 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
685 if ($is_gotofile) {
686 $goto = PMA_securePath($goto);
687 // Checks for a valid target script
688 $is_db = $is_table = false;
689 if (isset($_REQUEST['purge'])) {
690 $table = '';
691 unset($url_params['table']);
693 include 'libraries/db_table_exists.lib.php';
695 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
696 if (strlen($table)) {
697 $table = '';
699 $goto = 'db_sql.php';
701 if (strpos($goto, 'db_') === 0 && ! $is_db) {
702 if (strlen($db)) {
703 $db = '';
705 $goto = 'main.php';
707 // Loads to target script
708 if ($goto != 'main.php') {
709 require_once './libraries/header.inc.php';
711 $active_page = $goto;
712 require './' . $goto;
713 } else {
714 // avoid a redirect loop when last record was deleted
715 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
716 $goto = str_replace('sql.php','tbl_structure.php',$goto);
718 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
719 } // end else
720 exit();
721 } // end no rows returned
723 // At least one row is returned -> displays a table with results
724 else {
725 //If we are retrieving the full value of a truncated field or the original
726 // value of a transformed field, show it here and exit
727 if( $GLOBALS['inline_edit'] == true && $GLOBALS['cfg']['AjaxEnable']) {
728 $row = PMA_DBI_fetch_row($result);
729 $extra_data = array();
730 $extra_data['value'] = $row[0];
731 PMA_ajaxResponse(NULL, true, $extra_data);
734 // Displays the headers
735 if (isset($show_query)) {
736 unset($show_query);
738 if (isset($printview) && $printview == '1') {
739 require_once './libraries/header_printview.inc.php';
740 } else {
742 $GLOBALS['js_include'][] = 'functions.js';
743 $GLOBALS['js_include'][] = 'sql.js';
745 unset($message);
747 if( ! $GLOBALS['is_ajax_request'] || ! $GLOBALS['cfg']['AjaxEnable']) {
748 if (strlen($table)) {
749 require './libraries/tbl_common.php';
750 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
751 require './libraries/tbl_info.inc.php';
752 require './libraries/tbl_links.inc.php';
753 } elseif (strlen($db)) {
754 require './libraries/db_common.inc.php';
755 require './libraries/db_info.inc.php';
756 } else {
757 require './libraries/server_common.inc.php';
758 require './libraries/server_links.inc.php';
761 else {
762 require_once './libraries/header.inc.php';
763 //we don't need to buffer the output in PMA_showMessage here.
764 //set a global variable and check against it in the function
765 $GLOBALS['buffer_message'] = false;
769 if (strlen($db)) {
770 $cfgRelation = PMA_getRelationsParam();
773 // Gets the list of fields properties
774 if (isset($result) && $result) {
775 $fields_meta = PMA_DBI_get_fields_meta($result);
776 $fields_cnt = count($fields_meta);
779 if( ! $GLOBALS['is_ajax_request']) {
780 //begin the sqlqueryresults div here. container div
781 echo '<div id="sqlqueryresults"';
782 if ($GLOBALS['cfg']['AjaxEnable']) {
783 echo ' class="ajax"';
785 echo '>';
788 // Display previous update query (from tbl_replace)
789 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
790 PMA_showMessage($disp_message, $disp_query, 'success');
793 if (isset($profiling_results)) {
794 PMA_profilingResults($profiling_results, true);
797 // Displays the results in a table
798 if (empty($disp_mode)) {
799 // see the "PMA_setDisplayMode()" function in
800 // libraries/display_tbl.lib.php
801 $disp_mode = 'urdr111101';
804 // hide edit and delete links for information_schema
805 if ($db == 'information_schema') {
806 $disp_mode = 'nnnn110111';
809 if (isset($label)) {
810 $message = PMA_message::success(__('Bookmark %s created'));
811 $message->addParam($label);
812 $message->display();
815 PMA_displayTable($result, $disp_mode, $analyzed_sql);
816 PMA_DBI_free_result($result);
818 // BEGIN INDEX CHECK See if indexes should be checked.
819 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
820 foreach ($selected as $idx => $tbl_name) {
821 $check = PMA_Index::findDuplicates($tbl_name, $db);
822 if (! empty($check)) {
823 printf(__('Problems with indexes of table `%s`'), $tbl_name);
824 echo $check;
827 } // End INDEX CHECK
829 // Bookmark support if required
830 if ($disp_mode[7] == '1'
831 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
832 && !empty($sql_query)) {
833 echo "\n";
835 $goto = 'sql.php?'
836 . PMA_generate_common_url($db, $table)
837 . '&amp;sql_query=' . urlencode($sql_query)
838 . '&amp;id_bookmark=1';
841 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
842 <?php echo PMA_generate_common_hidden_inputs(); ?>
843 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
844 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
845 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
846 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
847 <fieldset>
848 <legend><?php
849 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
850 . __('Bookmark this SQL query');
852 </legend>
854 <div class="formelement">
855 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
856 <input type="text" id="fields_label_" name="fields[label]" value="" />
857 </div>
859 <div class="formelement">
860 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
861 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
862 </div>
864 <div class="clearfloat"></div>
865 </fieldset>
866 <fieldset class="tblFooters">
867 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
868 </fieldset>
869 </form>
870 <?php
871 } // end bookmark support
873 // Do print the page if required
874 if (isset($printview) && $printview == '1') {
876 <script type="text/javascript">
877 //<![CDATA[
878 // Do print the page
879 window.onload = function()
881 if (typeof(window.print) != 'undefined') {
882 window.print();
885 //]]>
886 </script>
887 <?php
888 } // end print case
890 if( $GLOBALS['is_ajax_request'] != true) {
891 echo '</div>'; // end sqlqueryresults div
893 } // end rows returned
896 * Displays the footer
898 require './libraries/footer.inc.php';