<?php
// +----------------------------------------------------------------------
// | 安装程序 [ 天方夜谭快速开发框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014~2019 http://www.eirds.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 天方夜谭 <17404785@qq.com>
// +----------------------------------------------------------------------
//报错处理
error_reporting(0);
//设置编码方式
header('Content-Type:application/json; charset=utf-8');
//0表示没有限制
@set_time_limit(0);
//设置时区
@date_default_timezone_set('PRC');
//请求参数
$action=isset($_POST['action'])?$_POST['action']:null;
//数据导入类
class ImportData{
    //数据库信息
    private $dbhost;
    private $dbuser;
    private $dbpw;
    private $dbport;
    private $dbname;
    private $dbcharset;
    private $link;
    private $tablepre;
    public function __construct($data)
    {
        $this->dbhost=isset($data['dbhost'])?$data['dbhost']:'';
        $this->dbuser=isset($data['dbuser'])?$data['dbuser']:'';
        $this->dbpw=isset($data['dbpw'])?$data['dbpw']:'';
        $this->dbport=isset($data['dbport'])?$data['dbport']:'3306';
        $this->dbname=isset($data['dbname'])?$data['dbname']:'';
        $this->dbcharset=isset($data['dbcharset'])?$data['dbcharset']:'utf8';
        $this->tablepre=isset($data['tablepre'])?$data['tablepre']:'';
        $link_info=$this->link_data();
        if(!$link_info['status']){
            return $link_info;
        }
    }

    //链接设置数据库
    protected function link_data(){
        $link=mysqli_connect($this->dbhost,$this->dbuser,$this->dbpw,null,$this->dbport);
        if(!$link)
            return array('status'=>false,'info'=>'数据库连接失败');
        else
            $this->link=$link;
        //mysql 版本
        //获得mysql版本
        $version = mysqli_get_server_info($this->link);
        //设置字符集
        if($version > '4.1' && $this->dbcharset) {
            mysqli_query($link, "SET NAMES {$this->dbcharset}");
        }
        //选择数据库
        mysqli_select_db($this->link,$this->dbname);
    }

    //导数据

    /**
     * @param $dbfile  要导入的sql数据文件
     * @param string $dbfile_table_pre  导入的sql文件的表前缀
     * @return array
     */
    public function import_data($dbfile,$dbfile_table_pre='zq_'){
        if(!file_exists($dbfile)){
            return array('status'=>false,'info'=>'数据库文件不存在');
        }
        $sqls = file_get_contents($dbfile);
        $sql = str_replace("{#prefix}",$dbfile_table_pre,$sqls);
        $status=$this->_sql_execute($this->link, $sql,$dbfile_table_pre);
        if($status){
//            echo '导入数据库成功';
            return array('status'=>true,'info'=>'导入数据库成功');
        }else{
            return array('status'=>true,'info'=>'导入数据库失败');
//            echo '导入数据库失败';
        }

    }

    /**
     * @param $link  数据库链接
     * @param $sql   要导入的sql语句
     * @param $dbfile_table_pre 导入的sql文件的表前缀
     * @return bool
     */
    protected function _sql_execute($link,$sql,$dbfile_table_pre) {
        $sqls =$this-> _sql_split($link,$sql,$dbfile_table_pre);
        if(is_array($sqls))
        {
            foreach($sqls as $sql)
            {
                if(trim($sql) != '')
                {
                    mysqli_query($link,$sql);
                }
            }
        }
        else
        {
            mysqli_query($link,$sqls);
        }
        return true;
    }


    /**
     * @param $link  表链接对象
     * @param $sql   导入的sql
     * @param $dbfile_table_pre  sql文件中的sql表前缀
     * @return array
     */
    protected function _sql_split($link,$sql,$dbfile_table_pre) {
        if(mysqli_get_server_info($link) > '4.1' && $this->dbcharset)
        {
            $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=".$this->dbcharset,$sql);
        }
        //如果有表前缀就替换现有的前缀
        if($this->tablepre){
            $sql=str_replace($dbfile_table_pre, $this->tablepre, $sql);
        }
        $sql = str_replace("\r", "\n", $sql);
        $ret = array();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach($queriesarray as $query)
        {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach($queries as $query)
            {
                $str1 = substr($query, 0, 1);
                if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
            }
            $num++;
        }
        return $ret;
    }

}

