<?php
declare(strict_types=1);

$requested = trim(str_replace('\\', '/', (string)($_GET['path'] ?? '')), '/');
if ($requested === '' || strpos($requested, '..') !== false) {
    http_response_code(404);
    exit('Not Found');
}

$base = realpath(__DIR__ . '/../by');
if ($base === false) {
    http_response_code(404);
    exit('Not Found');
}

$target = realpath($base . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $requested));
if ($target === false || strpos($target, $base) !== 0 || !is_file($target)) {
    http_response_code(404);
    exit('Not Found');
}

$ext = strtolower((string)pathinfo($target, PATHINFO_EXTENSION));
$mimes = [
    'css' => 'text/css; charset=UTF-8',
    'js' => 'application/javascript; charset=UTF-8',
    'svg' => 'image/svg+xml',
    'png' => 'image/png',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'webp' => 'image/webp',
    'ico' => 'image/x-icon',
    'woff' => 'font/woff',
    'woff2' => 'font/woff2',
    'ttf' => 'font/ttf',
    'eot' => 'application/vnd.ms-fontobject',
    'json' => 'application/json; charset=UTF-8',
];

if (!isset($mimes[$ext])) {
    http_response_code(403);
    exit('Forbidden');
}

header('Content-Type: ' . $mimes[$ext]);
header('Cache-Control: public, max-age=86400');
header('Content-Length: ' . (string)filesize($target));
readfile($target);
exit;
