<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
/**
 */
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class PublicController extends AdminbaseController {

    function _initialize() {
        C(S('sp_dynamic_config'));//加载动态配置
    }
    
    //后台登陆界面
    public function login() {
    	 
    	if(isset($_SESSION['ADMIN_ID'])){//已经登录
    		$this->success(L('LOGIN_SUCCESS'),U("Index/index"));
    	}else{
    		
    		
    		 
    	    $site_admin_url_password =C("SP_SITE_ADMIN_URL_PASSWORD");
    	    $upw=session("__SP_UPW__");
    		if(!empty($site_admin_url_password) && $upw!=$site_admin_url_password){
    			redirect(__ROOT__."/");
    		}else{
    		    session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__",true);
    			$this->display(":login");
    		}
    	}
    }
    
    public function logout(){
    	session('ADMIN_ID',null); 
    	redirect(__ROOT__."/admin");
    }
    
    public function dologin(){
        $login_page_showed_success=session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__");
        if(!$login_page_showed_success){
            $this->error('login error!');
        }
    	$name = I("post.username");
    	if(empty($name)){
    		$this->error(L('USERNAME_OR_EMAIL_EMPTY'));
    	}
    	$pass = I("post.password");
    	if(empty($pass)){
    		$this->error(L('PASSWORD_REQUIRED'));
    	}
    	$verrify = I("post.verify");
    	if(empty($verrify)){
    		$this->error(L('CAPTCHA_REQUIRED'));
    	}
    	//验证码
    	if(!sp_check_verify_code()){
    		$this->error(L('CAPTCHA_NOT_RIGHT'));
    	}else{
    		$user = D("Common/Users");
    		if(strpos($name,"@")>0){//邮箱登陆
    			$where['user_email']=$name;
    		}else{
    			$where['user_login']=$name;
    		}
    		
    		$result = $user->where($where)->find();
            $pssword = '###' . md5($pass);
    		if(!empty($result) && $result['user_type']==1){
                $allow_max_error_times = 5;// 允许的最大连续错误次数
                $lock_time = 2;// 达到最大连续错误次数后的锁定时长，单位：小时
                // 检测是否连续5次输错密码，在锁定时间范围内 Begin
                if ($allow_max_error_times <= $result['password_error_times']) {
                    if (($result['last_error_time'] + $lock_time * 3600) >= time()) {
                        $this->error('连续5次输入错误密码，账号已被锁定');
                    } else {
                        $result = [
                            'id' => $result['id'],
                            'password_error_times' => 0,
                            'last_error_time' => 0,
                        ];
                        $user->save($result);
                    }
                }
                // 检测是否连续5次输错密码，在锁定时间范围内 End
    			// if(sp_compare_password($pass,$result['user_pass'])){
    			if($pssword == $result['user_pass']){
    				$role_user_model=M("RoleUser");
    				
    				$role_user_join = C('DB_PREFIX').'role as b on a.role_id =b.id';
    				
    				$groups=$role_user_model->alias("a")->join($role_user_join)->where(array("user_id"=>$result["id"],"status"=>1))->getField("role_id",true);
    				
    				if( $result["id"]!=1 && ( empty($groups) || empty($result['user_status']) ) ){
    					$this->error(L('USE_DISABLED'));
    				}
    				
    				 
    				$roles = M('role_user')->where("user_id= ".$result['id'])->field('role_id')->select();
    				if($roles){
    					foreach($roles as $value){
    						$role .=",".$value['role_id'];
    					}
    				}else{
    					$role =1;  //超级管理员
    				}
    				 
    				//登入成功页面跳转
    				$_SESSION["ADMIN_ID"]=$result["id"];
    				$_SESSION['name']=$result["user_login"];
    				$_SESSION['role_id'] = ltrim($role,',');
    				 
    				$result['last_login_ip']=get_client_ip(0,true);
    				$result['last_login_time']=date("Y-m-d H:i:s");
    				$user->save($result);
                    adminlog($result["id"],L('ADMINLOG_LOGIN'));
    				setcookie("admin_username",$name,time()+30*24*3600,"/");
    				
    				//执行自动检测程序
    				$cxauto = new \Common\Lib\Autocheck();
    				$cxauto->index();

                    //判断是否赠积分
                    gpoint($result["id"],1);

                    // 登录成功，重置登录错误次数及时间 Begin
                    $result = [
                        'id' => $result['id'],
                        'password_error_times' => 0,
                        'last_error_time' => 0,
                    ];
                    $user->save($result);
                    // 登录成功，重置登录错误次数及时间 End
    				
    				$this->success(L('LOGIN_SUCCESS'),U("Index/index"));
    			}else{
                    // 密码错误，增加错误次数、更新最后错误时间 Begin
                    $result = [
                        'id' => $result['id'],
                        'password_error_times' => $result['password_error_times'] + 1,
                        'last_error_time' => time(),
                    ];
                    $user->save($result);
                    // 密码错误，增加错误次数、更新最后错误时间 End
    				$this->error(L('PASSWORD_NOT_RIGHT') . '已连续' . $result['password_error_times'] . '次输入错误，达到' . $allow_max_error_times . '次将被锁定' . $lock_time . '小时');
    			}
    		}else{
    			$this->error(L('USERNAME_NOT_EXIST'));
    		}
    	}
    }

    /**
     * 手机端登录页面
     * Author: Lyn
     * Date: 2023/6/9 13:48
     */
    public function mobileLogin()
    {
        $param = I('param.');
        if(isset($_SESSION['ADMIN_ID'])){//已经登录
            $this->success(L('LOGIN_SUCCESS'),U("portal/webChat/indexMobile"));
        }else{
            $site_admin_url_password =C("SP_SITE_ADMIN_URL_PASSWORD");
            $upw=session("__SP_UPW__");
            if(!empty($site_admin_url_password) && $upw!=$site_admin_url_password){
                redirect(__ROOT__."/");
            }else{
                session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__",true);
                $this->assign('param', $param);
                $this->display(":login_mobile");

            }
        }
    }

    /**
     * 手机端登录入口
     * Author: Lyn
     * Date: 2023/6/9 11:45
     */
    public function odMobileLogin()
    {
        $login_page_showed_success=session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__");
        if(!$login_page_showed_success){
            $data['msg'] = 'login error!';
            $data['success'] = false;
        }
        $name = I("post.username");
        if(empty($name)){
            $data['msg'] = L('USERNAME_OR_EMAIL_EMPTY');
            $data['success'] = false;
        }
        $pass = I("post.password");
        if(empty($pass)){
            $data['msg'] = L('PASSWORD_REQUIRED');
            $data['success'] = false;
        }
        $chat_id = I('post.chat_id');
        $verrify = I("post.verify");
        if(empty($verrify)){
            $data['msg'] = L('CAPTCHA_REQUIRED');
            $data['success'] = false;
        }
        //验证码
        if(!sp_check_verify_code()){
            $data['msg'] = L('CAPTCHA_NOT_RIGHT');
            $data['success'] = false;
        }else{
            $user = D("Common/Users");
            if(strpos($name,"@")>0){//邮箱登陆
                $where['user_email']=$name;
            }else{
                $where['user_login']=$name;
            }

            $result = $user->where($where)->find();
            $pssword = '###' . md5($pass);
            if(!empty($result) && $result['user_type']==1){
                $allow_max_error_times = 5;// 允许的最大连续错误次数
                $lock_time = 2;// 达到最大连续错误次数后的锁定时长，单位：小时
                // 检测是否连续5次输错密码，在锁定时间范围内 Begin
                if ($allow_max_error_times <= $result['password_error_times']) {
                    if (($result['last_error_time'] + $lock_time * 3600) >= time()) {
                        $data['msg'] = '连续5次输入错误密码，账号已被锁定';
                        $data['success'] = false;
                    } else {
                        $result = [
                            'id' => $result['id'],
                            'password_error_times' => 0,
                            'last_error_time' => 0,
                        ];
                        $user->save($result);
                    }
                }
                // 检测是否连续5次输错密码，在锁定时间范围内 End
                // if(sp_compare_password($pass,$result['user_pass'])){
                if($pssword == $result['user_pass']){
                    $role_user_model=M("RoleUser");
                    $role_user_join = C('DB_PREFIX').'role as b on a.role_id =b.id';
                    $groups=$role_user_model->alias("a")->join($role_user_join)->where(array("user_id"=>$result["id"],"status"=>1))->getField("role_id",true);
                    if( $result["id"]!=1 && ( empty($groups) || empty($result['user_status']) ) ){
                        $data['msg'] = L('USE_DISABLED');
                        $data['success'] = false;
                    }
                    $roles = M('role_user')->where("user_id= ".$result['id'])->field('role_id')->select();
                    if($roles){
                        foreach($roles as $value){
                            $role .=",".$value['role_id'];
                        }
                    }else{
                        $role =1;  //超级管理员
                    }

                    //登入成功页面跳转
                    $_SESSION["ADMIN_ID"]=$result["id"];
                    $_SESSION['name']=$result["user_login"];
                    $_SESSION['role_id'] = ltrim($role,',');

                    $result['last_login_ip']=get_client_ip(0,true);
                    $result['last_login_time']=date("Y-m-d H:i:s");
                    $user->save($result);
                    adminlog($result["id"],L('ADMINLOG_LOGIN'));
                    setcookie("admin_username",$name,time()+30*24*3600,"/");

                    //执行自动检测程序
                    $cxauto = new \Common\Lib\Autocheck();
                    $cxauto->index();

                    //判断是否赠积分
                    gpoint($result["id"],1);

                    // 登录成功，重置登录错误次数及时间 Begin
                    $result = [
                        'id' => $result['id'],
                        'password_error_times' => 0,
                        'last_error_time' => 0,
                    ];
                    $user->save($result);
                    // 登录成功，重置登录错误次数及时间 End
                    $data['msg'] = L('LOGIN_SUCCESS');
                    $data['success'] = true;
                    $data['status'] = true;
                    $data['url'] = U("portal/webChat/indexMobile", array('chat_id' => $chat_id));
                }else{
                    // 密码错误，增加错误次数、更新最后错误时间 Begin
                    $result = [
                        'id' => $result['id'],
                        'password_error_times' => $result['password_error_times'] + 1,
                        'last_error_time' => time(),
                    ];
                    $user->save($result);
                    // 密码错误，增加错误次数、更新最后错误时间 End
                    $data['msg'] = L('PASSWORD_NOT_RIGHT') . '已连续' . $result['password_error_times'] . '次输入错误，达到' . $allow_max_error_times . '次将被锁定' . $lock_time . '小时';
                    $data['success'] = false;
                }
            }else{
                $data['msg'] = L('USERNAME_NOT_EXIST');
                $data['success'] = false;
            }
        }
        $this->ajaxReturn($data);
    }

}