1 <?php namespace BookStack\Uploads;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\ImageUploadException;
7 use Illuminate\Contracts\Cache\Repository as Cache;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Intervention\Image\Exception\NotSupportedException;
10 use Intervention\Image\ImageManager;
11 use Symfony\Component\HttpFoundation\File\UploadedFile;
13 class ImageService extends UploadService
18 protected $storageUrl;
22 * ImageService constructor.
24 * @param ImageManager $imageTool
25 * @param FileSystem $fileSystem
28 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
30 $this->image = $image;
31 $this->imageTool = $imageTool;
32 $this->cache = $cache;
33 parent::__construct($fileSystem);
37 * Get the storage that will be used for storing images.
39 * @return \Illuminate\Contracts\Filesystem\Filesystem
41 protected function getStorage($type = '')
43 $storageType = config('filesystems.default');
45 // Override default location if set to local public to ensure not visible.
46 if ($type === 'system' && $storageType === 'local_secure') {
47 $storageType = 'local';
50 return $this->fileSystem->disk($storageType);
54 * Saves a new image from an upload.
55 * @param UploadedFile $uploadedFile
57 * @param int $uploadedTo
59 * @throws ImageUploadException
61 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
63 $imageName = $uploadedFile->getClientOriginalName();
64 $imageData = file_get_contents($uploadedFile->getRealPath());
65 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
69 * Save a new image from a uri-encoded base64 string of data.
70 * @param string $base64Uri
73 * @param int $uploadedTo
75 * @throws ImageUploadException
77 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
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 * Gets an image from url and saves it to the database.
91 * @param bool|string $imageName
95 private function saveNewFromUrl($url, $type, $imageName = false)
97 $imageName = $imageName ? $imageName : basename($url);
98 $imageData = file_get_contents($url);
99 if ($imageData === false) {
100 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
102 return $this->saveNew($imageName, $imageData, $type);
107 * @param string $imageName
108 * @param string $imageData
109 * @param string $type
110 * @param int $uploadedTo
112 * @throws ImageUploadException
114 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
116 $storage = $this->getStorage($type);
117 $secureUploads = setting('app-secure-images');
118 $imageName = str_replace(' ', '-', $imageName);
120 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
122 while ($storage->exists($imagePath . $imageName)) {
123 $imageName = str_random(3) . $imageName;
126 $fullPath = $imagePath . $imageName;
127 if ($secureUploads) {
128 $fullPath = $imagePath . str_random(16) . '-' . $imageName;
132 $storage->put($fullPath, $imageData);
133 $storage->setVisibility($fullPath, 'public');
134 } catch (Exception $e) {
135 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
139 'name' => $imageName,
141 'url' => $this->getPublicUrl($fullPath),
143 'uploaded_to' => $uploadedTo
146 if (user()->id !== 0) {
147 $userId = user()->id;
148 $imageDetails['created_by'] = $userId;
149 $imageDetails['updated_by'] = $userId;
152 $image = $this->image->newInstance();
153 $image->forceFill($imageDetails)->save();
159 * Checks if the image is a gif. Returns true if it is, else false.
160 * @param Image $image
163 protected function isGif(Image $image)
165 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
169 * Get the thumbnail for an image.
170 * If $keepRatio is true only the width will be used.
171 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
172 * @param Image $image
175 * @param bool $keepRatio
178 * @throws ImageUploadException
180 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
182 if ($keepRatio && $this->isGif($image)) {
183 return $this->getPublicUrl($image->path);
186 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
187 $imagePath = $image->path;
188 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
190 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
191 return $this->getPublicUrl($thumbFilePath);
194 $storage = $this->getStorage($image->type);
195 if ($storage->exists($thumbFilePath)) {
196 return $this->getPublicUrl($thumbFilePath);
200 $thumb = $this->imageTool->make($storage->get($imagePath));
201 } catch (Exception $e) {
202 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
203 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
209 $thumb->resize($width, null, function ($constraint) {
210 $constraint->aspectRatio();
211 $constraint->upsize();
214 $thumb->fit($width, $height);
217 $thumbData = (string)$thumb->encode();
218 $storage->put($thumbFilePath, $thumbData);
219 $storage->setVisibility($thumbFilePath, 'public');
220 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
222 return $this->getPublicUrl($thumbFilePath);
226 * Get the raw data content from an image.
227 * @param Image $image
229 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
231 public function getImageData(Image $image)
233 $imagePath = $image->path;
234 $storage = $this->getStorage();
235 return $storage->get($imagePath);
239 * Destroy an image along with its revisions, thumbnails and remaining folders.
240 * @param Image $image
243 public function destroy(Image $image)
245 $this->destroyImagesFromPath($image->path);
250 * Destroys an image at the given path.
251 * Searches for image thumbnails in addition to main provided path..
252 * @param string $path
255 protected function destroyImagesFromPath(string $path)
257 $storage = $this->getStorage();
259 $imageFolder = dirname($path);
260 $imageFileName = basename($path);
261 $allImages = collect($storage->allFiles($imageFolder));
263 // Delete image files
264 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
265 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
266 return strpos($imagePath, $imageFileName) === $expectedIndex;
268 $storage->delete($imagesToDelete->all());
270 // Cleanup of empty folders
271 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
272 foreach ($foldersInvolved as $directory) {
273 if ($this->isFolderEmpty($directory)) {
274 $storage->deleteDirectory($directory);
282 * Save a gravatar image and set a the profile image for a user.
283 * @param \BookStack\Auth\User $user
288 public function saveUserGravatar(User $user, $size = 500)
290 $emailHash = md5(strtolower(trim($user->email)));
291 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
292 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
293 $image = $this->saveNewFromUrl($url, 'user', $imageName);
294 $image->created_by = $user->id;
295 $image->updated_by = $user->id;
302 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
303 * Checks based off of only the image name.
304 * Could be much improved to be more specific but kept it generic for now to be safe.
306 * Returns the path of the images that would be/have been deleted.
307 * @param bool $checkRevisions
308 * @param bool $dryRun
309 * @param array $types
312 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
314 $types = array_intersect($types, ['gallery', 'drawio']);
317 $this->image->newQuery()->whereIn('type', $types)
318 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
319 foreach ($images as $image) {
320 $searchQuery = '%' . basename($image->path) . '%';
321 $inPage = DB::table('pages')
322 ->where('html', 'like', $searchQuery)->count() > 0;
324 if ($checkRevisions) {
325 $inRevision = DB::table('page_revisions')
326 ->where('html', 'like', $searchQuery)->count() > 0;
329 if (!$inPage && !$inRevision) {
330 $deletedPaths[] = $image->path;
332 $this->destroy($image);
337 return $deletedPaths;
341 * Convert a image URI to a Base64 encoded string.
342 * Attempts to find locally via set storage method first.
344 * @return null|string
345 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
347 public function imageUriToBase64(string $uri)
349 $isLocal = strpos(trim($uri), 'http') !== 0;
351 // Attempt to find local files even if url not absolute
352 $base = baseUrl('/');
353 if (!$isLocal && strpos($uri, $base) === 0) {
355 $uri = str_replace($base, '', $uri);
361 $uri = trim($uri, '/');
362 $storage = $this->getStorage();
363 if ($storage->exists($uri)) {
364 $imageData = $storage->get($uri);
369 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
370 $imageData = curl_exec($ch);
371 $err = curl_error($ch);
374 throw new \Exception("Image fetch failed, Received error: " . $err);
376 } catch (\Exception $e) {
380 if ($imageData === null) {
384 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
388 * Gets a public facing url for an image by checking relevant environment variables.
389 * @param string $filePath
392 private function getPublicUrl($filePath)
394 if ($this->storageUrl === null) {
395 $storageUrl = config('filesystems.url');
397 // Get the standard public s3 url if s3 is set as storage type
398 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
399 // region-based url will be used to prevent http issues.
400 if ($storageUrl == false && config('filesystems.default') === 's3') {
401 $storageDetails = config('filesystems.disks.s3');
402 if (strpos($storageDetails['bucket'], '.') === false) {
403 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
405 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
408 $this->storageUrl = $storageUrl;
411 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
412 return rtrim($basePath, '/') . $filePath;