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 * Replace the data for an image via a Base64 encoded string.
71 * @param string $base64Uri
73 * @throws ImageUploadException
75 public function replaceImageDataFromBase64Uri(Image $image, string $base64Uri)
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 $storage = $this->getStorage();
85 $storage->put($image->path, $data);
86 } catch (Exception $e) {
87 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $image->path]));
94 * Gets an image from url and saves it to the database.
97 * @param bool|string $imageName
101 private function saveNewFromUrl($url, $type, $imageName = false)
103 $imageName = $imageName ? $imageName : basename($url);
104 $imageData = file_get_contents($url);
105 if($imageData === false) throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
106 return $this->saveNew($imageName, $imageData, $type);
111 * @param string $imageName
112 * @param string $imageData
113 * @param string $type
114 * @param int $uploadedTo
116 * @throws ImageUploadException
118 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
120 $storage = $this->getStorage();
121 $secureUploads = setting('app-secure-images');
122 $imageName = str_replace(' ', '-', $imageName);
124 if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
126 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
128 if ($this->isLocal()) $imagePath = '/public' . $imagePath;
130 while ($storage->exists($imagePath . $imageName)) {
131 $imageName = str_random(3) . $imageName;
133 $fullPath = $imagePath . $imageName;
136 $storage->put($fullPath, $imageData);
137 $storage->setVisibility($fullPath, 'public');
138 } catch (Exception $e) {
139 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
142 if ($this->isLocal()) $fullPath = str_replace_first('/public', '', $fullPath);
145 'name' => $imageName,
147 'url' => $this->getPublicUrl($fullPath),
149 'uploaded_to' => $uploadedTo
152 if (user()->id !== 0) {
153 $userId = user()->id;
154 $imageDetails['created_by'] = $userId;
155 $imageDetails['updated_by'] = $userId;
158 $image = Image::forceCreate($imageDetails);
164 * Get the storage path, Dependant of storage type.
165 * @param Image $image
166 * @return mixed|string
168 protected function getPath(Image $image)
170 return ($this->isLocal()) ? ('public/' . $image->path) : $image->path;
174 * Get the thumbnail for an image.
175 * If $keepRatio is true only the width will be used.
176 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
178 * @param Image $image
181 * @param bool $keepRatio
184 * @throws ImageUploadException
186 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
188 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
189 $imagePath = $this->getPath($image);
190 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
192 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
193 return $this->getPublicUrl($thumbFilePath);
196 $storage = $this->getStorage();
198 if ($storage->exists($thumbFilePath)) {
199 return $this->getPublicUrl($thumbFilePath);
203 $thumb = $this->imageTool->make($storage->get($imagePath));
204 } catch (Exception $e) {
205 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
206 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
213 $thumb->resize($width, null, function ($constraint) {
214 $constraint->aspectRatio();
215 $constraint->upsize();
218 $thumb->fit($width, $height);
221 $thumbData = (string)$thumb->encode();
222 $storage->put($thumbFilePath, $thumbData);
223 $storage->setVisibility($thumbFilePath, 'public');
224 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
226 return $this->getPublicUrl($thumbFilePath);
230 * Get the raw data content from an image.
231 * @param Image $image
233 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
235 public function getImageData(Image $image)
237 $imagePath = $this->getPath($image);
238 $storage = $this->getStorage();
239 return $storage->get($imagePath);
243 * Destroys an Image object along with its files and thumbnails.
244 * @param Image $image
247 public function destroyImage(Image $image)
249 $storage = $this->getStorage();
251 $imageFolder = dirname($this->getPath($image));
252 $imageFileName = basename($this->getPath($image));
253 $allImages = collect($storage->allFiles($imageFolder));
255 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
256 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
257 return strpos($imagePath, $imageFileName) === $expectedIndex;
260 $storage->delete($imagesToDelete->all());
262 // Cleanup of empty folders
263 foreach ($storage->directories($imageFolder) as $directory) {
264 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
266 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
273 * Save a gravatar image and set a the profile image for a user.
278 public function saveUserGravatar(User $user, $size = 500)
280 $emailHash = md5(strtolower(trim($user->email)));
281 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
282 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
283 $image = $this->saveNewFromUrl($url, 'user', $imageName);
284 $image->created_by = $user->id;
285 $image->updated_by = $user->id;
291 * Gets a public facing url for an image by checking relevant environment variables.
292 * @param string $filePath
295 private function getPublicUrl($filePath)
297 if ($this->storageUrl === null) {
298 $storageUrl = config('filesystems.url');
300 // Get the standard public s3 url if s3 is set as storage type
301 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
302 // region-based url will be used to prevent http issues.
303 if ($storageUrl == false && config('filesystems.default') === 's3') {
304 $storageDetails = config('filesystems.disks.s3');
305 if (strpos($storageDetails['bucket'], '.') === false) {
306 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
308 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
312 $this->storageUrl = $storageUrl;
315 if ($this->isLocal()) $filePath = str_replace_first('public/', '', $filePath);
317 return ($this->storageUrl == false ? rtrim(baseUrl(''), '/') : rtrim($this->storageUrl, '/')) . $filePath;