3 // vim: expandtab sw=4 ts=4 sts=4:
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)) ?
$cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
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);
74 $sql_str = ereg_replace(' +', ' ', $sql_str);
76 // GROUP or ORDER: "BY" to uppercase too
77 $sql_str = eregi_replace('(GROUP|ORDER) BY', '\\1 BY', $sql_str);
80 } // end of the "PMA_sqlFormat()" function
84 * Check rights in case of DROP DATABASE
86 * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
87 * but since a malicious user may pass this variable by url/form, we don't take
88 * into account this case.
90 if (!defined('PMA_CHK_DROP')
91 && !$cfg['AllowUserDropDatabase']
92 && eregi('DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE[[:space:]]', $sql_query)) {
93 // Checks if the user is a Superuser
94 // TODO: set a global variable with this information
95 // loic1: optimized query
96 $result = @PMA_mysql_query
('USE mysql');
97 if (PMA_mysql_error()) {
98 include('./header.inc.php3');
99 PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
107 if (isset($store_bkm)) {
108 if (get_magic_quotes_gpc()) {
109 $fields['label'] = stripslashes($fields['label']);
111 include('./libraries/bookmark.lib.php3');
112 PMA_addBookmarks($fields, $cfg['Bookmark']);
113 header('Location: ' . $cfg['PmaAbsoluteUri'] . $goto);
118 * Gets the true sql query
120 // $sql_query has been urlencoded in the confirmation form for drop/delete
121 // queries or in the navigation bar for browsing among records
122 if (isset($btnDrop) ||
isset($navig)) {
123 $sql_query = urldecode($sql_query);
126 // SK -- Patch : Reformats query - adds spaces when omitted and removes extra
127 // spaces; converts reserved words to uppercase
128 $sql_query = PMA_sqlFormat($sql_query);
131 // If the query is a Select, extract the db and table names and modify
132 // $db and $table, to have correct page headers, links and left frame.
133 // db and table name may be enclosed with backquotes, db is optionnal,
134 // query may contain aliases.
135 // (todo: check for embedded comments...)
137 // (todo: if there are more than one table name in the Select:
138 // - do not extract the first table name
139 // - do not show a table name in the page header
140 // - do not display the sub-pages links)
142 $is_select = eregi('^SELECT[[:space:]]+', $sql_query);
144 eregi('^SELECT[[:space:]]+(.*)[[:space:]]+FROM[[:space:]]+(`[^`]+`|[A-Za-z0-9_$]+)([\.]*)(`[^`]*`|[A-Za-z0-9_$]*)', $sql_query, $tmp);
146 if ($tmp[3] == '.') {
148 $db = str_replace('`', '', $tmp[2]);
149 $reload = ($db == $prev_db) ?
0 : 1;
150 $table = str_replace('`', '', $tmp[4]);
153 $table = str_replace('`', '', $tmp[2]);
159 * Sets or modifies the $goto variable if required
161 if ($goto == 'sql.php3') {
164 . '&convcharset=' . $convcharset
165 . '&server=' . $server
166 . '&db=' . urlencode($db)
167 . '&table=' . urlencode($table)
169 . '&sql_query=' . urlencode($sql_query);
174 * Go back to further page if table should not be dropped
176 if (isset($btnDrop) && $btnDrop == $strNo) {
181 if (strpos(' ' . $goto, 'db_details') == 1 && !empty($table)) {
184 include('./' . ereg_replace('\.\.*', '.', $goto));
186 header('Location: ' . $cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
193 * Displays the confirm page if required
195 * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
196 * with js) because possible security issue is not so important here: at most,
197 * the confirm message isn't displayed.
199 * Also bypassed if only showing php code.or validating a SQL query
202 ||
(isset($is_js_confirmed) && $is_js_confirmed)
204 ||
!empty($GLOBALS['show_as_php'])
205 ||
!empty($GLOBALS['validatequery'])) {
208 /* SQL-Parser-Analyzer */
209 $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));
213 if (get_magic_quotes_gpc()) {
214 $stripped_sql_query = stripslashes($sql_query);
216 $stripped_sql_query = $sql_query;
218 include('./header.inc.php3');
219 echo $strDoYouReally . ' :<br />' . "\n";
220 echo '<tt>' . htmlspecialchars($stripped_sql_query) . '</tt> ?<br/>' . "\n";
222 <form action
="sql.php3" method
="post">
223 <input type
="hidden" name
="lang" value
="<?php echo $lang; ?>" />
224 <input type
="hidden" name
="convcharset" value
="<?php echo $convcharset; ?>" />
225 <input type
="hidden" name
="server" value
="<?php echo $server; ?>" />
226 <input type
="hidden" name
="db" value
="<?php echo $db; ?>" />
227 <input type
="hidden" name
="table" value
="<?php echo isset($table) ? $table : ''; ?>" />
228 <input type
="hidden" name
="sql_query" value
="<?php echo urlencode($sql_query); ?>" />
229 <input type
="hidden" name
="zero_rows" value
="<?php echo isset($zero_rows) ? $zero_rows : ''; ?>" />
230 <input type
="hidden" name
="goto" value
="<?php echo $goto; ?>" />
231 <input type
="hidden" name
="back" value
="<?php echo isset($back) ? $back : ''; ?>" />
232 <input type
="hidden" name
="reload" value
="<?php echo isset($reload) ? $reload : 0; ?>" />
233 <input type
="hidden" name
="show_query" value
="<?php echo isset($show_query) ? $show_query : ''; ?>" />
234 <input type
="submit" name
="btnDrop" value
="<?php echo $strYes; ?>" />
235 <input type
="submit" name
="btnDrop" value
="<?php echo $strNo; ?>" />
243 * Executes the query and displays results
246 if (!isset($sql_query)) {
248 } else if (get_magic_quotes_gpc()) {
249 $sql_query = stripslashes($sql_query);
251 // Defines some variables
252 // loic1: A table has to be created -> left frame should be reloaded
253 if ((!isset($reload) ||
$reload == 0)
254 && eregi('^CREATE TABLE[[:space:]]+(.*)', $sql_query)) {
257 // Gets the number of rows per page
258 if (!isset($session_max_rows)) {
259 $session_max_rows = $cfg['MaxRows'];
260 } else if ($session_max_rows != 'all') {
261 $cfg['MaxRows'] = $session_max_rows;
263 // Defines the display mode (horizontal/vertical) and header "frequency"
264 if (empty($disp_direction)) {
265 $disp_direction = $cfg['DefaultDisplay'];
267 if (empty($repeat_cells)) {
268 $repeat_cells = $cfg['RepeatCells'];
271 // SK -- Patch: $is_group added for use in calculation of total number of
273 // $is_count is changed for more correct "LIMIT" clause
274 // appending in queries like
275 // "SELECT COUNT(...) FROM ... GROUP BY ..."
276 $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = FALSE;
277 if ($is_select) { // see line 141
278 $is_group = eregi('[[:space:]]+(GROUP BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+', $sql_query);
279 $is_func = !$is_group && (eregi('[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(', $sql_query));
280 $is_count = !$is_group && (eregi('^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)', $sql_query));
281 $is_export = (eregi('[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+', $sql_query));
282 $is_analyse = (eregi('[[:space:]]+PROCEDURE[[:space:]]+ANALYSE\(', $sql_query));
283 } else if (eregi('^EXPLAIN[[:space:]]+', $sql_query)) {
285 } else if (eregi('^DELETE[[:space:]]+', $sql_query)) {
288 } else if (eregi('^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+', $sql_query)) {
291 } else if (eregi('^UPDATE[[:space:]]+', $sql_query)) {
293 } else if (eregi('^SHOW[[:space:]]+', $sql_query)) {
295 } else if (eregi('^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+', $sql_query)) {
299 // Do append a "LIMIT" clause?
301 && (!$cfg['ShowAll'] ||
$session_max_rows != 'all')
303 && !($is_count ||
$is_export ||
$is_func ||
$is_analyse)
304 && eregi('[[:space:]]FROM[[:space:]]', $sql_query)
305 && !eregi('[[:space:]]LIMIT[[:space:]0-9,-]+$', $sql_query)) {
306 $sql_limit_to_append = " LIMIT $pos, ".$cfg['MaxRows'];
307 if (eregi('(.*)([[:space:]](PROCEDURE[[:space:]](.*)|FOR[[:space:]]+UPDATE|LOCK[[:space:]]+IN[[:space:]]+SHARE[[:space:]]+MODE))$', $sql_query, $regs)) {
308 $full_sql_query = $regs[1] . $sql_limit_to_append . $regs[2];
310 $full_sql_query = $sql_query . $sql_limit_to_append;
313 $full_sql_query = $sql_query;
316 PMA_mysql_select_db($db);
318 // If the query is a DELETE query with no WHERE clause, get the number of
319 // rows that will be deleted (mysql_affected_rows will always return 0 in
322 && eregi('^DELETE([[:space:]].+)?([[:space:]]FROM[[:space:]](.+))$', $sql_query, $parts)
323 && !eregi('[[:space:]]WHERE[[:space:]]', $parts[3])) {
324 $cnt_all_result = @PMA_mysql_query
('SELECT COUNT(*) as count' . $parts[2]);
325 if ($cnt_all_result) {
326 $num_rows = PMA_mysql_result($cnt_all_result, 0, 'count');
327 mysql_free_result($cnt_all_result);
332 // Executes the query
333 // Only if we didn't ask to see the php code (mikebeck)
334 if (!empty($GLOBALS['show_as_php']) ||
!empty($GLOBALS['validatequery'])) {
339 $result = @PMA_mysql_query
($full_sql_query);
340 // Displays an error message if required and stop parsing the script
341 if (PMA_mysql_error()) {
342 $error = PMA_mysql_error();
343 include('./header.inc.php3');
344 $full_err_url = (ereg('^(db_details|tbl_properties)', $err_url))
345 ?
$err_url . '&show_query=1&sql_query=' . urlencode($sql_query)
347 PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
350 // tmpfile remove after convert encoding appended by Y.Kawada
351 if (function_exists('PMA_kanji_file_conv')
352 && (isset($textfile) && file_exists($textfile))) {
356 // Gets the number of rows affected/returned
358 $num_rows = ($result) ? @mysql_num_rows
($result) : 0;
359 } else if (!isset($num_rows)) {
360 $num_rows = @mysql_affected_rows
();
363 // Counts the total number of rows for the same 'SELECT' query without the
364 // 'LIMIT' clause that may have been programatically added
365 if (empty($sql_limit_to_append)) {
366 $unlim_num_rows = $num_rows;
368 else if ($is_select) {
369 // SK -- Patch : correct calculations for GROUP BY, HAVING, DISTINCT
371 // Reads only the from-part of the query...
372 // NOTE: here the presence of LIMIT is impossible, HAVING and GROUP BY
373 // are necessary for correct calculation, and extra spaces and
374 // lowercase reserved words are removed, so we have a simple split
377 $array = split('[[:space:]]+(FROM|ORDER BY)[[:space:]]+', $sql_query);
379 // if $array[1] is empty here, there is an error in the query:
380 // "... FROM [ORDER BY ...]", but the query is already executed with
381 // success so this check is redundant???
383 if (!empty($array[1])) {
384 // ... and makes a count(*) to count the entries
385 // Special case: SELECT DISTINCT ... FROM ...
386 // the count of resulting rows can be found as:
387 // SELECT COUNT(DISTINCT ...) FROM ...
388 if (eregi('^SELECT DISTINCT(.*)', $array[0], $array_dist)) {
389 $count_what = 'DISTINCT ' . $array_dist[1];
393 $count_query = 'SELECT COUNT(' . $count_what . ') AS count FROM ' . $array[1];
394 if ($cnt_all_result = mysql_query($count_query)) {
396 $unlim_num_rows = @mysql_num_rows
($cnt_all_result);
398 $unlim_num_rows = mysql_result($cnt_all_result, 0, 'count');
400 mysql_free_result($cnt_all_result);
405 } // end rows total count
406 } // end else "didn't ask to see php code"
408 // No rows returned -> move back to the calling page
409 if ($num_rows < 1 ||
$is_affected) {
411 $message = $strDeletedRows . ' ' . $num_rows;
412 } else if ($is_insert) {
413 $message = $strInsertedRows . ' ' . $num_rows;
414 } else if ($is_affected) {
415 $message = $strAffectedRows . ' ' . $num_rows;
416 } else if (!empty($zero_rows)) {
417 $message = $zero_rows;
418 } else if (!empty($GLOBALS['show_as_php'])) {
420 } else if (!empty($GLOBALS['validatequery'])) {
421 $message = $strValidateSQL;
423 $message = $strEmptyResultSet;
427 $goto = ereg_replace('\.\.*', '.', $goto);
428 // Checks for a valid target script
429 if (isset($table) && $table == '') {
432 if (isset($db) && $db == '') {
435 $is_db = $is_table = FALSE;
436 if (strpos(' ' . $goto, 'tbl_properties') == 1) {
437 if (!isset($table)) {
438 $goto = 'db_details.php3';
440 $is_table = @PMA_mysql_query
('SHOW TABLES LIKE \'' . PMA_sqlAddslashes($table, TRUE) . '\'');
441 if (!($is_table && @mysql_numrows
($is_table))) {
442 $goto = 'db_details.php3';
445 } // end if... else...
447 if (strpos(' ' . $goto, 'db_details') == 1) {
454 $is_db = @PMA_mysql_select_db
($db);
459 } // end if... else...
461 // Loads to target script
462 if (strpos(' ' . $goto, 'db_details') == 1
463 ||
strpos(' ' . $goto, 'tbl_properties') == 1) {
464 $js_to_run = 'functions.js';
466 if ($goto != 'main.php3') {
467 include('./header.inc.php3');
469 include('./' . $goto);
470 } // end if file_exist
472 header('Location: ' . $cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
475 } // end no rows returned
477 // At least one row is returned -> displays a table with results
479 // Displays the headers
480 if (isset($show_query)) {
483 if (isset($printview) && $printview == '1') {
484 include('./header_printview.inc.php3');
486 $js_to_run = 'functions.js';
488 if (!empty($table)) {
489 include('./tbl_properties_common.php3');
490 $url_query .= '&goto=tbl_properties.php3&back=tbl_properties.php3';
491 include('./tbl_properties_table_info.php3');
494 include('./db_details_common.php3');
495 include('./db_details_db_info.php3');
497 include('./libraries/relation.lib.php3');
498 $cfgRelation = PMA_getRelationsParam();
501 // Gets the list of fields properties
502 if (isset($result) && $result) {
503 while ($field = PMA_mysql_fetch_field($result)) {
504 $fields_meta[] = $field;
506 $fields_cnt = count($fields_meta);
508 // Displays the results in a table
509 include('./libraries/display_tbl.lib.php3');
510 if (empty($disp_mode)) {
511 // see the "PMA_setDisplayMode()" function in
512 // libraries/display_tbl.lib.php3
513 $disp_mode = 'urdr111101';
515 if (!isset($dontlimitchars)) {
519 $parsed_sql = PMA_SQP_parse($sql_query);
520 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
522 PMA_displayTable($result, $disp_mode, $analyzed_sql);
523 mysql_free_result($result);
525 if ($disp_mode[6] == '1' ||
$disp_mode[9] == '1') {
529 // Displays "Insert a new row" link if required
530 if ($disp_mode[6] == '1') {
531 $lnk_goto = 'sql.php3'
533 . '&convcharset=' . $convcharset
534 . '&server=' . $server
535 . '&db=' . urlencode($db)
536 . '&table=' . urlencode($table)
538 . '&session_max_rows=' . $session_max_rows
539 . '&disp_direction=' . $disp_direction
540 . '&repeat_cells=' . $repeat_cells
541 . '&dontlimitchars=' . $dontlimitchars
542 . '&sql_query=' . urlencode($sql_query);
543 $url_query = '?lang=' . $lang
544 . '&convcharset=' . $convcharset
545 . '&server=' . $server
546 . '&db=' . urlencode($db)
547 . '&table=' . urlencode($table)
549 . '&session_max_rows=' . $session_max_rows
550 . '&disp_direction=' . $disp_direction
551 . '&repeat_cells=' . $repeat_cells
552 . '&dontlimitchars=' . $dontlimitchars
553 . '&sql_query=' . urlencode($sql_query)
554 . '&goto=' . urlencode($lnk_goto);
556 echo ' <!-- Insert a new row -->' . "\n"
557 . ' <a href="tbl_change.php3' . $url_query . '">' . $strInsertNewRow . '</a>';
558 if ($disp_mode[9] == '1') {
562 } // end insert new row
564 // Displays "printable view" link if required
565 if ($disp_mode[9] == '1') {
566 $url_query = '?lang=' . $lang
567 . '&convcharset=' . $convcharset
568 . '&server=' . $server
569 . '&db=' . urlencode($db)
570 . '&table=' . urlencode($table)
572 . '&session_max_rows=' . $session_max_rows
573 . '&disp_direction=' . $disp_direction
574 . '&repeat_cells=' . $repeat_cells
576 . ((isset($dontlimitchars) && $dontlimitchars == '1') ?
'&dontlimitchars=1' : '')
577 . '&sql_query=' . urlencode($sql_query);
578 echo ' <!-- Print view -->' . "\n"
579 . ' <a href="sql.php3' . $url_query . '" target="print_view">' . $strPrintView . '</a>' . "\n";
580 } // end displays "printable view"
585 // Bookmark Support if required
586 if ($disp_mode[7] == '1'
587 && ($cfg['Bookmark']['db'] && $cfg['Bookmark']['table'] && empty($id_bookmark))
588 && !empty($sql_query)) {
593 . '&convcharset=' . $convcharset
594 . '&server=' . $server
595 . '&db=' . urlencode($db)
596 . '&table=' . urlencode($table)
598 . '&session_max_rows=' . $session_max_rows
599 . '&disp_direction=' . $disp_direction
600 . '&repeat_cells=' . $repeat_cells
601 . '&dontlimitchars=' . $dontlimitchars
602 . '&sql_query=' . urlencode($sql_query)
603 . '&id_bookmark=1';
605 <!-- Bookmark the query
-->
606 <form action
="sql.php3" method
="post" onsubmit
="return emptyFormElements(this, 'fields[label]');">
609 if ($disp_mode[3] == '1') {
610 echo ' <i>' . $strOr . '</i>' . "\n";
614 <?php
echo $strBookmarkLabel; ?
> 
;:
615 <input type
="hidden" name
="server" value
="<?php echo $server; ?>" />
616 <input type
="hidden" name
="goto" value
="<?php echo $goto; ?>" />
617 <input type
="hidden" name
="fields[dbase]" value
="<?php echo $db; ?>" />
618 <input type
="hidden" name
="fields[user]" value
="<?php echo $cfg['Bookmark']['user']; ?>" />
619 <input type
="hidden" name
="fields[query]" value
="<?php echo urlencode($sql_query); ?>" />
620 <input type
="text" name
="fields[label]" value
="" />
621 <input type
="submit" name
="store_bkm" value
="<?php echo $strBookmarkThis; ?>" />
624 } // end bookmark support
626 // Do print the page if required
627 if (isset($printview) && $printview == '1') {
630 <script type
="text/javascript" language
="javascript1.2">
633 if (typeof(window
.print) != 'undefined') {
640 } // end rows returned
642 } // end executes the query
647 * Displays the footer
649 require('./footer.inc.php3');