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