<?php
/*
+-----------------------------------------------------------------------------+
| $Id: install.php 2010-05-24 03:05:27Z Bleakwind $
| System Install
| Copyright (c) 2003-2010 Bleakwind (www.weaverdream.com)
| http://www.weaverdream.com/
| Release under the GNU Lesser General Public License Version 3 (LGPLv3):
|   http://www.gnu.org/licenses/lgpl.html
+-----------------------------------------------------------------------------+
*/

// Set file
$set['file_name']   = "./install.php";
$set['file_htm']    = "./install.htm";
$set['file_sql']    = "./install.mysql.sql";
$set['title']       = "全新安装";
$set['warn_input']  = "(注意:数据库中已存在的同名数据表将被覆盖!)";
$set['version']     = "1.1";

// Set envionment variables
@set_time_limit(0);
@error_reporting(E_ALL ^ E_NOTICE);
@set_magic_quotes_runtime(0);
session_start();

// Initialize
// Include all public files
include_once '../config.php';

include_once '../lib/adodb/adodb.inc.php';
include_once '../lib/smarty/Smarty.class.php';
include_once '../lib/function.php';

// Include all private files
include_once '../source/lib/sys.class.php';
include_once '../source/configure.php';

// Start the sys
$sys = new sys();

// Parse URL
$page_http              = $_SERVER['HTTPS'] == "on" ? "https://" : "http://";
$page_server_name       = $_SERVER['SERVER_NAME'];
$page_ports             = $_SERVER['SERVER_PORT'] != "80" ? ":".$_SERVER['SERVER_PORT'] : "";
$PAGE_PATH['rootdir']   = $page_http.$page_server_name.$page_ports.substr($_SERVER['SCRIPT_NAME'],0,strrpos($_SERVER['SCRIPT_NAME'],'/')-7);

// Set default timezone
date_default_timezone_set($CONFIG['default_timezone']);
// Set encoding for multibyte regex
mb_regex_encoding("UTF-8");

// Initialize db
$ADODB_CACHE_DIR = "./cache/adodb/";
if (!file_exists($ADODB_CACHE_DIR)) { func::make_dir($ADODB_CACHE_DIR); }
$db = &ADONewConnection(CONFIG_DB_TYPE);

// Get the Language
$LANGLIST[1]['id']    = "1";
$LANGLIST[1]['name']  = "Chinese simplified";
$LANGLIST[1]['code']  = "cn";
$LANGLIST[1]['icon']  = "icon.png";
$LANGLIST[1]['dir']   = "chinese_simplified";
$LANGLIST[1]['rank']  = "1";

// Get the Template
$TEMPLATE[1]['id']    = "1";
$TEMPLATE[1]['name']  = "Default";
$TEMPLATE[1]['dir']   = "default";
$TEMPLATE[1]['rank']  = "1";

// Set Default
$CONFIG['language'] = "1";
$CONFIG['template'] = "1";

// Include Language
include_once '../language/'.$LANGLIST[$CONFIG['language']]['dir'].'/source/_public.php';
include_once '../language/'.$LANGLIST[$CONFIG['language']]['dir'].'/template/_public.php';

// Start the Template
$compile_dir = "./cache/compile/";
$cache_dir   = "./cache/cache/";
if (!file_exists($compile_dir)) { func::make_dir($compile_dir); }
if (!file_exists($cache_dir))   { func::make_dir($cache_dir); }
$t = new Smarty();
include_once '../lib/function.smarty.php';
$t->template_dir   = "./";
$t->compile_dir    = $compile_dir;
$t->cache_dir      = $cache_dir;
$t->compile_check  = true;
$t->cache_lifetime = 60;
//$t->caching        = true;
//$t->debugging      = true;

