<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of DotClear.
# Copyright (c) 2005 Olivier Meunier and contributors. All rights
# reserved.
#
# DotClear is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# DotClear is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with DotClear; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ***** END LICENSE BLOCK *****

if (isset($_SERVER['DC_RC_PATH'])) {
	$rc_path = $_SERVER['DC_RC_PATH'];
} elseif (isset($_SERVER['REDIRECT_DC_RC_PATH'])) {
	$rc_path = $_SERVER['REDIRECT_DC_RC_PATH'];
} else {
	$rc_path = dirname(__FILE__).'/../../inc/config.php';
}

if (!is_file($rc_path)) {
	printf('Configuration file does not exist. Please create one
first. You may use the <a href="%s">wizard</a>.','wizard.php');
	exit;
}

require dirname(__FILE__).'/../../inc/prepend.php';
require dirname(__FILE__).'/check.php';

$can_install = true;
$err = '';

# Loading locales for detected language
$dlang = http::getAcceptLanguage();
if ($dlang) {
	l10n::init();
	l10n::set(dirname(__FILE__).'/../../locales/'.$dlang.'/main');
}

if (!defined('DC_MASTER_KEY') || DC_MASTER_KEY == '') {
	$can_install = false;
	$err = '<p>'.__('Please set a master key (DC_MASTER_KEY) in configuration file.').'</p>';
}

# Check if dotclear is already installed
$schema = dbSchema::init($core->con);
if (in_array($core->prefix.'version',$schema->getTables())) {
	$can_install = false;
	$err = '<p>'.__('DotClear is already installed.').'</p>';
}

# Check system capabilites
if (!dcSystemCheck($core->con,$_e)) {
	$can_install = false;
	$err = '<p>'.__('DotClear cannot be installed.').'</p><ul><li>'.implode('</li><li>',$_e).'</li></ul>';
}

# Get information and perform install
$u_email = $u_firstname = $u_name= '';
$mail_sent = false;
if ($can_install && !empty($_POST))
{
	$u_email = !empty($_POST['u_email']) ? $_POST['u_email'] : null;
	$u_firstname = !empty($_POST['u_firstname']) ? $_POST['u_firstname'] : null;
	$u_name = !empty($_POST['u_name']) ? $_POST['u_name'] : null;
	
	try
	{
		if (empty($u_email)) {
			throw new Exception(__('No email'));
		}
		if (!text::isEmail($u_email)) {
			throw new Exception(__('Invalid email address'));
		}
		
		$_s = new dbStruct($core->con,$core->prefix);
		require dirname(__FILE__).'/../../inc/dbschema/db-schema.php';
		
		$si = new dbStruct($core->con,$core->prefix);
		$changes = $si->synchronize($_s);
		
		$user_pwd = crypt::createPassword();
		
		$cur = $core->con->openCursor($core->prefix.'user');
		$cur->user_id = 'admin';
		$cur->user_super = 1;
		$cur->user_pwd = crypt::hmac(DC_MASTER_KEY,$user_pwd);
		$cur->user_name = (string) $u_name;
		$cur->user_firstname = (string) $u_firstname;
		$cur->user_email = (string) $u_email;
		$cur->user_lang = $dlang;
		$cur->user_creadt = array('NOW()');
		$cur->user_upddt = array('NOW()');
		$cur->user_options = serialize($core->userDefaults());
		$cur->insert();
		
		$core->auth->checkUser('admin');
		
		$admin_url = preg_replace('%install/index.php$%','',$_SERVER['REQUEST_URI']);
		$root_url = preg_replace('%/admin/install/index.php$%','',$_SERVER['REQUEST_URI']);
		
		$cur = $core->con->openCursor($core->prefix.'blog');
		$cur->blog_id = 'default';
		$cur->blog_url = http::getHost().$root_url.'/index.php?';
		$cur->blog_name = __('My first blog');
		$core->addBlog($cur);
		$core->blogDefaults($cur->blog_id);
		
		$blog_settings = new dcSettings($core,'default');
		$blog_settings->setNameSpace('system');
		$blog_settings->put('lang',$dlang);
		$blog_settings->put('public_url',$root_url.'/public');
		$blog_settings->put('themes_url',$root_url.'/themes');
		
		$cur = $core->con->openCursor($core->prefix.'version');
		$cur->module = 'core';
		$cur->version = (string) DC_VERSION;
		$cur->insert();
		
		$subject = mail::B64Header('DotClear '.__('successfully installed'));
		
		$message =
		__('Your new DotClear blog has been successfully set up at:')."\n\n".
		http::getHost().$admin_url."\n\n".
		
		__('You can log in to the administrator account with the following information:')."\n\n".
		
		__('Username:')." admin\n".
		__('Password:').' '.$user_pwd."\n\n".
		
		__('We hope you enjoy your new weblog. Thanks!')."\n\n".
		
		"--\n".
		"The DotClear Team\n".
		"http://www.dotclear.net/";
		
		$headers[] = 'From: dotclear@'.$_SERVER['HTTP_HOST'];
		$headers[] = 'Content-Type: text/plain; charset=UTF-8;';
		
		try {
			mail::sendMail($u_email,$subject,$message,$headers);
			$mail_sent = true;
		} catch (Exception $e) {	}
		
		$step = 1;
	}
	catch (Exception $e)
	{
		$err = $e->getMessage();
	}
}

if (!isset($step)) {
	$step = 0;
}
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta http-equiv="Content-Language" content="en" />
  <meta name="MSSmartTagsPreventParsing" content="TRUE" />
  <meta name="ROBOTS" content="NOARCHIVE,NOINDEX,NOFOLLOW" />
  <meta name="GOOGLEBOT" content="NOSNIPPET" />
  <title>DotClear Install</title>
  
  <style type="text/css">
  @import url(../style/default.css); 
  </style>
</head>

<body id="dotclear-admin" class="install">
<div id="content">
<?php
echo
'<h1>'.__('Dotclear installation').'</h1>';

if (!is_writable(DC_TPL_CACHE)) {
	echo '<div class="error"><p>'.sprintf(__('Cache directory %s is not writable.'),DC_TPL_CACHE).'</p></div>';
}

if (!empty($err)) {
	echo '<div class="error"><p><strong>'.__('Errors:').'</strong></p>'.$err.'</div>';
}

if (!empty($_GET['wiz'])) {
	echo '<p class="message">'.__('Confirugration file has been successfully created.').'</p>';
}

if ($can_install && $step == 0)
{
	echo
	'<h2>'.__('User information').'</h2>'.
	
	'<p>'.__('Please provide the following information needed to create the first user.').'</p>'.
	
	'<form action="index.php" method="post">'.
	'<p><label class="required" title="'.__('Required field').'">'.__('Email:').' '.
	form::field('u_email',20,255,html::escapeHTML($u_email)).'</label></p>'.
	'<p><label>'.__('Firstname:').' '.
	form::field('u_firstname',20,255,html::escapeHTML($u_firstname)).'</label></p>'.
	'<p><label>'.__('Name:').' '.
	form::field('u_name',20,255,html::escapeHTML($u_name)).'</label></p>'.
	'<p><input type="submit" value="'.__('save').'" /></p>'.
	'</form>';
}
elseif ($can_install && $step == 1)
{
	echo
	'<h2>'.__('All done!').'</h2>'.
	
	'<p>'.sprintf(__('Now you can <a href="%s">log in</a> with the following information:'),
	'../auth.php').'</p>'.
	'<ul>'.
	'<li>'.__('Login:').' <strong>admin</strong></li>'.
	'<li>'.__('Password:').' <strong>'.$user_pwd.'</strong></li>'.
	'</ul>';
	
	if ($mail_sent) {
		echo
		'<p>'.sprintf(__('A password reminder was sent to %s. You\'ll be able to change it once you\'re logged in.'),
		$u_email).'</p>';
	}
}
?>
</div>
</body>
</html>