]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Comments: Added HTML filter on load, tinymce elem filtering
[bookstack] / app / Uploads / ImageService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Exceptions\ImageUploadException;
9 use Exception;
10 use Illuminate\Support\Facades\DB;
11 use Illuminate\Support\Facades\Log;
12 use Illuminate\Support\Str;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
14 use Symfony\Component\HttpFoundation\StreamedResponse;
15
16 class ImageService
17 {
18     protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
19
20     public function __construct(
21         protected ImageStorage $storage,
22         protected ImageResizer $resizer,
23     ) {
24     }
25
26     /**
27      * Saves a new image from an upload.
28      *
29      * @throws ImageUploadException
30      */
31     public function saveNewFromUpload(
32         UploadedFile $uploadedFile,
33         string $type,
34         int $uploadedTo = 0,
35         int $resizeWidth = null,
36         int $resizeHeight = null,
37         bool $keepRatio = true
38     ): Image {
39         $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      * Destroy an image along with its revisions, thumbnails and remaining folders.
139      *
140      * @throws Exception
141      */
142     public function destroy(Image $image): void
143     {
144         $disk = $this->storage->getDisk($image->type);
145         $disk->destroyAllMatchingNameFromPath($image->path);
146         $image->delete();
147     }
148
149     /**
150      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
151      * Checks based off of only the image name.
152      * Could be much improved to be more specific but kept it generic for now to be safe.
153      *
154      * Returns the path of the images that would be/have been deleted.
155      */
156     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
157     {
158         $types = ['gallery', 'drawio'];
159         $deletedPaths = [];
160
161         Image::query()->whereIn('type', $types)
162             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
163                 /** @var Image $image */
164                 foreach ($images as $image) {
165                     $searchQuery = '%' . basename($image->path) . '%';
166                     $inPage = DB::table('pages')
167                             ->where('html', 'like', $searchQuery)->count() > 0;
168
169                     $inRevision = false;
170                     if ($checkRevisions) {
171                         $inRevision = DB::table('page_revisions')
172                                 ->where('html', 'like', $searchQuery)->count() > 0;
173                     }
174
175                     if (!$inPage && !$inRevision) {
176                         $deletedPaths[] = $image->path;
177                         if (!$dryRun) {
178                             $this->destroy($image);
179                         }
180                     }
181                 }
182             });
183
184         return $deletedPaths;
185     }
186
187     /**
188      * Convert an image URI to a Base64 encoded string.
189      * Attempts to convert the URL to a system storage url then
190      * fetch the data from the disk or storage location.
191      * Returns null if the image data cannot be fetched from storage.
192      */
193     public function imageUrlToBase64(string $url): ?string
194     {
195         $storagePath = $this->storage->urlToPath($url);
196         if (empty($url) || is_null($storagePath)) {
197             return null;
198         }
199
200         // Apply access control when local_secure_restricted images are active
201         if ($this->storage->usingSecureRestrictedImages()) {
202             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
203                 return null;
204             }
205         }
206
207         $disk = $this->storage->getDisk();
208         $imageData = null;
209         if ($disk->exists($storagePath)) {
210             $imageData = $disk->get($storagePath);
211         }
212
213         if (is_null($imageData)) {
214             return null;
215         }
216
217         $extension = pathinfo($url, PATHINFO_EXTENSION);
218         if ($extension === 'svg') {
219             $extension = 'svg+xml';
220         }
221
222         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
223     }
224
225     /**
226      * Check if the given path exists and is accessible in the local secure image system.
227      * Returns false if local_secure is not in use, if the file does not exist, if the
228      * file is likely not a valid image, or if permission does not allow access.
229      */
230     public function pathAccessibleInLocalSecure(string $imagePath): bool
231     {
232         $disk = $this->storage->getDisk('gallery');
233
234         if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
235             return false;
236         }
237
238         // Check local_secure is active
239         return $disk->usingSecureImages()
240             // Check the image file exists
241             && $disk->exists($imagePath)
242             // Check the file is likely an image file
243             && str_starts_with($disk->mimeType($imagePath), 'image/');
244     }
245
246     /**
247      * Check that the current user has access to the relation
248      * of the image at the given path.
249      */
250     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
251     {
252         if (str_starts_with($path, 'uploads/images/')) {
253             $path = substr($path, 15);
254         }
255
256         // Strip thumbnail element from path if existing
257         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
258             $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
259             $missingExtension = !str_contains($part, '.');
260
261             return !($resizedDir && $missingExtension);
262         });
263
264         // Build a database-format image path and search for the image entry
265         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
266         $image = Image::query()->where('path', '=', $fullPath)->first();
267
268         if (is_null($image)) {
269             return false;
270         }
271
272         $imageType = $image->type;
273
274         // Allow user or system (logo) images
275         // (No specific relation control but may still have access controlled by auth)
276         if ($imageType === 'user' || $imageType === 'system') {
277             return true;
278         }
279
280         if ($imageType === 'gallery' || $imageType === 'drawio') {
281             return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
282         }
283
284         if ($imageType === 'cover_book') {
285             return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
286         }
287
288         if ($imageType === 'cover_bookshelf') {
289             return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
290         }
291
292         return false;
293     }
294
295     /**
296      * For the given path, if existing, provide a response that will stream the image contents.
297      */
298     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
299     {
300         $disk = $this->storage->getDisk($imageType);
301
302         return $disk->response($path);
303     }
304
305     /**
306      * Check if the given image extension is supported by BookStack.
307      * The extension must not be altered in this function. This check should provide a guarantee
308      * that the provided extension is safe to use for the image to be saved.
309      */
310     public static function isExtensionSupported(string $extension): bool
311     {
312         return in_array($extension, static::$supportedExtensions);
313     }
314 }