<?php
namespace Install\Controller;
use Think\Controller;
use Think\Db;
class IndexController extends Controller {

	public function _initialize(){
		if(\Think\Storage::has(APP_PATH.'Common/Conf/install.lock')){
			if (I('step') != 4) {
				$this -> error('请不要重复安装！');
			}
		}
		$this -> namespace = MODULE_NAME.CONTROLLER_NAME;
	}

	// 首页
	public function index(){
		$step = I('step',-1,'intval');
		if ($step >=0) {
			if (IS_GET) {
				if ($step == 1) {
					session('error', false);
					$this -> check_env = check_env();
					$this -> check_dirfile = check_dirfile();
					$this -> check_func = check_func();
					$this -> huanjing = session('error')?0:1;
				}
				$this -> display('step'.$step);
			}
		}else{
			session(null);
			$this -> display();
		}
	}

	public function checkdata(){
		if (session('error')) {
			$this -> error('当前环境不支持安装本系统，请重新配置环境！');
		}
		if (IS_POST) {
			$password = I('password');
			if ($password != I('password2')) {
				$this -> error('两次密码输入不一样！请确认！');
			}
			if (strlen($password) > 10 || strlen($password) < 5) {
				$this -> error('密码长度不符合要求！');
			}
			$dbconfig = array(
				'DB_TYPE'	   =>  'mysql',
				'DB_HOST'	   =>  I('DB_HOST'),
				'DB_NAME'	   =>  I('DB_NAME'),
				'DB_USER'	   =>  I('DB_USER'),
				'DB_PWD'		=>  I('DB_PWD'),
				'DB_PREFIX'	 =>  I('DB_PREFIX'),
				);
			if (I('createdatabase') == 1) {
				$rootconfig = array(
					'DB_TYPE'	   =>  'mysql',
					'DB_HOST'	   =>  I('DB_HOST'),
					'DB_USER'	   =>  I('DB_USER_ROOT'),
					'DB_PWD'		=>  I('DB_PWD_ROOT'),
					'DB_PREFIX'	 =>  I('DB_PREFIX'),
					);
				$db  = Db::getInstance($rootconfig);
				$sql = 'CREATE DATABASE IF NOT EXISTS `'.$dbconfig['DB_NAME'].'` DEFAULT CHARACTER SET utf8';
				$db->execute($sql) || $this->error('ROOT账户配置错误！'.$db->getError());
			}
			$db  = Db::getInstance($dbconfig);
			$sql = "CREATE TABLE IF NOT EXISTS `".$dbconfig['DB_PREFIX'].md5(serialize($dbconfig))."` (id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),ebcmstest varchar(15));DROP TABLE IF EXISTS `".$dbconfig['DB_PREFIX'].md5(serialize($dbconfig))."`;";
			if ($db->execute($sql) === false) {
				$this -> error('数据库配置错误！');
			}
			session('dbconfig',$dbconfig);
			session('password',I('password'));
			$this -> success('配置成功！');
		}
	}

	public function createtable(){
		if (!session('dbconfig')) {
			die('请配置数据库！');
		}
		$dbconfig = session('dbconfig');
		$db  = Db::getInstance($dbconfig);
		print str_repeat(" ", 4096);//php.ini output_buffering默认是4069字符或者更大，即输出内容必须达到4069字符服务器才会flush刷新输出缓冲
		$sql = file_get_contents(MODULE_PATH.'Data/install.sql');
		$sql = str_replace('mmt_', $dbconfig['DB_PREFIX'], $sql);
		$ret = array();
		$num = 0;
		foreach(explode(";\r\n", trim($sql)) as $query) {
			$ret[$num] = '';
			$queries = explode("\r\n", trim($query));
			foreach($queries as $query) {
				$ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
			}
			$num++;
		}
		echo '创建数据库...<br/>';
		foreach ($ret as $key => $value) {
			if ($value) {
				$db -> execute($value);
				if(substr($value, 0, 12) == 'CREATE TABLE') {
					ob_flush();
					flush();
					echo '创建数据表：'.preg_replace("/CREATE TABLE `?([a-z0-9_]+)`? .*/is", "\\1", $value).'<br/>';
				}
			}
		}
		echo '创建数据库...完成！<br/>';
		echo '更新数据库...<br/>';
		// 更新数据库中的数据库信息
		$sql = 'update `'.$dbconfig['DB_PREFIX'].'config` set `value` = "'.$dbconfig['DB_HOST'].'" where `name`="DB_HOST";';
		$sql .= 'update `'.$dbconfig['DB_PREFIX'].'config` set `value` = "'.$dbconfig['DB_NAME'].'" where name="DB_NAME";';
		$sql .= 'update `'.$dbconfig['DB_PREFIX'].'config` set `value` = "'.$dbconfig['DB_USER'].'" where `name`="DB_USER";';
		$sql .= 'update `'.$dbconfig['DB_PREFIX'].'config` set `value` = "'.$dbconfig['DB_PWD'].'" where `name`="DB_PWD";';
		$sql .= 'update `'.$dbconfig['DB_PREFIX'].'config` set `value` = "'.$dbconfig['DB_PREFIX'].'" where `name`="DB_PREFIX";';
		$password = session('password');
		$sql .= 'update `'.$dbconfig['DB_PREFIX'].'user` set `password` = "'.crypt_pwd($password).'" where `username`="admin";';
		$db -> execute($sql);
		echo '更新数据库...完成！<br/>';
		// 更新配置文档
		echo '创建配置文件...<br/>';
		C($dbconfig);
		$config = read_config();
		foreach ($config as $key => $value) {
			ksort($value);
			$str = "<?php \n\r//配置文件由系统自动生成，如非必要请在后台修改！\n\rreturn ".var_export($value,true).';';
			$str = htmlspecialchars_decode($str);
			$patterns  = array(
				'/(\{\{)(.*)(\}\})/U',
				'/(=> \'\'\.)/U',
				'/(\.\'\',)(\r|\n)/U',
				'/(\.\'\'\.)/U',
				);
			$replace  = array(
				'\'.\2.\'',
				'=> ',
				',\2',
				'.',
				);
			$str = preg_replace($patterns, $replace, $str);
			$str = str_replace(array('[\\\'','\\\']'), array('[\'','\']'), $str);
			\Think\Storage::put(APP_PATH.$key.'/Conf/config.php',$str);
			echo '创建配置文件：'.APP_PATH.$key.'/Conf/config.php 成功！<br/>';
		}
		echo '创建配置文件...完成！<br/>';
		\Think\Storage::put(APP_PATH.'Common/Conf/install.lock','#lock');
		echo '生成安全文件...完成！<br/>';
		echo '清空缓存目录...<br/>';
		deldir(RUNTIME_PATH);
		echo '清空缓存目录...完成！<br/>';
		echo '程序安装成功！';
		echo '<script>var oDoc = top.parent.document;setTimeout(function(){oDoc.getElementById("finish").value = "1";},5000);oDoc.getElementById("finished").value = "1";</script>';
		die;
	}
}