home *** CD-ROM | disk | FTP | other *** search
/ Freelog 70 / Freelog070.iso / Internet / EasyPHP / easyphp1-8_setup.exe / {app} / phpmyadmin / sql.php < prev    next >
Encoding:
PHP Script  |  2005-01-01  |  37.0 KB  |  890 lines

  1. <?php
  2. /* $Id: sql.php,v 2.44 2005/01/01 21:36:48 nijel Exp $ */
  3. // vim: expandtab sw=4 ts=4 sts=4:
  4.  
  5. /**
  6.  * Gets some core libraries
  7.  */
  8. require_once('./libraries/grab_globals.lib.php');
  9. require_once('./libraries/common.lib.php');
  10. require_once('./libraries/tbl_indexes.lib.php');
  11.  
  12. /**
  13.  * Defines the url to return to in case of error in a sql statement
  14.  */
  15. // Security checkings
  16. if (!empty($goto)) {
  17.     $is_gotofile     = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
  18.     if (!@file_exists('./' . $is_gotofile)) {
  19.         unset($goto);
  20.     } else {
  21.         $is_gotofile = ($is_gotofile == $goto);
  22.     }
  23. } // end if (security checkings)
  24.  
  25. if (empty($goto)) {
  26.     $goto         = (empty($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
  27.     $is_gotofile  = TRUE;
  28. } // end if
  29. if (!isset($err_url)) {
  30.     $err_url = (!empty($back) ? $back : $goto)
  31.              . '?' . PMA_generate_common_url(isset($db) ? $db : '')
  32.              . ((strpos(' ' . $goto, 'db_details') != 1 && isset($table)) ? '&table=' . urlencode($table) : '');
  33. } // end if
  34.  
  35. // Coming from a bookmark dialog
  36. if (isset($fields['query'])) {
  37.     $sql_query = $fields['query'];
  38. }
  39.  
  40. // This one is just to fill $db
  41. if (isset($fields['dbase'])) {
  42.     $db = $fields['dbase'];
  43. }
  44.  
  45. // Now we can check the parameters
  46. PMA_checkParameters(array('sql_query', 'db'));
  47.  
  48. // instead of doing the test twice
  49. $is_drop_database = preg_match('@DROP[[:space:]]+DATABASE[[:space:]]+@i', $sql_query);
  50.  
  51. /**
  52.  * Check rights in case of DROP DATABASE
  53.  *
  54.  * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
  55.  * but since a malicious user may pass this variable by url/form, we don't take
  56.  * into account this case.
  57.  */
  58. if (!defined('PMA_CHK_DROP')
  59.     && !$cfg['AllowUserDropDatabase']
  60.     && $is_drop_database) {
  61.     // Checks if the user is a Superuser
  62.     // TODO: set a global variable with this information
  63.     // loic1: optimized query
  64.     if (!($result = PMA_DBI_select_db('mysql'))) {
  65.         require_once('./header.inc.php');
  66.         PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
  67.     } // end if
  68. } // end if
  69.  
  70.  
  71. /**
  72.  * Bookmark add
  73.  */
  74. if (isset($store_bkm)) {
  75.     require_once('./libraries/bookmark.lib.php');
  76.     PMA_addBookmarks($fields, $cfg['Bookmark'], (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
  77.     PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto);
  78. } // end if
  79.  
  80.  
  81. /**
  82.  * Gets the true sql query
  83.  */
  84. // $sql_query has been urlencoded in the confirmation form for drop/delete
  85. // queries or in the navigation bar for browsing among records
  86. if (isset($btnDrop) || isset($navig)) {
  87.     $sql_query = urldecode($sql_query);
  88. }
  89.  
  90. /**
  91.  * Reformat the query
  92.  */
  93.  
  94. $GLOBALS['unparsed_sql'] = $sql_query;
  95. $parsed_sql = PMA_SQP_parse($sql_query);
  96. $analyzed_sql = PMA_SQP_analyze($parsed_sql);
  97. // Bug #641765 - Robbat2 - 12 January 2003, 10:49PM
  98. // Reverted - Robbat2 - 13 January 2003, 2:40PM
  99.  
  100. // lem9: for bug 780516: now that we use case insensitive preg_match
  101. // or flags from the analyser, do not put back the reformatted query
  102. // into $sql_query, to make this kind of query work without
  103. // capitalizing keywords:
  104. //
  105. // CREATE TABLE SG_Persons (
  106. //  id int(10) unsigned NOT NULL auto_increment,
  107. //  first varchar(64) NOT NULL default '',
  108. //  PRIMARY KEY  (`id`)
  109. // )
  110. //
  111. // Note: now we probably do not need to fill and use $GLOBALS['unparsed_sql']
  112. // but I let this intact for now.
  113. //
  114. //$sql_query = PMA_SQP_formatHtml($parsed_sql, 'query_only');
  115.  
  116.  
  117. // check for a real SELECT ... FROM
  118. $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
  119.  
  120. // If the query is a Select, extract the db and table names and modify
  121. // $db and $table, to have correct page headers, links and left frame.
  122. // db and table name may be enclosed with backquotes, db is optionnal,
  123. // query may contain aliases.
  124.  
  125. // (TODO: if there are more than one table name in the Select:
  126. // - do not extract the first table name
  127. // - do not show a table name in the page header
  128. // - do not display the sub-pages links)
  129.  
  130. if ($is_select) {
  131.     $prev_db = $db;
  132.     if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name'])) {
  133.         $table = $analyzed_sql[0]['table_ref'][0]['table_true_name'];
  134.     }
  135.     if (isset($analyzed_sql[0]['table_ref'][0]['db'])
  136.        && !empty($analyzed_sql[0]['table_ref'][0]['db'])) {
  137.         $db    = $analyzed_sql[0]['table_ref'][0]['db'];
  138.     }
  139.     else {
  140.         $db = $prev_db;
  141.     }
  142.     // Nijel don't change reload, if we already decided to reload in read_dump
  143.     if (!isset($reload) || $reload == 0) {
  144.         $reload  = ($db == $prev_db) ? 0 : 1;
  145.     }
  146. }
  147.  
  148. /**
  149.  * Sets or modifies the $goto variable if required
  150.  */
  151. if ($goto == 'sql.php') {
  152.     $is_gotofile = FALSE;
  153.     $goto = 'sql.php?'
  154.           . PMA_generate_common_url($db, $table)
  155.           . '&pos=' . $pos
  156.           . '&sql_query=' . urlencode($sql_query);
  157. } // end if
  158.  
  159.  
  160. /**
  161.  * Go back to further page if table should not be dropped
  162.  */
  163. if (isset($btnDrop) && $btnDrop == $strNo) {
  164.     if (!empty($back)) {
  165.         $goto = $back;
  166.     }
  167.     if ($is_gotofile) {
  168.         if (strpos(' ' . $goto, 'db_details') == 1 && !empty($table)) {
  169.             unset($table);
  170.         }
  171.         $active_page = $goto;
  172.         require('./' . PMA_securePath($goto));
  173.     } else {
  174.         PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
  175.     }
  176.     exit();
  177. } // end if
  178.  
  179.  
  180. /**
  181.  * Displays the confirm page if required
  182.  *
  183.  * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
  184.  * with js) because possible security issue is not so important here: at most,
  185.  * the confirm message isn't displayed.
  186.  *
  187.  * Also bypassed if only showing php code.or validating a SQL query
  188.  */
  189. if (!$cfg['Confirm']
  190.     || (isset($is_js_confirmed) && $is_js_confirmed)
  191.     || isset($btnDrop)
  192.  
  193.     // if we are coming from a "Create PHP code" or a "Without PHP Code"
  194.     // dialog, we won't execute the query anyway, so don't confirm
  195.     //|| !empty($GLOBALS['show_as_php'])
  196.     || isset($GLOBALS['show_as_php'])
  197.  
  198.     || !empty($GLOBALS['validatequery'])) {
  199.     $do_confirm = FALSE;
  200. } else {
  201.     $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
  202. }
  203.  
  204. if ($do_confirm) {
  205.     $stripped_sql_query = $sql_query;
  206.     require_once('./header.inc.php');
  207.     echo '<table border="0" cellpadding="3" cellspacing="0">' . "\n";
  208.     if ($is_drop_database) {
  209.         echo '    <tr>' . "\n"
  210.            . '        <td class="tblHeadError">' . "\n";
  211.         if($cfg['ErrorIconic']){
  212.             echo '        <img src="' .$pmaThemeImage .'s_warn.png" border="0" hspace="2" vspace="2" align="left" />';
  213.         }
  214.         echo $strDropDatabaseStrongWarning . ' <br />' . "\n";
  215.     } else {
  216.         echo '    <tr>' . "\n"
  217.            . '        <td class="tblHeadError">' . "\n";
  218.         if($cfg['ErrorIconic']){
  219.             echo '        <img src="' .$pmaThemeImage .'s_really.png" border="0" hspace="2" align="middle" />';
  220.         }
  221.     }
  222.     echo $strDoYouReally . "\n"
  223.        . '        </td>' . "\n"
  224.        . '    </tr>' . "\n"
  225.        . '    <tr>' . "\n"
  226.        . '        <td class="tblError">' . "\n"
  227.        . '            <tt>' . htmlspecialchars($stripped_sql_query) . '</tt> ?<br/>' . "\n"
  228.        . '        </td>' . "\n"
  229.        . '    </tr>' . "\n"
  230.        . '    <form action="sql.php" method="post">' . "\n"
  231.        . '    <tr>' . "\n"
  232.        . '        <td align="right">' . "\n"
  233.     ?>
  234.     <?php echo PMA_generate_common_hidden_inputs($db, (isset($table)?$table:'')); ?>
  235.     <input type="hidden" name="sql_query" value="<?php echo urlencode($sql_query); ?>" />
  236.     <input type="hidden" name="zero_rows" value="<?php echo isset($zero_rows) ? PMA_sanitize($zero_rows) : ''; ?>" />
  237.     <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  238.     <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back) : ''; ?>" />
  239.     <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload) : 0; ?>" />
  240.     <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge) : ''; ?>" />
  241.     <input type="hidden" name="cpurge" value="<?php echo isset($cpurge) ? PMA_sanitize($cpurge) : ''; ?>" />
  242.     <input type="hidden" name="purgekey" value="<?php echo isset($purgekey) ? PMA_sanitize($purgekey) : ''; ?>" />
  243.     <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query) : ''; ?>" />
  244.     <input type="submit" name="btnDrop" value="<?php echo $strYes; ?>" id="buttonYes" />
  245.     <input type="submit" name="btnDrop" value="<?php echo $strNo; ?>" id="buttonNo" />
  246.     <?php
  247.     echo '        </td>' . "\n"
  248.        . '    </tr>' . "\n"
  249.        . '    </form>' . "\n"
  250.        . '</table>';
  251.     echo "\n";
  252. } // end if
  253.  
  254.  
  255. /**
  256.  * Executes the query and displays results
  257.  */
  258. else {
  259.     if (!isset($sql_query)) {
  260.         $sql_query = '';
  261.     }
  262.     // Defines some variables
  263.     // loic1: A table has to be created -> left frame should be reloaded
  264.     if ((!isset($reload) || $reload == 0)
  265.         && preg_match('@^CREATE TABLE[[:space:]]+(.*)@i', $sql_query)) {
  266.         $reload           = 1;
  267.     }
  268.     // Gets the number of rows per page
  269.     if (empty($session_max_rows)) {
  270.         $session_max_rows = $cfg['MaxRows'];
  271.     } else if ($session_max_rows != 'all') {
  272.         $cfg['MaxRows']   = $session_max_rows;
  273.     }
  274.     // Defines the display mode (horizontal/vertical) and header "frequency"
  275.     if (empty($disp_direction)) {
  276.         $disp_direction   = $cfg['DefaultDisplay'];
  277.     }
  278.     if (empty($repeat_cells)) {
  279.         $repeat_cells     = $cfg['RepeatCells'];
  280.     }
  281.  
  282.     // SK -- Patch: $is_group added for use in calculation of total number of
  283.     //              rows.
  284.     //              $is_count is changed for more correct "LIMIT" clause
  285.     //              appending in queries like
  286.     //                "SELECT COUNT(...) FROM ... GROUP BY ..."
  287.  
  288.     // TODO: detect all this with the parser, to avoid problems finding
  289.     // those strings in comments or backquoted identifiers
  290.  
  291.     $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = FALSE;
  292.     if ($is_select) { // see line 141
  293.         $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
  294.         $is_func =  !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
  295.         $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
  296.         $is_export   = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
  297.         $is_analyse  = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
  298.     } else if (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
  299.         $is_explain  = TRUE;
  300.     } else if (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
  301.         $is_delete   = TRUE;
  302.         $is_affected = TRUE;
  303.     } else if (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
  304.         $is_insert   = TRUE;
  305.         $is_affected = TRUE;
  306.     } else if (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
  307.         $is_affected = TRUE;
  308.     } else if (preg_match('@^SHOW[[:space:]]+@i', $sql_query)) {
  309.         $is_show     = TRUE;
  310.     } else if (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
  311.         $is_maint    = TRUE;
  312.     }
  313.  
  314.     // Do append a "LIMIT" clause?
  315.     if (isset($pos)
  316.         && (!$cfg['ShowAll'] || $session_max_rows != 'all')
  317.         && !($is_count || $is_export || $is_func || $is_analyse)
  318.         && isset($analyzed_sql[0]['queryflags']['select_from'])
  319.         && !isset($analyzed_sql[0]['queryflags']['offset'])
  320.         && !preg_match('@[[:space:]]LIMIT[[:space:]0-9,-]+$@i', $sql_query)) {
  321.         $sql_limit_to_append = " LIMIT $pos, ".$cfg['MaxRows'];
  322.         if (preg_match('@(.*)([[:space:]](PROCEDURE[[:space:]](.*)|FOR[[:space:]]+UPDATE|LOCK[[:space:]]+IN[[:space:]]+SHARE[[:space:]]+MODE))$@i', $sql_query, $regs)) {
  323.             $full_sql_query  = $regs[1] . $sql_limit_to_append . $regs[2];
  324.         } else {
  325.             $full_sql_query  = $sql_query . $sql_limit_to_append;
  326.         }
  327.  
  328.         if (isset($display_query)) {
  329.             if (preg_match('@((.|\n)*)(([[:space:]](PROCEDURE[[:space:]](.*)|FOR[[:space:]]+UPDATE|LOCK[[:space:]]+IN[[:space:]]+SHARE[[:space:]]+MODE))|;)[[:space:]]*$@i', $display_query, $regs)) {
  330.                 $display_query  = $regs[1] . $sql_limit_to_append . $regs[3];
  331.             } else {
  332.                 $display_query  = $display_query . $sql_limit_to_append;
  333.             }
  334.         }
  335.     } else {
  336.         $full_sql_query      = $sql_query;
  337.     } // end if...else
  338.  
  339.     PMA_DBI_select_db($db);
  340.  
  341.     // If the query is a DELETE query with no WHERE clause, get the number of
  342.     // rows that will be deleted (mysql_affected_rows will always return 0 in
  343.     // this case)
  344.  
  345.     if ($is_delete
  346.         && preg_match('@^DELETE([[:space:]].+)?(FROM[[:space:]](.+))$@i', $sql_query, $parts)
  347.         && !preg_match('@[[:space:]]WHERE[[:space:]]@i', $parts[3])) {
  348.         $cnt_all_result = @PMA_DBI_try_query('SELECT COUNT(*) as count ' .  $parts[2]);
  349.         if ($cnt_all_result) {
  350.             list($num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  351.             PMA_DBI_free_result($cnt_all_result);
  352.         } else {
  353.             $num_rows   = 0;
  354.         }
  355.     }
  356.  
  357.     //  E x e c u t e    t h e    q u e r y
  358.  
  359.     // Only if we didn't ask to see the php code (mikebeck)
  360.     if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
  361.         unset($result);
  362.         $num_rows = 0;
  363.     }
  364.     else {
  365.         // garvin: Measure query time. TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
  366.         list($usec, $sec) = explode(' ',microtime());
  367.         $querytime_before = ((float)$usec + (float)$sec);
  368.  
  369.         $result   = @PMA_DBI_try_query($full_sql_query, NULL, PMA_DBI_QUERY_STORE);
  370.  
  371.         list($usec, $sec) = explode(' ',microtime());
  372.         $querytime_after = ((float)$usec + (float)$sec);
  373.  
  374.         $GLOBALS['querytime'] = $querytime_after - $querytime_before;
  375.  
  376.         // Displays an error message if required and stop parsing the script
  377.         if ($error        = PMA_DBI_getError()) {
  378.             require_once('./header.inc.php');
  379.             $full_err_url = (preg_match('@^(db_details|tbl_properties)@', $err_url))
  380.                           ? $err_url . '&show_query=1&sql_query=' . urlencode($sql_query)
  381.                           : $err_url;
  382.             PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
  383.         }
  384.         unset($error);
  385.  
  386.         // Gets the number of rows affected/returned
  387.         // (This must be done immediately after the query because
  388.         // mysql_affected_rows() reports about the last query done)
  389.  
  390.         if (!$is_affected) {
  391.             $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
  392.         } else if (!isset($num_rows)) {
  393.             $num_rows = @PMA_DBI_affected_rows();
  394.         }
  395.  
  396.         // Checks if the current database has changed
  397.         // This could happen if the user sends a query like "USE `database`;"
  398.         $res = PMA_DBI_query('SELECT DATABASE() AS \'db\';');
  399.         $row = PMA_DBI_fetch_row($res);
  400.         if (is_array($row) && isset($row[0]) && (strcasecmp($db,$row[0]) != 0)) {
  401.             $db     = $row[0];
  402.             $reload = 1;
  403.         }
  404.         @PMA_DBI_free_result($res);
  405.         unset($res, $row);
  406.  
  407.         // tmpfile remove after convert encoding appended by Y.Kawada
  408.         if (function_exists('PMA_kanji_file_conv')
  409.             && (isset($textfile) && file_exists($textfile))) {
  410.             unlink($textfile);
  411.         }
  412.  
  413.         // Counts the total number of rows for the same 'SELECT' query without the
  414.         // 'LIMIT' clause that may have been programatically added
  415.  
  416.         if (empty($sql_limit_to_append)) {
  417.             $unlim_num_rows         = $num_rows;
  418.             // if we did not append a limit, set this to get a correct
  419.             // "Showing rows..." message
  420.             $GLOBALS['session_max_rows'] = 'all';
  421.         }
  422.         else if ($is_select) {
  423.  
  424.                 //    c o u n t    q u e r y
  425.  
  426.                 // If we are "just browsing", there is only one table,
  427.                 // and no where clause (or just 'WHERE 1 '),
  428.                 // so we do a quick count (which uses MaxExactCount)
  429.                 // because SQL_CALC_FOUND_ROWS
  430.                 // is not quick on large InnoDB tables
  431.  
  432.                 if (!$is_group
  433.                  && !isset($analyzed_sql[0]['queryflags']['union'])
  434.                  && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
  435.                  && (empty($analyzed_sql[0]['where_clause'])
  436.                    || $analyzed_sql[0]['where_clause'] == '1 ')) {
  437.  
  438.                     // "j u s t   b r o w s i n g"
  439.                     $unlim_num_rows = PMA_countRecords($db, $table, TRUE);
  440.  
  441.                 } else { // n o t   " j u s t   b r o w s i n g "
  442.  
  443.                     if (PMA_MYSQL_INT_VERSION < 40000) {
  444.  
  445.                         // detect this case:
  446.                         // SELECT DISTINCT x AS foo, y AS bar FROM sometable
  447.  
  448.                         if (isset($analyzed_sql[0]['queryflags']['distinct'])) {
  449.                             $count_what = 'DISTINCT ';
  450.                             $first_expr = TRUE;
  451.                             foreach($analyzed_sql[0]['select_expr'] as $part) {
  452.                                 $count_what .= (!$first_expr ? ', ' : '') . $part['expr'];
  453.                                 $first_expr = FALSE;
  454.                             }
  455.                          } else {
  456.                              $count_what = '*';
  457.                          }
  458.                         $count_query = 'SELECT COUNT(' . $count_what . ') AS count';
  459.                     }
  460.  
  461.                     // add the remaining of select expression if there is
  462.                     // a GROUP BY or HAVING clause
  463.                     if (PMA_MYSQL_INT_VERSION < 40000
  464.                      && $count_what =='*'
  465.                      && (!empty($analyzed_sql[0]['group_by_clause'])
  466.                         || !empty($analyzed_sql[0]['having_clause']))) {
  467.                         $count_query .= ' ,' . $analyzed_sql[0]['select_expr_clause'];
  468.                     }
  469.  
  470.                     if (PMA_MYSQL_INT_VERSION >= 40000) {
  471.                          // add select expression after the SQL_CALC_FOUND_ROWS
  472.  
  473.                             // for UNION, just adding SQL_CALC_FOUND_ROWS
  474.                             // after the first SELECT works.
  475.  
  476.                             // take the left part, could be:
  477.                             // SELECT
  478.                             // (SELECT
  479.                             $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
  480.                             $count_query .= ' SQL_CALC_FOUND_ROWS ';
  481.                             // add everything that was after the first SELECT
  482.                             $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
  483.                     } else { // PMA_MYSQL_INT_VERSION < 40000
  484.  
  485.                         if (!empty($analyzed_sql[0]['from_clause'])) {
  486.                             $count_query .= ' FROM ' . $analyzed_sql[0]['from_clause'];
  487.                         }
  488.                         if (!empty($analyzed_sql[0]['where_clause'])) {
  489.                             $count_query .= ' WHERE ' . $analyzed_sql[0]['where_clause'];
  490.                         }
  491.                         if (!empty($analyzed_sql[0]['group_by_clause'])) {
  492.                             $count_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
  493.                         }
  494.                         if (!empty($analyzed_sql[0]['having_clause'])) {
  495.                             $count_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
  496.                         }
  497.                     } // end if
  498.  
  499.                     // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
  500.                     // long delays. Returned count will be complete anyway.
  501.                     // (but a LIMIT would disrupt results in an UNION)
  502.  
  503.                     if (PMA_MYSQL_INT_VERSION >= 40000
  504.                     && !isset($analyzed_sql[0]['queryflags']['union'])) {
  505.                         $count_query .= ' LIMIT 1';
  506.                     }
  507.  
  508.                     // run the count query
  509.  
  510.                     if (PMA_MYSQL_INT_VERSION < 40000) {
  511.                         if ($cnt_all_result = PMA_DBI_try_query($count_query)) {
  512.                             if ($is_group && $count_what == '*') {
  513.                                 $unlim_num_rows = @PMA_DBI_num_rows($cnt_all_result);
  514.                             } else {
  515.                                 $unlim_num_rows = PMA_DBI_fetch_assoc($cnt_all_result);
  516.                                 $unlim_num_rows = $unlim_num_rows['count'];
  517.                             }
  518.                             PMA_DBI_free_result($cnt_all_result);
  519.                         } else {
  520.                             if (PMA_DBI_getError()) {
  521.  
  522.                                 // there are some cases where the generated
  523.                                 // count_query (for MySQL 3) is wrong,
  524.                                 // so we get here.
  525.                                 //TODO: use a big unlimited query to get
  526.                                 // the correct number of rows (depending
  527.                                 // on a config variable?)
  528.                                 $unlim_num_rows = 0;
  529.                             }
  530.                         }
  531.                     } else {
  532.                         PMA_DBI_try_query($count_query);
  533.                         // if (mysql_error()) {
  534.                         // void.
  535.                         // I tried the case
  536.                         // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
  537.                         // UNION (SELECT `User`, `Host`, "%" AS "Db",
  538.                         // `Select_priv`
  539.                         // FROM `user`) ORDER BY `User`, `Host`, `Db`;
  540.                         // and although the generated count_query is wrong
  541.                         // the SELECT FOUND_ROWS() work! (maybe it gets the
  542.                         // count from the latest query that worked)
  543.                         //
  544.                         // another case where the count_query is wrong:
  545.                         // SELECT COUNT( * ), f1 from t1 group by f1
  546.                         // and you click to sort on count( * )
  547.                         // }
  548.                         $cnt_all_result       = PMA_DBI_query('SELECT FOUND_ROWS() as count;');
  549.                         list($unlim_num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  550.                         @PMA_DBI_free_result($cnt_all_result);
  551.                     }
  552.             } // end else "just browsing"
  553.  
  554.         } else { // not $is_select
  555.              $unlim_num_rows         = 0;
  556.         } // end rows total count
  557.  
  558.         // garvin: if a table or database gets dropped, check column comments.
  559.         if (isset($purge) && $purge == '1') {
  560.             require_once('./libraries/relation_cleanup.lib.php');
  561.  
  562.             if (isset($table) && isset($db) && !empty($table) && !empty($db)) {
  563.                 PMA_relationsCleanupTable($db, $table);
  564.             } elseif (isset($db) && !empty($db)) {
  565.                 PMA_relationsCleanupDatabase($db);
  566.             } else {
  567.                 // garvin: VOID. No DB/Table gets deleted.
  568.             } // end if relation-stuff
  569.          } // end if ($purge)
  570.  
  571.         // garvin: If a column gets dropped, do relation magic.
  572.         if (isset($cpurge) && $cpurge == '1' && isset($purgekey)
  573.             && isset($db) && isset($table)
  574.             && !empty($db) && !empty($table) && !empty($purgekey)) {
  575.             require_once('./libraries/relation_cleanup.lib.php');
  576.             PMA_relationsCleanupColumn($db, $table, $purgekey);
  577.  
  578.         } // end if column PMA_* purge
  579.     } // end else "didn't ask to see php code"
  580.  
  581.  
  582.     // No rows returned -> move back to the calling page
  583.     if ($num_rows < 1 || $is_affected) {
  584.         if ($is_delete) {
  585.             $message = $strDeletedRows . ' ' . $num_rows;
  586.         } else if ($is_insert) {
  587.             $message = $strInsertedRows . ' ' . $num_rows;
  588.             $insert_id = PMA_DBI_insert_id();
  589.             if ($insert_id != 0) {
  590.                 $message .= '[br]'.$strInsertedRowId . ' ' . $insert_id;
  591.             }
  592.         } else if ($is_affected) {
  593.             $message = $strAffectedRows . ' ' . $num_rows;
  594.         } else if (!empty($zero_rows)) {
  595.             $message = $zero_rows;
  596.         } else if (!empty($GLOBALS['show_as_php'])) {
  597.             $message = $strPhp;
  598.         } else if (!empty($GLOBALS['validatequery'])) {
  599.             $message = $strValidateSQL;
  600.         } else {
  601.             $message = $strEmptyResultSet;
  602.         }
  603.  
  604.         $message .= ' ' . (isset($GLOBALS['querytime']) ? '(' . sprintf($strQueryTime, $GLOBALS['querytime']) . ')' : '');
  605.  
  606.         if ($is_gotofile) {
  607.             $goto = PMA_securePath($goto);
  608.             // Checks for a valid target script
  609.             if (isset($table) && $table == '') {
  610.                 unset($table);
  611.             }
  612.             if (isset($db) && $db == '') {
  613.                 unset($db);
  614.             }
  615.             $is_db = $is_table = FALSE;
  616.             if (strpos(' ' . $goto, 'tbl_properties') == 1) {
  617.                 if (!isset($table)) {
  618.                     $goto     = 'db_details.php';
  619.                 } else {
  620.                     $is_table = @PMA_DBI_query('SHOW TABLES LIKE \'' . PMA_sqlAddslashes($table, TRUE) . '\';', NULL, PMA_DBI_QUERY_STORE);
  621.                     if (!($is_table && @PMA_DBI_num_rows($is_table))) {
  622.                         $goto = 'db_details.php';
  623.                         unset($table);
  624.                     }
  625.                     @PMA_DBI_free_result($is_table);
  626.                 } // end if... else...
  627.             }
  628.             if (strpos(' ' . $goto, 'db_details') == 1) {
  629.                 if (isset($table)) {
  630.                     unset($table);
  631.                 }
  632.                 if (!isset($db)) {
  633.                     $goto     = 'main.php';
  634.                 } else {
  635.                     $is_db    = @PMA_DBI_select_db($db);
  636.                     if (!$is_db) {
  637.                         $goto = 'main.php';
  638.                         unset($db);
  639.                     }
  640.                 } // end if... else...
  641.             }
  642.             // Loads to target script
  643.             if (strpos(' ' . $goto, 'db_details') == 1
  644.                 || strpos(' ' . $goto, 'tbl_properties') == 1) {
  645.                 $js_to_run = 'functions.js';
  646.             }
  647.             if ($goto != 'main.php') {
  648.                 require_once('./header.inc.php');
  649.             }
  650.             $active_page = $goto;
  651.             require('./' . $goto);
  652.         } // end if file_exist
  653.         else {
  654.             PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
  655.         } // end else
  656.         exit();
  657.     } // end no rows returned
  658.  
  659.     // At least one row is returned -> displays a table with results
  660.     else {
  661.         // Displays the headers
  662.         if (isset($show_query)) {
  663.             unset($show_query);
  664.         }
  665.         if (isset($printview) && $printview == '1') {
  666.             require_once('./header_printview.inc.php');
  667.         } else {
  668.             $js_to_run = 'functions.js';
  669.             unset($message);
  670.             if (!empty($table)) {
  671.                 require('./tbl_properties_common.php');
  672.                 $url_query .= '&goto=tbl_properties.php&back=tbl_properties.php';
  673.                 require('./tbl_properties_table_info.php');
  674.                 require('./tbl_properties_links.php');
  675.             }
  676.             else {
  677.                 require('./db_details_common.php');
  678.                 require('./db_details_db_info.php');
  679.             }
  680.         }
  681.  
  682.         require_once('./libraries/relation.lib.php');
  683.         $cfgRelation = PMA_getRelationsParam();
  684.  
  685.         // Gets the list of fields properties
  686.         if (isset($result) && $result) {
  687.             $fields_meta = PMA_DBI_get_fields_meta($result);
  688.             $fields_cnt  = count($fields_meta);
  689.         }
  690.  
  691.         // Display previous update query (from tbl_replace)
  692.         if (isset($disp_query) && $cfg['ShowSQL'] == TRUE) {
  693.             $tmp_sql_query = $GLOBALS['sql_query'];
  694.             $GLOBALS['sql_query'] = $disp_query;
  695.             PMA_showMessage($disp_message);
  696.             $GLOBALS['sql_query'] = $tmp_sql_query;
  697.         }
  698.  
  699.         // Displays the results in a table
  700.         require_once('./libraries/display_tbl.lib.php');
  701.         if (empty($disp_mode)) {
  702.             // see the "PMA_setDisplayMode()" function in
  703.             // libraries/display_tbl.lib.php
  704.             $disp_mode = 'urdr111101';
  705.         }
  706.         if (!isset($dontlimitchars)) {
  707.             $dontlimitchars = 0;
  708.         }
  709.  
  710.         PMA_displayTable($result, $disp_mode, $analyzed_sql);
  711.         PMA_DBI_free_result($result);
  712.  
  713.         // BEGIN INDEX CHECK See if indexes should be checked.
  714.         if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
  715.             foreach($selected AS $idx => $tbl_name) {
  716.                 $indexes        = $indexes_info = $indexes_data = array();
  717.                 $tbl_ret_keys   = PMA_get_indexes(urldecode($tbl_name), $err_url_0);
  718.  
  719.                 PMA_extract_indexes($tbl_ret_keys, $indexes, $indexes_info, $indexes_data);
  720.  
  721.                 $idx_collection = PMA_show_indexes(urldecode($tbl_name), $indexes, $indexes_info, $indexes_data, false);
  722.                 $check          = PMA_check_indexes($idx_collection);
  723.                 if (!empty($check)) {
  724.                 ?>
  725. <table border="0" cellpadding="2" cellspacing="0">
  726.     <tr>
  727.         <td class="tblHeaders" colspan="7"><?php printf($strIndexWarningTable, urldecode($tbl_name)); ?></td>
  728.     </tr>
  729.     <?php echo $check; ?>
  730. </table>
  731.                 <?php
  732.                 }
  733.             }
  734.         } // End INDEX CHECK
  735.  
  736.         if ($disp_mode[6] == '1' || $disp_mode[9] == '1') {
  737.             echo "\n";
  738.             echo '<hr />' . "\n";
  739.  
  740.             // Displays "Insert a new row" link if required
  741.             if ($disp_mode[6] == '1') {
  742.                 $lnk_goto  = 'sql.php?'
  743.                            . PMA_generate_common_url($db, $table)
  744.                            . '&pos=' . $pos
  745.                            . '&session_max_rows=' . $session_max_rows
  746.                            . '&disp_direction=' . $disp_direction
  747.                            . '&repeat_cells=' . $repeat_cells
  748.                            . '&dontlimitchars=' . $dontlimitchars
  749.                            . '&sql_query=' . urlencode($sql_query);
  750.                 $url_query = '?'
  751.                            . PMA_generate_common_url($db, $table)
  752.                            . '&pos=' . $pos
  753.                            . '&session_max_rows=' . $session_max_rows
  754.                            . '&disp_direction=' . $disp_direction
  755.                            . '&repeat_cells=' . $repeat_cells
  756.                            . '&dontlimitchars=' . $dontlimitchars
  757.                            . '&sql_query=' . urlencode($sql_query)
  758.                            . '&goto=' . urlencode($lnk_goto);
  759.  
  760.                 echo '    <!-- Insert a new row -->' . "\n"
  761.                    . '    <a href="tbl_change.php' . $url_query . '">' . ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_insrow.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strInsertNewRow . '"/>' : '') . $strInsertNewRow . '</a>';
  762.                 if ($disp_mode[9] == '1') {
  763.                     echo '  ';
  764.                 }
  765.                 echo "\n";
  766.             } // end insert new row
  767.  
  768.             // Displays "printable view" link if required
  769.             if ($disp_mode[9] == '1') {
  770.                 $url_query = '?'
  771.                            . PMA_generate_common_url($db, $table)
  772.                            . '&pos=' . $pos
  773.                            . '&session_max_rows=' . $session_max_rows
  774.                            . '&disp_direction=' . $disp_direction
  775.                            . '&repeat_cells=' . $repeat_cells
  776.                            . '&printview=1'
  777.                            . '&sql_query=' . urlencode($sql_query);
  778.                 echo '    <!-- Print view -->' . "\n"
  779.                    . '    <a href="sql.php' . $url_query
  780.                    . ((isset($dontlimitchars) && $dontlimitchars == '1') ? '&dontlimitchars=1' : '')
  781.                    . '" target="print_view">'
  782.                    . ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_print.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strPrintView . '"/>' : '')
  783.                    . $strPrintView . '</a>' . "\n";
  784.                 if (!$dontlimitchars) {
  785.                    echo   '      ' . "\n"
  786.                         . '    <a href="sql.php' . $url_query
  787.                         . '&dontlimitchars=1'
  788.                         . '" target="print_view">'
  789.                         . ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_print.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strPrintViewFull . '" />' : '')
  790.                         . $strPrintViewFull . '</a>  ' . "\n";
  791.                 }
  792.             } // end displays "printable view"
  793.  
  794.             echo "\n";
  795.         }
  796.  
  797.         // Export link
  798.         // (the url_query has extra parameters that won't be used to export)
  799.         // (the single_table parameter is used in display_export.lib.php
  800.         //  to hide the SQL and the structure export dialogs)
  801.         if (isset($analyzed_sql[0]) && $analyzed_sql[0]['querytype'] == 'SELECT' && !isset($printview)) {
  802.             if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name']) && !isset($analyzed_sql[0]['table_ref'][1]['table_true_name'])) {
  803.                 $single_table   = '&single_table=true';
  804.             } else {
  805.                 $single_table   = '';
  806.             }
  807.             echo '    <!-- Export -->' . "\n"
  808.                    . '      <a href="tbl_properties_export.php' . $url_query
  809.                    . '&unlim_num_rows=' . $unlim_num_rows
  810.                    . $single_table
  811.                    . '">'
  812.                    . ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_tblexport.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strExport . '" />' : '')
  813.                    . $strExport . '</a>' . "\n";
  814.         }
  815.  
  816.         // Bookmark Support if required
  817.         if ($disp_mode[7] == '1'
  818.             && ($cfg['Bookmark']['db'] && $cfg['Bookmark']['table'] && empty($id_bookmark))
  819.             && !empty($sql_query)) {
  820.             echo "\n";
  821.  
  822.             $goto = 'sql.php?'
  823.                   . PMA_generate_common_url($db, $table)
  824.                   . '&pos=' . $pos
  825.                   . '&session_max_rows=' . $session_max_rows
  826.                   . '&disp_direction=' . $disp_direction
  827.                   . '&repeat_cells=' . $repeat_cells
  828.                   . '&dontlimitchars=' . $dontlimitchars
  829.                   . '&sql_query=' . urlencode($sql_query)
  830.                   . '&id_bookmark=1';
  831.             ?>
  832. <!-- Bookmark the query -->
  833.             <?php
  834.             echo "\n";
  835.             if ($disp_mode[3] == '1') {
  836.                 echo '    <i>' . $strOr . '</i>' . "\n";
  837.             }else echo '<br /><br />';
  838.             ?>
  839. <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
  840. <table border="0" cellpadding="2" cellspacing="0">
  841. <tr><td class="tblHeaders" colspan="2"><?php
  842.      echo ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_bookmark.png" border="0" width="16" height="16" hspace="2" align="middle" alt="' . $strBookmarkThis . '" />' : '')
  843.         . $strBookmarkThis;
  844. ?></td></tr>
  845. <tr bgcolor="<?php echo $cfg['BgcolorOne']; ?>"><td>
  846.     <?php echo $strBookmarkLabel; ?>:
  847.     <?php echo PMA_generate_common_hidden_inputs(); ?>
  848.     <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  849.     <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
  850.     <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
  851.     <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
  852.         </td><td>
  853.     <input type="text" name="fields[label]" value="" />
  854.         </td></tr>
  855. <tr bgcolor="<?php echo $cfg['BgcolorOne']; ?>"><td align="right" valign="top">
  856.     <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" /></td>
  857.     <td><label for="bkm_all_users"><?php echo $strBookmarkAllUsers; ?></label></td>
  858. </tr>
  859. <tr bgcolor="<?php echo $cfg['BgcolorOne']; ?>"><td colspan="2" align="right">
  860.     <input type="submit" name="store_bkm" value="<?php echo $strBookmarkThis; ?>" />
  861.     </td></tr>
  862. </table></form>
  863.             <?php
  864.         } // end bookmark support
  865.  
  866.         // Do print the page if required
  867.         if (isset($printview) && $printview == '1') {
  868.             echo "\n";
  869.             ?>
  870. <script type="text/javascript" language="javascript1.2">
  871. <!--
  872. // Do print the page
  873. if (typeof(window.print) != 'undefined') {
  874.     window.print();
  875. }
  876. //-->
  877. </script>
  878.             <?php
  879.         } // end print case
  880.     } // end rows returned
  881.  
  882. } // end executes the query
  883. echo "\n\n";
  884.  
  885. /**
  886.  * Displays the footer
  887.  */
  888. require_once('./footer.inc.php');
  889. ?>
  890.