<?php
/**
 * 安装程序
 */
class indexAction extends Action {

    public function _initialize() {
        L(include LANG_PATH . 'common.php');
    }
    /**
     * 安装协议
     */
    public function index(){
        $this->assign('step_curr', 'eula');
        $eula_html = file_get_contents(LANG_PATH . 'xieyi.html');
        $this->assign('eula_html', $eula_html);
        if (IS_POST) {
            $accept = $this->_post('accept');
            if (!$accept) {
                $error_msg = L('please_accept');
                $this->assign('error_msg', $error_msg);
                $this->display();
            } else {
                $this->redirect('check');
            }
        } else {
            $this->display();
        }
    }

    /**
     * 环境检测
     */
    public function check() {
        
        $flag = true;
        //检测文件夹权限
        $check_file = array(
            './data',
            './data/mail_tpl',
            './data/msg_tpl',
            './data/static',
            './data/upload',
            './data/config/db.php',
            './data/config/url.php',
            './data/config/index/config.php',
        );
        $error = array();
        foreach ($check_file as $file) {
            $path_file =  $file;
            if (!file_exists($path_file)) {
                $error[] = $file . L('not_exists');
                $flag = false;
                continue;
            }
            if (!is_writable($path_file)) {
                $error[] = $file . L('not_writable');
                $flag = false;
            }
        }
        if (!function_exists('curl_getinfo')) {
            $error[] = L('no_curl');
            $flag = false;
        }

        if (!function_exists('gd_info')) {
            $error[] = L('no_gd');
            $flag = false;
        }
        $dir_obj = new Dir;
        is_dir('./data/runtime') && $dir_obj->delDir('./data/runtime');

        if (!$flag) {
            $this->assign('error', $error);
            $this->assign('step_curr', 'check');
            $this->display('check');
        } else {
            $this->redirect('setconf');
        }
    }

    /**
     * 网站配置
     */
    public function setconf() {
        $this->assign('step_curr', 'setconf');
        if (IS_POST) {
            foreach ($_POST as $key => $val) {
                $this->assign($key, $val);
            }
            extract($_POST);
            if (!$db_host || !$db_port || !$db_name || !$db_user || !$db_prefix || !$admin_user || !$admin_email || !$admin_pass) {
                $this->assign('error_msg', L('please_input_config_info'));
                $this->display();
                exit;
            }
            if (!$this->_is_email($admin_email)) {
                $this->assign('error_msg', L('admin_email_format_incorrect'));
                $this->display();
                exit;
            }
            if ($admin_pass != $admin_pass_confirm) {
                $this->assign('error_msg', L('admin_pass_error'));
                $this->display();
                exit;
            }
            //试着连接数据库
            $db=array($db_type,$db_host,$db_name,$db_user,$db_pass,$db_port,$db_prefix,$admin_user,$admin_pass,$admin_email);
            $DB = array();
            list($DB['DB_TYPE'], $DB['DB_HOST'], $DB['DB_NAME'], $DB['DB_USER'], $DB['DB_PWD'],
            $DB['DB_PORT'], $DB['DB_PREFIX'],$DB['admin_user'],$DB['admin_pass'],$DB['admin_email']) = $db;
            
             //缓存数据库配置
             cookie('db_config',$DB);
            
            import('thinkphp.Lib.Core.Db');
        try {
                $dbname = $db_name;
                unset($db_name);
                $con  = Db::getInstance($DB);
                $sql = "CREATE DATABASE IF NOT EXISTS `{$dbname}` DEFAULT CHARACTER SET utf8";
                $con->execute($sql);
                
        } catch (\Exception $e){
          //$this->error('无法连接数据库，请检查数据库信息是否正确！');
           $this->assign('error_msg', L('connect_mysql_error'));
                $this->display();
            exit;
        }
            
            
             $this->_set_temp($_POST);
             $this->redirect('install');
           
        } else {
            $this->assign('database_name_tip', L('database_name_tip'));
            $this->assign('db_host', 'localhost');
            $this->assign('db_port', '3306');
            $this->assign('db_user', 'root');
            $this->assign('db_name', '');
            $this->assign('db_prefix', 'tqk_');

            $this->assign('admin_user', 'admin');
            $this->assign('db_pass', '');
            $this->assign('admin_pass', '');
            $this->assign('admin_pass_confirm', '');
            $this->assign('admin_email', '');
            $this->display();
        }
    }

