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