]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/EntityRepo.php
Rolled tri-layout to page edit and book-create
[bookstack] / app / Entities / Repos / EntityRepo.php
1 <?php namespace BookStack\Entities\Repos;
2
3 use BookStack\Actions\TagRepo;
4 use BookStack\Actions\ViewService;
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Book;
8 use BookStack\Entities\Bookshelf;
9 use BookStack\Entities\Chapter;
10 use BookStack\Entities\Entity;
11 use BookStack\Entities\EntityProvider;
12 use BookStack\Entities\Page;
13 use BookStack\Entities\SearchService;
14 use BookStack\Exceptions\NotFoundException;
15 use BookStack\Exceptions\NotifyException;
16 use BookStack\Uploads\AttachmentService;
17 use DOMDocument;
18 use Illuminate\Database\Eloquent\Builder;
19 use Illuminate\Http\Request;
20 use Illuminate\Support\Collection;
21
22 class EntityRepo
23 {
24
25     /**
26      * @var EntityProvider
27      */
28     protected $entityProvider;
29
30     /**
31      * @var PermissionService
32      */
33     protected $permissionService;
34
35     /**
36      * @var ViewService
37      */
38     protected $viewService;
39
40     /**
41      * @var TagRepo
42      */
43     protected $tagRepo;
44
45     /**
46      * @var SearchService
47      */
48     protected $searchService;
49
50     /**
51      * EntityRepo constructor.
52      * @param EntityProvider $entityProvider
53      * @param ViewService $viewService
54      * @param PermissionService $permissionService
55      * @param TagRepo $tagRepo
56      * @param SearchService $searchService
57      */
58     public function __construct(
59         EntityProvider $entityProvider,
60         ViewService $viewService,
61         PermissionService $permissionService,
62         TagRepo $tagRepo,
63         SearchService $searchService
64     ) {
65         $this->entityProvider = $entityProvider;
66         $this->viewService = $viewService;
67         $this->permissionService = $permissionService;
68         $this->tagRepo = $tagRepo;
69         $this->searchService = $searchService;
70     }
71
72     /**
73      * Base query for searching entities via permission system
74      * @param string $type
75      * @param bool $allowDrafts
76      * @param string $permission
77      * @return \Illuminate\Database\Query\Builder
78      */
79     protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
80     {
81         $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
82         if (strtolower($type) === 'page' && !$allowDrafts) {
83             $q = $q->where('draft', '=', false);
84         }
85         return $q;
86     }
87
88     /**
89      * Check if an entity with the given id exists.
90      * @param $type
91      * @param $id
92      * @return bool
93      */
94     public function exists($type, $id)
95     {
96         return $this->entityQuery($type)->where('id', '=', $id)->exists();
97     }
98
99     /**
100      * Get an entity by ID
101      * @param string $type
102      * @param integer $id
103      * @param bool $allowDrafts
104      * @param bool $ignorePermissions
105      * @return \BookStack\Entities\Entity
106      */
107     public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
108     {
109         $query = $this->entityQuery($type, $allowDrafts);
110
111         if ($ignorePermissions) {
112             $query = $this->entityProvider->get($type)->newQuery();
113         }
114
115         return $query->find($id);
116     }
117
118     /**
119      * @param string $type
120      * @param []int $ids
121      * @param bool $allowDrafts
122      * @param bool $ignorePermissions
123      * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
124      */
125     public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
126     {
127         $query = $this->entityQuery($type, $allowDrafts);
128
129         if ($ignorePermissions) {
130             $query = $this->entityProvider->get($type)->newQuery();
131         }
132
133         return $query->whereIn('id', $ids)->get();
134     }
135
136     /**
137      * Get an entity by its url slug.
138      * @param string $type
139      * @param string $slug
140      * @param string|bool $bookSlug
141      * @return \BookStack\Entities\Entity
142      * @throws NotFoundException
143      */
144     public function getBySlug($type, $slug, $bookSlug = false)
145     {
146         $q = $this->entityQuery($type)->where('slug', '=', $slug);
147
148         if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
149             $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
150                 $query->select('id')
151                     ->from($this->entityProvider->book->getTable())
152                     ->where('slug', '=', $bookSlug)->limit(1);
153             });
154         }
155         $entity = $q->first();
156         if ($entity === null) {
157             throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
158         }
159         return $entity;
160     }
161
162
163     /**
164      * Get all entities of a type with the given permission, limited by count unless count is false.
165      * @param string $type
166      * @param integer|bool $count
167      * @param string $permission
168      * @return Collection
169      */
170     public function getAll($type, $count = 20, $permission = 'view')
171     {
172         $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
173         if ($count !== false) {
174             $q = $q->take($count);
175         }
176         return $q->get();
177     }
178
179     /**
180      * Get all entities in a paginated format
181      * @param $type
182      * @param int $count
183      * @param string $sort
184      * @param string $order
185      * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
186      */
187     public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc')
188     {
189         $query = $this->entityQuery($type);
190         $query = $this->addSortToQuery($query, $sort, $order);
191         return $query->paginate($count);
192     }
193
194     protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
195     {
196         $order = ($order === 'asc') ? 'asc' : 'desc';
197         $propertySorts = ['name', 'created_at', 'updated_at'];
198
199         if (in_array($sort, $propertySorts)) {
200             return $query->orderBy($sort, $order);
201         }
202
203         return $query;
204     }
205
206     /**
207      * Get the most recently created entities of the given type.
208      * @param string $type
209      * @param int $count
210      * @param int $page
211      * @param bool|callable $additionalQuery
212      * @return Collection
213      */
214     public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
215     {
216         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
217             ->orderBy('created_at', 'desc');
218         if (strtolower($type) === 'page') {
219             $query = $query->where('draft', '=', false);
220         }
221         if ($additionalQuery !== false && is_callable($additionalQuery)) {
222             $additionalQuery($query);
223         }
224         return $query->skip($page * $count)->take($count)->get();
225     }
226
227     /**
228      * Get the most recently updated entities of the given type.
229      * @param string $type
230      * @param int $count
231      * @param int $page
232      * @param bool|callable $additionalQuery
233      * @return Collection
234      */
235     public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
236     {
237         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
238             ->orderBy('updated_at', 'desc');
239         if (strtolower($type) === 'page') {
240             $query = $query->where('draft', '=', false);
241         }
242         if ($additionalQuery !== false && is_callable($additionalQuery)) {
243             $additionalQuery($query);
244         }
245         return $query->skip($page * $count)->take($count)->get();
246     }
247
248     /**
249      * Get the most recently viewed entities.
250      * @param string|bool $type
251      * @param int $count
252      * @param int $page
253      * @return mixed
254      */
255     public function getRecentlyViewed($type, $count = 10, $page = 0)
256     {
257         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
258         return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
259     }
260
261     /**
262      * Get the latest pages added to the system with pagination.
263      * @param string $type
264      * @param int $count
265      * @return mixed
266      */
267     public function getRecentlyCreatedPaginated($type, $count = 20)
268     {
269         return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
270     }
271
272     /**
273      * Get the latest pages added to the system with pagination.
274      * @param string $type
275      * @param int $count
276      * @return mixed
277      */
278     public function getRecentlyUpdatedPaginated($type, $count = 20)
279     {
280         return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
281     }
282
283     /**
284      * Get the most popular entities base on all views.
285      * @param string|bool $type
286      * @param int $count
287      * @param int $page
288      * @return mixed
289      */
290     public function getPopular($type, $count = 10, $page = 0)
291     {
292         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
293         return $this->viewService->getPopular($count, $page, $filter);
294     }
295
296     /**
297      * Get draft pages owned by the current user.
298      * @param int $count
299      * @param int $page
300      * @return Collection
301      */
302     public function getUserDraftPages($count = 20, $page = 0)
303     {
304         return $this->entityProvider->page->where('draft', '=', true)
305             ->where('created_by', '=', user()->id)
306             ->orderBy('updated_at', 'desc')
307             ->skip($count * $page)->take($count)->get();
308     }
309
310     /**
311      * Get the number of entities the given user has created.
312      * @param string $type
313      * @param User $user
314      * @return int
315      */
316     public function getUserTotalCreated(string $type, User $user)
317     {
318         return $this->entityProvider->get($type)
319             ->where('created_by', '=', $user->id)->count();
320     }
321
322     /**
323      * Get the child items for a chapter sorted by priority but
324      * with draft items floated to the top.
325      * @param \BookStack\Entities\Bookshelf $bookshelf
326      * @return \Illuminate\Database\Eloquent\Collection|static[]
327      */
328     public function getBookshelfChildren(Bookshelf $bookshelf)
329     {
330         return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
331     }
332
333     /**
334      * Get all child objects of a book.
335      * Returns a sorted collection of Pages and Chapters.
336      * Loads the book slug onto child elements to prevent access database access for getting the slug.
337      * @param \BookStack\Entities\Book $book
338      * @param bool $filterDrafts
339      * @param bool $renderPages
340      * @return mixed
341      */
342     public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
343     {
344         $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
345         $entities = [];
346         $parents = [];
347         $tree = [];
348
349         foreach ($q as $index => $rawEntity) {
350             if ($rawEntity->entity_type ===  $this->entityProvider->page->getMorphClass()) {
351                 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
352                 if ($renderPages) {
353                     $entities[$index]->html = $rawEntity->html;
354                     $entities[$index]->html = $this->renderPage($entities[$index]);
355                 };
356             } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
357                 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
358                 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
359                 $parents[$key] = $entities[$index];
360                 $parents[$key]->setAttribute('pages', collect());
361             }
362             if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
363                 $tree[] = $entities[$index];
364             }
365             $entities[$index]->book = $book;
366         }
367
368         foreach ($entities as $entity) {
369             if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
370                 continue;
371             }
372             $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
373             if (!isset($parents[$parentKey])) {
374                 $tree[] = $entity;
375                 continue;
376             }
377             $chapter = $parents[$parentKey];
378             $chapter->pages->push($entity);
379         }
380
381         return collect($tree);
382     }
383
384     /**
385      * Get the child items for a chapter sorted by priority but
386      * with draft items floated to the top.
387      * @param \BookStack\Entities\Chapter $chapter
388      * @return \Illuminate\Database\Eloquent\Collection|static[]
389      */
390     public function getChapterChildren(Chapter $chapter)
391     {
392         return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
393             ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
394     }
395
396
397     /**
398      * Get the next sequential priority for a new child element in the given book.
399      * @param \BookStack\Entities\Book $book
400      * @return int
401      */
402     public function getNewBookPriority(Book $book)
403     {
404         $lastElem = $this->getBookChildren($book)->pop();
405         return $lastElem ? $lastElem->priority + 1 : 0;
406     }
407
408     /**
409      * Get a new priority for a new page to be added to the given chapter.
410      * @param \BookStack\Entities\Chapter $chapter
411      * @return int
412      */
413     public function getNewChapterPriority(Chapter $chapter)
414     {
415         $lastPage = $chapter->pages('DESC')->first();
416         return $lastPage !== null ? $lastPage->priority + 1 : 0;
417     }
418
419     /**
420      * Find a suitable slug for an entity.
421      * @param string $type
422      * @param string $name
423      * @param bool|integer $currentId
424      * @param bool|integer $bookId Only pass if type is not a book
425      * @return string
426      */
427     public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
428     {
429         $slug = $this->nameToSlug($name);
430         while ($this->slugExists($type, $slug, $currentId, $bookId)) {
431             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
432         }
433         return $slug;
434     }
435
436     /**
437      * Check if a slug already exists in the database.
438      * @param string $type
439      * @param string $slug
440      * @param bool|integer $currentId
441      * @param bool|integer $bookId
442      * @return bool
443      */
444     protected function slugExists($type, $slug, $currentId = false, $bookId = false)
445     {
446         $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
447         if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
448             $query = $query->where('book_id', '=', $bookId);
449         }
450         if ($currentId) {
451             $query = $query->where('id', '!=', $currentId);
452         }
453         return $query->count() > 0;
454     }
455
456     /**
457      * Updates entity restrictions from a request
458      * @param Request $request
459      * @param \BookStack\Entities\Entity $entity
460      * @throws \Throwable
461      */
462     public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
463     {
464         $entity->restricted = $request->get('restricted', '') === 'true';
465         $entity->permissions()->delete();
466
467         if ($request->filled('restrictions')) {
468             foreach ($request->get('restrictions') as $roleId => $restrictions) {
469                 foreach ($restrictions as $action => $value) {
470                     $entity->permissions()->create([
471                         'role_id' => $roleId,
472                         'action'  => strtolower($action)
473                     ]);
474                 }
475             }
476         }
477
478         $entity->save();
479         $this->permissionService->buildJointPermissionsForEntity($entity);
480     }
481
482
483
484     /**
485      * Create a new entity from request input.
486      * Used for books and chapters.
487      * @param string $type
488      * @param array $input
489      * @param bool|Book $book
490      * @return \BookStack\Entities\Entity
491      */
492     public function createFromInput($type, $input = [], $book = false)
493     {
494         $isChapter = strtolower($type) === 'chapter';
495         $entityModel = $this->entityProvider->get($type)->newInstance($input);
496         $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
497         $entityModel->created_by = user()->id;
498         $entityModel->updated_by = user()->id;
499         $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
500
501         if (isset($input['tags'])) {
502             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
503         }
504
505         $this->permissionService->buildJointPermissionsForEntity($entityModel);
506         $this->searchService->indexEntity($entityModel);
507         return $entityModel;
508     }
509
510     /**
511      * Update entity details from request input.
512      * Used for books and chapters
513      * @param string $type
514      * @param \BookStack\Entities\Entity $entityModel
515      * @param array $input
516      * @return \BookStack\Entities\Entity
517      */
518     public function updateFromInput($type, Entity $entityModel, $input = [])
519     {
520         if ($entityModel->name !== $input['name']) {
521             $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
522         }
523         $entityModel->fill($input);
524         $entityModel->updated_by = user()->id;
525         $entityModel->save();
526
527         if (isset($input['tags'])) {
528             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
529         }
530
531         $this->permissionService->buildJointPermissionsForEntity($entityModel);
532         $this->searchService->indexEntity($entityModel);
533         return $entityModel;
534     }
535
536     /**
537      * Sync the books assigned to a shelf from a comma-separated list
538      * of book IDs.
539      * @param \BookStack\Entities\Bookshelf $shelf
540      * @param string $books
541      */
542     public function updateShelfBooks(Bookshelf $shelf, string $books)
543     {
544         $ids = explode(',', $books);
545
546         // Check books exist and match ordering
547         $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
548         $syncData = [];
549         foreach ($ids as $index => $id) {
550             if ($bookIds->contains($id)) {
551                 $syncData[$id] = ['order' => $index];
552             }
553         }
554
555         $shelf->books()->sync($syncData);
556     }
557
558     /**
559      * Change the book that an entity belongs to.
560      * @param string $type
561      * @param integer $newBookId
562      * @param Entity $entity
563      * @param bool $rebuildPermissions
564      * @return \BookStack\Entities\Entity
565      */
566     public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
567     {
568         $entity->book_id = $newBookId;
569         // Update related activity
570         foreach ($entity->activity as $activity) {
571             $activity->book_id = $newBookId;
572             $activity->save();
573         }
574         $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
575         $entity->save();
576
577         // Update all child pages if a chapter
578         if (strtolower($type) === 'chapter') {
579             foreach ($entity->pages as $page) {
580                 $this->changeBook('page', $newBookId, $page, false);
581             }
582         }
583
584         // Update permissions if applicable
585         if ($rebuildPermissions) {
586             $entity->load('book');
587             $this->permissionService->buildJointPermissionsForEntity($entity->book);
588         }
589
590         return $entity;
591     }
592
593     /**
594      * Alias method to update the book jointPermissions in the PermissionService.
595      * @param Book $book
596      */
597     public function buildJointPermissionsForBook(Book $book)
598     {
599         $this->permissionService->buildJointPermissionsForEntity($book);
600     }
601
602     /**
603      * Format a name as a url slug.
604      * @param $name
605      * @return string
606      */
607     protected function nameToSlug($name)
608     {
609         $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
610         $slug = preg_replace('/\s{2,}/', ' ', $slug);
611         $slug = str_replace(' ', '-', $slug);
612         if ($slug === "") {
613             $slug = substr(md5(rand(1, 500)), 0, 5);
614         }
615         return $slug;
616     }
617
618     /**
619      * Render the page for viewing, Parsing and performing features such as page transclusion.
620      * @param Page $page
621      * @param bool $ignorePermissions
622      * @return mixed|string
623      */
624     public function renderPage(Page $page, $ignorePermissions = false)
625     {
626         $content = $page->html;
627         if (!config('app.allow_content_scripts')) {
628             $content = $this->escapeScripts($content);
629         }
630
631         $matches = [];
632         preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
633         if (count($matches[0]) === 0) {
634             return $content;
635         }
636
637         $topLevelTags = ['table', 'ul', 'ol'];
638         foreach ($matches[1] as $index => $includeId) {
639             $splitInclude = explode('#', $includeId, 2);
640             $pageId = intval($splitInclude[0]);
641             if (is_nan($pageId)) {
642                 continue;
643             }
644
645             $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
646             if ($matchedPage === null) {
647                 $content = str_replace($matches[0][$index], '', $content);
648                 continue;
649             }
650
651             if (count($splitInclude) === 1) {
652                 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
653                 continue;
654             }
655
656             $doc = new DOMDocument();
657             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
658             $matchingElem = $doc->getElementById($splitInclude[1]);
659             if ($matchingElem === null) {
660                 $content = str_replace($matches[0][$index], '', $content);
661                 continue;
662             }
663             $innerContent = '';
664             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
665             if ($isTopLevel) {
666                 $innerContent .= $doc->saveHTML($matchingElem);
667             } else {
668                 foreach ($matchingElem->childNodes as $childNode) {
669                     $innerContent .= $doc->saveHTML($childNode);
670                 }
671             }
672             $content = str_replace($matches[0][$index], trim($innerContent), $content);
673         }
674
675         return $content;
676     }
677
678     /**
679      * Escape script tags within HTML content.
680      * @param string $html
681      * @return mixed
682      */
683     protected function escapeScripts(string $html)
684     {
685         $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
686         $matches = [];
687         preg_match_all($scriptSearchRegex, $html, $matches);
688         if (count($matches) === 0) {
689             return $html;
690         }
691
692         foreach ($matches[0] as $match) {
693             $html = str_replace($match, htmlentities($match), $html);
694         }
695         return $html;
696     }
697
698     /**
699      * Search for image usage within page content.
700      * @param $imageString
701      * @return mixed
702      */
703     public function searchForImage($imageString)
704     {
705         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
706         foreach ($pages as $page) {
707             $page->url = $page->getUrl();
708             $page->html = '';
709             $page->text = '';
710         }
711         return count($pages) > 0 ? $pages : false;
712     }
713
714     /**
715      * Destroy a bookshelf instance
716      * @param \BookStack\Entities\Bookshelf $shelf
717      * @throws \Throwable
718      */
719     public function destroyBookshelf(Bookshelf $shelf)
720     {
721         $this->destroyEntityCommonRelations($shelf);
722         $shelf->delete();
723     }
724
725     /**
726      * Destroy the provided book and all its child entities.
727      * @param \BookStack\Entities\Book $book
728      * @throws NotifyException
729      * @throws \Throwable
730      */
731     public function destroyBook(Book $book)
732     {
733         foreach ($book->pages as $page) {
734             $this->destroyPage($page);
735         }
736         foreach ($book->chapters as $chapter) {
737             $this->destroyChapter($chapter);
738         }
739         $this->destroyEntityCommonRelations($book);
740         $book->delete();
741     }
742
743     /**
744      * Destroy a chapter and its relations.
745      * @param \BookStack\Entities\Chapter $chapter
746      * @throws \Throwable
747      */
748     public function destroyChapter(Chapter $chapter)
749     {
750         if (count($chapter->pages) > 0) {
751             foreach ($chapter->pages as $page) {
752                 $page->chapter_id = 0;
753                 $page->save();
754             }
755         }
756         $this->destroyEntityCommonRelations($chapter);
757         $chapter->delete();
758     }
759
760     /**
761      * Destroy a given page along with its dependencies.
762      * @param Page $page
763      * @throws NotifyException
764      * @throws \Throwable
765      */
766     public function destroyPage(Page $page)
767     {
768         // Check if set as custom homepage
769         $customHome = setting('app-homepage', '0:');
770         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
771             throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
772         }
773
774         $this->destroyEntityCommonRelations($page);
775
776         // Delete Attached Files
777         $attachmentService = app(AttachmentService::class);
778         foreach ($page->attachments as $attachment) {
779             $attachmentService->deleteFile($attachment);
780         }
781
782         $page->delete();
783     }
784
785     /**
786      * Destroy or handle the common relations connected to an entity.
787      * @param \BookStack\Entities\Entity $entity
788      * @throws \Throwable
789      */
790     protected function destroyEntityCommonRelations(Entity $entity)
791     {
792         \Activity::removeEntity($entity);
793         $entity->views()->delete();
794         $entity->permissions()->delete();
795         $entity->tags()->delete();
796         $entity->comments()->delete();
797         $this->permissionService->deleteJointPermissionsForEntity($entity);
798         $this->searchService->deleteEntityTerms($entity);
799     }
800
801     /**
802      * Copy the permissions of a bookshelf to all child books.
803      * Returns the number of books that had permissions updated.
804      * @param \BookStack\Entities\Bookshelf $bookshelf
805      * @return int
806      * @throws \Throwable
807      */
808     public function copyBookshelfPermissions(Bookshelf $bookshelf)
809     {
810         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
811         $shelfBooks = $bookshelf->books()->get();
812         $updatedBookCount = 0;
813
814         foreach ($shelfBooks as $book) {
815             if (!userCan('restrictions-manage', $book)) {
816                 continue;
817             }
818             $book->permissions()->delete();
819             $book->restricted = $bookshelf->restricted;
820             $book->permissions()->createMany($shelfPermissions);
821             $book->save();
822             $this->permissionService->buildJointPermissionsForEntity($book);
823             $updatedBookCount++;
824         }
825
826         return $updatedBookCount;
827     }
828 }