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