<?php
/**
 * Copyright (C) 2009  Honghao Geng (genghonghao@gmail.com)
 * $Id: install.php 537 2010-01-14 15:37:18Z genghonghao $
 */

error_reporting(E_ALL);
@ini_set('session.use_only_cookies', 1);
@ini_set('track_errors', 1);
@ini_set('get_magic_quotes_gpc', 0);

if (@ini_get('session.save_handler') == 'user') {
    @ini_set('session.save_handler', 'files');
}
if (function_exists('session_start')) {
    @session_start();
}

define('IN_GEN', true);
include './install.language.php';
include './../smartgoon_version.php';
include './function.inc.php';

$smartgoonsite = 'http://www.smartgoon.com';
$working_directory = str_replace('\\', '/', getcwd()).'/';
$root_directory = str_replace('install/', '', $working_directory);
$web_root = dirname((string)(@$_SERVER['PHP_SELF']));
$web_root = substr($web_root, 0, strlen($web_root) - 7); // strips the "setup" off the end of the path.

$incontext['steps'] = array(
        0 => array(1, $txt['install_step_welcome'], 'Welcome', 0),
        1 => array(2, $txt['install_step_writable'], 'CheckFilesWritable', 10),
        2 => array(3, $txt['install_step_databaseset'], 'DatabaseSettings', 15),
        3 => array(4, $txt['install_step_blog'], 'ForumSettings', 40),
        4 => array(5, $txt['install_step_databasechange'], 'DatabasePopulation', 75),
        5 => array(6, $txt['install_step_admin'], 'AdminAccount', 90),
        6 => array(7, $txt['install_step_done'], 'Done', 100),
);

// 获得安装步骤的参数
$incontext['current_step']    = isset($_GET['step']) ? (int) $_GET['step'] : 0;
$incontext['page_title']      = $txt['smartgoon_installer'];
$incontext['next_step']       = $incontext['current_step'] >= 6 ? 6 : $incontext['current_step'] + 1;
$incontext['pre_step']        = $incontext['current_step'] == 0 ? 0 : $incontext['current_step'] - 1;

$incontext['overall_percent'] = $incontext['steps'][$incontext['current_step']][3];

// 欢迎页面
if ($incontext['current_step'] === 0) {
    $_SESSION['install'][0] = true;
    InitInstaller();
    InitHeader();
    InitStatusMain();
    $warning = (true === CheckInstalled()) ? 'block' : 'none';
    $content = '<div style="max-height: 560px; overflow: auto;">
	<form action="./install.php?step='.$incontext['next_step']. '" method="post">
		<p>'.$txt['welcome_content']. '</p>
                    <div id="version_warning" style="margin: 2ex; padding: 2ex; border: 2px dashed #A92174; color: black; background-color: #FBBBE2; display: '.$warning.';">
                    <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
                    <strong style="text-decoration: underline;">' . $txt['warning'] . '!</strong><br />
                    <div style="padding-left: 6ex;">
                    '.$txt['program_already_installed'].'
    </div>
    </div>
    <h3>'.$txt['welcome_submit_notice'].'</h3>
        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
        <input type="submit"  name="contbutt" value="'.$txt['continue'].'" class="button_submit" />
</div>
</form>
</div>';
    InitCentral($content);
    InitFooter();
}