    /**
     * 开始安装
     */
    public function install() {
    	
    	
        $this->assign('step_curr', 'install');
        $this->display();
    	
    	       import('thinkphp.Lib.Core.Db'); 
    	       $dbconfig = cookie('db_config');
           $con  = Db::getInstance($dbconfig);
           $this->create_tables($con, $dbconfig['DB_PREFIX']);
           $this->register_administrator($con, $dbconfig['DB_PREFIX'], $dbconfig);
            //创建配置文件
            $conf   = $this->write_config($dbconfig);
            
            if(session('error')){
            //show_msg();
           } else {
            session('step', 3);
            $this->redirect('finish');
         }
    	
    	
    }
    
   /**
 * 写入配置文件
 * @param  array $config 配置信息
 */
private function write_config($config){
if(is_array($config)){
$db_str=<<<php
<?php
return array(

//*************************************数据库设置*************************************
    'DB_TYPE'               =>  '{$config['DB_TYPE']}',                 // 数据库类型
    'DB_HOST'               =>  '{$config['DB_HOST']}',     // 服务器地址
    'DB_NAME'               =>  '{$config['DB_NAME']}',     // 数据库名
    'DB_USER'               =>  '{$config['DB_USER']}',     // 用户名
    'DB_PWD'                =>  '{$config['DB_PWD']}',      // 密码
    'DB_PORT'               =>  '{$config['DB_PORT']}',     // 端口
    'DB_PREFIX'             =>  '{$config['DB_PREFIX']}',   // 数据库表前缀
);
php;
if(!IS_WRITE){
return '由于您的网站目录下data文件夹环境不可写，本次安装失败。';	

}else{
	
 if(file_put_contents('./data/config/db.php', $db_str)){
$this->_show_process(L('install_successed'), 'parent.install_successed();');
return false;
 	
 }else{
 	$this->_show_process('配置文件写入失败！');
	session('error', true);
 	
 }
 
 return '';

}


}	
	

}
    

    /**
     * 执行安装
     */
    public function finish_done() {
        $charset = 'latin1';
        header('Content-type:text/html;charset=' . $charset);
        $temp_info = F('temp_data');
        $conn = mysql_connect($temp_info['db_host'] . ':' . $temp_info['db_port'], $temp_info['db_user'], $temp_info['db_pass']);
       // $version = mysql_get_server_info();
        $charset = str_replace('-', '', $charset);
        if ($version > '4.1') {
            if ($charset != 'latin1') {
                //mysql_query("SET character_set_connection={$charset}, character_set_results={$charset}, character_set_client=binary", $conn);
            }if ($version > '5.0.1') {
                mysql_query("SET sql_mode=''", $conn);
            }
        }
        $selected_db = mysql_select_db($temp_info['db_name'], $conn);
        $this->_show_process(L('create_table_begin'));
        $sqls = $this->_get_sql(APP_PATH . 'Sql_data/initdata.sql');
        foreach ($sqls as $sql) {
            $sql = str_replace('`tqk_', '`' . $temp_info['db_prefix'], $sql);
            $sql = str_replace('tqk_', $temp_info['db_prefix'], $sql);
            $run = mysql_query($sql, $conn);
            if (substr($sql, 0, 12) == 'CREATE TABLE') {
                $table_name = $temp_info['db_prefix'] . preg_replace("/CREATE TABLE `" . $temp_info['db_prefix'] . "([a-z0-9_]+)` .*/is", "\\1", $sql);
                $this->_show_process(sprintf(L('create_table_successed'), $table_name));
            }
        }
        $this->_show_process(L('insert_initdate_begin'));
        $sqls = $this->_get_sql(APP_PATH . 'Sql_data/initdata.sql');
        $admin_pass = md5($temp_info['admin_pass']);
        $sqls[] = "INSERT INTO `" . $temp_info['db_prefix'] . "admin` (`username`, `password`, `email`, `role_id`) VALUES " .
                "('" . $temp_info['admin_user'] . "', '" . $admin_pass . "', '" . $temp_info['admin_email'] . "', 1);";
        foreach ($sqls as $sql) {
            $sql = str_replace('`tqk_', '`' . $temp_info['db_prefix'], $sql);
            $sql = str_replace('tqk_', $temp_info['db_prefix'], $sql);
            if (substr($sql, 0, 11) == 'INSERT INTO') {
                $table_name = $temp_info['db_prefix'] . preg_replace("/INSERT INTO `" . $temp_info['db_prefix'] . "([a-z0-9_]+)` .*/is", "\\1", $sql);
                $run = mysql_query($sql, $conn);
            }
        }
        $this->_show_process(L('insert_initdate_successed'));
        //修改配置文件
        $config_file = './data/config/db.php';
        $config_data['DB_HOST'] = $temp_info['db_host'];
        $config_data['DB_NAME'] = $temp_info['db_name'];
        $config_data['DB_USER'] = $temp_info['db_user'];
        $config_data['DB_PWD'] = $temp_info['db_pass'];
        $config_data['DB_PORT'] = $temp_info['db_port'];
        $config_data['DB_PREFIX'] = $temp_info['db_prefix'];
        file_put_contents($config_file, "<?php\r\nreturn " . var_export($config_data, true) . ";");
        //安装完毕
        $this->_show_process(L('install_successed'), 'parent.install_successed();');
        return false;
    }

