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