<?
////////////////////////////////////////////////////////////////////////
/*SMI - SHOUTcast Management Interface
A web based shoutcast server management program
Founding Author: Scott D. Harvanek <scotth@sourcemirrors.org>

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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/
////////////////////////////////////////////////////////////////////////
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SMI Setup</title>
<script language="JavaScript">
<!--

function chatPop(URL) {
        day = new Date();
        id = day.getTime();
        var centerWidth = (window.screen.width - 400) / 2;
	var centerHeight = (window.screen.height - 100) / 2;
	parseInt(centerHeight);
	parseInt(centerWidth);	
        eval("page"+id+" = window.open(URL, '"+id+"', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=100,left="+centerWidth+",top="+centerHeight+"'); ");
}

//-->
</script>
<link rel="stylesheet" type="text/css" href="../include/smi.css">
<link rel="shortcut icon" type="image/x-icon" href="../imgs/favicon.ico">
</head>
<body>
<center>
	<img src="../imgs/smi-logo.jpg">
<br>
<br>

<!-- HEADER TABLE -->
<table class="login" width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#FFFFFF">
<tr align="center">
   <td align="center">
        <table width="50%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
		<tr align="center">
   			<td colspan="3">
        <strong><big><a href="<? echo $_SERVER['PHP_SELF']; ?>">SMI - installation</a></big></strong><br>
	<? echo "Host: ".php_uname("n")." (".php_uname("s").")\n"; ?>
   			</td>
		</tr>
	</table>
    </td>
  </tr>
</table>

<!-- CONTENT TABLE -->
<table class="login" width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#FFFFFF">
<tr align="center">
   <td align="center">
        <table width="90%" border="0" cellpadding="5" cellspacing="1" bgcolor="#FFFFFF">
                <tr align="left">
                        <td align="left">

<?
require('../include/functions.inc.php');
/*
Determine installation step
*/
if(!isset($_POST['step'])) {
require_once('../include/config.php');
/*
Step 1: Determine if prerequisites are met
*/
$failed = 0;		// Reset failed flag
$directions = "";	// Empty string with directions
echo "<strong>STEP 1: CHECKING PREREQUISITES...</strong><br>\n";

// PHP version 
echo "<p>- Checking PHP version...";
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
 $failed = 1;
 $class = "bad";
 $directions = "<p>- Upgrade your PHP installation and restart web server</p>\n";
} else {
 $class = "good";
}
echo "<span class=\"check_".$class."\"><strong>".phpversion()."</strong> (Required: PHP 5.0 or newer)</span></p>";

// PHP safe mode
echo "<p>- Checking PHP safe mode...";
$safemode = ini_get('safe_mode');
if ($safemode == 1) {
 $failed = 1;
 $class = "bad";
 $tmpstr = "On";
 $directions .= "<p>- Edit ".php_ini_loaded_file()." and set <i>safe_mode = Off</i></p>";
} else {
 $class = "good";
 $tmpstr = "Off";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: Safe mode off)</span></p>";



// PHP MySQL extension
echo "<p>- Checking PHP MySQL...";
if (!in_array("mysql", get_loaded_extensions()) && !in_array("mysqli", get_loaded_extensions())) {
 $failed = 1;
 $class = "bad";
 $tmpstr = "missing";
 $directions .= "<p>- Install the <i>php-mysql</i> extension and restart web server</p>";
} else {
 $class = "good";
 $tmpstr = "OK";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: PHP MySQL extension)</span></p>";

// PHP cURL extension
echo "<p>- Checking PHP cURL...";
if (!in_array("curl", get_loaded_extensions())) {
 $failed = 1;
 $class = "bad";
 $tmpstr = "missing";
 $directions .= "<p>- Activate the <i>cURL</i> extension and restart web server</p>";
} else {
 $class = "good";
 $tmpstr = "OK";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: PHP cURL extension)</span></p>";



// MySQL version 
echo "<p>- Checking MySQL version...";
if ($safemode == 1) {
 echo "<span class=\"check_bad\">Unable to check with PHP safe mode on</span></p>";
} else {
 $mysql = explode(" ", shell_exec("mysqladmin --version \n"));
 $mysql = rtrim($mysql[5], ",");
 debug($mysql);
 if (version_compare($mysql, '4.1', '<')) {
  $failed = 1;
  $class = "bad";
  $directions .= "<p> - Install/upgrade MySQL server to version 4.1 or later</p>\n";
 } else {
  $class = "good";
 }
echo "<span class=\"check_".$class."\"><strong>".$mysql."</strong> (Required: MySQL 4.1 or newer)</span></p>";
}

