]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Filtered scripts in custom HTML head for exports
[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 = $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, ['visibility' => 'public']);
110         } catch (Exception $e) {
111             \Log::error('Error when attempting image upload:' . $e->getMessage());
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, ['visibility' => 'public']);
194         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
195
196
197         return $this->getPublicUrl($thumbFilePath);
198     }
199
200     /**
201      * Resize image data.
202      * @param string $imageData
203      * @param int $width
204      * @param int $height
205      * @param bool $keepRatio
206      * @return string
207      * @throws ImageUploadException
208      */
209     protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
210     {
211         try {
212             $thumb = $this->imageTool->make($imageData);
213         } catch (Exception $e) {
214             if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
215                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
216             }
217             throw $e;
218         }
219
220         if ($keepRatio) {
221             $thumb->resize($width, $height, function ($constraint) {
222                 $constraint->aspectRatio();
223                 $constraint->upsize();
224             });
225         } else {
226             $thumb->fit($width, $height);
227         }
228
229         $thumbData = (string)$thumb->encode();
230
231         // Use original image data if we're keeping the ratio
232         // and the resizing does not save any space.
233         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
234             return $imageData;
235         }
236
237         return $thumbData;
238     }
239
240     /**
241      * Get the raw data content from an image.
242      * @throws FileNotFoundException
243      */
244     public function getImageData(Image $image): string
245     {
246         $imagePath = $image->path;
247         $storage = $this->getStorage();
248         return $storage->get($imagePath);
249     }
250
251     /**
252      * Destroy an image along with its revisions, thumbnails and remaining folders.
253      * @throws Exception
254      */
255     public function destroy(Image $image)
256     {
257         $this->destroyImagesFromPath($image->path);
258         $image->delete();
259     }
260
261     /**
262      * Destroys an image at the given path.
263      * Searches for image thumbnails in addition to main provided path.
264      */
265     protected function destroyImagesFromPath(string $path): bool
266     {
267         $storage = $this->getStorage();
268
269         $imageFolder = dirname($path);
270         $imageFileName = basename($path);
271         $allImages = collect($storage->allFiles($imageFolder));
272
273         // Delete image files
274         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
275             return basename($imagePath) === $imageFileName;
276         });
277         $storage->delete($imagesToDelete->all());
278
279         // Cleanup of empty folders
280         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
281         foreach ($foldersInvolved as $directory) {
282             if ($this->isFolderEmpty($storage, $directory)) {
283                 $storage->deleteDirectory($directory);
284             }
285         }
286
287         return true;
288     }
289
290     /**
291      * Check whether or not a folder is empty.
292      */
293     protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
294     {
295         $files = $storage->files($path);
296         $folders = $storage->directories($path);
297         return (count($files) === 0 && count($folders) === 0);
298     }
299
300     /**
301      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
302      * Checks based off of only the image name.
303      * Could be much improved to be more specific but kept it generic for now to be safe.
304      *
305      * Returns the path of the images that would be/have been deleted.
306      */
307     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
308     {
309         $types = ['gallery', 'drawio'];
310         $deletedPaths = [];
311
312         $this->image->newQuery()->whereIn('type', $types)
313             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
314                 foreach ($images as $image) {
315                     $searchQuery = '%' . basename($image->path) . '%';
316                     $inPage = DB::table('pages')
317                             ->where('html', 'like', $searchQuery)->count() > 0;
318
319                     $inRevision = false;
320                     if ($checkRevisions) {
321                         $inRevision = DB::table('page_revisions')
322                                 ->where('html', 'like', $searchQuery)->count() > 0;
323                     }
324
325                     if (!$inPage && !$inRevision) {
326                         $deletedPaths[] = $image->path;
327                         if (!$dryRun) {
328                             $this->destroy($image);
329                         }
330                     }
331                 }
332             });
333         return $deletedPaths;
334     }
335
336     /**
337      * Convert a image URI to a Base64 encoded string.
338      * Attempts to convert the URL to a system storage url then
339      * fetch the data from the disk or storage location.
340      * Returns null if the image data cannot be fetched from storage.
341      * @throws FileNotFoundException
342      */
343     public function imageUriToBase64(string $uri): ?string
344     {
345         $storagePath = $this->imageUrlToStoragePath($uri);
346         if (empty($uri) || is_null($storagePath)) {
347             return null;
348         }
349
350         $storage = $this->getStorage();
351         $imageData = null;
352         if ($storage->exists($storagePath)) {
353             $imageData = $storage->get($storagePath);
354         }
355
356         if (is_null($imageData)) {
357             return null;
358         }
359
360         $extension = pathinfo($uri, PATHINFO_EXTENSION);
361         if ($extension === 'svg') {
362             $extension = 'svg+xml';
363         }
364
365         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
366     }
367
368     /**
369      * Get a storage path for the given image URL.
370      * Ensures the path will start with "uploads/images".
371      * Returns null if the url cannot be resolved to a local URL.
372      */
373     private function imageUrlToStoragePath(string $url): ?string
374     {
375         $url = ltrim(trim($url), '/');
376
377         // Handle potential relative paths
378         $isRelative = strpos($url, 'http') !== 0;
379         if ($isRelative) {
380             if (strpos(strtolower($url), 'uploads/images') === 0) {
381                 return trim($url, '/');
382             }
383             return null;
384         }
385
386         // Handle local images based on paths on the same domain
387         $potentialHostPaths = [
388             url('uploads/images/'),
389             $this->getPublicUrl('/uploads/images/'),
390         ];
391
392         foreach ($potentialHostPaths as $potentialBasePath) {
393             $potentialBasePath = strtolower($potentialBasePath);
394             if (strpos(strtolower($url), $potentialBasePath) === 0) {
395                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
396             }
397         }
398
399         return null;
400     }
401
402     /**
403      * Gets a public facing url for an image by checking relevant environment variables.
404      * If s3-style store is in use it will default to guessing a public bucket URL.
405      */
406     private function getPublicUrl(string $filePath): string
407     {
408         if ($this->storageUrl === null) {
409             $storageUrl = config('filesystems.url');
410
411             // Get the standard public s3 url if s3 is set as storage type
412             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
413             // region-based url will be used to prevent http issues.
414             if ($storageUrl == false && config('filesystems.images') === 's3') {
415                 $storageDetails = config('filesystems.disks.s3');
416                 if (strpos($storageDetails['bucket'], '.') === false) {
417                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
418                 } else {
419                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
420                 }
421             }
422             $this->storageUrl = $storageUrl;
423         }
424
425         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
426         return rtrim($basePath, '/') . $filePath;
427     }
428 }