0, 'start' => time()]; if (time() - $bucket['start'] > 60) { // 60-second window $bucket = ['count' => 0, 'start' => time()]; } $bucket['count']++; $_SESSION['ratelimit'][$ip] = $bucket; if ($bucket['count'] > 120) { // 120 requests/min/IP http_response_code(429); header('Content-Type: application/json'); echo json_encode(['error' => 'Too Many Requests']); exit; } // --- read .env file with CALCO2LATO_API_BASE and CALCO2LATO_API_KEY $env = file_get_contents(__DIR__."/../src/.env"); $lines = explode("\n",$env); foreach($lines as $line){ preg_match("/([^#]+)\=(.*)/",$line,$matches); if(isset($matches[2])){ putenv(trim($line)); } } // --- Read config --- $base = getenv('CALCO2LATO_API_BASE') ?: 'https://api.calco2la.to'; $key = getenv('CALCO2LATO_API_KEY') ?: ''; if (!$key) { http_response_code(500); header('Content-Type: application/json'); echo json_encode(['error' => 'Server misconfiguration: missing API key']); exit; } // --- Instantiate API client --- // Version from query (?ver=v1|test|latest), default latest $ver = $_GET['ver'] ?? $_POST['ver'] ?? Calco2latoApiVersion::LATEST; $client = new Calco2latoApiClient($base, $key, (string)$ver); // --- Whitelist router --- $input = json_decode(file_get_contents('php://input') ?: '[]', true) ?: []; $endpoint = $_GET['endpoint'] ?? $input['endpoint'] ?? ''; $method = $_SERVER['REQUEST_METHOD']; header('Content-Type: application/json; charset=utf-8'); try { switch ($endpoint) { case 'health': echo json_encode(['ok'=>true,'ver'=>$ver]); break; case 'airports.search': if ($method === 'GET') { $q = [ 'page' => isset($_GET['page']) ? (int)$_GET['page'] : null, 'per_page' => isset($_GET['per_page']) ? (int)$_GET['per_page'] : null, 'sort_by' => $_GET['sort_by'] ?? null, 'order' => $_GET['order'] ?? null, 'iata' => $_GET['iata'] ?? null, ]; echo json_encode($client->airports_get($q)); break; } elseif ($method === 'POST') { $params = $input['params'] ?? []; echo json_encode($client->airports_post($params)); break; } case 'flights.estimate': // POST with JSON body: { endpoint: "flights.estimate", params: {...} } if ($method !== 'POST') throw new RuntimeException('Use POST'); $params = $input['params'] ?? []; echo json_encode($client->flight_post($params)); break; default: http_response_code(404); echo json_encode(['error' => 'Unknown or unsupported endpoint']); } } catch (Throwable $e) { http_response_code(400); echo json_encode(['error' => $e->getMessage()]); }