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