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