// 检查运行环境
elseif ($incontext['current_step'] === 1) {
    InitInstaller();
    InitHeader();
    InitStatusMain();
    $check_status = CheckSurr();
    $warning = (0 != $check_status[1]) ? 'block' : 'none';
    $warning_btn = (0 != $check_status[1]) ? 'none' : '';
    $dir_code = $check_status[0];
    $notice_wi = (0 != $check_status[1]) ? '' : $txt['writable_submit_notice'];
    $content = '<div style="max-height: 560px; overflow: auto;">
	<form action="./install.php?step='.$incontext['next_step']. '" method="post">
		<p>'.$dir_code. '</p>
                    <div id="version_warning" style="margin: 2ex; padding: 2ex; border: 2px dashed #A92174; color: black; background-color: #FBBBE2; display: '.$warning.';">
                    <div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
                    <strong style="text-decoration: underline;">' . $txt['warning'] . '!</strong><br />
                    <div style="padding-left: 6ex;">
                    '.$txt['writable_warning'].'
    </div>
    </div>
    <h3>'.$notice_wi.'</h3>
        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
        <input type="submit"  name="contbutt" value="'.$txt['continue'].'" class="button_submit" style="display:'.$warning_btn.'"/>
</div>
</form>
</div>';
    InitCentral($content);
    InitFooter();
    $_SESSION['install'][1] = true;
}

// 设置数据库信息
elseif ($incontext['current_step'] === 2) {
    InitInstaller();
    InitHeader();
    InitStatusMain();
    $content = '<div style="max-height: 560px; overflow: auto;">
	<form action="./install.php?step='.$incontext['next_step']. '" method="post">
		<p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['db_server_address'].'</span><input type="text" name="db_server_address" size="45" value="localhost"></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['db_server_port'].'</span><input type="text" name="db_server_port" size="45" value="3306"></p>
                 <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['db_name'].'</span><input type="text" name="db_name" size="45" value=""></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['db_username'].'</span><input type="text" name="db_username" size="45" value=""></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['db_password'].'</span><input type="password" name="db_password" size="45" value=""></p>
   
        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
        <input type="submit"  name="contbutt" value="'.$txt['continue'].'" class="button_submit" style="display:"/>
</div>
</form>
</div>';
    InitCentral($content);
    InitFooter();
    $_SESSION['install'][2] = true;
}

// 设置博客数据
elseif ($incontext['current_step'] === 3) {
    ob_start();
    $db_server_address = isset($_REQUEST['db_server_address']) ? trim($_REQUEST['db_server_address']) : NULL;
    $db_server_port = isset($_REQUEST['db_server_port']) ? trim($_REQUEST['db_server_port']) : NULL;
    $db_name = isset($_REQUEST['db_name']) ? trim($_REQUEST['db_name']) : NULL;
    $db_username = isset($_REQUEST['db_username']) ? trim($_REQUEST['db_username']) : NULL;
    $db_password = isset($_REQUEST['db_password']) ? trim($_REQUEST['db_password']) : NULL;
    if (isset($_SESSION['install'][2]) && true === $_SESSION['install'][2]) {
        $conn = @mysql_connect($db_server_address.':'.$db_server_port, $db_username, $db_password);
        if (false !== $conn) {
            $select_db = @mysql_select_db($db_name, $conn);
            if (false === $select_db) {
                go_back($txt['notice_not_find_db']);
            }
        } else {
            go_back($txt['notice_db_link_failure']);
        }
        @mysql_close($conn);
        gen_config($db_server_address.':'.$db_server_port, $db_username, $db_password, $db_name);
    }
    InitInstaller();
    InitHeader();
    InitStatusMain();
    ob_end_flush();
    $content = '<div style="max-height: 560px; overflow: auto;">
	<form action="./install.php?step='.$incontext['next_step']. '" method="post">
		<p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_blogname'].'</span><input type="text" name="site_name" size="45" value="'.$txt['default_input_blogname'].'"></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_title'].'</span><input type="text" name="site_title" size="45" value="'.$txt['default_input_title'].'"></p>
                 <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_keywords'].'</span><input type="text" name="site_keywords" size="45" value="'.$txt['default_input_keywords'].'"></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_desc'].'</span><input type="text" name="site_desc" size="45" value="'.$txt['default_input_desc'].'"></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_language'].'</span>
                    <select name="lang">
                    <option value="zh_cn">'.$txt['option_zh_cn'].' </option>
                    <option value="zh_tw">'.$txt['option_zh_tw'].' </option>
                    <option value="en_us">'.$txt['option_en_us'].' </option>
                    </select>
                    </p>

        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
        <input type="submit"  name="contbutt" value="'.$txt['continue'].'" class="button_submit" style="display:"/>
</div>
</form>
</div>';
    InitCentral($content);
    InitFooter();
    $_SESSION['install'][3] = true;
}