// Optional features checking goes here...
echo "<strong>OPTIONAL FEATURES:</strong><br>\n";

// MRTG presence
echo "<p>- Checking for MRTG...";
if ($safemode == 1) {
  echo "<span class=\"check_bad\">Unable to check with PHP safe mode on</span></p>";
} else {
  if (strtoupper(substr(PHP_OS, 0, 3)) == "WIN") {
    // Try executing mrtg in Windows.
    $mrtg = shell_exec("start /b wperl ".$_SERVER['DOCUMENT_ROOT']."/mrtg/bin/mrtg");
  } else {  
    // Try to execute the mrtg command on Linux. Trap any STDERR from going to STDOUT
    $mrtg = `mrtg 2>&1`;
  }
  // See if we find something familiar from MRTG, fail if not
  if (stristr($mrtg, "Oetiker")) {
    $mrtgver = explode("-", str_replace(" ", "", $mrtg));
    $tmpstr = $mrtgver[2];
    $class = "good";
  } else {
    $class = "miss";
    $tmpstr = "not found (optional)";
    $directions .= "<p>- Install MRTG if you want to use graphical stats</p>\n";
  }
  echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required for stats)</span></p>";
}

echo "<p>&nbsp</p>";
 if ($failed == 1) {
  echo "<strong>To make your server ready for SMI...</strong>";
  echo $directions;
  echo "<strong>...and then click <big><a href=".$_SERVER['PHP_SELF'].">here</a></big> to reload this page.</strong>"; 
 } else {
  echo "<center><strong>Your server is ready to install SMI!</strong>";
?>
<p>
 <form name="installform" method="post" action="install.php">
  <input type="submit" name="step" value="Step 2 >>">
 </form>
( File permissions )
</p>
</center>
<?
 }
}
elseif ($_POST['step'] == "Step 2 >>" || $_POST['step'] == "Reload2") { 

/*
Step 2: Check file permissions
*/
$failed = 0;            // Reset failed flag
$directions = "";       // Empty string with directions
$path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);	  // Get pathname of this script
$root_path = str_replace('/install', '', $path_parts['dirname']); // Parent dir is the root path of SMI

echo "<strong>STEP 2: CHECKING FILE PERMISSIONS...</strong><br>\n";

// MRTG working directory
echo "<p>- directory <strong>mrtg</strong>...";
if (is_writeable("../mrtg")) {
 $class = "good";
 $tmpstr = "writable";
} else {
 $failed = 1;
 $class = "bad";
 $tmpstr = "failed";
 $directions = "<p>- Set directory <I>".$root_path."/mrtg</I> writable</p>\n";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: read/write access)</span></p>\n";

// PLAYLISTS working directory
echo "<p>- directory <strong>playlists</strong>...";
if (is_writeable("../playlists")) {
 $class = "good";
 $tmpstr = "writable";
} else {
 $failed = 1;
 $class = "bad";
 $tmpstr = "failed";
 $directions .= "<p>- Set directory <I>".$root_path."/playlists</I> writable</p>\n";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: read/write access)</span></p>\n";

// ICES working directory
echo "<p>- directory <strong>ices</strong>...";
if (is_writeable("../ices")) {
 $class = "good";
 $tmpstr = "writable";
} else {
 $failed = 1;
 $class = "bad";
 $tmpstr = "failed";
 $directions .= "<p>- Set directory <I>".$root_path."/ices</I> writable</p>\n";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: read/write access)</span></p>\n";

// SERVERS working directory
echo "<p>- directory <strong>servers</strong>...";
if (is_writeable("../servers")) {
 $class = "good";
 $tmpstr = "writable";
} else {
 $failed = 1;
 $class = "bad";
 $tmpstr = "failed";
 $directions .= "<p>- Set directory <I>".$root_path."/servers</I> writable</p>\n";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: read/write access)</span></p>\n";

