<?php
/**
 * HTTP / Cookie 辅助函数（ip_check 与 f_check 共用）
 */

if (!function_exists('cloak_get_SERVER_value')) {
    function cloak_get_SERVER_value($field_name)
    {
        return isset($_SERVER[$field_name]) ? $_SERVER[$field_name] : null;
    }
}

if (!function_exists('get_SERVER_value')) {
    function get_SERVER_value($field_name)
    {
        return cloak_get_SERVER_value($field_name);
    }
}

if (!function_exists('cloak_request_is_https')) {
    /**
     * 访客是否通过 HTTPS 访问（含 Cloudflare / 反代 X-Forwarded-Proto）
     */
    function cloak_request_is_https()
    {
        if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off' && $_SERVER['HTTPS'] !== '0') {
            return true;
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
            return true;
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_SSL']) === 'on') {
            return true;
        }
        if (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower((string) $_SERVER['HTTP_FRONT_END_HTTPS']) === 'on') {
            return true;
        }
        if (!empty($_SERVER['HTTP_CF_VISITOR'])) {
            $cf = json_decode((string) $_SERVER['HTTP_CF_VISITOR'], true);
            if (is_array($cf) && ($cf['scheme'] ?? '') === 'https') {
                return true;
            }
        }
        if (!empty($_SERVER['SERVER_PORT']) && (int) $_SERVER['SERVER_PORT'] === 443) {
            return true;
        }
        return false;
    }
}

if (!function_exists('cloak_current_request_url')) {
    /**
     * 浏览器实际访问的完整 URL（用于日志 page 字段；无 query 时不拼裸 ?）
     */
    function cloak_current_request_url()
    {
        $scheme = cloak_request_is_https() ? 'https' : 'http';
        $host   = (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');

        if (!empty($_SERVER['REQUEST_URI'])) {
            $uri = (string) $_SERVER['REQUEST_URI'];
            if (strpos($uri, '://') !== false) {
                return $uri;
            }
            if ($uri === '' || $uri[0] !== '/') {
                $uri = '/' . ltrim($uri, '/');
            }
            return $scheme . '://' . $host . $uri;
        }

        $path = (string) ($_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? '/');
        $qs   = (string) ($_SERVER['QUERY_STRING'] ?? '');
        $url  = $scheme . '://' . $host . $path;
        if ($qs !== '') {
            $url .= '?' . $qs;
        }
        return $url;
    }
}

if (!function_exists('cloak_encode_visitor_cookies')) {
    function cloak_encode_visitor_cookies()
    {
        $transmit_string = '';
        foreach ($_COOKIE as $name => $value) {
            try {
                $transmit_string .= "$name=$value; ";
            } catch (Exception $e) {
                continue;
            }
        }
        return $transmit_string;
    }
}

if (!function_exists('encode_visitor_cookies')) {
    function encode_visitor_cookies()
    {
        return cloak_encode_visitor_cookies();
    }
}

if (!function_exists('cloak_forward_response_cookies')) {
    function cloak_forward_response_cookies($ch, $headerLine)
    {
        if (preg_match('/^Set-Cookie:/mi', $headerLine, $cookie)) {
            header($headerLine, false);
        }
        return strlen($headerLine);
    }
}

if (!function_exists('forward_response_cookies')) {
    function forward_response_cookies($ch, $headerLine)
    {
        return cloak_forward_response_cookies($ch, $headerLine);
    }
}

if (!function_exists('cloak_write_nt_list')) {
    function cloak_write_nt_list($cong_name, $nt, $ot)
    {
        $cong_name = parse_url($cong_name, PHP_URL_PATH);
        $content   = $cong_name . '||||||' . $nt . "\n";
        $file      = 'nt.txt';

        if ($ot) {
            $handle      = @fopen($file, 'r+');
            $search      = '/' . $cong_name . '\|\|\|\|\|\|' . $ot . '/';
            $found       = false;
            $tempContent = '';

            while (!feof($handle)) {
                $line = fgets($handle);
                if (preg_match($search, $line)) {
                    $tempContent .= $content;
                    $found = true;
                } else {
                    $tempContent .= $line;
                }
            }

            if ($found && flock($handle, LOCK_EX)) {
                file_put_contents($file, $tempContent);
                flock($handle, LOCK_UN);
            }
            fclose($handle);
        } else {
            $handle = @fopen($file, 'a');
            if ($handle && flock($handle, LOCK_EX)) {
                fwrite($handle, $content);
                flock($handle, LOCK_UN);
            }
            if ($handle) {
                fclose($handle);
            }
        }
    }
}

if (!function_exists('write_nt_list')) {
    function write_nt_list($cong_name, $nt, $ot)
    {
        cloak_write_nt_list($cong_name, $nt, $ot);
    }
}

if (!function_exists('cloak_fingerprint_cookie_domain')) {
    /**
     * 指纹 Cookie 使用的跨子域 domain（与 setCrossDomainCookie 一致）
     */
    function cloak_fingerprint_cookie_domain()
    {
        if (empty($_SERVER['HTTP_HOST'])) {
            return '';
        }

        $host_names = explode('.', $_SERVER['HTTP_HOST']);
        if (count($host_names) < 2) {
            return '';
        }

        return '.' . $host_names[count($host_names) - 2] . '.' . $host_names[count($host_names) - 1];
    }
}

if (!function_exists('cloak_set_cross_domain_cookie')) {
    function cloak_set_cross_domain_cookie($name, $value, $expire)
    {
        $bottom_host_name = cloak_fingerprint_cookie_domain();
        if ($bottom_host_name === '') {
            setcookie($name, $value, $expire, '/');
            return;
        }
        setcookie($name, $value, $expire, '/', $bottom_host_name);
    }
}

if (!function_exists('setCrossDomainCookie')) {
    function setCrossDomainCookie($name, $value, $expire)
    {
        cloak_set_cross_domain_cookie($name, $value, $expire);
    }
}

if (!function_exists('cloak_fingerprint_time_param_present')) {
    /**
     * URL 是否已带 time 参数（表示前端指纹页已执行过一次跳转）
     */
    function cloak_fingerprint_time_param_present()
    {
        return isset($_GET['time']) && (string) $_GET['time'] !== '';
    }
}

if (!function_exists('cloak_fingerprint_cookies_ready')) {
    /**
     * 前端指纹 Cookie 是否已写入
     */
    function cloak_fingerprint_cookies_ready()
    {
        return isset($_COOKIE['ctime'], $_COOKIE['cyyek'], $_COOKIE['cl']);
    }
}

if (!function_exists('cloak_fingerprint_mmr_reason')) {
    /**
     * 根据 mmr Cookie 返回中文拒绝理由
     */
    function cloak_fingerprint_mmr_reason()
    {
        if (!isset($_COOKIE['mmr'])) {
            return '指纹检测未通过(未知原因)';
        }

        $mmrMap = [
            1  => '语言包含中文',
            2  => 'PC端客户不允许访问',
            3  => '操作系统非IOS或者安卓',
            4  => 'IPHONE 机型不符合要求',
            11 => '非IPHONE机型',
            12 => '自动化/WebDriver',
            13 => '模拟器或虚拟机UA',
            14 => '爬虫Bot UA',
            15 => 'WebGL软件渲染',
            16 => '环境不一致(平台/触摸/窗口)',
            17 => '移动GPU与UA不符',
            18 => '移动端无有效加速度计/陀螺仪',
        ];

        $mmr = (int) $_COOKIE['mmr'];

        return $mmrMap[$mmr] ?? '指纹检测未通过(未知原因)';
    }
}
