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