// CONFIG.PHP configuration file
echo "<p>- file <strong>config.php</strong>...";
if (is_writeable("../include/config.php")) {
 $class = "good";
 $tmpstr = "writable";
} else {
 $failed = 1;
 $class = "bad";
 $tmpstr = "failed";
 $directions .= "<p>- Set file <I>".$root_path."/include/config.php</I> writable</p>\n";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong> (Required: read/write access)</span></p>\n";

?>
<form name="installform" method="post" action="install.php">
<?
 echo "<p>&nbsp</p>";
 if ($failed == 1) {
  echo "<strong>To proceed with installation...</strong>";
  echo $directions;
  
  echo "<strong>...and then click below to reload this page.</strong>";
  echo "<center><p><input type=\"submit\" name=\"submit\" value=\"Reload\"></p></center>";
  echo "<input type=\"hidden\" name=\"step\" value=\"Reload2\">\n";
 } else {
  echo "<center><strong>All file and directory permissions OK!</strong>";
  echo "<p><input type=\"submit\" name=\"step\" value=\"Step 3 >>\">\n";
  echo "<br>( MySQL server configuration )\n";
 }
?>
</form><br>
</p>
</center>
<?
} elseif ($_POST['step'] == "Finish!") {

/*
Get config values via form
*/
$createdb = $_POST['createdb'];
$username = $_POST['username'];
$password = $_POST['password'];

  $db = dbConnect();
  
  // Do general settings
  $settings = groupsettings("1");
  foreach ($settings as $setting) {
    $condition = array('setting' => $setting['setting']);
    $update = array('value' => $_POST[$setting['setting']]);
    $db->update('config', $update, $condition);
  }	

  // Update superuser name and password from form
  $update = array('username' => $_POST['username'], 'password' => md5($_POST['password']));
  $db->update('members', $update, array('user_id' => 1));

  if (iswin()) {
    echo "<p>IMPORTANT! For SMI to run properly under Windows, the registry changes as listed ";
    echo "in the file <strong>pstools.reg</strong> within the <i>wintools</i> directory must be made.</p>";
    $sc_serv = $_POST['smi_path'].'/shoutcast/1.9.8-Windows/sc_serv.exe';
  } else {
    $sc_serv = $_POST['smi_path'].'/shoutcast/1.9.8-Linux/sc_serv';
  }
  // A qualified guess of which sc_serv binary to use
  $db->update('config', array('value' => $sc_serv), array('setting' => 'sc_serv'));

  echo "<br><p><div class=\"check_good\">Installation complete, if you need AutoDJ capabilities and bitrate checking please follow the instructions in INSTALL.txt in the /install/ folder!</div>";
  echo "<br><br><div class=\"check_bad\">IMPORTANT! Delete or rename /install/install.php!</div>";
  echo "<p>Then click <strong><a href=\"../\">here</a></strong> to login and administrate your SMI installation.</p>";

} elseif ($_POST['step'] == "Step 3 >>"  || substr($_POST['step'], 0, 7) == "Reload3") {

/*
Step 3: MySQL server setup
*/
$failed = 0;            // Reset failed flag
$directions = "";       // Empty string with directions
$path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);      // Get pathname of this script
$root_path = str_replace('/install', '', $path_parts['dirname']); // Parent dir is the root path of SMI

echo "<strong>STEP 3: MYSQL SERVER CONFIGURATION...</strong><br>\n";

// Check to see if we are fresh on step 3 or retrying
if ($_POST['step'] == "Step 3 >>") {
  require ('../include/config.php');
} else if (substr($_POST['step'], 0, 7) == "Reload3") {
  $dbhost = $_POST['databasehost'];
  $dbport = $_POST['databaseport'];
}
?>

<form name="installform" method="post" action="install.php">
<table width="50%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
 <tr align="center">
   <td colspan="3">
	<strong>Database server connection</strong>
   </td>
 </tr>
  <tr align="center">
   <td>Host</td>
   <td>:</td>
   <td><input class="input" name="databasehost" type="text" id="databasehost" value="<? echo $dbhost; ?>"></td>
 </tr>
  <tr align="center">
   <td>Port</td>
   <td>:</td>
   <td><input class="input" name="databaseport" type="text" id="databaseport" value="<? echo $dbport; ?>"></td>
 </tr>
</table>
<?
echo "- Testing MySQL server connection...";

