<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 8/26/2016	ELL

include ("include.php");
ini_set("track_errors", 1);

$template_file = $_POST['template_file'];
$userid = $_POST['userid'];
$password = $_POST['password'];
$require_ssl = 0;
$user_salt = $_POST["user_salt"];
$public_salt = $_POST["public_salt"];

if (isset($_POST['email']) && ($_POST['email'] != ""))
	$email = $_POST['email'];
else
	$email = "";
if (isset($_POST['first_name']) && ($_POST['first_name'] != ""))
	$first_name = $_POST['first_name'];
else
	$first_name = "";
if (isset($_POST['last_name']) && ($_POST['last_name'] != ""))
	$last_name = $_POST['last_name'];
else
	$last_name = "";

$language = $_POST["language"];
$access_level = "power_user";

$document_root = $_SERVER['DOCUMENT_ROOT'];
$stock_config_file = $document_root . "/firsttime/config.php";
$config_file = $document_root . "/connect/config.php";

if ((ini_get("allow_url_fopen") == 1) || (ini_get("allow_url_fopen") === true) || (strtolower(ini_get("allow_url_fopen")) == "on"))
{
	$ip = (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : "");
	$website = (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : "");
	$url = 'http://breezewebsitebuilder.com/php/generate_license.php';
	$delim = "?";
	if (isset($website) && ($website != ""))	{
		$url .= $delim . "website=" . $website;
		$delim = "&";
	}
	if (isset($email) && ($email != ""))	{
		$url .= $delim . "email=" . $email;
		$delim = "&";
	}
	if (isset($first_name) && ($first_name != ""))	{
		$url .= $delim . "first_name=" . $first_name;
		$delim = "&";
	}
	if (isset($last_name) && ($last_name != ""))	{
		$url .= $delim . "last_name=" . $last_name;
		$delim = "&";
	}
	if (isset($ip) && ($ip != ""))	{
		$url .= $delim . "ip=" . $ip;
		$delim = "&";
	}
	if (isset($language) && ($language != ""))	{
		$url .= $delim . "language=" . $language;
		$delim = "&";
	}
	$sn = file_get_contents($url);
}
else
	$sn = time();

///////////////////////////////////////////////////////////
function doEncrypt($Data, $Key)
{
// encrypting  a[] with key k[] into e[]
// a[] = array to be encrypted
// k[] = key of truly random gibberish
// e[] = encrypted data

	for( $i = 0; $i < strlen($Data); $i++)
	{
		$c = substr($Data, $i, 1);
		$a[$i] = ord($c);
	}
	
	for( $i = 0; $i < strlen($Data); $i++)
	{
		if ($i < strlen($Key))
		{
			$c = substr($Key, $i, 1);
			$k[$i] = ord($c);
		}
		else
			$k[$i] = 65 + $i;
	}
	
	for ( $i=0; $i < strlen($Data); $i++ )
   	{
   		$e[$i] = $k[$i] ^ $a[$i];
   	}
	
	$encrypted = "";
	for ( $i = 0; $i < strlen($Data); $i++ )
	{
		$encrypted = $encrypted. decToHex($e[$i]);
	}
	return($encrypted);
	
}

function decToHex($dec)
{
	$hexStr = "0123456789ABCDEF";
	$low = $dec % 16;
	$high = ($dec - $low)/16;
	$hex = "";
	$hex = substr($hexStr, $high, 1) . substr($hexStr, $low, 1);
	return $hex;
}

function AddUser($user_name, $salted_password, $password, $access_level, $email, $first_name, $last_name, $db_prefix, $dbh)
{
	$encrypt_password = doEncrypt($salted_password, $user_name);
	// Add user.
	$query = "INSERT INTO `" . $db_prefix . "users` SET `UserID`='$user_name', `password`='$encrypt_password', `email`='$email', `first_name`='$first_name', `last_name`='$last_name', `AccessLevel`='$access_level'";
	$cnt = $dbh->exec($query);
}

/////////////////////////////////////////////////////////////////
// Insert salt into password.
$pos = rand(0, (strlen($password)-1) );
$pass1 = substr($password, 0, $pos);
$pass2 = substr($password, $pos);
$salted_pass = $pass1 . $user_salt . $pass2;

$sql = "TRUNCATE TABLE " . BWB_TABLE_PREFIX . "users";
$cnt = $bwb_dbh->exec($sql);

//Encrypt password using user name as key.
AddUser($userid, $salted_pass, $password, $access_level, $email, $first_name, $last_name, BWB_TABLE_PREFIX, $bwb_dbh);
	
session_start();
$_SESSION['userid'] = $userid;
$session = md5(session_id());
$ip = $_SERVER['REMOTE_ADDR'];
$query = "UPDATE `" . BWB_TABLE_PREFIX . "users` SET `Session`='$session', `IP`='$ip' WHERE `UserID` = :userid";
$stmt = $bwb_dbh->prepare($query);
$stmt->execute(array(':userid' => $userid));

if ($access_level == "restricted")
{
	$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='EnableFileManager'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$enable_file_manager = $row["option_value"];
}

if (($access_level != "restricted") || ($enable_file_manager == 1))
	$_SESSION['enable_file_manager'] = "100";
else
	$_SESSION['enable_file_manager'] = "0";

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Breeze Website Builder Install</title>
<link type="text/css" href="/manage/theme/classic/manager.css" rel="stylesheet" />
<link type="image/x-icon" href="/manage/images/favicon.ico" rel="shortcut icon" />
<style type="text/css">
#login_btn	{
	border-style:solid;
	border-width:medium;
	border-color:#0000FF;
	background-color:#00FFFF;
	text-decoration:none;
	font-size:18px;
	font-weight:bold;
	display:inline;
	padding:5px;
	line-height:18px;
	position:relative;
	top:-8px;
}
#login_btn A:link	{
	text-decoration:none;
}
#login_btn:hover	{
	cursor:pointer;
	color:#FFFFFF;
	background-color:#FFFF00;
}
	
