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 * Gets an image from url and saves it to the database.
53 * @param bool|string $imageName
57 private function saveNewFromUrl($url, $type, $imageName = false)
59 $imageName = $imageName ? $imageName : basename($url);
60 $imageData = file_get_contents($url);
61 if($imageData === false) throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
62 return $this->saveNew($imageName, $imageData, $type);
67 * @param string $imageName
68 * @param string $imageData
70 * @param int $uploadedTo
72 * @throws ImageUploadException
74 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
76 $storage = $this->getStorage();
77 $secureUploads = setting('app-secure-images');
78 $imageName = str_replace(' ', '-', $imageName);
80 if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
82 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
84 while ($storage->exists($imagePath . $imageName)) {
85 $imageName = str_random(3) . $imageName;
87 $fullPath = $imagePath . $imageName;
90 $storage->put($fullPath, $imageData);
91 $storage->setVisibility($fullPath, 'public');
92 } catch (Exception $e) {
93 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
99 'url' => $this->getPublicUrl($fullPath),
101 'uploaded_to' => $uploadedTo
104 if (user()->id !== 0) {
105 $userId = user()->id;
106 $imageDetails['created_by'] = $userId;
107 $imageDetails['updated_by'] = $userId;
110 $image = (new Image());
111 $image->forceFill($imageDetails)->save();
116 * Get the storage path, Dependant of storage type.
117 * @param Image $image
118 * @return mixed|string
120 protected function getPath(Image $image)
126 * Get the thumbnail for an image.
127 * If $keepRatio is true only the width will be used.
128 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
129 * @param Image $image
132 * @param bool $keepRatio
135 * @throws ImageUploadException
137 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
139 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
140 $imagePath = $this->getPath($image);
141 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
143 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
144 return $this->getPublicUrl($thumbFilePath);
147 $storage = $this->getStorage();
148 if ($storage->exists($thumbFilePath)) {
149 return $this->getPublicUrl($thumbFilePath);
153 $thumb = $this->imageTool->make($storage->get($imagePath));
154 } catch (Exception $e) {
155 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
156 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
162 $thumb->resize($width, null, function ($constraint) {
163 $constraint->aspectRatio();
164 $constraint->upsize();
167 $thumb->fit($width, $height);
170 $thumbData = (string)$thumb->encode();
171 $storage->put($thumbFilePath, $thumbData);
172 $storage->setVisibility($thumbFilePath, 'public');
173 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
175 return $this->getPublicUrl($thumbFilePath);
179 * Destroys an Image object along with its files and thumbnails.
180 * @param Image $image
183 public function destroyImage(Image $image)
185 $storage = $this->getStorage();
187 $imageFolder = dirname($this->getPath($image));
188 $imageFileName = basename($this->getPath($image));
189 $allImages = collect($storage->allFiles($imageFolder));
191 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
192 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
193 return strpos($imagePath, $imageFileName) === $expectedIndex;
196 $storage->delete($imagesToDelete->all());
198 // Cleanup of empty folders
199 foreach ($storage->directories($imageFolder) as $directory) {
200 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
202 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
209 * Save a gravatar image and set a the profile image for a user.
214 public function saveUserGravatar(User $user, $size = 500)
216 $emailHash = md5(strtolower(trim($user->email)));
217 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
218 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
219 $image = $this->saveNewFromUrl($url, 'user', $imageName);
220 $image->created_by = $user->id;
221 $image->updated_by = $user->id;
227 * Gets a public facing url for an image by checking relevant environment variables.
228 * @param string $filePath
231 private function getPublicUrl($filePath)
233 if ($this->storageUrl === null) {
234 $storageUrl = config('filesystems.url');
236 // Get the standard public s3 url if s3 is set as storage type
237 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
238 // region-based url will be used to prevent http issues.
239 if ($storageUrl == false && config('filesystems.default') === 's3') {
240 $storageDetails = config('filesystems.disks.s3');
241 if (strpos($storageDetails['bucket'], '.') === false) {
242 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
244 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
247 $this->storageUrl = $storageUrl;
250 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
251 return rtrim($basePath, '/') . $filePath;