<?php
// $Id: install2.php,v 1.17 2004/03/20 11:17:38 rcastley Exp $
/**
* Step 2 of Installation
* @package Mambo Open Source
* @Copyright (C) 2000 - 2003 Miro International Pty Ltd
* @ All rights reserved
* @ Mambo Open Source is Free Software
* @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html
* @version $Revision: 1.17 $
**/

define( "_VALID_MOS", 1 );

require_once( "common.php" );
require_once( "../classes/database.php" );

$DBhostname = trim( mosGetParam( $_POST, 'DBhostname', '' ) );
$DBuserName = trim( mosGetParam( $_POST, 'DBuserName', '' ) );
$DBpassword = trim( mosGetParam( $_POST, 'DBpassword', '' ) );
$DBname  	= trim( mosGetParam( $_POST, 'DBname', '' ) );
$DBDel  	= intval( trim( mosGetParam( $_POST, 'DBDel', 0 ) ) );
$DBBackup  	= intval( trim( mosGetParam( $_POST, 'DBBackup', 0 ) ) );
$DBSample  	= trim( mosGetParam( $_POST, 'DBSample', '' ) );
$DBHelp 	= trim( mosGetParam( $_POST, 'DBHelp', '' ) );
$DBcreated = trim( mosGetParam( $_POST, 'DBcreated', 0 ) );
$DBPrefix = 'mos_';
$BUPrefix = 'old_';

$configArray['sitename'] = trim( mosGetParam( $_POST, 'sitename', '' ) );

$database = null;

if ($DBcreated != 1){
	if (!$DBhostname || !$DBuserName || !$DBname) {
		db_err ("stepBack3","The database details provided are incorrect and/or empty.");
	}

	if (!($mysql_link = @mysql_connect( $DBhostname, $DBuserName, $DBpassword ))) {
		db_err ("stepBack2","The password and username provided are incorrect.");
	}

	if($DBname == "") {
		db_err ("stepBack","The database name provided is empty.");
	}

	$configArray['DBhostname'] = $DBhostname;
	$configArray['DBuserName'] = $DBuserName;
	$configArray['DBpassword'] = $DBpassword;
	$configArray['DBname']     = $DBname;

	$sql = "CREATE DATABASE `$DBname`";
	$mysql_result = mysql_query( $sql );
	$test = mysql_errno();

	if ($test <> 0 && $test <> 1007) {
		db_err( "stepBack", "A database error occurred\n".mysql_error() );
	}

	// db is now new or existing, create the db object connector to do the serious work
	$database = new database( $DBhostname, $DBuserName, $DBpassword, $DBname, $DBPrefix );

	// delete existing mos table if requested
	if ($DBDel) {
		$database->setQuery( "SHOW TABLES FROM $DBname" );
		$errors = array();
		if ($tables = $database->loadResultArray()) {
			foreach ($tables as $table) {
				if (strpos( $table, $DBPrefix ) === 0) {
					if ($DBBackup) {
						$butable = str_replace( $DBPrefix, $BUPrefix, $table );
						$database->setQuery( "DROP TABLE IF EXISTS $butable" );
						$database->query();
						if ($database->getErrorNum()) {
							$errors[$database->getQuery()] = $database->getErrorMsg();
						}
						$database->setQuery( "RENAME TABLE $table TO $butable" );
						$database->query();
						if ($database->getErrorNum()) {
							$errors[$database->getQuery()] = $database->getErrorMsg();
						}
					}
					$database->setQuery( "DROP TABLE IF EXISTS $table" );
					$database->query();
					if ($database->getErrorNum()) {
						$errors[$database->getQuery()] = $database->getErrorMsg();
					}
				}
			}
		}
		/*
		if (count($errors)) {
			// abrupt failure...need to work on this
			echo '<pre>';print_r( $errors );echo '</pre>';
			die;
		}
		*/
	}

	populate_db($DBname,'mambo.sql');
	if ($DBSample == 1) {
		populate_db($DBname,'sample_data.sql');
	}
	if ($DBHelp == 1) {
		populate_db($DBname,'help.sql');
	}
}

function db_err($step, $alert) {
	global $DBhostname,$DBuserName,$DBpassword,$DBDel,$DBname;
	echo "<form name=\"$step\" method=\"post\" action=\"install1.php\">
	<input type=\"hidden\" name=\"DBhostname\" value=\"$DBhostname\">
	<input type=\"hidden\" name=\"DBuserName\" value=\"$DBuserName\">
	<input type=\"hidden\" name=\"DBpassword\" value=\"$DBpassword\">
	<input type=\"hidden\" name=\"DBDel\" value=\"$DBDel\">
	<input type=\"hidden\" name=\"DBname\" value=\"$DBname\">
	</form>";
	//echo "<SCRIPT>alert(\"$alert\"); document.$step.submit();</SCRIPT>";
	echo "<SCRIPT>alert(\"$alert\"); window.history.go(-1);</SCRIPT>";
	exit();
}

