<?php 

require ("config.php");
require ($CONFIG_PATH . "general_config.php");
require ($INCLUDE_DIRECTORY . "common.php");

/*
Copyright © 2001 Nick Gammon.

  Author: Nick Gammon <nick@gammon.com.au>
  Web:    http://www.gammon.com.au/
  Date:   February 2001

  This program is free software; you can redistribute it and/or modify 
  it under the terms of the GNU General Public License as published by 
  the Free Software Foundation; either version 2 of the License, 
  or (at your option) any later version. 

  This program is distributed in the hope that it will be useful, 
  but WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
  See the GNU General Public License for more details. 

  You should have received a copy of the GNU General Public License 
  along with this program; if not, write to 

  The Free Software Foundation, Inc., 
  59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


  The Free Software Foundation maintains a web page at: http://www.fsf.org

  See the file gpl.txt for the full GNU General Public License.

*/

Init ("Execute SQL command"); 

// check we can do it
Permission ("executesql");
 
$command = trim ($command);

$sqlid = trim ($sqlid);

if (!empty ($sqlid))
  {
  $query = "SELECT * "
         . "FROM sql "
         . "WHERE sqlid = $sqlid";
                         
  $result = mysql_query ($query) 
      or Problem ("Select failed: " . mysql_error ());
  
  if (!($row = mysql_fetch_array ($result)))
    Problem ("Sql command id $sqlid not found");
  
  $command = $row ["command"];  
  $description = $row ["summary"];
  mysql_free_result ($result);
  } // end of wanting a stock SQL command
 
?>

<h1>Execute SQL command</h1>


<form METHOD="post" ACTION="<?php echo $PHP_SELF;?>"> 
  </font>
  <code>
 <textarea name=command cols=80 rows=10 wrap=physical><?php echo (htmlentities(stripslashes ($command))) ?>
 </textarea> 
 </code>
<?php SetFont (); ?>
 
<?php FormSession (); ?>

<p><input Type=submit name=execute Value="Execute"> </p>

</form> 

<hr>

<?php
  
$fd = 0;
$totalrows = 0;
$returnedrows = 0;

function Summary ()
  {
  global $totalrows, $returnedrows;

  if ($returnedrows > 0)
    echo "<p><b>$returnedrows rows have been returned.</b></p>\n";
  else
    echo "<p><b>$totalrows rows have been affected.</b></p>\n";
  
  } // end of Summary
  
function ExecuteProblem ($why)
  {
echo <<< EOF
<h3>Problem executing SQL </h3>
<p>
<table border=0 cellpadding=5> <tr bgcolor=#A52A2A> <td><font color=#FFFFFF><b>
EOF;

  echo (htmlspecialchars ($why) . "\n");
  echo "</b></font></td></tr></table></p>\n";
  Summary ();
  MessageTail (); 
  die ();
  
  } // end of ExecuteProblem

function ShowStockSQL ()
  {
  global $PHP_SELF;
$query = "SELECT * "
       . "FROM sql "
       . "ORDER BY summary";
                       
$result = mysql_query ($query) 
    or Problem ("Select failed: " . mysql_error ());

echo "<h3>Stock SQL commands</h3>\n";

bList ();
  
while ($row = mysql_fetch_array ($result))
  {
  LI (); 
  hLink ( htmlspecialchars ($row ["summary"]),
          $PHP_SELF,
          sprintf ("sqlid=%d", $row ["sqlid"]));
} // end of doing each row

mysql_free_result ($result);

eList ();
  
  
  }   // end of ShowStockSQL
  
function ListTables ()
  {
  global $PHP_SELF, $whereclause, $showcreate, $showdata, $shownames, $userinfo;

  GetDatabaseName ($databasename);
                         
  $result = mysql_list_tables ($databasename) 
      or Problem ("List tables failed: " . mysql_error ());
  
  echo "<form METHOD=\"post\" ACTION=\"$PHP_SELF\"> \n";
    
  echo "<p>Dump contents of table: &nbsp; <select name=tablename size=1>\n";
  echo "<option value=\"--All--\">-- All tables --\n";
    
  while ($row = mysql_fetch_row ($result))
    {
    $table = $row [0];
    echo "<option value=\"$table\">$table\n";
    } // end of doing each row
  
  mysql_free_result ($result);
    
  echo "</select>\n";
  echo "&nbsp; WHERE &nbsp; <input type=text name=whereclause value=\"$whereclause\" size=35 maxlength=255>";
  
  FormSession ();
  echo "</p>";
  echo "<p>";
  echo "<input type=checkbox name=showcreate value=yes checked> Include CREATE statement\n";
  echo "&nbsp;";
  echo "<input type=checkbox name=showdata value=yes checked> Include table data\n";
  echo "&nbsp;";
  echo "<input type=checkbox name=shownames value=yes> Include field names\n";
  echo "</p>";
  
  echo "&nbsp; &nbsp; <input Type=submit name=dump Value=\"Dump\"> </p>\n";
  echo "</form>\n";
  
  if ($userinfo ['edittable'])
    {  
    echo "<hr><p>";
    ShowTablesToEdit ();
    echo "</p>";
    } // end of being allowed to edit tables
  
  }   // end of ListTables

