]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Images: Added base avif support
[bookstack] / app / Uploads / ImageService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Entities\Queries\EntityQueries;
6 use BookStack\Exceptions\ImageUploadException;
7 use Exception;
8 use Illuminate\Support\Facades\DB;
9 use Illuminate\Support\Facades\Log;
10 use Illuminate\Support\Str;
11 use Symfony\Component\HttpFoundation\File\UploadedFile;
12 use Symfony\Component\HttpFoundation\StreamedResponse;
13
14 class ImageService
15 {
16     protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif'];
17
18     public function __construct(
19         protected ImageStorage $storage,
20         protected ImageResizer $resizer,
21         protected EntityQueries $queries,
22     ) {
23     }
24
25     /**
26      * Saves a new image from an upload.
27      *
28      * @throws ImageUploadException
29      */
30     public function saveNewFromUpload(
31         UploadedFile $uploadedFile,
32         string $type,
33         int $uploadedTo = 0,
34         ?int $resizeWidth = null,
35         ?int $resizeHeight = null,
36         bool $keepRatio = true,
37         string $imageName = '',
38     ): Image {
39         $imageName = $imageName ?: $uploadedFile->getClientOriginalName();
40         $imageData = file_get_contents($uploadedFile->getRealPath());
41
42         if ($resizeWidth !== null || $resizeHeight !== null) {
43             $imageData = $this->resizer->resizeImageData($imageData, $resizeWidth, $resizeHeight, $keepRatio);
44         }
45
46         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
47     }
48
49     /**
50      * Save a new image from a uri-encoded base64 string of data.
51      *
52      * @throws ImageUploadException
53      */
54     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
55     {
56         $splitData = explode(';base64,', $base64Uri);
57         if (count($splitData) < 2) {
58             throw new ImageUploadException('Invalid base64 image data provided');
59         }
60         $data = base64_decode($splitData[1]);
61
62         return $this->saveNew($name, $data, $type, $uploadedTo);
63     }
64
65     /**
66      * Save a new image into storage.
67      *
68      * @throws ImageUploadException
69      */
70     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
71     {
72         $disk = $this->storage->getDisk($type);
73         $secureUploads = setting('app-secure-images');
74         $fileName = $this->storage->cleanImageFileName($imageName);
75
76         $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
77
78         while ($disk->exists($imagePath . $fileName)) {
79             $fileName = Str::random(3) . $fileName;
80         }
81
82         $fullPath = $imagePath . $fileName;
83         if ($secureUploads) {
84             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
85         }
86
87         try {
88             $disk->put($fullPath, $imageData, true);
89         } catch (Exception $e) {
90             Log::error('Error when attempting image upload:' . $e->getMessage());
91
92             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
93         }
94
95         $imageDetails = [
96             'name'        => $imageName,
97             'path'        => $fullPath,
98             'url'         => $this->storage->getPublicUrl($fullPath),
99             'type'        => $type,
100             'uploaded_to' => $uploadedTo,
101         ];
102
103         if (user()->id !== 0) {
104             $userId = user()->id;
105             $imageDetails['created_by'] = $userId;
106             $imageDetails['updated_by'] = $userId;
107         }
108
109         $image = (new Image())->forceFill($imageDetails);
110         $image->save();
111
112         return $image;
113     }
114
115     /**
116      * Replace an existing image file in the system using the given file.
117      */
118     public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
119     {
120         $imageData = file_get_contents($file->getRealPath());
121         $disk = $this->storage->getDisk($type);
122         $disk->put($path, $imageData);
123     }
124
125     /**
126      * Get the raw data content from an image.
127      *
128      * @throws Exception
129      */
130     public function getImageData(Image $image): string
131     {
132         $disk = $this->storage->getDisk();
133
134         return $disk->get($image->path);
135     }
136
137     /**
138      * Get the raw data content from an image.
139      *
140      * @throws Exception
141      * @returns ?resource
142      */
143     public function getImageStream(Image $image): mixed
144     {
145         $disk = $this->storage->getDisk();
146
147         return $disk->stream($image->path);
148     }
149
150     /**
151      * Destroy an image along with its revisions, thumbnails and remaining folders.
152      *
153      * @throws Exception
154      */
155     public function destroy(Image $image): void
156     {
157         $this->destroyFileAtPath($image->type, $image->path);
158         $image->delete();
159     }
160
161     /**
162      * Destroy the underlying image file at the given path.
163      */
164     public function destroyFileAtPath(string $type, string $path): void
165     {
166         $disk = $this->storage->getDisk($type);
167         $disk->destroyAllMatchingNameFromPath($path);
168     }
169
170     /**
171      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
172      * Checks based off of only the image name.
173      * Could be much improved to be more specific but kept it generic for now to be safe.
174      *
175      * Returns the path of the images that would be/have been deleted.
176      */
177     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
178     {
179         $types = ['gallery', 'drawio'];
180         $deletedPaths = [];
181
182         Image::query()->whereIn('type', $types)
183             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
184                 /** @var Image $image */
185                 foreach ($images as $image) {
186                     $searchQuery = '%' . basename($image->path) . '%';
187                     $inPage = DB::table('pages')
188                             ->where('html', 'like', $searchQuery)->count() > 0;
189
190                     $inRevision = false;
191                     if ($checkRevisions) {
192                         $inRevision = DB::table('page_revisions')
193                                 ->where('html', 'like', $searchQuery)->count() > 0;
194                     }
195
196                     if (!$inPage && !$inRevision) {
197                         $deletedPaths[] = $image->path;
198                         if (!$dryRun) {
199                             $this->destroy($image);
200                         }
201                     }
202                 }
203             });
204
205         return $deletedPaths;
206     }
207
208     /**
209      * Convert an image URI to a Base64 encoded string.
210      * Attempts to convert the URL to a system storage url then
211      * fetch the data from the disk or storage location.
212      * Returns null if the image data cannot be fetched from storage.
213      */
214     public function imageUrlToBase64(string $url): ?string
215     {
216         $storagePath = $this->storage->urlToPath($url);
217         if (empty($url) || is_null($storagePath)) {
218             return null;
219         }
220
221         // Apply access control when local_secure_restricted images are active
222         if ($this->storage->usingSecureRestrictedImages()) {
223             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
224                 return null;
225             }
226         }
227
228         $disk = $this->storage->getDisk();
229         $imageData = null;
230         if ($disk->exists($storagePath)) {
231             $imageData = $disk->get($storagePath);
232         }
233
234         if (is_null($imageData)) {
235             return null;
236         }
237
238         $extension = pathinfo($url, PATHINFO_EXTENSION);
239         if ($extension === 'svg') {
240             $extension = 'svg+xml';
241         }
242
243         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
244     }
245
246     /**
247      * Check if the given path exists and is accessible in the local secure image system.
248      * Returns false if local_secure is not in use, if the file does not exist, if the
249      * file is likely not a valid image, or if permission does not allow access.
250      */
251     public function pathAccessibleInLocalSecure(string $imagePath): bool
252     {
253         $disk = $this->storage->getDisk('gallery');
254
255         if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
256             return false;
257         }
258
259         // Check local_secure is active
260         return $disk->usingSecureImages()
261             // Check the image file exists
262             && $disk->exists($imagePath)
263             // Check the file is likely an image file
264             && str_starts_with($disk->mimeType($imagePath), 'image/');
265     }
266
267     /**
268      * Check that the current user has access to the relation
269      * of the image at the given path.
270      */
271     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
272     {
273         if (str_starts_with($path, 'uploads/images/')) {
274             $path = substr($path, 15);
275         }
276
277         // Strip thumbnail element from path if existing
278         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
279             $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
280             $missingExtension = !str_contains($part, '.');
281
282             return !($resizedDir && $missingExtension);
283         });
284
285         // Build a database-format image path and search for the image entry
286         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
287         $image = Image::query()->where('path', '=', $fullPath)->first();
288
289         if (is_null($image)) {
290             return false;
291         }
292
293         $imageType = $image->type;
294
295         // Allow user or system (logo) images
296         // (No specific relation control but may still have access controlled by auth)
297         if ($imageType === 'user' || $imageType === 'system') {
298             return true;
299         }
300
301         if ($imageType === 'gallery' || $imageType === 'drawio') {
302             return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
303         }
304
305         if ($imageType === 'cover_book') {
306             return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
307         }
308
309         if ($imageType === 'cover_bookshelf') {
310             return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
311         }
312
313         return false;
314     }
315
316     /**
317      * For the given path, if existing, provide a response that will stream the image contents.
318      */
319     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
320     {
321         $disk = $this->storage->getDisk($imageType);
322
323         return $disk->response($path);
324     }
325
326     /**
327      * Check if the given image extension is supported by BookStack.
328      * The extension must not be altered in this function. This check should provide a guarantee
329      * that the provided extension is safe to use for the image to be saved.
330      */
331     public static function isExtensionSupported(string $extension): bool
332     {
333         return in_array($extension, static::$supportedExtensions);
334     }
335 }