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