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