<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST , ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace plugin\login\home\controller;
use \temmoku\controller;
use \temmoku\db;
use \temmoku\lib\user;
use \temmoku\lib\cookie;
use \temmoku\lib\sms;
class index extends controller{
	
	public function index(){
		if(C('mydb')){
			$this->err('已经登陆，无需再次登陆');
		}
		if(C(MODULE.'|login.login_is_state_login')=='1'){
			$this->err('禁止登陆');
		}
		if($_POST['step']=='post'){
			hook_listen('login_post_begin');
			if(!$_POST['username'] || !$_POST['password']){
				$this->err('用户名或者密码不可以为空');
			}
			
			if (C(MODULE.'|LOGIN.login_is_yzm')){
				$yzm=\Temmoku\Lib\YZM::get_yzm_code($_POST['yzm']);
				if($yzm['code']=='9'){
					$this->err('验证码错误');
				}
			}
			$data=(new User)->login($_POST['username'],$_POST['password']);
			if('0'===$data['code']){
				if($data['UserDB']['is_login']=='0'){
					$this->err('此账号已经限制登陆，如需解封请联系客服');
				}
				if($data['UserDB']['not_login_star_time'] && $data['UserDB']['not_login_end_time'] && $data['UserDB']['not_login_star_time'] < NOWTIME && $data['UserDB']['not_login_end_time'] > NOWTIME){
					$this->err('此账号已经限制登陆，限制时间至'.date('Y年m月d日H时i分s秒止'));
				}elseif($data['UserDB']['not_login_star_time'] && $data['UserDB']['not_login_star_time'] < NOWTIME){
					$this->err('此账号已经限制登陆，限制时间：无限期，如需解封请联系客服');
				}elseif($data['UserDB']['not_login_end_time'] &&  $data['UserDB']['not_login_end_time'] > NOWTIME){
					$this->err('此账号已经限制登陆，限制时间至'.date('Y年m月d日H时i分s秒止'));
				}

				$ORDINARY_MEMBER=encode($data['UserDB']['uid'].' '.$data['UserDB']['password'].' '.C('ONLINEIP'));
				$cookie_day=intval(C(MODULE.'|LOGIN.login_save_cookie_time'));
				if(!$cookie_day){
					$cookie_day='1';
				}
				Cookie::set('ORDINARY_MEMBER',$ORDINARY_MEMBER,$cookie_day,C('cookie_domain'));
				$data['comment_yzm']=$group['setting']['comment_yzm'];
				unset($data['UserDB']);
			}else{
				$this->err($data['text']);
			}

			$fromurl=Cookie::get('fromurl');
			if(!$fromurl){
				$fromurl=WEBURL;
			}
			Cookie::del('fromurl');
			hook_listen('login_post_end');
			$this->Success('登陆成功',$fromurl);
		}
		
		if($_GET['fromurl']){
			Cookie::set('fromurl',$_GET['fromurl']);
		}elseif(defined('FromUrl')){
			Cookie::set('fromurl',FromUrl);
		}
		
		//title标签
    	$TITLE='用户登录_'.C('WEBNAME');
    	//关键字标签
    	$KEYWORDS=C('WEB_SEO_KEYWORDS');
    	//描述标签
    	$DESCRIPTION=C('WEB_SEO_DESCRIPTION');
    	$this->assign('WEBNAME',$TITLE);
    	$this->assign('KEYWORDS',$KEYWORDS);
    	$this->assign('DESCRIPTION',$DESCRIPTION);
		if(DEVICE != 'pc'){
			$this->assign('webname','用户登录');
		}
		$this->display(tpl('index'));
	}
	
	public function small_login(){
		$_GET['tpl'] ? $tpl=$_GET['tpl'] : $tpl='default';
		$this->display(tpl('small_login/'.$tpl));
	}
	
