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 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
<?php
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;
    }
}