]> BookStack Code Mirror - bookstack/blob - app/References/ModelResolvers/ImageModelResolver.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / References / ModelResolvers / ImageModelResolver.php
1 <?php
2
3 namespace BookStack\References\ModelResolvers;
4
5 use BookStack\Uploads\Image;
6 use BookStack\Uploads\ImageStorage;
7
8 class ImageModelResolver implements CrossLinkModelResolver
9 {
10     protected ?string $pattern = null;
11
12     public function resolve(string $link): ?Image
13     {
14         $pattern = $this->getUrlPattern();
15         $matches = [];
16         $match = preg_match($pattern, $link, $matches);
17         if (!$match) {
18             return null;
19         }
20
21         $path = $matches[2];
22
23         // Strip thumbnail element from path if existing
24         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
25             $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
26             $missingExtension = !str_contains($part, '.');
27
28             return !($resizedDir && $missingExtension);
29         });
30
31         // Build a database-format image path and search for the image entry
32         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
33
34         return Image::query()->where('path', '=', $fullPath)->first();
35     }
36
37     /**
38      * Get the regex pattern to identify image URLs.
39      * Caches the pattern since it requires looking up to settings/config.
40      */
41     protected function getUrlPattern(): string
42     {
43         if ($this->pattern) {
44             return $this->pattern;
45         }
46
47         $urls = [url('/uploads/images')];
48         $baseImageUrl = ImageStorage::getPublicUrl('/uploads/images');
49         if ($baseImageUrl !== $urls[0]) {
50             $urls[] = $baseImageUrl;
51         }
52
53         $imageUrlRegex = implode('|', array_map(fn ($url) => preg_quote($url, '/'), $urls));
54         $this->pattern = '/^(' . $imageUrlRegex . ')\/(.+)/';
55
56         return $this->pattern;
57     }
58 }