]> BookStack Code Mirror - bookstack/blob - app/Repos/EntityRepo.php
Update german translation
[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         $revisionLimit = config('app.revision_limit');
750         if ($revisionLimit !== false) {
751             $revisionsToDelete = $this->pageRevision->where('page_id', '=', $page->id)
752                 ->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
753             if ($revisionsToDelete->count() > 0) {
754                 $this->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
755             }
756         }
757
758         return $revision;
759     }
760
761     /**
762      * Formats a page's html to be tagged correctly
763      * within the system.
764      * @param string $htmlText
765      * @return string
766      */
767     protected function formatHtml($htmlText)
768     {
769         if ($htmlText == '') {
770             return $htmlText;
771         }
772         libxml_use_internal_errors(true);
773         $doc = new DOMDocument();
774         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
775
776         $container = $doc->documentElement;
777         $body = $container->childNodes->item(0);
778         $childNodes = $body->childNodes;
779
780         // Ensure no duplicate ids are used
781         $idArray = [];
782
783         foreach ($childNodes as $index => $childNode) {
784             /** @var \DOMElement $childNode */
785             if (get_class($childNode) !== 'DOMElement') {
786                 continue;
787             }
788
789             // Overwrite id if not a BookStack custom id
790             if ($childNode->hasAttribute('id')) {
791                 $id = $childNode->getAttribute('id');
792                 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
793                     $idArray[] = $id;
794                     continue;
795                 };
796             }
797
798             // Create an unique id for the element
799             // Uses the content as a basis to ensure output is the same every time
800             // the same content is passed through.
801             $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
802             $newId = urlencode($contentId);
803             $loopIndex = 0;
804             while (in_array($newId, $idArray)) {
805                 $newId = urlencode($contentId . '-' . $loopIndex);
806                 $loopIndex++;
807             }
808
809             $childNode->setAttribute('id', $newId);
810             $idArray[] = $newId;
811         }
812
813         // Generate inner html as a string
814         $html = '';
815         foreach ($childNodes as $childNode) {
816             $html .= $doc->saveHTML($childNode);
817         }
818
819         return $html;
820     }
821
822
823     /**
824      * Render the page for viewing, Parsing and performing features such as page transclusion.
825      * @param Page $page
826      * @param bool $ignorePermissions
827      * @return mixed|string
828      */
829     public function renderPage(Page $page, $ignorePermissions = false)
830     {
831         $content = $page->html;
832         if (!config('app.allow_content_scripts')) {
833             $content = $this->escapeScripts($content);
834         }
835
836         $matches = [];
837         preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
838         if (count($matches[0]) === 0) {
839             return $content;
840         }
841
842         $topLevelTags = ['table', 'ul', 'ol'];
843         foreach ($matches[1] as $index => $includeId) {
844             $splitInclude = explode('#', $includeId, 2);
845             $pageId = intval($splitInclude[0]);
846             if (is_nan($pageId)) {
847                 continue;
848             }
849
850             $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
851             if ($matchedPage === null) {
852                 $content = str_replace($matches[0][$index], '', $content);
853                 continue;
854             }
855
856             if (count($splitInclude) === 1) {
857                 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
858                 continue;
859             }
860
861             $doc = new DOMDocument();
862             $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
863             $matchingElem = $doc->getElementById($splitInclude[1]);
864             if ($matchingElem === null) {
865                 $content = str_replace($matches[0][$index], '', $content);
866                 continue;
867             }
868             $innerContent = '';
869             $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
870             if ($isTopLevel) {
871                 $innerContent .= $doc->saveHTML($matchingElem);
872             } else {
873                 foreach ($matchingElem->childNodes as $childNode) {
874                     $innerContent .= $doc->saveHTML($childNode);
875                 }
876             }
877             $content = str_replace($matches[0][$index], trim($innerContent), $content);
878         }
879
880         return $content;
881     }
882
883     /**
884      * Escape script tags within HTML content.
885      * @param string $html
886      * @return mixed
887      */
888     protected function escapeScripts(string $html)
889     {
890         $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
891         $matches = [];
892         preg_match_all($scriptSearchRegex, $html, $matches);
893         if (count($matches) === 0) {
894             return $html;
895         }
896
897         foreach ($matches[0] as $match) {
898             $html = str_replace($match, htmlentities($match), $html);
899         }
900         return $html;
901     }
902
903     /**
904      * Get the plain text version of a page's content.
905      * @param Page $page
906      * @return string
907      */
908     public function pageToPlainText(Page $page)
909     {
910         $html = $this->renderPage($page);
911         return strip_tags($html);
912     }
913
914     /**
915      * Search for image usage within page content.
916      * @param $imageString
917      * @return mixed
918      */
919     public function searchForImage($imageString)
920     {
921         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
922         foreach ($pages as $page) {
923             $page->url = $page->getUrl();
924             $page->html = '';
925             $page->text = '';
926         }
927         return count($pages) > 0 ? $pages : false;
928     }
929
930     /**
931      * Parse the headers on the page to get a navigation menu
932      * @param String $pageContent
933      * @return array
934      */
935     public function getPageNav($pageContent)
936     {
937         if ($pageContent == '') {
938             return [];
939         }
940         libxml_use_internal_errors(true);
941         $doc = new DOMDocument();
942         $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
943         $xPath = new DOMXPath($doc);
944         $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
945
946         if (is_null($headers)) {
947             return [];
948         }
949
950         $tree = collect([]);
951         foreach ($headers as $header) {
952             $text = $header->nodeValue;
953             $tree->push([
954                 'nodeName' => strtolower($header->nodeName),
955                 'level' => intval(str_replace('h', '', $header->nodeName)),
956                 'link' => '#' . $header->getAttribute('id'),
957                 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
958             ]);
959         }
960
961         // Normalise headers if only smaller headers have been used
962         if (count($tree) > 0) {
963             $minLevel = $tree->pluck('level')->min();
964             $tree = $tree->map(function ($header) use ($minLevel) {
965                 $header['level'] -= ($minLevel - 2);
966                 return $header;
967             });
968         }
969         return $tree->toArray();
970     }
971
972     /**
973      * Updates a page with any fillable data and saves it into the database.
974      * @param Page $page
975      * @param int $book_id
976      * @param array $input
977      * @return Page
978      */
979     public function updatePage(Page $page, $book_id, $input)
980     {
981         // Hold the old details to compare later
982         $oldHtml = $page->html;
983         $oldName = $page->name;
984
985         // Prevent slug being updated if no name change
986         if ($page->name !== $input['name']) {
987             $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
988         }
989
990         // Save page tags if present
991         if (isset($input['tags'])) {
992             $this->tagRepo->saveTagsToEntity($page, $input['tags']);
993         }
994
995         // Update with new details
996         $userId = user()->id;
997         $page->fill($input);
998         $page->html = $this->formatHtml($input['html']);
999         $page->text = $this->pageToPlainText($page);
1000         if (setting('app-editor') !== 'markdown') {
1001             $page->markdown = '';
1002         }
1003         $page->updated_by = $userId;
1004         $page->revision_count++;
1005         $page->save();
1006
1007         // Remove all update drafts for this user & page.
1008         $this->userUpdatePageDraftsQuery($page, $userId)->delete();
1009
1010         // Save a revision after updating
1011         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
1012             $this->savePageRevision($page, $input['summary']);
1013         }
1014
1015         $this->searchService->indexEntity($page);
1016
1017         return $page;
1018     }
1019
1020     /**
1021      * The base query for getting user update drafts.
1022      * @param Page $page
1023      * @param $userId
1024      * @return mixed
1025      */
1026     protected function userUpdatePageDraftsQuery(Page $page, $userId)
1027     {
1028         return $this->pageRevision->where('created_by', '=', $userId)
1029             ->where('type', 'update_draft')
1030             ->where('page_id', '=', $page->id)
1031             ->orderBy('created_at', 'desc');
1032     }
1033
1034     /**
1035      * Checks whether a user has a draft version of a particular page or not.
1036      * @param Page $page
1037      * @param $userId
1038      * @return bool
1039      */
1040     public function hasUserGotPageDraft(Page $page, $userId)
1041     {
1042         return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
1043     }
1044
1045     /**
1046      * Get the latest updated draft revision for a particular page and user.
1047      * @param Page $page
1048      * @param $userId
1049      * @return mixed
1050      */
1051     public function getUserPageDraft(Page $page, $userId)
1052     {
1053         return $this->userUpdatePageDraftsQuery($page, $userId)->first();
1054     }
1055
1056     /**
1057      * Get the notification message that informs the user that they are editing a draft page.
1058      * @param PageRevision $draft
1059      * @return string
1060      */
1061     public function getUserPageDraftMessage(PageRevision $draft)
1062     {
1063         $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
1064         if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
1065             return $message;
1066         }
1067         return $message . "\n" . trans('entities.pages_draft_edited_notification');
1068     }
1069
1070     /**
1071      * Check if a page is being actively editing.
1072      * Checks for edits since last page updated.
1073      * Passing in a minuted range will check for edits
1074      * within the last x minutes.
1075      * @param Page $page
1076      * @param null $minRange
1077      * @return bool
1078      */
1079     public function isPageEditingActive(Page $page, $minRange = null)
1080     {
1081         $draftSearch = $this->activePageEditingQuery($page, $minRange);
1082         return $draftSearch->count() > 0;
1083     }
1084
1085     /**
1086      * A query to check for active update drafts on a particular page.
1087      * @param Page $page
1088      * @param null $minRange
1089      * @return mixed
1090      */
1091     protected function activePageEditingQuery(Page $page, $minRange = null)
1092     {
1093         $query = $this->pageRevision->where('type', '=', 'update_draft')
1094             ->where('page_id', '=', $page->id)
1095             ->where('updated_at', '>', $page->updated_at)
1096             ->where('created_by', '!=', user()->id)
1097             ->with('createdBy');
1098
1099         if ($minRange !== null) {
1100             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1101         }
1102
1103         return $query;
1104     }
1105
1106     /**
1107      * Restores a revision's content back into a page.
1108      * @param Page $page
1109      * @param Book $book
1110      * @param  int $revisionId
1111      * @return Page
1112      */
1113     public function restorePageRevision(Page $page, Book $book, $revisionId)
1114     {
1115         $page->revision_count++;
1116         $this->savePageRevision($page);
1117         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
1118         $page->fill($revision->toArray());
1119         $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1120         $page->text = $this->pageToPlainText($page);
1121         $page->updated_by = user()->id;
1122         $page->save();
1123         $this->searchService->indexEntity($page);
1124         return $page;
1125     }
1126
1127
1128     /**
1129      * Save a page update draft.
1130      * @param Page $page
1131      * @param array $data
1132      * @return PageRevision|Page
1133      */
1134     public function updatePageDraft(Page $page, $data = [])
1135     {
1136         // If the page itself is a draft simply update that
1137         if ($page->draft) {
1138             $page->fill($data);
1139             if (isset($data['html'])) {
1140                 $page->text = $this->pageToPlainText($page);
1141             }
1142             $page->save();
1143             return $page;
1144         }
1145
1146         // Otherwise save the data to a revision
1147         $userId = user()->id;
1148         $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1149
1150         if ($drafts->count() > 0) {
1151             $draft = $drafts->first();
1152         } else {
1153             $draft = $this->pageRevision->newInstance();
1154             $draft->page_id = $page->id;
1155             $draft->slug = $page->slug;
1156             $draft->book_slug = $page->book->slug;
1157             $draft->created_by = $userId;
1158             $draft->type = 'update_draft';
1159         }
1160
1161         $draft->fill($data);
1162         if (setting('app-editor') !== 'markdown') {
1163             $draft->markdown = '';
1164         }
1165
1166         $draft->save();
1167         return $draft;
1168     }
1169
1170     /**
1171      * Get a notification message concerning the editing activity on a particular page.
1172      * @param Page $page
1173      * @param null $minRange
1174      * @return string
1175      */
1176     public function getPageEditingActiveMessage(Page $page, $minRange = null)
1177     {
1178         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1179
1180         $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]);
1181         $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1182         return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1183     }
1184
1185     /**
1186      * Change the page's parent to the given entity.
1187      * @param Page $page
1188      * @param Entity $parent
1189      */
1190     public function changePageParent(Page $page, Entity $parent)
1191     {
1192         $book = $parent->isA('book') ? $parent : $parent->book;
1193         $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1194         $page->save();
1195         if ($page->book->id !== $book->id) {
1196             $page = $this->changeBook('page', $book->id, $page);
1197         }
1198         $page->load('book');
1199         $this->permissionService->buildJointPermissionsForEntity($book);
1200     }
1201
1202     /**
1203      * Destroy a bookshelf instance
1204      * @param Bookshelf $shelf
1205      * @throws \Throwable
1206      */
1207     public function destroyBookshelf(Bookshelf $shelf)
1208     {
1209         $this->destroyEntityCommonRelations($shelf);
1210         $shelf->delete();
1211     }
1212
1213     /**
1214      * Destroy the provided book and all its child entities.
1215      * @param Book $book
1216      * @throws NotifyException
1217      * @throws \Throwable
1218      */
1219     public function destroyBook(Book $book)
1220     {
1221         foreach ($book->pages as $page) {
1222             $this->destroyPage($page);
1223         }
1224         foreach ($book->chapters as $chapter) {
1225             $this->destroyChapter($chapter);
1226         }
1227         $this->destroyEntityCommonRelations($book);
1228         $book->delete();
1229     }
1230
1231     /**
1232      * Destroy a chapter and its relations.
1233      * @param Chapter $chapter
1234      * @throws \Throwable
1235      */
1236     public function destroyChapter(Chapter $chapter)
1237     {
1238         if (count($chapter->pages) > 0) {
1239             foreach ($chapter->pages as $page) {
1240                 $page->chapter_id = 0;
1241                 $page->save();
1242             }
1243         }
1244         $this->destroyEntityCommonRelations($chapter);
1245         $chapter->delete();
1246     }
1247
1248     /**
1249      * Destroy a given page along with its dependencies.
1250      * @param Page $page
1251      * @throws NotifyException
1252      * @throws \Throwable
1253      */
1254     public function destroyPage(Page $page)
1255     {
1256         // Check if set as custom homepage
1257         $customHome = setting('app-homepage', '0:');
1258         if (intval($page->id) === intval(explode(':', $customHome)[0])) {
1259             throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
1260         }
1261
1262         $this->destroyEntityCommonRelations($page);
1263
1264         // Delete Attached Files
1265         $attachmentService = app(AttachmentService::class);
1266         foreach ($page->attachments as $attachment) {
1267             $attachmentService->deleteFile($attachment);
1268         }
1269
1270         $page->delete();
1271     }
1272
1273     /**
1274      * Destroy or handle the common relations connected to an entity.
1275      * @param Entity $entity
1276      * @throws \Throwable
1277      */
1278     protected function destroyEntityCommonRelations(Entity $entity)
1279     {
1280         \Activity::removeEntity($entity);
1281         $entity->views()->delete();
1282         $entity->permissions()->delete();
1283         $entity->tags()->delete();
1284         $entity->comments()->delete();
1285         $this->permissionService->deleteJointPermissionsForEntity($entity);
1286         $this->searchService->deleteEntityTerms($entity);
1287     }
1288
1289     /**
1290      * Copy the permissions of a bookshelf to all child books.
1291      * Returns the number of books that had permissions updated.
1292      * @param Bookshelf $bookshelf
1293      * @return int
1294      * @throws \Throwable
1295      */
1296     public function copyBookshelfPermissions(Bookshelf $bookshelf)
1297     {
1298         $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
1299         $shelfBooks = $bookshelf->books()->get();
1300         $updatedBookCount = 0;
1301
1302         foreach ($shelfBooks as $book) {
1303             if (!userCan('restrictions-manage', $book)) {
1304                 continue;
1305             }
1306             $book->permissions()->delete();
1307             $book->restricted = $bookshelf->restricted;
1308             $book->permissions()->createMany($shelfPermissions);
1309             $book->save();
1310             $this->permissionService->buildJointPermissionsForEntity($book);
1311             $updatedBookCount++;
1312         }
1313
1314         return $updatedBookCount;
1315     }
1316 }