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);
51 * Gets an image from url and saves it to the database.
54 * @param bool|string $imageName
58 private function saveNewFromUrl($url, $type, $imageName = false)
60 $imageName = $imageName ? $imageName : basename($url);
61 $imageData = file_get_contents($url);
62 if($imageData === false) throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
63 return $this->saveNew($imageName, $imageData, $type);
68 * @param string $imageName
69 * @param string $imageData
71 * @param int $uploadedTo
73 * @throws ImageUploadException
75 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
77 $storage = $this->getStorage();
78 $secureUploads = setting('app-secure-images');
79 $imageName = str_replace(' ', '-', $imageName);
81 if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
83 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
85 if ($this->isLocal()) $imagePath = '/public' . $imagePath;
87 while ($storage->exists($imagePath . $imageName)) {
88 $imageName = str_random(3) . $imageName;
90 $fullPath = $imagePath . $imageName;
93 $storage->put($fullPath, $imageData);
94 $storage->setVisibility($fullPath, 'public');
95 } catch (Exception $e) {
96 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
99 if ($this->isLocal()) $fullPath = str_replace_first('/public', '', $fullPath);
102 'name' => $imageName,
104 'url' => $this->getPublicUrl($fullPath),
106 'uploaded_to' => $uploadedTo
109 if (user()->id !== 0) {
110 $userId = user()->id;
111 $imageDetails['created_by'] = $userId;
112 $imageDetails['updated_by'] = $userId;
115 $image = Image::forceCreate($imageDetails);
121 * Get the storage path, Dependant of storage type.
122 * @param Image $image
123 * @return mixed|string
125 protected function getPath(Image $image)
127 return ($this->isLocal()) ? ('public/' . $image->path) : $image->path;
131 * Get the thumbnail for an image.
132 * If $keepRatio is true only the width will be used.
133 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
135 * @param Image $image
138 * @param bool $keepRatio
141 * @throws ImageUploadException
143 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
145 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
146 $imagePath = $this->getPath($image);
147 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
149 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
150 return $this->getPublicUrl($thumbFilePath);
153 $storage = $this->getStorage();
155 if ($storage->exists($thumbFilePath)) {
156 return $this->getPublicUrl($thumbFilePath);
160 $thumb = $this->imageTool->make($storage->get($imagePath));
161 } catch (Exception $e) {
162 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
163 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
170 $thumb->resize($width, null, function ($constraint) {
171 $constraint->aspectRatio();
172 $constraint->upsize();
175 $thumb->fit($width, $height);
178 $thumbData = (string)$thumb->encode();
179 $storage->put($thumbFilePath, $thumbData);
180 $storage->setVisibility($thumbFilePath, 'public');
181 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
183 return $this->getPublicUrl($thumbFilePath);
187 * Destroys an Image object along with its files and thumbnails.
188 * @param Image $image
191 public function destroyImage(Image $image)
193 $storage = $this->getStorage();
195 $imageFolder = dirname($this->getPath($image));
196 $imageFileName = basename($this->getPath($image));
197 $allImages = collect($storage->allFiles($imageFolder));
199 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
200 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
201 return strpos($imagePath, $imageFileName) === $expectedIndex;
204 $storage->delete($imagesToDelete->all());
206 // Cleanup of empty folders
207 foreach ($storage->directories($imageFolder) as $directory) {
208 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
210 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
217 * Save a gravatar image and set a the profile image for a user.
222 public function saveUserGravatar(User $user, $size = 500)
224 $emailHash = md5(strtolower(trim($user->email)));
225 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
226 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
227 $image = $this->saveNewFromUrl($url, 'user', $imageName);
228 $image->created_by = $user->id;
229 $image->updated_by = $user->id;
235 * Gets a public facing url for an image by checking relevant environment variables.
236 * @param string $filePath
239 private function getPublicUrl($filePath)
241 if ($this->storageUrl === null) {
242 $storageUrl = config('filesystems.url');
244 // Get the standard public s3 url if s3 is set as storage type
245 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
246 // region-based url will be used to prevent http issues.
247 if ($storageUrl == false && config('filesystems.default') === 's3') {
248 $storageDetails = config('filesystems.disks.s3');
249 if (strpos($storageDetails['bucket'], '.') === false) {
250 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
252 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
256 $this->storageUrl = $storageUrl;
259 if ($this->isLocal()) $filePath = str_replace_first('public/', '', $filePath);
261 return ($this->storageUrl == false ? rtrim(baseUrl(''), '/') : rtrim($this->storageUrl, '/')) . $filePath;