<?php
// +----------------------------------------------------------------+
// | step8.php														|
// |																|
// | Function: Write settings to config files and DB and finish up  |
// +----------------------------------------------------------------+
// | Source-code (C) CalaCode.com 1998-2009. All rights reserved	|
// | See http://calacode.com/license.ehtml for license agreement	|
// +----------------------------------------------------------------+
// | Date: May 2009													|
// +----------------------------------------------------------------+

// Make sure we are included from install/index.php, exit if not
if (!defined('ATMAIL_INSTALL_SCRIPT')) {
// link to installer
	die("You cannot request this file directly, please use <a href=\"index.php\">the installer</a>");
}

$vars['htaccess_error'] = false;
$vars['missing_ext'] = false;

// Setup log path
$logPath = '../log' . DIRECTORY_SEPARATOR . 'atmail.log';
if ( !file_exists($logPath)) {
	touch($logPath);
}

$logWriter = new Zend_Log_Writer_Stream($logPath);
$log = new Atmail_Log($logWriter);
$log->info('');
$log->info('------------------------------');
$log->info('Installation completed at: ' . time());
Zend_Registry::set('log', $log);

$pref = $_SESSION['pref'];
$reg = $_SESSION['reg'];
$plugins = $_SESSION['plugins'];

// Find the root dir of Atmail client system
$vars['install_dir'] = $pref['install_dir'] = dirname(dirname(__FILE__));

// Get the login URL
$vars['login_url'] = dirname(dirname($_SERVER['SCRIPT_NAME']));

$vars['webadmin_setup'] = $_SESSION['webadmin_setup'];

$pref['installdate'] = date('M d Y');
$pref['installed'] = 1;

// Set the location of the tmp dir
if ($pref['install_type'] == 'standalone')	{
	$pref['user_dir'] = $pref['install_dir'];
	$pref['allow_Signup'] = '0';
} else {
	$pref['user_dir'] = '/usr/local/atmail/';
}

$pref['aspell_path'] = findBinary(array('aspell', 'ispell'));
$pref['gpg_path'] = checkBinary(array('/usr/bin/gpg', '/usr/local/bin/gpg'));
$pref['openssl_path'] = checkBinary(array('/usr/bin/openssl', '/usr/local/bin/openssl'));

// Find the hostname of the server for SMTP HELO - step5 does this step now
//if (strpos(PHP_OS, 'WINNT') === false)
//	$pref['hostname'] = trim(`hostname`);

// If running Darwin, mysql does not accept connections on localhost, needs 127.0.0.1
if (PHP_OS == 'Darwin' && $pref['sql_host'] == 'localhost') {
    $pref['sql_host'] = '127.0.0.1';
}

// See if we have tnef installed
$pref['decode_tnef'] = 1;
$pref['tnef_path'] = '';

// Turn off decode_tnef if not supported
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
	$pref['decode_tnef'] = 0;
} else {
	$pref['tnef_path'] = findBinary(array('tnef'));
	if (empty($pref['tnef_path'])) {
		$pref['decode_tnef'] = 0;
	}
}

// Get database configuration    
$dbConfig = new Zend_Config_Ini('../config/dbconfig.ini', 'production');
Zend_Registry::set('dbConfig', $dbConfig);
$dbAdapter = Zend_Db::Factory($dbConfig->database);
$dbAdapter->query("SET NAMES 'utf8'");
Zend_Db_Table::setDefaultAdapter($dbAdapter);
Zend_Registry::set('dbAdapter', $dbAdapter);

//Get main configuration from database
$config = new Atmail_Config_Mysql($dbConfig, true);
Zend_Registry::set('config', $config);

$defaults = array();
$defaults['ThreadLimit'] = 6;

// Setup calendar off in the default group if required
$dbAdapter->update("Groups", array('Calendar' => 1), "GroupName='default'");
	
if( !isset($pref['allow_Push']) )
    $dbAdapter->update("Groups", array('PushSupport' => 0), "GroupName='default'");
else
	$dbAdapter->update("Groups", array('PushSupport' => $pref['allow_Push']), "GroupName='default'");

// Now save all collected data
require_once '../application/models/config.php';

config::save('global', $pref);
config::save('reg', $reg);
config::save('plugins', $plugins);
config::save('defaultUserSettings', $defaults);
                      

// Create the .htaccess to prevent a malicious re-install
$fh = @fopen('.htaccess', 'w');
if( is_resource($fh) )
{
	fwrite($fh, "<FilesMatch \"\.(php|html)$\">\norder allow,deny\ndeny from all\n</FilesMatch>");
	fclose($fh);
	chmod('.htaccess', 0640);
} else {
	$vars['htaccess_error'] = true;
}

@touch($pref['install_dir'] . '/.installed');

if (isset($_SESSION['missing_ext'])) {
	$vars['missing_ext'] = '<h2>Optional PHP Extensions</h2>
	<p>The following optional PHP extensions are missing. You may enable
	additional Atmail features if you install them</p><ul>';

	foreach ($_SESSION['missing_ext'] as $ext)
		$vars['missing_ext'] .= "<li>$ext functions</i>";

	$vars['missing_ext'] .= '</ul>';
}

// copy the clean-logs.php script into the daily cron
$vars['clean_logs_error'] = false;
$cleanLog = $pref['install_dir'] . "/utilities/tools/clean-logs.php";

$vars['cleanLogsScriptPath'] = $pref['install_dir'] . '/config/clean-logs.sh'; 
foreach (array("/etc/cron.daily", "/etc/periodic/daily") as $cronDir) {	
	if (is_dir($cronDir)) {
		$vars['cronDir'] = $cronDir;
		try
		{

			$cronFile = $vars['cleanLogsScriptPath'];
			if(!createCronWrapper($cronFile, $cleanLog)) {
				$var['clean_logs_error'] = true;
				break;
			}

			$vars['cleanLogsInCron'] = @copy($cronFile, "$cronDir/clean-logs.sh");
			
			if($vars['cleanLogsInCron'])
			{
				`chown root $cronDir/clean-logs.sh; chmod u+x $cronDir/clean-logs.sh`;
			}
			else
			{
				$vars['clean_logs_error'] = true;
			}
		}
		catch(Exception $e)
		{
			$vars['clean_logs_error'] = true;
			break;
		}
		break;
	}
}

$vars['output'] = parse("$htmlPath/step8.phtml", $vars);

session_destroy();

function createCronWrapper($fileName, $cleanLog)
{
	
	$handle = fopen($fileName, 'w');
	if(!$handle) return false;
	
	$script = "#!/bin/sh\n" .
			  "php " .  $cleanLog . "\n";
			  
	fwrite($handle, $script);
	fclose($handle);

	return true;
}

function checkBinary($searcharray)
{
	// Find where a specified command is on the server
	foreach ( $searcharray as $command)
	{
		if(is_file($command))
			return $command;
	}

	return '';
}
