<?php
// +----------------------------------------------------------------------
// | Quotes [未来可期]
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Author: 自助建站系统 https://www.kancloud.cn/btwcms-com/btwcms/2265967 作者QQ：1617643
// +----------------------------------------------------------------------
// | Date: 2020年2月5日
// +----------------------------------------------------------------------


include("../app/common.php");
$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;

@header('Content-Type: application/json; charset=UTF-8');

switch ($act) {

    case 'register':
        $username = trim(strip_tags(daddslashes($_POST['user'])));
        $password = trim(strip_tags(daddslashes($_POST['pass'])));
        $password2 = trim(strip_tags(daddslashes($_POST['pass2'])));
        $code = trim(strip_tags(daddslashes($_POST['code'])));
        $email = "";
        if($conf['need_email'] == 1){
            $email = trim(strip_tags(daddslashes($_POST['email'])));
            if(!preg_match('/^[A-z0-9._-]+@[A-z0-9._-]+\.[A-z0-9._-]+$/', $email)){
                $result = array("code" => -1, "msg" => "邮箱格式不正确！");
                exit(json_encode($result));
            }
            $row=$DB->query("select * from `wcms_code` where `type` = '1' and `code`='{$code}' and `email`='{$email}' order by `cid` desc limit 1")->fetch();
            if(!$row){
                $result = array("code" => -1, "msg" => "验证码不正确！ $code");
                exit(json_encode($result));
            }
            if($row['time']<time()-3600 || $row['status']>0){
                $result = array("code" => -1, "msg" => "验证码已失效，请重新获取！");
                exit(json_encode($result));
            }

        }else{ //未开启邮箱验证,使用 字母验证码
            $verifycode = 1;//验证码开关
            if (!function_exists("imagecreate") || !file_exists('./code.php')) $verifycode = 0;
            if ($verifycode == 1 && (!$code || strtolower($code) != $_SESSION['vc_code'])) {
                unset($_SESSION['vc_code']);
                $result = array("code" => -1, "msg" => "验证码错误,请重新输入");
                exit(json_encode($result));
            }
        }

        if ($password == null || $username == null || $password2 == null) {
            $result = array("code" => -1, "msg" => "数据填写不完整");
            exit(json_encode($result));
        }
        if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
            $result = array("code" => -1, "msg" => "用户名只能为英文或数字！");
            exit(json_encode($result));
        } elseif (strlen($password) < 6) {
            $result = array("code" => -1, "msg" => "密码不能低于6位！");
            exit(json_encode($result));
        }
        if ($password != $password2) {
            $result = array("code" => -1, "msg" => "两次输入密码不一致！");
            exit(json_encode($result));
        }
        $existUser = $DB->query("SELECT * FROM `wcms_user` WHERE `username`='{$username}' limit 1")->fetch();
        if ($existUser) {
            $result = array("code" => -1, "msg" => "账户存在,请更换用户名！");
            exit(json_encode($result));
        }
        $nickname = "网友";
        $city = getCityByIp($clientIp);
        $city = $city['city'];
        $password = md5($password);
        $sql = $DB->exec("INSERT INTO `wcms_user` (`username`, `password`,  `email`, `sid`,`phone`,`nickname`,`regtime`, `regip`, `regcity`, `mcode`,`money`,`status`)VALUES ('{$username}', '{$password}','{$email}','', '17800000000','{$nickname}',  '{$date}', '{$clientIp}','{$city}', '100','0.00', '1')");
        unset($_SESSION['vc_code']); //销毁验证码
        if ($sql) {
            $DB->exec("update `wcms_code` set `status` ='1' where `cid`='{$row['cid']}'");
            $result = array("code" => 1, "msg" => "用户注册成功");
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "用户注册失败,请稍后再试");
            exit(json_encode($result));
        }

        break;

    case 'login':
        $username = trim(strip_tags(daddslashes($_POST['user'])));
        $password = trim(strip_tags(daddslashes($_POST['pass'])));
        $isNologin = trim(strip_tags(daddslashes($_POST['isNologin'])));
        if ($password == null || $username == null) {
            $result = array("code" => -1, "msg" => "请填写账号密码后再登陆");
            exit(json_encode($result));
        }

        $userrow = $DB->query("SELECT * FROM `wcms_user` WHERE `username`='{$username}'  limit 1")->fetch();
        $password = md5($password);
        if ($username == $userrow['username'] && $password == $userrow['password']) {
            saveLog($userrow['uid'], "登录用户中心");
            /*
            $city = getCityByIp($clientIp);
            $city = $city['city'];
            $userLog = $DB->query("SELECT `uid` FROM `wcms_log` WHERE `uid`='{$userrow['uid']}' and `city`='{$city}' and `type`='登录用户中心' ")->rowCount();//判断异地
            $userLogAll = $DB->query("SELECT `uid` FROM `wcms_log` WHERE `uid`='{$userrow['uid']}' and `type`='登录用户中心'")->rowCount(); //总共登陆次数
            if ($userLogAll > 10 && $userLog < 5) { //在用户登陆第十次之后， 如果发生异地登陆开始执行
                //符合特定条件 发送邮件功能
                //如果当前登陆账户在此地登陆次数少于5次 则发送邮件
                $mail_name = $userrow['email'] ? $userrow['email'] : $conf["mail_name"];
                send_mail($mail_name, $conf["web_name"] . "-异地登陆提醒", '尊敬客户您好：');
            }

            */
            if (!$isNologin || $isNologin = 0) { //未开启30天免登录
                $expiretime = time() + 604800;
            } else {
                $expiretime = time() + 2592000;
            }
            $session = md5($username . $password . $password_hash);

            $token = authcode("{$username}\t{$session}\t{$expiretime}", 'ENCODE', SYS_KEY);
            setcookie("user_token", $token, $expiretime);
            exit('{"code":1,"msg":"尊敬的 ' . $userrow['nickname'] . ' ,登录成功!"}');
        } else {
            $result = array("code" => -1, "msg" => "用户名或密码不正确");
            exit(json_encode($result));
        }

        break;


    case 'logout':
        setcookie("admin_token", "", time()+6400,'/manage');
        setcookie("user_token", "1", time());
        $result = array("code" => 1, "msg" => "退出成功");
        exit(json_encode($result));
        break;


    case 'recoverPass':
        $code = trim(strip_tags(daddslashes($_POST['code'])));
        $email = trim(strip_tags(daddslashes($_POST['email'])));
        if ($code == null || $email == null) {
            $result = array("code" => -1, "msg" => "邮箱和验证码不能为空");
            exit(json_encode($result));
        }
        $userrow = $DB->query("SELECT `uid`,`username` FROM `wcms_user` WHERE `email`='{$email}' and `sid`='{$code}' limit 1")->fetch();
        if ($userrow) {
            $DB->exec("UPDATE `wcms_user` SET `password` ='e10adc3949ba59abbe56e057f20f883e',`sid`='' WHERE `uid`='{$userrow['uid']}'");
            $result = array("code" => 1, "msg" => "您的账号为:" . $userrow['username'] . " ,密码已重置为123456");
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "验证码失效");
            exit(json_encode($result));
        }
        break;


    case 'sendCode':
        $email = trim(daddslashes($_POST['email']));
        $type = trim(daddslashes($_POST['type']));
        if(!preg_match('/^[A-z0-9._-]+@[A-z0-9._-]+\.[A-z0-9._-]+$/', $email)){
            $result = array("code" => -1, "msg" => "邮箱格式不正确");
            exit(json_encode($result));
        }

        if (isset($_SESSION['send_mail']) && $_SESSION['send_mail'] > time() - 600) {
            $result = array("code" => -1, "msg" => "请勿频繁发送邮件，如果未收到请尝试在垃圾邮件箱寻找");
            exit(json_encode($result));
        }

        if($type == 1){ //发送注册 邮箱验证码

            $row=$DB->query("select * from `wcms_code` where `email`='{$email}' order by `cid` desc limit 1")->fetch();
            if($row['time']>time()-60){
                $result = array("code" => -1, "msg" => "两次发送邮件之间需要相隔60秒");
                exit(json_encode($result));
            }
            $count=$DB->query("select count(*) from `wcms_code` where `email`='{$email}' and time>'".(time()-3600*24)."'")->fetchColumn();
            if($count>6){
                $result = array("code" => -1, "msg" => "该邮箱发送次数过多，请更换邮箱！");
                exit(json_encode($result));
            }
            $count=$DB->query("select count(*) from `wcms_code` where `ip`='{$clientIp}' and time>'".(time()-3600*24)."'")->fetchColumn();
            if($count>10){
                $result = array("code" => -1, "msg" => "你今天发送次数过多，已被禁止发送！");
                exit(json_encode($result));
            }
            $row = $DB->query("SELECT uid FROM `wcms_user` WHERE `email`='{$email}' limit 1")->fetch();
            if ($row) {
                $result = array("code" => -1, "msg" => "该邮箱已经注册账号,请找回密码或更换邮箱");
                exit(json_encode($result));
            }
            $sub = $conf['web_name'].' - 注册账号';
            $code = rand(1111111,9999999);
            $msg = emailWritting($conf['web_name'], "注册账号", "您正在进行注册账号操作，本次操作验证码 :$code");
            $result = sendEmail($email, $sub, $msg);
            if($result===true) {
                if ($DB->exec("insert into `wcms_code` (`type`,`code`,`email`,`time`,`ip`,`status`) values ('1','" . $code . "','" . $email . "','" . time() . "','" . $clientIp . "','0')")) {
                    $_SESSION['send_mail'] = time();
                    $result = array("code" => 1, "msg" => "发送成功，请注意查收");
                    exit(json_encode($result));
                } else {
                    $result = array("code" => -1, "msg" => "写入数据库失败");
                    exit(json_encode($result));
                }
            }else{
                $result = array("code" => -1, "msg" => "邮件发送失败");
                exit(json_encode($result));
            }

        }else if($type == 2){//找回密码 邮箱验证码

            $row = $DB->query("SELECT uid FROM `wcms_user` WHERE `email`='$email' limit 1")->fetch();
            if (!$row) {
                $result = array("code" => -1, "msg" => "没有找到您的账号，请检查邮箱是否正确");
                exit(json_encode($result));
            }
            $scriptpath = str_replace('\\', '/', $_SERVER['SCRIPT_NAME']);
            $sitepath = substr($scriptpath, 0, strrpos($scriptpath, '/'));
            $siteurl = ($_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $sitepath . '/';
            $sub = $conf['web_name'] . ' - 用户密码找回';
            $sid = substr(md5(uniqid() . rand(1, 5)), 16);
            $DB->exec("UPDATE `wcms_user` SET `sid` ='{$sid}' WHERE `email`='{$email}'");
            $msg = emailWritting($conf['web_name'], "找回密码", "您正在进行找回密码操作，本次操作验证码 :$sid");
            $result = sendEmail($email, $sub, $msg);
            if ($result === true) {
                $_SESSION['send_mail'] = time();
                $result = array("code" => 1, "msg" => "发送成功，请注意查收");
                exit(json_encode($result));
            } else {
                file_put_contents('mail.log', $result);
                $result = array("code" => -1, "msg" => "邮件发送失败");
                exit(json_encode($result));
            }

        }else{
            $result = array("code" => -1, "msg" => "尝试刷新页面,再进行操作");
            exit(json_encode($result));
        }
        break;




    default:
        $result = array("code" => -1, "msg" => "服务器异常");
        exit(json_encode($result));
        break;

}



?>