1 <?php namespace BookStack\Uploads;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\HttpFetchException;
5 use BookStack\Exceptions\ImageUploadException;
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 phpDocumentor\Reflection\Types\Integer;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
15 class ImageService extends UploadService
20 protected $storageUrl;
25 * ImageService constructor.
27 * @param ImageManager $imageTool
28 * @param FileSystem $fileSystem
30 * @param HttpFetcher $http
32 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache, HttpFetcher $http)
34 $this->image = $image;
35 $this->imageTool = $imageTool;
36 $this->cache = $cache;
38 parent::__construct($fileSystem);
42 * Get the storage that will be used for storing images.
44 * @return \Illuminate\Contracts\Filesystem\Filesystem
46 protected function getStorage($type = '')
48 $storageType = config('filesystems.images');
50 // Ensure system images (App logo) are uploaded to a public space
51 if ($type === 'system' && $storageType === 'local_secure') {
52 $storageType = 'local';
55 return $this->fileSystem->disk($storageType);
59 * Saves a new image from an upload.
60 * @param UploadedFile $uploadedFile
62 * @param int $uploadedTo
63 * @param int|null $resizeWidth
64 * @param int|null $resizeHeight
65 * @param bool $keepRatio
67 * @throws ImageUploadException
69 public function saveNewFromUpload(
70 UploadedFile $uploadedFile,
73 int $resizeWidth = null,
74 int $resizeHeight = null,
75 bool $keepRatio = true
77 $imageName = $uploadedFile->getClientOriginalName();
78 $imageData = file_get_contents($uploadedFile->getRealPath());
80 if ($resizeWidth !== null || $resizeHeight !== null) {
81 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
84 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
88 * Save a new image from a uri-encoded base64 string of data.
89 * @param string $base64Uri
92 * @param int $uploadedTo
94 * @throws ImageUploadException
96 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
98 $splitData = explode(';base64,', $base64Uri);
99 if (count($splitData) < 2) {
100 throw new ImageUploadException("Invalid base64 image data provided");
102 $data = base64_decode($splitData[1]);
103 return $this->saveNew($name, $data, $type, $uploadedTo);
107 * Gets an image from url and saves it to the database.
109 * @param string $type
110 * @param bool|string $imageName
114 private function saveNewFromUrl($url, $type, $imageName = false)
116 $imageName = $imageName ? $imageName : basename($url);
118 $imageData = $this->http->fetch($url);
119 } catch (HttpFetchException $exception) {
120 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
122 return $this->saveNew($imageName, $imageData, $type);
127 * @param string $imageName
128 * @param string $imageData
129 * @param string $type
130 * @param int $uploadedTo
132 * @throws ImageUploadException
134 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
136 $storage = $this->getStorage($type);
137 $secureUploads = setting('app-secure-images');
138 $imageName = str_replace(' ', '-', $imageName);
140 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
142 while ($storage->exists($imagePath . $imageName)) {
143 $imageName = str_random(3) . $imageName;
146 $fullPath = $imagePath . $imageName;
147 if ($secureUploads) {
148 $fullPath = $imagePath . str_random(16) . '-' . $imageName;
152 $storage->put($fullPath, $imageData);
153 $storage->setVisibility($fullPath, 'public');
154 } catch (Exception $e) {
155 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
159 'name' => $imageName,
161 'url' => $this->getPublicUrl($fullPath),
163 'uploaded_to' => $uploadedTo
166 if (user()->id !== 0) {
167 $userId = user()->id;
168 $imageDetails['created_by'] = $userId;
169 $imageDetails['updated_by'] = $userId;
172 $image = $this->image->newInstance();
173 $image->forceFill($imageDetails)->save();
179 * Checks if the image is a gif. Returns true if it is, else false.
180 * @param Image $image
183 protected function isGif(Image $image)
185 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
189 * Get the thumbnail for an image.
190 * If $keepRatio is true only the width will be used.
191 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
192 * @param Image $image
195 * @param bool $keepRatio
198 * @throws ImageUploadException
200 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
202 if ($keepRatio && $this->isGif($image)) {
203 return $this->getPublicUrl($image->path);
206 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
207 $imagePath = $image->path;
208 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
210 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
211 return $this->getPublicUrl($thumbFilePath);
214 $storage = $this->getStorage($image->type);
215 if ($storage->exists($thumbFilePath)) {
216 return $this->getPublicUrl($thumbFilePath);
219 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
221 $storage->put($thumbFilePath, $thumbData);
222 $storage->setVisibility($thumbFilePath, 'public');
223 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
225 return $this->getPublicUrl($thumbFilePath);
230 * @param string $imageData
233 * @param bool $keepRatio
235 * @throws ImageUploadException
237 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
240 $thumb = $this->imageTool->make($imageData);
241 } catch (Exception $e) {
242 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
243 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
249 $thumb->resize($width, $height, function ($constraint) {
250 $constraint->aspectRatio();
251 $constraint->upsize();
254 $thumb->fit($width, $height);
256 return (string)$thumb->encode();
260 * Get the raw data content from an image.
261 * @param Image $image
263 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
265 public function getImageData(Image $image)
267 $imagePath = $image->path;
268 $storage = $this->getStorage();
269 return $storage->get($imagePath);
273 * Destroy an image along with its revisions, thumbnails and remaining folders.
274 * @param Image $image
277 public function destroy(Image $image)
279 $this->destroyImagesFromPath($image->path);
284 * Destroys an image at the given path.
285 * Searches for image thumbnails in addition to main provided path..
286 * @param string $path
289 protected function destroyImagesFromPath(string $path)
291 $storage = $this->getStorage();
293 $imageFolder = dirname($path);
294 $imageFileName = basename($path);
295 $allImages = collect($storage->allFiles($imageFolder));
297 // Delete image files
298 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
299 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
300 return strpos($imagePath, $imageFileName) === $expectedIndex;
302 $storage->delete($imagesToDelete->all());
304 // Cleanup of empty folders
305 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
306 foreach ($foldersInvolved as $directory) {
307 if ($this->isFolderEmpty($directory)) {
308 $storage->deleteDirectory($directory);
316 * Save an avatar image from an external service.
317 * @param \BookStack\Auth\User $user
322 public function saveUserAvatar(User $user, $size = 500)
324 $avatarUrl = $this->getAvatarUrl();
325 $email = strtolower(trim($user->email));
328 '${hash}' => md5($email),
330 '${email}' => urlencode($email),
333 $userAvatarUrl = strtr($avatarUrl, $replacements);
334 $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
335 $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
336 $image->created_by = $user->id;
337 $image->updated_by = $user->id;
338 $image->uploaded_to = $user->id;
345 * Check if fetching external avatars is enabled.
348 public function avatarFetchEnabled()
350 $fetchUrl = $this->getAvatarUrl();
351 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
355 * Get the URL to fetch avatars from.
356 * @return string|mixed
358 protected function getAvatarUrl()
360 $url = trim(config('services.avatar_url'));
362 if (empty($url) && !config('services.disable_services')) {
363 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
370 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
371 * Checks based off of only the image name.
372 * Could be much improved to be more specific but kept it generic for now to be safe.
374 * Returns the path of the images that would be/have been deleted.
375 * @param bool $checkRevisions
376 * @param bool $dryRun
377 * @param array $types
380 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
382 $types = array_intersect($types, ['gallery', 'drawio']);
385 $this->image->newQuery()->whereIn('type', $types)
386 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
387 foreach ($images as $image) {
388 $searchQuery = '%' . basename($image->path) . '%';
389 $inPage = DB::table('pages')
390 ->where('html', 'like', $searchQuery)->count() > 0;
392 if ($checkRevisions) {
393 $inRevision = DB::table('page_revisions')
394 ->where('html', 'like', $searchQuery)->count() > 0;
397 if (!$inPage && !$inRevision) {
398 $deletedPaths[] = $image->path;
400 $this->destroy($image);
405 return $deletedPaths;
409 * Convert a image URI to a Base64 encoded string.
410 * Attempts to find locally via set storage method first.
412 * @return null|string
413 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
415 public function imageUriToBase64(string $uri)
417 $isLocal = strpos(trim($uri), 'http') !== 0;
419 // Attempt to find local files even if url not absolute
420 $base = baseUrl('/');
421 if (!$isLocal && strpos($uri, $base) === 0) {
423 $uri = str_replace($base, '', $uri);
429 $uri = trim($uri, '/');
430 $storage = $this->getStorage();
431 if ($storage->exists($uri)) {
432 $imageData = $storage->get($uri);
436 $imageData = $this->http->fetch($uri);
437 } catch (\Exception $e) {
441 if ($imageData === null) {
445 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
449 * Gets a public facing url for an image by checking relevant environment variables.
450 * @param string $filePath
453 private function getPublicUrl($filePath)
455 if ($this->storageUrl === null) {
456 $storageUrl = config('filesystems.url');
458 // Get the standard public s3 url if s3 is set as storage type
459 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
460 // region-based url will be used to prevent http issues.
461 if ($storageUrl == false && config('filesystems.images') === 's3') {
462 $storageDetails = config('filesystems.disks.s3');
463 if (strpos($storageDetails['bucket'], '.') === false) {
464 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
466 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
469 $this->storageUrl = $storageUrl;
472 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
473 return rtrim($basePath, '/') . $filePath;