// Check if host is entered as an IP adress
$ip = false;
if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$dbhost))
{
  $parts=explode(".",$dbhost);
  foreach($parts as $ip_parts)
  {
    if(intval($ip_parts) > 255 || intval($ip_parts) < 0) {
      // Segment not in 0-255 range, most likely a hostname
      $ip = false;
      break;
    }
    $ip = true;
  }
} else {
  $ip = false; // Format does not match that of an ip address
}

// If host is entered as a hostname, try to resolve
if (!$ip) {
  $hostip = gethostbyname($dbhost);
} else {
  $hostip = $dbhost;
}

// If resolving failed, $hostip will just be the same as $dbhost
if ($ip == false && $hostip == $dbhost) {
  $failed = 1;
  $tmpstr = "DNS error";
  $class = "bad";
  $directions = "- Use a valid hostname for the MySQL server";
} else {
  $fp = fsockopen($hostip, $dbport, $errno, $errstr, 30); 
  if (!$fp) {
    $failed = 1;
    $tmpstr = $errstr;
    $class = "bad";
    $directions = "- Check that the MySQL server daemon is started<br>- Check that database hostname and port info is correct";
  } else {
    fclose($fp);
    $failed = 0;
    $tmpstr = "Connection OK";
    $class = "good";
  }
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong></span><br><p>";
if ($failed == 1) {
  echo "<p><strong>To proceed with installation...</strong><br>";
  echo $directions;
  echo "<br><strong>...and then click below to retry connecting.</strong></p>";
  echo "<center><p><input type=\"submit\" name=\"submit\" value=\"Retry\"></p></center>";
  echo "<input type=\"hidden\" name=\"step\" value=\"Reload33\">\n";
  echo "</form></table>";
  exit;
} 

// If this is a retry, use form values instead of those from config.php
if (substr($_POST['step'],0,9) == "Reload333") {
  $dbname = $_POST['database'];
  $dbuser = $_POST['databaseusername'];
  $dbpass = $_POST['databasepassword'];
} else {
  require_once('../include/config.php');
}
?>
<table width="50%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
 <tr align="center">
   <td colspan="3">
        <strong>Database name and authentication</strong>
   </td>
 </tr>
 <tr align="center">
   <td>Database</td>
   <td>:</td>
   <td><input class="input" name="database" type="text" id="database" value="<? echo $dbname; ?>"></td>
 </tr>
 <tr align="center">
   <td>Username</td>
   <td>:</td>
   <td><input class="input" name="databaseusername" type="text" id="databaseusername" value="<? echo $dbuser; ?>"></td>	
 </tr>
 <tr align="center">
   <td>Password</td>
   <td>:</td>
   <td><input class="input" name="databasepassword" type="password" id="databasepassword" value="<? echo $dbpass; ?>"></td>
 </tr>
 <!-- remove test button - test directly in script (FIXME: delete these lines when working)
 <tr>
   <td>&nbsp;</td>
   <td>&nbsp;</td>
   <td>
	<button onclick="chatPop('./dbtest.php?host='+document.installform.databasehost.value+'&uname='+document.installform.databaseusername.value+'&database='+document.installform.database.value+'&dbpass='+document.installform.databasepassword.value+''); return false;">Test</button>
   </td>
</tr>
 -->
</table>
<?
echo "- Testing authentication...";
$link = mysql_connect(gethostbyname($dbhost).":".$dbport, $dbuser, $dbpass);
if (!$link) {
  $failed = 1;
  $tmpstr = mysql_error();
  $class = "bad";
  $directions = "- Check that the user is created in MySQL with correct password (case sensitive)";
} else {
  $failed = 0;
  $tmpstr = "OK";
  $class = "good";
}
echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong></span><br>";

if ($failed == 1) {
  echo "<p><strong>To proceed with installation...</strong><br>";
  echo $directions;
  echo "<br><strong>...and then click below to retry connecting.</strong></p>";
  echo "<center><p><input type=\"submit\" name=\"submit\" value=\"Retry\"></p></center>";
  echo "<input type=\"hidden\" name=\"step\" value=\"Reload333\">\n";
  echo "</form></table>";
  exit;
} 

// Check database access and privileges
echo "- Testing access...";
$dbselect = mysql_select_db($dbname, $link);
if ($dbselect) {
  $failed = 0;
  $class = "good";
  $tmpstr = "OK";
  echo "<span class=\"check_".$class."\"><strong>".$tmpstr."</strong></span><br>";
    
  echo "- Testing CREATE TABLE...";
  // Do a DROP IF EXISTS to clean up earlier attempts, and for now ignore if it works
  mysql_query("DROP TABLE IF EXISTS `installtest`");
  $sql = "CREATE TABLE `installtest` (`test` varchar(200) NOT NULL,  PRIMARY KEY  (`test`) ) 
          ENGINE=MyISAM DEFAULT CHARSET=latin1";
  if (mysql_query($sql)) {
     echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
     $failed = 1;
     echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }

  echo "- Testing INSERT...";
  if (mysql_query("INSERT INTO installtest (test) VALUES ('test')")) {
    echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
     $failed = 1;
     echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }

  echo "- Testing UPDATE...";
  if (mysql_query("UPDATE installtest SET test = 'newtest'")) {
    echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
    $failed = 1;
    echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }
   
  echo "- Testing SELECT...";
  if (mysql_query("SELECT * FROM installtest")) {
    echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
     $failed = 1;
     echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }

  echo "- Testing DELETE...";
  if (mysql_query("DELETE FROM installtest")) {
    echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
     $failed = 1;
     echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }

  echo "- Testing ALTER TABLE...";
  if (mysql_query("ALTER TABLE installtest ADD COLUMN column2 varchar(200) NOT NULL default 'new column'")) {
    echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
     $failed = 1;
     echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }

  echo "- Testing DROP TABLE...";
  if (mysql_query("DROP TABLE installtest")) {
    echo "<span class=\"check_good\"><strong>OK</strong></span><br>";
  } else {
     $failed = 1;
     echo "<span class=\"check_bad\"><strong>failed</strong></span><br>";
  }

} else {
  $failed = 1;
  $tmpstr = mysql_error();
  $class = "bad";
} 
  
if ($failed == 1) {
  echo "<p><strong>To proceed with installation...</strong>";
  echo "<br>- Grant user <i>".$dbuser."</i> SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER and DROP access privileges on database <i>".$dbname."</i>";
  echo "<br><strong>...and then click below to recheck.</strong></p>";
  echo "<center><p><input type=\"submit\" name=\"submit\" value=\"Retry\"></p></center>";
  echo "<input type=\"hidden\" name=\"step\" value=\"Reload333\">\n";
  echo "</form></table>";
  exit;
} 
    $config_file = file_get_contents('../include/config.php');

    // Use perl style regular expressions to replace what is actually in the config file values
    $config_file = preg_replace('/\$dbhost.*=.*".*";/', '$dbhost = "'.$dbhost.'";', $config_file);
    $config_file = preg_replace('/\$dbport.*=.*".*";/', '$dbport = "'.$dbport.'";', $config_file);
    $config_file = preg_replace('/\$dbuser.*=.*".*";/', '$dbuser = "'.$dbuser.'";', $config_file);
    $config_file = preg_replace('/\$dbpass.*=.*".*";/', '$dbpass = "'.$dbpass.'";', $config_file);
    $config_file = preg_replace('/\$dbname.*=.*".*";/', '$dbname = "'.$dbname.'";', $config_file);

    $config = file_put_contents('../include/config.php', $config_file);
?>
<center>
<span class=\"check_good\"><i>( config.php was updated successfully )</i></span>
<p><input type="submit" name="step" value="Step 4 >>">
</form><br>
( Database settings )
</p>
</center>
<?
} elseif ($_POST['step'] == "Step 4 >>" || $_POST['step'] == "Select") {
/*
Step 4: Database and settings
*/
  echo "<strong>STEP 4: DATABASE SETTINGS...</strong><br>\n";
?>
<table width="50%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
 <tr align="center">
   <td colspan="3">
        <strong>Config and database tables</strong>
   </td>
 </tr>
</table>

<?
// Include config.php with correct db info for table creation
  require('../include/config.php');

  $link = mysql_connect($dbhost, $dbuser, $dbpass);
  mysql_select_db($dbname);
  
  // Check for tables in database
  echo "<p>- Database content...";

  $result = mysql_query("SHOW TABLES;");
  $numrows = mysql_num_rows($result);

  if ($numrows < 1) {
    echo "<span class=\"check_good\">Empty</span></p>";
    // Create the database tables
    echo "<p>- Recreating all tables...";
    shell_exec('mysql -u'.$dbuser.' -p'.$dbpass.' '.$dbname.' < create.sql');
    echo "<span class=\"check_good\">Success!</span></p>";

  // If tables found and we have not chosen already, decide wether to recreate or not
  } elseif ($_POST['step'] != "Select") {
    echo "<span class=\"check_bad\">tables exist. Choose action:</span>";
    ?>
    <form name="installform" method="post" action="install.php">
      <table width="50%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
        <tr align="center">
          <td colspan="3">
            <div align="left">
              <select name="createdb">
                <option value="yes">Recreate database tables (all old data will be lost)</option>
                <option value="no" selected>Leave database as it is (no action)</option>
              </select>
            </div>
          </td>
        </tr>
        <tr align="center">
          <td colspan="3">
            <input type="submit" name="step" value="Select">
          <td>
        </tr>
      </table>
    </form></p>
    <?
    exit;

  // We are called from the form and have made our choice 
  } else {
    $createdb = $_POST['createdb'];

    // We chose to keep database untouched, hope for the best and proceed
    if ($createdb == "no") {
      echo "<span class=\"check_bad\">Keep tables</span></p>";

    // We chose to recreate the tables
    } else {
      echo "<span class=\"check_good\">Recreate tables</span></p>";
     
      // Create the database
      echo "<p>- Recreating all tables...";
      shell_exec('mysql -u'.$dbuser.' -p'.$dbpass.' '.$dbname.' < create.sql');
      echo "<span class=\"check_good\">Success!</span><p>";
    }
  }

  // Tables are now either kept from before, or recreated 
?>
<p><hr noshade height="1"></p>
<form name="installform" method="post" action="install.php">
<input type="hidden" name="createdb" value="<? echo $createdb; ?>">
<table width="50%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
 <tr align="center">
   <td colspan="3">
	<strong>SMI superuser account</strong>
   </td>
 </tr>
 <tr align="center">
   <td>Username</td>
   <td>:</td>
   <td><input class="input" name="username" type="text" id="username" value="admin"></td>
 </tr>
 <tr align="center">
   <td>Password</td>
   <td>:</td>
   <td><input class="input" name="password" type="password" id="password" value="admin"></td>
 </tr>
</table>

<p><hr noshade height="1"></p>

<table width="60%" border="0" cellpadding="1" cellspacing="1" bgcolor="#FFFFFF">
 <tr align="center">
   <td colspan="3"><strong>General settings</strong></td>
 </tr>

<?
// Create a form with the general settings (category 1)
$db = dbConnect();
$settings = groupsettings('1');
  foreach ($settings as $setting) {

  // Find first time values
  if ($setting['setting'] == "web_addr") {
    $setting['value'] = "http://".str_replace('/install/install.php', '', $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"]);
  } elseif ($setting['setting'] == "smi_path") {
    $path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);
    $setting['value'] = str_replace('/install', '', $path_parts['dirname']);
  } elseif ($setting['setting'] == "host_addr") {
    $setting['value'] = $_SERVER["SERVER_ADDR"];
  }
  // Create &nbsp; to avoid breaks in setting's title
  $setting['title'] = str_replace(' ', '&nbsp;', $setting['title'])
?>
 <tr align="center">
   <td><? echo $setting['title']; ?></strong></td>
   <td>:</td>
   <td align="left">
     <?     // Check to see if this is a multiple choice setting
    $options = settingoptions($setting['id']);
    if (isset($options)) {
      echo "<select name=\"".$setting['setting']."\">\n";
      foreach ($options as $option) {
        echo "<option value=\"".$option['value']."\"";
        if ($option['value'] == $setting['value']) {
          echo " selected>";
        } else {
          echo ">";
        }
        echo $option['caption']."</option>\n";
      }
      echo "</select>\n";
    } else {
      if (strlen($setting['value']) < 8) {
        $fieldsize = "10";
      } else {
        $fieldsize = "25";
      }
      echo "<input class=\"input\" name=\"".$setting['setting']."\"
            value=\"".$setting['value']."\" size=\"".$fieldsize."\">\n";
    }
?>
 </tr>
<? } ?>
</table>

<center><input type="submit" name="step" value="Finish!"></center>
</form>

<?
}
?>
<div align="center">
<p>&nbsp;</p>
</div> 
</body>
</html>
