1 <?php namespace BookStack\Services;
3 use BookStack\Exceptions\ImageUploadException;
7 use Intervention\Image\Exception\NotSupportedException;
8 use Intervention\Image\ImageManager;
9 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
10 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
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);
86 * Replace the data for an image via a Base64 encoded string.
88 * @param string $base64Uri
90 * @throws ImageUploadException
92 public function replaceImageDataFromBase64Uri(Image $image, string $base64Uri)
94 $splitData = explode(';base64,', $base64Uri);
95 if (count($splitData) < 2) {
96 throw new ImageUploadException("Invalid base64 image data provided");
98 $data = base64_decode($splitData[1]);
99 $storage = $this->getStorage();
102 $storage->put($image->path, $data);
103 } catch (Exception $e) {
104 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $image->path]));
111 * Gets an image from url and saves it to the database.
113 * @param string $type
114 * @param bool|string $imageName
118 private function saveNewFromUrl($url, $type, $imageName = false)
120 $imageName = $imageName ? $imageName : basename($url);
121 $imageData = file_get_contents($url);
122 if ($imageData === false) {
123 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
125 return $this->saveNew($imageName, $imageData, $type);
130 * @param string $imageName
131 * @param string $imageData
132 * @param string $type
133 * @param int $uploadedTo
135 * @throws ImageUploadException
137 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
139 $storage = $this->getStorage($type);
140 $secureUploads = setting('app-secure-images');
141 $imageName = str_replace(' ', '-', $imageName);
143 if ($secureUploads) {
144 $imageName = str_random(16) . '-' . $imageName;
147 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
149 while ($storage->exists($imagePath . $imageName)) {
150 $imageName = str_random(3) . $imageName;
152 $fullPath = $imagePath . $imageName;
155 $storage->put($fullPath, $imageData);
156 $storage->setVisibility($fullPath, 'public');
157 } catch (Exception $e) {
158 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
162 'name' => $imageName,
164 'url' => $this->getPublicUrl($fullPath),
166 'uploaded_to' => $uploadedTo
169 if (user()->id !== 0) {
170 $userId = user()->id;
171 $imageDetails['created_by'] = $userId;
172 $imageDetails['updated_by'] = $userId;
175 $image = (new Image());
176 $image->forceFill($imageDetails)->save();
181 * Get the storage path, Dependant of storage type.
182 * @param Image $image
183 * @return mixed|string
185 protected function getPath(Image $image)
191 * Checks if the image is a gif. Returns true if it is, else false.
192 * @param Image $image
195 protected function isGif(Image $image)
197 return strtolower(pathinfo($this->getPath($image), PATHINFO_EXTENSION)) === 'gif';
201 * Get the thumbnail for an image.
202 * If $keepRatio is true only the width will be used.
203 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
204 * @param Image $image
207 * @param bool $keepRatio
210 * @throws ImageUploadException
212 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
214 if ($keepRatio && $this->isGif($image)) {
215 return $this->getPublicUrl($this->getPath($image));
218 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
219 $imagePath = $this->getPath($image);
220 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
222 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
223 return $this->getPublicUrl($thumbFilePath);
226 $storage = $this->getStorage($image->type);
227 if ($storage->exists($thumbFilePath)) {
228 return $this->getPublicUrl($thumbFilePath);
232 $thumb = $this->imageTool->make($storage->get($imagePath));
233 } catch (Exception $e) {
234 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
235 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
241 $thumb->resize($width, null, function ($constraint) {
242 $constraint->aspectRatio();
243 $constraint->upsize();
246 $thumb->fit($width, $height);
249 $thumbData = (string)$thumb->encode();
250 $storage->put($thumbFilePath, $thumbData);
251 $storage->setVisibility($thumbFilePath, 'public');
252 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
254 return $this->getPublicUrl($thumbFilePath);
258 * Get the raw data content from an image.
259 * @param Image $image
261 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
263 public function getImageData(Image $image)
265 $imagePath = $this->getPath($image);
266 $storage = $this->getStorage();
267 return $storage->get($imagePath);
271 * Destroys an Image object along with its files and thumbnails.
272 * @param Image $image
276 public function destroyImage(Image $image)
278 $storage = $this->getStorage();
280 $imageFolder = dirname($this->getPath($image));
281 $imageFileName = basename($this->getPath($image));
282 $allImages = collect($storage->allFiles($imageFolder));
284 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
285 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
286 return strpos($imagePath, $imageFileName) === $expectedIndex;
289 $storage->delete($imagesToDelete->all());
291 // Cleanup of empty folders
292 foreach ($storage->directories($imageFolder) as $directory) {
293 if ($this->isFolderEmpty($directory)) {
294 $storage->deleteDirectory($directory);
297 if ($this->isFolderEmpty($imageFolder)) {
298 $storage->deleteDirectory($imageFolder);
306 * Save a gravatar image and set a the profile image for a user.
312 public function saveUserGravatar(User $user, $size = 500)
314 $emailHash = md5(strtolower(trim($user->email)));
315 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
316 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
317 $image = $this->saveNewFromUrl($url, 'user', $imageName);
318 $image->created_by = $user->id;
319 $image->updated_by = $user->id;
325 * Gets a public facing url for an image by checking relevant environment variables.
326 * @param string $filePath
329 private function getPublicUrl($filePath)
331 if ($this->storageUrl === null) {
332 $storageUrl = config('filesystems.url');
334 // Get the standard public s3 url if s3 is set as storage type
335 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
336 // region-based url will be used to prevent http issues.
337 if ($storageUrl == false && config('filesystems.default') === 's3') {
338 $storageDetails = config('filesystems.disks.s3');
339 if (strpos($storageDetails['bucket'], '.') === false) {
340 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
342 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
345 $this->storageUrl = $storageUrl;
348 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
349 return rtrim($basePath, '/') . $filePath;