]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Allow uploads of files containing dots in filename. Closes BookStackApp/BookStack...
[bookstack] / app / Uploads / ImageService.php
1 <?php namespace BookStack\Uploads;
2
3 use BookStack\Exceptions\ImageUploadException;
4 use DB;
5 use ErrorException;
6 use Exception;
7 use Illuminate\Contracts\Cache\Repository as Cache;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
10 use Illuminate\Contracts\Filesystem\FileNotFoundException;
11 use Illuminate\Support\Str;
12 use Intervention\Image\Exception\NotSupportedException;
13 use Intervention\Image\ImageManager;
14 use Symfony\Component\HttpFoundation\File\UploadedFile;
15
16 class ImageService
17 {
18     protected $imageTool;
19     protected $cache;
20     protected $storageUrl;
21     protected $image;
22     protected $fileSystem;
23
24     /**
25      * ImageService constructor.
26      */
27     public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
28     {
29         $this->image = $image;
30         $this->imageTool = $imageTool;
31         $this->fileSystem = $fileSystem;
32         $this->cache = $cache;
33     }
34
35     /**
36      * Get the storage that will be used for storing images.
37      */
38     protected function getStorage(string $type = ''): FileSystemInstance
39     {
40         $storageType = config('filesystems.images');
41
42         // Ensure system images (App logo) are uploaded to a public space
43         if ($type === 'system' && $storageType === 'local_secure') {
44             $storageType = 'local';
45         }
46
47         return $this->fileSystem->disk($storageType);
48     }
49
50     /**
51      * Saves a new image from an upload.
52      * @return mixed
53      * @throws ImageUploadException
54      */
55     public function saveNewFromUpload(
56         UploadedFile $uploadedFile,
57         string $type,
58         int $uploadedTo = 0,
59         int $resizeWidth = null,
60         int $resizeHeight = null,
61         bool $keepRatio = true
62     ) {
63         $imageName = $this->sanitizeFileName($uploadedFile->getClientOriginalName());
64         $imageData = file_get_contents($uploadedFile->getRealPath());
65
66         if ($resizeWidth !== null || $resizeHeight !== null) {
67             $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
68         }
69
70         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
71     }
72
73     /**
74      * Save a new image from a uri-encoded base64 string of data.
75      * @throws ImageUploadException
76      */
77     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
78     {
79         $splitData = explode(';base64,', $base64Uri);
80         if (count($splitData) < 2) {
81             throw new ImageUploadException("Invalid base64 image data provided");
82         }
83         $data = base64_decode($splitData[1]);
84         return $this->saveNew($name, $data, $type, $uploadedTo);
85     }
86
87     /**
88      * Save a new image into storage.
89      * @throws ImageUploadException
90      */
91     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
92     {
93         $storage = $this->getStorage($type);
94         $secureUploads = setting('app-secure-images');
95         $fileName = $this->cleanImageFileName($imageName);
96
97         $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
98
99         while ($storage->exists($imagePath . $fileName)) {
100             $fileName = Str::random(3) . $fileName;
101         }
102
103         $fullPath = $imagePath . $fileName;
104         if ($secureUploads) {
105             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
106         }
107
108         try {
109             $storage->put($fullPath, $imageData);
110             $storage->setVisibility($fullPath, 'public');
111         } catch (Exception $e) {
112             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
113         }
114
115         $imageDetails = [
116             'name' => $imageName,
117             'path' => $fullPath,
118             'url' => $this->getPublicUrl($fullPath),
119             'type' => $type,
120             'uploaded_to' => $uploadedTo
121         ];
122
123         if (user()->id !== 0) {
124             $userId = user()->id;
125             $imageDetails['created_by'] = $userId;
126             $imageDetails['updated_by'] = $userId;
127         }
128
129         $image = $this->image->newInstance();
130         $image->forceFill($imageDetails)->save();
131         return $image;
132     }
133
134     /**
135      * Clean up an image file name to be both URL and storage safe.
136      */
137     protected function cleanImageFileName(string $name): string
138     {
139         $name = str_replace(' ', '-', $name);
140         $nameParts = explode('.', $name);
141         $extension = array_pop($nameParts);
142         $name = implode('.', $nameParts);
143         $name = Str::slug($name);
144
145         if (strlen($name) === 0) {
146             $name = Str::random(10);
147         }
148
149         return $name . '.' . $extension;
150     }
151
152     /**
153      * Checks if the image is a gif. Returns true if it is, else false.
154      */
155     protected function isGif(Image $image): bool
156     {
157         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
158     }
159
160     /**
161      * Get the thumbnail for an image.
162      * If $keepRatio is true only the width will be used.
163      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
164      * @param Image $image
165      * @param int $width
166      * @param int $height
167      * @param bool $keepRatio
168      * @return string
169      * @throws Exception
170      * @throws ImageUploadException
171      */
172     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
173     {
174         if ($keepRatio && $this->isGif($image)) {
175             return $this->getPublicUrl($image->path);
176         }
177
178         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
179         $imagePath = $image->path;
180         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
181
182         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
183             return $this->getPublicUrl($thumbFilePath);
184         }
185
186         $storage = $this->getStorage($image->type);
187         if ($storage->exists($thumbFilePath)) {
188             return $this->getPublicUrl($thumbFilePath);
189         }
190
191         $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
192
193         $storage->put($thumbFilePath, $thumbData);
194         $storage->setVisibility($thumbFilePath, 'public');
195         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
196
197
198         return $this->getPublicUrl($thumbFilePath);
199     }
200
201     /**
202      * Resize image data.
203      * @param string $imageData
204      * @param int $width
205      * @param int $height
206      * @param bool $keepRatio
207      * @return string
208      * @throws ImageUploadException
209      */
210     protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
211     {
212         try {
213             $thumb = $this->imageTool->make($imageData);
214         } catch (Exception $e) {
215             if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
216                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
217             }
218             throw $e;
219         }
220
221         if ($keepRatio) {
222             $thumb->resize($width, $height, function ($constraint) {
223                 $constraint->aspectRatio();
224                 $constraint->upsize();
225             });
226         } else {
227             $thumb->fit($width, $height);
228         }
229
230         $thumbData = (string)$thumb->encode();
231
232         // Use original image data if we're keeping the ratio
233         // and the resizing does not save any space.
234         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
235             return $imageData;
236         }
237
238         return $thumbData;
239     }
240
241     /**
242      * Get the raw data content from an image.
243      * @throws FileNotFoundException
244      */
245     public function getImageData(Image $image): string
246     {
247         $imagePath = $image->path;
248         $storage = $this->getStorage();
249         return $storage->get($imagePath);
250     }
251
252     /**
253      * Destroy an image along with its revisions, thumbnails and remaining folders.
254      * @throws Exception
255      */
256     public function destroy(Image $image)
257     {
258         $this->destroyImagesFromPath($image->path);
259         $image->delete();
260     }
261
262     /**
263      * Destroys an image at the given path.
264      * Searches for image thumbnails in addition to main provided path.
265      */
266     protected function destroyImagesFromPath(string $path): bool
267     {
268         $storage = $this->getStorage();
269
270         $imageFolder = dirname($path);
271         $imageFileName = basename($path);
272         $allImages = collect($storage->allFiles($imageFolder));
273
274         // Delete image files
275         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
276             return basename($imagePath) === $imageFileName;
277         });
278         $storage->delete($imagesToDelete->all());
279
280         // Cleanup of empty folders
281         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
282         foreach ($foldersInvolved as $directory) {
283             if ($this->isFolderEmpty($storage, $directory)) {
284                 $storage->deleteDirectory($directory);
285             }
286         }
287
288         return true;
289     }
290
291     /**
292      * Check whether or not a folder is empty.
293      */
294     protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
295     {
296         $files = $storage->files($path);
297         $folders = $storage->directories($path);
298         return (count($files) === 0 && count($folders) === 0);
299     }
300
301     /**
302      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
303      * Checks based off of only the image name.
304      * Could be much improved to be more specific but kept it generic for now to be safe.
305      *
306      * Returns the path of the images that would be/have been deleted.
307      */
308     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
309     {
310         $types = ['gallery', 'drawio'];
311         $deletedPaths = [];
312
313         $this->image->newQuery()->whereIn('type', $types)
314             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
315                 foreach ($images as $image) {
316                     $searchQuery = '%' . basename($image->path) . '%';
317                     $inPage = DB::table('pages')
318                             ->where('html', 'like', $searchQuery)->count() > 0;
319
320                     $inRevision = false;
321                     if ($checkRevisions) {
322                         $inRevision = DB::table('page_revisions')
323                                 ->where('html', 'like', $searchQuery)->count() > 0;
324                     }
325
326                     if (!$inPage && !$inRevision) {
327                         $deletedPaths[] = $image->path;
328                         if (!$dryRun) {
329                             $this->destroy($image);
330                         }
331                     }
332                 }
333             });
334         return $deletedPaths;
335     }
336
337     /**
338      * Convert a image URI to a Base64 encoded string.
339      * Attempts to convert the URL to a system storage url then
340      * fetch the data from the disk or storage location.
341      * Returns null if the image data cannot be fetched from storage.
342      * @throws FileNotFoundException
343      */
344     public function imageUriToBase64(string $uri): ?string
345     {
346         $storagePath = $this->imageUrlToStoragePath($uri);
347         if (empty($uri) || is_null($storagePath)) {
348             return null;
349         }
350
351         $storage = $this->getStorage();
352         $imageData = null;
353         if ($storage->exists($storagePath)) {
354             $imageData = $storage->get($storagePath);
355         }
356
357         if (is_null($imageData)) {
358             return null;
359         }
360
361         $extension = pathinfo($uri, PATHINFO_EXTENSION);
362         if ($extension === 'svg') {
363             $extension = 'svg+xml';
364         }
365
366         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
367     }
368
369     /**
370      * Get a storage path for the given image URL.
371      * Ensures the path will start with "uploads/images".
372      * Returns null if the url cannot be resolved to a local URL.
373      */
374     private function imageUrlToStoragePath(string $url): ?string
375     {
376         $url = ltrim(trim($url), '/');
377
378         // Handle potential relative paths
379         $isRelative = strpos($url, 'http') !== 0;
380         if ($isRelative) {
381             if (strpos(strtolower($url), 'uploads/images') === 0) {
382                 return trim($url, '/');
383             }
384             return null;
385         }
386
387         // Handle local images based on paths on the same domain
388         $potentialHostPaths = [
389             url('uploads/images/'),
390             $this->getPublicUrl('/uploads/images/'),
391         ];
392
393         foreach ($potentialHostPaths as $potentialBasePath) {
394             $potentialBasePath = strtolower($potentialBasePath);
395             if (strpos(strtolower($url), $potentialBasePath) === 0) {
396                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
397             }
398         }
399
400         return null;
401     }
402
403     /**
404      * Gets a public facing url for an image by checking relevant environment variables.
405      * If s3-style store is in use it will default to guessing a public bucket URL.
406      */
407     private function getPublicUrl(string $filePath): string
408     {
409         if ($this->storageUrl === null) {
410             $storageUrl = config('filesystems.url');
411
412             // Get the standard public s3 url if s3 is set as storage type
413             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
414             // region-based url will be used to prevent http issues.
415             if ($storageUrl == false && config('filesystems.images') === 's3') {
416                 $storageDetails = config('filesystems.disks.s3');
417                 if (strpos($storageDetails['bucket'], '.') === false) {
418                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
419                 } else {
420                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
421                 }
422             }
423             $this->storageUrl = $storageUrl;
424         }
425
426         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
427         return rtrim($basePath, '/') . $filePath;
428     }
429
430     /**
431      * Returns a sanitized filename with only one file extension
432      */
433     private function sanitizeFileName(string $fileName): string
434     {
435         $parts = explode('.', $fileName);
436         $extension = array_pop($parts);
437
438         return sprintf('%s.%s', implode('-', $parts), $extension);
439     }
440 }