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