<?php
// +----------------------------------------------------------------------
// | WANCMS游戏平台管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.wancms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 顽皮蛋 <shf_l@163.com> <http://www.wancms.com>
// +----------------------------------------------------------------------
// | 修改时间: 2015/05/26
// +----------------------------------------------------------------------

namespace Phonegame\Controller;
use Common\Controller\PhonegameController;
/**
 * 会员注册控制器
 * @author 顽皮蛋 <shf_l@163.com>
 */
class RegisterController extends PhonegameController {
	/**
     * 会员注册
     * @author 顽皮蛋 <shf_l@163.com>
     */
	function index(){
	    if(sp_is_user_login()){ //已经登录时直接跳到首页
	        redirect(__ROOT__."/");
	    }else{
	        $this->display($this->template.'/template1'.'/User'.'/register');
	    }
	}
    /**
     * 检测手机号码
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function checkTel(){
        $user_login = I('post.user_login');
        $tel = I('post.tel');
        $users_model=M("Users");
        $rules = array(
            //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
            array('user_login', 'require', '手机号不能为空！', 1 ),
            array('user_login','','手机号已经存在！',0,'unique',1), // 验证user_login字段是否唯一   
            array('tel','','手机号已经存在！',0,'unique',1), // 验证tel字段是否唯一       
        );
        //$users_model->validate($rules)->create();
        //print_r($users_model->getError());die();
        if($users_model->validate($rules)->create()===false){
            $data['state'] = "fail";
            $data['message'][0] = $users_model->getError();
            exit(json_encode($data));
        }

        //用户名需过滤的字符的正则
        $stripChar = '?<*.>\'"';
        if(preg_match('/['.$stripChar.']/is', $user_login)==1){
            $data['state'] ="fail";
            $data['message'][0] = '手机号中包含'.$stripChar.'等非法字符！';
            exit(json_encode($data));
        }
        if(strlen($user_login) < 6 || strlen($user_login) > 22){
            $data['state'] ="fail";
            $data['message'][0] = '手机号至少6位，最多22位！';
            exit(json_encode($data));
        }
        if(preg_match("/[\x7f-\xff]/", $user_login)){
            $data['state'] ="fail";
            $data['message'][0] = '手机号不能包括中文';
            exit(json_encode($data));
        }
        $banned_usernames=explode(",", sp_get_cmf_settings("banned_usernames"));
        
        if(in_array($user_login, $banned_usernames)){
            $data['state'] ="fail";
            $data['message'][0] = '此手机号禁止使用！';
            exit(json_encode($data));
        }

        $ucenter_syn=C("UCENTER_ENABLED");
        if($ucenter_syn){
           include UC_CLIENT_ROOT."client.php";
            $uc_checkusername=1;
            $uc_checkusername=uc_user_checkname($user_login);
            if($uc_checkusername<0){
                $data['state'] ="fail";
                $data['message'][0] = '此手机号已经使用！';
                exit(json_encode($data)); 
            }
        }
        $sdata['state'] = 'success';
        $sdata['message'][0] = '此手机号可以使用！';
        exit(json_encode($sdata));
    }


    /**
     * 检测用户名
     * @author 顽皮蛋 <shf_l@163.com>
     */
	public function checkName(){
        $user_login = I('post.user_login');
        $users_model=M("Users");
        $rules = array(
                //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
                array('user_login', 'require', '用户名不能为空！', 1 ),
                array('user_login','','用户名已经存在！',0,'unique',1), // 验证user_login字段是否唯一          
        );
        if($users_model->validate($rules)->create()===false){
            $data['state'] = "fail";
            $data['message'][0] = $users_model->getError();
            exit(json_encode($data));
        }
        //用户名需过滤的字符的正则
        $stripChar = '?<*.>\'"';
        if(preg_match('/['.$stripChar.']/is', $user_login)==1){
            $data['state'] ="fail";
            $data['message'][0] = '用户名中包含'.$stripChar.'等非法字符！';
            exit(json_encode($data));
        }
        if(strlen($user_login) <6 || strlen($user_login) > 22){
            $data['state'] ="fail";
            $data['message'][0] = '用户名至少6位，最多22位！';
            exit(json_encode($data));
        }
        if(preg_match("/[\x7f-\xff]/", $user_login)){
            $data['state'] ="fail";
            $data['message'][0] = '用户名不能包括中文';
            exit(json_encode($data));
        }
        $banned_usernames=explode(",", sp_get_cmf_settings("banned_usernames"));
        
        if(in_array($user_login, $banned_usernames)){
            $data['state'] ="fail";
            $data['message'][0] = '此用户名禁止使用！';
            exit(json_encode($data));
        }
        $ucenter_syn=C("UCENTER_ENABLED");
        if($ucenter_syn){
           include UC_CLIENT_ROOT."client.php";
            $uc_checkusername=1;
            $uc_checkusername=uc_user_checkname($user_login);
            if($uc_checkusername<0){
                $data['state'] ="fail";
                $data['message'][0] = '此用户名已经使用！';
                exit(json_encode($data)); 
            }
        }
        $sdata['state'] = 'success';
        $sdata['message'][0] = '此用户名可以使用！';
        exit(json_encode($sdata));
    }

