<?php
    //判断临时链接参数（Guard 之后、API/指纹 之前）
    if(empty($_SESSION["check_result"]) && !$whiteParamsMatched && SHOW_SITE_MODE_SWITCH == 'ip_check' && CLOAK_URL_ARGS_TIMEOUT > 0) {
        if ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__,'临时链接参数', 'info', 'CLOAK_URL_ARGS_TIMEOUT=' . CLOAK_URL_ARGS_TIMEOUT . ' 分钟，开始检查');
        }
        $dir = dirname(__DIR__, 4) . '/args';
        $pattern = '/^' . preg_quote($config_name, '/') . '_\d{10}\.txt$/i';
        $matchedFile = "";

        if (is_dir($dir)) {
            $iterator = new DirectoryIterator($dir);
            foreach ($iterator as $file) {
                if ($file->isFile() && preg_match($pattern, $file->getFilename())) {
                    $matchedFile = $file->getFilename();
                    break;
                }
            }
        }

        $__url_args_cfg = CloakAdSourceGuard::configFromDefines();
        $__url_args_ctx = CloakAdSourceGuard::buildRequestContext();
        $__url_args_qualifies = CloakAdSourceGuard::shouldStartUrlArgsTimer($__url_args_cfg, $__url_args_ctx);

        if ($__url_args_qualifies) {
            if(!$matchedFile) {
                $filename = $config_name . '_' . time() . '.txt';
                if(touch($dir . '/' . $filename)) {
                    $matchedFile = $filename;
                }
            }
            if ($__cloak_debug_on) {
                cloak_dbg_step(__LINE__, '临时链接参数', 'info', '命中广告来源规则，开始/续期有效时长', [
                    'platforms_enabled' => CloakAdSourceGuard::anyPlatformEnabled($__url_args_cfg),
                ]);
            }
        } elseif ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__, '临时链接参数', 'skip', '未通过广告来源规则，不启动计时');
        }

        unset($__url_args_cfg, $__url_args_ctx, $__url_args_qualifies);

        if($matchedFile) {
            if (preg_match('/_(\d{10})\.txt$/', $matchedFile, $matches)) {
                $fileTimestamp = $matches[1];
                $diffMinutes = floor((time() - $fileTimestamp) / 60);

                if ($diffMinutes < CLOAK_URL_ARGS_TIMEOUT) {
                    $check_result = false;
                    $reason = "临时链接参数：距离第一次访问过去了" . $diffMinutes . " 分钟";
                    if ($__cloak_debug_on) {
                        cloak_dbg_step(__LINE__,'临时链接参数', 'fail', $reason, ['diff_minutes' => $diffMinutes]);
                    }
                } else {
                    $check_result = true;
                    if ($__cloak_debug_on) {
                        cloak_dbg_step(__LINE__,'临时链接参数', 'pass', '已超过 ' . CLOAK_URL_ARGS_TIMEOUT . ' 分钟，继续后续判定');
                    }
                }
            }
        } else {
            $check_result = false;
            $reason = "临时链接参数：尚未有效访问";
            if ($__cloak_debug_on) {
                cloak_dbg_step(__LINE__,'临时链接参数', 'fail', $reason);
            }
        }

        if(!$check_result) {
            $reason = cloak_reason_or($reason, '临时链接参数拦截');
            if (class_exists('CloakPipelineTimer', false)) {
                CloakPipelineTimer::finish();
            }
            if ($__cloak_debug_on) {
                cloak_dbg_record(__LINE__,'false', $reason, ['stage' => 'url_args_timeout']);
                CloakDebugPage::setExitPoint(__LINE__, '临时链接参数拦截 → 安全页（DEBUG 提前截停）');
                CloakDebugPage::renderAndExit([
                    'config_name'  => $config_name,
                    'check_result' => 'false',
                    'reason'       => $reason,
                    'visitor'      => $v_info,
                    'logs'         => [],
                    'device'       => '',
                    'mode'         => SHOW_SITE_MODE_SWITCH,
                    'fp_urls'      => defined('DB_FP') ? DB_FP : [],
                    'zp_url'       => defined('DB_ZP') ? DB_ZP : '',
                    'started_at'   => $__cloak_debug_started,
                ]);
            }
            $logs = array();
            $zp_url = DB_ZP;
            $logs['site_name'] = str_replace("www.", "", $_SERVER['HTTP_HOST']);
            $logs['customers_ip'] = $v_info->v_ip;
            $logs['country'] = substr($v_info->v_country, 0, 2);
            $logs['v_Browser'] = $v_info->v_Browser;
            $logs['v_referer'] = $v_info->v_referer;
            $logs['Client'] = $v_info->v_Client;
            $logs['v_PageURL'] = $v_info->v_curPageURL;
            $logs['v_site_server'] = $v_info->v_site_server;
            $logs['accept_language'] = $v_info->accept_language;
            $logs['visit_md5_code'] = $v_info->visit_md5_code;
            $logs['campagin_id'] = $v_info->costm_ip_score;
            $logs['result'] = "false";
            $logs['device'] = "";
            $logs['reason'] = $reason;
            $logs['fp_url'] = $zp_url;
            write_log_db($logs);

            $redirect_method = CLOAK_REDIRECT_METHOD;
            if(!empty($zp_url)) {
                if($redirect_method == 'curl') {
                    $html = file_get_content_sstr($zp_url);
                    $_html = caiji_lujing_buquan($html, $zp_url, $_SERVER['HTTP_HOST']);
                    echo $_html;
                    exit;
                } elseif($redirect_method == '302') {
                    header('Location: ' . $zp_url);
                    exit;
                } elseif ($redirect_method == 'js') {
                    $zp_url_js = htmlspecialchars($zp_url, ENT_QUOTES, 'UTF-8');
                    echo '<SCRIPT LANGUAGE="JavaScript">'
                        . 'var time = 1;var timelong = 0;'
                        . 'function diplaytime(){document.all.his.innerHTML = time -timelong ;timelong ++;}'
                        . 'function redirect(){window.location.href="' . $zp_url_js . '";}'
                        . "timer=setInterval('diplaytime()', 30);"
                        . "timer=setTimeout('redirect()',time * 30);"
                        . '</SCRIPT>';
                    exit;
                }
            }
        }
    } elseif ($__cloak_debug_on && CLOAK_URL_ARGS_TIMEOUT <= 0) {
        cloak_dbg_step(__LINE__,'临时链接参数', 'skip', 'CLOAK_URL_ARGS_TIMEOUT=0，已关闭');
    }
