Merge remote branch 'origin/master'
[phpmyadmin-themes.git] / sql.php
blobfa0739841f3c04c3aa26c19be7269299d9a43dee
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 $dropdown = PMA_foreignDropdown($foreignData['disp_row'], $foreignData['foreign_field'], $foreignData['foreign_display'], $_REQUEST['curr_value'], $cfg['ForeignKeyMaxLimit']);
70 if( $dropdown == '<option value="">&nbsp;</option>'."\n" ) {
71 //Handle the case when number of values is more than $cfg['ForeignKeyMaxLimit']
72 $_url_params = array(
73 'db' => $db,
74 'table' => $table,
75 'field' => $column
78 $dropdown = '<span class="curr_value">' . htmlspecialchars($_REQUEST['curr_value']) . '</span> <a href="browse_foreigners.php' . PMA_generate_common_url($_url_params) . '"'
79 . ' target="_blank" class="browse_foreign" '
80 .'>' . __('Browse foreign values') . '</a>';
82 else {
83 $dropdown = '<select>' . $dropdown . '</select>';
86 $extra_data['dropdown'] = $dropdown;
87 PMA_ajaxResponse(NULL, true, $extra_data);
90 /**
91 * Just like above, find possible values for enum fields during inline edit.
93 * Logic taken from libraries/display_tbl_lib.php
95 if(isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
96 $field_info_query = 'SHOW FIELDS FROM `' . $db . '`.`' . $table . '` LIKE \'' . $_REQUEST['column'] . '\' ;';
98 $field_info_result = PMA_DBI_fetch_result($field_info_query, null, null, null, PMA_DBI_QUERY_STORE);
100 $search = array('enum', '(', ')', "'");
102 $values = explode(',', str_replace($search, '', $field_info_result[0]['Type']));
104 $dropdown = '';
105 foreach($values as $value) {
106 $dropdown .= '<option value="' . htmlspecialchars($value) . '"';
107 if($value == $_REQUEST['curr_value']) {
108 $dropdown .= ' selected="selected"';
110 $dropdown .= '>' . $value . '</option>';
113 $dropdown = '<select>' . $dropdown . '</select>';
115 $extra_data['dropdown'] = $dropdown;
116 PMA_ajaxResponse(NULL, true, $extra_data);
119 // Default to browse if no query set and we have table
120 // (needed for browsing from DefaultTabTable)
121 if (empty($sql_query) && strlen($table) && strlen($db)) {
122 require_once './libraries/bookmark.lib.php';
123 $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_sqlAddslashes($table) . '\'',
124 'label');
126 if (! empty($book_sql_query)) {
127 $sql_query = $book_sql_query;
128 } else {
129 $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
131 unset($book_sql_query);
133 // set $goto to what will be displayed if query returns 0 rows
134 $goto = 'tbl_structure.php';
135 } else {
136 // Now we can check the parameters
137 PMA_checkParameters(array('sql_query'));
140 // instead of doing the test twice
141 $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
142 $sql_query);
145 * Check rights in case of DROP DATABASE
147 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
148 * but since a malicious user may pass this variable by url/form, we don't take
149 * into account this case.
151 if (!defined('PMA_CHK_DROP')
152 && !$cfg['AllowUserDropDatabase']
153 && $is_drop_database
154 && !$is_superuser) {
155 require_once './libraries/header.inc.php';
156 PMA_mysqlDie(__('"DROP DATABASE" statements are disabled.'), '', '', $err_url);
157 } // end if
159 require_once './libraries/display_tbl.lib.php';
160 PMA_displayTable_checkConfigParams();
163 * Need to find the real end of rows?
165 if (isset($find_real_end) && $find_real_end) {
166 $unlim_num_rows = PMA_Table::countRecords($db, $table, $force_exact = true);
167 $_SESSION['tmp_user_values']['pos'] = @((ceil($unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']) - 1) * $_SESSION['tmp_user_values']['max_rows']);
172 * Bookmark add
174 if (isset($store_bkm)) {
175 PMA_Bookmark_save($fields, (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
176 // go back to sql.php to redisplay query; do not use &amp; in this case:
177 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']);
178 } // end if
181 * Parse and analyze the query
183 require_once './libraries/parse_analyze.lib.php';
186 * Sets or modifies the $goto variable if required
188 if ($goto == 'sql.php') {
189 $is_gotofile = false;
190 $goto = 'sql.php?'
191 . PMA_generate_common_url($db, $table)
192 . '&amp;sql_query=' . urlencode($sql_query);
193 } // end if
197 * Go back to further page if table should not be dropped
199 if (isset($btnDrop) && $btnDrop == __('No')) {
200 if (!empty($back)) {
201 $goto = $back;
203 if ($is_gotofile) {
204 if (strpos($goto, 'db_') === 0 && strlen($table)) {
205 $table = '';
207 $active_page = $goto;
208 require './' . PMA_securePath($goto);
209 } else {
210 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto));
212 exit();
213 } // end if
217 * Displays the confirm page if required
219 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
220 * with js) because possible security issue is not so important here: at most,
221 * the confirm message isn't displayed.
223 * Also bypassed if only showing php code.or validating a SQL query
225 if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
226 // if we are coming from a "Create PHP code" or a "Without PHP Code"
227 // dialog, we won't execute the query anyway, so don't confirm
228 || isset($GLOBALS['show_as_php'])
229 || !empty($GLOBALS['validatequery'])) {
230 $do_confirm = false;
231 } else {
232 $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
235 if ($do_confirm) {
236 $stripped_sql_query = $sql_query;
237 require_once './libraries/header.inc.php';
238 if ($is_drop_database) {
239 echo '<h1 class="warning">' . __('You are about to DESTROY a complete database!') . '</h1>';
241 echo '<form action="sql.php" method="post">' . "\n"
242 .PMA_generate_common_hidden_inputs($db, $table);
244 <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
245 <input type="hidden" name="message_to_show" value="<?php echo isset($message_to_show) ? PMA_sanitize($message_to_show, true) : ''; ?>" />
246 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
247 <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back, true) : ''; ?>" />
248 <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload, true) : 0; ?>" />
249 <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge, true) : ''; ?>" />
250 <input type="hidden" name="dropped_column" value="<?php echo isset($dropped_column) ? PMA_sanitize($dropped_column, true) : ''; ?>" />
251 <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query, true) : ''; ?>" />
252 <?php
253 echo '<fieldset class="confirmation">' . "\n"
254 .' <legend>' . __('Do you really want to ') . '</legend>'
255 .' <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
256 .'</fieldset>' . "\n"
257 .'<fieldset class="tblFooters">' . "\n";
259 <input type="submit" name="btnDrop" value="<?php echo __('Yes'); ?>" id="buttonYes" />
260 <input type="submit" name="btnDrop" value="<?php echo __('No'); ?>" id="buttonNo" />
261 <?php
262 echo '</fieldset>' . "\n"
263 . '</form>' . "\n";
266 * Displays the footer and exit
268 require './libraries/footer.inc.php';
269 } // end if $do_confirm
272 // Defines some variables
273 // A table has to be created, renamed, dropped -> navi frame should be reloaded
275 * @todo use the parser/analyzer
278 if (empty($reload)
279 && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
280 $reload = 1;
283 // SK -- Patch: $is_group added for use in calculation of total number of
284 // rows.
285 // $is_count is changed for more correct "LIMIT" clause
286 // appending in queries like
287 // "SELECT COUNT(...) FROM ... GROUP BY ..."
290 * @todo detect all this with the parser, to avoid problems finding
291 * those strings in comments or backquoted identifiers
294 $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;
295 if ($is_select) { // see line 141
296 $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
297 $is_func = !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
298 $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
299 $is_export = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
300 $is_analyse = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
301 } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
302 $is_explain = true;
303 } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
304 $is_delete = true;
305 $is_affected = true;
306 } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
307 $is_insert = true;
308 $is_affected = true;
309 if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
310 $is_replace = true;
312 } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
313 $is_affected = true;
314 } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
315 $is_show = true;
316 } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
317 $is_maint = true;
320 // Do append a "LIMIT" clause?
321 if ((! $cfg['ShowAll'] || $_SESSION['tmp_user_values']['max_rows'] != 'all')
322 && ! ($is_count || $is_export || $is_func || $is_analyse)
323 && isset($analyzed_sql[0]['queryflags']['select_from'])
324 && ! isset($analyzed_sql[0]['queryflags']['offset'])
325 && empty($analyzed_sql[0]['limit_clause'])
327 $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
329 $full_sql_query = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
331 * @todo pretty printing of this modified query
333 if (isset($display_query)) {
334 // if the analysis of the original query revealed that we found
335 // a section_after_limit, we now have to analyze $display_query
336 // to display it correctly
338 if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
339 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
340 $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
344 } else {
345 $full_sql_query = $sql_query;
346 } // end if...else
348 if (strlen($db)) {
349 PMA_DBI_select_db($db);
352 // E x e c u t e t h e q u e r y
354 // Only if we didn't ask to see the php code (mikebeck)
355 if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
356 unset($result);
357 $num_rows = 0;
358 } else {
359 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
360 PMA_DBI_query('SET PROFILING=1;');
363 // Measure query time.
364 // TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
365 $querytime_before = array_sum(explode(' ', microtime()));
367 $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
369 $querytime_after = array_sum(explode(' ', microtime()));
371 $GLOBALS['querytime'] = $querytime_after - $querytime_before;
373 // Displays an error message if required and stop parsing the script
374 if ($error = PMA_DBI_getError()) {
375 if ($is_gotofile) {
376 if (strpos($goto, 'db_') === 0 && strlen($table)) {
377 $table = '';
379 $active_page = $goto;
380 $message = PMA_Message::rawError($error);
382 if( $GLOBALS['is_ajax_request'] == true) {
383 PMA_ajaxResponse($message, false);
387 * Go to target path.
389 require './' . PMA_securePath($goto);
390 } else {
392 * HTML header.
395 if($GLOBALS['is_ajax_request'] != true) {
396 require_once './libraries/header.inc.php';
398 $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
399 ? $err_url . '&amp;show_query=1&amp;sql_query=' . urlencode($sql_query)
400 : $err_url;
401 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
403 exit;
405 unset($error);
407 // Gets the number of rows affected/returned
408 // (This must be done immediately after the query because
409 // mysql_affected_rows() reports about the last query done)
411 if (!$is_affected) {
412 $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
413 } elseif (!isset($num_rows)) {
414 $num_rows = @PMA_DBI_affected_rows();
417 // Grabs the profiling results
418 if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
419 $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
422 // Checks if the current database has changed
423 // This could happen if the user sends a query like "USE `database`;"
425 * commented out auto-switching to active database - really required?
426 * bug #1814718 win: table list disappears (mixed case db names)
427 * https://sourceforge.net/support/tracker.php?aid=1814718
428 * @todo RELEASE test and comit or rollback before release
429 $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
430 if ($db !== $current_db) {
431 $db = $current_db;
432 $reload = 1;
434 unset($current_db);
437 // tmpfile remove after convert encoding appended by Y.Kawada
438 if (function_exists('PMA_kanji_file_conv')
439 && (isset($textfile) && file_exists($textfile))) {
440 unlink($textfile);
443 // Counts the total number of rows for the same 'SELECT' query without the
444 // 'LIMIT' clause that may have been programatically added
446 if (empty($sql_limit_to_append)) {
447 $unlim_num_rows = $num_rows;
448 // if we did not append a limit, set this to get a correct
449 // "Showing rows..." message
450 //$_SESSION['tmp_user_values']['max_rows'] = 'all';
451 } elseif ($is_select) {
453 // c o u n t q u e r y
455 // If we are "just browsing", there is only one table,
456 // and no WHERE clause (or just 'WHERE 1 '),
457 // we do a quick count (which uses MaxExactCount) because
458 // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
460 // However, do not count again if we did it previously
461 // due to $find_real_end == true
463 if (!$is_group
464 && !isset($analyzed_sql[0]['queryflags']['union'])
465 && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
466 && (empty($analyzed_sql[0]['where_clause'])
467 || $analyzed_sql[0]['where_clause'] == '1 ')
468 && !isset($find_real_end)
471 // "j u s t b r o w s i n g"
472 $unlim_num_rows = PMA_Table::countRecords($db, $table);
474 } else { // n o t " j u s t b r o w s i n g "
476 // add select expression after the SQL_CALC_FOUND_ROWS
478 // for UNION, just adding SQL_CALC_FOUND_ROWS
479 // after the first SELECT works.
481 // take the left part, could be:
482 // SELECT
483 // (SELECT
484 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
485 $count_query .= ' SQL_CALC_FOUND_ROWS ';
486 // add everything that was after the first SELECT
487 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
488 // ensure there is no semicolon at the end of the
489 // count query because we'll probably add
490 // a LIMIT 1 clause after it
491 $count_query = rtrim($count_query);
492 $count_query = rtrim($count_query, ';');
494 // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
495 // long delays. Returned count will be complete anyway.
496 // (but a LIMIT would disrupt results in an UNION)
498 if (!isset($analyzed_sql[0]['queryflags']['union'])) {
499 $count_query .= ' LIMIT 1';
502 // run the count query
504 PMA_DBI_try_query($count_query);
505 // if (mysql_error()) {
506 // void.
507 // I tried the case
508 // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
509 // UNION (SELECT `User`, `Host`, "%" AS "Db",
510 // `Select_priv`
511 // FROM `user`) ORDER BY `User`, `Host`, `Db`;
512 // and although the generated count_query is wrong
513 // the SELECT FOUND_ROWS() work! (maybe it gets the
514 // count from the latest query that worked)
516 // another case where the count_query is wrong:
517 // SELECT COUNT(*), f1 from t1 group by f1
518 // and you click to sort on count(*)
519 // }
520 $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
521 } // end else "just browsing"
523 } else { // not $is_select
524 $unlim_num_rows = 0;
525 } // end rows total count
527 // if a table or database gets dropped, check column comments.
528 if (isset($purge) && $purge == '1') {
530 * Cleanup relations.
532 require_once './libraries/relation_cleanup.lib.php';
534 if (strlen($table) && strlen($db)) {
535 PMA_relationsCleanupTable($db, $table);
536 } elseif (strlen($db)) {
537 PMA_relationsCleanupDatabase($db);
538 } else {
539 // VOID. No DB/Table gets deleted.
540 } // end if relation-stuff
541 } // end if ($purge)
543 // If a column gets dropped, do relation magic.
544 if (isset($dropped_column) && strlen($db) && strlen($table) && !empty($dropped_column)) {
545 require_once './libraries/relation_cleanup.lib.php';
546 PMA_relationsCleanupColumn($db, $table, $dropped_column);
548 } // end if column was dropped
549 } // end else "didn't ask to see php code"
551 // No rows returned -> move back to the calling page
552 if (0 == $num_rows || $is_affected) {
553 if ($is_delete) {
554 $message = PMA_Message::deleted_rows($num_rows);
555 } elseif ($is_insert) {
556 if ($is_replace) {
557 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
558 $message = PMA_Message::affected_rows($num_rows);
559 } else {
560 $message = PMA_Message::inserted_rows($num_rows);
562 $insert_id = PMA_DBI_insert_id();
563 if ($insert_id != 0) {
564 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
565 $message->addMessage('[br]');
566 // need to use a temporary because the Message class
567 // currently supports adding parameters only to the first
568 // message
569 $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
570 $_inserted->addParam($insert_id + $num_rows - 1);
571 $message->addMessage($_inserted);
573 } elseif ($is_affected) {
574 $message = PMA_Message::affected_rows($num_rows);
576 // Ok, here is an explanation for the !$is_select.
577 // The form generated by sql_query_form.lib.php
578 // and db_sql.php has many submit buttons
579 // on the same form, and some confusion arises from the
580 // fact that $message_to_show is sent for every case.
581 // The $message_to_show containing a success message and sent with
582 // the form should not have priority over errors
583 } elseif (!empty($message_to_show) && !$is_select) {
584 $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
585 } elseif (!empty($GLOBALS['show_as_php'])) {
586 $message = PMA_Message::success(__('Showing as PHP code'));
587 } elseif (isset($GLOBALS['show_as_php'])) {
588 /* User disable showing as PHP, query is only displayed */
589 $message = PMA_Message::notice(__('Showing SQL query'));
590 } elseif (!empty($GLOBALS['validatequery'])) {
591 $message = PMA_Message::notice(__('Validated SQL'));
592 } else {
593 $message = PMA_Message::success(__('MySQL returned an empty result set (i.e. zero rows).'));
596 if (isset($GLOBALS['querytime'])) {
597 $_querytime = PMA_Message::notice(__('Query took %01.4f sec'));
598 $_querytime->addParam($GLOBALS['querytime']);
599 $message->addMessage('(');
600 $message->addMessage($_querytime);
601 $message->addMessage(')');
604 if( $GLOBALS['is_ajax_request'] == true) {
607 * If we are in inline editing, we need to process the relational and
608 * transformed fields, if they were edited. After that, output the correct
609 * link/transformed value and exit
611 * Logic taken from libraries/display_tbl.lib.php
614 if(isset($_REQUEST['rel_fields_list']) && $_REQUEST['rel_fields_list'] != '') {
615 //handle relations work here for updated row.
616 require_once './libraries/relation.lib.php';
618 $map = PMA_getForeigners($db, $table, '', 'both');
620 $rel_fields = array();
621 parse_str($_REQUEST['rel_fields_list'], $rel_fields);
623 foreach( $rel_fields as $rel_field => $rel_field_value) {
625 $where_comparison = '=' . $rel_field_value;
626 $_url_params = array(
627 'db' => $map[$rel_field]['foreign_db'],
628 'table' => $map[$rel_field]['foreign_table'],
629 'pos' => '0',
630 'sql_query' => 'SELECT * FROM '
631 . PMA_backquote($map[$rel_field]['foreign_db']) . '.' . PMA_backquote($map[$rel_field]['foreign_table'])
632 . ' WHERE ' . PMA_backquote($map[$rel_field]['foreign_field'])
633 . $where_comparison
636 $extra_data['relations'][$rel_field] = '<a href="sql.php' . PMA_generate_common_url($_url_params) . '">';
637 $extra_data['relations'][$rel_field] .= '</a>';
641 if(isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) {
642 require_once './libraries/transformations.lib.php';
643 //if some posted fields need to be transformed, generate them here.
644 $mime_map = PMA_getMIME($db, $table);
646 if ($mime_map === FALSE) {
647 $mime_map = array();
650 $edited_values = array();
651 parse_str($_REQUEST['transform_fields_list'], $edited_values);
653 foreach($mime_map as $transformation) {
654 $include_file = $transformation['transformation'];
655 $column_name = $transformation['column_name'];
656 $column_data = $edited_values[$column_name];
658 $_url_params = array(
659 'db' => $db,
660 'table' => $table,
661 'where_clause' => $_REQUEST['where_clause'],
662 'transform_key' => $column_name,
665 if (file_exists('./libraries/transformations/' . $include_file)) {
666 $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']);
668 require_once './libraries/transformations/' . $include_file;
670 if (function_exists('PMA_transformation_' . $transformfunction_name)) {
671 $transform_function = 'PMA_transformation_' . $transformfunction_name;
672 $transform_options = PMA_transformation_getOptions((isset($transformation['transformation_options']) ? $transformation['transformation_options'] : ''));
673 $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params);
677 $extra_data['transformations'][$column_name] = $transform_function($column_data, $transform_options);
681 if(isset($GLOBALS['display_query'])) {
682 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
684 if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
685 $extra_data['reload'] = 1;
686 $extra_data['db'] = $GLOBALS['db'];
688 PMA_ajaxResponse($message, $message->isSuccess(), (isset($extra_data) ? $extra_data : ''));
691 if ($is_gotofile) {
692 $goto = PMA_securePath($goto);
693 // Checks for a valid target script
694 $is_db = $is_table = false;
695 if (isset($_REQUEST['purge'])) {
696 $table = '';
697 unset($url_params['table']);
699 include 'libraries/db_table_exists.lib.php';
701 if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
702 if (strlen($table)) {
703 $table = '';
705 $goto = 'db_sql.php';
707 if (strpos($goto, 'db_') === 0 && ! $is_db) {
708 if (strlen($db)) {
709 $db = '';
711 $goto = 'main.php';
713 // Loads to target script
714 if ($goto != 'main.php') {
715 require_once './libraries/header.inc.php';
717 $active_page = $goto;
718 require './' . $goto;
719 } else {
720 // avoid a redirect loop when last record was deleted
721 if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
722 $goto = str_replace('sql.php','tbl_structure.php',$goto);
724 PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto) . '&message=' . urlencode($message));
725 } // end else
726 exit();
727 } // end no rows returned
729 // At least one row is returned -> displays a table with results
730 else {
731 //If we are retrieving the full value of a truncated field or the original
732 // value of a transformed field, show it here and exit
733 if( $GLOBALS['inline_edit'] == true) {
734 $row = PMA_DBI_fetch_row($result);
735 $extra_data = array();
736 $extra_data['value'] = $row[0];
737 PMA_ajaxResponse(NULL, true, $extra_data);
740 // Displays the headers
741 if (isset($show_query)) {
742 unset($show_query);
744 if (isset($printview) && $printview == '1') {
745 require_once './libraries/header_printview.inc.php';
746 } else {
748 $GLOBALS['js_include'][] = 'functions.js';
749 $GLOBALS['js_include'][] = 'sql.js';
751 unset($message);
753 if( $GLOBALS['is_ajax_request'] != true) {
754 if (strlen($table)) {
755 require './libraries/tbl_common.php';
756 $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
757 require './libraries/tbl_info.inc.php';
758 require './libraries/tbl_links.inc.php';
759 } elseif (strlen($db)) {
760 require './libraries/db_common.inc.php';
761 require './libraries/db_info.inc.php';
762 } else {
763 require './libraries/server_common.inc.php';
764 require './libraries/server_links.inc.php';
767 else {
768 //we don't need to buffer the output in PMA_showMessage here.
769 //set a global variable and check against it in the function
770 $GLOBALS['buffer_message'] = false;
774 if (strlen($db)) {
775 $cfgRelation = PMA_getRelationsParam();
778 // Gets the list of fields properties
779 if (isset($result) && $result) {
780 $fields_meta = PMA_DBI_get_fields_meta($result);
781 $fields_cnt = count($fields_meta);
784 if( $GLOBALS['is_ajax_request'] != true ) {
785 //begin the sqlqueryresults div here. container div
786 echo '<div id="sqlqueryresults">';
789 // Display previous update query (from tbl_replace)
790 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
791 PMA_showMessage($disp_message, $disp_query, 'success');
794 if (isset($profiling_results)) {
795 PMA_profilingResults($profiling_results, true);
798 // Displays the results in a table
799 if (empty($disp_mode)) {
800 // see the "PMA_setDisplayMode()" function in
801 // libraries/display_tbl.lib.php
802 $disp_mode = 'urdr111101';
805 // hide edit and delete links for information_schema
806 if ($db == 'information_schema') {
807 $disp_mode = 'nnnn110111';
810 if (isset($label)) {
811 $message = PMA_message::success(__('Bookmark %s created'));
812 $message->addParam($label);
813 $message->display();
816 PMA_displayTable($result, $disp_mode, $analyzed_sql);
817 PMA_DBI_free_result($result);
819 // BEGIN INDEX CHECK See if indexes should be checked.
820 if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
821 foreach ($selected as $idx => $tbl_name) {
822 $check = PMA_Index::findDuplicates($tbl_name, $db);
823 if (! empty($check)) {
824 printf(__('Problems with indexes of table `%s`'), $tbl_name);
825 echo $check;
828 } // End INDEX CHECK
830 // Bookmark support if required
831 if ($disp_mode[7] == '1'
832 && (! empty($cfg['Bookmark']) && empty($id_bookmark))
833 && !empty($sql_query)) {
834 echo "\n";
836 $goto = 'sql.php?'
837 . PMA_generate_common_url($db, $table)
838 . '&amp;sql_query=' . urlencode($sql_query)
839 . '&amp;id_bookmark=1';
842 <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
843 <?php echo PMA_generate_common_hidden_inputs(); ?>
844 <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
845 <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
846 <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
847 <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
848 <fieldset>
849 <legend><?php
850 echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . __('Bookmark this SQL query') . '" />' : '')
851 . __('Bookmark this SQL query');
853 </legend>
855 <div class="formelement">
856 <label for="fields_label_"><?php echo __('Label'); ?>:</label>
857 <input type="text" id="fields_label_" name="fields[label]" value="" />
858 </div>
860 <div class="formelement">
861 <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
862 <label for="bkm_all_users"><?php echo __('Let every user access this bookmark'); ?></label>
863 </div>
865 <div class="clearfloat"></div>
866 </fieldset>
867 <fieldset class="tblFooters">
868 <input type="submit" name="store_bkm" value="<?php echo __('Bookmark this SQL query'); ?>" />
869 </fieldset>
870 </form>
871 <?php
872 } // end bookmark support
874 // Do print the page if required
875 if (isset($printview) && $printview == '1') {
877 <script type="text/javascript">
878 //<![CDATA[
879 // Do print the page
880 window.onload = function()
882 if (typeof(window.print) != 'undefined') {
883 window.print();
886 //]]>
887 </script>
888 <?php
889 } // end print case
891 if( $GLOBALS['is_ajax_request'] != true) {
892 echo '</div>'; // end sqlqueryresults div
894 } // end rows returned
897 * Displays the footer
899 require './libraries/footer.inc.php';