<?php
if (!defined('puyuetian')) {
    exit('403');
}

//ini_set('display_errors', 'On');
//error_reporting(E_ALL | E_STRICT);

if (!$_G['SET']['APP_HADSKYCLOUDSERVER_SMS_OPEN']) {
    ExitJson('未开启云短信功能，请联系管理员在后台-云端-本地设置-云短信设置-功能开关处开启');
}

//验证是否等待了60秒
if ($_COOKIE['APP_PUYUETIAN_SMS_TIME']) {
    ExitJson('请等待60秒后再操作');
}

//验证码保护
if ($_G['SET']['APP_PUYUETIAN_SMS_VERIFYCODE']) {
    if (!$_G['GET']['VERIFYCODE'] || $_G['GET']['VERIFYCODE'] != $_SESSION['APP_VERIFYCODE_SMS']) {
        $_SESSION['APP_VERIFYCODE_SMS'] = '';
        ExitJson('验证码错误');
    }
    $_SESSION['APP_VERIFYCODE_SMS'] = '';
}

//验证该IP是否超出了今日最大请求数
if (Cnum($_G['SET']['APP_PUYUETIAN_SMS_IPMAX'])) {
    $rt = $_G['TABLE']['APP_PUYUETIAN_SMS_RECORD']->getCount(array('ip' => getClientInfos('ip'), 'date' => date('Ymd')));
    if ($rt >= $_G['SET']['APP_PUYUETIAN_SMS_IPMAX']) {
        ExitJson('该IP今日请求已达上限');
    }
}

//接收的手机号
$phonenumber = Cstr($_GET['phonenumber'], false, $_G['STRING']['NUMERICAL'], 11, 11);
if (substr($phonenumber, 0, 1) != 1 || !$phonenumber) {
    ExitJson('手机号不正确');
}
//验证该手机号是否超出了今日最大请求数
if (Cnum($_G['SET']['APP_PUYUETIAN_SMS_PNMAX'])) {
    $rt = $_G['TABLE']['APP_PUYUETIAN_SMS_RECORD']->getCount(array('pn' => $phonenumber, 'date' => date('Ymd')));
    if ($rt >= $_G['SET']['APP_PUYUETIAN_SMS_PNMAX']) {
        ExitJson('该号码今日请求已达上限');
    }
}

// 检验是否注册或未注册，防止无效获取
if ('reg' == $_G['GET']['TYPE'] && $_G['TABLE']['USER']->getId(array('phone' => $phonenumber))) {
    ExitJson('该号码已被注册，请<a class="pk-text-primary pk-hover-underline" href="index.php?c=app&a=hadskycloudserver:index&s=sms_login">登录</a>');
}
if ('login' == $_G['GET']['TYPE'] && !$_G['TABLE']['USER']->getId(array('phone' => $phonenumber))) {
    ExitJson('该号码暂未注册，请<a class="pk-text-primary pk-hover-underline" href="index.php?c=app&a=hadskycloudserver:index&s=sms_reg">注册</a>');
}

//创建短信验证码
if (!Cnum($_SESSION['APP_PUYUETIAN_SMS_CODE']) || !Cstr($_SESSION['APP_PUYUETIAN_SMS_PHONE'], false, $_G['STRING']['NUMERICAL'], 11, 11) || $phonenumber != $_SESSION['APP_PUYUETIAN_SMS_PHONE']) {
    $_SESSION['APP_PUYUETIAN_SMS_CODE']  = $code  = rand(1000, 9999);
    $_SESSION['APP_PUYUETIAN_SMS_PHONE'] = $phonenumber;
} else {
    $code = $_SESSION['APP_PUYUETIAN_SMS_CODE'];
}

//请求发送短信
$r = cloudSendSms($phonenumber, $code);

if (true === $r) {
    setcookie('APP_PUYUETIAN_SMS_TIME', true, time() + 60);
    ExitJson('发送成功', true);
}
ExitJson($r);
