Spaces:
Running
Running
Download app/Controllers/ImageController.php from buddhaword/web: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/buddhaword/web/resolve/main/app/Controllers/ImageController.php
- Command line
-
hf download hf://spaces/buddhaword/web/app/Controllers/ImageController.php
-
curl -L -o ImageController.php https://huggingface.co/spaces/buddhaword/web/resolve/main/app/Controllers/ImageController.php
17.2 kB
| namespace App\Controllers; | |
| /** | |
| * Serves mirrored cover images and proxies/caches remote images. | |
| * | |
| * All remote fetches are restricted to public IPv4 addresses (no localhost, | |
| * private ranges or link-local), redirects are re-validated, response size is | |
| * capped, and every image is decoded + re-encoded before it is stored. That | |
| * keeps /img from becoming an SSRF gadget while still letting the site recover | |
| * covers that were never mirrored. | |
| */ | |
| class ImageController { | |
| private const MAX_BYTES = 8 * 1024 * 1024; | |
| private const MAX_REDIRECTS = 3; | |
| private const FETCH_ATTEMPTS = 2; | |
| private const FAILURE_TTL = 900; // 15 min: do not hammer a dead imgbb | |
| // imgbb's 180x180 "imgbb.com service unavailable" placeholder. | |
| private const IMGBB_PLACEHOLDER_SHA256 = '3924575580e7b987e65ce7de63a3a51655e9c2abaafdf76d204174d1992c8a04'; | |
| /** GET /img?src=<base64url> — cached proxy for arbitrary remote images. */ | |
| public function serve() { | |
| $encoded = $_GET['src'] ?? ''; | |
| if (!is_string($encoded) || $encoded === '' || strlen($encoded) > 4096) { | |
| $this->fallback('assets/images/logo.png'); | |
| } | |
| $url = imageB64UrlDecode($encoded); | |
| if (!$url || !isRemoteImageUrl($url)) { | |
| $this->fallback('assets/images/logo.png'); | |
| } | |
| $key = imageCacheKey($url); | |
| $file = findImageCacheFile($key); | |
| if ($file !== null) { | |
| $this->sendFile($file); | |
| } | |
| $failKey = 'img-' . $key; | |
| if ($this->isFailureFresh($failKey)) { | |
| $this->fallback('assets/images/logo.png'); | |
| } | |
| $file = $this->fetchAndStore($url, $key, 100, 100, 1600, 2400); | |
| if ($file !== null) { | |
| $this->sendFile($file); | |
| } | |
| // Try alternative proxy if direct fetch failed (imgbb often blocks) | |
| if (stripos($url, 'i.ibb.co') !== false || stripos($url, 'ibb.co') !== false) { | |
| $proxied = 'https://wsrv.nl/?url=' . rawurlencode($url) . '&w=800&h=1200&fit=cover&q=80&output=webp'; | |
| $file = $this->fetchAndStore($proxied, $key, 100, 100, 1600, 2400); | |
| if ($file !== null) { | |
| $this->sendFile($file); | |
| } | |
| } | |
| $this->markFailure($failKey); | |
| $this->fallback('assets/images/book-placeholder.svg'); | |
| } | |
| /** GET /cover/book-<ID> or /cover/calendar-<ID> — mirror on first request. */ | |
| public function cover($name) { | |
| $name = preg_replace('/[^A-Za-z0-9_-]/', '', (string) $name); | |
| if ($name === '' || strlen($name) > 80) { | |
| $this->fallback('assets/images/book-placeholder.svg'); | |
| } | |
| $file = findImageCacheFile($name); | |
| if ($file !== null) { | |
| $this->sendFile($file); | |
| } | |
| if ($this->isFailureFresh($name)) { | |
| $this->fallback($this->coverFallback($name)); | |
| } | |
| $sources = []; | |
| $minW = 200; | |
| $minH = 200; | |
| if (strpos($name, 'book-') === 0) { | |
| $sources = $this->bookImageSources(substr($name, 5)); | |
| } elseif (strpos($name, 'calendar-') === 0) { | |
| $sources = $this->calendarImageSources(substr($name, 9)); | |
| $minH = 120; | |
| } else { | |
| $this->fallback('assets/images/book-placeholder.svg'); | |
| } | |
| foreach ($sources as $source) { | |
| $file = $this->fetchAndStore($source, $name, $minW, $minH, 1200, 1800); | |
| if ($file !== null) { | |
| $this->sendFile($file); | |
| } | |
| // If source is imgbb and failed, try wsrv.nl proxy | |
| if (stripos($source, 'i.ibb.co') !== false || stripos($source, 'ibb.co') !== false) { | |
| $proxied = 'https://wsrv.nl/?url=' . rawurlencode($source) . '&w=800&h=1200&fit=cover&q=80&output=webp'; | |
| $file = $this->fetchAndStore($proxied, $name, $minW, $minH, 1200, 1800); | |
| if ($file !== null) { | |
| $this->sendFile($file); | |
| } | |
| } | |
| } | |
| $this->markFailure($name); | |
| $this->fallback($this->coverFallback($name)); | |
| } | |
| private function coverFallback($name) { | |
| return strpos($name, 'book-') === 0 | |
| ? 'assets/images/book-placeholder.svg' | |
| : 'assets/images/logo.png'; | |
| } | |
| /** Read the raw cached sheet data (the model transforms image fields at runtime). */ | |
| private function rawRows($cacheFile) { | |
| $json = function_exists('readCache') ? readCache($cacheFile, PHP_INT_MAX) : null; | |
| if ($json === null) { | |
| $path = __DIR__ . '/../../storage/cache/' . $cacheFile; | |
| $json = is_file($path) ? @file_get_contents($path) : null; | |
| } | |
| if ($json === null) { | |
| return [null, []]; | |
| } | |
| $data = json_decode($json, true); | |
| if (!isset($data['values']) || !is_array($data['values']) || count($data['values']) < 2) { | |
| return [null, []]; | |
| } | |
| $headers = array_shift($data['values']); | |
| return [is_array($headers) ? $headers : null, $data['values']]; | |
| } | |
| /** Original imgbb image first, then reliable Google Drive thumbnails. */ | |
| private function bookImageSources($id) { | |
| [$headers, $rows] = $this->rawRows('book_api.json'); | |
| if (!$headers) { | |
| return []; | |
| } | |
| $idIdx = array_search('ID', $headers, true); | |
| $imgIdx = array_search('imageURL', $headers, true); | |
| $linkIdx = array_search('link', $headers, true); | |
| if ($idIdx === false) { | |
| return []; | |
| } | |
| foreach ($rows as $row) { | |
| if ((string) ($row[$idIdx] ?? '') !== (string) $id) { | |
| continue; | |
| } | |
| $sources = []; | |
| $image = trim((string) ($imgIdx !== false ? ($row[$imgIdx] ?? '') : '')); | |
| if ($image !== '') { | |
| $sources[] = $image; | |
| } | |
| $link = (string) ($linkIdx !== false ? ($row[$linkIdx] ?? '') : ''); | |
| if (preg_match('#/d/([A-Za-z0-9_-]+)#', $link, $m)) { | |
| $sources[] = 'https://drive.google.com/thumbnail?id=' . $m[1] . '&sz=w600'; | |
| $sources[] = 'https://lh3.googleusercontent.com/d/' . $m[1] . '=w800'; | |
| } | |
| return array_values(array_unique($sources)); | |
| } | |
| return []; | |
| } | |
| /** Calendar rows have no ID column — the model assigns ID = row index + 1. */ | |
| private function calendarImageSources($id) { | |
| [$headers, $rows] = $this->rawRows('calendar_api.json'); | |
| if (!$headers) { | |
| return []; | |
| } | |
| $posterIdx = array_search('poster', $headers, true); | |
| $idIdx = array_search('ID', $headers, true); | |
| if ($posterIdx === false) { | |
| return []; | |
| } | |
| if ($idIdx !== false) { | |
| foreach ($rows as $row) { | |
| if ((string) ($row[$idIdx] ?? '') === (string) $id) { | |
| $poster = trim((string) ($row[$posterIdx] ?? '')); | |
| return $poster !== '' ? [$poster] : []; | |
| } | |
| } | |
| return []; | |
| } | |
| $row = $rows[((int) $id) - 1] ?? null; | |
| if (!is_array($row)) { | |
| return []; | |
| } | |
| $poster = trim((string) ($row[$posterIdx] ?? '')); | |
| return $poster !== '' ? [$poster] : []; | |
| } | |
| /** | |
| * Download, validate, resize and store an image. Returns the saved path. | |
| */ | |
| private function fetchAndStore($url, $name, $minW, $minH, $maxW, $maxH) { | |
| $img = $this->fetchRemoteImage($url, $minW, $minH); | |
| if ($img === null) { | |
| return null; | |
| } | |
| $w = imagesx($img); | |
| $h = imagesy($img); | |
| $scale = min(1, $maxW / max(1, $w), $maxH / max(1, $h)); | |
| $nw = max(1, (int) round($w * $scale)); | |
| $nh = max(1, (int) round($h * $scale)); | |
| $dst = imagecreatetruecolor($nw, $nh); | |
| if ($dst === false) { | |
| imagedestroy($img); | |
| return null; | |
| } | |
| $white = imagecolorallocate($dst, 255, 255, 255); | |
| imagefill($dst, 0, 0, $white); | |
| imagecopyresampled($dst, $img, 0, 0, 0, 0, $nw, $nh, $w, $h); | |
| imagedestroy($img); | |
| $publicDir = imageCacheDir(); | |
| $storageDir = imageStorageCacheDir(); | |
| $dir = (is_dir($publicDir) || @mkdir($publicDir, 0777, true)) && is_writable($publicDir) | |
| ? $publicDir | |
| : $storageDir; | |
| if (!is_dir($dir)) { | |
| @mkdir($dir, 0777, true); | |
| } | |
| $file = $dir . '/' . $name . '.jpg'; | |
| $tmp = $file . '.' . getmypid() . '.' . mt_rand(1000, 9999) . '.tmp'; | |
| $ok = @imagejpeg($dst, $tmp, 86); | |
| imagedestroy($dst); | |
| if (!$ok || !@filesize($tmp)) { | |
| @unlink($tmp); | |
| return null; | |
| } | |
| if (!@rename($tmp, $file)) { | |
| @unlink($tmp); | |
| return null; | |
| } | |
| @chmod($file, 0644); | |
| return $file; | |
| } | |
| /** | |
| * Fetch one remote image and return a validated GD handle (or null). | |
| * Retries transient imgbb 503s; rejects imgbb's service-unavailable image. | |
| */ | |
| private function fetchRemoteImage($url, $minW, $minH) { | |
| for ($attempt = 0; $attempt < self::FETCH_ATTEMPTS; $attempt++) { | |
| $body = $this->downloadOnce($url); | |
| if ($body !== null && strlen($body) > 200) { | |
| if (hash('sha256', $body) === self::IMGBB_PLACEHOLDER_SHA256) { | |
| // Known placeholder. A retry occasionally returns the real image. | |
| usleep(350000); | |
| continue; | |
| } | |
| $img = @imagecreatefromstring($body); | |
| if ($img !== false && $img !== null) { | |
| $w = imagesx($img); | |
| $h = imagesy($img); | |
| if ($w >= $minW && $h >= $minH) { | |
| return $img; | |
| } | |
| imagedestroy($img); | |
| } | |
| } | |
| if ($attempt + 1 < self::FETCH_ATTEMPTS) { | |
| usleep(350000); | |
| } | |
| } | |
| return null; | |
| } | |
| /** One GET, following at most a few manually validated redirects. */ | |
| private function downloadOnce($url) { | |
| for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) { | |
| $parts = parse_url($url); | |
| if (!$parts || empty($parts['scheme']) || empty($parts['host'])) { | |
| return null; | |
| } | |
| $scheme = strtolower($parts['scheme']); | |
| if (!in_array($scheme, ['http', 'https'], true)) { | |
| return null; | |
| } | |
| if (isset($parts['user']) || isset($parts['pass'])) { | |
| return null; | |
| } | |
| $host = $parts['host']; | |
| $port = isset($parts['port']) ? (int) $parts['port'] : ($scheme === 'https' ? 443 : 80); | |
| if (!in_array($port, [80, 443], true)) { | |
| return null; | |
| } | |
| $ip = $this->firstPublicIp($host); | |
| if ($ip === null) { | |
| return null; | |
| } | |
| $result = $this->curlGet($url, $host, $ip, $port); | |
| if ($result === null) { | |
| return null; | |
| } | |
| $status = (int) $result['status']; | |
| if (in_array($status, [301, 302, 303, 307, 308], true)) { | |
| $next = $result['redirect']; | |
| if (!$next) { | |
| return null; | |
| } | |
| $url = $next; | |
| continue; | |
| } | |
| if ($status !== 200) { | |
| return null; | |
| } | |
| $type = strtolower(trim(explode(';', (string) $result['type'])[0])); | |
| if ($type !== '' && !in_array($type, [ | |
| 'image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif', 'application/octet-stream', | |
| ], true)) { | |
| return null; | |
| } | |
| return $result['body']; | |
| } | |
| return null; | |
| } | |
| private function firstPublicIp($host) { | |
| $host = trim($host, '[]'); | |
| if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { | |
| return $this->isPublicIp($host) ? $host : null; | |
| } | |
| $ips = @gethostbynamel($host); | |
| if (!$ips) { | |
| return null; | |
| } | |
| foreach ($ips as $ip) { | |
| if ($this->isPublicIp($ip)) { | |
| return $ip; | |
| } | |
| } | |
| return null; | |
| } | |
| private function isPublicIp($ip) { | |
| if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { | |
| return false; | |
| } | |
| $p = array_map('intval', explode('.', $ip)); | |
| // Carrier-grade NAT 100.64.0.0/10 (not covered by PHP's NO_PRIV_RANGE flag). | |
| if ($p[0] === 100 && $p[1] >= 64 && $p[1] <= 127) { | |
| return false; | |
| } | |
| return true; | |
| } | |
| private function curlGet($url, $host, $ip, $port) { | |
| $ch = curl_init($url); | |
| if ($ch === false) { | |
| return null; | |
| } | |
| $body = ''; | |
| $tooLarge = false; | |
| curl_setopt_array($ch, [ | |
| CURLOPT_RETURNTRANSFER => false, | |
| CURLOPT_HEADER => false, | |
| CURLOPT_FOLLOWLOCATION => false, | |
| CURLOPT_TIMEOUT => 12, | |
| CURLOPT_CONNECTTIMEOUT => 6, | |
| CURLOPT_SSL_VERIFYPEER => true, | |
| CURLOPT_SSL_VERIFYHOST => 2, | |
| CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, | |
| CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, | |
| CURLOPT_RESOLVE => [$host . ':' . $port . ':' . $ip], | |
| CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36', | |
| CURLOPT_HTTPHEADER => [ | |
| 'Accept: image/avif,image/webp,image/apng,image/*,*/*;q=0.8', | |
| 'Accept-Language: en-US,en;q=0.8', | |
| ], | |
| CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$body, &$tooLarge) { | |
| $body .= $chunk; | |
| if (strlen($body) > self::MAX_BYTES) { | |
| $tooLarge = true; | |
| return 0; | |
| } | |
| return strlen($chunk); | |
| }, | |
| ]); | |
| curl_exec($ch); | |
| $errno = curl_errno($ch); | |
| $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
| $type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE); | |
| $redirect = (string) curl_getinfo($ch, CURLINFO_REDIRECT_URL); | |
| curl_close($ch); | |
| if ($tooLarge || $errno !== 0) { | |
| return null; | |
| } | |
| return [ | |
| 'status' => $status, | |
| 'type' => $type, | |
| 'body' => $body, | |
| 'redirect' => $redirect, | |
| ]; | |
| } | |
| private function failureFile($name) { | |
| $dir = function_exists('getCacheDir') | |
| ? getCacheDir() . '/cover-fails' | |
| : __DIR__ . '/../../storage/cache/cover-fails'; | |
| if (!is_dir($dir)) { | |
| @mkdir($dir, 0777, true); | |
| } | |
| return $dir . '/' . preg_replace('/[^A-Za-z0-9_-]/', '', $name) . '.txt'; | |
| } | |
| private function isFailureFresh($name) { | |
| $file = $this->failureFile($name); | |
| return is_file($file) && (time() - (int) @filemtime($file)) < self::FAILURE_TTL; | |
| } | |
| private function markFailure($name) { | |
| @file_put_contents($this->failureFile($name), (string) time()); | |
| } | |
| private function sendFile($file) { | |
| $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); | |
| $types = [ | |
| 'jpg' => 'image/jpeg', | |
| 'jpeg' => 'image/jpeg', | |
| 'png' => 'image/png', | |
| 'webp' => 'image/webp', | |
| 'gif' => 'image/gif', | |
| ]; | |
| header('Content-Type: ' . ($types[$ext] ?? 'application/octet-stream')); | |
| header('Cache-Control: public, max-age=31536000, immutable'); | |
| header('X-Content-Type-Options: nosniff'); | |
| $size = @filesize($file); | |
| if ($size) { | |
| header('Content-Length: ' . $size); | |
| } | |
| while (ob_get_level()) { | |
| ob_end_clean(); | |
| } | |
| readfile($file); | |
| exit; | |
| } | |
| private function fallback($relative, $maxAge = 300) { | |
| $file = __DIR__ . '/../../public/' . ltrim((string) $relative, '/'); | |
| if (!is_file($file)) { | |
| $file = __DIR__ . '/../../public/assets/images/logo.png'; | |
| } | |
| $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); | |
| $types = [ | |
| 'svg' => 'image/svg+xml', | |
| 'png' => 'image/png', | |
| 'jpg' => 'image/jpeg', | |
| 'jpeg' => 'image/jpeg', | |
| 'webp' => 'image/webp', | |
| ]; | |
| header('Content-Type: ' . ($types[$ext] ?? 'image/png')); | |
| header('Cache-Control: public, max-age=' . (int) $maxAge); | |
| header('X-Content-Type-Options: nosniff'); | |
| $size = @filesize($file); | |
| if ($size) { | |
| header('Content-Length: ' . $size); | |
| } | |
| while (ob_get_level()) { | |
| ob_end_clean(); | |
| } | |
| readfile($file); | |
| exit; | |
| } | |
| } | |