<?php
/*
 * iOrange 安装文件,修改自pbdigg.
 * email: yzxh24@gmail.com
 */

error_reporting(0);
session_start();
define('IG_INSTALL', TRUE);
define('IG_ROOT', str_replace('\\', '/', substr(dirname(__FILE__), 0, -7)));

include IG_ROOT . 'include/Version.inc.php';
$_IGVERSION = VERSION;

include 'install_function.php';
include 'install_lang.php';

$timestamp = time();
$ip = getip();
$installfile = 'iorange.sql';
$ig_config_file = '/cache/Db.conf.php';
$setting_file = '/cache/Settings.inc.php';

//判断是否安装过
header('Content-Type: text/html; charset=utf-8');
if (file_exists('install.lock')) {
    exit($i_message['install_lock']);
}
if (!is_readable($installfile)) {
    exit($i_message['install_dbFile_error']);
}
$quit = false;
$msg = $alert = $link = $sql = $allownext = '';

$PHP_SELF = addslashes(htmlspecialchars($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']));
set_magic_quotes_runtime(0);
if (!get_magic_quotes_gpc()) {
    addS($_POST);
    addS($_GET);
}
@extract($_POST);
@extract($_GET);
?>
<html>
<head>
    <title><?php echo $i_message['install_title']; ?></title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <link href="images/style.css" rel="stylesheet" type="text/css"/>
<body>
<div id='content'>
<div id='innercontent'>
<h1>iOrange <?php echo $_IGVERSION, ' ', $i_message['install_wizard']; ?></h1>
<?php
if (!$v) {
    ?>
<div class="botBorder">
    <p><span class='red'><?php echo $i_message['install_warning'];?></span></p>
</div>
<div class="botBorder">
    <?php echo $i_message['install_intro'];?>
</div>
<form method="post" action="install.php?v=1">
    <p class="center"><input type="submit" class="submit" value="<?php echo $i_message['install_start'];?>"/></p>
</form>
    <?php

}
elseif ($v == '1')
{
    ?>
<h2><?php echo $i_message['install_license_title'];?></h2>
<p>
    <textarea class="textarea" readonly="readonly" cols="50">
        <?php echo $i_message['install_license'];?>
    </textarea>
</p>
<form action="install.php?v=2" method="post">
    <p><label><input type="checkbox" name="agree" value="1"
                     onClick="if(this.checked==true){this.form.next.disabled=''}else{this.form.next.disabled='true'}"
                     checked="checked"/><?php echo $i_message['install_agree'];?></label></p>

    <p class="center"><input type="submit" style="width:200px;" class="submit" name="next"
                             value="<?php echo $i_message['install_next'];?>"/></p>
</form>
    <?php

}
elseif ($v == '2')
{
    if ($agree == 'no') {
        echo '<script>alert(' . $i_message['install_disagree_license'] . ');history.go(-1)</script>';
    }
    $dirarray = array(
        '/data',
        '/cache',
    );
    $writeable = array();
    foreach ($dirarray as $key => $dir)
    {
        if (writable($dir)) {
            $writeable[$key] = $dir . result(1, 0);
        }
        else
        {
            $writeable[$key] = $dir . result(0, 0);
            $quit = TRUE;
        }
    }
    ?>
<div class="shade">
    <div class="settingHead"><?php echo $i_message['install_env'];?></div>
    <h5><?php echo $i_message['php_os'];?></h5>

    <p><?php echo PHP_OS;result(1, 1);?></p>
    <h5><?php echo $i_message['php_version'];?></h5>

    <p>
        <?php
        echo PHP_VERSION;
        if (PHP_VERSION < '5.1.2') {
            result(0, 1);
            $quit = TRUE;
        }
        else
        {
            result(1, 1);
        }
        ?></p>
    
    
    <h5>Zend版本</h5>

    <p>
    <?php
    	$zend = extension_loaded('Zend Optimizer');
    	if (!$zend)
    	{
    		echo '<span class="red">' . $i_message['unsupport'] . '</span>';
    		echo '<br/>必须安装 Zend Optimizer 3.3x 或者 Zend Guard Loader 5.5';
            $quit = TRUE;
    	}
    	else
    	{
    		if (OPTIMIZER_VERSION < '3.3')
    		{
    			echo 'Zend Optimizer版本必须大于 3.3 或者 Zend Guard Loader 5.5';
    			result(0, 1);
    			$quit = TRUE;
    		}
    		else
    		{
    			echo 'Zend Optimizer';
    			result(1, 1);
    		}
    	}
    ?>
    </p>
    
    
    
    
    
    <h5><?php echo $i_message['file_upload'];?></h5>

    <p>
        <?php
        if (@ini_get('file_uploads')) {
            echo $i_message['support'], '/', @ini_get('upload_max_filesize');
        }
        else
        {
            echo '<span class="red">' . $i_message['unsupport'] . '</span>';
        }
            result(1, 1);
            ?></p>
    <h5><?php echo $i_message['php_extention'];?></h5>

    <p>
        <?php
        if (extension_loaded('mysql')) {
            echo 'mysql:' . $i_message['support'];
            result(1, 1);
        }
        else
        {
            echo '<span class="red">' . $i_message['php_extention_unload_mysql'] . '</span>';
            result(0, 1);
            $quit = TRUE;
        }
            ?></p>

    <p>
        <?php
        if (extension_loaded('gd')) {
            echo 'gd:' . $i_message['support'];
            result(1, 1);
        }
        else
        {
            echo '<span class="red">' . $i_message['php_extention_unload_gd'] . '</span>';
            result(0, 1);
            $quit = TRUE;
        }
            ?></p>

    <p>
        <?php
        if (extension_loaded('curl')) {
            echo 'curl:' . $i_message['support'];
            result(1, 1);
        }
        else
        {
            echo '<span class="red">' . $i_message['php_extention_unload_curl'] . '</span>';
            result(0, 1);
            $quit = TRUE;
        }
            ?></p>

    <p>
        <?php
        if (extension_loaded('mbstring')) {
            echo 'mbstring:' . $i_message['support'];
            result(1, 1);
        }
        else
        {
            echo '<span class="red">' . $i_message['php_extention_unload_mbstring'] . '</span>';
            result(0, 1);
            $quit = TRUE;
        }
            ?></p>


    <h5><?php echo $i_message['mysql'];?></h5>

    <p>
        <?php
        if (function_exists('mysql_connect')) {
            echo $i_message['support'];
            result(1, 1);
        }
        else
        {
            echo '<span class="red">' . $i_message['mysql_unsupport'] . '</span>';
            result(0, 1);
            $quit = TRUE;
        }
            ?></p>


</div>
<div class="shade">
    <div class="settingHead"><?php echo $i_message['dirmod'];?></div>
        <?php
        foreach ($writeable as $value)
{
    echo '<p>' . $value . '</p>';
}

    if (is_writable(IG_ROOT . $ig_config_file)) {
        echo '<p>' . $ig_config_file . result(1, 0) . '</p>';
    }
    else
    {
        echo '<p>' . $ig_config_file . result(0, 0) . '</p>';
        $quit = TRUE;
    }
    if (is_writable(IG_ROOT . $setting_file)) {
        echo '<p>' . $setting_file . result(1, 0) . '</p>';
    }
    else
    {
        echo '<p>' . $setting_file . result(0, 0) . '</p>';
        $quit = TRUE;
    }
    ?>
    <!-- <span class='red'><?php echo $i_message['install_dirmod'];?></span> -->
</div>
<p class="center">
<form method="post" action='install.php?v=3'>
    <input style="width:200px;" type="submit" class="submit" name="next"
           value="<?php echo $i_message['install_next'];?>" <?php if ($quit) echo "disabled=\"disabled\"";?>>
</form>
</p>
        <?php

}
elseif ($v == '3')
{
    ?>
<!-- <h2><?php echo $i_message['install_setting'];?></h2> -->
<form method="post" action="install.php?v=4" id="install" onSubmit="return check(this);">
    <div class="shade">
        <div class="settingHead"><?php echo $i_message['install_mysql'];?></div>

        <h5><?php echo $i_message['install_mysql_host'];?></h5>

        <p><?php echo $i_message['install_mysql_host_intro'];?></p>

        <p><input type="text" name="db_host" value="localhost" size="40" class='input'/></p>

        <h5><?php echo $i_message['install_mysql_username'];?></h5>

        <p><input type="text" name="db_username" value="root" size="40" class='input'/></p>

        <h5><?php echo $i_message['install_mysql_password'];?></h5>

        <p><input type="password" name="db_password" value="" size="40" class='input'/></p>

        <h5><?php echo $i_message['install_mysql_name'];?></h5>

        <p><input type="text" name="db_name" value="orange" size="40" class='input'/>
        </p>

        
        <h5><?php echo $i_message['site_name'];?></h5>

        <p><input type="text" name="site_name" value="iOrange" size="40" class='input'/></p>

        <h5><?php echo $i_message['site_url'];?></h5>

        <p><?php echo $i_message['site_url_intro'];?></p>

        <p><input type="text" name="site_url"
                  value="<?php echo "http://" . $_SERVER['HTTP_HOST'] . rtrim(str_replace('\\', '/', dirname(dirname(dirname($_SERVER['SCRIPT_NAME'])))), '/');?>/"
                  size="40" class='input'/></p>
                  
        <h5><?php echo $i_message['site_web_url'];?></h5>

        <p><?php echo $i_message['site_web_url_intro'];?></p>

        <p><input type="text" name="site_web_url" value="" size="40" class='input'/></p>
        
		<h5><?php echo $i_message['site_path'];?></h5>

        <p><?php echo $i_message['site_path_intro'];?></p>

        <p><input type="text" name="site_path" value="" size="40" class='input'/></p>

    </div>

    <div class="shade">
        <div class="settingHead"><?php echo $i_message['founder'];?></div>

        <h5><?php echo $i_message['auto_increment'];?></h5>

        <p>admin</p>

        <h5><?php echo $i_message['install_founder_email'];?></h5>

        <p><input type="text" name="email" value="admin@admin.com" size="40" class='input'/></p>

        <h5><?php echo $i_message['install_founder_password'];?></h5>

        <p><input type="text" name="password" value="" size="40" class='input'/></p>

        <h5><?php echo $i_message['install_founder_rpassword'];?></h5>

        <p><input type="text" name="rpassword" value="" size="40" class='input'/></p>


    </div>
    <div class="center">
        <input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>"
               onClick="history.go(-1)">&nbsp;
        <input type="submit" class="submit" name="next" value="<?php echo $i_message['install_next'];?>">
</form>
</div>
<script type="text/javascript" language="javascript">
    function check(obj) {
        if (!obj.db_host.value) {
            alert('<?php echo $i_message['install_mysql_host_empty'];?>');
            obj.db_host.focus();
            return false;
        }
        else if (!obj.db_username.value) {
            alert('<?php echo $i_message['install_mysql_username_empty'];?>');
            obj.db_username.focus();
            return false;
        }
        else if (!obj.db_name.value) {
            alert('<?php echo $i_message['install_mysql_name_empty'];?>');
            obj.db_name.focus();
            return false;
        }
        else if (obj.password.value.length < 6) {
            alert('<?php echo $i_message['install_founder_password_length'];?>');
            obj.password.focus();
            return false;
        }
        else if (obj.password.value != obj.rpassword.value) {
            alert('<?php echo $i_message['install_founder_rpassword_error'];?>');
            obj.rpassword.focus();
            return false;
        }
        else if (!obj.email.value) {
            alert('<?php echo $i_message['install_founder_email_empty'];?>');
            obj.email.focus();
            return false;
        }
        return true;
    }
</script>
    <?php

}
elseif ($v == '4')
{
    $badPasswordArray = array(123456,123456789,234567,'admin123','admin666','admin888','admin234','admin123456');
    if (empty($db_host) || empty($db_username) || empty($db_name)) {
        $msg .= '<p>' . $i_message['mysql_invalid_configure'] . '<p>';
        $quit = TRUE;
    }
    elseif (!@mysql_connect($db_host, $db_username, $db_password))
    {
        $msg .= '<p>' . mysql_error() . '</p>';
        $quit = TRUE;
    }

    if (strlen($password) < 6) {
        $msg .= '<p>' . $i_message['founder_invalid_password'] . '</p>';
        $quit = TRUE;
    }
    elseif ($password != $rpassword)
    {
        $msg .= '<p>' . $i_message['founder_invalid_rpassword'] . '</p>';
        $quit = TRUE;
    }
    elseif (in_array($password, $badPasswordArray))
    {
    	$msg .= '<p>' . $i_message['founder_invalid_rpassword'] . '</p>';
        $quit = TRUE;
    }
    elseif (!preg_match('/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,3}$/i', $email))
    {
        $msg .= '<p>' . $i_message['founder_invalid_email'] . '</p>';
        $quit = TRUE;
    }
    else
    {
        $forbiddencharacter = array("\\", "&", " ", "'", "\"", "/", "*", ",", "<", ">", "\r", "\t", "\n", "#", "$", "(", ")", "%", "@", "+", "?", ";", "^");
        foreach ($forbiddencharacter as $value)
        {
            if (strpos($username, $value) !== FALSE) {
                $msg .= '<p>' . $i_message['forbidden_character'] . '</p>';
                $quit = TRUE;
                break;
            }
        }
    }

    if ($quit) {
        $allownext = 'disabled="disabled"';
        ?>
    <div class="error"><?php echo $i_message['error'];?></div>
        <?php
                echo $msg;
    }
    else
    {

        $config_file_content = array();
        $config_file_content['db_host'] = $db_host;
        $config_file_content['db_name'] = $db_name;
        $config_file_content['db_username'] = $db_username;
        $config_file_content['db_password'] = $db_password;
        $config_file_content['db_pconnect'] = 0;
        $config_file_content['db_charset'] = 'utf8';
        $config_file_content['dbType'] = 'MySQL';

        $default_manager_account = array();
        $default_manager_account['email'] = $email;
        $default_manager_account['password'] = md5($password);

        $_SESSION['config_file_content'] = $config_file_content;
        $_SESSION['default_manager_account'] = $default_manager_account;
        $_SESSION['site_url'] = $site_url;
        $_SESSION['site_web_url'] = $site_web_url;
        $_SESSION['site_name'] = $site_name;
        $_SESSION['site_path'] = $site_path;
    }
    ?>
<div class="botBorder">
    <p><?php echo $i_message['install_founder_name'], ': ', $email?></p>

    <p><?php echo $i_message['install_founder_password'], ': ', $password;?></p>
</div>
<div class="botBorder">

    <?php
    //写配置文件
    $fp = fopen(IG_ROOT . $ig_config_file, 'wb');
    $configfilecontent = <<<EOT
<?php
/**
 * iOrange(橘子)数据库配置文件
 * @author yzxh24
 * @email: yzxh24@gmail.com
 */
return array(
	'host' => '{$db_host}',
    'user' => '{$db_username}',
    'password' => '{$db_password}',
    'database' => '{$db_name}'
);

EOT;
    chmod(IG_ROOT . $ig_config_file, 0777);
    $result_1 = fwrite($fp, trim($configfilecontent));
    @fclose($fp);

    if ($result_1 && file_exists(IG_ROOT . $ig_config_file)) {
    	$sFile = IG_ROOT . $setting_file;
    	$settings = file_get_contents($sFile);
    	$_SESSION['key'] = random(8);
    	$settings = str_replace(array('#basehost#', '#path#', '#webname#', '#webhost#', '#key#'), array($_SESSION['site_url'], $_SESSION['site_path'], $_SESSION['site_name'], $_SESSION['site_web_url'], $_SESSION['key']), $settings);
    	file_put_contents($sFile, $settings);
    	file_put_contents(IG_ROOT . '/backend/.DEPLOY', ' ');
    ?>
	    <p><?php echo $i_message['config_log_success']; ?></p>
    <?php

    } else {
    ?>
    	<p><?php echo $i_message['config_read_failed']; $quit = TRUE;?></p>
    <?php
    }
    ?>
</div>
<div class="center">
    <form method="post" action="install.php?v=5">
        <input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>"
               onClick="history.go(-1)">&nbsp;
        <input type="submit" class="submit" name="next"
               value="<?php echo $i_message['install_next'];?>" <?php echo $allownext;?> >
    </form>
</div>
    <?php

}
elseif ($v == '5')
{
    $db_config = $_SESSION['config_file_content'];

    if (!$db_config['db_host'] && !$db_config['db_name']) {
        $msg .= '<p>' . $i_message['configure_read_failed'] . '</p>';
        $quit = TRUE;
    }
    else
    {
        mysql_connect($db_config['db_host'], $db_config['db_username'], $db_config['db_password']);
        $sqlv = mysql_get_server_info();
        if ($sqlv < '4.1') {
            $msg .= '<p>' . $i_message['mysql_version_402'] . '</p>';
            $quit = TRUE;
        }
        else
        {
            $db_charset = $db_config['db_charset'];
            $db_charset = (strpos($db_charset, '-') === FALSE) ? $db_charset : str_replace('-', '', $db_charset);

            mysql_query(" CREATE DATABASE IF NOT EXISTS `{$db_config['db_name']}` DEFAULT CHARACTER SET $db_charset ");

            if (mysql_errno()) {
                $errormsg = mysql_error();
                $msg .= '<p>' . ($errormsg ? $errormsg : $i_message['database_errno']) . '</p>';
                $quit = TRUE;
            }
            else
            {
                mysql_select_db($db_config['db_name']);
            }
        }
    }

    if ($quit) {
        $allownext = 'disabled="disabled"';
        ?>
    <div class="error"><?php echo $i_message['error'];?></div>
        <?php
            echo $msg;
    }
    else
    {
        ?>
    <div class="botBorder">
        <?php
        if ($ig_rebuild) {
        ?>
        <p style="color:red;font-size:16px;"><?php echo $i_message['ig_rebuild'];?></p>
        <?php

    }
        ?>
        <p><?php echo $i_message['mysql_import_data'];?></p>
    </div>
        <?php

    }
    ?>
<div class="center">
    <form method="post" action="install.php?v=6">
        <input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>"
               onClick="history.go(-1)">&nbsp;
        <input type="submit" class="submit" name="next"
               value="<?php echo $i_message['install_next'];?>" <?php echo $allownext, $alert?>>
    </form>
</div>
    <?php

}
elseif ($v == '6')
{
    $db_config = $_SESSION['config_file_content'];

    mysql_connect($db_config['db_host'], $db_config['db_username'], $db_config['db_password']);
    if (mysql_get_server_info() > '5.0') {
        mysql_query("SET sql_mode = ''");
    }
    $db_config['db_charset'] = (strpos($db_config['db_charset'], '-') === FALSE) ? $db_config['db_charset']
            : str_replace('-', '', $db_config['db_charset']);
    mysql_query("SET character_set_connection={$db_config['db_charset']}, character_set_results={$db_config['db_charset']}, character_set_client=binary");
    mysql_select_db($db_config['db_name']);
    $tablenum = 0;

    $fp = fopen($installfile, 'rb');
    $sql = fread($fp, filesize($installfile));
    fclose($fp);
    ?>
<div class="botBorder">
    <h4><?php echo $i_message['import_processing'];?></h4>

    <div style="overflow-y:scroll;height:100px;width:715px;padding:5px;border:1px solid #ccc;">
        <?php
        $db_charset = $db_config['db_charset'];
        $sql = str_replace("\r", "\n", $sql);
        foreach (explode(";\n", trim($sql)) as $query)
        {
            $query = trim($query);
            if ($query) {
                if (substr($query, 0, 12) == 'CREATE TABLE') {
                    $name = preg_replace("/CREATE TABLE ([A-Z ]*)`([a-z0-9_]+)` .*/is", "\\2", $query);
                    echo '<p>' . $i_message['create_table'] . ' ' . $name . ' ... <span class="blue">OK</span></p>';
                    @mysql_query(createtable($query, $db_charset));
                    $tablenum++;
                }
                else
                {
                    @mysql_query($query);
                }
            }
        }
        
        // 修改表引擎
        @mysql_query('ALTER TABLE ig_auth_item ENGINE=INNODB;');
        @mysql_query('ALTER TABLE ig_auth_assignment ENGINE=INNODB;');
        @mysql_query('ALTER TABLE ig_auth_item_child ENGINE=INNODB;');
        @mysql_query('ALTER TABLE ig_loginlog ENGINE=INNODB;');
        @mysql_query('ALTER TABLE ig_feed ENGINE=MEMORY;');
        @mysql_query('ALTER TABLE ig_sessions ENGINE=MEMORY;');
        @mysql_query('ALTER TABLE ig_adtmp ENGINE=MEMORY;');
        
        // 修改数据库里的配置数据
        @mysql_query("UPDATE ig_settings SET value = '".$_SESSION['site_name']."' WHERE var = 'cfg_webname'");
        @mysql_query("UPDATE ig_settings SET value = '".$_SESSION['site_url']."' WHERE var = 'cfg_basehost'");
        @mysql_query("UPDATE ig_settings SET value = '".$_SESSION['site_web_url']."' WHERE var = 'cfg_webhost'");
        @mysql_query("UPDATE ig_settings SET value = '".$_SESSION['site_path']."' WHERE var = 'cfg_path'");
        @mysql_query("UPDATE ig_settings SET value = '".$_SESSION['key']."' WHERE var = 'cfg_key'");
        ?>
    </div>
</div>
<div class="botBorder">
    <h4><?php echo $i_message['create_founder'];?></h4>

        <?php
            //设置网站用户起始ID

    $admin = $_SESSION['default_manager_account'];

    $sql0 = "UPDATE ig_admin SET password = '".$admin['password']."', email = '".$admin['email']."' WHERE username = 'admin'";
    if (mysql_query($sql0)) {
        echo '<p>' . $i_message['set_auto_increment_success'] . '... <span class="blue">OK..admin</span></p>';
        $sid = md5($admin['password'] . time());
        @mysql_query("UPDATE ig_members SET password = '".$admin['password']."',iorange = '".$sid."' WHERE username = 'admin'");
    } else {
        echo '<p>' . $i_message['set_auto_increment_error'] . '... <span class="red">ERROR</span></p>';
        $admin_id = 1;
    }

    if (!$quit) {
        //锁定安装
        fopen('install.lock', 'w');
        @unlink('../index.html');
    } else {
        echo '请重新安装';
    }
    ?>
</div>
<div class="botBorder">
    <h4><?php echo $i_message['install_success'];?></h4>
    <?php echo $i_message['install_success_intro'];?>
</div>

<?php
}
?>
</div>
<div class='copyright'><a href="http://www.iorange.cc">iOrange(橘子)</a> <?php echo $_IGVERSION; ?> &#169; Copyright <?php echo date('Y-m-d');?> www.iorange.cc All Rights Reserved
</div>
</div>

</body>
</html>