]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
e501cc7b12ded686776c7ba4d80b3d25c9fc8389
[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         $disk = $this->storage->getDisk($image->type);
157         $disk->destroyAllMatchingNameFromPath($image->path);
158         $image->delete();
159     }
160
161     /**
162      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
163      * Checks based off of only the image name.
164      * Could be much improved to be more specific but kept it generic for now to be safe.
165      *
166      * Returns the path of the images that would be/have been deleted.
167      */
168     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
169     {
170         $types = ['gallery', 'drawio'];
171         $deletedPaths = [];
172
173         Image::query()->whereIn('type', $types)
174             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
175                 /** @var Image $image */
176                 foreach ($images as $image) {
177                     $searchQuery = '%' . basename($image->path) . '%';
178                     $inPage = DB::table('pages')
179                             ->where('html', 'like', $searchQuery)->count() > 0;
180
181                     $inRevision = false;
182                     if ($checkRevisions) {
183                         $inRevision = DB::table('page_revisions')
184                                 ->where('html', 'like', $searchQuery)->count() > 0;
185                     }
186
187                     if (!$inPage && !$inRevision) {
188                         $deletedPaths[] = $image->path;
189                         if (!$dryRun) {
190                             $this->destroy($image);
191                         }
192                     }
193                 }
194             });
195
196         return $deletedPaths;
197     }
198
199     /**
200      * Convert an image URI to a Base64 encoded string.
201      * Attempts to convert the URL to a system storage url then
202      * fetch the data from the disk or storage location.
203      * Returns null if the image data cannot be fetched from storage.
204      */
205     public function imageUrlToBase64(string $url): ?string
206     {
207         $storagePath = $this->storage->urlToPath($url);
208         if (empty($url) || is_null($storagePath)) {
209             return null;
210         }
211
212         // Apply access control when local_secure_restricted images are active
213         if ($this->storage->usingSecureRestrictedImages()) {
214             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
215                 return null;
216             }
217         }
218
219         $disk = $this->storage->getDisk();
220         $imageData = null;
221         if ($disk->exists($storagePath)) {
222             $imageData = $disk->get($storagePath);
223         }
224
225         if (is_null($imageData)) {
226             return null;
227         }
228
229         $extension = pathinfo($url, PATHINFO_EXTENSION);
230         if ($extension === 'svg') {
231             $extension = 'svg+xml';
232         }
233
234         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
235     }
236
237     /**
238      * Check if the given path exists and is accessible in the local secure image system.
239      * Returns false if local_secure is not in use, if the file does not exist, if the
240      * file is likely not a valid image, or if permission does not allow access.
241      */
242     public function pathAccessibleInLocalSecure(string $imagePath): bool
243     {
244         $disk = $this->storage->getDisk('gallery');
245
246         if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
247             return false;
248         }
249
250         // Check local_secure is active
251         return $disk->usingSecureImages()
252             // Check the image file exists
253             && $disk->exists($imagePath)
254             // Check the file is likely an image file
255             && str_starts_with($disk->mimeType($imagePath), 'image/');
256     }
257
258     /**
259      * Check that the current user has access to the relation
260      * of the image at the given path.
261      */
262     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
263     {
264         if (str_starts_with($path, 'uploads/images/')) {
265             $path = substr($path, 15);
266         }
267
268         // Strip thumbnail element from path if existing
269         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
270             $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
271             $missingExtension = !str_contains($part, '.');
272
273             return !($resizedDir && $missingExtension);
274         });
275
276         // Build a database-format image path and search for the image entry
277         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
278         $image = Image::query()->where('path', '=', $fullPath)->first();
279
280         if (is_null($image)) {
281             return false;
282         }
283
284         $imageType = $image->type;
285
286         // Allow user or system (logo) images
287         // (No specific relation control but may still have access controlled by auth)
288         if ($imageType === 'user' || $imageType === 'system') {
289             return true;
290         }
291
292         if ($imageType === 'gallery' || $imageType === 'drawio') {
293             return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
294         }
295
296         if ($imageType === 'cover_book') {
297             return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
298         }
299
300         if ($imageType === 'cover_bookshelf') {
301             return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
302         }
303
304         return false;
305     }
306
307     /**
308      * For the given path, if existing, provide a response that will stream the image contents.
309      */
310     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
311     {
312         $disk = $this->storage->getDisk($imageType);
313
314         return $disk->response($path);
315     }
316
317     /**
318      * Check if the given image extension is supported by BookStack.
319      * The extension must not be altered in this function. This check should provide a guarantee
320      * that the provided extension is safe to use for the image to be saved.
321      */
322     public static function isExtensionSupported(string $extension): bool
323     {
324         return in_array($extension, static::$supportedExtensions);
325     }
326 }