if($action=='install'){
    $DB_HOST = $_POST['host'];
    $DB_PORT = $_POST['port'];
    $DB_NAME = $_POST['name'];
    $DB_USER = $_POST['user'];
    $DB_PWD = $_POST['pwd'];
    $DB_PREFIX = $_POST['prefix'];
    if(empty($DB_HOST) || empty($DB_PORT) || empty($DB_NAME) || empty($DB_USER) || empty($DB_PWD) || empty($DB_PREFIX)){
        $arr = array('state'=>'no','msg'=>'所有项不能为空！'.$DB_PWD);
    }else{
        $con = mysqli_connect($DB_HOST.':'.$DB_PORT,$DB_USER,$DB_PWD);
        if(!$con){
            $arr = array('state'=>'no','msg'=>'连接数据库失败，'.mysqli_connect_error().'');
        }else if(!mysqli_select_db($con,$DB_NAME)){
            $arr = array('state'=>'no','msg'=>'要连接的数据库（'.$DB_NAME.'）不存在！');
        }else{
            mysqli_query($con,"set names utf8");
            $sqls=file_get_contents('install.sql');
            $explode = explode(";",$sqls);
            $num = count($explode);
            $mysql=array(
                'dbhost'=>$DB_HOST.':'.$DB_PORT,
                'dbuser'=>$DB_USER,
                'dbpw'=>$DB_PWD,
                'dbname'=>$DB_NAME
            );
            $obj=new ImportData($mysql);
            $msg = $obj->import_data('install.sql',$DB_PREFIX);
            if(!$msg){
                $arr = array('state'=>'no','msg'=>''.$msg['info'].'');
            }else{
                $arr = array('state'=>'ok','msg'=>'导入数据表成功！本次共导入'.$num.'条数据');
            }
        }
    }
    exit(json_encode($arr));
}elseif ($action=='end'){
    $DB_HOST = $_POST['host'];
    $DB_PORT = $_POST['port'];
    $DB_NAME = $_POST['name'];
    $DB_USER = $_POST['user'];
    $DB_PWD = $_POST['pwd'];
    $DB_PREFIX = $_POST['prefix'];
    $DB_QQ = $_POST['qq'];
    $DB_CDKEY = $_POST['cdkey'];
    if (empty($DB_HOST) || empty($DB_PORT) || empty($DB_NAME) || empty($DB_USER) || empty($DB_PWD) || empty($DB_PREFIX) || empty($DB_QQ)){
        $arr = array('state'=>'no','msg'=>'缺少参数，请重新安装！');
    }elseif (empty($DB_CDKEY)){
        $arr = array('state'=>'no','msg'=>'请输入授权码！');
    }else{
        $time = date('Y-m-d h:i:s', time());
        $data="<?php
            return array(
                'DB_HOST'               =>  '{$DB_HOST}',
                'DB_NAME'               =>  '{$DB_NAME}',
                'DB_USER'               =>  '{$DB_USER}',
                'DB_PWD'                =>  '{$DB_PWD}',
                'DB_PORT'               =>  '{$DB_PORT}',
                'DB_PREFIX'             =>  '{$DB_PREFIX}',
                'TF_TIME'               =>  '{$time}',
                'DB_QQ'                =>  '{$DB_QQ}',
                'DB_CDKEY'                =>  '{$DB_CDKEY}',
            );";
        if(file_put_contents('../Configs/config.php',$data)){
            $arr = array('state'=>'ok','msg'=>'恭喜你，程序安装完成，请尽情的使用吧！');
        }else{
            $arr = array('state'=>'no','msg'=>'保存数据库配置文件失败，请检查网站是否有写入权限！');
        }
    }
    exit(json_encode($arr));
}else{
    exit('404');
}