<?php
/**
* Install, installs the data tables
*
* @name Install
* @verision ---
* @package ---
* @author Rashaud Teague <rashaud.teague@gmail.com>
* @since 03/17/2009
* @license GNU GPL
*/

include 'common.php';

if (check_install())
	die('WARNING: '.APP_NAME.' seems to be already installed...check your database for further configurations.');

print '
<html>
	<head>
		<title>'.APP_NAME.' | Install</title>
		<link type = "text/css" rel = "stylesheet" href = "style.css" />
		
		<script type = "text/javascript" src = "jslib.js"></script>
	</head>
	<body>
	<table class = "header" border = "0" cellspacing = "0" cellpadding = "0" width = "100%">
		<tr>
		<td align = "left" class = "doctitle">Installation</td>
		<td align = "right"></td>
		</tr>
	</table><br />';

if (isset($_GET['step'])) {
	$step = $_GET['step'];
} else {
	if ($step == '')
		$step = 1;
	$step = 1;
}

switch ($step) {
	case 1:
		if (!isset($_POST['submit'])) {
			step1_form();
		} elseif (isset($_POST['submit'])) {
			validate_step1($_POST['servername'], $_POST['username'], $_POST['password'], $_POST['dbname']);
		}
		break;
	case 2:
		if (!isset($_POST['submit'])) {
			step2_form();
		} else {
			validate_step2($_POST['username'], $_POST['email'], $_POST['pass1'], $_POST['pass2']);
		}
		break;
	default:
		print 'Uncharted area...';
}

function step1_form($errors = array()) {
	print '<div class = "logincontainer">
	<div class = "logincontent">
	<div class = "loginheader">'.APP_NAME.' Installation</div>';
	if (sizeof($errors) > 0) {
		print '<div class = "errors">';
		foreach ($errors as $error) {
			print $error.'<br />';
		}
		print '</div>';
	}
	print '<form action = "'.APP_DIR.'install.php?step=1" method = "post">
	<table border = "0">
		<tr>
			<td align = "right">Servername:</td>
			<td><input type = "text" name = "servername" maxlength = "100" /></td>
		</tr>
		<tr>
			<td align = "right">Username:</td>
			<td><input type = "text" name = "username" maxlength = "100" /></td>
		</tr>
		<tr>
			<td align = "right">Password:</td>
			<td><input type = "password" name = "password" maxlength = "100" /></td>
		</tr>
		<tr>
			<td align = "right">Database Name:</td>
			<td><input type = "text" name = "dbname" maxlength = "100" /></td>
		</tr>
		<tr>
			<td></td>
			<td><input type = "submit" name = "submit" value = "Submit and Continue" /></td>
		</tr>
	</table>
	</form>
	</div>
	</div>';
}

function validate_step1($servername, $username, $password, $dbname) {
	global $security;
	$error_array = array();
	
	if (empty($servername))
		$error_array[] = 'ERROR: Servername is empty.';
	if (empty($username))
		$error_array[] = 'ERROR: Username is empty.';
	if (empty($password))
		$error_array[] = 'ERROR: Password is empty.';
	if (empty($dbname))
		$error_array[] = 'ERROR: Database Name is empty.';
	
	if (sizeof($error_array) < 1) {
		save_step1($servername, $username, $password, $dbname);
		$security->redirect(APP_DIR.'install.php?step=2');
	} else {
		step1_form($error_array);
	}
}

function save_step1($servername, $username, $password, $dbname) {
	$lines = file(CORE.'config.php');
	
	if (sizeof($lines) == 0)
		die('ERROR: Config file error...');
	
	$new_lines = array();
	for ($i = 0; $i <= sizeof($lines)-1; $i++) {
		if ($i == 22) {
			$new = '$dbsettings[\'servername\'] = \''.$servername.'\';'."\n";
			$new_lines[] = $new;
		} elseif ($i == 23) {
			$new = '$dbsettings[\'username\'] = \''.$username.'\';'."\n";
			$new_lines[] = $new;
		} elseif ($i == 24) {
			$new = '$dbsettings[\'password\'] = \''.$password.'\';'."\n";
			$new_lines[] = $new;
		} elseif ($i == 25) {
			$new = '$dbsettings[\'dbname\'] = \''.$dbname.'\';'."\n";
			$new_lines[] = $new;
		} elseif ($i == 26) {
			$new = '$dbsettings[\'prefix\'] = \'\';'."\n";
			$new_lines[] = $new;
		} else {
			$new_lines[] = $lines[$i];
		}
	}
	unset($lines);
	
	$pFile = fopen(CORE.'config.php', 'w');
	fwrite($pFile, implode('', $new_lines));
	fclose($pFile);
	
	//create "cached_config.php"
	$pCachedFile = fopen(CORE.'cached_config.php', 'w');
	fwrite($pCachedFile, implode('', $new_lines));
	fclose($pCachedFile);
}

