<?php
/**
 * +------------------------------------------------------------
 * | CIM安装程序
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018/5/3
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018/5/3
 * +------------------------------------------------------------
 * |
 * +------------------------------------------------------------
 */
date_default_timezone_set('PRC');
error_reporting(E_ALL & ~E_NOTICE);

header('content-type:application:json;charset=utf8');

define('ROOT_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);
define('INSTALL_PATH', __DIR__ . DIRECTORY_SEPARATOR);

@set_time_limit(1000);

function lock()
{
    $file = @fopen(INSTALL_PATH . 'install.lock', 'wb+');
    if (!$file) {
        die('打开文件失败');
    }
    if (!@fwrite($file, "cim.wandu.net")) {
        die('写入文件失败');
    }
    @fclose($file);

    if (file_exists(ROOT_PATH . 'index_install.php')) {
        //删除有安装判断的入口文件
        @unlink(ROOT_PATH . 'index.php');
        //重命名无安装判断入的口文件
        @rename(ROOT_PATH . 'index_install.php', ROOT_PATH . 'index.php');
    }
}

function sql_split($sql, $tablepre, $auto_increment = 0)
{

    if ($tablepre != "cim_")
        $sql = str_replace("cim_", $tablepre, $sql);

    $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $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++;
    }
    if (!empty($auto_increment)) {
        $ret[$num] = "ALTER TABLE `" . $tablepre . "data` MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=" . $auto_increment . ";";
    }
    return $ret;
}

