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 Illuminate\Support\Str;
11 use Intervention\Image\Exception\NotSupportedException;
12 use Intervention\Image\ImageManager;
13 use phpDocumentor\Reflection\Types\Integer;
14 use Symfony\Component\HttpFoundation\File\UploadedFile;
16 class ImageService extends UploadService
21 protected $storageUrl;
26 * ImageService constructor.
28 * @param ImageManager $imageTool
29 * @param FileSystem $fileSystem
31 * @param HttpFetcher $http
33 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache, HttpFetcher $http)
35 $this->image = $image;
36 $this->imageTool = $imageTool;
37 $this->cache = $cache;
39 parent::__construct($fileSystem);
43 * Get the storage that will be used for storing images.
45 * @return \Illuminate\Contracts\Filesystem\Filesystem
47 protected function getStorage($type = '')
49 $storageType = config('filesystems.images');
51 // Ensure system images (App logo) are uploaded to a public space
52 if ($type === 'system' && $storageType === 'local_secure') {
53 $storageType = 'local';
56 return $this->fileSystem->disk($storageType);
60 * Saves a new image from an upload.
61 * @param UploadedFile $uploadedFile
63 * @param int $uploadedTo
64 * @param int|null $resizeWidth
65 * @param int|null $resizeHeight
66 * @param bool $keepRatio
68 * @throws ImageUploadException
70 public function saveNewFromUpload(
71 UploadedFile $uploadedFile,
74 int $resizeWidth = null,
75 int $resizeHeight = null,
76 bool $keepRatio = true
78 $imageName = $uploadedFile->getClientOriginalName();
79 $imageData = file_get_contents($uploadedFile->getRealPath());
81 if ($resizeWidth !== null || $resizeHeight !== null) {
82 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
85 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
89 * Save a new image from a uri-encoded base64 string of data.
90 * @param string $base64Uri
93 * @param int $uploadedTo
95 * @throws ImageUploadException
97 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
99 $splitData = explode(';base64,', $base64Uri);
100 if (count($splitData) < 2) {
101 throw new ImageUploadException("Invalid base64 image data provided");
103 $data = base64_decode($splitData[1]);
104 return $this->saveNew($name, $data, $type, $uploadedTo);
108 * Gets an image from url and saves it to the database.
110 * @param string $type
111 * @param bool|string $imageName
115 private function saveNewFromUrl($url, $type, $imageName = false)
117 $imageName = $imageName ? $imageName : basename($url);
119 $imageData = $this->http->fetch($url);
120 } catch (HttpFetchException $exception) {
121 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
123 return $this->saveNew($imageName, $imageData, $type);
127 * Save a new image into storage.
128 * @throws ImageUploadException
130 private function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
132 $storage = $this->getStorage($type);
133 $secureUploads = setting('app-secure-images');
134 $fileName = $this->cleanImageFileName($imageName);
136 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
138 while ($storage->exists($imagePath . $fileName)) {
139 $fileName = Str::random(3) . $fileName;
142 $fullPath = $imagePath . $fileName;
143 if ($secureUploads) {
144 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
148 $storage->put($fullPath, $imageData);
149 $storage->setVisibility($fullPath, 'public');
150 } catch (Exception $e) {
151 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
155 'name' => $imageName,
157 'url' => $this->getPublicUrl($fullPath),
159 'uploaded_to' => $uploadedTo
162 if (user()->id !== 0) {
163 $userId = user()->id;
164 $imageDetails['created_by'] = $userId;
165 $imageDetails['updated_by'] = $userId;
168 $image = $this->image->newInstance();
169 $image->forceFill($imageDetails)->save();
174 * Clean up an image file name to be both URL and storage safe.
176 protected function cleanImageFileName(string $name): string
178 $name = str_replace(' ', '-', $name);
179 $nameParts = explode('.', $name);
180 $extension = array_pop($nameParts);
181 $name = implode('.', $nameParts);
182 $name = Str::slug($name);
184 if (strlen($name) === 0) {
185 $name = Str::random(10);
188 return $name . '.' . $extension;
192 * Checks if the image is a gif. Returns true if it is, else false.
193 * @param Image $image
196 protected function isGif(Image $image)
198 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
202 * Get the thumbnail for an image.
203 * If $keepRatio is true only the width will be used.
204 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
205 * @param Image $image
208 * @param bool $keepRatio
211 * @throws ImageUploadException
213 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
215 if ($keepRatio && $this->isGif($image)) {
216 return $this->getPublicUrl($image->path);
219 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
220 $imagePath = $image->path;
221 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
223 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
224 return $this->getPublicUrl($thumbFilePath);
227 $storage = $this->getStorage($image->type);
228 if ($storage->exists($thumbFilePath)) {
229 return $this->getPublicUrl($thumbFilePath);
232 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
234 $storage->put($thumbFilePath, $thumbData);
235 $storage->setVisibility($thumbFilePath, 'public');
236 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
239 return $this->getPublicUrl($thumbFilePath);
244 * @param string $imageData
247 * @param bool $keepRatio
249 * @throws ImageUploadException
251 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
254 $thumb = $this->imageTool->make($imageData);
255 } catch (Exception $e) {
256 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
257 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
263 $thumb->resize($width, $height, function ($constraint) {
264 $constraint->aspectRatio();
265 $constraint->upsize();
268 $thumb->fit($width, $height);
271 $thumbData = (string)$thumb->encode();
273 // Use original image data if we're keeping the ratio
274 // and the resizing does not save any space.
275 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
283 * Get the raw data content from an image.
284 * @param Image $image
286 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
288 public function getImageData(Image $image)
290 $imagePath = $image->path;
291 $storage = $this->getStorage();
292 return $storage->get($imagePath);
296 * Destroy an image along with its revisions, thumbnails and remaining folders.
297 * @param Image $image
300 public function destroy(Image $image)
302 $this->destroyImagesFromPath($image->path);
307 * Destroys an image at the given path.
308 * Searches for image thumbnails in addition to main provided path.
310 protected function destroyImagesFromPath(string $path): bool
312 $storage = $this->getStorage();
314 $imageFolder = dirname($path);
315 $imageFileName = basename($path);
316 $allImages = collect($storage->allFiles($imageFolder));
318 // Delete image files
319 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
320 return basename($imagePath) === $imageFileName;
322 $storage->delete($imagesToDelete->all());
324 // Cleanup of empty folders
325 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
326 foreach ($foldersInvolved as $directory) {
327 if ($this->isFolderEmpty($directory)) {
328 $storage->deleteDirectory($directory);
336 * Save an avatar image from an external service.
337 * @param \BookStack\Auth\User $user
342 public function saveUserAvatar(User $user, $size = 500)
344 $avatarUrl = $this->getAvatarUrl();
345 $email = strtolower(trim($user->email));
348 '${hash}' => md5($email),
350 '${email}' => urlencode($email),
353 $userAvatarUrl = strtr($avatarUrl, $replacements);
354 $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
355 $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
356 $image->created_by = $user->id;
357 $image->updated_by = $user->id;
358 $image->uploaded_to = $user->id;
365 * Check if fetching external avatars is enabled.
368 public function avatarFetchEnabled()
370 $fetchUrl = $this->getAvatarUrl();
371 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
375 * Get the URL to fetch avatars from.
376 * @return string|mixed
378 protected function getAvatarUrl()
380 $url = trim(config('services.avatar_url'));
382 if (empty($url) && !config('services.disable_services')) {
383 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
390 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
391 * Checks based off of only the image name.
392 * Could be much improved to be more specific but kept it generic for now to be safe.
394 * Returns the path of the images that would be/have been deleted.
395 * @param bool $checkRevisions
396 * @param bool $dryRun
397 * @param array $types
400 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
402 $types = array_intersect($types, ['gallery', 'drawio']);
405 $this->image->newQuery()->whereIn('type', $types)
406 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
407 foreach ($images as $image) {
408 $searchQuery = '%' . basename($image->path) . '%';
409 $inPage = DB::table('pages')
410 ->where('html', 'like', $searchQuery)->count() > 0;
412 if ($checkRevisions) {
413 $inRevision = DB::table('page_revisions')
414 ->where('html', 'like', $searchQuery)->count() > 0;
417 if (!$inPage && !$inRevision) {
418 $deletedPaths[] = $image->path;
420 $this->destroy($image);
425 return $deletedPaths;
429 * Convert a image URI to a Base64 encoded string.
430 * Attempts to find locally via set storage method first.
432 * @return null|string
433 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
435 public function imageUriToBase64(string $uri)
437 $isLocal = strpos(trim($uri), 'http') !== 0;
439 // Attempt to find local files even if url not absolute
441 if (!$isLocal && strpos($uri, $base) === 0) {
443 $uri = str_replace($base, '', $uri);
449 $uri = trim($uri, '/');
450 $storage = $this->getStorage();
451 if ($storage->exists($uri)) {
452 $imageData = $storage->get($uri);
456 $imageData = $this->http->fetch($uri);
457 } catch (\Exception $e) {
461 if ($imageData === null) {
465 $extension = pathinfo($uri, PATHINFO_EXTENSION);
466 if ($extension === 'svg') {
467 $extension = 'svg+xml';
470 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
474 * Gets a public facing url for an image by checking relevant environment variables.
475 * @param string $filePath
478 private function getPublicUrl($filePath)
480 if ($this->storageUrl === null) {
481 $storageUrl = config('filesystems.url');
483 // Get the standard public s3 url if s3 is set as storage type
484 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
485 // region-based url will be used to prevent http issues.
486 if ($storageUrl == false && config('filesystems.images') === 's3') {
487 $storageDetails = config('filesystems.disks.s3');
488 if (strpos($storageDetails['bucket'], '.') === false) {
489 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
491 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
494 $this->storageUrl = $storageUrl;
497 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
498 return rtrim($basePath, '/') . $filePath;