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