<?php
namespace Install\Controller;
use Think\Controller;

class IndexController extends Controller {
    function _initialize(){
		$file = APP_PATH.'Common/Conf/db.php';
		if(file_exists($file)){
			$this->error('请勿重复安装！');
		}
	}
	function index(){
		
		$this->display();
    }
	
	function info(){
		$this->display();
	}
	
	function ajax(){
		$host = I('host');
		$dbuser = I('dbuser');
		$dbpwd = I('dbpwd');
		$dbpre = I('dbpre');
		$dbname = I('dbname');
		$user = I('user');
		$pwd = I('pwd');
		$conn=mysql_connect($host, $dbuser,$dbpwd);
		if(!$conn){
			echo '数据库信息错误';
			exit;
		}
		if(!mysql_select_db($dbname)){
			$sql = "CREATE DATABASE  `".$dbname."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;";
			$res = mysql_query($sql);
			if(!$res){
				echo '没有该数据名';
				exit;
			}else{
				mysql_select_db($dbname);
			}
		}
		mysql_query('set names utf8');
		//导入数据表
		$sql = file_get_contents(APP_PATH.'Install/mysql.sql');
		$queries = sql_split($sql,$dbpre);
		$count = count($queries);
        for ($i = 0; $i < $count; $i++) {
            $sql = trim($queries[$i]);
            if (strstr($sql, 'CREATE TABLE')) {
                // CREATE TABLE
                preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
                mysql_query($sql);
            } else {
                // DROP TABLE 或 INSERT INTO
                mysql_query($sql);
            }
        }
		//插入管理员
		$sql = "INSERT INTO `".$dbpre."master` (`user`,`pwd`) value ('".$user."','".md5($pwd)."')";
		$re = mysql_query($sql);
		if($re){
			echo 'ok';
		}else{
			echo '存在未知的错误';
		}
		
		//写入数据库链接信息
		$str = "<?php \n return array( \r";
		$str .=  "  'DB_TYPE' => 'mysqli',\r";
		$str .=  "  'DB_HOST' => '".$host."',\r";
		$str .=  "  'DB_NAME' => '".$dbname."',\r";
		$str .=  "  'DB_USER' => '".$dbuser."',\r";
		$str .=  "  'DB_PWD' => '".$dbpwd."',\r";
		$str .=  "  'DB_PORT' => '3306',\r";
		$str .=  "  'DB_PREFIX' => '".$dbpre."',\r";
		$str .= ");";
		$configFile = APP_PATH.'Common/Conf/db.php';
		$fp = fopen($configFile,'w');
		fwrite($fp,$str);
		$filecache = RUNTIME_PATH.'common~runtime.php';
		unlink($filecache);
		
	}
	
}