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