    /**
     * 检测邮箱
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function checkEmail(){
        $user_email = I('post.user_email');
        $users_model=M("Users");
        $rules = array(
                //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
                array('user_email', 'require', '邮箱不能为空！', 1 ),
                array('user_email','email','邮箱格式不正确！',1), // 验证email字段格式是否正确
                array('user_email','','邮箱已经存在！',0,'unique',1), // 验证user_login字段是否唯一          
        );
        if($users_model->validate($rules)->create()===false){
            $data['state'] = "fail";
            $data['message'][0] = $users_model->getError();
            exit(json_encode($data));
        }
        $sdata['state'] = 'success';
        $sdata['message'][0] = '此邮箱可以使用！';
        exit(json_encode($sdata));
    }
    /**
     * 注册提交
     * @author 顽皮蛋 <shf_l@163.com>
     */
	function doregister(){
    	$users_model=M("Users");
    	$rules = array(
    			//array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
    			array('checkboxname', 'require', '您未同意服务条款！', 1 ),
    			array('user_login', 'require', '账号不能为空！', 1 ),
    			array('user_email', 'require', '邮箱不能为空！', 1 ),
    			array('password','require','密码不能为空！',1),
    			array('repassword', 'require', '重复密码不能为空！', 1 ),
    			array('repassword','password','确认密码不正确',0,'confirm'),
    			array('user_email','email','邮箱格式不正确！',1), // 验证email字段格式是否正确
                array('user_email','','邮箱已经存在！',0,'unique',1), // 验证tel字段是否唯一  
    			 
    	);
    	if($users_model->validate($rules)->create()===false){
    		$this->error($users_model->getError());
    	}
    	extract($_POST);
        /*判断短信验证码*/
        if($code){
        $time = time()-2*60;
        $flag = M('smslog')->where('tel ='.$user_login.' and time >='.$time)->find();
        if($code != $flag['code']){
         $this->error('短信验证码错误或者已经过期！');      
        }  
        }
    	//用户名需过滤的字符的正则
    	$stripChar = '?<*.>\'"';
    	if(preg_match('/['.$stripChar.']/is', $user_login)==1){
    		$this->error('用户名中包含'.$stripChar.'等非法字符！');
    	}
    	$banned_usernames=explode(",", sp_get_cmf_settings("banned_usernames"));
    	if(in_array($user_login, $banned_usernames)){
    		$this->error("此用户名禁止使用！");
    	}
    	if(strlen($password) < 6 || strlen($password) > 20){
    		$this->error("密码长度至少6位，最多20位！");
    	}
    	$where['user_login']=$user_login;
    	$where['user_email']=$user_email;
        $where['tel']= $user_login;
    	$where['_logic'] = 'OR';
    	$ucenter_syn=C("UCENTER_ENABLED");
    	$uc_checkemail=1;
    	$uc_checkusername=1;
    	if($ucenter_syn){
    		include UC_CLIENT_ROOT."client.php";
    		$uc_checkemail=uc_user_checkemail($user_email);
    		$uc_checkusername=uc_user_checkname($user_login);
    	}
    	$users_model=M("Users");
    	$result = $users_model->where($where)->count();
    	if($result || $uc_checkemail<0 || $uc_checkusername<0){
    		$this->error("用户名、手机号或者该邮箱已经存在！");
    	}else{
    		$uc_register=true;
    		if($ucenter_syn){
    			$uc_uid=uc_user_register($user_login,$password,$user_email);
    			//exit($uc_uid);
    			if($uc_uid<0){
    				$uc_register=false;
    			}
    		}
    		if($uc_register){
    			$need_email_active=C("SP_MEMBER_EMAIL_ACTIVE");
                if($need_email_active){
                    if(!empty($code)){$user_status=1;}else{$user_status=2;}
                }else{
                    $user_status=1;
                }
    			$udata=array(
    					'user_login' => $user_login,
    					'user_email' => $user_email,
    					'user_nicename' =>$user_login,
    					'user_pass' => sp_password($password),
    					'last_login_ip' => get_client_ip(),
    					'create_time' => time(),
    					'last_login_time' => date("Y-m-d H:i:s"),
                        'register_ip' => get_client_ip(),
    					'user_status' => $need_email_active?2:1,
    					"user_type"=>2,
                        'realname' => $realname,
                        "id_card"=>$id_card,
                        "is_fcm"=>0
    			);
                if($code)$udata['tel'] = $user_login;
    			$rst = $users_model->add($udata);
    			if($rst){
                     M('users_other')->add(array('uid'=>$rst));
    				//登入成功页面跳转
    				$udata['id']=$rst;
    				$_SESSION['user']=$udata;
    				//发送激活邮件
    				if($need_email_active&&empty($code)){
    					$this->_send_to_active();
    					unset($_SESSION['user']);
    					$this->success("注册成功，激活后才能使用！",U("/login/index"));
    				}else {
                        $domain  = explode('.',$_SERVER['HTTP_HOST']);
                        include "data/uc_conf/".$domain['0']."/config.inc.php";
                        setcookie('thinkcmf_auth', sp_authcode($udata['id']."\t".$user_login, 'ENCODE',UC_KEY), 0, C ( 'COOKIE_PATH' ), C ( 'COOKIE_DOMAIN' ), 0, false );
                        $this->success("注册成功！",__ROOT__."/");
    				}
    					
    			}else{
    				$this->error("注册失败！",U("/register/index"));
    			}
    	
    		}else{
    			$this->error("注册失败！",U("/register/index"));
    		}
    	
    	}
    	 
    
	}
	/**
     * 激活用户（暂不使用）
     * @author 顽皮蛋 <shf_l@163.com>
     */
	function active(){
		$hash=I("get.hash","");
		if(empty($hash)){
			//$this->error("激活码不存在");
		}
		
		$users_model=M("Users");
		$find_user=$users_model->where(array("user_activation_key"=>$hash))->find();
		
		if($find_user){
			$result=$users_model->where(array("user_activation_key"=>$hash))->save(array("user_activation_key"=>"","user_status"=>1));
			
			if($result){
				$find_user['user_status']=1;
				$_SESSION['user']=$find_user;
				$this->success("用户激活成功，正在登录中...",__ROOT__."/");
			}else{
				$this->error("用户激活失败!",U("/login/index"));
			}
		}else{
			$this->error("用户激活失败，激活码无效！",U("/login/index"));
		}
		
		
	}
	/**
     * 检测用户名--推广链接
     * @author 顽皮蛋 <shf_l@163.com>
     */
    public function checkuName(){
        $user_login = I('user_login');
        $jsoncallback = isset($_GET['jsonpCallback'])?$_GET['jsonpCallback']:'jsonpCallback';
        $users_model=M("Users");
        $rules = array(
                //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
                array('user_login', 'require', '用户名不能为空！', 1 ),
                array('user_login','','用户名已经存在！',0,'unique',1), // 验证user_login字段是否唯一          
        );
        unset($_POST);
        $_POST['user_login'] = $user_login;
        if($users_model->validate($rules)->create()===false){
            $data = "{\"result\":\"error\",\"msg\":\"对不起，用户名只能由字母和数组组成!\"}";
            exit($jsoncallback.'('.$data.')');
        }
        //用户名需过滤的字符的正则
        $stripChar = '?<*.>\'"';
        if(preg_match('/['.$stripChar.']/is', $user_login)==1){
            $data = "{\"result\":\"error\",\"msg\":\"用户名中包含非法字符!\"}";
            exit($jsoncallback.'('.$data.')');
        }
        if(strlen($user_login) < 6 || strlen($user_login) > 22){
            $data = "{\"result\":\"error\",\"msg\":\"用户名至少6位，最多22位！\"}";
            exit($jsoncallback.'('.$data.')');
        }
        if(preg_match("/[\x7f-\xff]/", $user_login)){
            $data = "{\"result\":\"error\",\"msg\":\"用户名不能包括中文！\"}";
            exit($jsoncallback.'('.$data.')');
        }
        $banned_usernames=explode(",", sp_get_cmf_settings("banned_usernames"));
        
        if(in_array($user_login, $banned_usernames)){
             $data = "{\"result\":\"error\",\"msg\":\"此用户名禁止使用！\"}";
            exit($jsoncallback.'('.$data.')');
        }
        $ucenter_syn=C("UCENTER_ENABLED");
        if($ucenter_syn){
           include UC_CLIENT_ROOT."client.php";
            $uc_checkusername=1;
            $uc_checkusername=uc_user_checkname($user_login);
            if($uc_checkusername<0){
                $data = "{\"result\":\"error\",\"msg\":\"此用户名已经使用！\"}";
                exit($jsoncallback.'('.$data.')');
            }
        }
        $data = "{\"result\":\"success\",\"msg\":\"此用户名可以使用！\"}";
        exit($jsoncallback.'('.$data.')');
    }

    
}