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.default');
50 // Override default location if set to local public to ensure not visible.
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
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 * 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);
257 return (string)$thumb->encode();
261 * Get the raw data content from an image.
262 * @param Image $image
264 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
266 public function getImageData(Image $image)
268 $imagePath = $image->path;
269 $storage = $this->getStorage();
270 return $storage->get($imagePath);
274 * Destroy an image along with its revisions, thumbnails and remaining folders.
275 * @param Image $image
278 public function destroy(Image $image)
280 $this->destroyImagesFromPath($image->path);
285 * Destroys an image at the given path.
286 * Searches for image thumbnails in addition to main provided path..
287 * @param string $path
290 protected function destroyImagesFromPath(string $path)
292 $storage = $this->getStorage();
294 $imageFolder = dirname($path);
295 $imageFileName = basename($path);
296 $allImages = collect($storage->allFiles($imageFolder));
298 // Delete image files
299 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
300 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
301 return strpos($imagePath, $imageFileName) === $expectedIndex;
303 $storage->delete($imagesToDelete->all());
305 // Cleanup of empty folders
306 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
307 foreach ($foldersInvolved as $directory) {
308 if ($this->isFolderEmpty($directory)) {
309 $storage->deleteDirectory($directory);
317 * Save an avatar image from an external service.
318 * @param \BookStack\Auth\User $user
323 public function saveUserAvatar(User $user, $size = 500)
325 $avatarUrl = $this->getAvatarUrl();
326 $email = strtolower(trim($user->email));
329 '${hash}' => md5($email),
331 '${email}' => urlencode($email),
334 $userAvatarUrl = strtr($avatarUrl, $replacements);
335 $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
336 $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
337 $image->created_by = $user->id;
338 $image->updated_by = $user->id;
339 $image->uploaded_to = $user->id;
346 * Check if fetching external avatars is enabled.
349 public function avatarFetchEnabled()
351 $fetchUrl = $this->getAvatarUrl();
352 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
356 * Get the URL to fetch avatars from.
357 * @return string|mixed
359 protected function getAvatarUrl()
361 $url = trim(config('services.avatar_url'));
363 if (empty($url) && !config('services.disable_services')) {
364 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
371 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
372 * Checks based off of only the image name.
373 * Could be much improved to be more specific but kept it generic for now to be safe.
375 * Returns the path of the images that would be/have been deleted.
376 * @param bool $checkRevisions
377 * @param bool $dryRun
378 * @param array $types
381 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
383 $types = array_intersect($types, ['gallery', 'drawio']);
386 $this->image->newQuery()->whereIn('type', $types)
387 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
388 foreach ($images as $image) {
389 $searchQuery = '%' . basename($image->path) . '%';
390 $inPage = DB::table('pages')
391 ->where('html', 'like', $searchQuery)->count() > 0;
393 if ($checkRevisions) {
394 $inRevision = DB::table('page_revisions')
395 ->where('html', 'like', $searchQuery)->count() > 0;
398 if (!$inPage && !$inRevision) {
399 $deletedPaths[] = $image->path;
401 $this->destroy($image);
406 return $deletedPaths;
410 * Convert a image URI to a Base64 encoded string.
411 * Attempts to find locally via set storage method first.
413 * @return null|string
414 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
416 public function imageUriToBase64(string $uri)
418 $isLocal = strpos(trim($uri), 'http') !== 0;
420 // Attempt to find local files even if url not absolute
421 $base = baseUrl('/');
422 if (!$isLocal && strpos($uri, $base) === 0) {
424 $uri = str_replace($base, '', $uri);
430 $uri = trim($uri, '/');
431 $storage = $this->getStorage();
432 if ($storage->exists($uri)) {
433 $imageData = $storage->get($uri);
437 $imageData = $this->http->fetch($uri);
438 } catch (\Exception $e) {
442 if ($imageData === null) {
446 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
450 * Gets a public facing url for an image by checking relevant environment variables.
451 * @param string $filePath
454 private function getPublicUrl($filePath)
456 if ($this->storageUrl === null) {
457 $storageUrl = config('filesystems.url');
459 // Get the standard public s3 url if s3 is set as storage type
460 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
461 // region-based url will be used to prevent http issues.
462 if ($storageUrl == false && config('filesystems.default') === 's3') {
463 $storageDetails = config('filesystems.disks.s3');
464 if (strpos($storageDetails['bucket'], '.') === false) {
465 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
467 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
470 $this->storageUrl = $storageUrl;
473 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
474 return rtrim($basePath, '/') . $filePath;