.content_div	{
	padding-left:10px;
	padding-right:10px;
}
</style>
</head>

<body>
	<div align="center" id="login_logo"><img alt="Breeze Website Builder" src="/manage/theme/classic/images/Breeze_header_logo.png" /></div>
    <div id="header_divider_login"> </div>
    <div class="content_div">
<?php

// Setup connect file.
echo "Installation starting.  Scroll to bottom of this screen after installations is complete.<br><br>\n";

echo "\n<br />Creating new user account...<br><br>\n";
echo "The password for <b>$userid</b> has been set to <b>$password</b>.<br><br>\n";

// Setup config file.
echo "\n<br />Saving configuration...<br><br>\n";

$contents = "";

if (!($fh3 = fopen($stock_config_file, 'r'))) {
	echo "Error opening original config file.  Please contact your system administrator.  Click <a href=\"install.php\" title=\"here\">here</a> to return to the installation start.\n$php_errormsg";
	exit;
}

$contents = (fread($fh3, filesize($stock_config_file)));
fclose($fh3);

$contents = str_replace("define('BWB_BASE_DIR', '');", "define('BWB_BASE_DIR', '" . BWB_BASE_DIR . "');", $contents);
$contents = str_replace("define('BWB_WEBPAGE_DIR', '');", "define('BWB_WEBPAGE_DIR', '" . BWB_WEBPAGE_DIR . "');", $contents);
$contents = str_replace("define('BWB_IMAGE_DIR', 'images');", "define('BWB_IMAGE_DIR', '" . BWB_IMAGE_DIR . "');", $contents);
$contents = str_replace("define('BWB_CSS_DIR', 'css');", "define('BWB_CSS_DIR', '" . BWB_CSS_DIR . "');", $contents);
$contents = str_replace("define('BWB_FLASH_DIR', 'flash');", "define('BWB_FLASH_DIR', '" . BWB_FLASH_DIR . "');", $contents);
$contents = str_replace("define('BWB_MEDIA_DIR', 'media');", "define('BWB_MEDIA_DIR', '" . BWB_MEDIA_DIR . "');", $contents);
$contents = str_replace("define('BWB_SCRIPTS_DIR', 'scripts');", "define('BWB_SCRIPTS_DIR', '" . BWB_SCRIPTS_DIR . "');", $contents);
$contents = str_replace("define('BWB_FONTS_DIR', 'fonts');", "define('BWB_SCRIPTS_DIR', '" . BWB_SCRIPTS_DIR . "');", $contents);
$contents = str_replace("define('BWB_TABLE_PREFIX', 'bwb_');", "define('BWB_TABLE_PREFIX', '" . BWB_TABLE_PREFIX . "');", $contents);
$contents = str_replace("define('BWB_REQUIRE_SSL', 0);", "define('BWB_REQUIRE_SSL', '" . $require_ssl . "');", $contents);
$contents = str_replace("define('BWB_SALT', '!oegTGFhFD87@');", "define('BWB_SALT', '" . $user_salt . "');", $contents);
$contents = str_replace("define('BWB_PUB_SALT', '#uePYd%3f78C');", "define('BWB_PUB_SALT', '" . $public_salt . "');", $contents);
$contents = str_replace("define('BWB_SN', '255.255.255.255-1');", "define('BWB_SN', '" . $sn . "');", $contents);
$contents = str_replace("define('SESSION_SAVE_PATH', '/tmp');", "define('SESSION_SAVE_PATH', '" . SESSION_SAVE_PATH . "');", $contents);
$contents = str_replace("define('BWB_LANG', 'en');", "define('BWB_LANG', '" . $language . "');", $contents);

if (!($fh4 = fopen($config_file, 'w'))) {
	echo "Error opening config file.  Please contact your system administrator.  Click <a href=\"install.php\" title=\"here\">here</a> to return to the installation start.\n$php_errormsg";
	exit;
}

if (!fwrite($fh4, $contents)) {
			echo "Error updating config file.  Please contact your system administrator.  Click <a href=\"install.php\" title=\"here\">here</a> to return to the installation start.\n$php_errormsg";
			exit;
		}
if (!fclose($fh4)) {
	echo "Error closing config file.  Please contact your system administrator.  Click <a href=\"install.php\" title=\"here\">here</a> to return to the installation start.\n$php_errormsg";
	exit;
}
@chmod($config_file, 0644);

include ("install_template.php");
?>
<p><b>Installation complete.</b>  Click here <a href="finish.php"><span id="login_btn">Start using the Breeze&#8482; Website Builder</span></a> to start editing your website.</p>
<p>Thanks for using the Breeze&#8482; Website Builder!</p>
</div>
<script>
	var bottom = document.body.scrollHeight;
	var from_height = 0;
	var step = parseInt(bottom/100);
	var to_height = 0;
	var code = "AnimateScroll();";
	
	function AnimateScroll()
	{
		if (to_height < bottom)
		{
			to_height = to_height + step;
			window.scrollTo(from_height, to_height);
			setTimeout(code, 10);
			from_height = to_height;
		}
	}
	AnimateScroll();
	
	var redir_code = "window.location='finish.php';";
//	setTimeout(redir_code, 1000);
</script>
</body>
</html>