]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageRepo.php
bfe4b597739a8e26f423c4f5f04d9d78f0db805f
[bookstack] / app / Uploads / ImageRepo.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Exceptions\ImageUploadException;
8 use Exception;
9 use Illuminate\Database\Eloquent\Builder;
10 use Symfony\Component\HttpFoundation\File\UploadedFile;
11
12 class ImageRepo
13 {
14     protected $imageService;
15     protected $restrictionService;
16
17     /**
18      * ImageRepo constructor.
19      */
20     public function __construct(ImageService $imageService, PermissionService $permissionService)
21     {
22         $this->imageService = $imageService;
23         $this->restrictionService = $permissionService;
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->restrictionService->filterRelatedEntity(Page::class, $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         $this->loadThumbs($image);
127
128         return $image;
129     }
130
131     /**
132      * Save a new image from an existing image data string.
133      *
134      * @throws ImageUploadException
135      */
136     public function saveNewFromData(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
137     {
138         $image = $this->imageService->saveNew($imageName, $imageData, $type, $uploadedTo);
139         $this->loadThumbs($image);
140
141         return $image;
142     }
143
144     /**
145      * Save a drawing in the database.
146      *
147      * @throws ImageUploadException
148      */
149     public function saveDrawing(string $base64Uri, int $uploadedTo): Image
150     {
151         $name = 'Drawing-' . user()->id . '-' . time() . '.png';
152
153         return $this->imageService->saveNewFromBase64Uri($base64Uri, $name, 'drawio', $uploadedTo);
154     }
155
156     /**
157      * Update the details of an image via an array of properties.
158      *
159      * @throws Exception
160      */
161     public function updateImageDetails(Image $image, $updateDetails): Image
162     {
163         $image->fill($updateDetails);
164         $image->save();
165         $this->loadThumbs($image);
166
167         return $image;
168     }
169
170     /**
171      * Destroys an Image object along with its revisions, files and thumbnails.
172      *
173      * @throws Exception
174      */
175     public function destroyImage(Image $image = null): void
176     {
177         if ($image) {
178             $this->imageService->destroy($image);
179         }
180     }
181
182     /**
183      * Destroy all images of a certain type.
184      *
185      * @throws Exception
186      */
187     public function destroyByType(string $imageType): void
188     {
189         $images = Image::query()->where('type', '=', $imageType)->get();
190         foreach ($images as $image) {
191             $this->destroyImage($image);
192         }
193     }
194
195     /**
196      * Load thumbnails onto an image object.
197      */
198     public function loadThumbs(Image $image): void
199     {
200         $image->setAttribute('thumbs', [
201             'gallery' => $this->getThumbnail($image, 150, 150, false),
202             'display' => $this->getThumbnail($image, 1680, null, true),
203         ]);
204     }
205
206     /**
207      * Get the thumbnail for an image.
208      * If $keepRatio is true only the width will be used.
209      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
210      */
211     protected function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio): ?string
212     {
213         try {
214             return $this->imageService->getThumbnail($image, $width, $height, $keepRatio);
215         } catch (Exception $exception) {
216             return null;
217         }
218     }
219
220     /**
221      * Get the raw image data from an Image.
222      */
223     public function getImageData(Image $image): ?string
224     {
225         try {
226             return $this->imageService->getImageData($image);
227         } catch (Exception $exception) {
228             return null;
229         }
230     }
231
232     /**
233      * Get the user visible pages using the given image.
234      */
235     public function getPagesUsingImage(Image $image): array
236     {
237         $pages = Page::visible()
238             ->where('html', 'like', '%' . $image->url . '%')
239             ->get(['id', 'name', 'slug', 'book_id']);
240
241         foreach ($pages as $page) {
242             $page->setAttribute('url', $page->getUrl());
243         }
244
245         return $pages->all();
246     }
247 }