]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/EntityRepo.php
Merge branch 'master' into 2019-design
[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
620      * @param Page $page
621      * @param bool $blankIncludes
622      * @return string
623      */
624     public function renderPage(Page $page, bool $blankIncludes = false) : string
625     {
626         $content = $page->html;
627
628         if (!config('app.allow_content_scripts')) {
629             $content = $this->escapeScripts($content);
630         }
631
632         if ($blankIncludes) {
633             $content = $this->blankPageIncludes($content);
634         } else {
635             $content = $this->parsePageIncludes($content);
636         }
637
638         return $content;
639     }
640
641     /**
642      * Remove any page include tags within the given HTML.
643      * @param string $html
644      * @return string
645      */
646     protected function blankPageIncludes(string $html) : string
647     {
648         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
649     }
650
651     /**
652      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
653      * @param string $html
654      * @return mixed|string
655      */
656     protected function parsePageIncludes(string $html) : string
657     {
658         $matches = [];
659         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
660
661         $topLevelTags = ['table', 'ul', 'ol'];
662         foreach ($matches[1] as $index => $includeId) {
663             $splitInclude = explode('#', $includeId, 2);
664             $pageId = intval($splitInclude[0]);
665             if (is_nan($pageId)) {
666                 continue;
667             }
668
669             $matchedPage = $this->getById('page', $pageId);
670             if ($matchedPage === null) {
671                 $html = str_replace($matches[0][$index], '', $html);
672                 continue;
673             }
674
675             if (count($splitInclude) === 1) {
676                 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
677                 continue;
678             }
679
680             $doc = new DOMDocument();
681             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
682             $matchingElem = $doc->getElementById($splitInclude[1]);
683             if ($matchingElem === null) {
684                 $html = str_replace($matches[0][$index], '', $html);
685                 continue;
686             }
687             $innerContent = '';
688             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
689             if ($isTopLevel) {
690                 $innerContent .= $doc->saveHTML($matchingElem);
691             } else {
692                 foreach ($matchingElem->childNodes as $childNode) {
693                     $innerContent .= $doc->saveHTML($childNode);
694                 }
695             }
696             $html = str_replace($matches[0][$index], trim($innerContent), $html);
697         }
698
699         return $html;
700     }
701
702     /**
703      * Escape script tags within HTML content.
704      * @param string $html
705      * @return string
706      */
707     protected function escapeScripts(string $html) : string
708     {
709         $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
710         $matches = [];
711         preg_match_all($scriptSearchRegex, $html, $matches);
712
713         foreach ($matches[0] as $match) {
714             $html = str_replace($match, htmlentities($match), $html);
715         }
716         return $html;
717     }
718
719     /**
720      * Search for image usage within page content.
721      * @param $imageString
722      * @return mixed
723      */
724     public function searchForImage($imageString)
725     {
726         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
727         foreach ($pages as $page) {
728             $page->url = $page->getUrl();
729             $page->html = '';
730             $page->text = '';
731         }
732         return count($pages) > 0 ? $pages : false;
733     }
734
735     /**
736      * Destroy a bookshelf instance
737      * @param \BookStack\Entities\Bookshelf $shelf
738      * @throws \Throwable
739      */
740     public function destroyBookshelf(Bookshelf $shelf)
741     {
742         $this->destroyEntityCommonRelations($shelf);
743         $shelf->delete();
744     }
745
746     /**
747      * Destroy the provided book and all its child entities.
748      * @param \BookStack\Entities\Book $book
749      * @throws NotifyException
750      * @throws \Throwable
751      */
752     public function destroyBook(Book $book)
753     {
754         foreach ($book->pages as $page) {
755             $this->destroyPage($page);
756         }
757         foreach ($book->chapters as $chapter) {
758             $this->destroyChapter($chapter);
759         }
760         $this->destroyEntityCommonRelations($book);
761         $book->delete();
762     }
763
764     /**
765      * Destroy a chapter and its relations.
766      * @param \BookStack\Entities\Chapter $chapter
767      * @throws \Throwable
768      */
769     public function destroyChapter(Chapter $chapter)
770     {
771         if (count($chapter->pages) > 0) {
772             foreach ($chapter->pages as $page) {
773                 $page->chapter_id = 0;
774                 $page->save();
775             }
776         }
777         $this->destroyEntityCommonRelations($chapter);
778         $chapter->delete();
779     }
780
781     /**
782      * Destroy a given page along with its dependencies.
783      * @param Page $page
784      * @throws NotifyException
785      * @throws \Throwable
786      */
787     public function destroyPage(Page $page)
788     {
789         // Check if set as custom homepage
790         $customHome = setting('app-homepage', '0:');
791         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
792             throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
793         }
794
795         $this->destroyEntityCommonRelations($page);
796
797         // Delete Attached Files
798         $attachmentService = app(AttachmentService::class);
799         foreach ($page->attachments as $attachment) {
800             $attachmentService->deleteFile($attachment);
801         }
802
803         $page->delete();
804     }
805
806     /**
807      * Destroy or handle the common relations connected to an entity.
808      * @param \BookStack\Entities\Entity $entity
809      * @throws \Throwable
810      */
811     protected function destroyEntityCommonRelations(Entity $entity)
812     {
813         \Activity::removeEntity($entity);
814         $entity->views()->delete();
815         $entity->permissions()->delete();
816         $entity->tags()->delete();
817         $entity->comments()->delete();
818         $this->permissionService->deleteJointPermissionsForEntity($entity);
819         $this->searchService->deleteEntityTerms($entity);
820     }
821
822     /**
823      * Copy the permissions of a bookshelf to all child books.
824      * Returns the number of books that had permissions updated.
825      * @param \BookStack\Entities\Bookshelf $bookshelf
826      * @return int
827      * @throws \Throwable
828      */
829     public function copyBookshelfPermissions(Bookshelf $bookshelf)
830     {
831         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
832         $shelfBooks = $bookshelf->books()->get();
833         $updatedBookCount = 0;
834
835         foreach ($shelfBooks as $book) {
836             if (!userCan('restrictions-manage', $book)) {
837                 continue;
838             }
839             $book->permissions()->delete();
840             $book->restricted = $bookshelf->restricted;
841             $book->permissions()->createMany($shelfPermissions);
842             $book->save();
843             $this->permissionService->buildJointPermissionsForEntity($book);
844             $updatedBookCount++;
845         }
846
847         return $updatedBookCount;
848     }
849 }