function DumpTable ($tablename)
  {
  global $whereclause, $showcreate, $showdata, $shownames, $DUMP_TABLE_DIRECTORY;
  
  if (empty ($tablename))
    Problem ("No table specified to dump");
  
  $starttime = getmicrotime ();
  
  echo "<p><b>Dumping table $tablename ...</b><br>\n";
                       
  $result = mysql_query ("SHOW FIELDS FROM $tablename") 
      or Problem ("List fields failed: " . mysql_error ());
  
  $filename = $DUMP_TABLE_DIRECTORY . $tablename . ".sql";
  
  $fd = fopen ($filename, "w") 
      or Problem ("Can't open file: $filename");
  
  fwrite ($fd, "# DUMP of table $tablename\n");
  fwrite ($fd, "#\n");
  fwrite ($fd, "# Date: " . strftime ("%Y-%m-%d %H:%M:%S", time()) . "\n");  
  fwrite ($fd, "#\n");
  
  if ($showcreate == "yes")
    {
    fwrite ($fd, "# Table structure - $tablename\n");
    fwrite ($fd, "#\n");
    
    fwrite ($fd, "CREATE TABLE $tablename (");
    
    $first = true;
    
    while ($row = mysql_fetch_array ($result))
      {
      $def = "";
      if ($first)
        $first = false;
      else
        $def = ", ";
      $type = $row ['Type'];
      $name = $row ['Field'];
      $null = $row ['Null'];
      $key = $row ['Key'];
      $default = $row ['Default'];
      $extra = $row ['Extra'];
      
      $def .= "$name $type ";
      
      if ($null != "YES")
        $def .= "NOT NULL ";
      if (!empty ($default))
        $def .= "DEFAULT '$default' ";
  
      $def .= "$extra ";
      
      if ($key == "PRI")
        $def .= "primary key ";
      
      fwrite ($fd, $def);
      
      }
    fwrite ($fd, ");\n");    // end of create table
    
// now do indexes - older versions of mysql don't like them as part of CREATE TABLE

    mysql_data_seek ($result, 0); // back to start of result set
    
    while ($row = mysql_fetch_array ($result))
      {
      $key = $row ['Key'];
      $name = $row ['Field'];
      $null = $row ['Null'];
      
      if ($key == "UNI")
        $def = "unique";
      else if ($key == "MUL")
        $def = "index";      
      else
        continue;   // not unique or index, don't bother with it

      // output the index statement
      fwrite ($fd, "ALTER TABLE $tablename ADD $def idx_$name ($name);\n");

      if ($null == "YES")
        {
        echo "<b><font color=#FF0000>Warning:</font>";
        echo " Field '$name' has an index but may be NULL. This may cause problems.<br></b>\n";
        }
        
      } // end of doing each item again
              
    mysql_free_result ($result);
    } // end of CREATE wanted
    
  if ($showdata == "yes")
    {
    if (!empty ($whereclause))
      $where = "WHERE " . stripslashes ($whereclause);
      
    $result = mysql_query ("SELECT * FROM $tablename $where") 
        or Problem ("List table data failed: " . mysql_error ());
    
    fwrite ($fd, "#\n");
    fwrite ($fd, "# Data - $tablename $where\n");
    fwrite ($fd, "#\n");
  
    $count = 0;

    // get field names if required
    if ($shownames == "yes")
      {
      GetDatabaseName ($databasename);
      $fields = mysql_list_fields ($databasename, $tablename)
                or Problem ("Could not get field names" . mysql_error ());
      $fieldcount = mysql_num_fields ($fields);
      }
            
    while ($row = mysql_fetch_row ($result))
      {
      $count++;
      fwrite ($fd, "INSERT INTO $tablename ");
      
      if ($shownames == "yes")
        {
        $def = "(";
        for ($i = 0; $i < $fieldcount; $i++)
          {
          if ($i > 0)
            $def .= ", ";
          $def .= mysql_field_name ($fields, $i);
          }
          $def .= ") ";
        fwrite ($fd, $def); // write field names
        } // end of field names wanted
      
      fwrite ($fd, "VALUES (");
      $def = "";
      
      for ($i = 0; $i < mysql_num_fields ($result); $i++)
        {
        if ($i > 0)
          $def .= ", ";
        $meta = mysql_fetch_field ($result, $i);
        
        $value = $row [$i];
        if (!isset ($value))
          $value = "NULL";
        else if (!$meta->numeric)
          $value = "'" . addcslashes ($value, "\0\n\r\\\'\"") . "'";
        
        $def .= $value;
        }
      
      fwrite ($fd, $def);
      fwrite ($fd, ");\n");    // end of insert into
      
      }   // end of doing each row
    
    mysql_free_result ($result);

    if ($shownames == "yes")
      mysql_free_result ($fields);

    } // end of data wanted

    
  fwrite ($fd, "#\n");
  fwrite ($fd, "# Done.\n");
  fwrite ($fd, "#\n");

  fclose ($fd);
  
  
  chmod ($filename, 438); // octal 666 (rw-rw-rw-)
  
  $endtime = getmicrotime ();
  $diff = $endtime - $starttime;
  printf ("<b>Dumped successfully (%d rows)<br>File: %s<br>Time: %6.3f seconds</b></p>\n",
          $count, $filename, $diff);
 

  } // end of DumpTable

