<?php
// +-----------------------------------------------------------------------------------
// | Software: [ThinkPHP framework]
// | Version: V4.0
// | Site: http://www.czreg.com
// +-----------------------------------------------------------------------------------
// | Author: 飘叶 <cds425@163.com>
// | Copyright (c) 2012-2014, http://www.czreg.com All Rights Reserved.
// | time:2014.10.25
// | explain:公共类
// +-----------------------------------------------------------------------------------
namespace Home\Controller;
use Think\Controller,Com\Qqlogin;
class PublicController extends Controller {

    public function _initialize(){
        $configset			= M('Config')->limit(1)->find();//网站配置输出
        $this->configset	= $configset;//网站配置输出
        $this->main 		= M('Main')->limit(C('MAIN'))->select();//导航输出
        //qq登陆信息
        $qqauto = array(
        	'qq_id'       => get_webconfig('qq_id'),
        	'qq_key'      => get_webconfig('qq_key'), 
        	'qqcallback'  => 'http://'.$_SERVER['HTTP_HOST'].'/Index/callback.html',
        );
        $this->qqauto = $qqauto;
        if($configset['upimg']==1){
        	$this->IMGURL       =$configset['imgurl'];//图片远程地址
        }else{
        	$this->IMGURL       ='/Uploads/';//图片本地地址
        }
        //登陆信息
        if(session('userid')!=''){
            $userid=session('userid');
            $user=M('User')->where(array('id'=>$userid))->find();
            $this->user=$user;
        }
    }

    function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('Public:404');
	}

    public function reg(){
        if(IS_POST){
            //验证码验证
            // $code=I('post.verifycode');
            // if(check_verify($code) === false){
            //     $this->error("验证码错误");
            // }

            $arrayData = array(
                'username' => I('post.loginname'), 
                'userpass' => md5(I('post.loginpass')),
                'nickname' => I('post.nickname'),
                'birthday' =>'1980-1-1',
                'created'  => time(),
                'updataed' => time(),
                'updataip' => get_client_ip(),
                'createip' => get_client_ip(),
            );
            if(I('post.loginpass')!=I('post.repassword')){
                $this->error('两次输入的密码不一致');
            }
            //根据IP查询，限制同一IP每分钟限制注册一个用户
            $nowtime = $arrayData['created']-60;
            $ip = M('ip')->where(array('ip'=>$arrayData['createip']))->order('id desc')->find();
            if($ip!==false){
                if($ip['timeline']>$nowtime){
                    $timeline =$arrayData['created']-$ip['timeline'];
                    $timeline = 60 -$timeline;
                    $this->error('注册时间保护，请过'.$timeline.'秒后再注册');
                }
            }

            $rules = array(
            	array('username','require','用户名不能为空！'), // 在新增的时候验证name字段是否唯一  
                array('username','','用户名已经存在', 0, 'unique'), // 在新增的时候验证name字段是否唯一 
                array('regpass','loginpass','确认密码不正确',0,'confirm'),  // 验证确认密码是否和密码一致
            );

            $User=M('User');
            if ($User->validate($rules)->create($arrayData)){
            	//手机验证
                if(get_webconfig('phone_auth')==1){
                    $phonecode = I('post.phonecode');
                    if(I('post.phonecode')==''){
                        $this->error("短信验证码还未填写！");
                        exit;
                    }
                    $findphone = M('Phone')->field('id,phonenum,isuse,timeline')->where(array('phone'=>$arrayData['username']))->order('id desc')->find();
                    if($findphone['phonenum']!=$phonecode){
                        $this->error("短信验证码错误！");
                        exit;
                    }
                    if($findphone['isuse']==1){
                        $this->error("短信验证码已使用！");
                        exit;
                    }
                    $timeline = $findphone['timeline']+1800;
                    if($timeline<time()){
                        $this->error("短信验证码已过期！");
                        exit;
                    }
                    //服务器查询
                    if($findphone['isuse']==2){
                        $config = M('Config')->limit(1)->find();//网站配置输出
                        $st     = file_get_contents(C('SERVERURL')."send/cxnum/uid/".$config['serverid']."/phone/".$arrayData['username']."/phonenum/".I('post.phonecode'));
                        if($st!=1){
                            $this->error("短信验证码错误！");
                            exit;
                        }   
                    }
                    M('phone')->where('id='.$findphone['id'])->save(array('isuse'=>1));
                }
                 //入库
                $list=$User->add($arrayData);
                if($list !== false){
                    //注册成功
                    session('userid',$list);
                    //IP入库，限制注册时间
                    M('ip')->add(array('ip'=>$arrayData['createip'],'timeline'=>$arrayData['created']));
                    $this->success('注册成功！',U('User/index'));
                }else{
                    $this->error("注册失败");
                }
            }else{
                //exit($User->getError());
                $this->error($User->getError());
            }
        }else{
            $this->show();
        }
    }

    public function logout(){
        //退出登陆
        session('userid',null);
        session('username',null);
        $this->redirect('Index/index');
    }

    public function login(){
        $oauth=I('get.oauth');
        $qqauto = $this->qqauto;
        if($oauth=="qq"){
            $qq = new Qqlogin($qqauto['qq_id'],$qqauto['qq_key'],$qqauto['qqcallback']);
            echo $qq->qqlogin();
            exit;
        }
        //登陆及登陆验证
        if(IS_POST){
            if(I('post.openid')!=''){
                $data = array(
                    'nickname' => I('post.nickname'),
                    'img' =>I('post.img'),
                    'qqopenid' =>I('post.openid'),
                );
            }
            $DB = M('User');
            $con['username'] = I('post.loginname');
            $con['userpass']  = md5(I('post.loginpass'));
            $list = $DB->where($con)->find();
            if($list['id']!=''){
                if($list["level"]==0){
                    $this->error("用户已被禁用，如需再次启用。请与客服联系！",'',30);
                }
                $id=$list["id"];
                $data["updataed"]=time();
                $data["updataip"]=get_client_ip();
                $DB->where("id='$id'")->save($data);
                session('userid',$list["id"]);
                $this->success("登陆成功",U('User/index'));
            }else{
                $this->error("登陆失败",U('Index/reg'));
            }
            exit;
            //return ;
        }else{
             $this->show();
        }
    }

    public function callback(){
    	$qqauto = $this->qqauto;
        $qq = new Qqlogin($qqauto['qq_id'],$qqauto['qq_key'],$qqauto['qqcallback']);
         //得到access_token验证值
        $arr = $qq->get_token();
         if(isset($arr['access_token']))
            $access_token = $arr['access_token'];
         else
            die('登陆失败');
         //得到用户的openid(登陆用户的识别码)和Client_id
        $arr = $qq->get_client_id($access_token);
         if(isset($arr['client_id'])){
            $client_id = $arr['client_id'];
            $openid = $arr['openid'];
         }else{
            die('登陆失败');
         }

         $DB = M('User');
            $list = $DB->where(array('qqopenid' => $openid ))->find();
            if($list['id']!=''){
                if($list["level"]==0){
                    $this->error("用户已被禁用，如需再次启用。请与客服联系！",'',30);
                }
                $id=$list["id"];
                $data["updataed"]=time();
                $data["updataip"]=get_client_ip();
                $DB->where("id='$id'")->save($data);
                session('userid',$list["id"]);
                session('username',$list["username"]);
                $this->success("登陆成功",U('User/index'));
            }else{
             //会员绑定QQ
             if(session('userid')!=''){
                $save = $DB->where(array('id' => session('userid') ))->save(array('qqopenid'=> $openid));
                if($save !== false){
                    //绑定成功
                    $this->success('绑定QQ成功！',U('User/index'));
                }else{
                    $this->success('绑定失败',U('User/index'));
                }
                exit;
             }

            //用户不存在
            $arr = $qq->user_info($client_id,$openid,$access_token);//获取用户数据
            $arrayData = array(
                'username' => '', 
                'userpass' => '',
                'nickname' => $arr['nickname'],
                'img'      => $arr['figureurl_qq_2'],
                'qqopenid' =>$openid,
                'birthday' =>'1980-1-1',
                'created'  => time(),
                'updataed' => time(),
                'updataip' => get_client_ip(),
                'createip' => get_client_ip(),
            );
                $list=M('User')->add($arrayData);
                if($list !== false){
                    //注册成功
                    session('userid',$list);
                    session('username',$arr['nickname']);
                    $this->success('注册成功,建议在左侧“修改资料”中填写用户名和密码，又便更好的获得服务！',U('User/index'));
                }else{
                    $this->success('注册失败',U('Index/reg'));
                }
               //  $reg_url='/Index/reg?oauth=qq&openid='.$openid.'&nickname='.$arr['nickname'].'&img='.$arr['figureurl_qq_2'];
               // header("Location:".$reg_url);
            }
    }

    Public function verify(){
        //生成验证码
        $Verify =     new \Think\Verify();
        $Verify->fontSize = 20;
        $Verify->length   = 4;
        $Verify->useNoise = false;
        $verify->useCurve = false;
        
        $Verify->entry();
    }

