<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

$imgUrl = isset($_GET['url']) ? trim($_GET['url']) : '';
if (empty($imgUrl) || !filter_var($imgUrl, FILTER_VALIDATE_URL)) {
    http_response_code(400);
    exit('Invalid URL');
}

$sig = isset($_GET['sig']) ? $_GET['sig'] : '';
$secret = defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : md5(__TYPECHO_ROOT_DIR__ . '_mirai_proxy');
$expectedSig = hash_hmac('sha256', $imgUrl, $secret);
if (!hash_equals($expectedSig, $sig)) {
    http_response_code(403);
    exit('Invalid signature');
}

$parsed = parse_url($imgUrl);
$currentHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
if (isset($parsed['host']) && $parsed['host'] === $currentHost) {
    header('Location: ' . $imgUrl, true, 302);
    exit;
}

$imgData = false;
if (function_exists('curl_init')) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $imgUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Mirai/ImageProxy)'
    ]);
    $imgData = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($imgData === false || $httpCode !== 200) {
        $imgData = false;
    }
}
if ($imgData === false) {
    $imgData = @file_get_contents($imgUrl);
}
if ($imgData === false) {
    http_response_code(502);
    exit('Failed to fetch image');
}
if (strlen($imgData) > 5 * 1024 * 1024) {
    http_response_code(413);
    exit('Image too large');
}

$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($imgData);
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', 'image/bmp', 'image/svg+xml'];
if (!in_array($mimeType, $allowedTypes)) {
    http_response_code(415);
    exit('Unsupported image type');
}

while (ob_get_level() > 0) {
    ob_end_clean();
}
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . strlen($imgData));
header('Cache-Control: public, max-age=86400');
header('Access-Control-Allow-Origin: *');
echo $imgData;
exit;
