<?php
/**
 * 发送短信验证码到指定手机
 * @author Paul
 * @param string $mobile 手机号码
 * @param string $code 验证码
 * @param string $type 1=注册,2=改密码,3=找回密码,4=绑定手机
 */
function sendcode($mobile,$code,$type,$channelid) {

    $params = array(
		'channelid'=> $channelid,
        'mobile' => $mobile,
		'type'	=> $type,
		'code'	=> $code,
     );
    $params = array_map('urlencode', $params);
    $params = http_build_query($params);
    $ch = curl_init('http://www.mocuz.com/message/send_message');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    $result = curl_exec($ch);
	//出错则显示错误信息
	//if(curl_errno($ch)){
		//var_dump(curl_error($ch));
	//}
    curl_close($ch);
    if($result && ($data = explode(',', $result))) {
        odz_writelog('[SENDCODE] Send message to '.$mobile.', gateway result: '.$result);
        return $data[0];
    }
	return false;
}

if(!defined('IN_DISCUZ')) {
    exit('Access Denied');
}

$mobile = trim($_GET['mobile']);
$type	= trim($_GET['type']);
$channelid = trim($_GET['channelid']);
//$code = random(4, 1);
//sendcode($mobile,$code,$type);

if(empty($mobile) || !preg_match('/^(\+)?(86)?0?1\d{10}$/', $mobile)) {
    odz_error('error_phone_number');
}
if(DB::result_first('SELECT COUNT(*) FROM '.DB::table('mocuz_mobile')." WHERE mobile = '$mobile'")) {
    odz_error('phone_number_already_used');
}

$row = DB::fetch_first('SELECT tries, dateline FROM '.DB::table('mocuz_mobile_verify')." WHERE mobile = '$mobile'");
$code = random(4, 1); // 短信验证码

if(!$row) {
    $ret = sendcode($mobile,$code,$type,$channelid);
    if ($ret != '0') {
        odz_writelog('[GETCODE] Failed to sent message, gateway result: '.(string)$ret);
        odz_error('code_not_sent');
    }

    DB::insert('mocuz_mobile_verify', array(
        'mobile' => $mobile,
        'code' => $code,
        'tries' => 1,
        'dateline' => $_G['timestamp']
    ));
} else {
    $interval = $_G['timestamp'] - $row['dateline'];
    // 获取验证码间隔时间
    if($interval < 60) {
        odz_error('code_timelimit');
    }
    if(date('Ymd', $row['dateline']) != date('Ymd', $_G['timestamp'])) {
        $row['tries'] = 0;
    }

    $tries = $row['tries'] + 1;
    // 限制每日获取验证码次数
    if ($tries > 3) {
        odz_error('code_numlimit');
    }

    $ret = sendcode($mobile,$code,$type,$channelid);
    if ($ret != '0') {
        odz_writelog('[GETCODE] Failed to sent message, gateway result: '.(string)$ret);
        odz_error('code_not_sent');
    }

    DB::update('mocuz_mobile_verify', array(
        'code' => $code,
        'tries' => $tries,
        'dateline' => $_G['timestamp']
    ), array(
        'mobile' => $mobile
    ));
}

odz_success();

?>