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