<?php

class install
{
	private $root_path;
    private $dbhost;
    private $dbuser;
    private $dbpw;
    private $dbname;
    private $dbprefix;
    private $force;

    private $manager;
    private $manager_pwd;
    private $manager_ckpwd;
    private $manager_email;
    
    private $pdo = null;
    public $version;
    
    public function __construct()
    {
        $this->root_path = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR;
        $info = include $this->root_path.'vendor'.DIRECTORY_SEPARATOR.'wendasns'.DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'config.php';
        $this->version = $info['version'];
    }
    
	public function index()
	{
		
	}
	
	public function database()
	{
		if($_POST){
			$this->_database();
		}
	}

	public function finish()
	{
		
	}
	
	private function _database()
	{
        //数据库信息
        $this->dbhost = $_POST['dbhost'];//数据库服务器
        $this->dbuser = $_POST['dbuser'];//数据库用户名
        $this->dbpw = $_POST['dbpw'];//数据库密码
        $this->dbname = $_POST['dbname'];//数据库名
        $this->dbprefix = $_POST['dbprefix'];//数据库表前缀
        $this->force = $_POST['force'];

        //创始人信息
        $this->manager = $_POST['manager'];
        $this->manager_pwd = $_POST['manager_pwd'];
        $this->manager_ckpwd = $_POST['manager_ckpwd'];
        $this->manager_email = $_POST['manager_email'];
        
        // 检测是否安装过
        if (file_exists($this->root_path.'install.lock')) {
            $this->error('您已经安装过，重新安装需要先删除网站根目录下的 install.lock 文件');
        }

        if ($this->manager_pwd !== $this->manager_ckpwd) {
            $this->error('管理员两次密码不一致，请重新输入');
        }
        if (!preg_match('/^[\x7f-\xff\dA-Za-z\.\_]+$/', $this->manager)) {
            $this->error('用户名请用字母');
        }
        $usernameLen = strlen($this->manager);
        $passwordLen = strlen($this->manager_pwd);
        
        if ($usernameLen < 3 || $usernameLen > 15 || $passwordLen < 6 || $passwordLen > 25) {
            $this->error('用户名最长15字符，密码不能少于6位');
        }

        if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$this->manager_email)) {
            $this->error('请输入正确的电子邮箱地址');
        }

        try{
            //查询是否有数据库
            $this->pdo = new PDO("mysql:host={$this->dbhost};dbname={$this->dbname}",$this->dbuser,$this->dbpw);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        }catch(\PDOException $e){
            if(strpos($e->getMessage(), 'database exists') === false){
                $this->error($e->getMessage());
            }
        }
        
        $this->createdata();
        
	}
	
	private function createdata()
    {
        try {
            
            //创建数据表
            $sql_file = file_get_contents('db.sql');
            $sql_file = str_replace("{th}",$this->dbprefix,$sql_file);
            $this->pdo->exec($sql_file);

            //插入系统原始数据
            $sql_file = file_get_contents('data.sql');
            $sql_file = str_replace("{th}",$this->dbprefix,$sql_file);
            $this->pdo->exec($sql_file);
            
            //插入管理员信息
            $salt = $this->getrandstr();
            $password = md5(md5($this->manager_pwd).$salt);
            $create_time = time();
            $sql = "INSERT INTO `{$this->dbprefix}admin` SET `group_id`=1,`username`='{$this->manager}',`password`='{$password}',`salt`='{$salt}',`email`='{$this->manager_email}',`create_time`='{$create_time}',`status`=1";
            $this->pdo->exec($sql);
            
            //插入通讯信息
            $url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
            $secretkey = md5($url);
            $sql = "INSERT INTO `{$this->dbprefix}wendid_app` SET `name`='wendasns',`url`='{$url}/',`secretkey`='{$secretkey}',`apifile`='wendid.php'";
            $this->pdo->exec($sql);

            //更新配置信息
            $pwdHash = $this->getrandstr(8);
            $prefix = $this->getrandstr(3);
            $this->pdo->exec("UPDATE `{$this->dbprefix}config` SET `value`='{$pwdHash}' WHERE `id`='5'");
            $this->pdo->exec("UPDATE `{$this->dbprefix}config` SET `value`='{$url}' WHERE `id`='23'");
            $this->pdo->exec("UPDATE `{$this->dbprefix}config` SET `value`='1' WHERE `id`='24'");
            $this->pdo->exec("UPDATE `{$this->dbprefix}config` SET `value`='{$secretkey}' WHERE `id`='25'");
            $this->pdo->exec("UPDATE `{$this->dbprefix}config` SET `value`='{$prefix}_' WHERE `id`='35'");
            $this->pdo->exec("UPDATE `{$this->dbprefix}advert` SET `content`='{$url}/image/focus/b464659a9124057a1736e93a50474d89.jpg' WHERE `id`='1'");
            $this->pdo->exec("UPDATE `{$this->dbprefix}advert` SET `content`='{$url}/image/focus/a1749704c9dd9459814431be820060ed.png' WHERE `id`='2'");
            
        }catch(\PDOException $e){
            $this->error($e->getMessage()); 
        }
        $this->conff();
    }
    
    private function conff()
    {
        $row = fopen($this->root_path.'.env', 'r');
        $k = '';
        $res = [];
        while(!feof($row)){
            $content = fgets($row);
            $content = trim($content);
            if($content!==''){
            	if(strpos($content,'=') !== false){
            		list($key,$val) = explode(' = ',$content);
            		$res[$k][$key] = $val;
            	}else{
            		$k = strtr($content,['['=>'',']'=>'']);
            		$res[$k] = [];
            	}
            }
        }
        
        $res['DATABASE']['HOSTNAME'] = $this->dbhost;
        $res['DATABASE']['USERNAME'] = $this->dbuser;
        $res['DATABASE']['PASSWORD'] = $this->dbpw;
        $res['DATABASE']['DATABASE'] = $this->dbname;
    	$res['DATABASE']['PREFIX'] = $this->dbprefix;
    	fclose($row);
    	
    	$file = fopen($this->root_path.'.env', 'w');
    	$str = '';
    	foreach($res as $k=>$v){
    		$str .= "[{$k}]\r\n";
    		foreach($v as $key=>$val){
    			$str .= "{$key} = {$val}\r\n";
    		}
    		$str .= "\r\n";
    	}
    	fwrite($file, $str);
        fclose($file);
        
        file_put_contents($this->root_path.'install.lock',time());
        	
        $this->success('安装完毕');
    }
    
    private function getrandstr($length=6)
    {
		$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		$randStr = str_shuffle($str);
		$rands= substr($randStr,0,$length);
		return $rands;
	}
	
	private function error($code=1,$message='')
	{
		if(is_numeric($code)){
			$msg = $message;
		}else{
			$msg = $code;
			$code = 1;
		}
		echo json_encode(['code'=>$code,'msg'=>$msg]);
		die;
	}
	
	private function success($msg)
	{
		$this->error(0,$msg);
	}
}
$action = empty($_GET['action'])?'index':$_GET['action'];

