<?php
error_reporting(7);

ob_start();
define('VERSION_5W',8.0);
define('CHARSET_5W','UTF-8');
define('PUBTIME_5W','20110516');
define('ROOT_5W',ereg_replace("[\\/]install",'',dirname(__FILE__)));
// 允许程序在 register_globals = off 的环境下工作
if (function_exists('ini_get')) {
	$onoff = ini_get('register_globals');
} else {
	$onoff = get_cfg_var('register_globals');
}
if ($onoff != 1) {
	@extract($_POST, EXTR_SKIP);
	@extract($_GET, EXTR_SKIP);
}

// 去除转义字符
function stripslashes_array(&$array) {
	while(list($key,$var) = each($array)) {
		if ($key != 'argc' && $key != 'argv' && (strtoupper($key) != $key || ''.intval($key) == "$key")) {
			if (is_string($var)) {
				$array[$key] = stripslashes($var);
			}
			if (is_array($var))  {
				$array[$key] = stripslashes_array($var);
			}
		}
	}
	return $array;
}

// 判断 magic_quotes_gpc 状态
if (get_magic_quotes_gpc()) {
    $_GET = stripslashes_array($_GET);
    $_POST = stripslashes_array($_POST);
}

set_magic_quotes_runtime(0);

$step = (isset($_GET['step'])) ? $_GET['step'] : $_POST['step'];

$phpv = phpversion();
$sp_os = @getenv('OS');
if(!$sp_os){
	$systemversion=explode(" ", php_uname());
	switch (PHP_OS)
		{
		    case "Linux":
				$sp_os=$systemversion[0].'   '.$systemversion[2];
				break;
		    case "FreeBSD":
				$sp_os=$systemversion[0].'   '.$systemversion[2];
				break;
		    default:
				$sp_os=$systemversion[0].'  '.$systemversion[1].' '.$systemversion[3].$systemversion[4].$systemversion[5];
				break;
		}
}
$pass_check = true;
$sp_server = $_SERVER['SERVER_SOFTWARE'];
$sp_host = (empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_HOST'] : $_SERVER['REMOTE_ADDR']);
$sp_name = $_SERVER['SERVER_NAME'];
$sp_max_execution_time = ini_get('max_execution_time');
$sp_allow_reference = (ini_get('allow_call_time_pass_reference') ? '<img src="images/ico_ok.gif" width="16" height="16" />' : '<img src="images/ico_del.gif" width="16" height="16" />');
$allow_fwrite = (function_exists('fwrite') ? '<img src="images/ico_ok.gif" width="16" height="16" />' : '<img src="images/ico_del.gif" width="16" height="16" />');
//$sp_allow_url_fopen = (ini_get('allow_url_fopen') ? '<img src="images/ico_ok.gif" width="16" height="16" />' : '<img src="images/ico_del.gif" width="16" height="16" />');
$sp_mysql = (function_exists('mysql_connect') ? '<img src="images/ico_ok.gif" width="16" height="16" />' : '<img src="images/ico_del.gif" width="16" height="16" />');
//$sp_curl = (function_exists('curl_init') ? '<img src="images/ico_ok.gif" width="16" height="16" />' : '<img src="images/ico_del.gif" width="16" height="16" />');
$sp_iconv = (function_exists('iconv') ? '<img src="images/ico_ok.gif" width="16" height="16" />' : '<img src="images/ico_del.gif" width="16" height="16" />');
if(!function_exists('mysql_connect') ||  !function_exists('iconv') ||  !function_exists('fwrite'))
	$pass_check = false;
$rootdir = dirname(__FILE__);
$rootdir = substr($rootdir,0,strrpos($rootdir,DIRECTORY_SEPARATOR)+1);
$sp_testdirs = array(
	'./',
	'./config.php',
	'./data/',
	'./data/backup/',
	'./data/logs/',
	'./data/templates_c/',
	'./data/cache/',
	'./data/update/',
	'./data/update/sql/',
	'./data/cache/data/'
);
   
$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];

$installcharset = "utf8";


$lockfile = '../data/install.lock';
$configfile = '../config.php';


