1 <?php namespace BookStack\Uploads;
3 use BookStack\Exceptions\ImageUploadException;
4 use BookStack\Uploads\Image;
5 use BookStack\Auth\User;
6 use BookStack\Uploads\UploadService;
9 use Intervention\Image\Exception\NotSupportedException;
10 use Intervention\Image\ImageManager;
11 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
12 use Illuminate\Contracts\Cache\Repository as Cache;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
15 class ImageService extends UploadService
20 protected $storageUrl;
24 * ImageService constructor.
26 * @param ImageManager $imageTool
27 * @param FileSystem $fileSystem
30 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
32 $this->image = $image;
33 $this->imageTool = $imageTool;
34 $this->cache = $cache;
35 parent::__construct($fileSystem);
39 * Get the storage that will be used for storing images.
41 * @return \Illuminate\Contracts\Filesystem\Filesystem
43 protected function getStorage($type = '')
45 $storageType = config('filesystems.default');
47 // Override default location if set to local public to ensure not visible.
48 if ($type === 'system' && $storageType === 'local_secure') {
49 $storageType = 'local';
52 return $this->fileSystem->disk($storageType);
56 * Saves a new image from an upload.
57 * @param UploadedFile $uploadedFile
59 * @param int $uploadedTo
61 * @throws ImageUploadException
63 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
65 $imageName = $uploadedFile->getClientOriginalName();
66 $imageData = file_get_contents($uploadedFile->getRealPath());
67 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
71 * Save a new image from a uri-encoded base64 string of data.
72 * @param string $base64Uri
75 * @param int $uploadedTo
77 * @throws ImageUploadException
79 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
81 $splitData = explode(';base64,', $base64Uri);
82 if (count($splitData) < 2) {
83 throw new ImageUploadException("Invalid base64 image data provided");
85 $data = base64_decode($splitData[1]);
86 return $this->saveNew($name, $data, $type, $uploadedTo);
90 * Gets an image from url and saves it to the database.
93 * @param bool|string $imageName
97 private function saveNewFromUrl($url, $type, $imageName = false)
99 $imageName = $imageName ? $imageName : basename($url);
100 $imageData = file_get_contents($url);
101 if ($imageData === false) {
102 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
104 return $this->saveNew($imageName, $imageData, $type);
109 * @param string $imageName
110 * @param string $imageData
111 * @param string $type
112 * @param int $uploadedTo
114 * @throws ImageUploadException
116 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
118 $storage = $this->getStorage($type);
119 $secureUploads = setting('app-secure-images');
120 $imageName = str_replace(' ', '-', $imageName);
122 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
124 while ($storage->exists($imagePath . $imageName)) {
125 $imageName = str_random(3) . $imageName;
128 $fullPath = $imagePath . $imageName;
129 if ($secureUploads) {
130 $fullPath = $imagePath . str_random(16) . '-' . $imageName;
134 $storage->put($fullPath, $imageData);
135 $storage->setVisibility($fullPath, 'public');
136 } catch (Exception $e) {
137 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
141 'name' => $imageName,
143 'url' => $this->getPublicUrl($fullPath),
145 'uploaded_to' => $uploadedTo
148 if (user()->id !== 0) {
149 $userId = user()->id;
150 $imageDetails['created_by'] = $userId;
151 $imageDetails['updated_by'] = $userId;
154 $image = $this->image->newInstance();
155 $image->forceFill($imageDetails)->save();
161 * Checks if the image is a gif. Returns true if it is, else false.
162 * @param Image $image
165 protected function isGif(Image $image)
167 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
171 * Get the thumbnail for an image.
172 * If $keepRatio is true only the width will be used.
173 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
174 * @param Image $image
177 * @param bool $keepRatio
180 * @throws ImageUploadException
182 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
184 if ($keepRatio && $this->isGif($image)) {
185 return $this->getPublicUrl($image->path);
188 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
189 $imagePath = $image->path;
190 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
192 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
193 return $this->getPublicUrl($thumbFilePath);
196 $storage = $this->getStorage($image->type);
197 if ($storage->exists($thumbFilePath)) {
198 return $this->getPublicUrl($thumbFilePath);
202 $thumb = $this->imageTool->make($storage->get($imagePath));
203 } catch (Exception $e) {
204 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
205 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
211 $thumb->resize($width, null, function ($constraint) {
212 $constraint->aspectRatio();
213 $constraint->upsize();
216 $thumb->fit($width, $height);
219 $thumbData = (string)$thumb->encode();
220 $storage->put($thumbFilePath, $thumbData);
221 $storage->setVisibility($thumbFilePath, 'public');
222 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
224 return $this->getPublicUrl($thumbFilePath);
228 * Get the raw data content from an image.
229 * @param Image $image
231 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
233 public function getImageData(Image $image)
235 $imagePath = $image->path;
236 $storage = $this->getStorage();
237 return $storage->get($imagePath);
241 * Destroy an image along with its revisions, thumbnails and remaining folders.
242 * @param Image $image
245 public function destroy(Image $image)
247 $this->destroyImagesFromPath($image->path);
252 * Destroys an image at the given path.
253 * Searches for image thumbnails in addition to main provided path..
254 * @param string $path
257 protected function destroyImagesFromPath(string $path)
259 $storage = $this->getStorage();
261 $imageFolder = dirname($path);
262 $imageFileName = basename($path);
263 $allImages = collect($storage->allFiles($imageFolder));
265 // Delete image files
266 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
267 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
268 return strpos($imagePath, $imageFileName) === $expectedIndex;
270 $storage->delete($imagesToDelete->all());
272 // Cleanup of empty folders
273 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
274 foreach ($foldersInvolved as $directory) {
275 if ($this->isFolderEmpty($directory)) {
276 $storage->deleteDirectory($directory);
284 * Save a gravatar image and set a the profile image for a user.
285 * @param \BookStack\Auth\User $user
290 public function saveUserGravatar(User $user, $size = 500)
292 $emailHash = md5(strtolower(trim($user->email)));
293 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
294 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
295 $image = $this->saveNewFromUrl($url, 'user', $imageName);
296 $image->created_by = $user->id;
297 $image->updated_by = $user->id;
304 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
305 * Checks based off of only the image name.
306 * Could be much improved to be more specific but kept it generic for now to be safe.
308 * Returns the path of the images that would be/have been deleted.
309 * @param bool $checkRevisions
310 * @param bool $dryRun
311 * @param array $types
314 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
316 $types = array_intersect($types, ['gallery', 'drawio']);
319 $this->image->newQuery()->whereIn('type', $types)
320 ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
321 foreach ($images as $image) {
322 $searchQuery = '%' . basename($image->path) . '%';
323 $inPage = DB::table('pages')
324 ->where('html', 'like', $searchQuery)->count() > 0;
326 if ($checkRevisions) {
327 $inRevision = DB::table('page_revisions')
328 ->where('html', 'like', $searchQuery)->count() > 0;
331 if (!$inPage && !$inRevision) {
332 $deletedPaths[] = $image->path;
334 $this->destroy($image);
339 return $deletedPaths;
343 * Convert a image URI to a Base64 encoded string.
344 * Attempts to find locally via set storage method first.
346 * @return null|string
347 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
349 public function imageUriToBase64(string $uri)
351 $isLocal = strpos(trim($uri), 'http') !== 0;
353 // Attempt to find local files even if url not absolute
354 $base = baseUrl('/');
355 if (!$isLocal && strpos($uri, $base) === 0) {
357 $uri = str_replace($base, '', $uri);
363 $uri = trim($uri, '/');
364 $storage = $this->getStorage();
365 if ($storage->exists($uri)) {
366 $imageData = $storage->get($uri);
371 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
372 $imageData = curl_exec($ch);
373 $err = curl_error($ch);
376 throw new \Exception("Image fetch failed, Received error: " . $err);
378 } catch (\Exception $e) {
382 if ($imageData === null) {
386 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
390 * Gets a public facing url for an image by checking relevant environment variables.
391 * @param string $filePath
394 private function getPublicUrl($filePath)
396 if ($this->storageUrl === null) {
397 $storageUrl = config('filesystems.url');
399 // Get the standard public s3 url if s3 is set as storage type
400 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
401 // region-based url will be used to prevent http issues.
402 if ($storageUrl == false && config('filesystems.default') === 's3') {
403 $storageDetails = config('filesystems.disks.s3');
404 if (strpos($storageDetails['bucket'], '.') === false) {
405 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
407 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
410 $this->storageUrl = $storageUrl;
413 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
414 return rtrim($basePath, '/') . $filePath;