]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/EntityRepo.php
Normalize ini and properties values
[bookstack] / app / Entities / Repos / EntityRepo.php
1 <?php namespace BookStack\Entities\Repos;
2
3 use Activity;
4 use BookStack\Actions\TagRepo;
5 use BookStack\Actions\ViewService;
6 use BookStack\Auth\Permissions\PermissionService;
7 use BookStack\Auth\User;
8 use BookStack\Entities\Book;
9 use BookStack\Entities\Bookshelf;
10 use BookStack\Entities\Chapter;
11 use BookStack\Entities\Entity;
12 use BookStack\Entities\EntityProvider;
13 use BookStack\Entities\Page;
14 use BookStack\Entities\SearchService;
15 use BookStack\Exceptions\NotFoundException;
16 use BookStack\Exceptions\NotifyException;
17 use BookStack\Uploads\AttachmentService;
18 use DOMDocument;
19 use DOMNode;
20 use DOMXPath;
21 use Illuminate\Contracts\Pagination\LengthAwarePaginator;
22 use Illuminate\Database\Eloquent\Builder;
23 use Illuminate\Database\Query\Builder as QueryBuilder;
24 use Illuminate\Http\Request;
25 use Illuminate\Support\Collection;
26 use Throwable;
27
28 class EntityRepo
29 {
30
31     /**
32      * @var EntityProvider
33      */
34     protected $entityProvider;
35
36     /**
37      * @var PermissionService
38      */
39     protected $permissionService;
40
41     /**
42      * @var ViewService
43      */
44     protected $viewService;
45
46     /**
47      * @var TagRepo
48      */
49     protected $tagRepo;
50
51     /**
52      * @var SearchService
53      */
54     protected $searchService;
55
56     /**
57      * EntityRepo constructor.
58      * @param EntityProvider $entityProvider
59      * @param ViewService $viewService
60      * @param PermissionService $permissionService
61      * @param TagRepo $tagRepo
62      * @param SearchService $searchService
63      */
64     public function __construct(
65         EntityProvider $entityProvider,
66         ViewService $viewService,
67         PermissionService $permissionService,
68         TagRepo $tagRepo,
69         SearchService $searchService
70     ) {
71         $this->entityProvider = $entityProvider;
72         $this->viewService = $viewService;
73         $this->permissionService = $permissionService;
74         $this->tagRepo = $tagRepo;
75         $this->searchService = $searchService;
76     }
77
78     /**
79      * Base query for searching entities via permission system
80      * @param string $type
81      * @param bool $allowDrafts
82      * @param string $permission
83      * @return QueryBuilder
84      */
85     protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
86     {
87         $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
88         if (strtolower($type) === 'page' && !$allowDrafts) {
89             $q = $q->where('draft', '=', false);
90         }
91         return $q;
92     }
93
94     /**
95      * Check if an entity with the given id exists.
96      * @param $type
97      * @param $id
98      * @return bool
99      */
100     public function exists($type, $id)
101     {
102         return $this->entityQuery($type)->where('id', '=', $id)->exists();
103     }
104
105     /**
106      * Get an entity by ID
107      * @param string $type
108      * @param integer $id
109      * @param bool $allowDrafts
110      * @param bool $ignorePermissions
111      * @return Entity
112      */
113     public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
114     {
115         $query = $this->entityQuery($type, $allowDrafts);
116
117         if ($ignorePermissions) {
118             $query = $this->entityProvider->get($type)->newQuery();
119         }
120
121         return $query->find($id);
122     }
123
124     /**
125      * @param string $type
126      * @param []int $ids
127      * @param bool $allowDrafts
128      * @param bool $ignorePermissions
129      * @return Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
130      */
131     public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
132     {
133         $query = $this->entityQuery($type, $allowDrafts);
134
135         if ($ignorePermissions) {
136             $query = $this->entityProvider->get($type)->newQuery();
137         }
138
139         return $query->whereIn('id', $ids)->get();
140     }
141
142     /**
143      * Get an entity by its url slug.
144      * @param string $type
145      * @param string $slug
146      * @param string|null $bookSlug
147      * @return Entity
148      * @throws NotFoundException
149      */
150     public function getEntityBySlug(string $type, string $slug, string $bookSlug = null): Entity
151     {
152         $type = strtolower($type);
153         $query = $this->entityQuery($type)->where('slug', '=', $slug);
154
155         if ($type === 'chapter' || $type === 'page') {
156             $query = $query->where('book_id', '=', function (QueryBuilder $query) use ($bookSlug) {
157                 $query->select('id')
158                     ->from($this->entityProvider->book->getTable())
159                     ->where('slug', '=', $bookSlug)->limit(1);
160             });
161         }
162
163         $entity = $query->first();
164
165         if ($entity === null) {
166             throw new NotFoundException(trans('errors.' . $type . '_not_found'));
167         }
168
169         return $entity;
170     }
171
172
173     /**
174      * Get all entities of a type with the given permission, limited by count unless count is false.
175      * @param string $type
176      * @param integer|bool $count
177      * @param string $permission
178      * @return Collection
179      */
180     public function getAll($type, $count = 20, $permission = 'view')
181     {
182         $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
183         if ($count !== false) {
184             $q = $q->take($count);
185         }
186         return $q->get();
187     }
188
189     /**
190      * Get all entities in a paginated format
191      * @param $type
192      * @param int $count
193      * @param string $sort
194      * @param string $order
195      * @param null|callable $queryAddition
196      * @return LengthAwarePaginator
197      */
198     public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc', $queryAddition = null)
199     {
200         $query = $this->entityQuery($type);
201         $query = $this->addSortToQuery($query, $sort, $order);
202         if ($queryAddition) {
203             $queryAddition($query);
204         }
205         return $query->paginate($count);
206     }
207
208     /**
209      * Add sorting operations to an entity query.
210      * @param Builder $query
211      * @param string $sort
212      * @param string $order
213      * @return Builder
214      */
215     protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
216     {
217         $order = ($order === 'asc') ? 'asc' : 'desc';
218         $propertySorts = ['name', 'created_at', 'updated_at'];
219
220         if (in_array($sort, $propertySorts)) {
221             return $query->orderBy($sort, $order);
222         }
223
224         return $query;
225     }
226
227     /**
228      * Get the most recently created entities of the given type.
229      * @param string $type
230      * @param int $count
231      * @param int $page
232      * @param bool|callable $additionalQuery
233      * @return Collection
234      */
235     public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
236     {
237         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
238             ->orderBy('created_at', 'desc');
239         if (strtolower($type) === 'page') {
240             $query = $query->where('draft', '=', false);
241         }
242         if ($additionalQuery !== false && is_callable($additionalQuery)) {
243             $additionalQuery($query);
244         }
245         return $query->skip($page * $count)->take($count)->get();
246     }
247
248     /**
249      * Get the most recently updated entities of the given type.
250      * @param string $type
251      * @param int $count
252      * @param int $page
253      * @param bool|callable $additionalQuery
254      * @return Collection
255      */
256     public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
257     {
258         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
259             ->orderBy('updated_at', 'desc');
260         if (strtolower($type) === 'page') {
261             $query = $query->where('draft', '=', false);
262         }
263         if ($additionalQuery !== false && is_callable($additionalQuery)) {
264             $additionalQuery($query);
265         }
266         return $query->skip($page * $count)->take($count)->get();
267     }
268
269     /**
270      * Get the most recently viewed entities.
271      * @param string|bool $type
272      * @param int $count
273      * @param int $page
274      * @return mixed
275      */
276     public function getRecentlyViewed($type, $count = 10, $page = 0)
277     {
278         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
279         return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
280     }
281
282     /**
283      * Get the latest pages added to the system with pagination.
284      * @param string $type
285      * @param int $count
286      * @return mixed
287      */
288     public function getRecentlyCreatedPaginated($type, $count = 20)
289     {
290         return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
291     }
292
293     /**
294      * Get the latest pages added to the system with pagination.
295      * @param string $type
296      * @param int $count
297      * @return mixed
298      */
299     public function getRecentlyUpdatedPaginated($type, $count = 20)
300     {
301         return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
302     }
303
304     /**
305      * Get the most popular entities base on all views.
306      * @param string $type
307      * @param int $count
308      * @param int $page
309      * @return mixed
310      */
311     public function getPopular(string $type, int $count = 10, int $page = 0)
312     {
313         return $this->viewService->getPopular($count, $page, $type);
314     }
315
316     /**
317      * Get draft pages owned by the current user.
318      * @param int $count
319      * @param int $page
320      * @return Collection
321      */
322     public function getUserDraftPages($count = 20, $page = 0)
323     {
324         return $this->entityProvider->page->where('draft', '=', true)
325             ->where('created_by', '=', user()->id)
326             ->orderBy('updated_at', 'desc')
327             ->skip($count * $page)->take($count)->get();
328     }
329
330     /**
331      * Get the number of entities the given user has created.
332      * @param string $type
333      * @param User $user
334      * @return int
335      */
336     public function getUserTotalCreated(string $type, User $user)
337     {
338         return $this->entityProvider->get($type)
339             ->where('created_by', '=', $user->id)->count();
340     }
341
342     /**
343      * Get the child items for a chapter sorted by priority but
344      * with draft items floated to the top.
345      * @param Bookshelf $bookshelf
346      * @return \Illuminate\Database\Eloquent\Collection|static[]
347      */
348     public function getBookshelfChildren(Bookshelf $bookshelf)
349     {
350         return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
351     }
352
353     /**
354      * Get the direct children of a book.
355      * @param Book $book
356      * @return \Illuminate\Database\Eloquent\Collection
357      */
358     public function getBookDirectChildren(Book $book)
359     {
360         $pages = $this->permissionService->enforceEntityRestrictions('page', $book->directPages())->get();
361         $chapters = $this->permissionService->enforceEntityRestrictions('chapters', $book->chapters())->get();
362         return collect()->concat($pages)->concat($chapters)->sortBy('priority')->sortByDesc('draft');
363     }
364
365     /**
366      * Get all child objects of a book.
367      * Returns a sorted collection of Pages and Chapters.
368      * Loads the book slug onto child elements to prevent access database access for getting the slug.
369      * @param Book $book
370      * @param bool $filterDrafts
371      * @param bool $renderPages
372      * @return mixed
373      */
374     public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
375     {
376         $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
377         $entities = [];
378         $parents = [];
379         $tree = [];
380
381         foreach ($q as $index => $rawEntity) {
382             if ($rawEntity->entity_type ===  $this->entityProvider->page->getMorphClass()) {
383                 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
384                 if ($renderPages) {
385                     $entities[$index]->html = $rawEntity->html;
386                     $entities[$index]->html = $this->renderPage($entities[$index]);
387                 };
388             } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
389                 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
390                 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
391                 $parents[$key] = $entities[$index];
392                 $parents[$key]->setAttribute('pages', collect());
393             }
394             if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
395                 $tree[] = $entities[$index];
396             }
397             $entities[$index]->book = $book;
398         }
399
400         foreach ($entities as $entity) {
401             if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
402                 continue;
403             }
404             $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
405             if (!isset($parents[$parentKey])) {
406                 $tree[] = $entity;
407                 continue;
408             }
409             $chapter = $parents[$parentKey];
410             $chapter->pages->push($entity);
411         }
412
413         return collect($tree);
414     }
415
416     /**
417      * Get the child items for a chapter sorted by priority but
418      * with draft items floated to the top.
419      * @param Chapter $chapter
420      * @return \Illuminate\Database\Eloquent\Collection|static[]
421      */
422     public function getChapterChildren(Chapter $chapter)
423     {
424         return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
425             ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
426     }
427
428
429     /**
430      * Get the next sequential priority for a new child element in the given book.
431      * @param Book $book
432      * @return int
433      */
434     public function getNewBookPriority(Book $book)
435     {
436         $lastElem = $this->getBookChildren($book)->pop();
437         return $lastElem ? $lastElem->priority + 1 : 0;
438     }
439
440     /**
441      * Get a new priority for a new page to be added to the given chapter.
442      * @param Chapter $chapter
443      * @return int
444      */
445     public function getNewChapterPriority(Chapter $chapter)
446     {
447         $lastPage = $chapter->pages('DESC')->first();
448         return $lastPage !== null ? $lastPage->priority + 1 : 0;
449     }
450
451     /**
452      * Find a suitable slug for an entity.
453      * @param string $type
454      * @param string $name
455      * @param bool|integer $currentId
456      * @param bool|integer $bookId Only pass if type is not a book
457      * @return string
458      */
459     public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
460     {
461         $slug = $this->nameToSlug($name);
462         while ($this->slugExists($type, $slug, $currentId, $bookId)) {
463             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
464         }
465         return $slug;
466     }
467
468     /**
469      * Check if a slug already exists in the database.
470      * @param string $type
471      * @param string $slug
472      * @param bool|integer $currentId
473      * @param bool|integer $bookId
474      * @return bool
475      */
476     protected function slugExists($type, $slug, $currentId = false, $bookId = false)
477     {
478         $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
479         if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
480             $query = $query->where('book_id', '=', $bookId);
481         }
482         if ($currentId) {
483             $query = $query->where('id', '!=', $currentId);
484         }
485         return $query->count() > 0;
486     }
487
488     /**
489      * Updates entity restrictions from a request
490      * @param Request $request
491      * @param Entity $entity
492      * @throws Throwable
493      */
494     public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
495     {
496         $entity->restricted = $request->get('restricted', '') === 'true';
497         $entity->permissions()->delete();
498
499         if ($request->filled('restrictions')) {
500             foreach ($request->get('restrictions') as $roleId => $restrictions) {
501                 foreach ($restrictions as $action => $value) {
502                     $entity->permissions()->create([
503                         'role_id' => $roleId,
504                         'action'  => strtolower($action)
505                     ]);
506                 }
507             }
508         }
509
510         $entity->save();
511         $this->permissionService->buildJointPermissionsForEntity($entity);
512     }
513
514
515     /**
516      * Create a new entity from request input.
517      * Used for books and chapters.
518      * @param string $type
519      * @param array $input
520      * @param Book|null $book
521      * @return Entity
522      * @throws Throwable
523      */
524     public function createFromInput(string $type, array $input = [], Book $book = null)
525     {
526         $entityModel = $this->entityProvider->get($type)->newInstance($input);
527         $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $book ? $book->id : false);
528         $entityModel->created_by = user()->id;
529         $entityModel->updated_by = user()->id;
530
531         if ($book) {
532             $entityModel->book_id = $book->id;
533         }
534
535         $entityModel->save();
536
537         if (isset($input['tags'])) {
538             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
539         }
540
541         $this->permissionService->buildJointPermissionsForEntity($entityModel);
542         $this->searchService->indexEntity($entityModel);
543         return $entityModel;
544     }
545
546     /**
547      * Update entity details from request input.
548      * Used for books and chapters
549      * @param string $type
550      * @param Entity $entityModel
551      * @param array $input
552      * @return Entity
553      * @throws Throwable
554      */
555     public function updateFromInput(string $type, Entity $entityModel, array $input = [])
556     {
557         if ($entityModel->name !== $input['name']) {
558             $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
559         }
560
561         $entityModel->fill($input);
562         $entityModel->updated_by = user()->id;
563         $entityModel->save();
564
565         if (isset($input['tags'])) {
566             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
567         }
568
569         $this->permissionService->buildJointPermissionsForEntity($entityModel);
570         $this->searchService->indexEntity($entityModel);
571         return $entityModel;
572     }
573
574     /**
575      * Sync the books assigned to a shelf from a comma-separated list
576      * of book IDs.
577      * @param Bookshelf $shelf
578      * @param string $books
579      */
580     public function updateShelfBooks(Bookshelf $shelf, string $books)
581     {
582         $ids = explode(',', $books);
583
584         // Check books exist and match ordering
585         $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
586         $syncData = [];
587         foreach ($ids as $index => $id) {
588             if ($bookIds->contains($id)) {
589                 $syncData[$id] = ['order' => $index];
590             }
591         }
592
593         $shelf->books()->sync($syncData);
594     }
595
596     /**
597      * Change the book that an entity belongs to.
598      * @param string $type
599      * @param integer $newBookId
600      * @param Entity $entity
601      * @param bool $rebuildPermissions
602      * @return Entity
603      */
604     public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
605     {
606         $entity->book_id = $newBookId;
607         // Update related activity
608         foreach ($entity->activity as $activity) {
609             $activity->book_id = $newBookId;
610             $activity->save();
611         }
612         $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
613         $entity->save();
614
615         // Update all child pages if a chapter
616         if (strtolower($type) === 'chapter') {
617             foreach ($entity->pages as $page) {
618                 $this->changeBook('page', $newBookId, $page, false);
619             }
620         }
621
622         // Update permissions if applicable
623         if ($rebuildPermissions) {
624             $entity->load('book');
625             $this->permissionService->buildJointPermissionsForEntity($entity->book);
626         }
627
628         return $entity;
629     }
630
631     /**
632      * Alias method to update the book jointPermissions in the PermissionService.
633      * @param Book $book
634      */
635     public function buildJointPermissionsForBook(Book $book)
636     {
637         $this->permissionService->buildJointPermissionsForEntity($book);
638     }
639
640     /**
641      * Format a name as a url slug.
642      * @param $name
643      * @return string
644      */
645     protected function nameToSlug($name)
646     {
647         $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
648         $slug = preg_replace('/\s{2,}/', ' ', $slug);
649         $slug = str_replace(' ', '-', $slug);
650         if ($slug === "") {
651             $slug = substr(md5(rand(1, 500)), 0, 5);
652         }
653         return $slug;
654     }
655
656     /**
657      * Render the page for viewing
658      * @param Page $page
659      * @param bool $blankIncludes
660      * @return string
661      */
662     public function renderPage(Page $page, bool $blankIncludes = false) : string
663     {
664         $content = $page->html;
665
666         if (!config('app.allow_content_scripts')) {
667             $content = $this->escapeScripts($content);
668         }
669
670         if ($blankIncludes) {
671             $content = $this->blankPageIncludes($content);
672         } else {
673             $content = $this->parsePageIncludes($content);
674         }
675
676         return $content;
677     }
678
679     /**
680      * Remove any page include tags within the given HTML.
681      * @param string $html
682      * @return string
683      */
684     protected function blankPageIncludes(string $html) : string
685     {
686         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
687     }
688
689     /**
690      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
691      * @param string $html
692      * @return mixed|string
693      */
694     protected function parsePageIncludes(string $html) : string
695     {
696         $matches = [];
697         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
698
699         $topLevelTags = ['table', 'ul', 'ol'];
700         foreach ($matches[1] as $index => $includeId) {
701             $splitInclude = explode('#', $includeId, 2);
702             $pageId = intval($splitInclude[0]);
703             if (is_nan($pageId)) {
704                 continue;
705             }
706
707             $matchedPage = $this->getById('page', $pageId);
708             if ($matchedPage === null) {
709                 $html = str_replace($matches[0][$index], '', $html);
710                 continue;
711             }
712
713             if (count($splitInclude) === 1) {
714                 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
715                 continue;
716             }
717
718             $doc = new DOMDocument();
719             libxml_use_internal_errors(true);
720             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
721             $matchingElem = $doc->getElementById($splitInclude[1]);
722             if ($matchingElem === null) {
723                 $html = str_replace($matches[0][$index], '', $html);
724                 continue;
725             }
726             $innerContent = '';
727             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
728             if ($isTopLevel) {
729                 $innerContent .= $doc->saveHTML($matchingElem);
730             } else {
731                 foreach ($matchingElem->childNodes as $childNode) {
732                     $innerContent .= $doc->saveHTML($childNode);
733                 }
734             }
735             libxml_clear_errors();
736             $html = str_replace($matches[0][$index], trim($innerContent), $html);
737         }
738
739         return $html;
740     }
741
742     /**
743      * Escape script tags within HTML content.
744      * @param string $html
745      * @return string
746      */
747     protected function escapeScripts(string $html) : string
748     {
749         if ($html == '') {
750             return $html;
751         }
752
753         libxml_use_internal_errors(true);
754         $doc = new DOMDocument();
755         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
756         $xPath = new DOMXPath($doc);
757
758         // Remove standard script tags
759         $scriptElems = $xPath->query('//script');
760         foreach ($scriptElems as $scriptElem) {
761             $scriptElem->parentNode->removeChild($scriptElem);
762         }
763
764         // Remove data or JavaScript iFrames
765         $badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
766         foreach ($badIframes as $badIframe) {
767             $badIframe->parentNode->removeChild($badIframe);
768         }
769
770         // Remove 'on*' attributes
771         $onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
772         foreach ($onAttributes as $attr) {
773             /** @var \DOMAttr $attr*/
774             $attrName = $attr->nodeName;
775             $attr->parentNode->removeAttribute($attrName);
776         }
777
778         $html = '';
779         $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
780         foreach ($topElems as $child) {
781             $html .= $doc->saveHTML($child);
782         }
783
784         return $html;
785     }
786
787     /**
788      * Search for image usage within page content.
789      * @param $imageString
790      * @return mixed
791      */
792     public function searchForImage($imageString)
793     {
794         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get(['id', 'name', 'slug', 'book_id']);
795         foreach ($pages as $page) {
796             $page->url = $page->getUrl();
797             $page->html = '';
798             $page->text = '';
799         }
800         return count($pages) > 0 ? $pages : false;
801     }
802
803     /**
804      * Destroy a bookshelf instance
805      * @param Bookshelf $shelf
806      * @throws Throwable
807      */
808     public function destroyBookshelf(Bookshelf $shelf)
809     {
810         $this->destroyEntityCommonRelations($shelf);
811         $shelf->delete();
812     }
813
814     /**
815      * Destroy a chapter and its relations.
816      * @param Chapter $chapter
817      * @throws Throwable
818      */
819     public function destroyChapter(Chapter $chapter)
820     {
821         if (count($chapter->pages) > 0) {
822             foreach ($chapter->pages as $page) {
823                 $page->chapter_id = 0;
824                 $page->save();
825             }
826         }
827         $this->destroyEntityCommonRelations($chapter);
828         $chapter->delete();
829     }
830
831     /**
832      * Destroy a given page along with its dependencies.
833      * @param Page $page
834      * @throws NotifyException
835      * @throws Throwable
836      */
837     public function destroyPage(Page $page)
838     {
839         // Check if set as custom homepage & remove setting if not used or throw error if active
840         $customHome = setting('app-homepage', '0:');
841         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
842             if (setting('app-homepage-type') === 'page') {
843                 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
844             }
845             setting()->remove('app-homepage');
846         }
847
848         $this->destroyEntityCommonRelations($page);
849
850         // Delete Attached Files
851         $attachmentService = app(AttachmentService::class);
852         foreach ($page->attachments as $attachment) {
853             $attachmentService->deleteFile($attachment);
854         }
855
856         $page->delete();
857     }
858
859     /**
860      * Destroy or handle the common relations connected to an entity.
861      * @param Entity $entity
862      * @throws Throwable
863      */
864     protected function destroyEntityCommonRelations(Entity $entity)
865     {
866         Activity::removeEntity($entity);
867         $entity->views()->delete();
868         $entity->permissions()->delete();
869         $entity->tags()->delete();
870         $entity->comments()->delete();
871         $this->permissionService->deleteJointPermissionsForEntity($entity);
872         $this->searchService->deleteEntityTerms($entity);
873     }
874
875     /**
876      * Copy the permissions of a bookshelf to all child books.
877      * Returns the number of books that had permissions updated.
878      * @param Bookshelf $bookshelf
879      * @return int
880      * @throws Throwable
881      */
882     public function copyBookshelfPermissions(Bookshelf $bookshelf)
883     {
884         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
885         $shelfBooks = $bookshelf->books()->get();
886         $updatedBookCount = 0;
887
888         foreach ($shelfBooks as $book) {
889             if (!userCan('restrictions-manage', $book)) {
890                 continue;
891             }
892             $book->permissions()->delete();
893             $book->restricted = $bookshelf->restricted;
894             $book->permissions()->createMany($shelfPermissions);
895             $book->save();
896             $this->permissionService->buildJointPermissionsForEntity($book);
897             $updatedBookCount++;
898         }
899
900         return $updatedBookCount;
901     }
902 }