1 <?php namespace BookStack\Services;
3 use BookStack\Exceptions\ImageUploadException;
8 use Intervention\Image\Exception\NotSupportedException;
9 use Intervention\Image\ImageManager;
10 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
11 use Illuminate\Contracts\Cache\Repository as Cache;
12 use Symfony\Component\HttpFoundation\File\UploadedFile;
14 class ImageService extends UploadService
19 protected $storageUrl;
23 * ImageService constructor.
25 * @param ImageManager $imageTool
26 * @param FileSystem $fileSystem
29 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
31 $this->image = $image;
32 $this->imageTool = $imageTool;
33 $this->cache = $cache;
34 parent::__construct($fileSystem);
38 * Get the storage that will be used for storing images.
40 * @return \Illuminate\Contracts\Filesystem\Filesystem
42 protected function getStorage($type = '')
44 $storageType = config('filesystems.default');
46 // Override default location if set to local public to ensure not visible.
47 if ($type === 'system' && $storageType === 'local_secure') {
48 $storageType = 'local';
51 return $this->fileSystem->disk($storageType);
55 * Saves a new image from an upload.
56 * @param UploadedFile $uploadedFile
58 * @param int $uploadedTo
60 * @throws ImageUploadException
62 public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
64 $imageName = $uploadedFile->getClientOriginalName();
65 $imageData = file_get_contents($uploadedFile->getRealPath());
66 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
70 * Save a new image from a uri-encoded base64 string of data.
71 * @param string $base64Uri
74 * @param int $uploadedTo
76 * @throws ImageUploadException
78 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
80 $splitData = explode(';base64,', $base64Uri);
81 if (count($splitData) < 2) {
82 throw new ImageUploadException("Invalid base64 image data provided");
84 $data = base64_decode($splitData[1]);
85 return $this->saveNew($name, $data, $type, $uploadedTo);
89 * Gets an image from url and saves it to the database.
92 * @param bool|string $imageName
96 private function saveNewFromUrl($url, $type, $imageName = false)
98 $imageName = $imageName ? $imageName : basename($url);
99 $imageData = file_get_contents($url);
100 if ($imageData === false) {
101 throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
103 return $this->saveNew($imageName, $imageData, $type);
108 * @param string $imageName
109 * @param string $imageData
110 * @param string $type
111 * @param int $uploadedTo
113 * @throws ImageUploadException
115 private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
117 $storage = $this->getStorage($type);
118 $secureUploads = setting('app-secure-images');
119 $imageName = str_replace(' ', '-', $imageName);
121 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
123 while ($storage->exists($imagePath . $imageName)) {
124 $imageName = str_random(3) . $imageName;
127 $fullPath = $imagePath . $imageName;
128 if ($secureUploads) {
129 $fullPath = $imagePath . str_random(16) . '-' . $imageName;
133 $storage->put($fullPath, $imageData);
134 $storage->setVisibility($fullPath, 'public');
135 } catch (Exception $e) {
136 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
140 'name' => $imageName,
142 'url' => $this->getPublicUrl($fullPath),
144 'uploaded_to' => $uploadedTo
147 if (user()->id !== 0) {
148 $userId = user()->id;
149 $imageDetails['created_by'] = $userId;
150 $imageDetails['updated_by'] = $userId;
153 $image = $this->image->newInstance();
154 $image->forceFill($imageDetails)->save();
160 * Checks if the image is a gif. Returns true if it is, else false.
161 * @param Image $image
164 protected function isGif(Image $image)
166 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
170 * Get the thumbnail for an image.
171 * If $keepRatio is true only the width will be used.
172 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
173 * @param Image $image
176 * @param bool $keepRatio
179 * @throws ImageUploadException
181 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
183 if ($keepRatio && $this->isGif($image)) {
184 return $this->getPublicUrl($image->path);
187 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
188 $imagePath = $image->path;
189 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
191 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
192 return $this->getPublicUrl($thumbFilePath);
195 $storage = $this->getStorage($image->type);
196 if ($storage->exists($thumbFilePath)) {
197 return $this->getPublicUrl($thumbFilePath);
201 $thumb = $this->imageTool->make($storage->get($imagePath));
202 } catch (Exception $e) {
203 if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
204 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
210 $thumb->resize($width, null, function ($constraint) {
211 $constraint->aspectRatio();
212 $constraint->upsize();
215 $thumb->fit($width, $height);
218 $thumbData = (string)$thumb->encode();
219 $storage->put($thumbFilePath, $thumbData);
220 $storage->setVisibility($thumbFilePath, 'public');
221 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
223 return $this->getPublicUrl($thumbFilePath);
227 * Get the raw data content from an image.
228 * @param Image $image
230 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
232 public function getImageData(Image $image)
234 $imagePath = $image->path;
235 $storage = $this->getStorage();
236 return $storage->get($imagePath);
240 * Destroy an image along with its revisions, thumbnails and remaining folders.
241 * @param Image $image
244 public function destroy(Image $image)
246 $this->destroyImagesFromPath($image->path);
251 * Destroys an image at the given path.
252 * Searches for image thumbnails in addition to main provided path..
253 * @param string $path
256 protected function destroyImagesFromPath(string $path)
258 $storage = $this->getStorage();
260 $imageFolder = dirname($path);
261 $imageFileName = basename($path);
262 $allImages = collect($storage->allFiles($imageFolder));
264 // Delete image files
265 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
266 $expectedIndex = strlen($imagePath) - strlen($imageFileName);
267 return strpos($imagePath, $imageFileName) === $expectedIndex;
269 $storage->delete($imagesToDelete->all());
271 // Cleanup of empty folders
272 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
273 foreach ($foldersInvolved as $directory) {
274 if ($this->isFolderEmpty($directory)) {
275 $storage->deleteDirectory($directory);
283 * Save a gravatar image and set a the profile image for a user.
289 public function saveUserGravatar(User $user, $size = 500)
291 $emailHash = md5(strtolower(trim($user->email)));
292 $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
293 $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
294 $image = $this->saveNewFromUrl($url, 'user', $imageName);
295 $image->created_by = $user->id;
296 $image->updated_by = $user->id;
303 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
304 * Checks based off of only the image name.
305 * Could be much improved to be more specific but kept it generic for now to be safe.
307 * Returns the path of the images that would be/have been deleted.
308 * @param bool $checkRevisions
309 * @param bool $dryRun
310 * @param array $types
313 public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
315 $types = array_intersect($types, ['gallery', 'drawio']);
318 $this->image->newQuery()->whereIn('type', $types)
319 ->chunk(1000, function($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
320 foreach ($images as $image) {
321 $searchQuery = '%' . basename($image->path) . '%';
322 $inPage = DB::table('pages')
323 ->where('html', 'like', $searchQuery)->count() > 0;
325 if ($checkRevisions) {
326 $inRevision = DB::table('page_revisions')
327 ->where('html', 'like', $searchQuery)->count() > 0;
330 if (!$inPage && !$inRevision) {
331 $deletedPaths[] = $image->path;
333 $this->destroy($image);
338 return $deletedPaths;
342 * Convert a image URI to a Base64 encoded string.
343 * Attempts to find locally via set storage method first.
345 * @return null|string
346 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
348 public function imageUriToBase64(string $uri)
350 $isLocal = strpos(trim($uri), 'http') !== 0;
352 // Attempt to find local files even if url not absolute
353 $base = baseUrl('/');
354 if (!$isLocal && strpos($uri, $base) === 0) {
356 $uri = str_replace($base, '', $uri);
362 $uri = trim($uri, '/');
363 $storage = $this->getStorage();
364 if ($storage->exists($uri)) {
365 $imageData = $storage->get($uri);
370 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
371 $imageData = curl_exec($ch);
372 $err = curl_error($ch);
375 throw new \Exception("Image fetch failed, Received error: " . $err);
377 } catch (\Exception $e) {
381 if ($imageData === null) {
385 return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
389 * Gets a public facing url for an image by checking relevant environment variables.
390 * @param string $filePath
393 private function getPublicUrl($filePath)
395 if ($this->storageUrl === null) {
396 $storageUrl = config('filesystems.url');
398 // Get the standard public s3 url if s3 is set as storage type
399 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
400 // region-based url will be used to prevent http issues.
401 if ($storageUrl == false && config('filesystems.default') === 's3') {
402 $storageDetails = config('filesystems.disks.s3');
403 if (strpos($storageDetails['bucket'], '.') === false) {
404 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
406 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
409 $this->storageUrl = $storageUrl;
412 $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
413 return rtrim($basePath, '/') . $filePath;