function DumpAllTables ()
  {
GetDatabaseName ($databasename);
                       
$result = mysql_list_tables ($databasename) 
    or Problem ("List tables failed: " . mysql_error ());

$starttime = getmicrotime ();
  
while ($row = mysql_fetch_row ($result))
    DumpTable ($row [0]);

$endtime = getmicrotime ();
$diff = $endtime - $starttime;
printf ("<p><b>TOTAL: Dumped successfully (%d tables) in %6.3f seconds total</b></p>\n",
        mysql_num_rows ($result), $diff);

mysql_free_result ($result);
  
  }   // end of DumpAllTables

/*

Web page to execute a file containing SQL statements 

*/

$dump = trim ($dump);

if ($dump == "Dump")
  {
  if ($tablename == "--All--")
    DumpAllTables ();
  else
    DumpTable ($tablename);
  ShowStockSQL ();
  ListTables ();
  MessageTail (); 
  die ();
  }   // end of no command
  
  
$command = trim (stripslashes ($command));

// no command yet? do nothing.
if (empty ($command))
  {
  ShowStockSQL ();
  ListTables ();
  ExecuteProblem ("No command specified.");
  }   // end of no command
    
// remove trailing semicolon
if ($line [strlen ($command) - 1] == ";")
   $line [strlen ($command) - 1] = " ";

$i = strpos ($command, " ");
$firstword = strtolower (trim (substr ($command, 0, $i)));
 
$bSelect = $firstword == "select" || 
           $firstword == "show" || 
           $firstword == "explain" ||
           $firstword == "describe";

$result = mysql_query ($command) 
        or die ("SQL statement failed: "
                . "<b>" . mysql_error () . "</b>");

$totalrows += mysql_affected_rows ();   // count affected rows

if (!empty ($description))
  echo "<p><b>$description</b></p>";

// we can't display a result set on UPDATE, CREATE etc.
if ($bSelect)
  {
  $returnedrows += mysql_num_rows ($result);
  
  if (mysql_num_rows ($result) > 0)
    {
    bTable ();
    
    // column names
  
    bRow ("lightblue");
    for ($i = 0; $i < mysql_num_fields ($result); $i++)
      tHead (mysql_field_name ($result, $i));
    eRow ();
    
    while ($row = mysql_fetch_row ($result))
      {
      // row data
      bRow ("azure");
      for ($i = 0; $i < mysql_num_fields ($result); $i++)
        {
        $value = $row [$i];
        if (!isset ($value))
          $value = "-";
        tData ($value);
        }
      eRow ();
      
      }   // end of doing each row
      
    eTable ();
      
    mysql_free_result ($result);
    
    } // end of having rows to display
  } // end of a select or show command
  
Summary ();

echo "<hr>\n";

ShowStockSQL ();
ListTables ();

MessageTail (); 

?>
