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 Symfony\Component\HttpFoundation\File\UploadedFile;
14 class ImageService extends UploadService
19 protected $storageUrl;
24 * ImageService constructor.
26 * @param ImageManager $imageTool
27 * @param FileSystem $fileSystem
29 * @param HttpFetcher $http
31 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache, HttpFetcher $http)
33 $this->image = $image;
34 $this->imageTool = $imageTool;
35 $this->cache = $cache;
37 parent::__construct($fileSystem);
41 * Get the storage that will be used for storing images.
43 * @return \Illuminate\Contracts\Filesystem\Filesystem
45 protected function getStorage($type = '')
47 $storageType = config('filesystems.default');
49 // Override default location if set to local public to ensure not visible.
50 if ($type === 'system' && $storageType === 'local_secure') {
51 $storageType = 'local';
54 return $this->fileSystem->disk($storageType);
58 * Saves a new image from an upload.
59 * @param UploadedFile $uploadedFile
61 * @param int $uploadedTo
63 * @throws ImageUploadException
65 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
67 $imageName = $uploadedFile->getClientOriginalName();
68 $imageData = file_get_contents($uploadedFile->getRealPath());
69 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
73 * Save a new image from a uri-encoded base64 string of data.
74 * @param string $base64Uri
77 * @param int $uploadedTo
79 * @throws ImageUploadException
81 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
83 $splitData = explode(';base64,', $base64Uri);
84 if (count($splitData) < 2) {
85 throw new ImageUploadException("Invalid base64 image data provided");
87 $data = base64_decode($splitData[1]);
88 return $this->saveNew($name, $data, $type, $uploadedTo);
92 * Gets an image from url and saves it to the database.
95 * @param bool|string $imageName
99 private function saveNewFromUrl($url, $type, $imageName = false)
101 $imageName = $imageName ? $imageName : basename($url);
103 $imageData = $this->http->fetch($url);
104 } catch (HttpFetchException $exception) {
105 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
107 return $this->saveNew($imageName, $imageData, $type);
112 * @param string $imageName
113 * @param string $imageData
114 * @param string $type
115 * @param int $uploadedTo
117 * @throws ImageUploadException
119 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
121 $storage = $this->getStorage($type);
122 $secureUploads = setting('app-secure-images');
123 $imageName = str_replace(' ', '-', $imageName);
125 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
127 while ($storage->exists($imagePath . $imageName)) {
128 $imageName = str_random(3) . $imageName;
131 $fullPath = $imagePath . $imageName;
132 if ($secureUploads) {
133 $fullPath = $imagePath . str_random(16) . '-' . $imageName;
137 $storage->put($fullPath, $imageData);
138 $storage->setVisibility($fullPath, 'public');
139 } catch (Exception $e) {
140 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
144 'name' => $imageName,
146 'url' => $this->getPublicUrl($fullPath),
148 'uploaded_to' => $uploadedTo
151 if (user()->id !== 0) {
152 $userId = user()->id;
153 $imageDetails['created_by'] = $userId;
154 $imageDetails['updated_by'] = $userId;
157 $image = $this->image->newInstance();
158 $image->forceFill($imageDetails)->save();
164 * Checks if the image is a gif. Returns true if it is, else false.
165 * @param Image $image
168 protected function isGif(Image $image)
170 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
174 * Get the thumbnail for an image.
175 * If $keepRatio is true only the width will be used.
176 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
177 * @param Image $image
180 * @param bool $keepRatio
183 * @throws ImageUploadException
185 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
187 if ($keepRatio && $this->isGif($image)) {
188 return $this->getPublicUrl($image->path);
191 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
192 $imagePath = $image->path;
193 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
195 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
196 return $this->getPublicUrl($thumbFilePath);
199 $storage = $this->getStorage($image->type);
200 if ($storage->exists($thumbFilePath)) {
201 return $this->getPublicUrl($thumbFilePath);
205 $thumb = $this->imageTool->make($storage->get($imagePath));
206 } catch (Exception $e) {
207 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
208 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
214 $thumb->resize($width, null, function ($constraint) {
215 $constraint->aspectRatio();
216 $constraint->upsize();
219 $thumb->fit($width, $height);
222 $thumbData = (string)$thumb->encode();
223 $storage->put($thumbFilePath, $thumbData);
224 $storage->setVisibility($thumbFilePath, 'public');
225 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
227 return $this->getPublicUrl($thumbFilePath);
231 * Get the raw data content from an image.
232 * @param Image $image
234 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
236 public function getImageData(Image $image)
238 $imagePath = $image->path;
239 $storage = $this->getStorage();
240 return $storage->get($imagePath);
244 * Destroy an image along with its revisions, thumbnails and remaining folders.
245 * @param Image $image
248 public function destroy(Image $image)
250 $this->destroyImagesFromPath($image->path);
255 * Destroys an image at the given path.
256 * Searches for image thumbnails in addition to main provided path..
257 * @param string $path
260 protected function destroyImagesFromPath(string $path)
262 $storage = $this->getStorage();
264 $imageFolder = dirname($path);
265 $imageFileName = basename($path);
266 $allImages = collect($storage->allFiles($imageFolder));
268 // Delete image files
269 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
270 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
271 return strpos($imagePath, $imageFileName) === $expectedIndex;
273 $storage->delete($imagesToDelete->all());
275 // Cleanup of empty folders
276 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
277 foreach ($foldersInvolved as $directory) {
278 if ($this->isFolderEmpty($directory)) {
279 $storage->deleteDirectory($directory);
287 * Save an avatar image from an external service.
288 * @param \BookStack\Auth\User $user
293 public function saveUserAvatar(User $user, $size = 500)
295 $avatarUrl = $this->getAvatarUrl();
296 $email = strtolower(trim($user->email));
299 '${hash}' => md5($email),
301 '${email}' => urlencode($email),
304 $userAvatarUrl = strtr($avatarUrl, $replacements);
305 $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
306 $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
307 $image->created_by = $user->id;
308 $image->updated_by = $user->id;
315 * Check if fetching external avatars is enabled.
318 public function avatarFetchEnabled()
320 $fetchUrl = $this->getAvatarUrl();
321 return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
325 * Get the URL to fetch avatars from.
326 * @return string|mixed
328 protected function getAvatarUrl()
330 $url = trim(config('services.avatar_url'));
332 if (empty($url) && !config('services.disable_services')) {
333 $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
340 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
341 * Checks based off of only the image name.
342 * Could be much improved to be more specific but kept it generic for now to be safe.
344 * Returns the path of the images that would be/have been deleted.
345 * @param bool $checkRevisions
346 * @param bool $dryRun
347 * @param array $types
350 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
352 $types = array_intersect($types, ['gallery', 'drawio']);
355 $this->image->newQuery()->whereIn('type', $types)
356 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
357 foreach ($images as $image) {
358 $searchQuery = '%' . basename($image->path) . '%';
359 $inPage = DB::table('pages')
360 ->where('html', 'like', $searchQuery)->count() > 0;
362 if ($checkRevisions) {
363 $inRevision = DB::table('page_revisions')
364 ->where('html', 'like', $searchQuery)->count() > 0;
367 if (!$inPage && !$inRevision) {
368 $deletedPaths[] = $image->path;
370 $this->destroy($image);
375 return $deletedPaths;
379 * Convert a image URI to a Base64 encoded string.
380 * Attempts to find locally via set storage method first.
382 * @return null|string
383 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
385 public function imageUriToBase64(string $uri)
387 $isLocal = strpos(trim($uri), 'http') !== 0;
389 // Attempt to find local files even if url not absolute
390 $base = baseUrl('/');
391 if (!$isLocal && strpos($uri, $base) === 0) {
393 $uri = str_replace($base, '', $uri);
399 $uri = trim($uri, '/');
400 $storage = $this->getStorage();
401 if ($storage->exists($uri)) {
402 $imageData = $storage->get($uri);
406 $imageData = $this->http->fetch($uri);
407 } catch (\Exception $e) {
411 if ($imageData === null) {
415 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
419 * Gets a public facing url for an image by checking relevant environment variables.
420 * @param string $filePath
423 private function getPublicUrl($filePath)
425 if ($this->storageUrl === null) {
426 $storageUrl = config('filesystems.url');
428 // Get the standard public s3 url if s3 is set as storage type
429 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
430 // region-based url will be used to prevent http issues.
431 if ($storageUrl == false && config('filesystems.default') === 's3') {
432 $storageDetails = config('filesystems.disks.s3');
433 if (strpos($storageDetails['bucket'], '.') === false) {
434 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
436 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
439 $this->storageUrl = $storageUrl;
442 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
443 return rtrim($basePath, '/') . $filePath;