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