	public function reg(){
		if(C(MODULE.'|login.reg_is_open')){
			$this->err(C(MODULE.'|login.reg_close_why'));
		}
		if(C('mydb')){
			$this->err('已经登陆，不允许注册');
		}
		if(C(MODULE.'|login.reg_interval_time')){
			$second=60*intval(C(MODULE.'|login.reg_interval_time'));
			$hour_ago=NOWTIME-$second;
			$is_hour_ago=db::select('*')->from(jab.'user')->where("regip LIKE '".onlineip."' AND regtime >'".$hour_ago."'")->orderByDESC(['regtime'])->row();
			if($is_hour_ago){
				$second=$second/60/60;
				$this->err('你在'.$second.'小时前已经注册过');
			}
		}
		if($_POST['step']==='post'){
			hook_listen('login_reg_begin');
			$_POST['username']=trim($_POST['username']);
			$test_username=(new user)->GET_User_Name($_POST['username']);
			if($test_username['code']==0){
				$this->err('用户名已经存在');
			}
			//验证码
			if(C(MODULE.'|login.reg_is_yzm')){
				$yzm=\Temmoku\Lib\YZM::get_yzm_code($_POST['yzm']);
				if($yzm['code']==='9'){
					$this->err('验证码错误');
				}
			}
			if(!$_POST['username']){
				$this->err('用户名必须填写');
			}
			//判断限制名称
			if($not_use_username=C(MODULE.'|login.not_use_username')){
				$_not_use_username=explode(' ',$not_use_username);
				foreach($_not_use_username AS $value){
					$pattern ='/'.$value.'/is';
					preg_match($pattern, $_POST['username'], $matches);
					if($matches){
						$this->err('用户名限制使用，请更换一个');
					}
				}
			}
			
			if(!$_POST['password']){
				$this->err('密码必须填写');
			}elseif($_POST['password'] != $_POST['password1']){
				$this->err('重复密码不对');
			}
			//email 注册码
			$state=0;
			if (C(MODULE.'|login.reg_is_code')==1){
				if(!$_POST['code']){
					$this->err('email验证码不可为空');
				}
				$code=Cookie::get('REG_CODE');
				if(!$code){
					$this->err('不存在email验证码原始值');
				}
				$code=decode($code);
				list($email,$code,$onlineip,$codetime)=explode(' ',$code);
				if($codetime < time()-3600){
					$this->err('验证码已经超时');
				}
				if($email != $_POST['email'] || $code!=$_POST['code']){
					$this->err('email验证失败，请重新发起注册');
				}
				$state=1;
				Cookie::del('REG_CODE');
			}elseif(C(MODULE.'|login.reg_is_code')==2){//手机注册码
				if(!$_POST['code']){
					$this->err('手机验证码不可为空');
				}
				$code=Cookie::get('mobile_code');
				$decode=decode($code,C('ONLINEIP'));
				list($mobile,$code,$time)=explode(" ",$decode);
				
				if($mobile != $_POST['mobile'] || $code != $_POST['code']){
					$this->err('手机验证失败');
				}
				
				$mobile_useful_time=C(MODULE.'|login.mobile_useful_time') ? C(MODULE.'|login.mobile_useful_time') : 5;
				$mobile_useful_time=$mobile_useful_time*60;
				$time=$mobile_useful_time+$time;
				if($time > NOWTIME){
					$this->err('手机验证码已经超时');
				}
				$state=1;
			}else{
				$state=C(MODULE.'|login.reg_user_state');
			}
			if(is_email($_POST['email'])==false){
				$this->err('Email地址不正确');
			}
			if(is_phone($_POST['mobile'])==false){
				$this->err('您的手机号不正确，或者不支持的号段');
			}
			$rand=_rand(4);
			C(MODULE.'|login.reg_groupid') ? $groupid=C(MODULE.'|login.reg_groupid') :$groupid='2';
			$arr=[
				'username'=>$_POST['username'],
				'password'=>md5(md5($_POST['password']).$rand),
				'rand'=>$rand,
				'groupid'=>$groupid,
				'email'=>$_POST['email'],
				'state'=>$state,
				'mobile'=>$_POST['mobile'],
				'regtime'=>NOWTIME,
				'regip'=>onlineip,
				'thumb'=>WEBURL."/public/global/images/default.png"
			];
			$uid=db::insert(jab.'user')->cols($arr)->query();
			$qq_cookie=decode(Cookie::get('qq_userid'));
			list($access_token,$openid)=explode(' ',$qq_cookie);
			if($openid){
				db::update(jab.'user')->cols(['qq_openid'=>$openid])->where("uid='$uid'")->query();
				Cookie::del('qq_user_name');
				Cookie::del('qq_user_pic');
				Cookie::del('qq_userid');
				$this->Success('账号绑定成功，请登陆','/login'.C('html'));
			}
			hook_listen('login_reg_end');
			$this->Success('注册成功','/login'.C('html'));
		}
		
		//title标签
    	$TITLE='用户注册_'.C('WEBNAME');
    	//关键字标签
    	$KEYWORDS=C('WEB_SEO_KEYWORDS');
    	//描述标签
		$this->assign('WEBNAME',$TITLE);
    	$this->assign('KEYWORDS',$KEYWORDS);
    	$this->assign('DESCRIPTION',$DESCRIPTION);
    	if(Cookie::get('qq_user_name')){
    		$this->assign('username',Cookie::get('qq_user_name'));
    	}
		if(DEVICE != 'pc'){
			$this->assign('webname','用户注册');
		}
		$this->display(tpl('reg'));
	}
	
