File size: 5,597 Bytes
4f3a06d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1790e5d
 
 
 
 
4f3a06d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php
/**
 * Image helpers.
 *
 * Book covers and calendar posters used to be linked straight to i.ibb.co (imgbb).
 * When imgbb is unavailable it answers HTTP 200 with a 180x180 blue
 * "imgbb.com service unavailable" image, which made every card in every list show
 * the same broken placeholder. We now keep cover images on local disk and only
 * fall back to a server-side proxy for images that have not been mirrored yet.
 */

/** Absolute directory where mirrored/generated cover images are stored (public). */
function imageCacheDir() {
    return __DIR__ . '/../../public/assets/covers';
}

/** Absolute fallback directory for runtimes where public/ is read-only. */
function imageStorageCacheDir() {
    // getCacheDir() resolves to a writable temp dir on serverless hosts (Vercel),
    // where the repository itself is mounted read-only.
    if (function_exists('getCacheDir')) {
        return getCacheDir() . '/images';
    }
    return __DIR__ . '/../../storage/cache/images';
}

/** Public URL prefix (relative to the app base) for mirrored covers. */
function imageCacheUrlBase() {
    return 'assets/covers';
}

function isRemoteImageUrl($url) {
    return (bool) preg_match('#^https?://#i', trim((string) $url));
}

function imageCacheKey($url) {
    return sha1(trim((string) $url));
}

function imageB64UrlEncode($value) {
    return rtrim(strtr(base64_encode((string) $value), '+/', '-_'), '=');
}

function imageB64UrlDecode($value) {
    $value = strtr((string) $value, '-_', '+/');
    $pad = strlen($value) % 4;
    if ($pad > 0) {
        $value .= str_repeat('=', 4 - $pad);
    }
    $decoded = base64_decode($value, true);
    return $decoded === false ? null : $decoded;
}

/**
 * Locate a cached image by key (sha1 of source URL or "book-<ID>"/"calendar-<ID>").
 * Checks public first, then the storage fallback. Returns an absolute path or null.
 */
function findImageCacheFile($key, array $exts = ['jpg', 'jpeg', 'png', 'webp', 'gif']) {
    $key = basename((string) $key);
    if ($key === '') {
        return null;
    }
    foreach ([imageCacheDir(), imageStorageCacheDir()] as $dir) {
        foreach ($exts as $ext) {
            $file = $dir . '/' . $key . '.' . $ext;
            if (is_file($file) && @filesize($file) > 0) {
                return $file;
            }
        }
    }
    return null;
}

/** Static URL for a public cached image, or null when it lives in storage/none. */
function publicImageCacheUrl($file) {
    $dir = imageCacheDir();
    if (strpos($file, $dir . '/') !== 0) {
        return null;
    }
    $url = url(imageCacheUrlBase() . '/' . basename($file));
    $mtime = @filemtime($file);
    return $mtime ? $url . '?v=' . $mtime : $url;
}

/**
 * Normalise any image reference for use in an <img src>.
 * - Remote URL already mirrored  -> local static URL (fast, offline-safe)
 * - Remote URL not mirrored yet  -> /img?src=<base64url> (server-side cache/proxy)
 * - Local path/URL               -> unchanged (app base path is kept)
 */
function imageUrl($url, $fallback = 'assets/images/book-placeholder.svg') {
    $url = trim((string) $url);
    if ($url === '') {
        return url($fallback);
    }

    if (!isRemoteImageUrl($url)) {
        if (preg_match('#^(https?:)?//#i', $url) || (isset($url[0]) && $url[0] === '/')) {
            return $url;
        }
        return url($url);
    }

    $file = findImageCacheFile(imageCacheKey($url));
    if ($file !== null) {
        $static = publicImageCacheUrl($file);
        if ($static !== null) {
            return $static;
        }
    }

    return url('/img?src=' . imageB64UrlEncode($url));
}

/**
 * Stable cover URL for a book. Prefers a mirrored local cover, then a dynamic
 * /cover/book-<ID> endpoint that mirrors on first request, then the generic proxy.
 */
function bookCoverUrl(array $book) {
    static $memo = [];

    $id = preg_replace('/[^A-Za-z0-9_-]/', '', (string) ($book['ID'] ?? ''));
    $fallback = 'assets/images/book-placeholder.svg';

    if ($id !== '') {
        $name = 'book-' . $id;
        if (array_key_exists($name, $memo)) {
            return $memo[$name];
        }

        $file = findImageCacheFile($name);
        if ($file !== null) {
            $static = publicImageCacheUrl($file);
            if ($static !== null) {
                return $memo[$name] = $static;
            }
        }
        // Not mirrored yet: let /cover fetch + resize it on demand.
        return $memo[$name] = url('/cover/' . $name);
    }

    return imageUrl($book['imageURL'] ?? '', $fallback);
}

/** Stable cover URL for a calendar event poster. */
function calendarPosterUrl(array $event) {
    static $memo = [];

    $id = preg_replace('/[^A-Za-z0-9_-]/', '', (string) ($event['ID'] ?? ''));
    $fallback = 'assets/images/logo.png';

    if ($id !== '') {
        $name = 'calendar-' . $id;
        if (array_key_exists($name, $memo)) {
            return $memo[$name];
        }

        $file = findImageCacheFile($name);
        if ($file !== null) {
            $static = publicImageCacheUrl($file);
            if ($static !== null) {
                return $memo[$name] = $static;
            }
        }
        return $memo[$name] = url('/cover/' . $name);
    }

    return imageUrl($event['poster'] ?? '', $fallback);
}

/** Absolute image URL for Open Graph / JSON-LD. */
function absoluteImageUrl($url, $fallback = 'assets/images/book-placeholder.svg') {
    $local = imageUrl($url, $fallback);
    if (preg_match('#^https?://#i', $local)) {
        return $local;
    }
    return absoluteUrl(ltrim($local, '/'));
}