]> BookStack Code Mirror - bookstack/blob - app/Entities/EntityRepo.php
Fixes "bookshelf" pt_BR translation in "activities"
[bookstack] / app / Entities / EntityRepo.php
1 <?php namespace BookStack\Entities;
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\Exceptions\NotFoundException;
8 use BookStack\Exceptions\NotifyException;
9 use BookStack\Uploads\AttachmentService;
10 use Carbon\Carbon;
11 use DOMDocument;
12 use DOMXPath;
13 use Illuminate\Http\Request;
14 use Illuminate\Support\Collection;
15
16 class EntityRepo
17 {
18
19     /**
20      * @var EntityProvider
21      */
22     protected $entityProvider;
23
24     /**
25      * @var PermissionService
26      */
27     protected $permissionService;
28
29     /**
30      * @var ViewService
31      */
32     protected $viewService;
33
34     /**
35      * @var TagRepo
36      */
37     protected $tagRepo;
38
39     /**
40      * @var SearchService
41      */
42     protected $searchService;
43
44     /**
45      * EntityRepo constructor.
46      * @param EntityProvider $entityProvider
47      * @param ViewService $viewService
48      * @param PermissionService $permissionService
49      * @param TagRepo $tagRepo
50      * @param SearchService $searchService
51      */
52     public function __construct(
53         EntityProvider $entityProvider,
54         ViewService $viewService,
55         PermissionService $permissionService,
56         TagRepo $tagRepo,
57         SearchService $searchService
58     ) {
59         $this->entityProvider = $entityProvider;
60         $this->viewService = $viewService;
61         $this->permissionService = $permissionService;
62         $this->tagRepo = $tagRepo;
63         $this->searchService = $searchService;
64     }
65
66     /**
67      * Base query for searching entities via permission system
68      * @param string $type
69      * @param bool $allowDrafts
70      * @param string $permission
71      * @return \Illuminate\Database\Query\Builder
72      */
73     protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
74     {
75         $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
76         if (strtolower($type) === 'page' && !$allowDrafts) {
77             $q = $q->where('draft', '=', false);
78         }
79         return $q;
80     }
81
82     /**
83      * Check if an entity with the given id exists.
84      * @param $type
85      * @param $id
86      * @return bool
87      */
88     public function exists($type, $id)
89     {
90         return $this->entityQuery($type)->where('id', '=', $id)->exists();
91     }
92
93     /**
94      * Get an entity by ID
95      * @param string $type
96      * @param integer $id
97      * @param bool $allowDrafts
98      * @param bool $ignorePermissions
99      * @return \BookStack\Entities\Entity
100      */
101     public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
102     {
103         $query = $this->entityQuery($type, $allowDrafts);
104
105         if ($ignorePermissions) {
106             $query = $this->entityProvider->get($type)->newQuery();
107         }
108
109         return $query->find($id);
110     }
111
112     /**
113      * @param string $type
114      * @param []int $ids
115      * @param bool $allowDrafts
116      * @param bool $ignorePermissions
117      * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
118      */
119     public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
120     {
121         $query = $this->entityQuery($type, $allowDrafts);
122
123         if ($ignorePermissions) {
124             $query = $this->entityProvider->get($type)->newQuery();
125         }
126
127         return $query->whereIn('id', $ids)->get();
128     }
129
130     /**
131      * Get an entity by its url slug.
132      * @param string $type
133      * @param string $slug
134      * @param string|bool $bookSlug
135      * @return \BookStack\Entities\Entity
136      * @throws NotFoundException
137      */
138     public function getBySlug($type, $slug, $bookSlug = false)
139     {
140         $q = $this->entityQuery($type)->where('slug', '=', $slug);
141
142         if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
143             $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
144                 $query->select('id')
145                     ->from($this->entityProvider->book->getTable())
146                     ->where('slug', '=', $bookSlug)->limit(1);
147             });
148         }
149         $entity = $q->first();
150         if ($entity === null) {
151             throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
152         }
153         return $entity;
154     }
155
156
157     /**
158      * Search through page revisions and retrieve the last page in the
159      * current book that has a slug equal to the one given.
160      * @param string $pageSlug
161      * @param string $bookSlug
162      * @return null|Page
163      */
164     public function getPageByOldSlug($pageSlug, $bookSlug)
165     {
166         $revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
167             ->whereHas('page', function ($query) {
168                 $this->permissionService->enforceEntityRestrictions('page', $query);
169             })
170             ->where('type', '=', 'version')
171             ->where('book_slug', '=', $bookSlug)
172             ->orderBy('created_at', 'desc')
173             ->with('page')->first();
174         return $revision !== null ? $revision->page : null;
175     }
176
177     /**
178      * Get all entities of a type with the given permission, limited by count unless count is false.
179      * @param string $type
180      * @param integer|bool $count
181      * @param string $permission
182      * @return Collection
183      */
184     public function getAll($type, $count = 20, $permission = 'view')
185     {
186         $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
187         if ($count !== false) {
188             $q = $q->take($count);
189         }
190         return $q->get();
191     }
192
193     /**
194      * Get all entities in a paginated format
195      * @param $type
196      * @param int $count
197      * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
198      */
199     public function getAllPaginated($type, $count = 10)
200     {
201         return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
202     }
203
204     /**
205      * Get the most recently created entities of the given type.
206      * @param string $type
207      * @param int $count
208      * @param int $page
209      * @param bool|callable $additionalQuery
210      * @return Collection
211      */
212     public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
213     {
214         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
215             ->orderBy('created_at', 'desc');
216         if (strtolower($type) === 'page') {
217             $query = $query->where('draft', '=', false);
218         }
219         if ($additionalQuery !== false && is_callable($additionalQuery)) {
220             $additionalQuery($query);
221         }
222         return $query->skip($page * $count)->take($count)->get();
223     }
224
225     /**
226      * Get the most recently updated entities of the given type.
227      * @param string $type
228      * @param int $count
229      * @param int $page
230      * @param bool|callable $additionalQuery
231      * @return Collection
232      */
233     public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
234     {
235         $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
236             ->orderBy('updated_at', 'desc');
237         if (strtolower($type) === 'page') {
238             $query = $query->where('draft', '=', false);
239         }
240         if ($additionalQuery !== false && is_callable($additionalQuery)) {
241             $additionalQuery($query);
242         }
243         return $query->skip($page * $count)->take($count)->get();
244     }
245
246     /**
247      * Get the most recently viewed entities.
248      * @param string|bool $type
249      * @param int $count
250      * @param int $page
251      * @return mixed
252      */
253     public function getRecentlyViewed($type, $count = 10, $page = 0)
254     {
255         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
256         return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
257     }
258
259     /**
260      * Get the latest pages added to the system with pagination.
261      * @param string $type
262      * @param int $count
263      * @return mixed
264      */
265     public function getRecentlyCreatedPaginated($type, $count = 20)
266     {
267         return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
268     }
269
270     /**
271      * Get the latest pages added to the system with pagination.
272      * @param string $type
273      * @param int $count
274      * @return mixed
275      */
276     public function getRecentlyUpdatedPaginated($type, $count = 20)
277     {
278         return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
279     }
280
281     /**
282      * Get the most popular entities base on all views.
283      * @param string|bool $type
284      * @param int $count
285      * @param int $page
286      * @return mixed
287      */
288     public function getPopular($type, $count = 10, $page = 0)
289     {
290         $filter = is_bool($type) ? false : $this->entityProvider->get($type);
291         return $this->viewService->getPopular($count, $page, $filter);
292     }
293
294     /**
295      * Get draft pages owned by the current user.
296      * @param int $count
297      * @param int $page
298      * @return Collection
299      */
300     public function getUserDraftPages($count = 20, $page = 0)
301     {
302         return $this->entityProvider->page->where('draft', '=', true)
303             ->where('created_by', '=', user()->id)
304             ->orderBy('updated_at', 'desc')
305             ->skip($count * $page)->take($count)->get();
306     }
307
308     /**
309      * Get the number of entities the given user has created.
310      * @param string $type
311      * @param User $user
312      * @return int
313      */
314     public function getUserTotalCreated(string $type, User $user)
315     {
316         return $this->entityProvider->get($type)
317             ->where('created_by', '=', $user->id)->count();
318     }
319
320     /**
321      * Get the child items for a chapter sorted by priority but
322      * with draft items floated to the top.
323      * @param \BookStack\Entities\Bookshelf $bookshelf
324      * @return \Illuminate\Database\Eloquent\Collection|static[]
325      */
326     public function getBookshelfChildren(Bookshelf $bookshelf)
327     {
328         return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
329     }
330
331     /**
332      * Get all child objects of a book.
333      * Returns a sorted collection of Pages and Chapters.
334      * Loads the book slug onto child elements to prevent access database access for getting the slug.
335      * @param \BookStack\Entities\Book $book
336      * @param bool $filterDrafts
337      * @param bool $renderPages
338      * @return mixed
339      */
340     public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
341     {
342         $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
343         $entities = [];
344         $parents = [];
345         $tree = [];
346
347         foreach ($q as $index => $rawEntity) {
348             if ($rawEntity->entity_type ===  $this->entityProvider->page->getMorphClass()) {
349                 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
350                 if ($renderPages) {
351                     $entities[$index]->html = $rawEntity->html;
352                     $entities[$index]->html = $this->renderPage($entities[$index]);
353                 };
354             } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
355                 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
356                 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
357                 $parents[$key] = $entities[$index];
358                 $parents[$key]->setAttribute('pages', collect());
359             }
360             if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
361                 $tree[] = $entities[$index];
362             }
363             $entities[$index]->book = $book;
364         }
365
366         foreach ($entities as $entity) {
367             if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
368                 continue;
369             }
370             $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
371             if (!isset($parents[$parentKey])) {
372                 $tree[] = $entity;
373                 continue;
374             }
375             $chapter = $parents[$parentKey];
376             $chapter->pages->push($entity);
377         }
378
379         return collect($tree);
380     }
381
382     /**
383      * Get the child items for a chapter sorted by priority but
384      * with draft items floated to the top.
385      * @param \BookStack\Entities\Chapter $chapter
386      * @return \Illuminate\Database\Eloquent\Collection|static[]
387      */
388     public function getChapterChildren(Chapter $chapter)
389     {
390         return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
391             ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
392     }
393
394
395     /**
396      * Get the next sequential priority for a new child element in the given book.
397      * @param \BookStack\Entities\Book $book
398      * @return int
399      */
400     public function getNewBookPriority(Book $book)
401     {
402         $lastElem = $this->getBookChildren($book)->pop();
403         return $lastElem ? $lastElem->priority + 1 : 0;
404     }
405
406     /**
407      * Get a new priority for a new page to be added to the given chapter.
408      * @param \BookStack\Entities\Chapter $chapter
409      * @return int
410      */
411     public function getNewChapterPriority(Chapter $chapter)
412     {
413         $lastPage = $chapter->pages('DESC')->first();
414         return $lastPage !== null ? $lastPage->priority + 1 : 0;
415     }
416
417     /**
418      * Find a suitable slug for an entity.
419      * @param string $type
420      * @param string $name
421      * @param bool|integer $currentId
422      * @param bool|integer $bookId Only pass if type is not a book
423      * @return string
424      */
425     public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
426     {
427         $slug = $this->nameToSlug($name);
428         while ($this->slugExists($type, $slug, $currentId, $bookId)) {
429             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
430         }
431         return $slug;
432     }
433
434     /**
435      * Check if a slug already exists in the database.
436      * @param string $type
437      * @param string $slug
438      * @param bool|integer $currentId
439      * @param bool|integer $bookId
440      * @return bool
441      */
442     protected function slugExists($type, $slug, $currentId = false, $bookId = false)
443     {
444         $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
445         if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
446             $query = $query->where('book_id', '=', $bookId);
447         }
448         if ($currentId) {
449             $query = $query->where('id', '!=', $currentId);
450         }
451         return $query->count() > 0;
452     }
453
454     /**
455      * Updates entity restrictions from a request
456      * @param Request $request
457      * @param \BookStack\Entities\Entity $entity
458      * @throws \Throwable
459      */
460     public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
461     {
462         $entity->restricted = $request->get('restricted', '') === 'true';
463         $entity->permissions()->delete();
464
465         if ($request->filled('restrictions')) {
466             foreach ($request->get('restrictions') as $roleId => $restrictions) {
467                 foreach ($restrictions as $action => $value) {
468                     $entity->permissions()->create([
469                         'role_id' => $roleId,
470                         'action'  => strtolower($action)
471                     ]);
472                 }
473             }
474         }
475
476         $entity->save();
477         $this->permissionService->buildJointPermissionsForEntity($entity);
478     }
479
480
481
482     /**
483      * Create a new entity from request input.
484      * Used for books and chapters.
485      * @param string $type
486      * @param array $input
487      * @param bool|Book $book
488      * @return \BookStack\Entities\Entity
489      */
490     public function createFromInput($type, $input = [], $book = false)
491     {
492         $isChapter = strtolower($type) === 'chapter';
493         $entityModel = $this->entityProvider->get($type)->newInstance($input);
494         $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
495         $entityModel->created_by = user()->id;
496         $entityModel->updated_by = user()->id;
497         $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
498
499         if (isset($input['tags'])) {
500             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
501         }
502
503         $this->permissionService->buildJointPermissionsForEntity($entityModel);
504         $this->searchService->indexEntity($entityModel);
505         return $entityModel;
506     }
507
508     /**
509      * Update entity details from request input.
510      * Used for books and chapters
511      * @param string $type
512      * @param \BookStack\Entities\Entity $entityModel
513      * @param array $input
514      * @return \BookStack\Entities\Entity
515      */
516     public function updateFromInput($type, Entity $entityModel, $input = [])
517     {
518         if ($entityModel->name !== $input['name']) {
519             $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
520         }
521         $entityModel->fill($input);
522         $entityModel->updated_by = user()->id;
523         $entityModel->save();
524
525         if (isset($input['tags'])) {
526             $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
527         }
528
529         $this->permissionService->buildJointPermissionsForEntity($entityModel);
530         $this->searchService->indexEntity($entityModel);
531         return $entityModel;
532     }
533
534     /**
535      * Sync the books assigned to a shelf from a comma-separated list
536      * of book IDs.
537      * @param \BookStack\Entities\Bookshelf $shelf
538      * @param string $books
539      */
540     public function updateShelfBooks(Bookshelf $shelf, string $books)
541     {
542         $ids = explode(',', $books);
543
544         // Check books exist and match ordering
545         $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
546         $syncData = [];
547         foreach ($ids as $index => $id) {
548             if ($bookIds->contains($id)) {
549                 $syncData[$id] = ['order' => $index];
550             }
551         }
552
553         $shelf->books()->sync($syncData);
554     }
555
556     /**
557      * Change the book that an entity belongs to.
558      * @param string $type
559      * @param integer $newBookId
560      * @param Entity $entity
561      * @param bool $rebuildPermissions
562      * @return \BookStack\Entities\Entity
563      */
564     public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
565     {
566         $entity->book_id = $newBookId;
567         // Update related activity
568         foreach ($entity->activity as $activity) {
569             $activity->book_id = $newBookId;
570             $activity->save();
571         }
572         $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
573         $entity->save();
574
575         // Update all child pages if a chapter
576         if (strtolower($type) === 'chapter') {
577             foreach ($entity->pages as $page) {
578                 $this->changeBook('page', $newBookId, $page, false);
579             }
580         }
581
582         // Update permissions if applicable
583         if ($rebuildPermissions) {
584             $entity->load('book');
585             $this->permissionService->buildJointPermissionsForEntity($entity->book);
586         }
587
588         return $entity;
589     }
590
591     /**
592      * Alias method to update the book jointPermissions in the PermissionService.
593      * @param Book $book
594      */
595     public function buildJointPermissionsForBook(Book $book)
596     {
597         $this->permissionService->buildJointPermissionsForEntity($book);
598     }
599
600     /**
601      * Format a name as a url slug.
602      * @param $name
603      * @return string
604      */
605     protected function nameToSlug($name)
606     {
607         $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
608         $slug = preg_replace('/\s{2,}/', ' ', $slug);
609         $slug = str_replace(' ', '-', $slug);
610         if ($slug === "") {
611             $slug = substr(md5(rand(1, 500)), 0, 5);
612         }
613         return $slug;
614     }
615
616     /**
617      * Get a new draft page instance.
618      * @param Book $book
619      * @param Chapter|bool $chapter
620      * @return \BookStack\Entities\Page
621      */
622     public function getDraftPage(Book $book, $chapter = false)
623     {
624         $page = $this->entityProvider->page->newInstance();
625         $page->name = trans('entities.pages_initial_name');
626         $page->created_by = user()->id;
627         $page->updated_by = user()->id;
628         $page->draft = true;
629
630         if ($chapter) {
631             $page->chapter_id = $chapter->id;
632         }
633
634         $book->pages()->save($page);
635         $page = $this->entityProvider->page->find($page->id);
636         $this->permissionService->buildJointPermissionsForEntity($page);
637         return $page;
638     }
639
640     /**
641      * Publish a draft page to make it a normal page.
642      * Sets the slug and updates the content.
643      * @param Page $draftPage
644      * @param array $input
645      * @return Page
646      */
647     public function publishPageDraft(Page $draftPage, array $input)
648     {
649         $draftPage->fill($input);
650
651         // Save page tags if present
652         if (isset($input['tags'])) {
653             $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
654         }
655
656         $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
657         $draftPage->html = $this->formatHtml($input['html']);
658         $draftPage->text = $this->pageToPlainText($draftPage);
659         $draftPage->draft = false;
660         $draftPage->revision_count = 1;
661
662         $draftPage->save();
663         $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
664         $this->searchService->indexEntity($draftPage);
665         return $draftPage;
666     }
667
668     /**
669      * Create a copy of a page in a new location with a new name.
670      * @param \BookStack\Entities\Page $page
671      * @param \BookStack\Entities\Entity $newParent
672      * @param string $newName
673      * @return \BookStack\Entities\Page
674      */
675     public function copyPage(Page $page, Entity $newParent, $newName = '')
676     {
677         $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
678         $newChapter = $newParent->isA('chapter') ? $newParent : null;
679         $copyPage = $this->getDraftPage($newBook, $newChapter);
680         $pageData = $page->getAttributes();
681
682         // Update name
683         if (!empty($newName)) {
684             $pageData['name'] = $newName;
685         }
686
687         // Copy tags from previous page if set
688         if ($page->tags) {
689             $pageData['tags'] = [];
690             foreach ($page->tags as $tag) {
691                 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
692             }
693         }
694
695         // Set priority
696         if ($newParent->isA('chapter')) {
697             $pageData['priority'] = $this->getNewChapterPriority($newParent);
698         } else {
699             $pageData['priority'] = $this->getNewBookPriority($newParent);
700         }
701
702         return $this->publishPageDraft($copyPage, $pageData);
703     }
704
705     /**
706      * Saves a page revision into the system.
707      * @param Page $page
708      * @param null|string $summary
709      * @return \BookStack\Entities\PageRevision
710      */
711     public function savePageRevision(Page $page, $summary = null)
712     {
713         $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
714         if (setting('app-editor') !== 'markdown') {
715             $revision->markdown = '';
716         }
717         $revision->page_id = $page->id;
718         $revision->slug = $page->slug;
719         $revision->book_slug = $page->book->slug;
720         $revision->created_by = user()->id;
721         $revision->created_at = $page->updated_at;
722         $revision->type = 'version';
723         $revision->summary = $summary;
724         $revision->revision_number = $page->revision_count;
725         $revision->save();
726
727         $revisionLimit = config('app.revision_limit');
728         if ($revisionLimit !== false) {
729             $revisionsToDelete = $this->entityProvider->pageRevision->where('page_id', '=', $page->id)
730                 ->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
731             if ($revisionsToDelete->count() > 0) {
732                 $this->entityProvider->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
733             }
734         }
735
736         return $revision;
737     }
738
739     /**
740      * Formats a page's html to be tagged correctly
741      * within the system.
742      * @param string $htmlText
743      * @return string
744      */
745     protected function formatHtml($htmlText)
746     {
747         if ($htmlText == '') {
748             return $htmlText;
749         }
750         libxml_use_internal_errors(true);
751         $doc = new DOMDocument();
752         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
753
754         $container = $doc->documentElement;
755         $body = $container->childNodes->item(0);
756         $childNodes = $body->childNodes;
757
758         // Ensure no duplicate ids are used
759         $idArray = [];
760
761         foreach ($childNodes as $index => $childNode) {
762             /** @var \DOMElement $childNode */
763             if (get_class($childNode) !== 'DOMElement') {
764                 continue;
765             }
766
767             // Overwrite id if not a BookStack custom id
768             if ($childNode->hasAttribute('id')) {
769                 $id = $childNode->getAttribute('id');
770                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
771                     $idArray[] = $id;
772                     continue;
773                 };
774             }
775
776             // Create an unique id for the element
777             // Uses the content as a basis to ensure output is the same every time
778             // the same content is passed through.
779             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
780             $newId = urlencode($contentId);
781             $loopIndex = 0;
782             while (in_array($newId, $idArray)) {
783                 $newId = urlencode($contentId . '-' . $loopIndex);
784                 $loopIndex++;
785             }
786
787             $childNode->setAttribute('id', $newId);
788             $idArray[] = $newId;
789         }
790
791         // Generate inner html as a string
792         $html = '';
793         foreach ($childNodes as $childNode) {
794             $html .= $doc->saveHTML($childNode);
795         }
796
797         return $html;
798     }
799
800
801     /**
802      * Render the page for viewing, Parsing and performing features such as page transclusion.
803      * @param Page $page
804      * @param bool $ignorePermissions
805      * @return mixed|string
806      */
807     public function renderPage(Page $page, $ignorePermissions = false)
808     {
809         $content = $page->html;
810         if (!config('app.allow_content_scripts')) {
811             $content = $this->escapeScripts($content);
812         }
813
814         $matches = [];
815         preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
816         if (count($matches[0]) === 0) {
817             return $content;
818         }
819
820         $topLevelTags = ['table', 'ul', 'ol'];
821         foreach ($matches[1] as $index => $includeId) {
822             $splitInclude = explode('#', $includeId, 2);
823             $pageId = intval($splitInclude[0]);
824             if (is_nan($pageId)) {
825                 continue;
826             }
827
828             $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
829             if ($matchedPage === null) {
830                 $content = str_replace($matches[0][$index], '', $content);
831                 continue;
832             }
833
834             if (count($splitInclude) === 1) {
835                 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
836                 continue;
837             }
838
839             $doc = new DOMDocument();
840             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
841             $matchingElem = $doc->getElementById($splitInclude[1]);
842             if ($matchingElem === null) {
843                 $content = str_replace($matches[0][$index], '', $content);
844                 continue;
845             }
846             $innerContent = '';
847             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
848             if ($isTopLevel) {
849                 $innerContent .= $doc->saveHTML($matchingElem);
850             } else {
851                 foreach ($matchingElem->childNodes as $childNode) {
852                     $innerContent .= $doc->saveHTML($childNode);
853                 }
854             }
855             $content = str_replace($matches[0][$index], trim($innerContent), $content);
856         }
857
858         return $content;
859     }
860
861     /**
862      * Escape script tags within HTML content.
863      * @param string $html
864      * @return mixed
865      */
866     protected function escapeScripts(string $html)
867     {
868         $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
869         $matches = [];
870         preg_match_all($scriptSearchRegex, $html, $matches);
871         if (count($matches) === 0) {
872             return $html;
873         }
874
875         foreach ($matches[0] as $match) {
876             $html = str_replace($match, htmlentities($match), $html);
877         }
878         return $html;
879     }
880
881     /**
882      * Get the plain text version of a page's content.
883      * @param \BookStack\Entities\Page $page
884      * @return string
885      */
886     public function pageToPlainText(Page $page)
887     {
888         $html = $this->renderPage($page);
889         return strip_tags($html);
890     }
891
892     /**
893      * Search for image usage within page content.
894      * @param $imageString
895      * @return mixed
896      */
897     public function searchForImage($imageString)
898     {
899         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
900         foreach ($pages as $page) {
901             $page->url = $page->getUrl();
902             $page->html = '';
903             $page->text = '';
904         }
905         return count($pages) > 0 ? $pages : false;
906     }
907
908     /**
909      * Parse the headers on the page to get a navigation menu
910      * @param String $pageContent
911      * @return array
912      */
913     public function getPageNav($pageContent)
914     {
915         if ($pageContent == '') {
916             return [];
917         }
918         libxml_use_internal_errors(true);
919         $doc = new DOMDocument();
920         $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
921         $xPath = new DOMXPath($doc);
922         $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
923
924         if (is_null($headers)) {
925             return [];
926         }
927
928         $tree = collect([]);
929         foreach ($headers as $header) {
930             $text = $header->nodeValue;
931             $tree->push([
932                 'nodeName' => strtolower($header->nodeName),
933                 'level' => intval(str_replace('h', '', $header->nodeName)),
934                 'link' => '#' . $header->getAttribute('id'),
935                 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
936             ]);
937         }
938
939         // Normalise headers if only smaller headers have been used
940         if (count($tree) > 0) {
941             $minLevel = $tree->pluck('level')->min();
942             $tree = $tree->map(function ($header) use ($minLevel) {
943                 $header['level'] -= ($minLevel - 2);
944                 return $header;
945             });
946         }
947         return $tree->toArray();
948     }
949
950     /**
951      * Updates a page with any fillable data and saves it into the database.
952      * @param \BookStack\Entities\Page $page
953      * @param int $book_id
954      * @param array $input
955      * @return \BookStack\Entities\Page
956      */
957     public function updatePage(Page $page, $book_id, $input)
958     {
959         // Hold the old details to compare later
960         $oldHtml = $page->html;
961         $oldName = $page->name;
962
963         // Prevent slug being updated if no name change
964         if ($page->name !== $input['name']) {
965             $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
966         }
967
968         // Save page tags if present
969         if (isset($input['tags'])) {
970             $this->tagRepo->saveTagsToEntity($page, $input['tags']);
971         }
972
973         // Update with new details
974         $userId = user()->id;
975         $page->fill($input);
976         $page->html = $this->formatHtml($input['html']);
977         $page->text = $this->pageToPlainText($page);
978         if (setting('app-editor') !== 'markdown') {
979             $page->markdown = '';
980         }
981         $page->updated_by = $userId;
982         $page->revision_count++;
983         $page->save();
984
985         // Remove all update drafts for this user & page.
986         $this->userUpdatePageDraftsQuery($page, $userId)->delete();
987
988         // Save a revision after updating
989         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
990             $this->savePageRevision($page, $input['summary']);
991         }
992
993         $this->searchService->indexEntity($page);
994
995         return $page;
996     }
997
998     /**
999      * The base query for getting user update drafts.
1000      * @param \BookStack\Entities\Page $page
1001      * @param $userId
1002      * @return mixed
1003      */
1004     protected function userUpdatePageDraftsQuery(Page $page, $userId)
1005     {
1006         return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
1007             ->where('type', 'update_draft')
1008             ->where('page_id', '=', $page->id)
1009             ->orderBy('created_at', 'desc');
1010     }
1011
1012     /**
1013      * Checks whether a user has a draft version of a particular page or not.
1014      * @param \BookStack\Entities\Page $page
1015      * @param $userId
1016      * @return bool
1017      */
1018     public function hasUserGotPageDraft(Page $page, $userId)
1019     {
1020         return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
1021     }
1022
1023     /**
1024      * Get the latest updated draft revision for a particular page and user.
1025      * @param Page $page
1026      * @param $userId
1027      * @return mixed
1028      */
1029     public function getUserPageDraft(Page $page, $userId)
1030     {
1031         return $this->userUpdatePageDraftsQuery($page, $userId)->first();
1032     }
1033
1034     /**
1035      * Get the notification message that informs the user that they are editing a draft page.
1036      * @param PageRevision $draft
1037      * @return string
1038      */
1039     public function getUserPageDraftMessage(PageRevision $draft)
1040     {
1041         $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
1042         if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
1043             return $message;
1044         }
1045         return $message . "\n" . trans('entities.pages_draft_edited_notification');
1046     }
1047
1048     /**
1049      * Check if a page is being actively editing.
1050      * Checks for edits since last page updated.
1051      * Passing in a minuted range will check for edits
1052      * within the last x minutes.
1053      * @param \BookStack\Entities\Page $page
1054      * @param null $minRange
1055      * @return bool
1056      */
1057     public function isPageEditingActive(Page $page, $minRange = null)
1058     {
1059         $draftSearch = $this->activePageEditingQuery($page, $minRange);
1060         return $draftSearch->count() > 0;
1061     }
1062
1063     /**
1064      * A query to check for active update drafts on a particular page.
1065      * @param Page $page
1066      * @param null $minRange
1067      * @return mixed
1068      */
1069     protected function activePageEditingQuery(Page $page, $minRange = null)
1070     {
1071         $query = $this->entityProvider->pageRevision->where('type', '=', 'update_draft')
1072             ->where('page_id', '=', $page->id)
1073             ->where('updated_at', '>', $page->updated_at)
1074             ->where('created_by', '!=', user()->id)
1075             ->with('createdBy');
1076
1077         if ($minRange !== null) {
1078             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1079         }
1080
1081         return $query;
1082     }
1083
1084     /**
1085      * Restores a revision's content back into a page.
1086      * @param Page $page
1087      * @param Book $book
1088      * @param  int $revisionId
1089      * @return \BookStack\Entities\Page
1090      */
1091     public function restorePageRevision(Page $page, Book $book, $revisionId)
1092     {
1093         $page->revision_count++;
1094         $this->savePageRevision($page);
1095         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
1096         $page->fill($revision->toArray());
1097         $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1098         $page->text = $this->pageToPlainText($page);
1099         $page->updated_by = user()->id;
1100         $page->save();
1101         $this->searchService->indexEntity($page);
1102         return $page;
1103     }
1104
1105
1106     /**
1107      * Save a page update draft.
1108      * @param Page $page
1109      * @param array $data
1110      * @return PageRevision|Page
1111      */
1112     public function updatePageDraft(Page $page, $data = [])
1113     {
1114         // If the page itself is a draft simply update that
1115         if ($page->draft) {
1116             $page->fill($data);
1117             if (isset($data['html'])) {
1118                 $page->text = $this->pageToPlainText($page);
1119             }
1120             $page->save();
1121             return $page;
1122         }
1123
1124         // Otherwise save the data to a revision
1125         $userId = user()->id;
1126         $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1127
1128         if ($drafts->count() > 0) {
1129             $draft = $drafts->first();
1130         } else {
1131             $draft = $this->entityProvider->pageRevision->newInstance();
1132             $draft->page_id = $page->id;
1133             $draft->slug = $page->slug;
1134             $draft->book_slug = $page->book->slug;
1135             $draft->created_by = $userId;
1136             $draft->type = 'update_draft';
1137         }
1138
1139         $draft->fill($data);
1140         if (setting('app-editor') !== 'markdown') {
1141             $draft->markdown = '';
1142         }
1143
1144         $draft->save();
1145         return $draft;
1146     }
1147
1148     /**
1149      * Get a notification message concerning the editing activity on a particular page.
1150      * @param Page $page
1151      * @param null $minRange
1152      * @return string
1153      */
1154     public function getPageEditingActiveMessage(Page $page, $minRange = null)
1155     {
1156         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1157
1158         $userMessage = $pageDraftEdits->count() > 1 ? trans('entities.pages_draft_edit_active.start_a', ['count' => $pageDraftEdits->count()]): trans('entities.pages_draft_edit_active.start_b', ['userName' => $pageDraftEdits->first()->createdBy->name]);
1159         $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1160         return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1161     }
1162
1163     /**
1164      * Change the page's parent to the given entity.
1165      * @param \BookStack\Entities\Page $page
1166      * @param \BookStack\Entities\Entity $parent
1167      */
1168     public function changePageParent(Page $page, Entity $parent)
1169     {
1170         $book = $parent->isA('book') ? $parent : $parent->book;
1171         $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1172         $page->save();
1173         if ($page->book->id !== $book->id) {
1174             $page = $this->changeBook('page', $book->id, $page);
1175         }
1176         $page->load('book');
1177         $this->permissionService->buildJointPermissionsForEntity($book);
1178     }
1179
1180     /**
1181      * Destroy a bookshelf instance
1182      * @param \BookStack\Entities\Bookshelf $shelf
1183      * @throws \Throwable
1184      */
1185     public function destroyBookshelf(Bookshelf $shelf)
1186     {
1187         $this->destroyEntityCommonRelations($shelf);
1188         $shelf->delete();
1189     }
1190
1191     /**
1192      * Destroy the provided book and all its child entities.
1193      * @param \BookStack\Entities\Book $book
1194      * @throws NotifyException
1195      * @throws \Throwable
1196      */
1197     public function destroyBook(Book $book)
1198     {
1199         foreach ($book->pages as $page) {
1200             $this->destroyPage($page);
1201         }
1202         foreach ($book->chapters as $chapter) {
1203             $this->destroyChapter($chapter);
1204         }
1205         $this->destroyEntityCommonRelations($book);
1206         $book->delete();
1207     }
1208
1209     /**
1210      * Destroy a chapter and its relations.
1211      * @param \BookStack\Entities\Chapter $chapter
1212      * @throws \Throwable
1213      */
1214     public function destroyChapter(Chapter $chapter)
1215     {
1216         if (count($chapter->pages) > 0) {
1217             foreach ($chapter->pages as $page) {
1218                 $page->chapter_id = 0;
1219                 $page->save();
1220             }
1221         }
1222         $this->destroyEntityCommonRelations($chapter);
1223         $chapter->delete();
1224     }
1225
1226     /**
1227      * Destroy a given page along with its dependencies.
1228      * @param Page $page
1229      * @throws NotifyException
1230      * @throws \Throwable
1231      */
1232     public function destroyPage(Page $page)
1233     {
1234         // Check if set as custom homepage
1235         $customHome = setting('app-homepage', '0:');
1236         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
1237             throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
1238         }
1239
1240         $this->destroyEntityCommonRelations($page);
1241
1242         // Delete Attached Files
1243         $attachmentService = app(AttachmentService::class);
1244         foreach ($page->attachments as $attachment) {
1245             $attachmentService->deleteFile($attachment);
1246         }
1247
1248         $page->delete();
1249     }
1250
1251     /**
1252      * Destroy or handle the common relations connected to an entity.
1253      * @param \BookStack\Entities\Entity $entity
1254      * @throws \Throwable
1255      */
1256     protected function destroyEntityCommonRelations(Entity $entity)
1257     {
1258         \Activity::removeEntity($entity);
1259         $entity->views()->delete();
1260         $entity->permissions()->delete();
1261         $entity->tags()->delete();
1262         $entity->comments()->delete();
1263         $this->permissionService->deleteJointPermissionsForEntity($entity);
1264         $this->searchService->deleteEntityTerms($entity);
1265     }
1266
1267     /**
1268      * Copy the permissions of a bookshelf to all child books.
1269      * Returns the number of books that had permissions updated.
1270      * @param \BookStack\Entities\Bookshelf $bookshelf
1271      * @return int
1272      * @throws \Throwable
1273      */
1274     public function copyBookshelfPermissions(Bookshelf $bookshelf)
1275     {
1276         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
1277         $shelfBooks = $bookshelf->books()->get();
1278         $updatedBookCount = 0;
1279
1280         foreach ($shelfBooks as $book) {
1281             if (!userCan('restrictions-manage', $book)) {
1282                 continue;
1283             }
1284             $book->permissions()->delete();
1285             $book->restricted = $bookshelf->restricted;
1286             $book->permissions()->createMany($shelfPermissions);
1287             $book->save();
1288             $this->permissionService->buildJointPermissionsForEntity($book);
1289             $updatedBookCount++;
1290         }
1291
1292         return $updatedBookCount;
1293     }
1294 }