function step2_form($errors = array()) {
	print '<div class = "logincontainer">
	<div class = "logincontent">
	<div class = "loginheader">'.APP_NAME.' Installation - Step 2</div>';
	if (sizeof($errors) > 0) {
		print '<div class = "errors">';
		foreach ($errors as $error) {
			print $error.'<br />';
		}
		print '</div>';
	}
	print '<form action = "'.APP_DIR.'install.php?step=2" method = "post">
	<table border = "0">
		<tr>
			<td align = "right">Admin Username:</td>
			<td><input type = "text" name = "username" maxlength = "50" /></td>
		</tr>
		<tr>
			<td align = "right">Admin Email Address:</td>
			<td><input type = "text" name = "email" maxlength = "100" /></td>
		</tr>
		<tr>
			<td align = "right">Password:</td>
			<td><input type = "password" name = "pass1" maxlength = "100" /></td>
		</tr>
		<tr>
			<td align = "right">Verify Password:</td>
			<td><input type = "password" name = "pass2" maxlength = "100" /></td>
		</tr>
		<tr>
			<td></td>
			<td><input type = "submit" name = "submit" value = "Submit and Install" /></td>
		</tr>
	</table>
	</form>
	</div>
	</div>';
}

function validate_step2($username, $email, $pass1, $pass2) {
	global $security;
	$error_array = array();
		
	if (empty($username))
		$error_array[] = 'ERROR: Username field is empty.';
	if (!$security->is_email($email))
		$error_array[] = 'ERROR: Invalid email address.';
	if (strlen($pass1) < 5)
		$error_array[] = 'ERROR: Your password needs to be at least 5 characters.';
	if ($pass2 != $pass1)
		$error_array[] = 'ERROR: Your passwords don\'t match.';
	
	if (sizeof($error_array) < 1) {
		install_tables($username, $email, $pass1);
		print 'The '.APP_NAME.' has been successfully installed. Please <a href = "'.APP_DIR.'?p=login">login</a> and edit your <a href = "'.APP_DIR.'?p=cp&tab=sys">system configuration</a> and start adding content!';
	} else {
		step2_form($error_array);
	}
}

function install_tables($username, $email, $password) {
	global $db;
	
	//users table
	$userstbl = <<<HERE
CREATE TABLE IF NOT EXISTS `docu_users` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `username` varchar(50) NOT NULL default '',
  `email` varchar(100) NOT NULL default '',
  `password` varchar(100) NOT NULL default '',
  `reg_date` int(10) unsigned NOT NULL default '0',
  `last_ip` varchar(100) NOT NULL default '',
  `auth` tinyint(1) unsigned NOT NULL default '1',
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM;
HERE;
	$db->exe_sql($userstbl);
	
	//install the first user
	$admin_user = mysql_real_escape_string(trim($username));
	$admin_email = mysql_real_escape_string(trim($email));
	$admin_password = md5($password);
	
	$first_user = "INSERT INTO docu_users VALUES(
	'',
	'$admin_user',
	'$admin_email',
	'$admin_password',
	'".time()."',
	'".getenv('REMOTE_ADDR')."',
	'3')";
	$db->exe_sql($first_user);
	
	//pages table
	$pagestbl = <<<HERE
CREATE TABLE IF NOT EXISTS `pages` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(50) NOT NULL default '',
  `content` text NOT NULL default '',
  `post_date` int(10) unsigned NOT NULL default '0',
  `last_update` int(10) unsigned NOT NULL default '0',
  `parent` int(10) unsigned NOT NULL default '0',
  `last_ip` varchar(100) NOT NULL default '',
  `p_order` int(5) unsigned NOT NULL default '0',
  `hidden` tinyint(1) unsigned NOT NULL default '0',
  `views` int(10) unsigned NOT NULL default '0',
  `locked` tinyint(1) unsigned NOT NULL default '0',
  UNIQUE KEY `id` (`id`),
  KEY `parent` (`parent`)
) ENGINE=MyISAM;
HERE;
	$db->exe_sql($pagestbl);
	
	//sys config table
	$sysconfigtbl = <<<HERE
CREATE TABLE IF NOT EXISTS `sys_config` (
  `org_name` varchar(100) NOT NULL default '',
  `site_url` varchar(150) NOT NULL default '',
  `org_email` varchar(100) NOT NULL default '',
  `doc_title` varchar(50) NOT NULL default '',
  `allow_registration` tinyint(1) NOT NULL default '1',
  `rsurl_toggle` tinyint(1) unsigned NOT NULL default '1',
  KEY `org_nam` (`org_name`)
) ENGINE=MyISAM;
HERE;
	$db->exe_sql($sysconfigtbl);
	
	//default sys config
	$default_sys = "INSERT INTO `sys_config`
	(`org_name`, `site_url`, `org_email`, `doc_title`, `allow_registration`) VALUES(
	'Example Organization',
	'http://www.yoursite.com',
	'email@yoursite.com',
	'Example Documentation Title',
	'1');";
	$db->exe_sql($default_sys);
}

print '<p>&nbsp;</p>
<div class = "footercontainer"><div class = "footercontent">Copyright &copy; '.date("Y").' 
<a href = "http://www.marislabs.org/" title = "Maris Labs">Maris Labs</a> | 
Powered by <a href = "" title = "Maris SimpleDocu">Maris SimpleDocu</a>&trade; v'.APP_VERSION.'</div></div>
</body>
</html>';
?>