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