1 <?php namespace BookStack\Services;
3 use BookStack\Exceptions\ImageUploadException;
5 use BookStack\ImageRevision;
8 use Intervention\Image\Exception\NotSupportedException;
9 use Intervention\Image\ImageManager;
10 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
11 use Illuminate\Contracts\Cache\Repository as Cache;
12 use Symfony\Component\HttpFoundation\File\UploadedFile;
14 class ImageService extends UploadService
19 protected $storageUrl;
22 * ImageService constructor.
27 public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
29 $this->imageTool = $imageTool;
30 $this->cache = $cache;
31 parent::__construct($fileSystem);
35 * Get the storage that will be used for storing images.
37 * @return \Illuminate\Contracts\Filesystem\Filesystem
39 protected function getStorage($type = '')
41 $storageType = config('filesystems.default');
43 // Override default location if set to local public to ensure not visible.
44 if ($type === 'system' && $storageType === 'local_secure') {
45 $storageType = 'local';
48 return $this->fileSystem->disk($storageType);
52 * Saves a new image from an upload.
53 * @param UploadedFile $uploadedFile
55 * @param int $uploadedTo
57 * @throws ImageUploadException
59 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
61 $imageName = $uploadedFile->getClientOriginalName();
62 $imageData = file_get_contents($uploadedFile->getRealPath());
63 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
67 * Save a new image from a uri-encoded base64 string of data.
68 * @param string $base64Uri
71 * @param int $uploadedTo
73 * @throws ImageUploadException
75 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
77 $splitData = explode(';base64,', $base64Uri);
78 if (count($splitData) < 2) {
79 throw new ImageUploadException("Invalid base64 image data provided");
81 $data = base64_decode($splitData[1]);
82 return $this->saveNew($name, $data, $type, $uploadedTo);
87 * @param string $base64Uri
89 * @throws ImageUploadException
91 public function updateImageFromBase64Uri(Image $image, string $base64Uri)
93 $splitData = explode(';base64,', $base64Uri);
94 if (count($splitData) < 2) {
95 throw new ImageUploadException("Invalid base64 image data provided");
97 $data = base64_decode($splitData[1]);
98 return $this->update($image, $data);
102 * Gets an image from url and saves it to the database.
104 * @param string $type
105 * @param bool|string $imageName
109 private function saveNewFromUrl($url, $type, $imageName = false)
111 $imageName = $imageName ? $imageName : basename($url);
112 $imageData = file_get_contents($url);
113 if ($imageData === false) {
114 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
116 return $this->saveNew($imageName, $imageData, $type);
121 * @param string $imageName
122 * @param string $imageData
123 * @param string $type
124 * @param int $uploadedTo
126 * @throws ImageUploadException
128 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
130 $storage = $this->getStorage($type);
131 $secureUploads = setting('app-secure-images');
132 $imageName = str_replace(' ', '-', $imageName);
134 if ($secureUploads) {
135 $imageName = str_random(16) . '-' . $imageName;
138 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
140 while ($storage->exists($imagePath . $imageName)) {
141 $imageName = str_random(3) . $imageName;
143 $fullPath = $imagePath . $imageName;
146 $storage->put($fullPath, $imageData);
147 $storage->setVisibility($fullPath, 'public');
148 } catch (Exception $e) {
149 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
153 'name' => $imageName,
155 'url' => $this->getPublicUrl($fullPath),
157 'uploaded_to' => $uploadedTo
160 if (user()->id !== 0) {
161 $userId = user()->id;
162 $imageDetails['created_by'] = $userId;
163 $imageDetails['updated_by'] = $userId;
166 $image = (new Image());
167 $image->forceFill($imageDetails)->save();
172 * Update the content of an existing image.
173 * Uploaded the new image content and creates a revision for the old image content.
174 * @param Image $image
177 * @throws ImageUploadException
179 private function update(Image $image, $imageData)
181 // Save image revision if not previously exists to ensure we always have
182 // a reference to the image files being uploaded.
183 if ($image->revisions()->count() === 0) {
184 $this->saveImageRevision($image);
187 $pathInfo = pathinfo($image->path);
188 $revisionCount = $image->revisionCount() + 1;
189 $newFileName = preg_replace('/^(.+?)(-v\d+)?$/', '$1-v' . $revisionCount, $pathInfo['filename']);
191 $image->path = str_replace_last($pathInfo['filename'], $newFileName, $image->path);
192 $image->url = $this->getPublicUrl($image->path);
193 $image->updated_by = user()->id;
195 $storage = $this->getStorage();
198 $storage->put($image->path, $imageData);
199 $storage->setVisibility($image->path, 'public');
201 $this->saveImageRevision($image);
202 } catch (Exception $e) {
203 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $image->path]));
209 * Save a new revision for an image.
210 * @param Image $image
211 * @return ImageRevision
213 protected function saveImageRevision(Image $image)
215 $revision = new ImageRevision();
216 $revision->image_id = $image->id;
217 $revision->path = $image->path;
218 $revision->url = $image->url;
219 $revision->created_by = user()->id;
220 $revision->revision = $image->revisionCount() + 1;
226 * Checks if the image is a gif. Returns true if it is, else false.
227 * @param Image $image
230 protected function isGif(Image $image)
232 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
236 * Get the thumbnail for an image.
237 * If $keepRatio is true only the width will be used.
238 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
239 * @param Image $image
242 * @param bool $keepRatio
245 * @throws ImageUploadException
247 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
249 if ($keepRatio && $this->isGif($image)) {
250 return $this->getPublicUrl($image->path);
253 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
254 $imagePath = $image->path;
255 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
257 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
258 return $this->getPublicUrl($thumbFilePath);
261 $storage = $this->getStorage($image->type);
262 if ($storage->exists($thumbFilePath)) {
263 return $this->getPublicUrl($thumbFilePath);
267 $thumb = $this->imageTool->make($storage->get($imagePath));
268 } catch (Exception $e) {
269 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
270 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
276 $thumb->resize($width, null, function ($constraint) {
277 $constraint->aspectRatio();
278 $constraint->upsize();
281 $thumb->fit($width, $height);
284 $thumbData = (string)$thumb->encode();
285 $storage->put($thumbFilePath, $thumbData);
286 $storage->setVisibility($thumbFilePath, 'public');
287 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
289 return $this->getPublicUrl($thumbFilePath);
293 * Get the raw data content from an image.
294 * @param Image $image
296 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
298 public function getImageData(Image $image)
300 $imagePath = $image->path;
301 $storage = $this->getStorage();
302 return $storage->get($imagePath);
306 * Destroy an image along with its revisions, thumbnails and remaining folders.
307 * @param Image $image
310 public function destroy(Image $image)
312 // Destroy image revisions
313 foreach ($image->revisions as $revision) {
314 $this->destroyImagesFromPath($revision->path);
318 // Destroy main image
319 $this->destroyImagesFromPath($image->path);
324 * Destroys an image at the given path.
325 * Searches for image thumbnails in addition to main provided path..
326 * @param string $path
329 protected function destroyImagesFromPath(string $path)
331 $storage = $this->getStorage();
333 $imageFolder = dirname($path);
334 $imageFileName = basename($path);
335 $allImages = collect($storage->allFiles($imageFolder));
337 // Delete image files
338 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
339 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
340 return strpos($imagePath, $imageFileName) === $expectedIndex;
342 $storage->delete($imagesToDelete->all());
344 // Cleanup of empty folders
345 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
346 foreach ($foldersInvolved as $directory) {
347 if ($this->isFolderEmpty($directory)) {
348 $storage->deleteDirectory($directory);
356 * Save a gravatar image and set a the profile image for a user.
362 public function saveUserGravatar(User $user, $size = 500)
364 $emailHash = md5(strtolower(trim($user->email)));
365 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
366 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
367 $image = $this->saveNewFromUrl($url, 'user', $imageName);
368 $image->created_by = $user->id;
369 $image->updated_by = $user->id;
375 * Convert a image URI to a Base64 encoded string.
376 * Attempts to find locally via set storage method first.
378 * @return null|string
379 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
381 public function imageUriToBase64(string $uri)
383 $isLocal = strpos(trim($uri), 'http') !== 0;
385 // Attempt to find local files even if url not absolute
386 $base = baseUrl('/');
387 if (!$isLocal && strpos($uri, $base) === 0) {
389 $uri = str_replace($base, '', $uri);
395 $uri = trim($uri, '/');
396 $storage = $this->getStorage();
397 if ($storage->exists($uri)) {
398 $imageData = $storage->get($uri);
403 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
404 $imageData = curl_exec($ch);
405 $err = curl_error($ch);
408 throw new \Exception("Image fetch failed, Received error: " . $err);
410 } catch (\Exception $e) {
414 if ($imageData === null) {
418 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
422 * Gets a public facing url for an image by checking relevant environment variables.
423 * @param string $filePath
426 private function getPublicUrl($filePath)
428 if ($this->storageUrl === null) {
429 $storageUrl = config('filesystems.url');
431 // Get the standard public s3 url if s3 is set as storage type
432 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
433 // region-based url will be used to prevent http issues.
434 if ($storageUrl == false && config('filesystems.default') === 's3') {
435 $storageDetails = config('filesystems.disks.s3');
436 if (strpos($storageDetails['bucket'], '.') === false) {
437 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
439 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
442 $this->storageUrl = $storageUrl;
445 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
446 return rtrim($basePath, '/') . $filePath;