<?php

namespace Org;

/**
 * 验证操作类
 * @category   ORG
 * @package  ORG
 * @subpackage  Vcode
 * @author    liu21st <liu21st@gmail.com>
 * @version   $Id: Date.class.php 2662 2012-01-26 06:32:50Z liu21st $
 */
class Vcode {
	// 保存错误信息
	public $error;

    var $ttl = 86400;

    public function __construct(){
    }

    //随机取6位字符数
    public function randomkeys($length){
        $key = '';
        $pattern = '1234567890';    //字符池
        for($i=0;$i<$length;$i++){
            $key .= $pattern{mt_rand(0,9)};    //生成php随机数
        }
        return $key;
    }

    /*
     * 生成验证码
    *
    * @params $mobile 手机号码
    * @params $type  reg 注册 | forgot 忘记密码
    * @params $msg 提示信息
    * */
    public function set_vcode($mobile){
        $vcodeData = $this->get_vcode($mobile);
        if($vcodeData){
            if( time() - $vcodeData['when_send'] < 120 ){
                $this->error = L('once_2mins');
                return false;
            }
        }

        $vcode = $this->randomkeys(4);
        $vcodeData['mobile'] = $mobile;
        $vcodeData['vcode'] = $vcode;
        $vcodeData['when_send'] = time();

        $key = $this->get_vcode_key($mobile);
        S($key,$vcodeData,1800);
        return $vcode;
    }


    public function get_vcode($mobile){
        $key = $this->get_vcode_key($mobile);
        $vcodeData = S($key);
        return $vcodeData;
    }

    /*
     * 校验验证码
    *
    * @params $mobile 手机号码
    * @params $type  reg 注册 | forgot 忘记密码
    * @params $msg 提示信息
    * */
    public function check_vcode($tel, $vcode){

        $vcodeData = $this->get_vcode($tel);
        //print_r($vcodeData);
        if ($vcodeData) {
            if($vcodeData['mobile']==$tel && $vcodeData['vcode']==$vcode){
                if(time()-$vcodeData['when_send'] > 1800){
                    $this->error = L('verify_fail');
                    return false;
                }else{
                    return true;
                }
                //超时或验证成功后删除缓存
                $this->delete_vcode($tel);
            }else{
                $this->error = L('verify_fail');
                return false;
            }
        }else{
            $this->error = L('verify_fail');
            return false;
        }
    }

    /*
     * 删除验证码,清除缓存
    * */
    public function delete_vcode($mobile){
        $key = $this->get_vcode_key($mobile);
        S($key,null);
    }

    public function get_vcode_key($mobile){
        return md5($mobile);
    }

}