1 <?php namespace BookStack\Services;
3 use BookStack\Exceptions\ImageUploadException;
7 use Intervention\Image\ImageManager;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
10 use Illuminate\Contracts\Cache\Repository as Cache;
12 use Symfony\Component\HttpFoundation\File\UploadedFile;
18 protected $fileSystem;
22 * @var FileSystemInstance
24 protected $storageInstance;
25 protected $storageUrl;
28 * ImageService constructor.
33 public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
35 $this->imageTool = $imageTool;
36 $this->fileSystem = $fileSystem;
37 $this->cache = $cache;
41 * Saves a new image from an upload.
42 * @param UploadedFile $uploadedFile
46 public function saveNewFromUpload(UploadedFile $uploadedFile, $type)
48 $imageName = $uploadedFile->getClientOriginalName();
49 $imageData = file_get_contents($uploadedFile->getRealPath());
50 return $this->saveNew($imageName, $imageData, $type);
55 * Gets an image from url and saves it to the database.
58 * @param bool|string $imageName
62 private function saveNewFromUrl($url, $type, $imageName = false)
64 $imageName = $imageName ? $imageName : basename($url);
65 $imageData = file_get_contents($url);
66 if($imageData === false) throw new \Exception('Cannot get image from ' . $url);
67 return $this->saveNew($imageName, $imageData, $type);
72 * @param string $imageName
73 * @param string $imageData
76 * @throws ImageUploadException
78 private function saveNew($imageName, $imageData, $type)
80 $storage = $this->getStorage();
81 $secureUploads = Setting::get('app-secure-images');
82 $imageName = str_replace(' ', '-', $imageName);
84 if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
86 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
87 while ($storage->exists($imagePath . $imageName)) {
88 $imageName = str_random(3) . $imageName;
90 $fullPath = $imagePath . $imageName;
93 $storage->put($fullPath, $imageData);
94 } catch (Exception $e) {
95 throw new ImageUploadException('Image Path ' . $fullPath . ' is not writable by the server.');
101 'url' => $this->getPublicUrl($fullPath),
105 if (auth()->user() && auth()->user()->id !== 0) {
106 $userId = auth()->user()->id;
107 $imageDetails['created_by'] = $userId;
108 $imageDetails['updated_by'] = $userId;
111 $image = Image::forceCreate($imageDetails);
117 * Get the thumbnail for an image.
118 * If $keepRatio is true only the width will be used.
119 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
121 * @param Image $image
124 * @param bool $keepRatio
127 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
129 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
130 $thumbFilePath = dirname($image->path) . $thumbDirName . basename($image->path);
132 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
133 return $this->getPublicUrl($thumbFilePath);
136 $storage = $this->getStorage();
138 if ($storage->exists($thumbFilePath)) {
139 return $this->getPublicUrl($thumbFilePath);
142 // Otherwise create the thumbnail
143 $thumb = $this->imageTool->make($storage->get($image->path));
145 $thumb->resize($width, null, function ($constraint) {
146 $constraint->aspectRatio();
147 $constraint->upsize();
150 $thumb->fit($width, $height);
153 $thumbData = (string)$thumb->encode();
154 $storage->put($thumbFilePath, $thumbData);
155 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
157 return $this->getPublicUrl($thumbFilePath);
161 * Destroys an Image object along with its files and thumbnails.
162 * @param Image $image
165 public function destroyImage(Image $image)
167 $storage = $this->getStorage();
169 $imageFolder = dirname($image->path);
170 $imageFileName = basename($image->path);
171 $allImages = collect($storage->allFiles($imageFolder));
173 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
174 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
175 return strpos($imagePath, $imageFileName) === $expectedIndex;
178 $storage->delete($imagesToDelete->all());
180 // Cleanup of empty folders
181 foreach ($storage->directories($imageFolder) as $directory) {
182 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
184 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
191 * Save a gravatar image and set a the profile image for a user.
196 public function saveUserGravatar(User $user, $size = 500)
198 $emailHash = md5(strtolower(trim($user->email)));
199 $url = 'http://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
200 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
201 $image = $this->saveNewFromUrl($url, 'user', $imageName);
202 $image->created_by = $user->id;
203 $image->updated_by = $user->id;
209 * Get the storage that will be used for storing images.
210 * @return FileSystemInstance
212 private function getStorage()
214 if ($this->storageInstance !== null) return $this->storageInstance;
216 $storageType = config('filesystems.default');
217 $this->storageInstance = $this->fileSystem->disk($storageType);
219 return $this->storageInstance;
223 * Check whether or not a folder is empty.
227 private function isFolderEmpty($path)
229 $files = $this->getStorage()->files($path);
230 $folders = $this->getStorage()->directories($path);
231 return count($files) === 0 && count($folders) === 0;
235 * Gets a public facing url for an image by checking relevant environment variables.
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 if ($storageUrl == false && config('filesystems.default') === 's3') {
246 $storageDetails = config('filesystems.disks.s3');
247 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
250 $this->storageUrl = $storageUrl;
253 return ($this->storageUrl == false ? '' : rtrim($this->storageUrl, '/')) . $filePath;