<?php
/* 安全验证 */
//use Yurun\Util\HttpRequest;
// 极验证二次验证请求
function geetest_check($data){

    $captcha_id = get_op('geetest_id','');
    $captcha_key = get_op('geetest_key','');
    $api_server = "http://gcaptcha4.geetest.com";

    if(empty($captcha_id) || empty($captcha_key)) {
        return array('code' => 1 , 'msg' => '行为验证后台参数错误，请联系管理员');
    }

    if (isset($data['lot']) && is_array($data['lot'])) {
        $data = $data['lot'];
    }

    if(empty($data['lot_number']) || empty($data['captcha_output']) || empty($data['pass_token']) || empty($data['gen_time']) ) {
        return array('code' => 1 , 'msg' => '行为验证参数错误，请重试');
    }

    $lot_number     = $data['lot_number'];
    $captcha_output = $data['captcha_output'];
    $pass_token     = $data['pass_token'];
    $gen_time       = $data['gen_time'];

    $sign_token = hash_hmac('sha256', $lot_number, $captcha_key);

    $query = array(
        "lot_number"     => $lot_number,
        "captcha_output" => $captcha_output,
        "pass_token"     => $pass_token,
        "gen_time"       => $gen_time,
        "sign_token"     => $sign_token,
    );

    $url = sprintf($api_server . "/validate" . "?captcha_id=%s", $captcha_id);

    $http     = new Yurun\Util\HttpRequest;
    $response = $http->post($url, $query);
    $result   = $response->json(true);

    if (!isset($result['result'])) {
        return array('code' => 1, 'msg' => '行为验证服务出错');
    }

    if ($result['result'] === 'success') {
        return array('code' => 0);
    }

    return array('code' => 1, 'msg' => '行为验证失败' . ((!empty($result['reason']) ? '：' . $result['reason'] : '')) . ((!empty($result['msg']) ? '：' . $result['msg'] : ''))); 
}

// ppo滑动验证
use Kkokk\Poster\PosterManager;

function ppoc_check(){
    $type = 'slider';
    $key = isset($_POST['key']) ? $_POST['key'] : '';
    $x = isset($_POST['x']) ? $_POST['x'] : '';
    $leeway = 8;

    if($key == '' || $x == ''){
        wp_send_json(array('code' => 404 , 'msg' => '非法操作，验证参数错误！'));
    } 
    
    $data = ppoc_verify($key,$x,$leeway);

    if($data){
        wp_send_json(array('code' => 200 , 'msg' => '验证成功！'));
    } else {
        wp_send_json(array('code' => 404 , 'msg' => '验证失败'));
    }
}
add_action( 'wp_ajax_nopriv_ppoc_check', 'ppoc_check' );
add_action( 'wp_ajax_ppoc_check', 'ppoc_check' );

//获取滑块验证图和参数
function get_ppoc_data(){
    try {
        $expiration = 3600;
        $rand = mt_rand(1,20);
        
        $local_path = get_template_directory() . '/img/captcha/' . $rand . '.jpg';
        if (!file_exists($local_path)) {
            wp_send_json(array('code' => 0, 'msg' => '验证码背景图片不存在：' . $local_path));
        }
        
        $params = [
            'src'           => $local_path,
            'im_width'      => 340,
            'im_height'     => 251,
            'im_type'       => 'png',
            'quality'       => 80,
            'type'          => mt_rand(3,6),
            'bg_width'      => 340,
            'bg_height'     => 191,
            'slider_width'  => 50,
            'slider_height' => 50,
            'slider_border' => 2,
            'slider_bg'     => 1,
        ];
        
        $type = 'slider';
        
        $captcha = PosterManager::Captcha()->setCache(new \Kkokk\Poster\Cache\SessionCacheAdapter());
        $result = $captcha->type($type)->config($params)->get();
          
        wp_send_json($result);
    } catch (Exception $e) {
        wp_send_json(array('code' => 0, 'msg' => '验证码生成失败：' . $e->getMessage()));
    }
}
add_action( 'wp_ajax_nopriv_get_ppoc_data', 'get_ppoc_data' );
add_action( 'wp_ajax_get_ppoc_data', 'get_ppoc_data' );

function ppoc_verify($key, $value, $leeway = 0){
    $adapter = new \Kkokk\Poster\Cache\SessionCacheAdapter();
    $x = $adapter->pull($key);

    if (empty($x)) return false;

    return $x >= ($value - $leeway) && $x <= ($value + $leeway);
}

//验证码
function captcha_code_data(){
    session_start();

    $params = [
        'src'         => '',
        'im_width'    => 220,
        'im_height'   => 60,
        'im_type'     => 'png',
        'quality'     => 80,
        'type'        => 'alpha_num',
        'font_family' => get_template_directory().'/inc/assets/grobold.ttf',
        'font_size'   => 32,
        'font_count'  => 4,
        'line_count'  => 0,
        'char_count'  => 0,
    ];

    $type = 'input';

    try {
        $captcha = PosterManager::Captcha()->setCache(new \Kkokk\Poster\Cache\SessionCacheAdapter());
        $data = $captcha->type($type)->config($params)->get();

        if(!empty($data) && isset($data['img'])){
            $_SESSION['captcha_code'] = $data['secret'] ?? $data['key'];
            wp_send_json(array('code' => 200 , 'res' => $data['img']));
        }

        wp_send_json(array('code' => 404 , 'msg' => '验证码生成失败: 数据为空'));
    } catch (Exception $e) {
        wp_send_json(array('code' => 404 , 'msg' => '验证码生成异常: '.$e->getMessage()));
    }
}

add_action( 'wp_ajax_nopriv_captcha_code_data', 'captcha_code_data' );
add_action( 'wp_ajax_captcha_code_data', 'captcha_code_data' );

// 验证码检查
function captcha_code_check(){
    if (!isset($_SESSION)) {
	    session_start();
	}
    $check_code = isset($_POST['captcha_code']) ? $_POST['captcha_code'] : '';
    $msg = '';

    if(!$check_code){
        $msg .= __('请输入验证码. ');
    } else {
        $cacheKey = isset($_SESSION['captcha_code']) ? $_SESSION['captcha_code'] : '';
        if($cacheKey){
            $adapter = new \Kkokk\Poster\Cache\SessionCacheAdapter();
            $correctCode = $adapter->pull($cacheKey);
            if($correctCode && strtolower($check_code) == strtolower($correctCode)){
                $_SESSION['captcha_verified'] = true;
                wp_send_json(array('code' => 200 , 'msg' => '验证成功'));
            }
        }
        $msg .= __('验证码错误. ');
    }

    wp_send_json(array('code' => 404 , 'msg' => $msg));
}
add_action( 'wp_ajax_nopriv_captcha_code_check', 'captcha_code_check' );
add_action( 'wp_ajax_captcha_code_check', 'captcha_code_check' );

//手机或邮箱验证码验证
function check_phone_email_code($mobile,$auth_code){
    $data = get_transient('auth_'.$mobile.'');
	
	return $data;
}