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