$step = (!empty($_REQUEST['step']) && in_array($_REQUEST['step'], [0, 1, 2])) ? $_REQUEST['step'] : 0;
switch ($step) {
    case 0:
        if (file_exists('./install.lock')) {
            $result = ['code' => 1, 'msg' => '已安装过系统'];
        } else {
            $sys = include(dirname(ROOT_PATH) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'cim.php');
            $result = ['code' => 0, 'msg' => '未安装', 'data' => $sys];
        }
        break;
    case 1:
        $gd = function_exists('gd_info') ? gd_info() : array();
        $result['data']['env'] = [
            [
                'name' => 'PHP版本',
                'now' => phpversion() < 7 ? 'PHP版本必须大于7' : phpversion(),
                'status' => (phpversion() < 7) ? 0 : 1,
                'request' => '7.0.1'
            ], [
                'name' => 'session',
                'now' => function_exists('session_start') ? '开启' : '请开启session支持',
                'status' => function_exists('session_start') ? 1 : 0,
                'request' => '开启'
            ], [
                'name' => 'GD库',
                'now' => empty($gd['GD Version']) ? '请开始gd扩展' : '开启',
                'status' => empty($gd['GD Version']) ? 0 : 1,
                'request' => '开启'
            ], [
                'name' => 'mysqli',
                'now' => function_exists('mysqli_connect') ? '开启' : '请安装mysqli扩展',
                'status' => function_exists('mysqli_connect') ? 1 : 0,
                'request' => '开启'
            ], [
                'name' => 'fileinfo',
                'now' => extension_loaded('fileinfo') ? '开启' : '请开启fileinfo扩展',
                'status' => extension_loaded('fileinfo') ? 1 : 0,
                'request' => '开启'
            ], [
                'name' => 'memcache',
                'now' => extension_loaded('memcache') ? '开启' : '建议开启memcache存储',
                'status' => 1,
                'request' => '建议开启'
            ]
        ];
        $result['data']['auth'] = [
            [
                'path' => 'public/install',
                'request' => '可写',
                'now' => is_writable(INSTALL_PATH) ? '可写' : '不可写',
                'status' => is_writable(INSTALL_PATH) ? 1 : 0,
            ],
            [
                'path' => 'config/database.php',
                'request' => '可写',
                'now' => is_writable(dirname(ROOT_PATH) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php') ? '可写' : '不可写',
                'status' => is_writable(dirname(ROOT_PATH) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php') ? 1 : 0,
            ],
            [
                'path' => 'public/uploads',
                'request' => '可写',
                'now' => is_writable(ROOT_PATH . 'uploads') ? '可写' : '不可写',
                'status' => is_writable(ROOT_PATH . 'uploads') ? 1 : 0,
            ],
            [
                'path' => 'runtime',
                'request' => '可写',
                'now' => is_writable(dirname(ROOT_PATH) . DIRECTORY_SEPARATOR . 'runtime') ? '可写' : '不可写',
                'status' => is_writable(dirname(ROOT_PATH) . DIRECTORY_SEPARATOR . 'runtime') ? 1 : 0,
            ],
        ];
        $status = array_merge(array_column($result['data']['env'], 'status'), array_column($result['data']['auth'], 'status'));
        if (array_sum($status) < count($status)) {
            $result['code'] = 0;
            $result['msg'] = '环境检测未通过';
        } else {
            $result['code'] = 1;
            $result['msg'] = '环境检测通过';
        }
        break;
    case 2:
        //数据库地址
        $host = $_POST['host'] ?: 'localhost';
        //数据库名称
        $name = $_POST['name'] ?: 'cim';
        //数据库用户名
        $user = $_POST['user'] ?: '';
        //数据库密码
        $pwd = $_POST['pwd'] ?: '';
        //数据库端口
        $port = $_POST['port'] ?: '3306';
        //数据库前缀
        $prefix = $_POST['prefix'] ?: 'cim_';
        //后台管理员账号
        $admin_name = $_POST['admin_name'] ?: 'cim';
        //后台管理员密码
        $admin_pwd = $_POST['admin_pwd'] ?: 'cim';
        //后台管理员邮箱
        $admin_email = $_POST['email'];
        //数据表自增id
        $auto_increment = $_POST['auto_increment'] ?: 0;
        if (function_exists('mysqli_connect')) {
            $connect = @mysqli_connect($host, $user, $pwd, NULL, $port);
            if (!mysqli_connect_errno($connect)) {
                mysqli_set_charset($connect, "utf8");
                $version = mysqli_get_server_info($connect);
                if ($version >= 5.7) {
                    if (isset($_POST['n'])) {
                        if (mysqli_select_db($connect, $name) || mysqli_query($connect, "CREATE DATABASE IF NOT EXISTS `" . $name . "` DEFAULT CHARACTER SET utf8;")) {
                            mysqli_select_db($connect, $name);
                            $file = file_get_contents(INSTALL_PATH . 'cim.sql');
                            $sqls = sql_split($file, $prefix, $auto_increment);
                            $count = count($sqls);
                            for ($i = $_POST['n']; $i < $count; $i++) {
                                $sql = trim($sqls[$i]);
                                if (strstr($sql, 'CREATE TABLE')) {
                                    preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
                                    mysqli_query($connect, "DROP TABLE IF EXISTS `$matches[1]");
                                    $res = mysqli_query($connect, $sql);
                                    $i++;
                                    $result['n'] = $i;
                                    if ($res) {
                                        $result['msg'] = '创建数据表' . $matches[1] . '，成功';
                                        $result['time'] = date('Y-m-d H:i:s');
                                        $result['code'] = 1;
                                    } else {
                                        $result['msg'] = '创建数据表' . $matches[1] . '，失败';
                                        $result['code'] = 0;
                                    }
                                    exit(json_encode($result));
                                } else {
                                    if (trim($sql) == '')
                                        continue;
                                    mysqli_query($connect, $sql);
                                }
                            }
                            //替换数据库配置文件
                            $config_path = ROOT_PATH . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
                            $config = @file_get_contents($config_path);
                            $config = preg_replace('/\'hostname\'\s*\=\>.*\,/', "'hostname'=>'$host',", $config);
                            $config = preg_replace('/\'database\'\s*\=\>.*\,/', "'database'=>'$name',", $config);
                            $config = preg_replace('/\'username\'\s*\=\>.*\,/', "'username'=>'$user',", $config);
                            $config = preg_replace('/\'password\'\s*\=\>.*\,/', "'password'=>'$pwd',", $config);
                            $config = preg_replace('/\'hostport\'\s*\=\>.*\,/', "'hostport'=>'$port',", $config);
                            $config = preg_replace('/\'prefix\'\s*\=\>.*\,/', "'prefix'=>'$prefix',", $config);
                            @chmod($config_path, 0777);
                            @file_put_contents($config_path, $config);
                            //替换系统配置文件
                            $cim_path = ROOT_PATH . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'cim.php';
                            @chmod($cim_path, 0777);
                            @file_put_contents($cim_path, preg_replace('/\'install_date\'\s*\=\>.*\,/', "'install_date'=>'" . date('Y-m-d H:i:s') . "',", file_get_contents($cim_path)));
                            //替换缓存配置文件
                            $cache_path = ROOT_PATH . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'cache.php';
                            @chmod($cache_path, 0777);
                            @file_put_contents($cache_path, preg_replace('/\'prefix\'\s*\=\>.*\,/', "'prefix'=>'" . substr(md5($_SERVER['HTTP_HOST'] . rand(1, 10000)), 0, 10) . "_',", file_get_contents($cache_path)));
                            $sql = "INSERT INTO `{$prefix}user` values(null,1,'{$admin_name}','{$admin_email}','" . md5($admin_pwd) . "','','','','',0,0,1,0,null);";
                            mysqli_query($connect, $sql);
                            $sql = "INSERT INTO `{$prefix}admin` (`id`,`create_time`) values(1," . time() . ");";
                            mysqli_query($connect, $sql);
                            $sql = "INSERT INTO `{$prefix}user_log` (`user_id`,`action`,`ip`,`port`,`os`,`browser`,`event`,`memo`,`create_time`) values(1,'register','127.0.0.1','50901','unknown','unknown','用户注册','',1537925560);";
                            mysqli_query($connect, $sql);
                            mysqli_close($connect);
                            $result['msg'] = '成功添加管理员<br />成功写入配置文件<br />安装完成．';
                            $result['time'] = date('Y-m-d H:i:s');
                            $result['code'] = 1;
                            $result['n'] = 'installed';
                            //写入锁文件
                            lock();
                        } else {
                            $result = ['code' => 0, 'msg' => '数据库创建失败'];
                        }
                    } else {
                        $result = ['code' => 1, 'msg' => '数据库连接成功'];
                    }
                } else {
                    $result = ['code' => 0, 'msg' => '当前数据库版本:' . $version . ',数据库版本必须5.7以上'];
                }
            } else {
                $result = ['code' => 0, 'msg' => '连接数据库失败'];
            }
        } else {
            $result = ['code' => 0, 'msg' => '请安装 mysqli 扩展!'];
        }
        break;
}
exit(json_encode($result));






