6 * Gets some core libraries
8 require('./libraries/grab_globals.lib.php3');
9 require('./libraries/common.lib.php3');
13 * Defines the url to return to in case of error in a sql statement
17 $is_gotofile = ereg_replace('^([^?]+).*$', '\\1', $goto);
18 if (!@file_exists
('./' . $is_gotofile)) {
21 $is_gotofile = ($is_gotofile == $goto);
23 } // end if (security checkings)
26 $goto = (empty($table)) ?
'db_details.php3' : 'tbl_properties.php3';
29 if (!isset($err_url)) {
30 $err_url = (!empty($back) ?
$back : $goto)
32 . '&convcharset=' . $convcharset
33 . '&server=' . $server
34 . (isset($db) ?
'&db=' . urlencode($db) : '')
35 . ((strpos(' ' . $goto, 'db_details') != 1 && isset($table)) ?
'&table=' . urlencode($table) : '');
42 * Does some preliminary formatting of the $sql_query to avoid problems with
44 * 1) separates reserved words in $sql_str from the next backquoted or
45 * parenthesized expression with a space;
46 * 2) capitalizes reserved words
47 * 3) removes repeated spaces
49 * @param string original query
51 * @return string formatted query
53 function PMA_sqlFormat($sql_str) {
54 // Defines reserved words to deal with
55 $res_words_arr = array('DROP', 'SELECT', 'DELETE', 'UPDATE', 'INSERT', 'LOAD', 'EXPLAIN', 'SHOW', 'FROM', 'INTO', 'OUTFILE', 'DATA', 'REPLACE', 'CHECK', 'ANALYZE', 'REPAIR', 'OPTIMIZE', 'TABLE', 'ORDER', 'HAVING', 'LIMIT', 'GROUP', 'DISTINCT');
57 while (list(, $w) = each($res_words_arr)) {
58 // Separates a backquoted expression with spaces
59 $pattern = '[[:space:]]' . $w . '`([^`]*)`(.*)';
60 $replace = ' ' . $w . ' `\\1` \\2';
61 $sql_str = substr(eregi_replace($pattern, $replace, ' ' . $sql_str), 1);
63 // Separates a parenthesized expression with spaces
64 $pattern = '[[:space:]]' . $w . '\(([^)]*)\)(.*)';
65 $replace = ' ' . $w . ' (\\1) \\2';
66 $sql_str = substr(eregi_replace($pattern, $replace, ' ' . $sql_str), 1);
68 // Converts reservered words to upper case if not yet done
69 $sql_str = substr(eregi_replace('[[:space:]]' . $w . '[[:space:]]', ' ' . $w . ' ', ' ' . $sql_str), 1);
72 // Removes repeated spaces
73 $sql_str = ereg_replace('[[:space:]]+', ' ', $sql_str);
75 // GROUP or ORDER: "BY" to uppercase too
76 $sql_str = eregi_replace('(GROUP|ORDER) BY', '\\1 BY', $sql_str);
79 } // end of the "PMA_sqlFormat()" function
83 * Check rights in case of DROP DATABASE
85 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
86 * but since a malicious user may pass this variable by url/form, we don't take
87 * into account this case.
89 if (!defined('PMA_CHK_DROP')
90 && !$cfg['AllowUserDropDatabase']
91 && eregi('DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE[[:space:]]', $sql_query)) {
92 // Checks if the user is a Superuser
93 // TODO: set a global variable with this information
94 // loic1: optimized query
95 $result = @PMA_mysql_query
('USE mysql');
96 if (PMA_mysql_error()) {
97 include('./header.inc.php3');
98 PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
106 if (isset($store_bkm)) {
107 if (get_magic_quotes_gpc()) {
108 $fields['label'] = stripslashes($fields['label']);
110 include('./libraries/bookmark.lib.php3');
111 PMA_addBookmarks($fields, $cfg['Bookmark']);
112 header('Location: ' . $cfg['PmaAbsoluteUri'] . $goto);
117 * Gets the true sql query
119 // $sql_query has been urlencoded in the confirmation form for drop/delete
120 // queries or in the navigation bar for browsing among records
121 if (isset($btnDrop) ||
isset($navig)) {
122 $sql_query = urldecode($sql_query);
125 // SK -- Patch : Reformats query - adds spaces when omitted and removes extra
126 // spaces; converts reserved words to uppercase
127 $sql_query = PMA_sqlFormat($sql_query);
130 // If the query is a Select, extract the db and table names and modify
131 // $db and $table, to have correct page headers, links and left frame.
132 // db and table name may be enclosed with backquotes, db is optionnal,
133 // query may contain aliases.
134 // (todo: check for embedded comments...)
136 // (todo: if there are more than one table name in the Select:
137 // - do not extract the first table name
138 // - do not show a table name in the page header
139 // - do not display the sub-pages links)
141 $is_select = eregi('^SELECT[[:space:]]+', $sql_query);
143 eregi('^SELECT[[:space:]]+(.*)[[:space:]]+FROM[[:space:]]+(`[^`]+`|[A-Za-z0-9_$]+)([\.]*)(`[^`]*`|[A-Za-z0-9_$]*)', $sql_query, $tmp);
145 if ($tmp[3] == '.') {
147 $db = str_replace('`', '', $tmp[2]);
148 $reload = ($db == $prev_db) ?
0 : 1;
149 $table = str_replace('`', '', $tmp[4]);
152 $table = str_replace('`', '', $tmp[2]);
158 * Sets or modifies the $goto variable if required
160 if ($goto == 'sql.php3') {
163 . '&convcharset=' . $convcharset
164 . '&server=' . $server
165 . '&db=' . urlencode($db)
166 . '&table=' . urlencode($table)
168 . '&sql_query=' . urlencode($sql_query);
173 * Go back to further page if table should not be dropped
175 if (isset($btnDrop) && $btnDrop == $strNo) {
180 if (strpos(' ' . $goto, 'db_details') == 1 && !empty($table)) {
183 include('./' . ereg_replace('\.\.*', '.', $goto));
185 header('Location: ' . $cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
192 * Displays the confirm page if required
194 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
195 * with js) because possible security issue is not so important here: at most,
196 * the confirm message isn't displayed.
198 * Also bypassed if only showing php code.
201 ||
(isset($is_js_confirmed) && $is_js_confirmed)
203 ||
!empty($GLOBALS['show_as_php'])) {
206 $do_confirm = (eregi('DROP[[:space:]]+(IF[[:space:]]+EXISTS[[:space:]]+)?(TABLE|DATABASE[[:space:]])|ALTER[[:space:]]+TABLE[[:space:]]+((`[^`]+`)|([A-Za-z0-9_$]+))[[:space:]]+DROP[[:space:]]|DELETE[[:space:]]+FROM[[:space:]]', $sql_query));
210 if (get_magic_quotes_gpc()) {
211 $stripped_sql_query = stripslashes($sql_query);
213 $stripped_sql_query = $sql_query;
215 include('./header.inc.php3');
216 echo $strDoYouReally . ' :<br />' . "\n";
217 echo '<tt>' . htmlspecialchars($stripped_sql_query) . '</tt> ?<br/>' . "\n";
219 <form action
="sql.php3" method
="post">
220 <input type
="hidden" name
="lang" value
="<?php echo $lang; ?>" />
221 <input type
="hidden" name
="convcharset" value
="<?php echo $convcharset; ?>" />
222 <input type
="hidden" name
="server" value
="<?php echo $server; ?>" />
223 <input type
="hidden" name
="db" value
="<?php echo $db; ?>" />
224 <input type
="hidden" name
="table" value
="<?php echo isset($table) ? $table : ''; ?>" />
225 <input type
="hidden" name
="sql_query" value
="<?php echo urlencode($sql_query); ?>" />
226 <input type
="hidden" name
="zero_rows" value
="<?php echo isset($zero_rows) ? $zero_rows : ''; ?>" />
227 <input type
="hidden" name
="goto" value
="<?php echo $goto; ?>" />
228 <input type
="hidden" name
="back" value
="<?php echo isset($back) ? $back : ''; ?>" />
229 <input type
="hidden" name
="reload" value
="<?php echo isset($reload) ? $reload : 0; ?>" />
230 <input type
="hidden" name
="show_query" value
="<?php echo isset($show_query) ? $show_query : ''; ?>" />
231 <input type
="submit" name
="btnDrop" value
="<?php echo $strYes; ?>" />
232 <input type
="submit" name
="btnDrop" value
="<?php echo $strNo; ?>" />
240 * Executes the query and displays results
243 if (!isset($sql_query)) {
245 } else if (get_magic_quotes_gpc()) {
246 $sql_query = stripslashes($sql_query);
248 // Defines some variables
249 // loic1: A table has to be created -> left frame should be reloaded
250 if ((!isset($reload) ||
$reload == 0)
251 && eregi('^CREATE TABLE[[:space:]]+(.*)', $sql_query)) {
254 // Gets the number of rows per page
255 if (!isset($session_max_rows)) {
256 $session_max_rows = $cfg['MaxRows'];
257 } else if ($session_max_rows != 'all') {
258 $cfg['MaxRows'] = $session_max_rows;
260 // Defines the display mode (horizontal/vertical) and header "frequency"
261 if (empty($disp_direction)) {
262 $disp_direction = $cfg['DefaultDisplay'];
264 if (empty($repeat_cells)) {
265 $repeat_cells = $cfg['RepeatCells'];
268 // SK -- Patch: $is_group added for use in calculation of total number of
270 // $is_count is changed for more correct "LIMIT" clause
271 // appending in queries like
272 // "SELECT COUNT(...) FROM ... GROUP BY ..."
273 $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = FALSE;
274 if ($is_select) { // see line 141
275 $is_func = !$is_group && (eregi('[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(', $sql_query));
276 $is_group = eregi('[[:space:]]+(GROUP BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+', $sql_query);
277 $is_count = !$is_group && (eregi('^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)', $sql_query));
278 $is_export = (eregi('[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+', $sql_query));
279 $is_analyse = (eregi('[[:space:]]+PROCEDURE[[:space:]]+ANALYSE\(', $sql_query));
280 } else if (eregi('^EXPLAIN[[:space:]]+', $sql_query)) {
282 } else if (eregi('^DELETE[[:space:]]+', $sql_query)) {
285 } else if (eregi('^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+', $sql_query)) {
288 } else if (eregi('^UPDATE[[:space:]]+', $sql_query)) {
290 } else if (eregi('^SHOW[[:space:]]+', $sql_query)) {
292 } else if (eregi('^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+', $sql_query)) {
296 // Do append a "LIMIT" clause?
298 && (!$cfg['ShowAll'] ||
$session_max_rows != 'all')
300 && !($is_count ||
$is_export ||
$is_func ||
$is_analyse)
301 && eregi('[[:space:]]FROM[[:space:]]', $sql_query)
302 && !eregi('[[:space:]]LIMIT[[:space:]0-9,-]+$', $sql_query)) {
303 $sql_limit_to_append = " LIMIT $pos, ".$cfg['MaxRows'];
304 if (eregi('(.*)([[:space:]](PROCEDURE[[:space:]](.*)|FOR[[:space:]]+UPDATE|LOCK[[:space:]]+IN[[:space:]]+SHARE[[:space:]]+MODE))$', $sql_query, $regs)) {
305 $full_sql_query = $regs[1] . $sql_limit_to_append . $regs[2];
307 $full_sql_query = $sql_query . $sql_limit_to_append;
310 $full_sql_query = $sql_query;
313 PMA_mysql_select_db($db);
315 // If the query is a DELETE query with no WHERE clause, get the number of
316 // rows that will be deleted (mysql_affected_rows will always return 0 in
319 && eregi('^DELETE([[:space:]].+)?([[:space:]]FROM[[:space:]](.+))$', $sql_query, $parts)
320 && !eregi('[[:space:]]WHERE[[:space:]]', $parts[3])) {
321 $cnt_all_result = @PMA_mysql_query
('SELECT COUNT(*) as count' . $parts[2]);
322 if ($cnt_all_result) {
323 $num_rows = PMA_mysql_result($cnt_all_result, 0, 'count');
324 mysql_free_result($cnt_all_result);
329 // Executes the query
330 // Only if we didn't ask to see the php code (mikebeck)
331 if (!empty($GLOBALS['show_as_php'])) {
336 $result = @PMA_mysql_query
($full_sql_query);
337 // Displays an error message if required and stop parsing the script
338 if (PMA_mysql_error()) {
339 $error = PMA_mysql_error();
340 include('./header.inc.php3');
341 $full_err_url = (ereg('^(db_details|tbl_properties)', $err_url))
342 ?
$err_url . '&show_query=y&sql_query=' . urlencode($sql_query)
344 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
347 // tmpfile remove after convert encoding appended by Y.Kawada
348 if (function_exists('PMA_kanji_file_conv')
349 && (isset($textfile) && file_exists($textfile))) {
353 // Gets the number of rows affected/returned
355 $num_rows = ($result) ? @mysql_num_rows
($result) : 0;
356 } else if (!isset($num_rows)) {
357 $num_rows = @mysql_affected_rows
();
360 // Counts the total number of rows for the same 'SELECT' query without the
361 // 'LIMIT' clause that may have been programatically added
362 if (empty($sql_limit_to_append)) {
363 $unlim_num_rows = $num_rows;
365 else if ($is_select) {
366 // SK -- Patch : correct calculations for GROUP BY, HAVING, DISTINCT
368 // Reads only the from-part of the query...
369 // NOTE: here the presence of LIMIT is impossible, HAVING and GROUP BY
370 // are necessary for correct calculation, and extra spaces and
371 // lowercase reserved words are removed, so we have a simple split
374 $array = split('[[:space:]]+(FROM|ORDER BY)[[:space:]]+', $sql_query);
376 // if $array[1] is empty here, there is an error in the query:
377 // "... FROM [ORDER BY ...]", but the query is already executed with
378 // success so this check is redundant???
380 if (!empty($array[1])) {
381 // ... and makes a count(*) to count the entries
382 // Special case: SELECT DISTINCT ... FROM ...
383 // the count of resulting rows can be found as:
384 // SELECT COUNT(DISTINCT ...) FROM ...
385 if (eregi('^SELECT DISTINCT(.*)', $array[0], $array_dist)) {
386 $count_what = 'DISTINCT ' . $array_dist[1];
390 $count_query = 'SELECT COUNT(' . $count_what . ') AS count FROM ' . $array[1];
391 if ($cnt_all_result = mysql_query($count_query)) {
393 $unlim_num_rows = @mysql_num_rows
($cnt_all_result);
395 $unlim_num_rows = mysql_result($cnt_all_result, 0, 'count');
397 mysql_free_result($cnt_all_result);
402 } // end rows total count
403 } // end else "didn't ask to see php code"
405 // No rows returned -> move back to the calling page
406 if ($num_rows < 1 ||
$is_affected) {
408 $message = $strDeletedRows . ' ' . $num_rows;
409 } else if ($is_insert) {
410 $message = $strInsertedRows . ' ' . $num_rows;
411 } else if ($is_affected) {
412 $message = $strAffectedRows . ' ' . $num_rows;
413 } else if (!empty($zero_rows)) {
414 $message = $zero_rows;
415 } else if (!empty($GLOBALS['show_as_php'])) {
418 $message = $strEmptyResultSet;
422 $goto = ereg_replace('\.\.*', '.', $goto);
423 // Checks for a valid target script
424 if (isset($table) && $table == '') {
427 if (isset($db) && $db == '') {
430 $is_db = $is_table = FALSE;
431 if (strpos(' ' . $goto, 'tbl_properties') == 1) {
432 if (!isset($table)) {
433 $goto = 'db_details.php3';
435 $is_table = @PMA_mysql_query
('SHOW TABLES LIKE \'' . PMA_sqlAddslashes($table, TRUE) . '\'');
436 if (!($is_table && @mysql_numrows
($is_table))) {
437 $goto = 'db_details.php3';
440 } // end if... else...
442 if (strpos(' ' . $goto, 'db_details.php3') == 1) {
449 $is_db = @PMA_mysql_select_db
($db);
454 } // end if... else...
456 // Loads to target script
457 if (strpos(' ' . $goto, 'db_details') == 1
458 ||
strpos(' ' . $goto, 'tbl_properties') == 1) {
459 $js_to_run = 'functions.js';
461 if ($goto != 'main.php3') {
462 include('./header.inc.php3');
464 include('./' . $goto);
465 } // end if file_exist
467 header('Location: ' . $cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
470 } // end no rows returned
472 // At least one row is returned -> displays a table with results
474 // Displays the headers
475 if (isset($show_query)) {
478 if (isset($printview) && $printview == '1') {
479 include('./header_printview.inc.php3');
481 $js_to_run = 'functions.js';
483 if (!empty($table)) {
484 include('./tbl_properties_common.php3');
485 include('./tbl_properties_table_info.php3');
488 include('./db_details_common.php3');
489 include('./db_details_db_info.php3');
491 include('./libraries/relation.lib.php3');
492 $cfgRelation = PMA_getRelationsParam();
495 // Gets the list of fields properties
496 if (isset($result) && $result) {
497 while ($field = PMA_mysql_fetch_field($result)) {
498 $fields_meta[] = $field;
500 $fields_cnt = count($fields_meta);
502 // Displays the results in a table
503 include('./libraries/display_tbl.lib.php3');
504 if (empty($disp_mode)) {
505 // see the "PMA_setDisplayMode()" function in
506 // libraries/display_tbl.lib.php3
507 $disp_mode = 'urdr111101';
509 PMA_displayTable($result, $disp_mode);
510 mysql_free_result($result);
512 if ($disp_mode[6] == '1' ||
$disp_mode[9] == '1') {
516 // Displays "Insert a new row" link if required
517 if ($disp_mode[6] == '1') {
518 $lnk_goto = 'sql.php3'
520 . '&convcharset=' . $convcharset
521 . '&server=' . $server
522 . '&db=' . urlencode($db)
523 . '&table=' . urlencode($table)
525 . '&session_max_rows=' . $session_max_rows
526 . '&disp_direction=' . $disp_direction
527 . '&repeat_cells=' . $repeat_cells
528 . '&sql_query=' . urlencode($sql_query);
529 $url_query = '?lang=' . $lang
530 . '&convcharset=' . $convcharset
531 . '&server=' . $server
532 . '&db=' . urlencode($db)
533 . '&table=' . urlencode($table)
535 . '&session_max_rows=' . $session_max_rows
536 . '&disp_direction=' . $disp_direction
537 . '&repeat_cells=' . $repeat_cells
538 . '&sql_query=' . urlencode($sql_query)
539 . '&goto=' . urlencode($lnk_goto);
541 echo ' <!-- Insert a new row -->' . "\n"
542 . ' <a href="tbl_change.php3' . $url_query . '">' . $strInsertNewRow . '</a>';
543 if ($disp_mode[9] == '1') {
547 } // end insert new row
549 // Displays "printable view" link if required
550 if ($disp_mode[9] == '1') {
551 $url_query = '?lang=' . $lang
552 . '&convcharset=' . $convcharset
553 . '&server=' . $server
554 . '&db=' . urlencode($db)
555 . '&table=' . urlencode($table)
557 . '&session_max_rows=' . $session_max_rows
558 . '&disp_direction=' . $disp_direction
559 . '&repeat_cells=' . $repeat_cells
561 . (($dontlimitchars == '1') ?
'&dontlimitchars=1' : '')
562 . '&sql_query=' . urlencode($sql_query);
563 echo ' <!-- Print view -->' . "\n"
564 . ' <a href="sql.php3' . $url_query . '" target="print_view">' . $strPrintView . '</a>' . "\n";
565 } // end displays "printable view"
570 // Bookmark Support if required
571 if ($disp_mode[7] == '1'
572 && ($cfg['Bookmark']['db'] && $cfg['Bookmark']['table'] && empty($id_bookmark))
573 && !empty($sql_query)) {
578 . '&convcharset=' . $convcharset
579 . '&server=' . $server
580 . '&db=' . urlencode($db)
581 . '&table=' . urlencode($table)
583 . '&session_max_rows=' . $session_max_rows
584 . '&disp_direction=' . $disp_direction
585 . '&repeat_cells=' . $repeat_cells
586 . '&sql_query=' . urlencode($sql_query)
587 . '&id_bookmark=1';
589 <!-- Bookmark the query
-->
590 <form action
="sql.php3" method
="post" onsubmit
="return emptyFormElements(this, 'fields[label]');">
593 if ($disp_mode[3] == '1') {
594 echo ' <i>' . $strOr . '</i>' . "\n";
598 <?php
echo $strBookmarkLabel; ?
> 
;:
599 <input type
="hidden" name
="server" value
="<?php echo $server; ?>" />
600 <input type
="hidden" name
="goto" value
="<?php echo $goto; ?>" />
601 <input type
="hidden" name
="fields[dbase]" value
="<?php echo $db; ?>" />
602 <input type
="hidden" name
="fields[user]" value
="<?php echo $cfg['Bookmark']['user']; ?>" />
603 <input type
="hidden" name
="fields[query]" value
="<?php echo urlencode($sql_query); ?>" />
604 <input type
="text" name
="fields[label]" value
="" />
605 <input type
="submit" name
="store_bkm" value
="<?php echo $strBookmarkThis; ?>" />
608 } // end bookmark support
610 // Do print the page if required
611 if (isset($printview) && $printview == '1') {
614 <script type
="text/javascript" language
="javascript1.2">
617 if (typeof(window
.print) != 'undefined') {
624 } // end rows returned
626 } // end executes the query
631 * Displays the footer
633 require('./footer.inc.php3');