<?php
defined('PP_PATH') or exit;
class public_control extends control {
	public $_uid;
	public $_cfg = array();	// 全站参数

	public function __construct(){
		$this->_uid = session::get('_uid');

		$this->_cfg = $this->runtime->xget();
		$this->_cfg['FORM_HASH'] = form_hash();
		$this->assign('pp', $this->_cfg);

		if( empty($this->_cfg['user']['open_user_model']) ){	//关闭用户模块
			$this->message(0, '用户中心暂时关闭！',$this->_cfg['weburl']);
			//E(1, '用户中心暂时关闭！');
		}
		$_ENV['_hometheme'] 		= &$this->_cfg['theme'];
		
	}
	public function login(){
		$this->_cfg['titles'] = '会员登陆';
		if( $this->_uid ){
			$this->message(0, '你已经登录！',$this->_cfg['weburl'].'member/');
		}
		if( empty($_POST) ){
			$this->assign('jumpurl', $_SERVER['HTTP_REFERER']);
			$this->display('login.htm');
		}elseif(form_submit()) {
			$user = &$this->user;
			$username 	= strip_tags(R('username', 'P'));
			$password 	= R('password', 'P');
			$code 		= R('code', 'P');
			
			if( empty($username) ){
				E(1, '用户名不能为空！');
			}elseif( empty($password) ){
				E(1, '密码不能为空！');
			}elseif( empty($code) ){
				E(1, '验证码不能为空！');
			}elseif( md5($code) != session::get('logincode') ){
				E(1, '验证码不正确！');
			}

			if($message = $user->check_username($username)) {
				E(1, $message);
			}elseif($message = $user->check_password($password)){
				E(1, $message);
			}

			// 防IP暴力破解
			$ip = &$_ENV['_ip'];
			if($user->anti_ip_brute($ip)) {
				E(1, '请15分钟之后再试！');
			}

			$data = $user->get_user_by_username($username);
			if($data && $user->verify_password($password, $data['salt'], $data['password'])) {
				$email = $data['email'] ;
				$statusFormat = array(
					0 => "账号未通过审核或未激活，请联系客服",
					1 => '正常',
					2 => '该账号已被冻结！',
				);
				
				if( $data['status'] != 1 ){
					E(1, $statusFormat[$data['status']]);
				}
				
				//写入SESSION
				session::set('_uid', $data['uid']);

				// 更新登陆信息
				$data['lastip'] 	= $data['loginip'];
				$data['lastdate'] 	= $data['logindate'];
				$data['loginip'] 	= ip2long($ip);
				$data['logindate'] 	= $_ENV['_time'];
				$data['logins']++;
				$user->update($data);

				// 删除密码错误记录
				$this->runtime->delete('password_error_'.$ip);
				E(0, '登录成功！请稍候...');
			}else{
				// 记录密码错误次数
				$user->password_error($ip);
				E(1, '帐号或密码不正确！');
			}
		}else{
			E(1, '失败！请刷新再试！');
		}
	}
	public function register(){
		$this->_cfg['titles'] = '会员注册';
		if( $this->_uid ){
			header('Location:'.$this->_cfg['weburl'].'member');
		}
		if( empty($this->_cfg['user']['open_user_reg'])){	//关闭新会员注册
			$this->message(0, '站点已关闭注册功能！');
		}
		$up_id	= 0 ;
		$code = R($_ENV['_config']['cookie_pre'].'tcode','R');
		if(!empty($code)){
			$up_id = $code; 
		}
		if( empty($_POST) ){
			$this->display('register.htm');
		}elseif(form_submit()) {
			$user = &$this->user;
			$username 	= strip_tags(R('username', 'P'));
			$password 	= R('password', 'P');
			$repassword = R('repassword', 'P');
			$code 		= R('code', 'P');
			
			if(empty($username)){
				E(1, '用户名不能为空！');
			}elseif( empty($password) ){
				E(1, '密码不能为空！');
			}elseif( empty($repassword) ){
				E(1, '确认密码不能为空！');
			}elseif( empty($code) ){
				E(1, '验证码不能为空！');
			}elseif ( $password != $repassword ){
				E(1, '两次输入的密码不一致！');
			}elseif( md5($code) != session::get('regcode') ){
				E(1, '验证码不正确！');
			}
			
			if($message = $user->check_username($username)) {
				E(1, $message);
			}elseif($message = $user->check_password($password)){
				E(1, $message);
				
			}
			if($user->get_user_by_username($username)){
				E(1, '用户名已被注册！');
			}
			$ip = &$_ENV['_ip'];
			$time = time();
			$salt = random(16, 3, '0123456789abcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+<>,.');
			$data = array(
				'username'	=> $username,
				'password'	=> get_password($password,$salt),
				'salt'		=> $salt,
				'groupid'	=> 4,
				'regip'		=> ip2long($ip),
				'regdate'	=> $time,
				'author'	=> $username,
				'isadmin'	=> 0,
				'status'	=> 1,
				'upid'		=> $up_id,
			);
			//红包
			if($this->_cfg['user']['gift']>0 && $this->is_hongbao($this->_cfg['user']['gift_mobi_off'],$this->_cfg['user']['gift_email_off'],0,0)){
				$data['money'] = $this->_cfg['user']['gift'];
			}
			$uid = $user->create($data);

			if($uid){
				//直接登陆
				session::set('_uid', $uid);
				$data['uid'] = $uid ;
				$data['loginip'] = ip2long($ip);
				$data['logindate'] = $time ;
				$data['logins'] = 1 ;
				$user->update($data);

				if(!empty($data['money'])){
					$this->write_record($uid,$username,$data['money']);
				}
				$res_code = 0 ;
				$endStr = '';
				_setcookie('tcode', '', 1);
				E($res_code, '注册成功！'.$endStr);
			}else{
				E(1, '注册失败，请重试！');
			}
		}else{
			E(1, '失败！请刷新再试！');
		}
	}
	//发送短信验证码
	public function send_sms_code(){
		if(empty($_POST) ){
			E(1, '无效参数!');
		}else{
			$mobile = R('mobile','P');
			$username = R('username','P');
			if(!check::is_mobile($mobile)){
				E(1, '手机格式不正确！');
			}
			
			$sms_cfg = $this->kv->xget('sms_cfg');
			$code = other::rand_string(6,1);
			$content = $sms_cfg['phonecode'];
			
			$res = other::send_sms($sms_cfg,$mobile,str_replace(array("{username}","{code}"),array($username,$code),$content));
			if(!$res){
				E(1, '发送失败，请联系网站管理员！');
			}else{
				session::set('code_tmp',str_auth($code, 'ENCODE',$this->_uid,300));//5分钟
				$user = $this->user->read($this->_uid);
				$user['mobile'] 	= $mobile;
				$this->user->update($user);
			}
			$endStr = '请输入手机验证码';
			$res_code = $this->_uid ;
			E($res_code, '发送成功！'.$endStr);
		}
	}
	//短信验证码激活
    public function sms_active(){
		if(empty($_POST) ){
			E(1, '无效参数!');
		}else{
			$uid = $this->_uid;
			$code = R('code','P');
			$mobile = R('mobile','P');
			if(!check::is_mobile($mobile)){
				E(1, '手机格式不正确！');
			}
			$tmp_code = session::get('code_tmp');
			$tmp_code = str_auth($tmp_code, 'DECODE',$uid);

			if($tmp_code!=$code){
				E(1, '验证失败或已超时(5分钟)，请重新验证');
				//E(1, $tmp_code.'!='.$code);
			}
			//已通过验证处理
			$user = $this->user->read($uid);
			if(empty($user) ) {
				E(1, '用户不存在！可能已经被删除。');
			}elseif($user['mobile_staus'] == 1) {
				E(1, '您已经绑定过手机。');
			}
			$user['mobile_staus'] 	= 1;
			$user['mobile'] 		= $mobile;
			//红包
			if($this->_cfg['user']['gift']>0 && $this->is_hongbao($this->_cfg['user']['gift_mobi_off'],$this->_cfg['user']['gift_email_off'],$user['mobile_staus'],$user['email_staus'])){
				$user['money'] = $this->_cfg['user']['gift'];
				$this->write_record($uid,$user['username'],$user['money']);
			}
			$this->user->update($user);
			E(0, $user['username'].'，您好！您已通过手机认证！');
		}
    }

