<?php
// AI gate with a counter (2026-10-05). The .htaccess crawler rules rewrite every blocked request here. This prints the
// same /ai.html page with the same headers as before and adds one line per hit to data/ai_gate_hits.jsonl (outside the
// web root): UTC time, which rule matched, the matched bot name, the User-Agent (200 chars) and the path asked for.
// No IP address is stored. A failed write never changes the response: the gate page is sent first.
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store, private');   // the CDN caches by URL only: a stored copy would hand the gate to a visitor
header('Vary: User-Agent');
header('X-A2T-Gate: ai');
header('X-Robots-Tag: noindex, nofollow, noai, noimageai');
$page = @file_get_contents(__DIR__ . '/ai.html');
if ($page === false || $page === '') { http_response_code(403); $page = ''; }
echo $page;
if (function_exists('fastcgi_finish_request')) { @fastcgi_finish_request(); } else { @ob_flush(); @flush(); }

try {
    $env = function ($k) { foreach ([$k, 'REDIRECT_' . $k, 'REDIRECT_REDIRECT_' . $k] as $n) { $v = $_SERVER[$n] ?? getenv($n); if (is_string($v) && $v !== '') return $v; } return ''; };
    $clean = function ($s, $n) { return substr(preg_replace('/[\x00-\x1F\x7F]+/', ' ', (string)$s), 0, $n); };
    $rule = $env('A2T_GATE');                                  // "bot" (named AI crawler) or "tool" (generic tooling), set by the rewrite rule
    $path = (string)($_SERVER['REQUEST_URI'] ?? '');
    if ($rule === '') $rule = preg_match('~^/ai_gate\.php~', $path) ? 'direct' : 'unknown';
    $ua = (string)($_SERVER['HTTP_USER_AGENT'] ?? '');
    $row = ['t' => gmdate('Y-m-d\TH:i:s\Z'), 'rule' => $rule,
            'bot' => $rule === 'tool' ? 'generic tooling' : $clean($env('A2T_BOT'), 60),
            'ua' => $clean($ua, 200), 'path' => $clean(strtok($path, '?'), 200)];
    if (isset($_SERVER['HTTP_X_A2T_PROBE'])) $row['probe'] = 1;   // our own daily guard and verify runs
    $dir = dirname(rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__)), '/\\')) . '/data';
    $f = $dir . '/ai_gate_hits.jsonl';
    if (is_dir($dir)) {
        if (@filesize($f) > 4000000) { @rename($f, $f . '.1'); }   // cap: two files of 4 MB at most
        @file_put_contents($f, json_encode($row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX);
    }
} catch (\Throwable $e) { }
