1 <?php namespace BookStack\Services;
5 use Intervention\Image\ImageManager;
6 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
7 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
8 use Illuminate\Contracts\Cache\Repository as Cache;
10 use Symfony\Component\HttpFoundation\File\UploadedFile;
16 protected $fileSystem;
20 * @var FileSystemInstance
22 protected $storageInstance;
23 protected $storageUrl;
26 * ImageService constructor.
31 public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
33 $this->imageTool = $imageTool;
34 $this->fileSystem = $fileSystem;
35 $this->cache = $cache;
39 * Saves a new image from an upload.
40 * @param UploadedFile $uploadedFile
44 public function saveNewFromUpload(UploadedFile $uploadedFile, $type)
46 $imageName = $uploadedFile->getClientOriginalName();
47 $imageData = file_get_contents($uploadedFile->getRealPath());
48 return $this->saveNew($imageName, $imageData, $type);
53 * Gets an image from url and saves it to the database.
56 * @param bool|string $imageName
60 private function saveNewFromUrl($url, $type, $imageName = false)
62 $imageName = $imageName ? $imageName : basename($url);
63 $imageData = file_get_contents($url);
64 if($imageData === false) throw new \Exception('Cannot get image from ' . $url);
65 return $this->saveNew($imageName, $imageData, $type);
70 * @param string $imageName
71 * @param string $imageData
75 private function saveNew($imageName, $imageData, $type)
77 $storage = $this->getStorage();
78 $secureUploads = Setting::get('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') . '/';
84 while ($storage->exists($imagePath . $imageName)) {
85 $imageName = str_random(3) . $imageName;
87 $fullPath = $imagePath . $imageName;
89 $storage->put($fullPath, $imageData);
91 $userId = auth()->user()->id;
92 $image = Image::forceCreate([
95 'url' => $this->getPublicUrl($fullPath),
97 'created_by' => $userId,
98 'updated_by' => $userId
105 * Get the thumbnail for an image.
106 * If $keepRatio is true only the width will be used.
107 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
109 * @param Image $image
112 * @param bool $keepRatio
115 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
117 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
118 $thumbFilePath = dirname($image->path) . $thumbDirName . basename($image->path);
120 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
121 return $this->getPublicUrl($thumbFilePath);
124 $storage = $this->getStorage();
126 if ($storage->exists($thumbFilePath)) {
127 return $this->getPublicUrl($thumbFilePath);
130 // Otherwise create the thumbnail
131 $thumb = $this->imageTool->make($storage->get($image->path));
133 $thumb->resize($width, null, function ($constraint) {
134 $constraint->aspectRatio();
135 $constraint->upsize();
138 $thumb->fit($width, $height);
141 $thumbData = (string)$thumb->encode();
142 $storage->put($thumbFilePath, $thumbData);
143 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
145 return $this->getPublicUrl($thumbFilePath);
149 * Destroys an Image object along with its files and thumbnails.
150 * @param Image $image
153 public function destroyImage(Image $image)
155 $storage = $this->getStorage();
157 $imageFolder = dirname($image->path);
158 $imageFileName = basename($image->path);
159 $allImages = collect($storage->allFiles($imageFolder));
161 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
162 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
163 return strpos($imagePath, $imageFileName) === $expectedIndex;
166 $storage->delete($imagesToDelete->all());
168 // Cleanup of empty folders
169 foreach ($storage->directories($imageFolder) as $directory) {
170 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
172 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
179 * Save a gravatar image and set a the profile image for a user.
184 public function saveUserGravatar(User $user, $size = 500)
186 if (!env('USE_GRAVATAR', false)) return false;
187 $emailHash = md5(strtolower(trim($user->email)));
188 $url = 'http://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
189 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
190 $image = $this->saveNewFromUrl($url, 'user', $imageName);
191 $image->created_by = $user->id;
193 $user->avatar()->associate($image);
199 * Get the storage that will be used for storing images.
200 * @return FileSystemInstance
202 private function getStorage()
204 if ($this->storageInstance !== null) return $this->storageInstance;
206 $storageType = env('STORAGE_TYPE');
207 $this->storageInstance = $this->fileSystem->disk($storageType);
209 return $this->storageInstance;
213 * Check whether or not a folder is empty.
217 private function isFolderEmpty($path)
219 $files = $this->getStorage()->files($path);
220 $folders = $this->getStorage()->directories($path);
221 return count($files) === 0 && count($folders) === 0;
225 * Gets a public facing url for an image by checking relevant environment variables.
229 private function getPublicUrl($filePath)
231 if ($this->storageUrl === null) {
232 $storageUrl = env('STORAGE_URL');
234 // Get the standard public s3 url if s3 is set as storage type
235 if ($storageUrl == false && env('STORAGE_TYPE') === 's3') {
236 $storageDetails = config('filesystems.disks.s3');
237 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
240 $this->storageUrl = $storageUrl;
243 return ($this->storageUrl == false ? '' : rtrim($this->storageUrl, '/')) . $filePath;