public function upimg(){
        $id=I('get.id');
        $width=I('get.width');
        $this->id=$id;
        $this->width=$width;
        if (IS_POST) {
            $config = $this->configset;//网站配置输出 
            if($config['upimg']==1){
                //使用七牛存储图片
                $setting=C('UPLOAD_SITEIMG_QINIU');
                $Upload = new \Think\Upload($setting);
                $info = $Upload->uploadOne($_FILES['logo']);
            }else{
                //本地图片处理
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =  524288 ;// 设置附件上传大小    
                $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型    
                $upload->savePath  =     ''; // 设置附件上传目录
                $info   =   $upload->uploadOne($_FILES['logo']);
            }
    
            if(!$info) {
            // 上传错误提示错误信息  
                $this->error($upload->getError());    
            }else{
            // 上传成功
                $img=$info['savepath'].$info['savename'];
                echo "<script language=javascript>window.opener.document.getElementById('".$id."').value='" . $img . "';var opened=window.open('about:blank','_self');opened.opener=null;
            opened.close();</script>";    
            }
        }
        $this->show();
    }

    public function send(){
        //获取用户手机号
        $to = I('post.phone');
        //查询该号码有没有注册过
        $finduser = M('User')->field('id')->where(array('username'=>$to))->order('id desc')->find();
        if(!empty($finduser)){
            exit('该手机号码已经注册过用户名了');
        }
        //系统配置
        $config = M('Config')->limit(1)->find();//网站配置输出
        $nowtime =time();
        $verstr = md5($config['serverid'].$to.I('sendid').$nowtime.$config['verifystring']);
        $st     = file_get_contents(C('SERVERURL')."send/index/uid/".$config['serverid']."/phone/".$to."/nowtime/".$nowtime."/verifystring/".$verstr."/tempid/".$tempid);
        $msg = json_decode($st);
        if($msg->errcode =="success"){
            $param = $msg->errmsg;
            $isuse = 0;
            $msg = array(
                'errcode' => 'success',
                'errmsg'  => '短信验证码已发送成功，请在30分钟内输入！',
            );
            echo json_encode($msg); 

        }else{
            $param = 0;
            $isuse = 2;
            echo $st; 
        }
        M('Phone')->add(array('phone'=>$to,'phonenum'=>$param,'timeline'=>time(),isuse=>$isuse));
              
    }
}