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