1 <?php namespace BookStack\Uploads;
3 use BookStack\Exceptions\ImageUploadException;
7 use Illuminate\Contracts\Cache\Repository as Cache;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
10 use Illuminate\Contracts\Filesystem\FileNotFoundException;
11 use Illuminate\Support\Str;
12 use Intervention\Image\Exception\NotSupportedException;
13 use Intervention\Image\ImageManager;
14 use Symfony\Component\HttpFoundation\File\UploadedFile;
20 protected $storageUrl;
22 protected $fileSystem;
25 * ImageService constructor.
27 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
29 $this->image = $image;
30 $this->imageTool = $imageTool;
31 $this->fileSystem = $fileSystem;
32 $this->cache = $cache;
36 * Get the storage that will be used for storing images.
38 protected function getStorage(string $type = ''): FileSystemInstance
40 $storageType = config('filesystems.images');
42 // Ensure system images (App logo) are uploaded to a public space
43 if ($type === 'system' && $storageType === 'local_secure') {
44 $storageType = 'local';
47 return $this->fileSystem->disk($storageType);
51 * Saves a new image from an upload.
53 * @throws ImageUploadException
55 public function saveNewFromUpload(
56 UploadedFile $uploadedFile,
59 int $resizeWidth = null,
60 int $resizeHeight = null,
61 bool $keepRatio = true
63 $imageName = $uploadedFile->getClientOriginalName();
64 $imageData = file_get_contents($uploadedFile->getRealPath());
66 if ($resizeWidth !== null || $resizeHeight !== null) {
67 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
70 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
74 * Save a new image from a uri-encoded base64 string of data.
75 * @throws ImageUploadException
77 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
79 $splitData = explode(';base64,', $base64Uri);
80 if (count($splitData) < 2) {
81 throw new ImageUploadException("Invalid base64 image data provided");
83 $data = base64_decode($splitData[1]);
84 return $this->saveNew($name, $data, $type, $uploadedTo);
88 * Save a new image into storage.
89 * @throws ImageUploadException
91 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
93 $storage = $this->getStorage($type);
94 $secureUploads = setting('app-secure-images');
95 $fileName = $this->cleanImageFileName($imageName);
97 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
99 while ($storage->exists($imagePath . $fileName)) {
100 $fileName = Str::random(3) . $fileName;
103 $fullPath = $imagePath . $fileName;
104 if ($secureUploads) {
105 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
109 $storage->put($fullPath, $imageData, ['visibility' => 'public']);
110 } catch (Exception $e) {
111 \Log::error('Error when attempting image upload:' . $e->getMessage());
112 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
116 'name' => $imageName,
118 'url' => $this->getPublicUrl($fullPath),
120 'uploaded_to' => $uploadedTo
123 if (user()->id !== 0) {
124 $userId = user()->id;
125 $imageDetails['created_by'] = $userId;
126 $imageDetails['updated_by'] = $userId;
129 $image = $this->image->newInstance();
130 $image->forceFill($imageDetails)->save();
135 * Clean up an image file name to be both URL and storage safe.
137 protected function cleanImageFileName(string $name): string
139 $name = str_replace(' ', '-', $name);
140 $nameParts = explode('.', $name);
141 $extension = array_pop($nameParts);
142 $name = implode('-', $nameParts);
143 $name = Str::slug($name);
145 if (strlen($name) === 0) {
146 $name = Str::random(10);
149 return $name . '.' . $extension;
153 * Checks if the image is a gif. Returns true if it is, else false.
155 protected function isGif(Image $image): bool
157 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
161 * Get the thumbnail for an image.
162 * If $keepRatio is true only the width will be used.
163 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
164 * @param Image $image
167 * @param bool $keepRatio
170 * @throws ImageUploadException
172 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
174 if ($keepRatio && $this->isGif($image)) {
175 return $this->getPublicUrl($image->path);
178 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
179 $imagePath = $image->path;
180 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
182 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
183 return $this->getPublicUrl($thumbFilePath);
186 $storage = $this->getStorage($image->type);
187 if ($storage->exists($thumbFilePath)) {
188 return $this->getPublicUrl($thumbFilePath);
191 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
193 $storage->put($thumbFilePath, $thumbData, ['visibility' => 'public']);
194 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
197 return $this->getPublicUrl($thumbFilePath);
202 * @param string $imageData
205 * @param bool $keepRatio
207 * @throws ImageUploadException
209 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
212 $thumb = $this->imageTool->make($imageData);
213 } catch (Exception $e) {
214 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
215 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
221 $thumb->resize($width, $height, function ($constraint) {
222 $constraint->aspectRatio();
223 $constraint->upsize();
226 $thumb->fit($width, $height);
229 $thumbData = (string)$thumb->encode();
231 // Use original image data if we're keeping the ratio
232 // and the resizing does not save any space.
233 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
241 * Get the raw data content from an image.
242 * @throws FileNotFoundException
244 public function getImageData(Image $image): string
246 $imagePath = $image->path;
247 $storage = $this->getStorage();
248 return $storage->get($imagePath);
252 * Destroy an image along with its revisions, thumbnails and remaining folders.
255 public function destroy(Image $image)
257 $this->destroyImagesFromPath($image->path);
262 * Destroys an image at the given path.
263 * Searches for image thumbnails in addition to main provided path.
265 protected function destroyImagesFromPath(string $path): bool
267 $storage = $this->getStorage();
269 $imageFolder = dirname($path);
270 $imageFileName = basename($path);
271 $allImages = collect($storage->allFiles($imageFolder));
273 // Delete image files
274 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
275 return basename($imagePath) === $imageFileName;
277 $storage->delete($imagesToDelete->all());
279 // Cleanup of empty folders
280 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
281 foreach ($foldersInvolved as $directory) {
282 if ($this->isFolderEmpty($storage, $directory)) {
283 $storage->deleteDirectory($directory);
291 * Check whether or not a folder is empty.
293 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
295 $files = $storage->files($path);
296 $folders = $storage->directories($path);
297 return (count($files) === 0 && count($folders) === 0);
301 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
302 * Checks based off of only the image name.
303 * Could be much improved to be more specific but kept it generic for now to be safe.
305 * Returns the path of the images that would be/have been deleted.
307 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
309 $types = ['gallery', 'drawio'];
312 $this->image->newQuery()->whereIn('type', $types)
313 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
314 foreach ($images as $image) {
315 $searchQuery = '%' . basename($image->path) . '%';
316 $inPage = DB::table('pages')
317 ->where('html', 'like', $searchQuery)->count() > 0;
320 if ($checkRevisions) {
321 $inRevision = DB::table('page_revisions')
322 ->where('html', 'like', $searchQuery)->count() > 0;
325 if (!$inPage && !$inRevision) {
326 $deletedPaths[] = $image->path;
328 $this->destroy($image);
333 return $deletedPaths;
337 * Convert a image URI to a Base64 encoded string.
338 * Attempts to convert the URL to a system storage url then
339 * fetch the data from the disk or storage location.
340 * Returns null if the image data cannot be fetched from storage.
341 * @throws FileNotFoundException
343 public function imageUriToBase64(string $uri): ?string
345 $storagePath = $this->imageUrlToStoragePath($uri);
346 if (empty($uri) || is_null($storagePath)) {
350 $storage = $this->getStorage();
352 if ($storage->exists($storagePath)) {
353 $imageData = $storage->get($storagePath);
356 if (is_null($imageData)) {
360 $extension = pathinfo($uri, PATHINFO_EXTENSION);
361 if ($extension === 'svg') {
362 $extension = 'svg+xml';
365 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
369 * Get a storage path for the given image URL.
370 * Ensures the path will start with "uploads/images".
371 * Returns null if the url cannot be resolved to a local URL.
373 private function imageUrlToStoragePath(string $url): ?string
375 $url = ltrim(trim($url), '/');
377 // Handle potential relative paths
378 $isRelative = strpos($url, 'http') !== 0;
380 if (strpos(strtolower($url), 'uploads/images') === 0) {
381 return trim($url, '/');
386 // Handle local images based on paths on the same domain
387 $potentialHostPaths = [
388 url('uploads/images/'),
389 $this->getPublicUrl('/uploads/images/'),
392 foreach ($potentialHostPaths as $potentialBasePath) {
393 $potentialBasePath = strtolower($potentialBasePath);
394 if (strpos(strtolower($url), $potentialBasePath) === 0) {
395 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
403 * Gets a public facing url for an image by checking relevant environment variables.
404 * If s3-style store is in use it will default to guessing a public bucket URL.
406 private function getPublicUrl(string $filePath): string
408 if ($this->storageUrl === null) {
409 $storageUrl = config('filesystems.url');
411 // Get the standard public s3 url if s3 is set as storage type
412 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
413 // region-based url will be used to prevent http issues.
414 if ($storageUrl == false && config('filesystems.images') === 's3') {
415 $storageDetails = config('filesystems.disks.s3');
416 if (strpos($storageDetails['bucket'], '.') === false) {
417 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
419 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
422 $this->storageUrl = $storageUrl;
425 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
426 return rtrim($basePath, '/') . $filePath;