1 <?php namespace BookStack\Uploads;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\HttpFetchException;
5 use BookStack\Exceptions\ImageUploadException;
9 use Illuminate\Contracts\Cache\Repository as Cache;
10 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
11 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
12 use Illuminate\Contracts\Filesystem\FileNotFoundException;
13 use Illuminate\Support\Str;
14 use Intervention\Image\Exception\NotSupportedException;
15 use Intervention\Image\ImageManager;
16 use Symfony\Component\HttpFoundation\File\UploadedFile;
23 protected $storageUrl;
26 protected $fileSystem;
29 * ImageService constructor.
31 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache, HttpFetcher $http)
33 $this->image = $image;
34 $this->imageTool = $imageTool;
35 $this->fileSystem = $fileSystem;
36 $this->cache = $cache;
41 * Get the storage that will be used for storing images.
43 protected function getStorage(string $type = ''): FileSystemInstance
45 $storageType = config('filesystems.images');
47 // Ensure system images (App logo) are uploaded to a public space
48 if ($type === 'system' && $storageType === 'local_secure') {
49 $storageType = 'local';
52 return $this->fileSystem->disk($storageType);
56 * Saves a new image from an upload.
58 * @throws ImageUploadException
60 public function saveNewFromUpload(
61 UploadedFile $uploadedFile,
64 int $resizeWidth = null,
65 int $resizeHeight = null,
66 bool $keepRatio = true
68 $imageName = $uploadedFile->getClientOriginalName();
69 $imageData = file_get_contents($uploadedFile->getRealPath());
71 if ($resizeWidth !== null || $resizeHeight !== null) {
72 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
75 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
79 * Save a new image from a uri-encoded base64 string of data.
80 * @param string $base64Uri
83 * @param int $uploadedTo
85 * @throws ImageUploadException
87 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
89 $splitData = explode(';base64,', $base64Uri);
90 if (count($splitData) < 2) {
91 throw new ImageUploadException("Invalid base64 image data provided");
93 $data = base64_decode($splitData[1]);
94 return $this->saveNew($name, $data, $type, $uploadedTo);
98 * Gets an image from url and saves it to the database.
100 * @param string $type
101 * @param bool|string $imageName
105 private function saveNewFromUrl($url, $type, $imageName = false)
107 $imageName = $imageName ? $imageName : basename($url);
109 $imageData = $this->http->fetch($url);
110 } catch (HttpFetchException $exception) {
111 throw new Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
113 return $this->saveNew($imageName, $imageData, $type);
117 * Save a new image into storage.
118 * @throws ImageUploadException
120 private function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
122 $storage = $this->getStorage($type);
123 $secureUploads = setting('app-secure-images');
124 $fileName = $this->cleanImageFileName($imageName);
126 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
128 while ($storage->exists($imagePath . $fileName)) {
129 $fileName = Str::random(3) . $fileName;
132 $fullPath = $imagePath . $fileName;
133 if ($secureUploads) {
134 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
138 $storage->put($fullPath, $imageData);
139 $storage->setVisibility($fullPath, 'public');
140 } catch (Exception $e) {
141 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
145 'name' => $imageName,
147 'url' => $this->getPublicUrl($fullPath),
149 'uploaded_to' => $uploadedTo
152 if (user()->id !== 0) {
153 $userId = user()->id;
154 $imageDetails['created_by'] = $userId;
155 $imageDetails['updated_by'] = $userId;
158 $image = $this->image->newInstance();
159 $image->forceFill($imageDetails)->save();
164 * Clean up an image file name to be both URL and storage safe.
166 protected function cleanImageFileName(string $name): string
168 $name = str_replace(' ', '-', $name);
169 $nameParts = explode('.', $name);
170 $extension = array_pop($nameParts);
171 $name = implode('.', $nameParts);
172 $name = Str::slug($name);
174 if (strlen($name) === 0) {
175 $name = Str::random(10);
178 return $name . '.' . $extension;
182 * Checks if the image is a gif. Returns true if it is, else false.
184 protected function isGif(Image $image): bool
186 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
190 * Get the thumbnail for an image.
191 * If $keepRatio is true only the width will be used.
192 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
193 * @param Image $image
196 * @param bool $keepRatio
199 * @throws ImageUploadException
201 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
203 if ($keepRatio && $this->isGif($image)) {
204 return $this->getPublicUrl($image->path);
207 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
208 $imagePath = $image->path;
209 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
211 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
212 return $this->getPublicUrl($thumbFilePath);
215 $storage = $this->getStorage($image->type);
216 if ($storage->exists($thumbFilePath)) {
217 return $this->getPublicUrl($thumbFilePath);
220 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
222 $storage->put($thumbFilePath, $thumbData);
223 $storage->setVisibility($thumbFilePath, 'public');
224 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
227 return $this->getPublicUrl($thumbFilePath);
232 * @param string $imageData
235 * @param bool $keepRatio
237 * @throws ImageUploadException
239 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
242 $thumb = $this->imageTool->make($imageData);
243 } catch (Exception $e) {
244 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
245 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
251 $thumb->resize($width, $height, function ($constraint) {
252 $constraint->aspectRatio();
253 $constraint->upsize();
256 $thumb->fit($width, $height);
259 $thumbData = (string)$thumb->encode();
261 // Use original image data if we're keeping the ratio
262 // and the resizing does not save any space.
263 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
271 * Get the raw data content from an image.
272 * @throws FileNotFoundException
274 public function getImageData(Image $image): string
276 $imagePath = $image->path;
277 $storage = $this->getStorage();
278 return $storage->get($imagePath);
282 * Destroy an image along with its revisions, thumbnails and remaining folders.
285 public function destroy(Image $image)
287 $this->destroyImagesFromPath($image->path);
292 * Destroys an image at the given path.
293 * Searches for image thumbnails in addition to main provided path.
295 protected function destroyImagesFromPath(string $path): bool
297 $storage = $this->getStorage();
299 $imageFolder = dirname($path);
300 $imageFileName = basename($path);
301 $allImages = collect($storage->allFiles($imageFolder));
303 // Delete image files
304 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
305 return basename($imagePath) === $imageFileName;
307 $storage->delete($imagesToDelete->all());
309 // Cleanup of empty folders
310 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
311 foreach ($foldersInvolved as $directory) {
312 if ($this->isFolderEmpty($storage, $directory)) {
313 $storage->deleteDirectory($directory);
321 * Check whether or not a folder is empty.
323 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
325 $files = $storage->files($path);
326 $folders = $storage->directories($path);
327 return (count($files) === 0 && count($folders) === 0);
331 * Save an avatar image from an external service.
334 public function saveUserAvatar(User $user, int $size = 500): Image
336 $avatarUrl = $this->getAvatarUrl();
337 $email = strtolower(trim($user->email));
340 '${hash}' => md5($email),
342 '${email}' => urlencode($email),
345 $userAvatarUrl = strtr($avatarUrl, $replacements);
346 $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
347 $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
348 $image->created_by = $user->id;
349 $image->updated_by = $user->id;
350 $image->uploaded_to = $user->id;
357 * Check if fetching external avatars is enabled.
359 public function avatarFetchEnabled(): bool
361 $fetchUrl = $this->getAvatarUrl();
362 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
366 * Get the URL to fetch avatars from.
367 * @return string|mixed
369 protected function getAvatarUrl()
371 $url = trim(config('services.avatar_url'));
373 if (empty($url) && !config('services.disable_services')) {
374 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
381 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
382 * Checks based off of only the image name.
383 * Could be much improved to be more specific but kept it generic for now to be safe.
385 * Returns the path of the images that would be/have been deleted.
386 * @param bool $checkRevisions
387 * @param bool $dryRun
388 * @param array $types
391 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
393 $types = array_intersect($types, ['gallery', 'drawio']);
396 $this->image->newQuery()->whereIn('type', $types)
397 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
398 foreach ($images as $image) {
399 $searchQuery = '%' . basename($image->path) . '%';
400 $inPage = DB::table('pages')
401 ->where('html', 'like', $searchQuery)->count() > 0;
403 if ($checkRevisions) {
404 $inRevision = DB::table('page_revisions')
405 ->where('html', 'like', $searchQuery)->count() > 0;
408 if (!$inPage && !$inRevision) {
409 $deletedPaths[] = $image->path;
411 $this->destroy($image);
416 return $deletedPaths;
420 * Convert a image URI to a Base64 encoded string.
421 * Attempts to find locally via set storage method first.
422 * @throws FileNotFoundException
424 public function imageUriToBase64(string $uri): ?string
426 $isLocal = strpos(trim($uri), 'http') !== 0;
428 // Attempt to find local files even if url not absolute
430 if (!$isLocal && strpos($uri, $base) === 0) {
432 $uri = str_replace($base, '', $uri);
438 $uri = trim($uri, '/');
439 $storage = $this->getStorage();
440 if ($storage->exists($uri)) {
441 $imageData = $storage->get($uri);
445 $imageData = $this->http->fetch($uri);
446 } catch (Exception $e) {
450 if ($imageData === null) {
454 $extension = pathinfo($uri, PATHINFO_EXTENSION);
455 if ($extension === 'svg') {
456 $extension = 'svg+xml';
459 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
463 * Gets a public facing url for an image by checking relevant environment variables.
464 * If s3-style store is in use it will default to guessing a public bucket URL.
466 private function getPublicUrl(string $filePath): string
468 if ($this->storageUrl === null) {
469 $storageUrl = config('filesystems.url');
471 // Get the standard public s3 url if s3 is set as storage type
472 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
473 // region-based url will be used to prevent http issues.
474 if ($storageUrl == false && config('filesystems.images') === 's3') {
475 $storageDetails = config('filesystems.disks.s3');
476 if (strpos($storageDetails['bucket'], '.') === false) {
477 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
479 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
482 $this->storageUrl = $storageUrl;
485 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
486 return rtrim($basePath, '/') . $filePath;