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);
128 * @param string $imageName
129 * @param string $imageData
130 * @param string $type
131 * @param int $uploadedTo
133 * @throws ImageUploadException
135 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
137 $storage = $this->getStorage($type);
138 $secureUploads = setting('app-secure-images');
139 $imageName = str_replace(' ', '-', $imageName);
141 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
143 while ($storage->exists($imagePath . $imageName)) {
144 $imageName = Str::random(3) . $imageName;
147 $fullPath = $imagePath . $imageName;
148 if ($secureUploads) {
149 $fullPath = $imagePath . Str::random(16) . '-' . $imageName;
153 $storage->put($fullPath, $imageData);
154 $storage->setVisibility($fullPath, 'public');
155 } catch (Exception $e) {
156 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
160 'name' => $imageName,
162 'url' => $this->getPublicUrl($fullPath),
164 'uploaded_to' => $uploadedTo
167 if (user()->id !== 0) {
168 $userId = user()->id;
169 $imageDetails['created_by'] = $userId;
170 $imageDetails['updated_by'] = $userId;
173 $image = $this->image->newInstance();
174 $image->forceFill($imageDetails)->save();
180 * Checks if the image is a gif. Returns true if it is, else false.
181 * @param Image $image
184 protected function isGif(Image $image)
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);
226 return $this->getPublicUrl($thumbFilePath);
231 * @param string $imageData
234 * @param bool $keepRatio
236 * @throws ImageUploadException
238 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
241 $thumb = $this->imageTool->make($imageData);
242 } catch (Exception $e) {
243 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
244 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
250 $thumb->resize($width, $height, function ($constraint) {
251 $constraint->aspectRatio();
252 $constraint->upsize();
255 $thumb->fit($width, $height);
258 $thumbData = (string)$thumb->encode();
260 // Use original image data if we're keeping the ratio
261 // and the resizing does not save any space.
262 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
270 * Get the raw data content from an image.
271 * @param Image $image
273 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
275 public function getImageData(Image $image)
277 $imagePath = $image->path;
278 $storage = $this->getStorage();
279 return $storage->get($imagePath);
283 * Destroy an image along with its revisions, thumbnails and remaining folders.
284 * @param Image $image
287 public function destroy(Image $image)
289 $this->destroyImagesFromPath($image->path);
294 * Destroys an image at the given path.
295 * Searches for image thumbnails in addition to main provided path..
296 * @param string $path
299 protected function destroyImagesFromPath(string $path)
301 $storage = $this->getStorage();
303 $imageFolder = dirname($path);
304 $imageFileName = basename($path);
305 $allImages = collect($storage->allFiles($imageFolder));
307 // Delete image files
308 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
309 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
310 return strpos($imagePath, $imageFileName) === $expectedIndex;
312 $storage->delete($imagesToDelete->all());
314 // Cleanup of empty folders
315 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
316 foreach ($foldersInvolved as $directory) {
317 if ($this->isFolderEmpty($directory)) {
318 $storage->deleteDirectory($directory);
326 * Save an avatar image from an external service.
327 * @param \BookStack\Auth\User $user
332 public function saveUserAvatar(User $user, $size = 500)
334 $avatarUrl = $this->getAvatarUrl();
335 $email = strtolower(trim($user->email));
338 '${hash}' => md5($email),
340 '${email}' => urlencode($email),
343 $userAvatarUrl = strtr($avatarUrl, $replacements);
344 $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
345 $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
346 $image->created_by = $user->id;
347 $image->updated_by = $user->id;
348 $image->uploaded_to = $user->id;
355 * Check if fetching external avatars is enabled.
358 public function avatarFetchEnabled()
360 $fetchUrl = $this->getAvatarUrl();
361 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
365 * Get the URL to fetch avatars from.
366 * @return string|mixed
368 protected function getAvatarUrl()
370 $url = trim(config('services.avatar_url'));
372 if (empty($url) && !config('services.disable_services')) {
373 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
380 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
381 * Checks based off of only the image name.
382 * Could be much improved to be more specific but kept it generic for now to be safe.
384 * Returns the path of the images that would be/have been deleted.
385 * @param bool $checkRevisions
386 * @param bool $dryRun
387 * @param array $types
390 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
392 $types = array_intersect($types, ['gallery', 'drawio']);
395 $this->image->newQuery()->whereIn('type', $types)
396 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
397 foreach ($images as $image) {
398 $searchQuery = '%' . basename($image->path) . '%';
399 $inPage = DB::table('pages')
400 ->where('html', 'like', $searchQuery)->count() > 0;
402 if ($checkRevisions) {
403 $inRevision = DB::table('page_revisions')
404 ->where('html', 'like', $searchQuery)->count() > 0;
407 if (!$inPage && !$inRevision) {
408 $deletedPaths[] = $image->path;
410 $this->destroy($image);
415 return $deletedPaths;
419 * Convert a image URI to a Base64 encoded string.
420 * Attempts to find locally via set storage method first.
422 * @return null|string
423 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
425 public function imageUriToBase64(string $uri)
427 $isLocal = strpos(trim($uri), 'http') !== 0;
429 // Attempt to find local files even if url not absolute
431 if (!$isLocal && strpos($uri, $base) === 0) {
433 $uri = str_replace($base, '', $uri);
439 $uri = trim($uri, '/');
440 $storage = $this->getStorage();
441 if ($storage->exists($uri)) {
442 $imageData = $storage->get($uri);
446 $imageData = $this->http->fetch($uri);
447 } catch (\Exception $e) {
451 if ($imageData === null) {
455 $extension = pathinfo($uri, PATHINFO_EXTENSION);
456 if ($extension === 'svg') {
457 $extension = 'svg+xml';
460 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
464 * Gets a public facing url for an image by checking relevant environment variables.
465 * @param string $filePath
468 private function getPublicUrl($filePath)
470 if ($this->storageUrl === null) {
471 $storageUrl = config('filesystems.url');
473 // Get the standard public s3 url if s3 is set as storage type
474 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
475 // region-based url will be used to prevent http issues.
476 if ($storageUrl == false && config('filesystems.images') === 's3') {
477 $storageDetails = config('filesystems.disks.s3');
478 if (strpos($storageDetails['bucket'], '.') === false) {
479 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
481 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
484 $this->storageUrl = $storageUrl;
487 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
488 return rtrim($basePath, '/') . $filePath;