]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/EntityRepo.php
Updated existing image tests to reflect changes
[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      * Append a Book to a BookShelf.
582      * @param Bookshelf $shelf
583      * @param Book $book
584      */
585     public function appendBookToShelf(Bookshelf $shelf, Book $book)
586     {
587         if ($shelf->contains($book)) {
588             return;
589         }
590
591         $maxOrder = $shelf->books()->max('order');
592         $shelf->books()->attach($book->id, ['order' => $maxOrder + 1]);
593     }
594
595     /**
596      * Change the book that an entity belongs to.
597      * @param string $type
598      * @param integer $newBookId
599      * @param Entity $entity
600      * @param bool $rebuildPermissions
601      * @return \BookStack\Entities\Entity
602      */
603     public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
604     {
605         $entity->book_id = $newBookId;
606         // Update related activity
607         foreach ($entity->activity as $activity) {
608             $activity->book_id = $newBookId;
609             $activity->save();
610         }
611         $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
612         $entity->save();
613
614         // Update all child pages if a chapter
615         if (strtolower($type) === 'chapter') {
616             foreach ($entity->pages as $page) {
617                 $this->changeBook('page', $newBookId, $page, false);
618             }
619         }
620
621         // Update permissions if applicable
622         if ($rebuildPermissions) {
623             $entity->load('book');
624             $this->permissionService->buildJointPermissionsForEntity($entity->book);
625         }
626
627         return $entity;
628     }
629
630     /**
631      * Alias method to update the book jointPermissions in the PermissionService.
632      * @param Book $book
633      */
634     public function buildJointPermissionsForBook(Book $book)
635     {
636         $this->permissionService->buildJointPermissionsForEntity($book);
637     }
638
639     /**
640      * Format a name as a url slug.
641      * @param $name
642      * @return string
643      */
644     protected function nameToSlug($name)
645     {
646         $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
647         $slug = preg_replace('/\s{2,}/', ' ', $slug);
648         $slug = str_replace(' ', '-', $slug);
649         if ($slug === "") {
650             $slug = substr(md5(rand(1, 500)), 0, 5);
651         }
652         return $slug;
653     }
654
655     /**
656      * Render the page for viewing
657      * @param Page $page
658      * @param bool $blankIncludes
659      * @return string
660      */
661     public function renderPage(Page $page, bool $blankIncludes = false) : string
662     {
663         $content = $page->html;
664
665         if (!config('app.allow_content_scripts')) {
666             $content = $this->escapeScripts($content);
667         }
668
669         if ($blankIncludes) {
670             $content = $this->blankPageIncludes($content);
671         } else {
672             $content = $this->parsePageIncludes($content);
673         }
674
675         return $content;
676     }
677
678     /**
679      * Remove any page include tags within the given HTML.
680      * @param string $html
681      * @return string
682      */
683     protected function blankPageIncludes(string $html) : string
684     {
685         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
686     }
687
688     /**
689      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
690      * @param string $html
691      * @return mixed|string
692      */
693     protected function parsePageIncludes(string $html) : string
694     {
695         $matches = [];
696         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
697
698         $topLevelTags = ['table', 'ul', 'ol'];
699         foreach ($matches[1] as $index => $includeId) {
700             $splitInclude = explode('#', $includeId, 2);
701             $pageId = intval($splitInclude[0]);
702             if (is_nan($pageId)) {
703                 continue;
704             }
705
706             $matchedPage = $this->getById('page', $pageId);
707             if ($matchedPage === null) {
708                 $html = str_replace($matches[0][$index], '', $html);
709                 continue;
710             }
711
712             if (count($splitInclude) === 1) {
713                 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
714                 continue;
715             }
716
717             $doc = new DOMDocument();
718             libxml_use_internal_errors(true);
719             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
720             $matchingElem = $doc->getElementById($splitInclude[1]);
721             if ($matchingElem === null) {
722                 $html = str_replace($matches[0][$index], '', $html);
723                 continue;
724             }
725             $innerContent = '';
726             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
727             if ($isTopLevel) {
728                 $innerContent .= $doc->saveHTML($matchingElem);
729             } else {
730                 foreach ($matchingElem->childNodes as $childNode) {
731                     $innerContent .= $doc->saveHTML($childNode);
732                 }
733             }
734             libxml_clear_errors();
735             $html = str_replace($matches[0][$index], trim($innerContent), $html);
736         }
737
738         return $html;
739     }
740
741     /**
742      * Escape script tags within HTML content.
743      * @param string $html
744      * @return string
745      */
746     protected function escapeScripts(string $html) : string
747     {
748         $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
749         $matches = [];
750         preg_match_all($scriptSearchRegex, $html, $matches);
751
752         foreach ($matches[0] as $match) {
753             $html = str_replace($match, htmlentities($match), $html);
754         }
755         return $html;
756     }
757
758     /**
759      * Search for image usage within page content.
760      * @param $imageString
761      * @return mixed
762      */
763     public function searchForImage($imageString)
764     {
765         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get(['id', 'name', 'slug', 'book_id']);
766         foreach ($pages as $page) {
767             $page->url = $page->getUrl();
768             $page->html = '';
769             $page->text = '';
770         }
771         return count($pages) > 0 ? $pages : false;
772     }
773
774     /**
775      * Destroy a bookshelf instance
776      * @param \BookStack\Entities\Bookshelf $shelf
777      * @throws \Throwable
778      */
779     public function destroyBookshelf(Bookshelf $shelf)
780     {
781         $this->destroyEntityCommonRelations($shelf);
782         $shelf->delete();
783     }
784
785     /**
786      * Destroy the provided book and all its child entities.
787      * @param \BookStack\Entities\Book $book
788      * @throws NotifyException
789      * @throws \Throwable
790      */
791     public function destroyBook(Book $book)
792     {
793         foreach ($book->pages as $page) {
794             $this->destroyPage($page);
795         }
796         foreach ($book->chapters as $chapter) {
797             $this->destroyChapter($chapter);
798         }
799         $this->destroyEntityCommonRelations($book);
800         $book->delete();
801     }
802
803     /**
804      * Destroy a chapter and its relations.
805      * @param \BookStack\Entities\Chapter $chapter
806      * @throws \Throwable
807      */
808     public function destroyChapter(Chapter $chapter)
809     {
810         if (count($chapter->pages) > 0) {
811             foreach ($chapter->pages as $page) {
812                 $page->chapter_id = 0;
813                 $page->save();
814             }
815         }
816         $this->destroyEntityCommonRelations($chapter);
817         $chapter->delete();
818     }
819
820     /**
821      * Destroy a given page along with its dependencies.
822      * @param Page $page
823      * @throws NotifyException
824      * @throws \Throwable
825      */
826     public function destroyPage(Page $page)
827     {
828         // Check if set as custom homepage
829         $customHome = setting('app-homepage', '0:');
830         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
831             throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
832         }
833
834         $this->destroyEntityCommonRelations($page);
835
836         // Delete Attached Files
837         $attachmentService = app(AttachmentService::class);
838         foreach ($page->attachments as $attachment) {
839             $attachmentService->deleteFile($attachment);
840         }
841
842         $page->delete();
843     }
844
845     /**
846      * Destroy or handle the common relations connected to an entity.
847      * @param \BookStack\Entities\Entity $entity
848      * @throws \Throwable
849      */
850     protected function destroyEntityCommonRelations(Entity $entity)
851     {
852         \Activity::removeEntity($entity);
853         $entity->views()->delete();
854         $entity->permissions()->delete();
855         $entity->tags()->delete();
856         $entity->comments()->delete();
857         $this->permissionService->deleteJointPermissionsForEntity($entity);
858         $this->searchService->deleteEntityTerms($entity);
859     }
860
861     /**
862      * Copy the permissions of a bookshelf to all child books.
863      * Returns the number of books that had permissions updated.
864      * @param \BookStack\Entities\Bookshelf $bookshelf
865      * @return int
866      * @throws \Throwable
867      */
868     public function copyBookshelfPermissions(Bookshelf $bookshelf)
869     {
870         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
871         $shelfBooks = $bookshelf->books()->get();
872         $updatedBookCount = 0;
873
874         foreach ($shelfBooks as $book) {
875             if (!userCan('restrictions-manage', $book)) {
876                 continue;
877             }
878             $book->permissions()->delete();
879             $book->restricted = $bookshelf->restricted;
880             $book->permissions()->createMany($shelfPermissions);
881             $book->save();
882             $this->permissionService->buildJointPermissionsForEntity($book);
883             $updatedBookCount++;
884         }
885
886         return $updatedBookCount;
887     }
888 }