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