$install = new install();
$version = $install->version;
$install->$action();
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>安装向导 - WendaSNS问答社区系统</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="//cdn.bootcdn.net/ajax/libs/layui/2.5.7/css/layui.css">
  <link rel="stylesheet" href="//cdn.bootcdn.net/ajax/libs/layui/2.5.7/css/modules/layer/default/layer.css?v=3.1.1" media="all">
  <script src="//cdn.bootcdn.net/ajax/libs/layui/2.5.7/layui.all.js"></script>
  <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
    body {background-color: #F2F2F2;}
    header{
    	    position: relative;
    left: 0;
    top: 0;
    padding-top: 110px;
    padding-bottom: 10px;
    box-sizing: border-box;
    	display: block!important;
    	
    }
    .main{
    	    width: 750px;
    		margin: 0 auto;
    		box-sizing: border-box;
    }
    .layui-textarea {
    min-height: 500px;
    	
    }
    .layui-card {border-radius: 10px;}
    .layui-input {border-radius: .25rem;}
    .layui-input:hover,.layui-textarea:hover{border-color:#5FB878!important}.layui-input:focus,.layui-textarea:focus{border-color:#007bff!important;box-shadow:0 0 0 .2rem rgba(0,123,255,.25);}
    .accept{
    	
    	text-align: center;
    	
    	padding: 10px 0;
    }
    footer{
    	text-align: center;
    }
    .layui-elem-field legend{
    	 font-size: 14px;
    }
    .layui-form-item .layui-input-inline {
    
    width: 300px;
    }
    .layui-form-label {
    	font-size: 15px;
    	width: 100px;
    }
    .success {
    width: 600px;
    margin: 30px auto;
    padding: 30px 15px;
    border-top: 5px solid #009688;
    line-height: 30px;
    text-align: center;
    font-size: 16px;
    font-weight: 300;
    color: #999;
    font-size: 18px;
	}
   </style>

</head>
<body>
<?php if($action=='index'): ?>
	<header>
		<div class="main">
		<div class="layui-card">
			<div class="layui-card-header"><h3>安装向导<small style="float: right;">V<?=$version?></small></h3></div>
			<div class="layui-card-body">
			<textarea class="layui-textarea">
	Wendasns 软件使用协议

	版权所有(c)2020，wendasns.com保留所有权力。

	感谢您选择 wendasns问答社区系统, 希望我们的产品能够帮您把网站发展的更快、更好、更强！

	官方网站为 http://www.wendasns.com

	本授权协议适用于 wendasns 任何版本，本公司拥有对本授权协议的最终解释权和修改权。

	wendasns问答社区系统(以下简称 wendasns)使用限制 
	  1、您在使用 wendasns 时应遵守中华人民共和国相关法律法规、您所在国家或地区之法令及相关国际惯例，不将 wendasns 用于任何非法目的，也不以任何非法方式使用 wendasns。
	  2、所有用户均可查看 wendasns 的全部源代码,也可以根据自己的需要对其进行修改！但无论如何，既无论用途如何、是否经过修改或美化、修改程度如何，只要您使用 wendasns 的任何整体或部分程序算法，都必须保留页脚处的本公司下属网站(https://www.wendasns.com)链接地址，不能清除或修改。
	  3、wendasns 中集成交易或支付接口，通过交易或支付接口产生的交易行为与本公司无关，您不得利用本服务从事侵害他人合法权益之行为，否则应承担所有相关法律责任，您应承担赔偿责任。上述行为包括但不限于： 
	    a、侵害他人名誉权、隐私权、商业秘密、商标权、著作权、专利权等合法权益。 
	    b、从事不法交易行为，如贩卖枪支、毒品、禁药、盗版软件、黄色淫秽物品、其他本公司认为不得使用本服务进行交易的物品等。 
	    c、提供赌博资讯或以任何方式引诱他人参与非法博弈。
	    d、从事任何可能含有电脑病毒或是可能侵害本服务系统、资料之行为。 
	    e、其他本公司有正当理由认为不适当之行为。 

	wendasns 免责声明
	  1、利用 wendasns 构建的网站的任何信息内容以及导致的任何版权纠纷和法律争议及后果，wendasns 官方不承担任何责任。
	  2、wendasns 损坏包括程序的使用(或无法再使用)中所有一般化、特殊化、偶然性的或必然性的损坏(包括但不限于数据的丢失，自己或第三方所维护数据的不正确修改，和其他程序协作过程中程序的崩溃等)，wendasns 官方不承担任何责任。

	电子文本形式的授权协议如同双方书面签署的协议一样，具有完全的和等同的法律效力。您一旦安装使用wendasns，即被视为完全理解并接受本协议的各项条款，在享有上述条款授予的权力的同时，受到相关的约束和限制。协议许可范围以外的行为，将直接违反本授权协议并构成侵权，本公司有权随时终止授权，责令停止损害，并保留追究相关责任的权力。
			</textarea>
			
			</div>
			<div class="accept">
				<a href="?action=database" class="layui-btn layui-btn-normal">接受使用协议</a>
				</div>
		</div>
	</div>
	</header>
<?php endif; ?>

<?php if($action=='database'): ?>
	<header>
		<div class="main">
		<div class="layui-card">
			<div class="layui-card-header"><h3>创建数据<small style="float: right;">V<?=$version?></small></h3></div>
			<div class="layui-card-body">
	
			<div class="layui-form">
				<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
  <legend>数据库信息</legend>
</fieldset>
				
			<div class="layui-form-item">
    		<label class="layui-form-label">数据库服务器</label>
		    <div class="layui-input-inline">
		      <input type="text" name="dbhost" lay-verify="required" autocomplete="off" placeholder="localhost" value="localhost" class="layui-input">
		    </div>
		    <div class="layui-form-mid layui-word-aux">数据库服务器地址，一般为localhost</div>
		  </div>

		  <div class="layui-form-item">
    		<label class="layui-form-label">数据库名称</label>
		    <div class="layui-input-inline">
		      <input type="text" name="dbname" lay-verify="required" autocomplete="off" placeholder="" value="" class="layui-input">
		    </div>
		  </div>
		  	  
		  <div class="layui-form-item">
    		<label class="layui-form-label">数据库用户名</label>
		    <div class="layui-input-inline">
		      <input type="text" name="dbuser" lay-verify="required" autocomplete="off" placeholder="root" value="root" class="layui-input">
		    </div>
		  </div>
		  		
		  <div class="layui-form-item">
    		<label class="layui-form-label">数据库密码</label>
		    <div class="layui-input-inline">
		      <input type="text" name="dbpw" lay-verify="required" autocomplete="off" placeholder="" value="" class="layui-input">
		    </div>
		  </div>
		  	  
		  <div class="layui-form-item">
    		<label class="layui-form-label">数据库表前缀</label>
		    <div class="layui-input-inline">
		      <input type="text" name="dbprefix" lay-verify="required" autocomplete="off" placeholder="wds_" value="wds_" class="layui-input">
		    </div>
		    <div class="layui-form-mid layui-word-aux">建议使用默认，同一数据库安装多个需修改</div>
		  </div>
				
			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
			  <legend>创始人信息</legend>
			</fieldset>
				
			<div class="layui-form-item">
    		<label class="layui-form-label">管理员帐号</label>
		    <div class="layui-input-inline">
		      <input type="text" name="manager" lay-verify="required" autocomplete="off" placeholder="admin" value="admin" class="layui-input">
		    </div>
		  </div>
		  	  
		  <div class="layui-form-item">
    		<label class="layui-form-label">密码</label>
		    <div class="layui-input-inline">
		      <input type="text" name="manager_pwd" lay-verify="required" autocomplete="off" placeholder="" value="" class="layui-input">
		    </div>
		  </div>
		  	  
		  <div class="layui-form-item">
    		<label class="layui-form-label">重复密码</label>
		    <div class="layui-input-inline">
		      <input type="text" name="manager_ckpwd" lay-verify="required" autocomplete="off" placeholder="" value="" class="layui-input">
		    </div>
		  </div>
		  	  
		  <div class="layui-form-item">
    		<label class="layui-form-label">管理员Email</label>
		    <div class="layui-input-inline">
		      <input type="text" name="manager_email" lay-verify="required|email" autocomplete="off" placeholder="" value="" class="layui-input">
		    </div>
		  </div>
		  	  <input type="hidden" name="force" value="0">
		  	  <div class="accept"><button class="layui-btn layui-btn-normal" lay-submit lay-filter="J_form_submit">创建数据库</button></div>
			</div>
				  
			</div>
		</div>
	</div>
	</header>
<script type="text/javascript">
;!function(){
  var $ = layui.$
  ,layer = layui.layer
  ,form = layui.form;

    form.on('submit(J_form_submit)', function(obj){
    	var _this = $(this);
    	go(obj.field, _this);
        return false;
    });
    
}();
function go(data,_this){
        layui.$.ajax({
            url: ''
            ,type: 'post'
            ,data: data
            ,dataType: 'json'
    		,beforeSend: function(XMLHttpRequest){
    			var textnode = document.createTextNode('\u4e2d\u002e\u002e\u002e');
  	  	  		_this[0].appendChild(textnode);
  	  	  		_this.prop('disabled',true).addClass('layui-btn-disabled');
    		}
    		,complete: function(XMLHttpRequest, textStatus){
    			var org_text = _this.text();
  	  	  	  	_this.text(org_text.replace(/(\u4e2d\u002e\u002e\u002e)$/, ''));
  	  	  	  	_this.removeProp('disabled').removeClass('layui-btn-disabled');
  	  	  	}
            ,success: function(res){
            	if(res.code==2){
			      layer.confirm(res.msg, {}, function(){
			      	  data.force = 1;
			      	go(data,_this);
			      });
			      return false;
            	}
            	
            	layer.msg(res.msg,{time:2000},function(){
	                if(res.code>0){
	                    layer.msg(res.msg);
	                    return false;
	                }
	                location.href = '?action=finish';
            	});
                
            }
    		,error: function(res){
    		    layer.msg('\u63d0\u4ea4\u5f02\u5e38');
    		}
        });
}
</script>
<?php endif; ?>

<?php if($action=='finish'): ?>
		<header>
		<div class="main">
		<div class="layui-card">
			<div class="layui-card-header"><h3>安装成功<small style="float: right;">V<?=$version?></small></h3></div>
			<div class="layui-card-body">
				<div style="line-height: normal; height: 300px;text-align: center;"><i class="layui-icon layui-icon-face-smile" style="font-size: 200px;color: #009688;"></i>Success</div>
				<div class="success"><p>点击进入<a href="/">网站首页</a>，或进入<a href="/admin.php">网站后台</a></p><p style="font-size: 14px;"><img src="https://www.wendasns.com/wdintog/finish.gif?v=<?=$version?>" height="22" width="22"><font color="red">为安全起见，安装成功后，建议删除安装目录"public\install"</font></p></div>
			</div>
		</div>
	</div>
	
	</header>
<?php endif; ?>

	<footer>
		<div class="main">
			<p>Powered by <a href="https://www.wendasns.com">Wendasns V<?=$version?></a> © 2020-<?=date('Y',time())?>&nbsp;&nbsp;<a href="https://www.wendasns.com">WendaSNS问答社区系统</a></p>
		</div>
	</footer>
</body>
</html>