3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\EntityContainerData;
10 use BookStack\Entities\Models\HasCoverInterface;
11 use BookStack\Entities\Models\Deletion;
12 use BookStack\Entities\Models\Entity;
13 use BookStack\Entities\Models\Page;
14 use BookStack\Entities\Queries\EntityQueries;
15 use BookStack\Exceptions\NotifyException;
16 use BookStack\Facades\Activity;
17 use BookStack\Uploads\AttachmentService;
18 use BookStack\Uploads\Image;
19 use BookStack\Uploads\ImageService;
20 use BookStack\Util\DatabaseTransaction;
22 use Illuminate\Database\Eloquent\Builder;
23 use Illuminate\Support\Carbon;
27 public function __construct(
28 protected EntityQueries $queries,
33 * Send a shelf to the recycle bin.
35 * @throws NotifyException
37 public function softDestroyShelf(Bookshelf $shelf)
39 $this->ensureDeletable($shelf);
40 Deletion::createForEntity($shelf);
45 * Send a book to the recycle bin.
49 public function softDestroyBook(Book $book)
51 $this->ensureDeletable($book);
52 Deletion::createForEntity($book);
54 foreach ($book->pages as $page) {
55 $this->softDestroyPage($page, false);
58 foreach ($book->chapters as $chapter) {
59 $this->softDestroyChapter($chapter, false);
66 * Send a chapter to the recycle bin.
70 public function softDestroyChapter(Chapter $chapter, bool $recordDelete = true)
73 $this->ensureDeletable($chapter);
74 Deletion::createForEntity($chapter);
77 if (count($chapter->pages) > 0) {
78 foreach ($chapter->pages as $page) {
79 $this->softDestroyPage($page, false);
87 * Send a page to the recycle bin.
91 public function softDestroyPage(Page $page, bool $recordDelete = true)
94 $this->ensureDeletable($page);
95 Deletion::createForEntity($page);
102 * Ensure the given entity is deletable.
103 * Is not for permissions, but logical conditions within the application.
104 * Will throw if not deletable.
106 * @throws NotifyException
108 protected function ensureDeletable(Entity $entity): void
110 $customHomeId = intval(explode(':', setting('app-homepage', '0:'))[0]);
111 $customHomeActive = setting('app-homepage-type') === 'page';
112 $removeCustomHome = false;
114 // Check custom homepage usage for pages
115 if ($entity instanceof Page && $entity->id === $customHomeId) {
116 if ($customHomeActive) {
117 throw new NotifyException(trans('errors.page_custom_home_deletion'), $entity->getUrl());
119 $removeCustomHome = true;
122 // Check custom homepage usage within chapters or books
123 if ($entity instanceof Chapter || $entity instanceof Book) {
124 if ($entity->pages()->where('id', '=', $customHomeId)->exists()) {
125 if ($customHomeActive) {
126 throw new NotifyException(trans('errors.page_custom_home_deletion'), $entity->getUrl());
128 $removeCustomHome = true;
132 if ($removeCustomHome) {
133 setting()->remove('app-homepage');
138 * Remove a bookshelf from the system.
142 protected function destroyShelf(Bookshelf $shelf): int
144 $this->destroyCommonRelations($shelf);
145 $shelf->books()->detach();
146 $shelf->forceDelete();
152 * Remove a book from the system.
153 * Destroys any child chapters and pages.
157 protected function destroyBook(Book $book): int
160 $pages = $book->pages()->withTrashed()->get();
161 foreach ($pages as $page) {
162 $this->destroyPage($page);
166 $chapters = $book->chapters()->withTrashed()->get();
167 foreach ($chapters as $chapter) {
168 $this->destroyChapter($chapter);
172 $this->destroyCommonRelations($book);
173 $book->shelves()->detach();
174 $book->forceDelete();
180 * Remove a chapter from the system.
181 * Destroys all pages within.
185 protected function destroyChapter(Chapter $chapter): int
188 $pages = $chapter->pages()->withTrashed()->get();
189 foreach ($pages as $page) {
190 $this->destroyPage($page);
194 $this->destroyCommonRelations($chapter);
195 $chapter->forceDelete();
201 * Remove a page from the system.
205 protected function destroyPage(Page $page): int
207 $this->destroyCommonRelations($page);
208 $page->allRevisions()->delete();
210 // Delete Attached Files
211 $attachmentService = app()->make(AttachmentService::class);
212 foreach ($page->attachments as $attachment) {
213 $attachmentService->deleteFile($attachment);
216 // Remove use as a template
217 EntityContainerData::query()
218 ->where('default_template_id', '=', $page->id)
219 ->update(['default_template_id' => null]);
221 // Nullify uploaded image relations
223 ->whereIn('type', ['gallery', 'drawio'])
224 ->where('uploaded_to', '=', $page->id)
225 ->update(['uploaded_to' => null]);
227 $page->forceDelete();
233 * Get the total counts of those that have been trashed
234 * but not yet fully deleted (In recycle bin).
236 public function getTrashedCounts(): array
240 foreach ((new EntityProvider())->all() as $key => $instance) {
241 /** @var Builder<Entity> $query */
242 $query = $instance->newQuery();
243 $counts[$key] = $query->onlyTrashed()->count();
250 * Destroy all items that have pending deletions.
254 public function empty(): int
256 $deletions = Deletion::all();
258 foreach ($deletions as $deletion) {
259 $deleteCount += $this->destroyFromDeletion($deletion);
266 * Destroy an element from the given deletion model.
270 public function destroyFromDeletion(Deletion $deletion): int
272 // We directly load the deletable element here just to ensure it still
273 // exists in the event it has already been destroyed during this request.
274 $entity = $deletion->deletable()->first();
276 if ($entity instanceof Entity) {
277 $count = $this->destroyEntity($entity);
285 * Restore the content within the given deletion.
289 public function restoreFromDeletion(Deletion $deletion): int
291 $shouldRestore = true;
294 if ($deletion->deletable instanceof Entity) {
295 $parent = $deletion->deletable->getParent();
296 if ($parent && $parent->trashed()) {
297 $shouldRestore = false;
301 if ($deletion->deletable instanceof Entity && $shouldRestore) {
302 $restoreCount = $this->restoreEntity($deletion->deletable);
307 return $restoreCount;
311 * Automatically clear old content from the recycle bin
312 * depending on the configured lifetime.
313 * Returns the total number of deleted elements.
317 public function autoClearOld(): int
319 $lifetime = intval(config('app.recycle_bin_lifetime'));
324 $clearBeforeDate = Carbon::now()->addSeconds(10)->subDays($lifetime);
327 $deletionsToRemove = Deletion::query()->where('created_at', '<', $clearBeforeDate)->get();
328 foreach ($deletionsToRemove as $deletion) {
329 $deleteCount += $this->destroyFromDeletion($deletion);
336 * Restore an entity so it is essentially un-deleted.
337 * Deletions on restored child elements will be removed during this restoration.
339 protected function restoreEntity(Entity $entity): int
344 $restoreAction = function ($entity) use (&$count) {
345 if ($entity->deletions_count > 0) {
346 $entity->deletions()->delete();
353 if ($entity instanceof Chapter || $entity instanceof Book) {
354 $entity->pages()->withTrashed()->withCount('deletions')->get()->each($restoreAction);
357 if ($entity instanceof Book) {
358 $entity->chapters()->withTrashed()->withCount('deletions')->get()->each($restoreAction);
365 * Destroy the given entity.
366 * Returns the number of total entities destroyed in the operation.
370 public function destroyEntity(Entity $entity): int
372 $result = (new DatabaseTransaction(function () use ($entity) {
373 if ($entity instanceof Page) {
374 return $this->destroyPage($entity);
375 } else if ($entity instanceof Chapter) {
376 return $this->destroyChapter($entity);
377 } else if ($entity instanceof Book) {
378 return $this->destroyBook($entity);
379 } else if ($entity instanceof Bookshelf) {
380 return $this->destroyShelf($entity);
389 * Update entity relations to remove or update outstanding connections.
391 protected function destroyCommonRelations(Entity $entity)
393 Activity::removeEntity($entity);
394 $entity->views()->delete();
395 $entity->permissions()->delete();
396 $entity->tags()->delete();
397 $entity->comments()->delete();
398 $entity->jointPermissions()->delete();
399 $entity->searchTerms()->delete();
400 $entity->deletions()->delete();
401 $entity->favourites()->delete();
402 $entity->watches()->delete();
403 $entity->referencesTo()->delete();
404 $entity->referencesFrom()->delete();
406 if ($entity instanceof HasCoverInterface && $entity->coverInfo()->exists()) {
407 $imageService = app()->make(ImageService::class);
408 $imageService->destroy($entity->coverInfo()->getImage());
411 $entity->relatedData()->delete();