// 插入入数据表以及默认数据
elseif ($incontext['current_step'] === 4) {
    InitInstaller();
    InitHeader();
    InitStatusMain();

    include '../data/config.inc.php';
    $conn = mysql_connect($db_host, $db_user, $db_pass);
    if (false !== $conn) {
        $select_db = @mysql_select_db($db_name, $conn);
        if (false === $select_db) {
            go_back($txt['notice_not_find_db']);
        }
    } else {
        go_back($txt['notice_db_link_failure']);
    }
    // 安装配置数据
    include '../data/config.inc.php';
    include './data/conf.sql.php';
    include '../includes/mysql.class.php';
    include './sql_executor.php';

    // 初始化数据库类
    $db = new mysql($db_host, $db_user, $db_pass, $db_name, $prefix);
    $se = new sql_executor($db, 'utf8', 'sg_', $prefix);

    $sql_files = array('./data/structure.sql', './data/data.sql');
    $result = $se->run_all($sql_files);
    if ($result === false) {
        $install_status = 'none';
        $notice = $txt['failure_install_sql'];
    } else {
        $install_status = '';
        $notice = $txt['success_install_sql'];
        $db->query($conf_sql);
    }
    $content = '<div style="max-height: 560px; overflow: auto;">
	<form action="./install.php?step='.$incontext['next_step']. '" method="post">
		<p><span style="width:500px;display:-moz-inline-box;display:inline-block;">'.$notice.'</span></p>

        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
        <input type="submit"  name="contbutt" value="'.$txt['continue'].'" class="button_submit" style="display:'.$install_status.'"/>
</div>
</form>
</div>';
    InitCentral($content);
    InitFooter();
    $_SESSION['install'][4] = true;
}

// 设置管理员帐帐号
elseif ($incontext['current_step'] === 5) {
    InitInstaller();
    InitHeader();
    InitStatusMain();
    $content = '<div style="max-height: 560px; overflow: auto;">
	<form action="./install.php?step='.$incontext['next_step']. '" method="post">
		<p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_adminname'].'</span><input type="text" name="admin_name" size="45" value="admin"></p>
                <p><span style="width:100px;display:-moz-inline-box;display:inline-block;">'.$txt['label_adminpass'].'</span><input type="text" name="admin_pass" size="45" value=""></p>
        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
        <input type="submit"  name="contbutt" value="'.$txt['continue'].'" class="button_submit" style="display:"/>
</div>
</form>
</div>';
    InitCentral($content);
    InitFooter();
    $_SESSION['install'][5] = true;
}

// 完成安装程序
elseif ($incontext['current_step'] === 6) {
    InitInstaller();
    InitHeader();
    InitStatusMain();
    // 创建管理员
    $admin = isset($_REQUEST['admin_name']) ? trim($_REQUEST['admin_name']) : null;
    $pass = isset($_REQUEST['admin_pass']) ? md5(trim($_REQUEST['admin_pass'])) : null;
    // 获得客户端用户IP
    $client_ip = (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : getenv('REMOTE_ADDR'));
    $current_time = time();
    if (null == $admin || null == $pass) {
        go_back($txt['notice_create_failure']);
    }
    include '../data/config.inc.php';
    include '../includes/mysql.class.php';
    // 初始化数据库类
    $db = new mysql($db_host, $db_user, $db_pass, $db_name, $prefix);
    $db->query("INSERT INTO sg_admin VALUES(NULL, '$pass', '$admin', 'Adminitrators', '$client_ip', '$current_time','$client_ip', '$current_time','$client_ip', '$current_time')");
    @mkdir('../data/install.lock', 0777);
    $content = '<div style="max-height: 560px; overflow: auto;">
		<p>'.$txt['notice_done_good'].'</p>
                <p>'.$txt['notice_done_alert'].'</p>
                <p>'.$txt['notice_done_in'].'</p>
        <div style="height: 100px;"></div>
        <div class="righttext" style="margin: 1ex;">
</div>
</div>';
    InitCentral($content);
    InitFooter();
    $_SESSION['install'][6] = true;
}

