]> BookStack Code Mirror - bookstack/blob - app/Repos/EntityRepo.php
Brazilian Portuguese Localization
[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)->findOrFail($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) $tree[] = $entities[$index];
336             $entities[$index]->book = $book;
337         }
338
339         foreach ($entities as $entity) {
340             if ($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      * Get a new draft page instance.
801      * @param Book $book
802      * @param Chapter|bool $chapter
803      * @return Page
804      */
805     public function getDraftPage(Book $book, $chapter = false)
806     {
807         $page = $this->page->newInstance();
808         $page->name = trans('entities.pages_initial_name');
809         $page->created_by = user()->id;
810         $page->updated_by = user()->id;
811         $page->draft = true;
812
813         if ($chapter) $page->chapter_id = $chapter->id;
814
815         $book->pages()->save($page);
816         $this->permissionService->buildJointPermissionsForEntity($page);
817         return $page;
818     }
819
820     /**
821      * Search for image usage within page content.
822      * @param $imageString
823      * @return mixed
824      */
825     public function searchForImage($imageString)
826     {
827         $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
828         foreach ($pages as $page) {
829             $page->url = $page->getUrl();
830             $page->html = '';
831             $page->text = '';
832         }
833         return count($pages) > 0 ? $pages : false;
834     }
835
836     /**
837      * Parse the headers on the page to get a navigation menu
838      * @param Page $page
839      * @return array
840      */
841     public function getPageNav(Page $page)
842     {
843         if ($page->html == '') return [];
844         libxml_use_internal_errors(true);
845         $doc = new DOMDocument();
846         $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8'));
847         $xPath = new DOMXPath($doc);
848         $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
849
850         if (is_null($headers)) return [];
851
852         $tree = collect([]);
853         foreach ($headers as $header) {
854             $text = $header->nodeValue;
855             $tree->push([
856                 'nodeName' => strtolower($header->nodeName),
857                 'level' => intval(str_replace('h', '', $header->nodeName)),
858                 'link' => '#' . $header->getAttribute('id'),
859                 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
860             ]);
861         }
862
863         // Normalise headers if only smaller headers have been used
864         if (count($tree) > 0) {
865             $minLevel = $tree->pluck('level')->min();
866             $tree = $tree->map(function($header) use ($minLevel) {
867                 $header['level'] -= ($minLevel - 2);
868                 return $header;
869             });
870         }
871         return $tree->toArray();
872     }
873
874     /**
875      * Updates a page with any fillable data and saves it into the database.
876      * @param Page $page
877      * @param int $book_id
878      * @param array $input
879      * @return Page
880      */
881     public function updatePage(Page $page, $book_id, $input)
882     {
883         // Hold the old details to compare later
884         $oldHtml = $page->html;
885         $oldName = $page->name;
886
887         // Prevent slug being updated if no name change
888         if ($page->name !== $input['name']) {
889             $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
890         }
891
892         // Save page tags if present
893         if (isset($input['tags'])) {
894             $this->tagRepo->saveTagsToEntity($page, $input['tags']);
895         }
896
897         // Update with new details
898         $userId = user()->id;
899         $page->fill($input);
900         $page->html = $this->formatHtml($input['html']);
901         $page->text = strip_tags($page->html);
902         if (setting('app-editor') !== 'markdown') $page->markdown = '';
903         $page->updated_by = $userId;
904         $page->save();
905
906         // Remove all update drafts for this user & page.
907         $this->userUpdatePageDraftsQuery($page, $userId)->delete();
908
909         // Save a revision after updating
910         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
911             $this->savePageRevision($page, $input['summary']);
912         }
913
914         return $page;
915     }
916
917     /**
918      * The base query for getting user update drafts.
919      * @param Page $page
920      * @param $userId
921      * @return mixed
922      */
923     protected function userUpdatePageDraftsQuery(Page $page, $userId)
924     {
925         return $this->pageRevision->where('created_by', '=', $userId)
926             ->where('type', 'update_draft')
927             ->where('page_id', '=', $page->id)
928             ->orderBy('created_at', 'desc');
929     }
930
931     /**
932      * Checks whether a user has a draft version of a particular page or not.
933      * @param Page $page
934      * @param $userId
935      * @return bool
936      */
937     public function hasUserGotPageDraft(Page $page, $userId)
938     {
939         return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
940     }
941
942     /**
943      * Get the latest updated draft revision for a particular page and user.
944      * @param Page $page
945      * @param $userId
946      * @return mixed
947      */
948     public function getUserPageDraft(Page $page, $userId)
949     {
950         return $this->userUpdatePageDraftsQuery($page, $userId)->first();
951     }
952
953     /**
954      * Get the notification message that informs the user that they are editing a draft page.
955      * @param PageRevision $draft
956      * @return string
957      */
958     public function getUserPageDraftMessage(PageRevision $draft)
959     {
960         $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
961         if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
962         return $message . "\n" . trans('entities.pages_draft_edited_notification');
963     }
964
965     /**
966      * Check if a page is being actively editing.
967      * Checks for edits since last page updated.
968      * Passing in a minuted range will check for edits
969      * within the last x minutes.
970      * @param Page $page
971      * @param null $minRange
972      * @return bool
973      */
974     public function isPageEditingActive(Page $page, $minRange = null)
975     {
976         $draftSearch = $this->activePageEditingQuery($page, $minRange);
977         return $draftSearch->count() > 0;
978     }
979
980     /**
981      * A query to check for active update drafts on a particular page.
982      * @param Page $page
983      * @param null $minRange
984      * @return mixed
985      */
986     protected function activePageEditingQuery(Page $page, $minRange = null)
987     {
988         $query = $this->pageRevision->where('type', '=', 'update_draft')
989             ->where('page_id', '=', $page->id)
990             ->where('updated_at', '>', $page->updated_at)
991             ->where('created_by', '!=', user()->id)
992             ->with('createdBy');
993
994         if ($minRange !== null) {
995             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
996         }
997
998         return $query;
999     }
1000
1001     /**
1002      * Restores a revision's content back into a page.
1003      * @param Page $page
1004      * @param Book $book
1005      * @param  int $revisionId
1006      * @return Page
1007      */
1008     public function restorePageRevision(Page $page, Book $book, $revisionId)
1009     {
1010         $this->savePageRevision($page);
1011         $revision = $this->getById('page_revision', $revisionId);
1012         $page->fill($revision->toArray());
1013         $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1014         $page->text = strip_tags($page->html);
1015         $page->updated_by = user()->id;
1016         $page->save();
1017         return $page;
1018     }
1019
1020
1021     /**
1022      * Save a page update draft.
1023      * @param Page $page
1024      * @param array $data
1025      * @return PageRevision|Page
1026      */
1027     public function updatePageDraft(Page $page, $data = [])
1028     {
1029         // If the page itself is a draft simply update that
1030         if ($page->draft) {
1031             $page->fill($data);
1032             if (isset($data['html'])) {
1033                 $page->text = strip_tags($data['html']);
1034             }
1035             $page->save();
1036             return $page;
1037         }
1038
1039         // Otherwise save the data to a revision
1040         $userId = user()->id;
1041         $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1042
1043         if ($drafts->count() > 0) {
1044             $draft = $drafts->first();
1045         } else {
1046             $draft = $this->pageRevision->newInstance();
1047             $draft->page_id = $page->id;
1048             $draft->slug = $page->slug;
1049             $draft->book_slug = $page->book->slug;
1050             $draft->created_by = $userId;
1051             $draft->type = 'update_draft';
1052         }
1053
1054         $draft->fill($data);
1055         if (setting('app-editor') !== 'markdown') $draft->markdown = '';
1056
1057         $draft->save();
1058         return $draft;
1059     }
1060
1061     /**
1062      * Get a notification message concerning the editing activity on a particular page.
1063      * @param Page $page
1064      * @param null $minRange
1065      * @return string
1066      */
1067     public function getPageEditingActiveMessage(Page $page, $minRange = null)
1068     {
1069         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1070
1071         $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]);
1072         $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1073         return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1074     }
1075
1076     /**
1077      * Change the page's parent to the given entity.
1078      * @param Page $page
1079      * @param Entity $parent
1080      */
1081     public function changePageParent(Page $page, Entity $parent)
1082     {
1083         $book = $parent->isA('book') ? $parent : $parent->book;
1084         $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1085         $page->save();
1086         if ($page->book->id !== $book->id) {
1087             $page = $this->changeBook('page', $book->id, $page);
1088         }
1089         $page->load('book');
1090         $this->permissionService->buildJointPermissionsForEntity($book);
1091     }
1092
1093     /**
1094      * Destroy the provided book and all its child entities.
1095      * @param Book $book
1096      */
1097     public function destroyBook(Book $book)
1098     {
1099         foreach ($book->pages as $page) {
1100             $this->destroyPage($page);
1101         }
1102         foreach ($book->chapters as $chapter) {
1103             $this->destroyChapter($chapter);
1104         }
1105         \Activity::removeEntity($book);
1106         $book->views()->delete();
1107         $book->permissions()->delete();
1108         $this->permissionService->deleteJointPermissionsForEntity($book);
1109         $book->delete();
1110     }
1111
1112     /**
1113      * Destroy a chapter and its relations.
1114      * @param Chapter $chapter
1115      */
1116     public function destroyChapter(Chapter $chapter)
1117     {
1118         if (count($chapter->pages) > 0) {
1119             foreach ($chapter->pages as $page) {
1120                 $page->chapter_id = 0;
1121                 $page->save();
1122             }
1123         }
1124         \Activity::removeEntity($chapter);
1125         $chapter->views()->delete();
1126         $chapter->permissions()->delete();
1127         $this->permissionService->deleteJointPermissionsForEntity($chapter);
1128         $chapter->delete();
1129     }
1130
1131     /**
1132      * Destroy a given page along with its dependencies.
1133      * @param Page $page
1134      */
1135     public function destroyPage(Page $page)
1136     {
1137         \Activity::removeEntity($page);
1138         $page->views()->delete();
1139         $page->tags()->delete();
1140         $page->revisions()->delete();
1141         $page->permissions()->delete();
1142         $this->permissionService->deleteJointPermissionsForEntity($page);
1143
1144         // Delete Attached Files
1145         $attachmentService = app(AttachmentService::class);
1146         foreach ($page->attachments as $attachment) {
1147             $attachmentService->deleteFile($attachment);
1148         }
1149
1150         $page->delete();
1151     }
1152
1153 }
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165