function populate_db($DBname, $sqlfile='mambo.sql') {
	mysql_select_db($DBname);
	$mqr = @get_magic_quotes_runtime();
	@set_magic_quotes_runtime(0);
	$query = fread(fopen("../sql/".$sqlfile, "r"), filesize("../sql/".$sqlfile));
	@set_magic_quotes_runtime($mqr);
	$pieces  = split_sql($query);
	$errors = array();
	for ($i=0; $i<count($pieces); $i++) {
		$pieces[$i] = trim($pieces[$i]);
		if(!empty($pieces[$i]) && $pieces[$i] != "#") {
			if (!$result = mysql_query ($pieces[$i])) {
				$errors[] = array ( mysql_error(), $pieces[$i] );
			}
		}
	}
}

function split_sql($sql) {
	$sql = trim($sql);
	$sql = ereg_replace("\n#[^\n]*\n", "\n", $sql);

	$buffer = array();
	$ret = array();
	$in_string = false;

	for($i=0; $i<strlen($sql)-1; $i++) {
		if($sql[$i] == ";" && !$in_string) {
			$ret[] = substr($sql, 0, $i);
			$sql = substr($sql, $i + 1);
			$i = 0;
		}

		if($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
			$in_string = false;
		}
		elseif(!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
			$in_string = $sql[$i];
		}
		if(isset($buffer[1])) {
			$buffer[0] = $buffer[1];
		}
		$buffer[1] = $sql[$i];
	}

	if(!empty($sql)) {
		$ret[] = $sql;
	}
	return($ret);
}
?>
<?php echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Mambo Open Source Installer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="shortcut icon" href="../../images/M_images/favicon.ico" />
<link rel="stylesheet" href="install.css" type="text/css" />
</head>
<body>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="dottedline">
  <tr>
    <td align="center" class="contentbackgr"><span class="installheader">Welcome
      to Mambo Open Source installation</span></td>
  </tr>
</table>
<br />
<form action="install3.php" method="post" name="form" id="form">
  <input type="hidden" name="DBhostname" value="<?php echo "$DBhostname"; ?>" />
  <input type="hidden" name="DBuserName" value="<?php echo "$DBuserName"; ?>" />
  <input type="hidden" name="DBpassword" value="<?php echo "$DBpassword"; ?>" />
  <input type="hidden" name="DBname" value="<?php echo "$DBname"; ?>" />

  <table width="550" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
      <td width="10" height="10"><img src="../images/M_images/top_left_corner.png" width="10" height="10" /></td>
      <td background="../images/M_images/top_line.png"></td>
      <td width="10" height="10"><img src="../images/M_images/top_right_corner.png" width="10" height="10" /></td>
    </tr>
    <tr>
      <td background="../images/M_images/left_line.png"></td>
      <td>
  <table width="100%" border="0" align="center" cellpadding="0" cellspacing="4">
          <tr>
            <td colspan="2" class="heading">Step 2 - Enter the name of your Mambo Open
        Source site</td>
          </tr>
<?php
	if (@count($errors)) {
		echo "<tr><td colspan=\"2\">";
		echo "<b>Looks like there have been some errors with inserting data into your database!<br />
			You can continue, but you may need to manually insert the database data.</b>";
		echo "<br /><br />Error log:<br />\n";
		// abrupt failure
		echo '<pre>';print_r( $errors );echo '</pre>';
		foreach($errors as $key => $value) {
			echo "$key: $value<br />\n";
		}
		echo "</td></tr>\n";
	}
?>
          <tr>
            <td colspan="2"> <p>Type in the name for your Mambo Open Source site. This
          name is used in email messages so make it something meaningful. <br />
          <br />
        </p></td>
          </tr>
          <tr>
            <td width="100">Site name</td>
            <td align="center"><input class="inputbox" type="text" name="sitename" size="50" value="<?php echo "{$configArray['sitename']}"; ?>" /></td>
          </tr>
          <tr>
            <td width="100">&nbsp;</td>
            <td align="center" class="small">e.g. The Home of Mambo Open Source</td>
          </tr>
          <tr>
            <td colspan="2" align="right"><br />
        <input class="button" type="submit" name="next" value='Next' /> </td>
          </tr>
  </table></td>
      <td background="../images/M_images/right_line.png"></td>
    </tr>
    <tr>
      <td width="10" height="10" background="../images/M_images/bottom_left_corner.png"></td>
      <td background="../images/M_images/bottom_line.png"></td>
      <td width="10" height="10" background="../images/M_images/bottom_right_corner.png"></td>
    </tr>
  </table>
</form>
</body>
</html>