	//忘记密码
	public function getpassword(){
		if( $this->_uid ){
			$this->message(0, '你已经登录！',$this->_cfg['weburl'].'member/');
		}
		$this->_cfg['titles'] = '找回密码';
		if( empty($_POST) ){
			$this->assign('maybe', $this->_cfg);
			$this->display('forget.htm');
		}else{
			$username = strip_tags(R('username','P'));
			$email 	= R('email','P');
			$mobile = R('mobile','P');
			$type 	= (int)R('type','P');
			
			$user = &$this->user;
			
			if(empty($username)){
				E(1, '用户名不能为空！');
			}
			$message = $user->check_username($username);
			if($message != '') {
				E(1, $message);
			}
			$userInfo = $user->get_user_by_username($username);
			if(empty($userInfo) ){
				E(1, '用户名不存在！');
			}
			//生成一个新的随机密码
			$password = random(6,2,'0123456789');
			$userInfo['password'] = get_password($password,$userInfo['salt']);
			
			if($type>0){//手机找回
				$sms_cfg 		= $this->kv->xget('sms_cfg');
				if(empty($sms_cfg['sms_pwd_off']) || empty($sms_cfg['sms_off'])){
					E(1, '系统未开启手机找回密码功能！');
				}
				if(!check::is_mobile($mobile)){
					E(1, '手机格式不正确！');
				}
				if(!$userInfo['mobile_staus']){
					E(1, '未绑定手机！不能使用手机找回功能！');
				}
				if($userInfo['mobile'] != $mobile ){
					E(1, '绑定手机不正确！');
				}else{
					if(!$user->update($userInfo) ){
						E(1, '重置密码失败，请重试！');
					}else{
						
						$sms_content 	= $sms_cfg['sms_pwd_content'];
						$sms_content 	= str_replace('{password}', $password, $sms_content);

						$res = other::send_sms($sms_cfg,$mobile,$sms_content);
						if(!$res){
							E(1, '发送失败，请联系网站管理员！');
						}
					}
					E(0, '新密码发送成功，请查阅您的手机短信！');
					// $this->message(1, '新密码发送成功，请查阅您的手机短信！',$this->_cfg['webdir'].'member/');
				}
			}else{//邮箱找回
				$mail_cfg 		= $this->kv->xget('mail_cfg');
				if(empty($mail_cfg['moban']['email_pwd_off'])){
					E(1, '系统未开启邮件找回密码功能！');
				}
				if(!check::is_email($email) ){
					E(1, '邮箱格式不正确！');
				}
				if(!$userInfo['email_staus']){
					E(1, '未绑定邮箱！不能使用邮箱找回功能！');
				}
				if($userInfo['email'] != $email){
					E(1, '绑定邮箱不正确！');
				}else{
					if( !$user->update($userInfo) ){
						E(1, '重置密码失败，请重试！');
					}else{
						$email_content = $mail_cfg['moban']['email_pwd_content'];
						$email_content = str_replace('{password}', $password, $email_content);

						$subject = $this->_cfg['webname'].'找回密码！';
						$message = "
						<html>
						<head>
						<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />
						</head>
						<body>
						{$username}，您好！<br />
						$email_content
						</body>
						</html>";
							
						$mmiscModel = &$this->mmisc;
						$errMsg = $mmiscModel->sendmail($username,$email,$subject,$message);
						if( $errMsg ){
							E(1, '邮件发送失败，请重试！');
						}
					}
				}
				E(0, '成功，新密码已发送到你的邮箱！');
				// $this->message(1, '成功，新密码已发送到你的邮箱！',$this->_cfg['webdir'].'member/');
			}
		}
	}
	//登出
	public function logout(){
		session::delete('_uid');
		session::destory();
		exit('<html><body><script>window.location="'.$this->_cfg['webdir'].'index.php"</script></body></html>');
	}
	//绑定邮箱
	public function active(){
		$code = rawurldecode(R('code','G'));
		$uid = (int)R('uid','G');
		if(empty($code)) {
			$this->message(0,'缺少参数 code。');
		}
		
		$tmp_code = str_auth($code, 'DECODE',$_ENV['_config']['auth_key']);

		if(!$tmp_code){
			$this->message(0,'认证失败或已超时(1小时)，请重新发送认证邮件'.$code,$this->_cfg['webdir'].'member/');
		}

		$arr = explode(",",  $tmp_code);
		$uid = $arr[0];
		
		//已通过验证处理
		$user = $this->user->read($uid);
		if(empty($user) ) {
			$this->message(0,'用户不存在！可能已经被删除。',$this->_cfg['webdir']);
		}elseif($user['email_staus'] == 1) {
			$this->message(0,'您已经过邮箱认证，不需要重新认证。',$this->_cfg['webdir'].'member/');
		}
		$user['email_staus'] 	= 1;
		//红包
		if($this->_cfg['user']['gift']>0 && $this->is_hongbao($this->_cfg['user']['gift_mobi_off'],$this->_cfg['user']['gift_email_off'],$user['mobile_staus'],$user['email_staus'])){
			$user['money'] = $this->_cfg['user']['gift'];
			$this->write_record($uid,$user['username'],$user['money']);
		}
		$this->user->update($user);
		$this->message(1,$user['username'].'，恭喜！您已通过邮箱认证！',$this->_cfg['webdir'].'member/');
		
	}
	//发送邮件
    public function send_email_code(){
		if(empty($_POST) ){
			E(1, '无效参数!');
		}else{
			$uid = $this->_uid;
			$email = R('email','P');
			if(!check::is_email($email)){
				E(1, '邮箱格式不正确！');
			}
			$username = R('username','P');
			$user = $this->user->read($uid);
			if($this->user->get_user_by_email($email) && $user['email_staus'] == 1){
				E(1, '此邮箱已被注册！请更换邮箱');
			}
			if(!$this->sent_email($uid,$username,$email)){
				E(1, '邮件发送失败，请联系网站管理员！');
			}else{
				$user['email'] 	= $email;
				$this->user->update($user);
			}
			E(0, '发送成功！请到邮箱查收！');
		}
    }
	//发送激活邮件
	protected function sent_email($uid,$username,$email) {
		//发送邮件
		$mail_cfg = $this->kv->xget('mail_cfg');
		if(!$mail_cfg['moban']['email_active_off']){
			return false;
		}
		$s = $uid.','.time();
		$code = str_auth($s, 'ENCODE',$_ENV['_config']['auth_key']);
		$url = $this->_cfg['weburl'].'member/index.php?u=public-active-code-'.rawurlencode($code);
		$clickUrl = '<a target="_blank" href="'.$url.'">点击此链接进行激活</a>';

		$email_content = $mail_cfg['moban']['email_active_content'];
		$email_content = str_replace('{click}', $clickUrl, $email_content);
		$email_content = str_replace('{url}', $url, $email_content);
		
		$subject = '请认证您在'.$this->_cfg['webname'].'注册的帐号！';
		$message = "
		<html>
		<head>
		<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />
		</head>
		<body>
		{$username}，您好！<br />
		$email_content
		</body>
		</html>";
		
		$mmiscModel = &$this->mmisc;
		$errMsg = $mmiscModel->sendmail($username,$email,$subject,$message);

		if( $errMsg ){
			return false;
		}
		return true;
	}
	//写入交易记录库
	protected function write_record($uid,$username,$money){
		$record = &$this->record;
		$recordata = array(
			'uid'		=> $uid,
			'username'	=> $username,
			'money'		=> $money,
			'gold'		=> 0,
			'type'		=> 1,
			'created'	=> $_ENV['_time'],
			'status'	=> 0,
			'comment'	=> '注册红包',
		);
		$record->create($recordata);
	}
	protected function is_hongbao($mobi_off,$email_off,$mobi_status,$email_status){
		if(empty($mobi_off) && empty($email_off)){ //都没有开启
			return true;
		}
		if(!empty($mobi_off) && !empty($email_off)){ //手机、邮箱同时开启
			if(!empty($mobi_status) && !empty($email_status)){
				return true;
			}
		}
		if(!empty($mobi_off) && empty($email_off)){//仅开启了手机
			if(!empty($mobi_status)){
				return true;
			}
		}
		if(!empty($email_off) && empty($mobi_off)){//仅开启了邮箱
			if(!empty($email_status)){
				return true;
			}
		}
		return false;
	}
}
