<?php
// +----------------------------------------------------------------+
// | install/index.php												|
// |																|
// | Function: Install script for Atmail webmail client				|
// +----------------------------------------------------------------+
// | Source-code (C) CalaCode.com 1998-2009 . All rights reserved	|
// | See http://calacode.com/license.ehtml for license agreement	|
// +----------------------------------------------------------------+
// | Date: May 2006													|
// +----------------------------------------------------------------+
// define minimum PHP version required
define('ATMAIL_MIN_PHP_VERSION', '5.1.6');

// Read in current Atmail version
$atmailVersion = trim(@file_get_contents('../.VERSION'));

// Setup lib paths
define('APP_ROOT', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
$path = dirname(dirname(__FILE__));
set_include_path('.' . PATH_SEPARATOR . "$path/library/");

session_start();

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
//$loader->registerNamespace('App_'); //for model namespacing
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);

// Report all errors except E_NOTICE
error_reporting(E_ALL ^ E_NOTICE);

// Security Check! Double check that the .htaccess file does not exist!!
// If the directory under which we are installed has "AllowOverride none"
// or "AccessFile" is not == ".htaccess" in httpd.conf then our .htaccess
// will not have stopped access
// Do before copying Config.php.default, otherwise will overwrite it!
if (file_exists('.htaccess'))
{
	echo <<<EOF
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>Atmail already installed</title>
</head><body>
<h1>Install Error</h1>
<p>The installer can not go any further as it seems you have already installed Atmail
on your system.</p>
<p>For added security the installer cannot proceed until you remove the
webmail/install/.htaccess file. Once removed reload the browser to continue the installation.</p>
</body></html>
EOF;
	exit;
}

// Find out which step of the install is required
$vars = array();

$vars['step'] = $step = (!empty($_REQUEST['step'])) ? $_REQUEST['step'] : 0;

// Check config directory write permissions
$libDir = dirname(dirname(__FILE__)) . '';
$fp = @fopen('../config/write.test', 'w+');
if ($fp)
{
	@fclose($fp);
}
else
{
	$vars['php_version'] = PHP_VERSION;
	$vars['install_error'] = "Please ensure that $libDir is writable by webserver user. See the <a href='http://support.atmail.com/php/webmail-install.html'>installation documentation</a> for the complete tutorial on installing Atmail";
	$vars['install_error2'] = "To change the permissions run on the command-line: <p><em>chown -R [webserveruser] $libDir</em><p>Where [webserveruser] is the user which runs Apache ( Generally user apache, nobody or www )";
	$vars['output'] = parse("html/english/install_error.html", $vars);
	echo parse("html/english/template.phtml", $vars);
	exit;
}

if (!file_exists('../config/dbconfig.ini'))
{
	if (!copy('../config/dbconfig.ini.default', '../config/dbconfig.ini'))
	{
		$vars['php_version'] = PHP_VERSION;
		$vars['install_error'] = "Please ensure that $libDir is writable by webserver user. See the <a href='http://support.atmail.com/php/webmail-install.html'>installation documentation</a> for the complete tutorial on installing Atmail";
		$vars['install_error2'] = "To change the permissions run on the command-line: <p><em>chown -R [webserveruser] $libDir</em><p>Where [webserveruser] is the user which runs Apache ( Generally user apache, nobody or www )";
		$vars['output'] = parse("html/english/install_error.html", $vars);
		echo parse("html/english/template.phtml", $vars);
		exit;
	}
}

// Initial check for PHP version >= 4.3.0
if (version_compare(PHP_VERSION, ATMAIL_MIN_PHP_VERSION, '<'))
{
	$vars['php_version'] = PHP_VERSION;
	$vars['install_error'] = 'PHP Version not Supported';
	$vars['install_error2'] = "Atmail requires PHP version >= " . ATMAIL_MIN_PHP_VERSION . ". Your version is {$vars['php_version']}, the installation cannot proceed until you install a more recent version of PHP";
	$vars['output'] = parse("html/english/install_error.html", $vars);
	echo parse("html/english/template.html", $vars);
	exit;
}

// Set session vars for extension checks
$_SESSION['checked_extensions'] = 1;
if (isset($ext) && count($ext['opt']))
{
	$_SESSION['missing_ext'] = $ext['opt'];
}

$_SESSION['pref']['version'] = $atmailVersion;

// Set our lang var if known
$lang = isset($_SESSION['step1']['lang']) ? $_SESSION['step1']['lang'] : 'english';

// If language $lang is not supported for installation script
// default to english
$htmlPath = ( @is_dir("html/$lang") && $lang ) ? "html/$lang" : 'html/english';

// Set up a constant to prove to the install step scripts
// that they have been included by this script
define('ATMAIL_INSTALL_SCRIPT', 1);

if (file_exists("step$step.php"))
{
	// ensure any step does NOT recreate $vars array
	require_once("step$step.php");
}
else
{
	$vars['output'] = parse("$htmlPath/file_missing_error.html");
}

// Output the page
echo parse("$htmlPath/template.phtml", $vars);
//
// Functions
//
// Send user to a install step
function gotoStep($step, $args=null)
{
	$extra = '';
	if (is_array($args))
	{
		foreach ($args as $k => $v)
		{
			$extra .= "&$k=$v";
		}
	}

	$s = empty($_SERVER["HTTPS"]) ? "" : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/") . $s;
	$port = ($_SERVER['SERVER_PORT'] != '80') ? ':' . $_SERVER['SERVER_PORT'] : '';
	$location = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['SCRIPT_NAME'] . "?step=$step$extra";
	header("Location: $location");
	exit;
}

// Parse a HTML/Template file, and expand all vars into a value
function parse($file, $var=null)
{
	// Make Config vars available
	global $pref, $reg, $domains, $settings;

	ob_start();
	include($file);
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}

function strleft($s1, $s2)
{
	return substr($s1, 0, strpos($s1, $s2));
}

function findBinary($searcharray)
{
	// Check for safe mode, otherwise we cannot exec
	if (ini_get('safe_mode') || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
	{
		return;
	}

	// Find where a specified command is on the server
	foreach ($searcharray as $command)
	{
		$cmd = `whereis -b $command`;
		$cmd = trim($cmd);

		if (preg_match('/:\s(.*)\s?/', $cmd, $m))
		{
			return $m[1];
		}
	}

	return '';
}

