]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageRepo.php
Added the ability to replace existing image files
[bookstack] / app / Uploads / ImageRepo.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Entities\Models\Page;
6 use BookStack\Exceptions\ImageUploadException;
7 use BookStack\Permissions\PermissionApplicator;
8 use Exception;
9 use Illuminate\Database\Eloquent\Builder;
10 use Symfony\Component\HttpFoundation\File\UploadedFile;
11
12 class ImageRepo
13 {
14     public function __construct(
15         protected ImageService $imageService,
16         protected PermissionApplicator $permissions
17     ) {
18     }
19
20     /**
21      * Get an image with the given id.
22      */
23     public function getById($id): Image
24     {
25         return Image::query()->findOrFail($id);
26     }
27
28     /**
29      * Execute a paginated query, returning in a standard format.
30      * Also runs the query through the restriction system.
31      */
32     private function returnPaginated($query, $page = 1, $pageSize = 24): array
33     {
34         $images = $query->orderBy('created_at', 'desc')->skip($pageSize * ($page - 1))->take($pageSize + 1)->get();
35         $hasMore = count($images) > $pageSize;
36
37         $returnImages = $images->take($pageSize);
38         $returnImages->each(function (Image $image) {
39             $this->loadThumbs($image);
40         });
41
42         return [
43             'images'   => $returnImages,
44             'has_more' => $hasMore,
45         ];
46     }
47
48     /**
49      * Fetch a list of images in a paginated format, filtered by image type.
50      * Can be filtered by uploaded to and also by name.
51      */
52     public function getPaginatedByType(
53         string $type,
54         int $page = 0,
55         int $pageSize = 24,
56         int $uploadedTo = null,
57         string $search = null,
58         callable $whereClause = null
59     ): array {
60         $imageQuery = Image::query()->where('type', '=', strtolower($type));
61
62         if ($uploadedTo !== null) {
63             $imageQuery = $imageQuery->where('uploaded_to', '=', $uploadedTo);
64         }
65
66         if ($search !== null) {
67             $imageQuery = $imageQuery->where('name', 'LIKE', '%' . $search . '%');
68         }
69
70         // Filter by page access
71         $imageQuery = $this->permissions->restrictPageRelationQuery($imageQuery, 'images', 'uploaded_to');
72
73         if ($whereClause !== null) {
74             $imageQuery = $imageQuery->where($whereClause);
75         }
76
77         return $this->returnPaginated($imageQuery, $page, $pageSize);
78     }
79
80     /**
81      * Get paginated gallery images within a specific page or book.
82      */
83     public function getEntityFiltered(
84         string $type,
85         string $filterType = null,
86         int $page = 0,
87         int $pageSize = 24,
88         int $uploadedTo = null,
89         string $search = null
90     ): array {
91         /** @var Page $contextPage */
92         $contextPage = Page::visible()->findOrFail($uploadedTo);
93         $parentFilter = null;
94
95         if ($filterType === 'book' || $filterType === 'page') {
96             $parentFilter = function (Builder $query) use ($filterType, $contextPage) {
97                 if ($filterType === 'page') {
98                     $query->where('uploaded_to', '=', $contextPage->id);
99                 } elseif ($filterType === 'book') {
100                     $validPageIds = $contextPage->book->pages()
101                         ->scopes('visible')
102                         ->pluck('id')
103                         ->toArray();
104                     $query->whereIn('uploaded_to', $validPageIds);
105                 }
106             };
107         }
108
109         return $this->getPaginatedByType($type, $page, $pageSize, null, $search, $parentFilter);
110     }
111
112     /**
113      * Save a new image into storage and return the new image.
114      *
115      * @throws ImageUploadException
116      */
117     public function saveNew(UploadedFile $uploadFile, string $type, int $uploadedTo = 0, int $resizeWidth = null, int $resizeHeight = null, bool $keepRatio = true): Image
118     {
119         $image = $this->imageService->saveNewFromUpload($uploadFile, $type, $uploadedTo, $resizeWidth, $resizeHeight, $keepRatio);
120
121         if ($type !== 'system') {
122             $this->loadThumbs($image);
123         }
124
125         return $image;
126     }
127
128     /**
129      * Save a new image from an existing image data string.
130      *
131      * @throws ImageUploadException
132      */
133     public function saveNewFromData(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
134     {
135         $image = $this->imageService->saveNew($imageName, $imageData, $type, $uploadedTo);
136         $this->loadThumbs($image);
137
138         return $image;
139     }
140
141     /**
142      * Save a drawing in the database.
143      *
144      * @throws ImageUploadException
145      */
146     public function saveDrawing(string $base64Uri, int $uploadedTo): Image
147     {
148         $name = 'Drawing-' . user()->id . '-' . time() . '.png';
149
150         return $this->imageService->saveNewFromBase64Uri($base64Uri, $name, 'drawio', $uploadedTo);
151     }
152
153     /**
154      * Update the details of an image via an array of properties.
155      *
156      * @throws Exception
157      */
158     public function updateImageDetails(Image $image, $updateDetails): Image
159     {
160         $image->fill($updateDetails);
161         $image->updated_by = user()->id;
162         $image->save();
163         $this->loadThumbs($image);
164
165         return $image;
166     }
167
168     /**
169      * Update the image file of an existing image in the system.
170      * @throws ImageUploadException
171      */
172     public function updateImageFile(Image $image, UploadedFile $file): void
173     {
174         if ($file->getClientOriginalExtension() !== pathinfo($image->path, PATHINFO_EXTENSION)) {
175             throw new ImageUploadException(trans('errors.image_upload_replace_type'));
176         }
177
178         $image->updated_by = user()->id;
179         $image->save();
180         $this->imageService->replaceExistingFromUpload($image->path, $image->type, $file);
181         $this->loadThumbs($image, true);
182     }
183
184     /**
185      * Destroys an Image object along with its revisions, files and thumbnails.
186      *
187      * @throws Exception
188      */
189     public function destroyImage(Image $image = null): void
190     {
191         if ($image) {
192             $this->imageService->destroy($image);
193         }
194     }
195
196     /**
197      * Destroy images that have a specific URL and type combination.
198      *
199      * @throws Exception
200      */
201     public function destroyByUrlAndType(string $url, string $imageType): void
202     {
203         $images = Image::query()
204             ->where('url', '=', $url)
205             ->where('type', '=', $imageType)
206             ->get();
207
208         foreach ($images as $image) {
209             $this->destroyImage($image);
210         }
211     }
212
213     /**
214      * Load thumbnails onto an image object.
215      */
216     public function loadThumbs(Image $image, bool $forceCreate = false): void
217     {
218         $image->setAttribute('thumbs', [
219             'gallery' => $this->getThumbnail($image, 150, 150, false, $forceCreate),
220             'display' => $this->getThumbnail($image, 1680, null, true, $forceCreate),
221         ]);
222     }
223
224     /**
225      * Get the thumbnail for an image.
226      * If $keepRatio is true only the width will be used.
227      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
228      */
229     protected function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio, bool $forceCreate): ?string
230     {
231         try {
232             return $this->imageService->getThumbnail($image, $width, $height, $keepRatio, $forceCreate);
233         } catch (Exception $exception) {
234             return null;
235         }
236     }
237
238     /**
239      * Get the raw image data from an Image.
240      */
241     public function getImageData(Image $image): ?string
242     {
243         try {
244             return $this->imageService->getImageData($image);
245         } catch (Exception $exception) {
246             return null;
247         }
248     }
249
250     /**
251      * Get the user visible pages using the given image.
252      */
253     public function getPagesUsingImage(Image $image): array
254     {
255         $pages = Page::visible()
256             ->where('html', 'like', '%' . $image->url . '%')
257             ->get(['id', 'name', 'slug', 'book_id']);
258
259         foreach ($pages as $page) {
260             $page->setAttribute('url', $page->getUrl());
261         }
262
263         return $pages->all();
264     }
265 }