]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageRepo.php
5c6228b378df9b6bb35962eb05dcf1684c9d97bf
[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()->visible()->get(['id'])->pluck('id')->toArray();
107                     $query->whereIn('uploaded_to', $validPageIds);
108                 }
109             };
110         }
111
112         return $this->getPaginatedByType($type, $page, $pageSize, null, $search, $parentFilter);
113     }
114
115     /**
116      * Save a new image into storage and return the new image.
117      *
118      * @throws ImageUploadException
119      */
120     public function saveNew(UploadedFile $uploadFile, string $type, int $uploadedTo = 0, int $resizeWidth = null, int $resizeHeight = null, bool $keepRatio = true): Image
121     {
122         $image = $this->imageService->saveNewFromUpload($uploadFile, $type, $uploadedTo, $resizeWidth, $resizeHeight, $keepRatio);
123         $this->loadThumbs($image);
124
125         return $image;
126     }
127
128     /**
129      * Save a new image from an existing image data string.
130      *
131      * @throws ImageUploadException
132      */
133     public function saveNewFromData(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
134     {
135         $image = $this->imageService->saveNew($imageName, $imageData, $type, $uploadedTo);
136         $this->loadThumbs($image);
137
138         return $image;
139     }
140
141     /**
142      * Save a drawing in the database.
143      *
144      * @throws ImageUploadException
145      */
146     public function saveDrawing(string $base64Uri, int $uploadedTo): Image
147     {
148         $name = 'Drawing-' . user()->id . '-' . time() . '.png';
149
150         return $this->imageService->saveNewFromBase64Uri($base64Uri, $name, 'drawio', $uploadedTo);
151     }
152
153     /**
154      * Update the details of an image via an array of properties.
155      *
156      * @throws Exception
157      */
158     public function updateImageDetails(Image $image, $updateDetails): Image
159     {
160         $image->fill($updateDetails);
161         $image->save();
162         $this->loadThumbs($image);
163
164         return $image;
165     }
166
167     /**
168      * Destroys an Image object along with its revisions, files and thumbnails.
169      *
170      * @throws Exception
171      */
172     public function destroyImage(Image $image = null): void
173     {
174         if ($image) {
175             $this->imageService->destroy($image);
176         }
177     }
178
179     /**
180      * Destroy all images of a certain type.
181      *
182      * @throws Exception
183      */
184     public function destroyByType(string $imageType): void
185     {
186         $images = Image::query()->where('type', '=', $imageType)->get();
187         foreach ($images as $image) {
188             $this->destroyImage($image);
189         }
190     }
191
192     /**
193      * Load thumbnails onto an image object.
194      */
195     public function loadThumbs(Image $image): void
196     {
197         $image->setAttribute('thumbs', [
198             'gallery' => $this->getThumbnail($image, 150, 150, false),
199             'display' => $this->getThumbnail($image, 1680, null, true),
200         ]);
201     }
202
203     /**
204      * Get the thumbnail for an image.
205      * If $keepRatio is true only the width will be used.
206      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
207      */
208     protected function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio): ?string
209     {
210         try {
211             return $this->imageService->getThumbnail($image, $width, $height, $keepRatio);
212         } catch (Exception $exception) {
213             return null;
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 = Page::visible()
235             ->where('html', 'like', '%' . $image->url . '%')
236             ->get(['id', 'name', 'slug', 'book_id']);
237
238         foreach ($pages as $page) {
239             $page->url = $page->getUrl();
240         }
241
242         return $pages->all();
243     }
244 }