	public function reg_email_code(){
		if(C('mydb')){
			$this->err('已经登陆，禁止操作');
		}
		//判断如果禁止重复
		if(C(MODULE.'|login.reg_is_email_repeat')){
			$test=db::select('*')->from(jab.'user')->where("email Like '$_POST[email]' ")->row();
			if($test){
				echo json_encode(['code'=>'31','text'=>'系统已经存在此Email地址，请更换一个']);
				exit;
			}
		}
		if(is_email($_POST['email'])==false){
			echo json_encode(['code'=>'32','text'=>'Email地址不正确']);
			exit;
		}
		$title="您在".C('WEBNAME')."注册时所需的Email验证码";
		$rand=rand(100000,999999);
		$code=encode($_POST['email'].' '.$rand.' '.onlineip." ".NOWTIME);
		Cookie::set('REG_CODE',$code,'0.04');
		$content="Email验证码为:".$rand.".有效期为1小时";
		$SMS=(new Sms)->smtp($_POST['email'],$title,$content);
		if($SMS != true){
			$text=ob_get_clean();
			echo json_encode(['code'=>'33','text'=>'发信失败，请联系客服。错误信息：'.$text]);
			exit;
		}
		echo json_encode(['code'=>'0','text'=>'ok']);
	}
	
	public function reg_mobile_code(){
		if(C('mydb')){
			$this->err('已经登陆，禁止操作');
		}
		//验证码

		$yzm=\temmoku\lib\yzm::get_yzm_code($_POST['yzm']);
		if($yzm['code']==='9'){
			$array=['code'=>'9','text'=>'验证码错误'];
			echo json_encode($array);
			exit;
		}

		//判断如果禁止重复
		if(C(MODULE.'|login.reg_is_mobile_repeat')){
			$test=db::select('*')->from(jab.'user')->where("mobile Like '$_POST[mobile]'")->row();
			if($test){
				echo json_encode(['code'=>'1','text'=>'手机号码已经在系统中存在，请更换一个']);
				exit;
			}
		}
		
		$timer=db::select('*')->from(jab.'plugin_sms_put')->where("mobile='$_POST[mobile]' AND code='100'")->orderByDESC(['id'])->row();
		
		$_put_timer=C(MODULE.'|LOGIN.mobile_put_time') ? C(MODULE.'|LOGIN.mobile_put_time') : 60;
		$put_timer=intval($timer['posttime'])+intval($_put_timer);
		if($timer &&  $put_timer > NOWTIME){
			echo json_encode(['code'=>'103','text'=>'该手机号在'.$_put_timer.'秒内不允许重复发送']);
			exit;
		}
		
		$mobile_yzm_num=!C(MODULE.'|login.mobile_yzm_num') || C(MODULE.'|login.mobile_yzm_num') >'6' ? '4' :C(MODULE.'|login.mobile_yzm_num');
		$yzm='';
		for($i=0;$i<$mobile_yzm_num;$i++){
			$yzm .=rand(0,9);
		}
		
		$short=\temmoku\lib\sms::short($_POST['mobile'],$yzm,'100');
		if($short['code']=='0'){
			/*
			 * 这个地方不适用cook
			 * sql及cookie双层保证，防止短信轰炸
			 */
			$array=['mobile'=>$_POST['mobile'],'text'=>$yzm,'posttime'=>NOWTIME,'code'=>'100'];
			db::insert(jab.'plugin_sms_put')->cols($array)->query();
			$encode=encode($_POST['mobile'].' '.$yzm.' '.NOWTIME,C('ONLINEIP'));
			Cookie::set('mobile_code',$encode);
		}
		$data['code']=$short['code'];
		$data['text']=$short['text'];
    	echo json_encode($data);
	}
	
	
	public function forgot(){
		if(C('mydb')){
			$this->err('已经登陆，禁止操作');
		}
		if($_POST['step']=='post'){
			if(C(MODULE.'|login.recaption_method') !='0'){
				$this->err('系统禁止邮箱方法取回密码');
			}
			if (C(MODULE.'|LOGIN.forgot_is_yzm')){
				$yzm=\Temmoku\Lib\YZM::get_yzm_code($_POST['yzm']);
				if($yzm['code']==='9'){
					$this->err('验证码错误');
				}
			}
			
			if(!$_POST['username']){
				$this->err('必须输入用户名');
			}
			if (C(MODULE.'|LOGIN.forgot_is_email')){
				if(!$_POST['email']){
					$this->err('必须输入email');
				}
			}
			$data=(new User)->GET_User_Name($_POST['username']);
			if($data['code']){
				$this->err('不存在的用户');
			}
			if(!$data['data']['email']){
				$this->err('没有设置email，请联系客服');
			}
			if (C(MODULE.'|LOGIN.forgot_is_email')){
				if($_POST['email'] != $data['data']['email']){
					$this->err('输入的email和当前用户不匹配');
				}
			}
			$title=$_POST['username']."用户在".C('WEBNAME')."找回密码的邮件";
			$rand=rand(1000000,9999999);
			$password='temmoku'.$rand;
		    $code=encode($data['data']['uid'].' '.$data['data']['email'].' '.$password);
			$content="你在“".C('webname')."”使用密码找回功能 ：账号： “".$data['data']['username']."” 新密码：“".$password."”,请点击此以下网址,激活新密码。<br><br><A HREF='".WEBURL."/login/index/forgot/code/".$code.C('HTML')."' target='_blank'>".WEBURL."/login/index/forgot/code/".$code.C('HTML')."</A>";
			$SMS=(new Sms)->smtp($data['data']['email'],$title,$content);
			if(!$SMS){
				$text=ob_get_clean();
				$this->err('发信失败，请联系客服。错误信息：'.$text);
			}
			$this->Success('密码验证已经发送到你的email，请注意查收');
		}elseif($_GET['code']){
			$code= decode($_GET['code']);
			if(json_encode($code)){
				list($uid,$email,$password,$state)=explode(' ',$code);
				if($uid && $email){
					$user=db::select('*')->from(jab."user")->where("uid= '$uid' AND email LIKE '$email'")->row();
					if($user){
						$array['password']=md5(md5($password).$user['rand']);
						if($state){
							$array['state']='1';
						}
						db::update(jab."user")->cols($array)->where("uid= '$uid'")->row();
						$this->Success('密码修改成功',WEBURL);
					}else{
						$this->err('激活码不正确，请不要随意改动激活码');
					}
				}else{
					$this->err('激活码不正确，请不要随意改动激活码');
				}
			}else{
				$this->err('激活码不正确，请不要随意改动激活码');
			}
		}elseif($_POST['step']=='password'){
			$mobile_code=cookie::get('mobile_code');
			$code= decode($mobile_code,C('ONLINEIP'));
			list($username,$mobile,$code,$time)=explode(' ',$code);
			if($_POST['method']){
				if(!$code || !$time){
					$this->err('验证失败');
				}
				if($_POST['password'] != $_POST['password1']){
					$this->err('重复密码不正确');
				}
				$user=db::select('*')->from(jab."user")->where("username= '$username'")->row();
				
				db::update(jab."user")->cols(['password'=>md5(md5($_POST['password']).$user['rand'])])->where("uid = '$user[uid]'")->row();
				$this->Success('密码修改成功',WEBURL);
			}
			if($username != $_POST['username'] || $code !=$_POST['code'] || $mobile != $_POST['mobile']){
				$this->err('验证失败');
			}
			
			$this->display(tpl('password'));
			exit;
		}
		
		//title标签
    	$TITLE='用户密码找回_'.C('WEBNAME');
    	//关键字标签
    	$KEYWORDS=C('WEB_SEO_KEYWORDS');
    	//描述标签
		$this->assign('WEBNAME',$TITLE);
    	$this->assign('KEYWORDS',$KEYWORDS);
    	$this->assign('DESCRIPTION',$DESCRIPTION);
		if(DEVICE != 'pc'){
			$this->assign('webname','用户密码找回');
		}
		$this->display(tpl('forgot'));
	}
	
	
	
	
	public function forgot_mobile_code(){
		if(C('mydb')){
			$this->err('已经登陆，禁止操作');
		}
		//验证码
		if(C(MODULE.'|login.recaption_method') !='1'){
			$this->err('系统禁止使用此方法取回密码');
		}
		
		$yzm=\Temmoku\Lib\YZM::get_yzm_code($_POST['yzm']);
		if($yzm['code']==='9'){
			$array=['code'=>'9','text'=>'验证码错误'];
			echo json_encode($array);
			exit;
		}


		$test=db::select('*')->from(jab.'user')->where("username='$_POST[username]'")->row();
		if(!$test){
			echo json_encode(['code'=>'20','text'=>'用户名不存在']);
			exit;
		}
		if($test['mobile'] != $_POST['mobile']){
			echo json_encode(['code'=>'1','text'=>'手机号码不相同']);
			exit;
		}
		
		$timer=db::select('*')->from(jab.'plugin_sms_put')->where("mobile='$_POST[mobile]' AND code='101'")->orderByDESC(['id'])->row();
		
		$_put_timer=C(MODULE.'|LOGIN.mobile_put_time') ? C(MODULE.'|LOGIN.mobile_put_time') : 60;
		$put_timer=intval($timer['posttime'])+intval($_put_timer);
		if($timer &&  $put_timer > NOWTIME){
			echo json_encode(['code'=>'103','text'=>'该手机号在'.$_put_timer.'秒内不允许重复发送']);
			exit;
		}
		
		$mobile_yzm_num=!C(MODULE.'|login.mobile_yzm_num') || C(MODULE.'|login.mobile_yzm_num') >'6' ? '4' :C(MODULE.'|login.mobile_yzm_num');
		$yzm='';
		for($i=0;$i<$mobile_yzm_num;$i++){
			$yzm .=rand(0,9);
		}
		
		$short=\temmoku\lib\sms::short($_POST['mobile'],$yzm,'101');
		if($short['code'] !='0'){
			/*
			 * 这个地方不适用cook
			 * sql及cookie双层保证，防止短信轰炸
			 */
			$array=['mobile'=>$_POST['mobile'],'text'=>$yzm,'posttime'=>NOWTIME,'code'=>'101'];
			db::insert(jab.'plugin_sms_put')->cols($array)->query();
			$encode=encode($_POST['username']." ".$_POST['mobile'].' '.$yzm.' '.NOWTIME,C('ONLINEIP'));
			Cookie::set('mobile_code',$encode);
		}
		$data['code']=$short['code'];
		$data['text']=$short['text'];
    	echo json_encode($data);
	}
	public function login_out(){
		hook_listen('login_out');
		Cookie::del('ORDINARY_MEMBER');
		$this->success('退出成功');
	}
	
	public function vendor(){
		if(!$_GET['name'] ){
			$this->err('缺少参数');
		}
		$son_controller=$_GET['login_c'] ? strtolower($_GET['login_c']) :'index';
		$son_method=$_GET['login_m'] ? strtolower($_GET['login_m']) :'index';
		$_GET['name']=strtolower($_GET['name']);
		$file= APP_PATH."plugin/".MODULE."/vendor/".$_GET['name']."/home/".$son_controller.".php";
	    if(!is_file($file)){
	    		$this->err('不存在的控制器文件<br>'.$file);
	    }
	    @include_once $file;
	    define('home_login_url',WEBURL."/".MODULE.'/index/vendor/name/'.$_GET['name']."/");
		$Modular_Class= "plugin\\".MODULE."\\vendor\\".$_GET['name']."\\home\\".$son_controller;
	    if (class_exists($Modular_Class)) {
		    //加载类
		    $Class=new $Modular_Class(C(MODULE.'|more_login_list.'.$_GET['name']));
		    //加载方法
		    Load_Method($Class,$son_method,$Modular_Class);
		}else{
			E($Modular_Class.'控制器不存在');
		}
	}
}
?>