]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageRepo.php
Altered ldap_connect usage, cleaned up LDAP classes
[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->refresh();
179         $image->updated_by = user()->id;
180         $image->save();
181         $this->imageService->replaceExistingFromUpload($image->path, $image->type, $file);
182         $this->loadThumbs($image, true);
183     }
184
185     /**
186      * Destroys an Image object along with its revisions, files and thumbnails.
187      *
188      * @throws Exception
189      */
190     public function destroyImage(Image $image = null): void
191     {
192         if ($image) {
193             $this->imageService->destroy($image);
194         }
195     }
196
197     /**
198      * Destroy images that have a specific URL and type combination.
199      *
200      * @throws Exception
201      */
202     public function destroyByUrlAndType(string $url, string $imageType): void
203     {
204         $images = Image::query()
205             ->where('url', '=', $url)
206             ->where('type', '=', $imageType)
207             ->get();
208
209         foreach ($images as $image) {
210             $this->destroyImage($image);
211         }
212     }
213
214     /**
215      * Load thumbnails onto an image object.
216      */
217     public function loadThumbs(Image $image, bool $forceCreate = false): void
218     {
219         $image->setAttribute('thumbs', [
220             'gallery' => $this->getThumbnail($image, 150, 150, false, $forceCreate),
221             'display' => $this->getThumbnail($image, 1680, null, true, $forceCreate),
222         ]);
223     }
224
225     /**
226      * Get the thumbnail for an image.
227      * If $keepRatio is true only the width will be used.
228      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
229      */
230     protected function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio, bool $forceCreate): ?string
231     {
232         try {
233             return $this->imageService->getThumbnail($image, $width, $height, $keepRatio, $forceCreate);
234         } catch (Exception $exception) {
235             return null;
236         }
237     }
238
239     /**
240      * Get the raw image data from an Image.
241      */
242     public function getImageData(Image $image): ?string
243     {
244         try {
245             return $this->imageService->getImageData($image);
246         } catch (Exception $exception) {
247             return null;
248         }
249     }
250
251     /**
252      * Get the user visible pages using the given image.
253      */
254     public function getPagesUsingImage(Image $image): array
255     {
256         $pages = Page::visible()
257             ->where('html', 'like', '%' . $image->url . '%')
258             ->get(['id', 'name', 'slug', 'book_id']);
259
260         foreach ($pages as $page) {
261             $page->setAttribute('url', $page->getUrl());
262         }
263
264         return $pages->all();
265     }
266 }