// 初始化安装程序
function InitInstaller() {
    global $incontext;
    if (0 == $incontext['current_step']) {

    } elseif ($incontext['current_step'] > 0) {
        if (!$_SESSION['install'][$incontext['pre_step']]) {
            header("Location: install.php?step={$incontext['pre_step']}");
        }
    } else {
        header("Location: install.php");
    }
}

// 检查程序是否已安装过了
function CheckInstalled() {
    if (file_exists('../data/install.lock')) {
        return true;
    }
    return false;
}

// 初始化头部
function InitHeader() {
    global $incontext;

    echo <<<EOF
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta name="robots" content="noindex" />
		<title>{$incontext['page_title']}</title>
		<link rel="stylesheet" type="text/css" href="css/index.css?rc2" />
		<link rel="stylesheet" type="text/css" href="css/install.css?rc2" />
	</head>
	<body>
	<div id="header"><div class="frame">
		<div id="top_section">
			<h1 class="forumtitle">{$incontext['page_title']}</h1>
			<img id="smflogo" src="images/smflogo.png" alt="Smarty Goon Blog" title="Smarty Goon Blog" />
		</div>
		<div id="upper_section" class="middletext flow_hidden">
			<div class="user"></div>
			<div class="news normaltext">
			</div>
		</div>
	</div></div>
EOF;
}

// 初始化安装状态显示部分
function InitStatusMain() {
    global $txt, $incontext;
    echo <<<EOM
	<div id="content_section"><div class="frame">
		<div id="main_content_section">
			<div id="main-steps">
				<h2>{$txt['progress']}</h2>
				<ul>
EOM;
    foreach ($incontext['steps'] as $num => $step) {
        echo '<li class="', $num < $incontext['current_step'] ? 'stepdone' : ($num == $incontext['current_step'] ? 'stepcurrent' : 'stepwaiting'), '">', $txt['upgrade_step'], ' ', $step[0], ': ', $step[1], '</li>';
    }

    echo <<<EOMM
				</ul>
			</div>
			<div style="font-size: 12pt; height: 25pt; border: 1px solid black; background: white; float: left; margin-left: 12%; width: 25%;">
				<div id="overall_text" style="padding-top: 8pt;  z-index: 2; color: black; margin-left: -4em; position: absolute; text-align: center; font-weight: bold;">{$incontext['overall_percent']}%</div>
				<div id="overall_progress" style="width: {$incontext['overall_percent']}%; height: 25pt; z-index: 1; background-color: lime;">&nbsp;</div>
				<div class="overall_progress">{$txt['overall_progress']}</div>
			</div>
EOMM;
}

// 初始化安装区域
function InitCentral($content) {
    global $incontext;
    echo <<<EOCI
			<div id="main_screen" class="clear">
				<h2>{$incontext['steps'][$incontext['current_step']][1]}</h2>
				<div class="panel">
EOCI;
    echo $content;
    echo <<<EOCC
</div>
</div>
</div>
</div></div>
EOCC;
}

// 初始化底部
function InitFooter() {
    echo <<<EOH
<div id="footer_section"><div class="frame" style="height: 40px;">
<div class="smalltext"><a href="http://www.smartgoon.com/" title="Free Blog Software" target="_blank" class="new_win">SMARTGOON &copy; 2009 , Gen</a></div>
</div></div>
</body>

</html>
EOH;
}
?>