// Start Ajax
if (is_file("../lib/xajax/xajax_core/xajaxAIO.inc.php")) {
    include_once '../lib/xajax/xajax_core/xajaxAIO.inc.php';
} elseif (is_file("../lib/xajax/xajax_core/xajax.inc.php")) {
    include_once '../lib/xajax/xajax_core/xajax.inc.php';
} else {
    echo "Error load Xajax module!";
    exit;
}
$bwajax = new xajax();
//$bwajax->configure('debug',true);
$bwajax->configure('statusMessages',true);
$bwajax->configure('javascript URI', '../lib/xajax/');
include_once '../lib/function.ajax.php';

// Include Setting
include_once '../source/setting.php';

$t->assign(array(
    "set"   => $set,
));

/************************************ Config **********************************/

$check_dir = array(
                "../config.php",
                "../cache",
                "../build",
                "../upload",
                "../upload/channel_cover",
                "../upload/content_cover",
                "../upload/content_attach",
                "../upload/article_cover",
                "../upload/article_attach",
                "../upload/datum_cover",
                "../upload/datum_attach",
                "../upload/upload_tmp",
                "../upload/member_avatar",
                "../upload/userfiles",
                "../admin/cache",
                "../install",
             );
$install['introduction'] = '　　1. 本软件是由 <a href="http://www.weaverdream.com/" target="_blank">Weaverdream</a> 开发制作的 Firmkernel网站内容管理系统. <br />　　2. Firmkernel采用PHP开发. <br />　　3. 您可以从 <a href="http://www.weaverdream.com/" target="_blank">www.weaverdream.com</a> 获取该软件. <br />　　4. 您使用本软件所产生的任何事情 Weaverdream 均不承担任何责任和义务. <br />　　5. 如需更多关于 Weaverdream, Firmkernel 的信息请访问 <a href="http://www.weaverdream.com/" target="_blank">www.weaverdream.com</a>.';
$install['rule'] = '　　Firmkernel'.$set['version'].' 是基于 <a href="http://www.gnu.org/licenses/gpl.html" target="_blank">GNU GENERAL PUBLIC LICENSE Version 3(GPLv3)</a> 授权协议的软件.';
/************************************ Function **********************************/
function check_agree(){
    global $check_dir;
    $result = "1";
    if ($_SESSION['agree'] != "1") {
        $result = "2";
    }
    return $result;
}
function check_dir(){
    global $check_dir;
    $result = "1";
    foreach ($check_dir as $v){
        if (!is_writable($v)) {
            $result = "2";
        }
    }
    return $result;
}
function agree_rule($value)
{
    global $SETTING,$LANGUAGE,$CONFIG,$CONFIGURE,$PROMPT,$LANGLIST,$db,$sys,$c;
    $ajax_response = new xajaxResponse();
    $button = "button_agree";
    $error = false;
    //$ajax_response->alert(print_r($value, true)); $ajax_response->assign($submit,"disabled",false); return $ajax_response;
    //func::fp($value);

    if ( $value['agree'] != "1" ) {
        $error = true;
        $ajax_response->assign("agree_return", "innerHTML", "<span class=\"prompt_failed\">您必须同意Firmkernel授权协议才能继续安装!</span>");
    }else{
        $ajax_response->assign("agree_return", "innerHTML", "");
    }

    if($error){
        $ajax_response->assign($button,"value", "下一步");
        $ajax_response->assign($button,"disabled",false);
    }else{
        $_SESSION['agree']            = $value['agree'];
        $ajax_response->redirect($set['file_name']."?act=check");
    }
    return $ajax_response;
}
$bwajax->register(XAJAX_FUNCTION, "agree_rule");
function input_msg($value)
{
    global $SETTING,$LANGUAGE,$CONFIG,$CONFIGURE,$PROMPT,$LANGLIST,$db,$sys,$c;
    $ajax_response = new xajaxResponse();
    $button = "button_input";
    $error = false;
    //$ajax_response->alert(print_r($value, true)); $ajax_response->assign($submit,"disabled",false); return $ajax_response;
    //func::fp($value);

    if ( !preg_match("/^[a-z0-9_]{1,20}$/i",$value['site_cookie_prefix']) ) {
        $error = true;
        if(empty($anchor)) { $anchor = "site_cookie_prefix"; }
        $ajax_response->assign("site_cookie_prefix_return", "innerHTML", "<span class=\"prompt_failed\">Cookies前缀不符合规范,1-10字节,英文,数字或下划线!</span>");
    }else{
        $ajax_response->assign("site_cookie_prefix_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    $value['admin_username'] = strtolower(trim($value['admin_username']));
    if ( mb_strwidth($value['admin_username'],"UTF-8") < 4 ||
         mb_strwidth($value['admin_username'],"UTF-8") > 60 ||
         preg_match("/[\x01-\x2E]|[\\x2F]|[\x3A-\x40]|[\x5B-\x5E]|[\x60]|[\x7B-\x7F]/",$value['admin_username']) ) {
         //}elseif( !preg_match("/^[^\$\=\&\*\#\"\<\>\{\}]+$/",$value['admin_username']) ){
        $error = true;
        if(empty($anchor)) { $anchor = "admin_username"; }
        $ajax_response->assign("admin_username_return", "innerHTML", "<span class=\"prompt_failed\">管理员用户名不符合规范,4-30字节,汉字,英文,数字或下划线,并不能含非法字符!</span>");
    }else{
        $ajax_response->assign("admin_username_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    $value['admin_email'] = strtolower($value['admin_email']);
    if ( !preg_match("/^[a-z0-9-_\.]+@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,4}$/i",$value['admin_email']) ) {
        $error = true;
        if(empty($anchor)) { $anchor = "admin_email"; }
        $ajax_response->assign("admin_email_return", "innerHTML", "<span class=\"prompt_failed\">E-mail地址不符合规范!</span>");
    } else {
        $ajax_response->assign("admin_email_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    if ( mb_strwidth($value['admin_password1'],"UTF-8") < 6 ||
        mb_strwidth($value['admin_password1'],"UTF-8") > 60 ){
        $error = true;
        if(empty($anchor)) { $anchor = "admin_password1"; }
        $ajax_response->assign("admin_password1_return", "innerHTML", "<span class=\"prompt_failed\">密码不符合规范,密码必须为英文,数字,下划线的组合,6-30字节!</span>");
    } else {
        $ajax_response->assign("admin_password1_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    if ( mb_strwidth($value['admin_password2'],"UTF-8") < 6 ||
        mb_strwidth($value['admin_password2'],"UTF-8") > 60 ||
        $value['admin_password2'] != $value['admin_password1']){
        $error = true;
        if(empty($anchor)) { $anchor = "admin_password2"; }
        $ajax_response->assign("admin_password2_return", "innerHTML", "<span class=\"prompt_failed\">密码确认必须和密码相同!</span>");
    } else {
        $ajax_response->assign("admin_password2_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    $result_connect = @$db->NConnect($value['db_host'], $value['db_user'], $value['db_pass'], $value['db_database']);
    if (!$result_connect) {
        $error = true;
        if(empty($anchor)) { $anchor = "db_host"; }
        $ajax_response->assign("db_host_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库主机地址!</span>");
        $ajax_response->assign("db_user_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库连接用户名!</span>");
        $ajax_response->assign("db_pass_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库连接密码!</span>");
        $ajax_response->assign("db_database_return", "innerHTML", "<span class=\"prompt_failed\">无法连接数据库,请仔细检查数据库是否存在,不存在请先建立数据库!</span>");
    } else {
        $ajax_response->assign("db_host_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
        $ajax_response->assign("db_user_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
        $ajax_response->assign("db_pass_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
        $ajax_response->assign("db_database_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    if ( !preg_match("/^[a-z0-9_]{1,10}$/i",$value['db_prefix']) ) {
        $error = true;
        if(empty($anchor)) { $anchor = "db_prefix"; }
        $ajax_response->assign("db_prefix_return", "innerHTML", "<span class=\"prompt_failed\">数据库表前缀不符合规范,1-10字节,英文,数字或下划线!</span>");
    }else{
        $ajax_response->assign("db_prefix_return", "innerHTML", "<span class=\"prompt_succeed\">正确</span>");
    }

    if($error){
        $ajax_response->assign($button,"value", "下一步");
        $ajax_response->assign($button,"disabled",false);
        $ajax_response->redirect("#".$anchor);
    }else{
        $_SESSION['db_host']            = $value['db_host'];
        $_SESSION['db_user']            = $value['db_user'];
        $_SESSION['db_pass']            = $value['db_pass'];
        $_SESSION['db_database']        = $value['db_database'];
        $_SESSION['db_prefix']          = $value['db_prefix'];
        $_SESSION['site_root']          = $value['site_root'];
        $_SESSION['site_root_admin']    = $value['site_root_admin'];
        $_SESSION['site_cookie_prefix'] = $value['site_cookie_prefix'];
        $_SESSION['admin_username']     = $value['admin_username'];
        $_SESSION['admin_email']        = $value['admin_email'];
        $_SESSION['admin_password1']    = $value['admin_password1'];
        $_SESSION['admin_password2']    = $value['admin_password2'];
        $ajax_response->redirect($set['file_name']."?act=install");
    }
    return $ajax_response;
}
$bwajax->register(XAJAX_FUNCTION, "input_msg");

/************************************ Install **********************************/
$install_lock = "2";
if (is_file("./install.lock") && $sys->get['act'] != "finish") {
    $install_lock = "1";
} else {
    if ($sys->get['act'] == "check"){
        foreach ($check_dir as $v){
            if (!@chmod($v, $SETTING['chmod_mode_file'])) {
                @chmod($v, "0777");
            }
        }
        $result_agree       = check_agree();
        $result_check_dir   = check_dir();
        if ($result_agree != "1") {
            @header("Location: ".$set['file_name']);
        } elseif ($result_check_dir == "1") {
            @header("Location: ".$set['file_name']."?act=input");
        }
        $t->assign("result_check_dir", $result_check_dir);

    } elseif ($sys->get['act'] == "input"){
        $result_agree       = check_agree();
        $result_check_dir   = check_dir();
        if ($result_agree != "1") {
            @header("Location: ".$set['file_name']);
        } elseif ($result_check_dir != "1") {
            @header("Location: ".$set['file_name']."?act=check");
        }

    } elseif ($sys->get['act'] == "install"){
        $result_agree       = check_agree();
        $result_check_dir   = check_dir();
        if ($result_agree != "1") {
            @header("Location: ".$set['file_name']);
        } elseif ($result_check_dir != "1") {
            @header("Location: ".$set['file_name']."?act=check");
        }

        $result_connect = @$db->NConnect($_SESSION['db_host'], $_SESSION['db_user'], $_SESSION['db_pass'], $_SESSION['db_database']);
        if (!$result_connect) {
            @header("Location: ".$set['file_name']."?act=input");
        }
        $db->Execute("SET NAMES '".CONFIG_DB_CHARSET."'");
        $content_config = func::read_file("../config.php");
        $content_config = trim($content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_ROOT[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_ROOT',                       '".$_SESSION['site_root']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_ROOT_ADMIN[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_ROOT_ADMIN',                 '".$_SESSION['site_root_admin']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_ADMINEMAIL[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_ADMINEMAIL',                 '".$_SESSION['admin_email']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_COOKIE_PREFIX[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_COOKIE_PREFIX',              '".$_SESSION['site_cookie_prefix']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_HOSTNAME[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_HOSTNAME',                '".$_SESSION['db_host']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_USERNAME[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_USERNAME',                '".$_SESSION['db_user']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_PASSWORD[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_PASSWORD',                '".$_SESSION['db_pass']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_DATABASE[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_DATABASE',                '".$_SESSION['db_database']."');", $content_config);
        $content_config = preg_replace("/define\([\'\"]CONFIG_DB_PREFIX[\'\"]\s*\,\s*[\'\"][^\'\"]*[\'\"]\)\;/i", "define('CONFIG_DB_PREFIX',                  '".$_SESSION['db_prefix']."');", $content_config);

        $content_sql = func::read_file($set['file_sql']);
        $content_sql = trim($content_sql);
        $content_sql = preg_replace("/\'admin\'\,\s*\'bleakwind@gmail\.com\'\,\s*\'\'\,\s*\'8ac418439874fa525c0a56743f7ead1badc1be1d\'\,/i", "'".$_SESSION['admin_username']."', '".$_SESSION['admin_email']."', '', '".func::str_encrypt($_SESSION['admin_password1'],$CONFIGURE['sys']['encrypt_mix'])."',", $content_sql);
        if ($_SESSION['db_prefix'] != "fk_") {
            $content_sql = preg_replace("/CREATE TABLE IF NOT EXISTS `fk_/i", "CREATE TABLE IF NOT EXISTS `".$_SESSION['db_prefix']."", $content_sql);
        }
        $content_sql = preg_replace("/\n--[^\n]*/i", "", $content_sql);
        $content_sql = preg_replace("/\/\*.*?\*\/\;\n?/i", "", $content_sql);
        $content_sql = preg_replace("/DROP TABLE IF EXISTS/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR DROP TABLE IF EXISTS", $content_sql);
        $content_sql = preg_replace("/CREATE TABLE IF NOT EXISTS/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR CREATE TABLE IF NOT EXISTS", $content_sql);
        $content_sql = preg_replace("/INSERT INTO/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR INSERT INTO", $content_sql);
        $content_sql = preg_replace("/ALTER TABLE/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR ALTER TABLE", $content_sql);
        $content_sql = preg_replace("/UPDATE/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR UPDATE", $content_sql);
        $content_sql = preg_replace("/TRUNCATE/", "WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR TRUNCATE", $content_sql);
        $content_sql = explode("WEAVERDREAM_FIRMKERNEL_DATABASE_SEPARATOR", $content_sql);

        $result_install_config  = "1";
        $result_install_sql     = "1";

        if (!func::write_file("../config.php", $content_config)){
            $result_install_config = "2";
        }

        foreach($content_sql as $v){
            $v = trim($v);
            if (!empty($v)) {
                $result = &$db->Execute($v);
                if (!$result) {
                    $result_install_sql = "2";
                }
            }
        }

        if ($result_install_config == "1" && $result_install_sql == "1") {
            func::write_file("./install.lock", "Locked By Weaverdream...");
            @chmod("./install.lock", $SETTING['chmod_mode_file']);
            @header("Location: ".$set['file_name']."?act=finish");
        }

        $t->assign("result_install_config", $result_install_config);
        $t->assign("result_install_sql", $result_install_sql);

    } elseif ($sys->get['act'] == "finish"){

    } elseif ($sys->get['act'] == "lisense"){

    } else {

    }

}

/************************************ End **********************************/
// Other parse
$t->assign("install_lock", $install_lock);
$t->assign("check_dir", $check_dir);
$t->assign("page_path", $PAGE_PATH);
$t->assign("install", $install);
$t->assign("_session", $_SESSION);
$t->assign("get", $sys->get);
$t->assign("post", $sys->post);
$t->assign("langlist", $LANGLIST);
$t->assign("lang", $LANGUAGE);
$t->assign($public_var);
// Xajax
$bwajax->processRequest();
$bwajax_printJavascript = $bwajax->getJavascript();
$t->assign(array(
    "bwajax_printJavascript"    => $bwajax_printJavascript,
));
// Print page
$t->display($set['file_htm']);
?>