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 * Saves a new image from an upload.
36 * @param UploadedFile $uploadedFile
38 * @param int $uploadedTo
40 * @throws ImageUploadException
42 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
44 $imageName = $uploadedFile->getClientOriginalName();
45 $imageData = file_get_contents($uploadedFile->getRealPath());
46 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
50 * Save a new image from a uri-encoded base64 string of data.
51 * @param string $base64Uri
54 * @param int $uploadedTo
56 * @throws ImageUploadException
58 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
60 $splitData = explode(';base64,', $base64Uri);
61 if (count($splitData) < 2) {
62 throw new ImageUploadException("Invalid base64 image data provided");
64 $data = base64_decode($splitData[1]);
65 return $this->saveNew($name, $data, $type, $uploadedTo);
69 * Gets an image from url and saves it to the database.
72 * @param bool|string $imageName
76 private function saveNewFromUrl($url, $type, $imageName = false)
78 $imageName = $imageName ? $imageName : basename($url);
79 $imageData = file_get_contents($url);
80 if($imageData === false) throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
81 return $this->saveNew($imageName, $imageData, $type);
86 * @param string $imageName
87 * @param string $imageData
89 * @param int $uploadedTo
91 * @throws ImageUploadException
93 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
95 $storage = $this->getStorage();
96 $secureUploads = setting('app-secure-images');
97 $imageName = str_replace(' ', '-', $imageName);
99 if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
101 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
103 if ($this->isLocal()) $imagePath = '/public' . $imagePath;
105 while ($storage->exists($imagePath . $imageName)) {
106 $imageName = str_random(3) . $imageName;
108 $fullPath = $imagePath . $imageName;
111 $storage->put($fullPath, $imageData);
112 $storage->setVisibility($fullPath, 'public');
113 } catch (Exception $e) {
114 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
117 if ($this->isLocal()) $fullPath = str_replace_first('/public', '', $fullPath);
120 'name' => $imageName,
122 'url' => $this->getPublicUrl($fullPath),
124 'uploaded_to' => $uploadedTo
127 if (user()->id !== 0) {
128 $userId = user()->id;
129 $imageDetails['created_by'] = $userId;
130 $imageDetails['updated_by'] = $userId;
133 $image = Image::forceCreate($imageDetails);
139 * Get the storage path, Dependant of storage type.
140 * @param Image $image
141 * @return mixed|string
143 protected function getPath(Image $image)
145 return ($this->isLocal()) ? ('public/' . $image->path) : $image->path;
149 * Get the thumbnail for an image.
150 * If $keepRatio is true only the width will be used.
151 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
153 * @param Image $image
156 * @param bool $keepRatio
159 * @throws ImageUploadException
161 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
163 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
164 $imagePath = $this->getPath($image);
165 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
167 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
168 return $this->getPublicUrl($thumbFilePath);
171 $storage = $this->getStorage();
173 if ($storage->exists($thumbFilePath)) {
174 return $this->getPublicUrl($thumbFilePath);
178 $thumb = $this->imageTool->make($storage->get($imagePath));
179 } catch (Exception $e) {
180 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
181 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
188 $thumb->resize($width, null, function ($constraint) {
189 $constraint->aspectRatio();
190 $constraint->upsize();
193 $thumb->fit($width, $height);
196 $thumbData = (string)$thumb->encode();
197 $storage->put($thumbFilePath, $thumbData);
198 $storage->setVisibility($thumbFilePath, 'public');
199 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
201 return $this->getPublicUrl($thumbFilePath);
205 * Get the raw data content from an image.
206 * @param Image $image
208 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
210 public function getImageData(Image $image)
212 $imagePath = $this->getPath($image);
213 $storage = $this->getStorage();
214 return $storage->get($imagePath);
218 * Destroys an Image object along with its files and thumbnails.
219 * @param Image $image
222 public function destroyImage(Image $image)
224 $storage = $this->getStorage();
226 $imageFolder = dirname($this->getPath($image));
227 $imageFileName = basename($this->getPath($image));
228 $allImages = collect($storage->allFiles($imageFolder));
230 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
231 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
232 return strpos($imagePath, $imageFileName) === $expectedIndex;
235 $storage->delete($imagesToDelete->all());
237 // Cleanup of empty folders
238 foreach ($storage->directories($imageFolder) as $directory) {
239 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
241 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
248 * Save a gravatar image and set a the profile image for a user.
253 public function saveUserGravatar(User $user, $size = 500)
255 $emailHash = md5(strtolower(trim($user->email)));
256 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
257 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
258 $image = $this->saveNewFromUrl($url, 'user', $imageName);
259 $image->created_by = $user->id;
260 $image->updated_by = $user->id;
266 * Gets a public facing url for an image by checking relevant environment variables.
267 * @param string $filePath
270 private function getPublicUrl($filePath)
272 if ($this->storageUrl === null) {
273 $storageUrl = config('filesystems.url');
275 // Get the standard public s3 url if s3 is set as storage type
276 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
277 // region-based url will be used to prevent http issues.
278 if ($storageUrl == false && config('filesystems.default') === 's3') {
279 $storageDetails = config('filesystems.disks.s3');
280 if (strpos($storageDetails['bucket'], '.') === false) {
281 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
283 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
287 $this->storageUrl = $storageUrl;
290 if ($this->isLocal()) $filePath = str_replace_first('public/', '', $filePath);
292 return ($this->storageUrl == false ? rtrim(baseUrl(''), '/') : rtrim($this->storageUrl, '/')) . $filePath;