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\Cache\Repository as Cache;
11 use Symfony\Component\HttpFoundation\File\UploadedFile;
13 class ImageService extends UploadService
18 protected $storageUrl;
21 * ImageService constructor.
26 public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
28 $this->imageTool = $imageTool;
29 $this->cache = $cache;
30 parent::__construct($fileSystem);
34 * Get the storage that will be used for storing images.
36 * @return \Illuminate\Contracts\Filesystem\Filesystem
38 protected function getStorage($type = '')
40 $storageType = config('filesystems.default');
42 // Override default location if set to local public to ensure not visible.
43 if ($type === 'system' && $storageType === 'local_secure') {
44 $storageType = 'local';
47 return $this->fileSystem->disk($storageType);
51 * Saves a new image from an upload.
52 * @param UploadedFile $uploadedFile
54 * @param int $uploadedTo
56 * @throws ImageUploadException
58 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
60 $imageName = $uploadedFile->getClientOriginalName();
61 $imageData = file_get_contents($uploadedFile->getRealPath());
62 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
66 * Save a new image from a uri-encoded base64 string of data.
67 * @param string $base64Uri
70 * @param int $uploadedTo
72 * @throws ImageUploadException
74 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
76 $splitData = explode(';base64,', $base64Uri);
77 if (count($splitData) < 2) {
78 throw new ImageUploadException("Invalid base64 image data provided");
80 $data = base64_decode($splitData[1]);
81 return $this->saveNew($name, $data, $type, $uploadedTo);
85 * Gets an image from url and saves it to the database.
88 * @param bool|string $imageName
92 private function saveNewFromUrl($url, $type, $imageName = false)
94 $imageName = $imageName ? $imageName : basename($url);
95 $imageData = file_get_contents($url);
96 if ($imageData === false) {
97 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
99 return $this->saveNew($imageName, $imageData, $type);
104 * @param string $imageName
105 * @param string $imageData
106 * @param string $type
107 * @param int $uploadedTo
109 * @throws ImageUploadException
111 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
113 $storage = $this->getStorage($type);
114 $secureUploads = setting('app-secure-images');
115 $imageName = str_replace(' ', '-', $imageName);
117 if ($secureUploads) {
118 $imageName = str_random(16) . '-' . $imageName;
121 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
123 while ($storage->exists($imagePath . $imageName)) {
124 $imageName = str_random(3) . $imageName;
126 $fullPath = $imagePath . $imageName;
129 $storage->put($fullPath, $imageData);
130 $storage->setVisibility($fullPath, 'public');
131 } catch (Exception $e) {
132 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
136 'name' => $imageName,
138 'url' => $this->getPublicUrl($fullPath),
140 'uploaded_to' => $uploadedTo
143 if (user()->id !== 0) {
144 $userId = user()->id;
145 $imageDetails['created_by'] = $userId;
146 $imageDetails['updated_by'] = $userId;
149 $image = (new Image());
150 $image->forceFill($imageDetails)->save();
156 * Checks if the image is a gif. Returns true if it is, else false.
157 * @param Image $image
160 protected function isGif(Image $image)
162 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
166 * Get the thumbnail for an image.
167 * If $keepRatio is true only the width will be used.
168 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
169 * @param Image $image
172 * @param bool $keepRatio
175 * @throws ImageUploadException
177 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
179 if ($keepRatio && $this->isGif($image)) {
180 return $this->getPublicUrl($image->path);
183 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
184 $imagePath = $image->path;
185 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
187 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
188 return $this->getPublicUrl($thumbFilePath);
191 $storage = $this->getStorage($image->type);
192 if ($storage->exists($thumbFilePath)) {
193 return $this->getPublicUrl($thumbFilePath);
197 $thumb = $this->imageTool->make($storage->get($imagePath));
198 } catch (Exception $e) {
199 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
200 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
206 $thumb->resize($width, null, function ($constraint) {
207 $constraint->aspectRatio();
208 $constraint->upsize();
211 $thumb->fit($width, $height);
214 $thumbData = (string)$thumb->encode();
215 $storage->put($thumbFilePath, $thumbData);
216 $storage->setVisibility($thumbFilePath, 'public');
217 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
219 return $this->getPublicUrl($thumbFilePath);
223 * Get the raw data content from an image.
224 * @param Image $image
226 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
228 public function getImageData(Image $image)
230 $imagePath = $image->path;
231 $storage = $this->getStorage();
232 return $storage->get($imagePath);
236 * Destroy an image along with its revisions, thumbnails and remaining folders.
237 * @param Image $image
240 public function destroy(Image $image)
242 $this->destroyImagesFromPath($image->path);
247 * Destroys an image at the given path.
248 * Searches for image thumbnails in addition to main provided path..
249 * @param string $path
252 protected function destroyImagesFromPath(string $path)
254 $storage = $this->getStorage();
256 $imageFolder = dirname($path);
257 $imageFileName = basename($path);
258 $allImages = collect($storage->allFiles($imageFolder));
260 // Delete image files
261 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
262 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
263 return strpos($imagePath, $imageFileName) === $expectedIndex;
265 $storage->delete($imagesToDelete->all());
267 // Cleanup of empty folders
268 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
269 foreach ($foldersInvolved as $directory) {
270 if ($this->isFolderEmpty($directory)) {
271 $storage->deleteDirectory($directory);
279 * Save a gravatar image and set a the profile image for a user.
285 public function saveUserGravatar(User $user, $size = 500)
287 $emailHash = md5(strtolower(trim($user->email)));
288 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
289 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
290 $image = $this->saveNewFromUrl($url, 'user', $imageName);
291 $image->created_by = $user->id;
292 $image->updated_by = $user->id;
298 * Convert a image URI to a Base64 encoded string.
299 * Attempts to find locally via set storage method first.
301 * @return null|string
302 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
304 public function imageUriToBase64(string $uri)
306 $isLocal = strpos(trim($uri), 'http') !== 0;
308 // Attempt to find local files even if url not absolute
309 $base = baseUrl('/');
310 if (!$isLocal && strpos($uri, $base) === 0) {
312 $uri = str_replace($base, '', $uri);
318 $uri = trim($uri, '/');
319 $storage = $this->getStorage();
320 if ($storage->exists($uri)) {
321 $imageData = $storage->get($uri);
326 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
327 $imageData = curl_exec($ch);
328 $err = curl_error($ch);
331 throw new \Exception("Image fetch failed, Received error: " . $err);
333 } catch (\Exception $e) {
337 if ($imageData === null) {
341 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
345 * Gets a public facing url for an image by checking relevant environment variables.
346 * @param string $filePath
349 private function getPublicUrl($filePath)
351 if ($this->storageUrl === null) {
352 $storageUrl = config('filesystems.url');
354 // Get the standard public s3 url if s3 is set as storage type
355 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
356 // region-based url will be used to prevent http issues.
357 if ($storageUrl == false && config('filesystems.default') === 's3') {
358 $storageDetails = config('filesystems.disks.s3');
359 if (strpos($storageDetails['bucket'], '.') === false) {
360 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
362 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
365 $this->storageUrl = $storageUrl;
368 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
369 return rtrim($basePath, '/') . $filePath;