]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageRepo.php
Updated translator & dependency attribution before release v25.05.1
[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                 } else if ($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(
113         UploadedFile $uploadFile,
114         string $type,
115         int $uploadedTo = 0,
116         ?int $resizeWidth = null,
117         ?int $resizeHeight = null,
118         bool $keepRatio = true
119     ): Image {
120         $image = $this->imageService->saveNewFromUpload($uploadFile, $type, $uploadedTo, $resizeWidth, $resizeHeight, $keepRatio);
121
122         if ($type !== 'system') {
123             $this->imageResizer->loadGalleryThumbnailsForImage($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->imageResizer->loadGalleryThumbnailsForImage($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->imageResizer->loadGalleryThumbnailsForImage($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 (strtolower($file->getClientOriginalExtension()) !== strtolower(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->imageResizer->loadGalleryThumbnailsForImage($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      * Get the raw image data from an Image.
219      */
220     public function getImageData(Image $image): ?string
221     {
222         try {
223             return $this->imageService->getImageData($image);
224         } catch (Exception $exception) {
225             return null;
226         }
227     }
228
229     /**
230      * Get the user visible pages using the given image.
231      */
232     public function getPagesUsingImage(Image $image): array
233     {
234         $pages = $this->pageQueries->visibleForList()
235             ->where('html', 'like', '%' . $image->url . '%')
236             ->get();
237
238         foreach ($pages as $page) {
239             $page->setAttribute('url', $page->getUrl());
240         }
241
242         return $pages->all();
243     }
244 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.