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;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
19 protected $fileSystem;
23 * @var FileSystemInstance
25 protected $storageInstance;
26 protected $storageUrl;
29 * ImageService constructor.
34 public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
36 $this->imageTool = $imageTool;
37 $this->fileSystem = $fileSystem;
38 $this->cache = $cache;
42 * Saves a new image from an upload.
43 * @param UploadedFile $uploadedFile
47 public function saveNewFromUpload(UploadedFile $uploadedFile, $type)
49 $imageName = $uploadedFile->getClientOriginalName();
50 $imageData = file_get_contents($uploadedFile->getRealPath());
51 return $this->saveNew($imageName, $imageData, $type);
56 * Gets an image from url and saves it to the database.
59 * @param bool|string $imageName
63 private function saveNewFromUrl($url, $type, $imageName = false)
65 $imageName = $imageName ? $imageName : basename($url);
66 $imageData = file_get_contents($url);
67 if($imageData === false) throw new \Exception('Cannot get image from ' . $url);
68 return $this->saveNew($imageName, $imageData, $type);
73 * @param string $imageName
74 * @param string $imageData
77 * @throws ImageUploadException
79 private function saveNew($imageName, $imageData, $type)
81 $storage = $this->getStorage();
82 $secureUploads = Setting::get('app-secure-images');
83 $imageName = str_replace(' ', '-', $imageName);
85 if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
87 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
88 while ($storage->exists($imagePath . $imageName)) {
89 $imageName = str_random(3) . $imageName;
91 $fullPath = $imagePath . $imageName;
94 $storage->put($fullPath, $imageData);
95 } catch (Exception $e) {
96 throw new ImageUploadException('Image Path ' . $fullPath . ' is not writable by the server.');
100 'name' => $imageName,
102 'url' => $this->getPublicUrl($fullPath),
106 if (auth()->user() && auth()->user()->id !== 0) {
107 $userId = auth()->user()->id;
108 $imageDetails['created_by'] = $userId;
109 $imageDetails['updated_by'] = $userId;
112 $image = Image::forceCreate($imageDetails);
118 * Get the thumbnail for an image.
119 * If $keepRatio is true only the width will be used.
120 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
122 * @param Image $image
125 * @param bool $keepRatio
128 * @throws ImageUploadException
130 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
132 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
133 $thumbFilePath = dirname($image->path) . $thumbDirName . basename($image->path);
135 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
136 return $this->getPublicUrl($thumbFilePath);
139 $storage = $this->getStorage();
141 if ($storage->exists($thumbFilePath)) {
142 return $this->getPublicUrl($thumbFilePath);
146 $thumb = $this->imageTool->make($storage->get($image->path));
147 } catch (Exception $e) {
148 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
149 throw new ImageUploadException('The server cannot create thumbnails. Please check you have the GD PHP extension installed.');
156 $thumb->resize($width, null, function ($constraint) {
157 $constraint->aspectRatio();
158 $constraint->upsize();
161 $thumb->fit($width, $height);
164 $thumbData = (string)$thumb->encode();
165 $storage->put($thumbFilePath, $thumbData);
166 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
168 return $this->getPublicUrl($thumbFilePath);
172 * Destroys an Image object along with its files and thumbnails.
173 * @param Image $image
176 public function destroyImage(Image $image)
178 $storage = $this->getStorage();
180 $imageFolder = dirname($image->path);
181 $imageFileName = basename($image->path);
182 $allImages = collect($storage->allFiles($imageFolder));
184 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
185 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
186 return strpos($imagePath, $imageFileName) === $expectedIndex;
189 $storage->delete($imagesToDelete->all());
191 // Cleanup of empty folders
192 foreach ($storage->directories($imageFolder) as $directory) {
193 if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
195 if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
202 * Save a gravatar image and set a the profile image for a user.
207 public function saveUserGravatar(User $user, $size = 500)
209 $emailHash = md5(strtolower(trim($user->email)));
210 $url = 'http://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
211 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
212 $image = $this->saveNewFromUrl($url, 'user', $imageName);
213 $image->created_by = $user->id;
214 $image->updated_by = $user->id;
220 * Get the storage that will be used for storing images.
221 * @return FileSystemInstance
223 private function getStorage()
225 if ($this->storageInstance !== null) return $this->storageInstance;
227 $storageType = config('filesystems.default');
228 $this->storageInstance = $this->fileSystem->disk($storageType);
230 return $this->storageInstance;
234 * Check whether or not a folder is empty.
238 private function isFolderEmpty($path)
240 $files = $this->getStorage()->files($path);
241 $folders = $this->getStorage()->directories($path);
242 return count($files) === 0 && count($folders) === 0;
246 * Gets a public facing url for an image by checking relevant environment variables.
250 private function getPublicUrl($filePath)
252 if ($this->storageUrl === null) {
253 $storageUrl = config('filesystems.url');
255 // Get the standard public s3 url if s3 is set as storage type
256 if ($storageUrl == false && config('filesystems.default') === 's3') {
257 $storageDetails = config('filesystems.disks.s3');
258 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
261 $this->storageUrl = $storageUrl;
264 return ($this->storageUrl == false ? '' : rtrim($this->storageUrl, '/')) . $filePath;