if(file_exists($lockfile) && $step!=5)die('您已经安装过了，如需重新安装，请删掉data目录install.lock文件');
$sqlfile = 'database.sql';
if(!is_readable($sqlfile)) {
	exit('数据库文件不存在或者读取<font color="red">失败</font>');
}
$fp = fopen($sqlfile, 'rb');
$sql = fread($fp, 2048000);
fclose($fp);


include('header.tpl');
if (empty($step) || $step == '1') {
	include('step_1.tpl');
} elseif ($step == '2') {
	include('step_2.tpl');
} elseif ($step == '3') {
	include('step_3.tpl');
} elseif ($step == '4') {

	if(trim($_POST['dbname']) == "" || trim($_POST['dbhost']) == "" || trim($_POST['dbuser']) == "" || trim($_POST['admin_name']) == "" || trim($_POST['admin_password']) == ""){
		$errormsg = '请返回并确认所有选项均已填写';
		include('error_4.tpl');
	} elseif(!@mysql_connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpw'])) {
		$errormsg = '数据库不能连接';
		include('error_4.tpl');
	}   else {

		if(is_writeable($configfile)) {
			$dbhost 	= trim($_POST['dbhost']);
			$dbuser 	= trim($_POST['dbuser']);
			$dbpw 		= trim($_POST['dbpw']);
			$dbname 	= trim($_POST['dbname']);
			$dbprefix 	= trim($_POST['dbprefix']);

			$admin_name	= trim($_POST['admin_name']);
			$admin_password	= md5(trim($_POST['admin_password']));
			$getpwd_mask = randStr(16);

			$db_prefix   = '';


			$fp = @fopen($configfile, 'r');
			$filecontent = @fread($fp, @filesize($configfile));
			@fclose($fp);

//			$filecontent = str_replace("define('DBHOST','DBHOST');","define('DBHOST','$dbhost');",$filecontent);
//			$filecontent = str_replace("define('DBUSER','DBUSER');","define('DBUSER','$dbuser');",$filecontent);
//			$filecontent = str_replace("define('DBPWD','DBPWD');","define('DBPWD','$dbpw');",$filecontent);
//			$filecontent = str_replace("define('DBNAME','DBNAME');","define('DBNAME','$dbname');",$filecontent);
//  fengguanxing  10.26
			$pat_dbprefix = "/define\('DBPREFIX','(.*)'\)/U";
			$pat_dbhost = "/define\('DBHOST','(.*)'\)/U";
			$pat_dbuser = "/define\('DBUSER','(.*)'\)/U";
			$pat_dbpw = "/define\('DBPWD','(.*)'\)/U";
			$pat_dbname = "/define\('DBNAME','(.*)'\)/U";
			$pat_host = "/define\('WEB_HOST','(.*)'\)/U";
			$pat_pwdmask = "/define\('GETPWD_MASK','(.*)'\)/U";
			$s_host = $_SERVER['SERVER_NAME'];
			$s_host = str_replace('www','',$s_host);

			$filecontent=preg_replace($pat_host,"define('WEB_HOST','$s_host')",$filecontent);
			$filecontent=preg_replace($pat_dbprefix,"define('DBPREFIX','$dbprefix')",$filecontent);
			$filecontent=preg_replace($pat_dbhost,"define('DBHOST','$dbhost')",$filecontent);
			$filecontent=preg_replace($pat_dbuser,"define('DBUSER','$dbuser')",$filecontent);
			$filecontent=preg_replace($pat_dbpw,"define('DBPWD','$dbpw')",$filecontent);
			$filecontent=preg_replace($pat_dbname,"define('DBNAME','$dbname')",$filecontent);
			$filecontent=preg_replace($pat_pwdmask,"define('GETPWD_MASK','$getpwd_mask')",$filecontent);

			$fp = @fopen($configfile, 'w');
			@fwrite($fp, trim($filecontent));
			@fclose($fp);

		}
		$dbresult = array();
		$dbOK = array();

		$rs = mysql_query("create database IF NOT EXISTS ".$_POST['dbname']);
		if(!$rs)
			$dbresult[] = '建库 '.$_POST['dbname'].' 异常，请检查您是否有相关授权';

		$rs = mysql_query("use ".$_POST['dbname']);
		if(!$rs)
			$dbresult[] = 'use '.$_POST['dbname'].' 异常，请检查是否有此数据库';
		$rs = mysql_query("set names utf8 ");
		//@mysql_select_db($_POST['dbname']);
// 附加数据文件
if(is_file('../data/newdata.sql')){
	$fp = fopen('../data/newdata.sql','rb');
	$data = fread($fp, 2048000);
	$sql.=$data;
	fclose($fp);
}
	  $sql = str_replace("\r", "\n", str_replace('py_', $db_prefix, $sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == '#' ? '' : $query;
		}
		$num++;
	}
	unset($sql);

	foreach($ret as $query) {
		$query = trim($query);
		if($query) {
			if(substr($query, 0, 12) == 'CREATE TABLE') {
				$name = preg_replace("/CREATE TABLE IF NOT EXISTS `([a-z0-9_]+)` .*/is", "\\1", $query);

				$query = preg_replace("/CREATE TABLE IF NOT EXISTS `([a-z0-9_]+)` (.*)/is", "CREATE TABLE IF NOT EXISTS `".$dbprefix."\\1` \\2", $query);
				$rs = mysql_query(createtable($query, $installcharset));
				if(!$rs)
					$dbresult[] = '创建表 '.$dbprefix.$name.' ... <font color="red">失败</font>';
				else{
					$dbOK[] = '创建表 '.$dbprefix.$name.' ... <font color="#0000EE">成功</font><br />';
					$tablenum++;
				}

			} else if(substr($query, 0, 10) == 'DROP TABLE'){
				$name = preg_replace("/DROP TABLE IF EXISTS `([a-z0-9_]+)`/is","\\1",$query);
				$query = preg_replace("/DROP TABLE IF EXISTS `([a-z0-9_]+)`/is","DROP TABLE IF EXISTS `".$dbprefix."\\1`",$query);
				$rs = mysql_query($query);
				if(!$rs)
					$dbresult[] = '删除表 '.$dbprefix.$name.' ... <font color="red">失败</font>';
			} else {
				$name = preg_replace("/INSERT INTO `([a-z0-9_]+)` .*/is","\\1",$query);
				$query = preg_replace("/INSERT INTO `([a-z0-9_]+)` (.*)/is","INSERT INTO `".$dbprefix."\\1` \\2",$query);
				$rs = mysql_query($query);
				if(!$rs)
					$dbresult[] = '插入数据 '.$dbprefix.$name.' ... <font color="red">失败</font>';
			}
		}
	}
	$rs = mysql_query("insert into ".$dbprefix."admin_master (masterMail,groupID,masterPwd,masterName,masterState)values('".$admin_name."','1','".$admin_password."','".$admin_name."','1')");
	if(!$rs)
		$dbresult[] = '生成管理员<font color="red">失败</font>';
	$sitedomain = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	$sitedomain = preg_replace("#/install/index.php\?step(.*)$#i","",$sitedomain);
	$rs = mysql_query("update ".$dbprefix."site_setting set siteDomain='".addslashes($sitedomain)."',siteName='".addslashes($_POST['sitename'])."'");
	if(!$rs)
		$dbresult[] = '更新配置表<font color="red">失败</font>';
	if(count($dbresult) == 0){
		file_put_contents($lockfile,'');
	}
	if(count($dbresult) == 0){
		include('step_4.tpl');

}else{
	$errormsg = '';
	foreach($dbresult as $value){
		$errormsg .= '<p>'.$value.'</p>';
	}
	include('error_4.tpl');

}
}
}else if($step==5){
	include('step_5.tpl');
}

function result($result = 1, $output = 1) {
	if($result) {
		$text = '... <font color="#0000EE">Yes</font><br />';
		if(!$output) {
			return $text;
		}
		echo $text;
	} else {
		$text = '... <font color="#FF0000">No</font><br />';
		if(!$output) {
			return $text;
		}
		echo $text;
	}
}

function runquery($sql) {
	global $installcharset, $db_prefix, $DB, $tablenum;


}

function createtable($sql, $installcharset) {

	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
		(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$installcharset" : " TYPE=$type");
}

function randStr($len=6){
	$chars='ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789#%*';
	mt_srand((double)microtime()*1000000*getmypid());
	$password='';
	while(strlen($password)<$len)
		$password.=substr($chars,(mt_rand()%strlen($chars)),1);
	return $password;
}

include('footer.tpl');
?>