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