<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-25
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\install\controller;
use think\Controller;
use think\facade\Request;

class Index extends Controller
{
    protected $testresult = true;
    //判断是否已安装
    protected function initialize()
    {
        if (is_file('./data/install.lock')) {
            $this->error('系统已经安装过','/');
        }
        if(ENTER_NAME != 'INSTALL') $this->error('非法访问');
    }

    public function index()
    {
        $title = '使用协议';
        return $this->fetch('/index',compact('title'));
    }

    public function choosedb($dbtype='')
    {
        $title = '数据库类型';
        if(empty($dbtype)) {
            $test[]=[];
            $icon_s="<i class='layui-icon layui-icon-ok 'style='color:#5FB878;'></i> ";
            $icon_e="<i class='layui-icon layui-icon-close 'style='color:#FF5722;font-weight:bold;'></i> ";
            //pdo检测
            $test[0]['title'] = 'PDO';
            if (class_exists('pdo')) {
                $test[0]['result'] = $icon_s.'已开启';
                $test[0]['pass'] = true;
            } else {
                $test[0]['result'] = $icon_e.'未开启';
                $this->testresult = $test[0]['pass'] = false;
            }
            //扩展检测
            $test[1]['title'] = '扩展：pdo_mysql';
            if (extension_loaded('pdo_mysql')) {
                $test[1]['result'] = $icon_s.'已开启';
                $test[1]['pass'] = true;
            } else {
                $test[1]['result'] =$icon_e.'未开启';
                $this->testresult = $test[1]['pass'] = false;
            }
            $test[14]['title'] = '扩展：pdo_sqlite';
            if (extension_loaded('pdo_sqlite')) {
                $test[14]['result'] = $icon_s.'已开启';
                $test[14]['pass'] = true;
            } else {
                $test[14]['result'] =$icon_e.'未开启';
                $this->testresult = $test[14]['pass'] = false;
            }
            $test[2]['title'] = '扩展：curl';
            if (extension_loaded('curl')) {
                $test[2]['result'] = $icon_s.'已开启';
                $test[2]['pass'] = true;
            } else {
                $test[2]['result'] = $icon_e.'未开启';
                $this->testresult = $test[2]['pass'] = false;
            }
            $test[3]['title'] = '扩展：mbstring';
            if (extension_loaded('mbstring')) {
                $test[3]['result'] = $icon_s.'已开启';
                $test[3]['pass'] = true;
            } else {
                $test[3]['result'] = $icon_e.'未开启';
                $this->testresult = $test[3]['pass'] = false;
            }
            //函数检测
            $test[5]['title'] = '函数：file_get_contents';
            if (function_exists('file_get_contents')) {
                $test[5]['result'] = $icon_s.'已开启';
                $test[5]['pass'] = true;
            } else {
                $test[5]['result'] = $icon_e.'未开启';
                $this->testresult = $test[5]['pass'] = false;
            }
            // 文件权限
            $test[7]['title'] = '权限：/runtime文件夹';
            if (is_writable('./runtime')) {
                $test[7]['result'] = $icon_s.'可写';
                $test[7]['pass'] = true;
            } else {
                $test[7]['result'] = $icon_e.'不可写';
                $this->testresult = $test[7]['pass'] = false;
            }
            $test[8]['title'] = '权限：/upload文件夹';
            if (is_writable('./upload')) {
                $test[8]['result'] = $icon_s.'可写';
                $test[8]['pass'] = true;
            } else {
                $test[8]['result'] = $icon_e.'不可写';
                $this->testresult = $test[8]['pass'] = false;
            }
            $test[9]['title'] = '权限：/data文件夹';
            if (is_writable('./data')) {
                $test[9]['result'] = $icon_s.'可写';
                $test[9]['pass'] = true;
            } else {
                $test[9]['result'] = $icon_e.'不可写';
                $this->testresult = $test[9]['pass'] = false;
            }
            $test[10]['title'] = '权限：/public文件夹';
            if (is_writable('./public')) {
                $test[10]['result'] = $icon_s.'可写';
                $test[10]['pass'] = true;
            } else {
                $test[10]['result'] = $icon_e.'不可写';
                $this->testresult = $test[10]['pass'] = false;
            }
            $test[11]['title'] = '权限：/config/database.php文件';
            if (is_writable('./config/database.php')) {
                $test[11]['result'] = $icon_s.'可写';
                $test[11]['pass'] = true;
            } else {
                $test[11]['result'] = $icon_e.'不可写';
                $this->testresult = $test[11]['pass'] = false;
            }
            if (version_compare("7.0", PHP_VERSION, ">")) {
                $test[12]['title'] = 'always_populate_raw_post_data';
                if (ini_get('always_populate_raw_post_data')==-1) {
                    $test[12]['result'] = $icon_s.'支持';;
                    $test[12]['pass'] = true;
                } else {
                    $test[12]['result'] = $icon_e.'php版本小于7.0时,修改php.ini,去除always_populate_raw_post_data=-1前面的分号';
                    $this->testresult = $test[12]['pass'] = false;
                }
            }
            $test[13]['title'] = '权限：/app/common/model文件夹';
            if (is_writable('./app/common/model')) {
                $test[13]['result'] = $icon_s.'可写';
                $test[13]['pass'] = true;
            } else {
                $test[13]['result'] = $icon_e.'不可写';
                $this->testresult = $test[13]['pass'] = false;
            }
            return $this->fetch('/choosedb',compact('title','test'));
        } else {
            return $this->fetch('/'.$dbtype,compact('title','dbtype'));
        }
        
    }