    public function finish() {
        $this->assign('step_curr', 'finish');
        touch('./data/install.lock');
        $this->display();
    }

    /**
     * 显示安装进程
     */
    private function _show_process($msg, $script = '') {
        echo '<script type="text/javascript">parent.show_process(\'<p><span>' . $msg . '</span></p>\');' . $script . '</script>';
        flush();
        ob_flush();
    }

    private function _set_temp($temp_data) {
        F('temp_data', $temp_data);
    }

    private function _get_sql($sql_file) {
        $contents = file_get_contents($sql_file);
        $contents = str_replace("\r\n", "\n", $contents);
        $contents = trim(str_replace("\r", "\n", $contents));
        $return_items = $items = array();
        $items = explode(";\n", $contents);
        foreach ($items as $item) {
            $return_item = '';
            $item = trim($item);
            $lines = explode("\n", $item);
            foreach ($lines as $line) {
                if (isset($line[1]) && $line[0] . $line[1] == '--') {
                    continue;
                }
                $return_item .= $line;
            }
            if ($return_item) {
                $return_items[] = $return_item; //.";";
            }
        }
        return $return_items;
    }
    
    
 private   function create_tables($db, $prefix = ''){
	//读取SQL文件
	$sql = file_get_contents(APP_PATH . 'Sql_data/initdata.sql');
	$sql = str_replace("\r", "\n", $sql);
	$sql = explode(";\n", $sql);

	//替换表前缀
	//$orginal = C('ORIGINAL_TABLE_PREFIX');
	//$sql = str_replace(" `{$orginal}", " `{$prefix}", $sql);

	//开始安装
  $this->_show_process(L('create_table_begin'));
  
	foreach ($sql as $value) {
		$value = trim($value);
		if(empty($value)) continue;
		if(substr($value, 0, 12) == 'CREATE TABLE') {
			$name = preg_replace("/^CREATE TABLE IF NOT EXISTS `(\w+)` .*/s", "\\1", $value);
			//$table_name = $prefix . preg_replace("/CREATE TABLE `" . $prefix . "([a-z0-9_]+)` .*/is", "\\1", $value);
			$msg  = "创建数据表{$name}";
			if(false !== $db->execute($value)){
                $this->_show_process(sprintf(L('create_table_successed'),$name));
			} else {
			// $this->_show_process('安装失败');
			session('error', true);
			}
		} else {
			$db->execute($value);
		}

	}
}

private function register_administrator($db, $prefix, $admin){
	$this->_show_process('开始注册创始人帐号...');
	$admin= F('temp_data');
	  $password = md5($admin['admin_pass']);   
      $sqls = "INSERT INTO `" . $prefix . "admin` (`id`,`username`, `password`, `email`, `role_id`,`last_time`,`last_ip`) VALUES " .
                "(1,'" . $admin['admin_user'] . "', '" . $password . "', '" . $admin['admin_email'] . "', 1, '" . NOW_TIME. "','" .get_client_ip(1). "')";
	$db->execute($sqls);
	$this->_show_process('创始人帐号注册完成！');
}
    
    

    private function _is_email($email) {
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
        if (strpos($email, '@') !== false && strpos($email, '.') !== false) {
            if (preg_match($chars, $email)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
?>