<?php
include("./includes/common.php");

if(!$conf['userlogin']){
    @header('Content-Type: text/html; charset=UTF-8');
	exit("<script language='javascript'>alert('未开启登录');window.location.href='./';</script>");
}
if($islogin2==1){
	@header('Content-Type: text/html; charset=UTF-8');
	exit("<script language='javascript'>alert('您已登录！');window.location.href='./';</script>");
}
if(isset($_POST['act']) && $_POST['act']=='forgot'){
    @header('Content-Type: application/json; charset=UTF-8');
    $email = trim(isset($_POST['email'])?daddslashes($_POST['email']):'');
    if(empty($email)){
        exit('{"code":-1,"msg":"请输入邮箱"}');
    }
    if(!preg_match('/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/', $email)){
        exit('{"code":-1,"msg":"邮箱格式不正确"}');
    }
    $user=$DB->find('user','*',['email'=>$email], null, '1');
    if(!$user){
        exit('{"code":-1,"msg":"该邮箱未注册"}');
    }
    if($user['type']!='local'){
        exit('{"code":-1,"msg":"该邮箱未绑定本地账号，无法通过邮箱找回"}');
    }
    if($user['enable']==0){
        exit('{"code":-1,"msg":"当前用户已被禁止登录"}');
    }
    if(!$conf['mail_open'] || !$conf['mail_smtp'] || !$conf['mail_user'] || !$conf['mail_pass']){
        exit('{"code":-1,"msg":"邮件服务未配置，请联系管理员"}');
    }
    $token = md5(uniqid(mt_rand(), true));
    $expire = time()+1800;
    $DB->update('user', ['reset_token'=>$token, 'reset_expire'=>$expire], ['uid'=>$user['uid']]);
    try{
        $Mailer = new \lib\Mailer($conf['mail_smtp'], $conf['mail_port'], $conf['mail_user'], $conf['mail_pass'], $conf['mail_ssl'], $conf['mail_from'], $conf['mail_name']);
        $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
        $link = $scheme.$host.$dir.'/forgot.php?reset='.$token;
        $title = $conf['title'].' - 密码找回';
        $content = '<div style="font-family:Arial,Microsoft YaHei;font-size:14px;line-height:1.8;color:#333;">'.
            '<h3 style="color:#23b7e5;">密码找回</h3>'.
            '<p>尊敬的 <b>'.htmlspecialchars($user['nickname']).'</b>，您好：</p>'.
            '<p>您正在申请找回 <b>'.htmlspecialchars($conf['title']).'</b> 的登录密码，请点击以下链接进行重置：</p>'.
            '<p style="margin:15px 0;"><a href="'.$link.'" style="background:#23b7e5;color:#fff;padding:10px 24px;text-decoration:none;border-radius:4px;">重置密码</a></p>'.
            '<p style="word-break:break-all;color:#888;">如果按钮无法点击，请复制以下链接到浏览器打开：<br/><a href="'.$link.'">'.$link.'</a></p>'.
            '<p>该链接 <b>30分钟</b> 内有效，为保障账号安全，请勿将链接转发给他人。</p>'.
            '<p style="color:#999;font-size:12px;">如果您没有申请找回密码，请忽略此邮件。</p>'.
            '</div>';
        $res = $Mailer->send($email, $title, $content);
        if(isset($res['code']) && $res['code']!==0){
            $DB->update('user', ['reset_token'=>'', 'reset_expire'=>0], ['uid'=>$user['uid']]);
            exit('{"code":-1,"msg":"邮件发送失败，请稍后重试"}');
        }
    }catch(Exception $e){
        $DB->update('user', ['reset_token'=>'', 'reset_expire'=>0], ['uid'=>$user['uid']]);
        exit('{"code":-1,"msg":"邮件发送失败，请稍后重试"}');
    }
    exit('{"code":0,"msg":"重置链接已发送至您的邮箱，请30分钟内完成重置"}');
}elseif(isset($_POST['act']) && $_POST['act']=='reset'){
    @header('Content-Type: application/json; charset=UTF-8');
    $token = trim(isset($_POST['token'])?daddslashes($_POST['token']):'');
    $password = isset($_POST['password'])?$_POST['password']:'';
    $repassword = isset($_POST['repassword'])?$_POST['repassword']:'';
    if(empty($token)){
        exit('{"code":-1,"msg":"重置链接无效"}');
    }
    if(strlen($password) < 6 || strlen($password) > 32){
        exit('{"code":-1,"msg":"密码长度需为6-32位"}');
    }
    if($password !== $repassword){
        exit('{"code":-1,"msg":"两次输入的密码不一致"}');
    }
    $user=$DB->find('user','*',['reset_token'=>$token], null, '1');
    if(!$user || $user['reset_expire'] < time()){
        exit('{"code":-1,"msg":"重置链接无效或已过期，请重新申请"}');
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $DB->update('user', ['password'=>$hash, 'reset_token'=>'', 'reset_expire'=>0], ['uid'=>$user['uid']]);
    exit('{"code":0,"msg":"密码重置成功，请使用新密码登录"}');
}

$reset_token = isset($_GET['reset']) ? daddslashes(trim($_GET['reset'])) : '';
if($reset_token){
    $reset_user = $DB->find('user','uid',['reset_token'=>$reset_token], null, '1');
    if(!$reset_user){
        $title = '密码找回 - ' . $conf['title'];
        $authTitle = '密码找回';
$authSub   = '输入注册邮箱，我们发送重置链接';
$authIcon  = 'fa-key';
include SYSTEM_ROOT.'auth_header.php';
        echo '<div class="auth-tip">重置链接无效或已过期，请重新申请。</div>';
        echo '<div class="auth-links"><a href="./forgot.php">返回重新申请</a><a href="./login.php">去登录</a></div>';
        
        include SYSTEM_ROOT.'auth_footer.php';
        exit;
    }
    $title = '重置密码 - ' . $conf['title'];
    $authTitle = '重置密码';
$authSub   = '请设置你的新密码';
$authIcon  = 'fa-key';
include SYSTEM_ROOT.'auth_header.php';
?>
            <form id="resetform" onsubmit="return resetSubmit();">
                <div class="auth-field">
                    <i class="fa fa-lock"></i>
                    <input type="password" name="password" id="password" placeholder="新密码（6-32位）" required="">
                </div>
                <div class="auth-field">
                    <i class="fa fa-lock"></i>
                    <input type="password" name="repassword" id="repassword" placeholder="确认新密码" required="">
                </div>
                <input type="hidden" name="token" id="token" value="<?php echo htmlspecialchars($reset_token);?>">
                <button type="submit" class="auth-btn"><i class="fa fa-key"></i> 重置密码</button>
            </form>
            <div class="auth-links"><a href="./login.php">返回登录</a></div>
<?php
    include SYSTEM_ROOT.'auth_footer.php';
}else{
    $title = '密码找回 - ' . $conf['title'];
    $authTitle = '密码找回';
$authSub   = '输入注册邮箱，我们发送重置链接';
$authIcon  = 'fa-key';
include SYSTEM_ROOT.'auth_header.php';
?>
            <form id="forgotform" onsubmit="return forgotSubmit();">
                <div class="auth-field">
                    <i class="fa fa-envelope"></i>
                    <input type="email" name="email" id="email" placeholder="请输入注册邮箱" required="">
                </div>
                <button type="submit" class="auth-btn"><i class="fa fa-paper-plane"></i> 发送重置链接</button>
            </form>
            <div class="auth-links">重置链接将发送至您的注册邮箱</p>
            <div class="auth-tip"><a href="./login.php">返回登录</a></p>
<?php
    include SYSTEM_ROOT.'auth_footer.php';
}
?>
<script src="https://s4.zstatic.net/ajax/libs/layer/2.3/layer.js"></script>
<script>
function forgotSubmit(){
    var email = document.getElementById('email').value.trim();
    if(!email){
        layer.alert('请输入注册邮箱', {icon: 7});
        return false;
    }
    var ii = layer.load(2, {shade:[0.1,'#fff']});
	$.ajax({
		type : "POST",
		url : "forgot.php",
		data : {act:'forgot', email:email},
		dataType : 'json',
		success : function(data) {
			layer.close(ii);
			if(data.code == 0){
				layer.alert(data.msg, {icon: 1});
			}else{
				layer.alert(data.msg, {icon: 7});
			}
		},
		error : function() {
			layer.close(ii);
			layer.alert('网络错误，请稍后重试', {icon: 7});
		}
	});
	return false;
}
function resetSubmit(){
    var password = document.getElementById('password').value;
    var repassword = document.getElementById('repassword').value;
    if(!password || !repassword){
        layer.alert('请填写新密码和确认密码', {icon: 7});
        return false;
    }
    if(password.length < 6 || password.length > 32){
        layer.alert('密码长度需为6-32位', {icon: 7});
        return false;
    }
    if(password !== repassword){
        layer.alert('两次输入的密码不一致', {icon: 7});
        return false;
    }
    var ii = layer.load(2, {shade:[0.1,'#fff']});
	$.ajax({
		type : "POST",
		url : "forgot.php",
		data : {act:'reset', token:document.getElementById('token').value, password:password, repassword:repassword},
		dataType : 'json',
		success : function(data) {
			layer.close(ii);
			if(data.code == 0){
				layer.alert(data.msg, {icon: 1}, function(){
					window.location.href = './login.php';
				});
			}else{
				layer.alert(data.msg, {icon: 7});
			}
		},
		error : function() {
			layer.close(ii);
			layer.alert('网络错误，请稍后重试', {icon: 7});
		}
	});
	return false;
}
</script>
</body>
</html>