    public function install($dbtype)
    {
        if(Request::isPost()) {
            $data = Request::post();
            switch ($dbtype) {
                case 'mysql':
                    $dbip = $data['dbip'] ? $data['dbip'] : $this->error('IP必填');
                    $dbport = $data['dbport'] ? $data['dbport'] : $this->error('端口必填');
                    $dbusername = $data['dbusername'] ? $data['dbusername'] : $this->error('数据库用户必填');
                    $dbpassword = $data['dbpassword'] ? $data['dbpassword'] : $this->error('数据库密码必填');
                    $dbname = $data['dbname'] ? strtolower($data['dbname']) : $this->error('数据库名称必填');
                    try {
                        $dsn = "mysql:host={$dbip};port={$dbport};charset=utf8";
                        $db = new \PDO($dsn, $dbusername, $dbpassword);
                        $sql = "CREATE DATABASE IF NOT EXISTS `".$dbname."` DEFAULT CHARACTER SET utf8";
                        $db->exec($sql);
                    } catch (\PDOException $e) {
                        $this->error($e->getMessage());
                    }
                    
                    try{
                        $sql = file_get_contents('./data/default/database.sql');
                        $dsn = "mysql:dbname=".$dbname.";host=".$dbip.";port=".$dbport.";charset=utf8";
                        $db = new \PDO($dsn, $dbusername, $dbpassword);
                        $sql = str_replace("\r", "\n", $sql);
                        $sql = explode(";\n", $sql);
                        foreach ($sql as $item) {
                            $item = trim($item);
                            if(empty($item)) continue;
                            $db->exec($item);
                        }
                    } catch (\PDOException $e) {
                        $this->error($e->getMessage());
                    }
                    //更新系统数据库配置文件
                    //读取配置内容
                    $conf = file_get_contents(env('app_path'). request()->module(). '/database/database_mysql.php');
                    //替换配置项
                    foreach ($data as $key => $value) {
                        $conf = str_replace("#{$key}#", $value, $conf);
                    }
                    //写入应用配置文件
                    if(file_put_contents(env('config_path'). 'database.php', $conf)){
                        @touch('./data/install.lock');
                        $this->success('系统安装完成！');
                    } else {
                        $this->error('写入配置文件权限不足！');
                    }
                    break;
                case 'sqlite':
                	$dbname = $data['dbname'] ? $data['dbname'] : $this->error('数据库名称必填');
                    $result = @copy('./data/default/database.db','./data/'.$dbname.'.db');
                    if($result) {
                        $conf = file_get_contents(env('app_path'). request()->module(). '/database/database_sqlite.php');
                        //替换配置项
                        $conf = str_replace("#dbname#", $dbname, $conf);
                        //写入应用配置文件
                        if(file_put_contents(env('config_path'). 'database.php', $conf)){
                            @touch('./data/install.lock');
                            $this->success('系统安装完成！');
                        } else {
                            $this->error('写入配置文件权限不足！');
                        }
                    }
                    $this->error('安装失败！');
                    break;
            }
        }
    }
    
    public function testdb()
    {
        if(request()->isPost()){
            $data = input('post.');
            $dbip = $data['dbip'] ? $data['dbip'] : $this->error('IP必填');
            $dbport = $data['dbport'] ? $data['dbport'] : $this->error('端口必填');
            $dbusername = $data['dbusername'] ? $data['dbusername'] : $this->error('数据库用户必填');
            $dbpassword = $data['dbpassword'] ? $data['dbpassword'] : $this->error('数据库密码必填');
            $dbname = $data['dbname'] ? strtolower($data['dbname']) : $this->error('数据库名称必填');
            $dsn = "mysql:host={$dbip};port={$dbport};charset=utf8";
            try {
                $db = new \PDO($dsn, $dbusername, $dbpassword);
            } catch (\PDOException $e) {
                $this->error('数据库连接失败');
            }
            try{
                $db->query("show databases;");
            }catch (\PDOException $e){
                $this->error('数据库连接失败');
            }
            $this->success('数据库连接成功');
        }else{
            $this->error('非法提交');
        }
    }
}
