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