]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/EntityRepo.php
dd9ea8ebf3db7322c83ab456e91d7bdf96e62b37
[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      * @param null|callable $queryAddition
186      * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
187      */
188     public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc', $queryAddition = null)
189     {
190         $query = $this->entityQuery($type);
191         $query = $this->addSortToQuery($query, $sort, $order);
192         if ($queryAddition) {
193             $queryAddition($query);
194         }
195         return $query->paginate($count);
196     }
197
198     /**
199      * Add sorting operations to an entity query.
200      * @param Builder $query
201      * @param string $sort
202      * @param string $order
203      * @return Builder
204      */
205     protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
206     {
207         $order = ($order === 'asc') ? 'asc' : 'desc';
208         $propertySorts = ['name', 'created_at', 'updated_at'];
209
210         if (in_array($sort, $propertySorts)) {
211             return $query->orderBy($sort, $order);
212         }
213
214         return $query;
215     }
216
217     /**
218      * Get the most recently created entities of the given type.
219      * @param string $type
220      * @param int $count
221      * @param int $page
222      * @param bool|callable $additionalQuery
223      * @return Collection
224      */
225     public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
226     {
227         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
228             ->orderBy('created_at', 'desc');
229         if (strtolower($type) === 'page') {
230             $query = $query->where('draft', '=', false);
231         }
232         if ($additionalQuery !== false && is_callable($additionalQuery)) {
233             $additionalQuery($query);
234         }
235         return $query->skip($page * $count)->take($count)->get();
236     }
237
238     /**
239      * Get the most recently updated entities of the given type.
240      * @param string $type
241      * @param int $count
242      * @param int $page
243      * @param bool|callable $additionalQuery
244      * @return Collection
245      */
246     public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
247     {
248         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
249             ->orderBy('updated_at', 'desc');
250         if (strtolower($type) === 'page') {
251             $query = $query->where('draft', '=', false);
252         }
253         if ($additionalQuery !== false && is_callable($additionalQuery)) {
254             $additionalQuery($query);
255         }
256         return $query->skip($page * $count)->take($count)->get();
257     }
258
259     /**
260      * Get the most recently viewed entities.
261      * @param string|bool $type
262      * @param int $count
263      * @param int $page
264      * @return mixed
265      */
266     public function getRecentlyViewed($type, $count = 10, $page = 0)
267     {
268         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
269         return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
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 getRecentlyCreatedPaginated($type, $count = 20)
279     {
280         return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
281     }
282
283     /**
284      * Get the latest pages added to the system with pagination.
285      * @param string $type
286      * @param int $count
287      * @return mixed
288      */
289     public function getRecentlyUpdatedPaginated($type, $count = 20)
290     {
291         return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
292     }
293
294     /**
295      * Get the most popular entities base on all views.
296      * @param string|bool $type
297      * @param int $count
298      * @param int $page
299      * @return mixed
300      */
301     public function getPopular($type, $count = 10, $page = 0)
302     {
303         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
304         return $this->viewService->getPopular($count, $page, $filter);
305     }
306
307     /**
308      * Get draft pages owned by the current user.
309      * @param int $count
310      * @param int $page
311      * @return Collection
312      */
313     public function getUserDraftPages($count = 20, $page = 0)
314     {
315         return $this->entityProvider->page->where('draft', '=', true)
316             ->where('created_by', '=', user()->id)
317             ->orderBy('updated_at', 'desc')
318             ->skip($count * $page)->take($count)->get();
319     }
320
321     /**
322      * Get the number of entities the given user has created.
323      * @param string $type
324      * @param User $user
325      * @return int
326      */
327     public function getUserTotalCreated(string $type, User $user)
328     {
329         return $this->entityProvider->get($type)
330             ->where('created_by', '=', $user->id)->count();
331     }
332
333     /**
334      * Get the child items for a chapter sorted by priority but
335      * with draft items floated to the top.
336      * @param \BookStack\Entities\Bookshelf $bookshelf
337      * @return \Illuminate\Database\Eloquent\Collection|static[]
338      */
339     public function getBookshelfChildren(Bookshelf $bookshelf)
340     {
341         return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
342     }
343
344     /**
345      * Get the direct children of a book.
346      * @param Book $book
347      * @return \Illuminate\Database\Eloquent\Collection
348      */
349     public function getBookDirectChildren(Book $book)
350     {
351         $pages = $this->permissionService->enforceEntityRestrictions('page', $book->directPages())->get();
352         $chapters = $this->permissionService->enforceEntityRestrictions('chapters', $book->chapters())->get();
353         return collect()->concat($pages)->concat($chapters)->sortBy('priority')->sortByDesc('draft');
354     }
355
356     /**
357      * Get all child objects of a book.
358      * Returns a sorted collection of Pages and Chapters.
359      * Loads the book slug onto child elements to prevent access database access for getting the slug.
360      * @param \BookStack\Entities\Book $book
361      * @param bool $filterDrafts
362      * @param bool $renderPages
363      * @return mixed
364      */
365     public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
366     {
367         $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
368         $entities = [];
369         $parents = [];
370         $tree = [];
371
372         foreach ($q as $index => $rawEntity) {
373             if ($rawEntity->entity_type ===  $this->entityProvider->page->getMorphClass()) {
374                 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
375                 if ($renderPages) {
376                     $entities[$index]->html = $rawEntity->html;
377                     $entities[$index]->html = $this->renderPage($entities[$index]);
378                 };
379             } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
380                 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
381                 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
382                 $parents[$key] = $entities[$index];
383                 $parents[$key]->setAttribute('pages', collect());
384             }
385             if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
386                 $tree[] = $entities[$index];
387             }
388             $entities[$index]->book = $book;
389         }
390
391         foreach ($entities as $entity) {
392             if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
393                 continue;
394             }
395             $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
396             if (!isset($parents[$parentKey])) {
397                 $tree[] = $entity;
398                 continue;
399             }
400             $chapter = $parents[$parentKey];
401             $chapter->pages->push($entity);
402         }
403
404         return collect($tree);
405     }
406
407     /**
408      * Get the child items for a chapter sorted by priority but
409      * with draft items floated to the top.
410      * @param \BookStack\Entities\Chapter $chapter
411      * @return \Illuminate\Database\Eloquent\Collection|static[]
412      */
413     public function getChapterChildren(Chapter $chapter)
414     {
415         return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
416             ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
417     }
418
419
420     /**
421      * Get the next sequential priority for a new child element in the given book.
422      * @param \BookStack\Entities\Book $book
423      * @return int
424      */
425     public function getNewBookPriority(Book $book)
426     {
427         $lastElem = $this->getBookChildren($book)->pop();
428         return $lastElem ? $lastElem->priority + 1 : 0;
429     }
430
431     /**
432      * Get a new priority for a new page to be added to the given chapter.
433      * @param \BookStack\Entities\Chapter $chapter
434      * @return int
435      */
436     public function getNewChapterPriority(Chapter $chapter)
437     {
438         $lastPage = $chapter->pages('DESC')->first();
439         return $lastPage !== null ? $lastPage->priority + 1 : 0;
440     }
441
442     /**
443      * Find a suitable slug for an entity.
444      * @param string $type
445      * @param string $name
446      * @param bool|integer $currentId
447      * @param bool|integer $bookId Only pass if type is not a book
448      * @return string
449      */
450     public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
451     {
452         $slug = $this->nameToSlug($name);
453         while ($this->slugExists($type, $slug, $currentId, $bookId)) {
454             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
455         }
456         return $slug;
457     }
458
459     /**
460      * Check if a slug already exists in the database.
461      * @param string $type
462      * @param string $slug
463      * @param bool|integer $currentId
464      * @param bool|integer $bookId
465      * @return bool
466      */
467     protected function slugExists($type, $slug, $currentId = false, $bookId = false)
468     {
469         $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
470         if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
471             $query = $query->where('book_id', '=', $bookId);
472         }
473         if ($currentId) {
474             $query = $query->where('id', '!=', $currentId);
475         }
476         return $query->count() > 0;
477     }
478
479     /**
480      * Updates entity restrictions from a request
481      * @param Request $request
482      * @param \BookStack\Entities\Entity $entity
483      * @throws \Throwable
484      */
485     public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
486     {
487         $entity->restricted = $request->get('restricted', '') === 'true';
488         $entity->permissions()->delete();
489
490         if ($request->filled('restrictions')) {
491             foreach ($request->get('restrictions') as $roleId => $restrictions) {
492                 foreach ($restrictions as $action => $value) {
493                     $entity->permissions()->create([
494                         'role_id' => $roleId,
495                         'action'  => strtolower($action)
496                     ]);
497                 }
498             }
499         }
500
501         $entity->save();
502         $this->permissionService->buildJointPermissionsForEntity($entity);
503     }
504
505
506
507     /**
508      * Create a new entity from request input.
509      * Used for books and chapters.
510      * @param string $type
511      * @param array $input
512      * @param bool|Book $book
513      * @return \BookStack\Entities\Entity
514      */
515     public function createFromInput($type, $input = [], $book = false)
516     {
517         $isChapter = strtolower($type) === 'chapter';
518         $entityModel = $this->entityProvider->get($type)->newInstance($input);
519         $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
520         $entityModel->created_by = user()->id;
521         $entityModel->updated_by = user()->id;
522         $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
523
524         if (isset($input['tags'])) {
525             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
526         }
527
528         $this->permissionService->buildJointPermissionsForEntity($entityModel);
529         $this->searchService->indexEntity($entityModel);
530         return $entityModel;
531     }
532
533     /**
534      * Update entity details from request input.
535      * Used for books and chapters
536      * @param string $type
537      * @param \BookStack\Entities\Entity $entityModel
538      * @param array $input
539      * @return \BookStack\Entities\Entity
540      */
541     public function updateFromInput($type, Entity $entityModel, $input = [])
542     {
543         if ($entityModel->name !== $input['name']) {
544             $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
545         }
546         $entityModel->fill($input);
547         $entityModel->updated_by = user()->id;
548         $entityModel->save();
549
550         if (isset($input['tags'])) {
551             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
552         }
553
554         $this->permissionService->buildJointPermissionsForEntity($entityModel);
555         $this->searchService->indexEntity($entityModel);
556         return $entityModel;
557     }
558
559     /**
560      * Sync the books assigned to a shelf from a comma-separated list
561      * of book IDs.
562      * @param \BookStack\Entities\Bookshelf $shelf
563      * @param string $books
564      */
565     public function updateShelfBooks(Bookshelf $shelf, string $books)
566     {
567         $ids = explode(',', $books);
568
569         // Check books exist and match ordering
570         $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
571         $syncData = [];
572         foreach ($ids as $index => $id) {
573             if ($bookIds->contains($id)) {
574                 $syncData[$id] = ['order' => $index];
575             }
576         }
577
578         $shelf->books()->sync($syncData);
579     }
580
581     /**
582      * Change the book that an entity belongs to.
583      * @param string $type
584      * @param integer $newBookId
585      * @param Entity $entity
586      * @param bool $rebuildPermissions
587      * @return \BookStack\Entities\Entity
588      */
589     public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
590     {
591         $entity->book_id = $newBookId;
592         // Update related activity
593         foreach ($entity->activity as $activity) {
594             $activity->book_id = $newBookId;
595             $activity->save();
596         }
597         $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
598         $entity->save();
599
600         // Update all child pages if a chapter
601         if (strtolower($type) === 'chapter') {
602             foreach ($entity->pages as $page) {
603                 $this->changeBook('page', $newBookId, $page, false);
604             }
605         }
606
607         // Update permissions if applicable
608         if ($rebuildPermissions) {
609             $entity->load('book');
610             $this->permissionService->buildJointPermissionsForEntity($entity->book);
611         }
612
613         return $entity;
614     }
615
616     /**
617      * Alias method to update the book jointPermissions in the PermissionService.
618      * @param Book $book
619      */
620     public function buildJointPermissionsForBook(Book $book)
621     {
622         $this->permissionService->buildJointPermissionsForEntity($book);
623     }
624
625     /**
626      * Format a name as a url slug.
627      * @param $name
628      * @return string
629      */
630     protected function nameToSlug($name)
631     {
632         $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
633         $slug = preg_replace('/\s{2,}/', ' ', $slug);
634         $slug = str_replace(' ', '-', $slug);
635         if ($slug === "") {
636             $slug = substr(md5(rand(1, 500)), 0, 5);
637         }
638         return $slug;
639     }
640
641     /**
642      * Render the page for viewing
643      * @param Page $page
644      * @param bool $blankIncludes
645      * @return string
646      */
647     public function renderPage(Page $page, bool $blankIncludes = false) : string
648     {
649         $content = $page->html;
650
651         if (!config('app.allow_content_scripts')) {
652             $content = $this->escapeScripts($content);
653         }
654
655         if ($blankIncludes) {
656             $content = $this->blankPageIncludes($content);
657         } else {
658             $content = $this->parsePageIncludes($content);
659         }
660
661         return $content;
662     }
663
664     /**
665      * Remove any page include tags within the given HTML.
666      * @param string $html
667      * @return string
668      */
669     protected function blankPageIncludes(string $html) : string
670     {
671         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
672     }
673
674     /**
675      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
676      * @param string $html
677      * @return mixed|string
678      */
679     protected function parsePageIncludes(string $html) : string
680     {
681         $matches = [];
682         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
683
684         $topLevelTags = ['table', 'ul', 'ol'];
685         foreach ($matches[1] as $index => $includeId) {
686             $splitInclude = explode('#', $includeId, 2);
687             $pageId = intval($splitInclude[0]);
688             if (is_nan($pageId)) {
689                 continue;
690             }
691
692             $matchedPage = $this->getById('page', $pageId);
693             if ($matchedPage === null) {
694                 $html = str_replace($matches[0][$index], '', $html);
695                 continue;
696             }
697
698             if (count($splitInclude) === 1) {
699                 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
700                 continue;
701             }
702
703             $doc = new DOMDocument();
704             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
705             $matchingElem = $doc->getElementById($splitInclude[1]);
706             if ($matchingElem === null) {
707                 $html = str_replace($matches[0][$index], '', $html);
708                 continue;
709             }
710             $innerContent = '';
711             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
712             if ($isTopLevel) {
713                 $innerContent .= $doc->saveHTML($matchingElem);
714             } else {
715                 foreach ($matchingElem->childNodes as $childNode) {
716                     $innerContent .= $doc->saveHTML($childNode);
717                 }
718             }
719             $html = str_replace($matches[0][$index], trim($innerContent), $html);
720         }
721
722         return $html;
723     }
724
725     /**
726      * Escape script tags within HTML content.
727      * @param string $html
728      * @return string
729      */
730     protected function escapeScripts(string $html) : string
731     {
732         $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
733         $matches = [];
734         preg_match_all($scriptSearchRegex, $html, $matches);
735
736         foreach ($matches[0] as $match) {
737             $html = str_replace($match, htmlentities($match), $html);
738         }
739         return $html;
740     }
741
742     /**
743      * Search for image usage within page content.
744      * @param $imageString
745      * @return mixed
746      */
747     public function searchForImage($imageString)
748     {
749         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
750         foreach ($pages as $page) {
751             $page->url = $page->getUrl();
752             $page->html = '';
753             $page->text = '';
754         }
755         return count($pages) > 0 ? $pages : false;
756     }
757
758     /**
759      * Destroy a bookshelf instance
760      * @param \BookStack\Entities\Bookshelf $shelf
761      * @throws \Throwable
762      */
763     public function destroyBookshelf(Bookshelf $shelf)
764     {
765         $this->destroyEntityCommonRelations($shelf);
766         $shelf->delete();
767     }
768
769     /**
770      * Destroy the provided book and all its child entities.
771      * @param \BookStack\Entities\Book $book
772      * @throws NotifyException
773      * @throws \Throwable
774      */
775     public function destroyBook(Book $book)
776     {
777         foreach ($book->pages as $page) {
778             $this->destroyPage($page);
779         }
780         foreach ($book->chapters as $chapter) {
781             $this->destroyChapter($chapter);
782         }
783         $this->destroyEntityCommonRelations($book);
784         $book->delete();
785     }
786
787     /**
788      * Destroy a chapter and its relations.
789      * @param \BookStack\Entities\Chapter $chapter
790      * @throws \Throwable
791      */
792     public function destroyChapter(Chapter $chapter)
793     {
794         if (count($chapter->pages) > 0) {
795             foreach ($chapter->pages as $page) {
796                 $page->chapter_id = 0;
797                 $page->save();
798             }
799         }
800         $this->destroyEntityCommonRelations($chapter);
801         $chapter->delete();
802     }
803
804     /**
805      * Destroy a given page along with its dependencies.
806      * @param Page $page
807      * @throws NotifyException
808      * @throws \Throwable
809      */
810     public function destroyPage(Page $page)
811     {
812         // Check if set as custom homepage
813         $customHome = setting('app-homepage', '0:');
814         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
815             throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
816         }
817
818         $this->destroyEntityCommonRelations($page);
819
820         // Delete Attached Files
821         $attachmentService = app(AttachmentService::class);
822         foreach ($page->attachments as $attachment) {
823             $attachmentService->deleteFile($attachment);
824         }
825
826         $page->delete();
827     }
828
829     /**
830      * Destroy or handle the common relations connected to an entity.
831      * @param \BookStack\Entities\Entity $entity
832      * @throws \Throwable
833      */
834     protected function destroyEntityCommonRelations(Entity $entity)
835     {
836         \Activity::removeEntity($entity);
837         $entity->views()->delete();
838         $entity->permissions()->delete();
839         $entity->tags()->delete();
840         $entity->comments()->delete();
841         $this->permissionService->deleteJointPermissionsForEntity($entity);
842         $this->searchService->deleteEntityTerms($entity);
843     }
844
845     /**
846      * Copy the permissions of a bookshelf to all child books.
847      * Returns the number of books that had permissions updated.
848      * @param \BookStack\Entities\Bookshelf $bookshelf
849      * @return int
850      * @throws \Throwable
851      */
852     public function copyBookshelfPermissions(Bookshelf $bookshelf)
853     {
854         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
855         $shelfBooks = $bookshelf->books()->get();
856         $updatedBookCount = 0;
857
858         foreach ($shelfBooks as $book) {
859             if (!userCan('restrictions-manage', $book)) {
860                 continue;
861             }
862             $book->permissions()->delete();
863             $book->restricted = $bookshelf->restricted;
864             $book->permissions()->createMany($shelfPermissions);
865             $book->save();
866             $this->permissionService->buildJointPermissionsForEntity($book);
867             $updatedBookCount++;
868         }
869
870         return $updatedBookCount;
871     }
872 }