home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / Servidores / xampp-win32-1.6.7-installer.exe / phpMyAdmin / sql.php < prev    next >
PHP Script  |  2008-06-23  |  29KB  |  772 lines

  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.  *          what returns 0 rows - to prevent cyclic redirects or includes
  6.  * @version $Id: sql.php 11163 2008-03-16 11:28:18Z lem9 $
  7.  */
  8.  
  9. /**
  10.  * Gets some core libraries
  11.  */
  12. require_once './libraries/common.inc.php';
  13. require_once './libraries/Table.class.php';
  14. require_once './libraries/tbl_indexes.lib.php';
  15. require_once './libraries/check_user_privileges.lib.php';
  16. require_once './libraries/bookmark.lib.php';
  17.  
  18. /**
  19.  * Defines the url to return to in case of error in a sql statement
  20.  */
  21. // Security checkings
  22. if (!empty($goto)) {
  23.     $is_gotofile     = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
  24.     if (!@file_exists('./' . $is_gotofile)) {
  25.         unset($goto);
  26.     } else {
  27.         $is_gotofile = ($is_gotofile == $goto);
  28.     }
  29. } // end if (security checkings)
  30.  
  31. if (empty($goto)) {
  32.     $goto = (! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
  33.     $is_gotofile  = true;
  34. } // end if
  35. if (!isset($err_url)) {
  36.     $err_url = (!empty($back) ? $back : $goto)
  37.              . '?' . PMA_generate_common_url($db)
  38.              . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table)) ? '&table=' . urlencode($table) : '');
  39. } // end if
  40.  
  41. // Coming from a bookmark dialog
  42. if (isset($fields['query'])) {
  43.     $sql_query = $fields['query'];
  44. }
  45.  
  46. // This one is just to fill $db
  47. if (isset($fields['dbase'])) {
  48.     $db = $fields['dbase'];
  49. }
  50.  
  51. // Default to browse if no query set and we have table
  52. // (needed for browsing from DefaultTabTable)
  53. if (empty($sql_query) && strlen($table) && strlen($db)) {
  54.     require_once './libraries/bookmark.lib.php';
  55.     $book_sql_query = PMA_queryBookmarks($db,
  56.         $GLOBALS['cfg']['Bookmark'], '\'' . PMA_sqlAddslashes($table) . '\'',
  57.         'label');
  58.  
  59.     if (! empty($book_sql_query)) {
  60.         $sql_query = $book_sql_query;
  61.     } else {
  62.         $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
  63.     }
  64.     unset($book_sql_query);
  65.  
  66.     // set $goto to what will be displayed if query returns 0 rows
  67.     $goto = 'tbl_structure.php';
  68. } else {
  69.     // Now we can check the parameters
  70.     PMA_checkParameters(array('sql_query'));
  71. }
  72.  
  73. // instead of doing the test twice
  74. $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
  75.     $sql_query);
  76.  
  77. /**
  78.  * Check rights in case of DROP DATABASE
  79.  *
  80.  * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
  81.  * but since a malicious user may pass this variable by url/form, we don't take
  82.  * into account this case.
  83.  */
  84. if (!defined('PMA_CHK_DROP')
  85.  && !$cfg['AllowUserDropDatabase']
  86.  && $is_drop_database
  87.  && !$is_superuser) {
  88.     require_once './libraries/header.inc.php';
  89.     PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
  90. } // end if
  91.  
  92. require_once './libraries/display_tbl.lib.php';
  93. PMA_displayTable_checkConfigParams();
  94.  
  95. /**
  96.  * Need to find the real end of rows?
  97.  */
  98. if (isset($find_real_end) && $find_real_end) {
  99.     $unlim_num_rows = PMA_Table::countRecords($db, $table, true, true);
  100.     $_SESSION['userconf']['pos'] = @((ceil($unlim_num_rows / $_SESSION['userconf']['max_rows']) - 1) * $_SESSION['userconf']['max_rows']);
  101. }
  102.  
  103.  
  104. /**
  105.  * Bookmark add
  106.  */
  107. if (isset($store_bkm)) {
  108.     PMA_addBookmarks($fields, $cfg['Bookmark'], (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
  109.     PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto);
  110. } // end if
  111.  
  112. /**
  113.  * Parse and analyze the query
  114.  */
  115. require_once './libraries/parse_analyze.lib.php';
  116.  
  117. /**
  118.  * Sets or modifies the $goto variable if required
  119.  */
  120. if ($goto == 'sql.php') {
  121.     $is_gotofile = false;
  122.     $goto = 'sql.php?'
  123.           . PMA_generate_common_url($db, $table)
  124.           . '&sql_query=' . urlencode($sql_query);
  125. } // end if
  126.  
  127.  
  128. /**
  129.  * Go back to further page if table should not be dropped
  130.  */
  131. if (isset($btnDrop) && $btnDrop == $strNo) {
  132.     if (!empty($back)) {
  133.         $goto = $back;
  134.     }
  135.     if ($is_gotofile) {
  136.         if (strpos(' ' . $goto, 'db_') == 1 && strlen($table)) {
  137.             $table = '';
  138.         }
  139.         $active_page = $goto;
  140.         require './' . PMA_securePath($goto);
  141.     } else {
  142.         PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
  143.     }
  144.     exit();
  145. } // end if
  146.  
  147.  
  148. /**
  149.  * Displays the confirm page if required
  150.  *
  151.  * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
  152.  * with js) because possible security issue is not so important here: at most,
  153.  * the confirm message isn't displayed.
  154.  *
  155.  * Also bypassed if only showing php code.or validating a SQL query
  156.  */
  157. if (! $cfg['Confirm'] || isset($_REQUEST['is_js_confirmed']) || isset($btnDrop)
  158.  // if we are coming from a "Create PHP code" or a "Without PHP Code"
  159.  // dialog, we won't execute the query anyway, so don't confirm
  160.  //|| !empty($GLOBALS['show_as_php'])
  161.  || isset($GLOBALS['show_as_php'])
  162.  || !empty($GLOBALS['validatequery'])) {
  163.     $do_confirm = false;
  164. } else {
  165.     $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
  166. }
  167.  
  168. if ($do_confirm) {
  169.     $stripped_sql_query = $sql_query;
  170.     require_once './libraries/header.inc.php';
  171.     if ($is_drop_database) {
  172.         echo '<h1 class="warning">' . $strDropDatabaseStrongWarning . '</h1>';
  173.     }
  174.     echo '<form action="sql.php" method="post">' . "\n"
  175.         .PMA_generate_common_hidden_inputs($db, $table);
  176.     ?>
  177.     <input type="hidden" name="sql_query" value="<?php echo htmlspecialchars($sql_query); ?>" />
  178.     <input type="hidden" name="zero_rows" value="<?php echo isset($zero_rows) ? PMA_sanitize($zero_rows) : ''; ?>" />
  179.     <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  180.     <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back) : ''; ?>" />
  181.     <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload) : 0; ?>" />
  182.     <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge) : ''; ?>" />
  183.     <input type="hidden" name="cpurge" value="<?php echo isset($cpurge) ? PMA_sanitize($cpurge) : ''; ?>" />
  184.     <input type="hidden" name="purgekey" value="<?php echo isset($purgekey) ? PMA_sanitize($purgekey) : ''; ?>" />
  185.     <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query) : ''; ?>" />
  186.     <?php
  187.     echo '<fieldset class="confirmation">' . "\n"
  188.         .'    <legend>' . $strDoYouReally . '</legend>'
  189.         .'    <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
  190.         .'</fieldset>' . "\n"
  191.         .'<fieldset class="tblFooters">' . "\n";
  192.     ?>
  193.     <input type="submit" name="btnDrop" value="<?php echo $strYes; ?>" id="buttonYes" />
  194.     <input type="submit" name="btnDrop" value="<?php echo $strNo; ?>" id="buttonNo" />
  195.     <?php
  196.     echo '</fieldset>' . "\n"
  197.        . '</form>' . "\n";
  198.  
  199.     /**
  200.      * Displays the footer and exit
  201.      */
  202.     require_once './libraries/footer.inc.php';
  203. } // end if $do_confirm
  204.  
  205.  
  206. // Defines some variables
  207. // A table has to be created, renamed, dropped -> navi frame should be reloaded
  208. /**
  209.  * @todo use the parser/analyzer
  210.  */
  211.  
  212. if (empty($reload)
  213.     && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
  214.     $reload = 1;
  215. }
  216.  
  217. // SK -- Patch: $is_group added for use in calculation of total number of
  218. //              rows.
  219. //              $is_count is changed for more correct "LIMIT" clause
  220. //              appending in queries like
  221. //                "SELECT COUNT(...) FROM ... GROUP BY ..."
  222.  
  223. /**
  224.  * @todo detect all this with the parser, to avoid problems finding
  225.  * those strings in comments or backquoted identifiers
  226.  */
  227.  
  228. $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;
  229. if ($is_select) { // see line 141
  230.     $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
  231.     $is_func =  !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
  232.     $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
  233.     $is_export   = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
  234.     $is_analyse  = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
  235. } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
  236.     $is_explain  = true;
  237. } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
  238.     $is_delete   = true;
  239.     $is_affected = true;
  240. } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
  241.     $is_insert   = true;
  242.     $is_affected = true;
  243.     if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
  244.         $is_replace = true;
  245.     }
  246. } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
  247.     $is_affected = true;
  248. } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
  249.     $is_show     = true;
  250. } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
  251.     $is_maint    = true;
  252. }
  253.  
  254. // Do append a "LIMIT" clause?
  255. if ((! $cfg['ShowAll'] || $_SESSION['userconf']['max_rows'] != 'all')
  256.  && ! ($is_count || $is_export || $is_func || $is_analyse)
  257.  && isset($analyzed_sql[0]['queryflags']['select_from'])
  258.  && ! isset($analyzed_sql[0]['queryflags']['offset'])
  259.  && empty($analyzed_sql[0]['limit_clause'])
  260.  ) {
  261.     $sql_limit_to_append = ' LIMIT ' . $_SESSION['userconf']['pos'] . ', ' . $_SESSION['userconf']['max_rows'] . " ";
  262.  
  263.     $full_sql_query  = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
  264.     /**
  265.      * @todo pretty printing of this modified query
  266.      */
  267.     if (isset($display_query)) {
  268.         // if the analysis of the original query revealed that we found
  269.         // a section_after_limit, we now have to analyze $display_query
  270.         // to display it correctly
  271.  
  272.         if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
  273.             $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
  274.             $display_query  = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
  275.         }
  276.     }
  277.  
  278. } else {
  279.     $full_sql_query      = $sql_query;
  280. } // end if...else
  281.  
  282. if (strlen($db)) {
  283.     PMA_DBI_select_db($db);
  284. }
  285.  
  286. // If the query is a DELETE query with no WHERE clause, get the number of
  287. // rows that will be deleted (mysql_affected_rows will always return 0 in
  288. // this case)
  289. // Note: testing shows that this no longer applies since MySQL 4.0.x
  290.  
  291. if (PMA_MYSQL_INT_VERSION < 40000) {
  292.     if ($is_delete
  293.         && preg_match('@^DELETE([[:space:]].+)?(FROM[[:space:]](.+))$@i', $sql_query, $parts)
  294.         && !preg_match('@[[:space:]]WHERE[[:space:]]@i', $parts[3])) {
  295.         $cnt_all_result = @PMA_DBI_try_query('SELECT COUNT(*) as count ' .  $parts[2]);
  296.         if ($cnt_all_result) {
  297.             list($num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  298.             PMA_DBI_free_result($cnt_all_result);
  299.         } else {
  300.             $num_rows   = 0;
  301.         }
  302.     }
  303. }
  304.  
  305. //  E x e c u t e    t h e    q u e r y
  306.  
  307. // Only if we didn't ask to see the php code (mikebeck)
  308. if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
  309.     unset($result);
  310.     $num_rows = 0;
  311. } else {
  312.     if (isset($_SESSION['profiling']) && PMA_profilingSupported()) {
  313.         PMA_DBI_query('SET PROFILING=1;');
  314.     }
  315.         
  316.     // garvin: Measure query time.
  317.     // TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
  318.     $querytime_before = array_sum(explode(' ', microtime()));
  319.  
  320.     $result   = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
  321.  
  322.     $querytime_after = array_sum(explode(' ', microtime()));
  323.  
  324.     $GLOBALS['querytime'] = $querytime_after - $querytime_before;
  325.  
  326.     // Displays an error message if required and stop parsing the script
  327.     if ($error        = PMA_DBI_getError()) {
  328.         require_once './libraries/header.inc.php';
  329.         $full_err_url = (preg_match('@^(db|tbl)_@', $err_url))
  330.                       ? $err_url . '&show_query=1&sql_query=' . urlencode($sql_query)
  331.                       : $err_url;
  332.         PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
  333.     }
  334.     unset($error);
  335.  
  336.     // Gets the number of rows affected/returned
  337.     // (This must be done immediately after the query because
  338.     // mysql_affected_rows() reports about the last query done)
  339.  
  340.     if (!$is_affected) {
  341.         $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
  342.     } elseif (!isset($num_rows)) {
  343.         $num_rows = @PMA_DBI_affected_rows();
  344.     }
  345.  
  346.     // Grabs the profiling results
  347.     if (isset($_SESSION['profiling']) && PMA_profilingSupported() ) {
  348.         $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
  349.     }
  350.         
  351.     // Checks if the current database has changed
  352.     // This could happen if the user sends a query like "USE `database`;"
  353.     $res = PMA_DBI_query('SELECT DATABASE() AS \'db\';');
  354.     $row = PMA_DBI_fetch_row($res);
  355.     if (strlen($db) && is_array($row) && isset($row[0]) && (strcasecmp($db, $row[0]) != 0)) {
  356.         $db     = $row[0];
  357.         $reload = 1;
  358.     }
  359.     @PMA_DBI_free_result($res);
  360.     unset($res, $row);
  361.  
  362.     // tmpfile remove after convert encoding appended by Y.Kawada
  363.     if (function_exists('PMA_kanji_file_conv')
  364.         && (isset($textfile) && file_exists($textfile))) {
  365.         unlink($textfile);
  366.     }
  367.  
  368.     // Counts the total number of rows for the same 'SELECT' query without the
  369.     // 'LIMIT' clause that may have been programatically added
  370.  
  371.     if (empty($sql_limit_to_append)) {
  372.         $unlim_num_rows         = $num_rows;
  373.         // if we did not append a limit, set this to get a correct
  374.         // "Showing rows..." message
  375.         //$_SESSION['userconf']['max_rows'] = 'all';
  376.     } elseif ($is_select) {
  377.  
  378.         //    c o u n t    q u e r y
  379.  
  380.         // If we are "just browsing", there is only one table,
  381.         // and no where clause (or just 'WHERE 1 '),
  382.         // so we do a quick count (which uses MaxExactCount)
  383.         // because SQL_CALC_FOUND_ROWS
  384.         // is not quick on large InnoDB tables
  385.  
  386.         // but do not count again if we did it previously
  387.         // due to $find_real_end == true
  388.  
  389.         if (!$is_group
  390.          && !isset($analyzed_sql[0]['queryflags']['union'])
  391.          && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
  392.          && (empty($analyzed_sql[0]['where_clause'])
  393.            || $analyzed_sql[0]['where_clause'] == '1 ')
  394.          && !isset($find_real_end)
  395.         ) {
  396.  
  397.             // "j u s t   b r o w s i n g"
  398.             $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
  399.  
  400.         } else { // n o t   " j u s t   b r o w s i n g "
  401.  
  402.             if (PMA_MYSQL_INT_VERSION < 40000) {
  403.  
  404.                 // detect this case:
  405.                 // SELECT DISTINCT x AS foo, y AS bar FROM sometable
  406.  
  407.                 if (isset($analyzed_sql[0]['queryflags']['distinct'])) {
  408.                     $count_what = 'DISTINCT ';
  409.                     $first_expr = true;
  410.                     foreach ($analyzed_sql[0]['select_expr'] as $part) {
  411.                         $count_what .= (!$first_expr ? ', ' : '') . $part['expr'];
  412.                         $first_expr = false;
  413.                     }
  414.                 } else {
  415.                     $count_what = '*';
  416.                 }
  417.                 // this one does not apply to VIEWs
  418.                 $count_query = 'SELECT COUNT(' . $count_what . ') AS count';
  419.             }
  420.  
  421.             // add the remaining of select expression if there is
  422.             // a GROUP BY or HAVING clause
  423.             if (PMA_MYSQL_INT_VERSION < 40000
  424.              && $count_what =='*'
  425.              && (!empty($analyzed_sql[0]['group_by_clause'])
  426.                 || !empty($analyzed_sql[0]['having_clause']))) {
  427.                 $count_query .= ' ,' . $analyzed_sql[0]['select_expr_clause'];
  428.             }
  429.  
  430.             if (PMA_MYSQL_INT_VERSION >= 40000) {
  431.                 // add select expression after the SQL_CALC_FOUND_ROWS
  432.  
  433.                 // for UNION, just adding SQL_CALC_FOUND_ROWS
  434.                 // after the first SELECT works.
  435.  
  436.                 // take the left part, could be:
  437.                 // SELECT
  438.                 // (SELECT
  439.                 $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
  440.                 $count_query .= ' SQL_CALC_FOUND_ROWS ';
  441.                 // add everything that was after the first SELECT
  442.                 $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
  443.                 // ensure there is no semicolon at the end of the
  444.                 // count query because we'll probably add
  445.                 // a LIMIT 1 clause after it
  446.                 $count_query = rtrim($count_query);
  447.                 $count_query = rtrim($count_query, ';');
  448.             } else { // PMA_MYSQL_INT_VERSION < 40000
  449.  
  450.                 if (!empty($analyzed_sql[0]['from_clause'])) {
  451.                     $count_query .= ' FROM ' . $analyzed_sql[0]['from_clause'];
  452.                 }
  453.                 if (!empty($analyzed_sql[0]['where_clause'])) {
  454.                     $count_query .= ' WHERE ' . $analyzed_sql[0]['where_clause'];
  455.                 }
  456.                 if (!empty($analyzed_sql[0]['group_by_clause'])) {
  457.                     $count_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
  458.                 }
  459.                 if (!empty($analyzed_sql[0]['having_clause'])) {
  460.                     $count_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
  461.                 }
  462.             } // end if
  463.  
  464.             // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
  465.             // long delays. Returned count will be complete anyway.
  466.             // (but a LIMIT would disrupt results in an UNION)
  467.  
  468.             if (PMA_MYSQL_INT_VERSION >= 40000
  469.              && !isset($analyzed_sql[0]['queryflags']['union'])) {
  470.                 $count_query .= ' LIMIT 1';
  471.             }
  472.  
  473.             // run the count query
  474.  
  475.             if (PMA_MYSQL_INT_VERSION < 40000) {
  476.                 if ($cnt_all_result = PMA_DBI_try_query($count_query)) {
  477.                     if ($is_group && $count_what == '*') {
  478.                         $unlim_num_rows = @PMA_DBI_num_rows($cnt_all_result);
  479.                     } else {
  480.                         $unlim_num_rows = PMA_DBI_fetch_assoc($cnt_all_result);
  481.                         $unlim_num_rows = $unlim_num_rows['count'];
  482.                     }
  483.                     PMA_DBI_free_result($cnt_all_result);
  484.                 } else {
  485.                     if (PMA_DBI_getError()) {
  486.  
  487.                         // there are some cases where the generated
  488.                         // count_query (for MySQL 3) is wrong,
  489.                         // so we get here.
  490.                         /**
  491.                          * @todo use a big unlimited query to get the correct
  492.                          * number of rows (depending on a config variable?)
  493.                          */
  494.                         $unlim_num_rows = 0;
  495.                     }
  496.                 }
  497.             } else {
  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)
  509.                 //
  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.                 $cnt_all_result       = PMA_DBI_query('SELECT FOUND_ROWS() as count;');
  515.                 list($unlim_num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  516.                 @PMA_DBI_free_result($cnt_all_result);
  517.             }
  518.         } // end else "just browsing"
  519.  
  520.     } else { // not $is_select
  521.          $unlim_num_rows         = 0;
  522.     } // end rows total count
  523.  
  524.     // garvin: if a table or database gets dropped, check column comments.
  525.     if (isset($purge) && $purge == '1') {
  526.         require_once './libraries/relation_cleanup.lib.php';
  527.  
  528.         if (strlen($table) && strlen($db)) {
  529.             PMA_relationsCleanupTable($db, $table);
  530.         } elseif (strlen($db)) {
  531.             PMA_relationsCleanupDatabase($db);
  532.         } else {
  533.             // garvin: VOID. No DB/Table gets deleted.
  534.         } // end if relation-stuff
  535.     } // end if ($purge)
  536.  
  537.     // garvin: If a column gets dropped, do relation magic.
  538.     if (isset($cpurge) && $cpurge == '1' && isset($purgekey)
  539.      && strlen($db) && strlen($table) && !empty($purgekey)) {
  540.         require_once './libraries/relation_cleanup.lib.php';
  541.         PMA_relationsCleanupColumn($db, $table, $purgekey);
  542.  
  543.     } // end if column PMA_* purge
  544. } // end else "didn't ask to see php code"
  545.  
  546. // No rows returned -> move back to the calling page
  547. if ($num_rows < 1 || $is_affected) {
  548.     if ($is_delete) {
  549.         $message = $strDeletedRows . ' ' . $num_rows;
  550.     } elseif ($is_insert) {
  551.         if ($is_replace) {
  552.             /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
  553.             $message = $strAffectedRows . ' ' . $num_rows;
  554.         } else {
  555.             $message = $strInsertedRows . ' ' . $num_rows;
  556.         }
  557.         $insert_id = PMA_DBI_insert_id();
  558.         if ($insert_id != 0) {
  559.             // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
  560.             $message .= '[br]'.$strInsertedRowId . ' ' . ($insert_id + $num_rows - 1);
  561.         }
  562.     } elseif ($is_affected) {
  563.         $message = $strAffectedRows . ' ' . $num_rows;
  564.  
  565.         // Ok, here is an explanation for the !$is_select.
  566.         // The form generated by sql_query_form.lib.php
  567.         // and db_sql.php has many submit buttons
  568.         // on the same form, and some confusion arises from the
  569.         // fact that $zero_rows is sent for every case.
  570.         // The $zero_rows containing $strSuccess and sent with
  571.         // the form should not have priority over
  572.         // errors like $strEmptyResultSet
  573.     } elseif (!empty($zero_rows) && !$is_select) {
  574.         $message = $zero_rows;
  575.     } elseif (!empty($GLOBALS['show_as_php'])) {
  576.         $message = $strShowingPhp;
  577.     } elseif (isset($GLOBALS['show_as_php'])) {
  578.         /* User disable showing as PHP, query is only displayed */
  579.         $message = $strShowingSQL;
  580.     } elseif (!empty($GLOBALS['validatequery'])) {
  581.         $message = $strValidateSQL;
  582.     } else {
  583.         $message = $strEmptyResultSet;
  584.     }
  585.  
  586.     $message .= ' ' . (isset($GLOBALS['querytime']) ? '(' . sprintf($strQueryTime, $GLOBALS['querytime']) . ')' : '');
  587.  
  588.     if ($is_gotofile) {
  589.         $goto = PMA_securePath($goto);
  590.         // Checks for a valid target script
  591.         $is_db = $is_table = false;
  592.         include 'libraries/db_table_exists.lib.php';
  593.         if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
  594.             if (strlen($table)) {
  595.                 $table = '';
  596.             }
  597.             $goto = 'db_sql.php';
  598.         }
  599.         if (strpos($goto, 'db_') === 0 && ! $is_db) {
  600.             if (strlen($db)) {
  601.                 $db = '';
  602.             }
  603.             $goto = 'main.php';
  604.         }
  605.         // Loads to target script
  606.         if (strpos($goto, 'db_') === 0
  607.          || strpos($goto, 'tbl_') === 0) {
  608.             $js_to_run = 'functions.js';
  609.         }
  610.         if ($goto != 'main.php') {
  611.             require_once './libraries/header.inc.php';
  612.         }
  613.         $active_page = $goto;
  614.         require './' . $goto;
  615.     } else {
  616.         // avoid a redirect loop when last record was deleted
  617.         if ('sql.php' == $cfg['DefaultTabTable']) {
  618.             $goto = str_replace('sql.php','tbl_structure.php',$goto);
  619.         }
  620.         PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
  621.     } // end else
  622.     exit();
  623. } // end no rows returned
  624.  
  625. // At least one row is returned -> displays a table with results
  626. else {
  627.     // Displays the headers
  628.     if (isset($show_query)) {
  629.         unset($show_query);
  630.     }
  631.     if (isset($printview) && $printview == '1') {
  632.         require_once './libraries/header_printview.inc.php';
  633.     } else {
  634.         $js_to_run = 'functions.js';
  635.         unset($message);
  636.         if (strlen($table)) {
  637.             require './libraries/tbl_common.php';
  638.             $url_query .= '&goto=tbl_sql.php&back=tbl_sql.php';
  639.             require './libraries/tbl_info.inc.php';
  640.             require './libraries/tbl_links.inc.php';
  641.         } elseif (strlen($db)) {
  642.             require './libraries/db_common.inc.php';
  643.             require './libraries/db_info.inc.php';
  644.         } else {
  645.             require './libraries/server_common.inc.php';
  646.             require './libraries/server_links.inc.php';
  647.         }
  648.     }
  649.  
  650.     if (strlen($db)) {
  651.         require_once './libraries/relation.lib.php';
  652.         $cfgRelation = PMA_getRelationsParam();
  653.     }
  654.  
  655.     // Gets the list of fields properties
  656.     if (isset($result) && $result) {
  657.         $fields_meta = PMA_DBI_get_fields_meta($result);
  658.         $fields_cnt  = count($fields_meta);
  659.     }
  660.  
  661.     // Display previous update query (from tbl_replace)
  662.     if (isset($disp_query) && $cfg['ShowSQL'] == true) {
  663.         $tmp_sql_query = $GLOBALS['sql_query'];
  664.         $GLOBALS['sql_query'] = $disp_query;
  665.         PMA_showMessage($disp_message);
  666.         $GLOBALS['sql_query'] = $tmp_sql_query;
  667.     }
  668.  
  669.     if (isset($profiling_results)) {
  670.         PMA_profilingResults($profiling_results);
  671.     }
  672.  
  673.     // Displays the results in a table
  674.     if (empty($disp_mode)) {
  675.         // see the "PMA_setDisplayMode()" function in
  676.         // libraries/display_tbl.lib.php
  677.         $disp_mode = 'urdr111101';
  678.     }
  679.  
  680.     // hide edit and delete links for information_schema
  681.     if (PMA_MYSQL_INT_VERSION >= 50002 && $db == 'information_schema') {
  682.         $disp_mode = 'nnnn110111';
  683.     }
  684.  
  685.     PMA_displayTable($result, $disp_mode, $analyzed_sql);
  686.     PMA_DBI_free_result($result);
  687.  
  688.     // BEGIN INDEX CHECK See if indexes should be checked.
  689.     if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
  690.         foreach ($selected as $idx => $tbl_name) {
  691.             $check = PMA_check_indexes($tbl_name);
  692.             if (! empty($check)) {
  693.                 ?>
  694. <table border="0" cellpadding="2" cellspacing="0">
  695.     <tr>
  696.         <td class="tblHeaders" colspan="7"><?php printf($strIndexWarningTable, urldecode($tbl_name)); ?></td>
  697.     </tr>
  698.     <?php echo $check; ?>
  699. </table>
  700.                 <?php
  701.             }
  702.         }
  703.     } // End INDEX CHECK
  704.  
  705.     // Bookmark support if required
  706.     if ($disp_mode[7] == '1'
  707.         && (isset($cfg['Bookmark']) && ! empty($cfg['Bookmark']['db']) && ! empty($cfg['Bookmark']['table']) && empty($id_bookmark))
  708.         && !empty($sql_query)) {
  709.         echo "\n";
  710.  
  711.         $goto = 'sql.php?'
  712.               . PMA_generate_common_url($db, $table)
  713.               . '&sql_query=' . urlencode($sql_query)
  714.               . '&id_bookmark=1';
  715.  
  716.         ?>
  717. <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
  718. <?php echo PMA_generate_common_hidden_inputs(); ?>
  719. <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  720. <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
  721. <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
  722. <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
  723. <fieldset>
  724.     <legend><?php
  725.      echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . $strBookmarkThis . '" />' : '')
  726.         . $strBookmarkThis;
  727. ?>
  728.     </legend>
  729.  
  730.     <div class="formelement">
  731.         <label for="fields_label_"><?php echo $strBookmarkLabel; ?>:</label>
  732.         <input type="text" id="fields_label_" name="fields[label]" value="" />
  733.     </div>
  734.  
  735.     <div class="formelement">
  736.         <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
  737.         <label for="bkm_all_users"><?php echo $strBookmarkAllUsers; ?></label>
  738.     </div>
  739.  
  740.     <div class="clearfloat"></div>
  741. </fieldset>
  742. <fieldset class="tblFooters">
  743.     <input type="submit" name="store_bkm" value="<?php echo $strBookmarkThis; ?>" />
  744. </fieldset>
  745. </form>
  746.         <?php
  747.     } // end bookmark support
  748.  
  749.     // Do print the page if required
  750.     if (isset($printview) && $printview == '1') {
  751.         ?>
  752. <script type="text/javascript">
  753. //<![CDATA[
  754. // Do print the page
  755. window.onload = function()
  756. {
  757.     if (typeof(window.print) != 'undefined') {
  758.         window.print();
  759.     }
  760. }
  761. //]]>
  762. </script>
  763.         <?php
  764.     } // end print case
  765. } // end rows returned
  766.  
  767. /**
  768.  * Displays the footer
  769.  */
  770. require_once './libraries/footer.inc.php';
  771. ?>
  772.