]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Started implementation of page template
[bookstack] / app / Entities / Repos / PageRepo.php
1 <?php namespace BookStack\Entities\Repos;
2
3 use BookStack\Entities\Book;
4 use BookStack\Entities\Chapter;
5 use BookStack\Entities\Entity;
6 use BookStack\Entities\Page;
7 use BookStack\Entities\PageRevision;
8 use Carbon\Carbon;
9 use DOMDocument;
10 use DOMElement;
11 use DOMXPath;
12
13 class PageRepo extends EntityRepo
14 {
15
16     /**
17      * Get page by slug.
18      * @param string $pageSlug
19      * @param string $bookSlug
20      * @return Page
21      * @throws \BookStack\Exceptions\NotFoundException
22      */
23     public function getPageBySlug(string $pageSlug, string $bookSlug)
24     {
25         return $this->getBySlug('page', $pageSlug, $bookSlug);
26     }
27
28     /**
29      * Search through page revisions and retrieve the last page in the
30      * current book that has a slug equal to the one given.
31      * @param string $pageSlug
32      * @param string $bookSlug
33      * @return null|Page
34      */
35     public function getPageByOldSlug(string $pageSlug, string $bookSlug)
36     {
37         $revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
38             ->whereHas('page', function ($query) {
39                 $this->permissionService->enforceEntityRestrictions('page', $query);
40             })
41             ->where('type', '=', 'version')
42             ->where('book_slug', '=', $bookSlug)
43             ->orderBy('created_at', 'desc')
44             ->with('page')->first();
45         return $revision !== null ? $revision->page : null;
46     }
47
48     /**
49      * Updates a page with any fillable data and saves it into the database.
50      * @param Page $page
51      * @param int $book_id
52      * @param array $input
53      * @return Page
54      * @throws \Exception
55      */
56     public function updatePage(Page $page, int $book_id, array $input)
57     {
58         // Hold the old details to compare later
59         $oldHtml = $page->html;
60         $oldName = $page->name;
61
62         // Prevent slug being updated if no name change
63         if ($page->name !== $input['name']) {
64             $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
65         }
66
67         // Save page tags if present
68         if (isset($input['tags'])) {
69             $this->tagRepo->saveTagsToEntity($page, $input['tags']);
70         }
71
72         if (isset($input['template']) && userCan('templates-manage')) {
73             $page->template = ($input['template'] === 'true');
74         }
75
76         // Update with new details
77         $userId = user()->id;
78         $page->fill($input);
79         $page->html = $this->formatHtml($input['html']);
80         $page->text = $this->pageToPlainText($page);
81         if (setting('app-editor') !== 'markdown') {
82             $page->markdown = '';
83         }
84         $page->updated_by = $userId;
85         $page->revision_count++;
86         $page->save();
87
88         // Remove all update drafts for this user & page.
89         $this->userUpdatePageDraftsQuery($page, $userId)->delete();
90
91         // Save a revision after updating
92         $summary = $input['summary'] ?? null;
93         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
94             $this->savePageRevision($page, $summary);
95         }
96
97         $this->searchService->indexEntity($page);
98
99         return $page;
100     }
101
102     /**
103      * Saves a page revision into the system.
104      * @param Page $page
105      * @param null|string $summary
106      * @return PageRevision
107      * @throws \Exception
108      */
109     public function savePageRevision(Page $page, string $summary = null)
110     {
111         $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
112         if (setting('app-editor') !== 'markdown') {
113             $revision->markdown = '';
114         }
115         $revision->page_id = $page->id;
116         $revision->slug = $page->slug;
117         $revision->book_slug = $page->book->slug;
118         $revision->created_by = user()->id;
119         $revision->created_at = $page->updated_at;
120         $revision->type = 'version';
121         $revision->summary = $summary;
122         $revision->revision_number = $page->revision_count;
123         $revision->save();
124
125         $revisionLimit = config('app.revision_limit');
126         if ($revisionLimit !== false) {
127             $revisionsToDelete = $this->entityProvider->pageRevision->where('page_id', '=', $page->id)
128                 ->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
129             if ($revisionsToDelete->count() > 0) {
130                 $this->entityProvider->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
131             }
132         }
133
134         return $revision;
135     }
136
137     /**
138      * Formats a page's html to be tagged correctly within the system.
139      * @param string $htmlText
140      * @return string
141      */
142     protected function formatHtml(string $htmlText)
143     {
144         if ($htmlText == '') {
145             return $htmlText;
146         }
147
148         libxml_use_internal_errors(true);
149         $doc = new DOMDocument();
150         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
151
152         $container = $doc->documentElement;
153         $body = $container->childNodes->item(0);
154         $childNodes = $body->childNodes;
155
156         // Set ids on top-level nodes
157         $idMap = [];
158         foreach ($childNodes as $index => $childNode) {
159             $this->setUniqueId($childNode, $idMap);
160         }
161
162         // Ensure no duplicate ids within child items
163         $xPath = new DOMXPath($doc);
164         $idElems = $xPath->query('//body//*//*[@id]');
165         foreach ($idElems as $domElem) {
166             $this->setUniqueId($domElem, $idMap);
167         }
168
169         // Generate inner html as a string
170         $html = '';
171         foreach ($childNodes as $childNode) {
172             $html .= $doc->saveHTML($childNode);
173         }
174
175         return $html;
176     }
177
178     /**
179      * Set a unique id on the given DOMElement.
180      * A map for existing ID's should be passed in to check for current existence.
181      * @param DOMElement $element
182      * @param array $idMap
183      */
184     protected function setUniqueId($element, array &$idMap)
185     {
186         if (get_class($element) !== 'DOMElement') {
187             return;
188         }
189
190         // Overwrite id if not a BookStack custom id
191         $existingId = $element->getAttribute('id');
192         if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
193             $idMap[$existingId] = true;
194             return;
195         }
196
197         // Create an unique id for the element
198         // Uses the content as a basis to ensure output is the same every time
199         // the same content is passed through.
200         $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
201         $newId = urlencode($contentId);
202         $loopIndex = 0;
203
204         while (isset($idMap[$newId])) {
205             $newId = urlencode($contentId . '-' . $loopIndex);
206             $loopIndex++;
207         }
208
209         $element->setAttribute('id', $newId);
210         $idMap[$newId] = true;
211     }
212
213     /**
214      * Get the plain text version of a page's content.
215      * @param \BookStack\Entities\Page $page
216      * @return string
217      */
218     protected function pageToPlainText(Page $page) : string
219     {
220         $html = $this->renderPage($page, true);
221         return strip_tags($html);
222     }
223
224     /**
225      * Get a new draft page instance.
226      * @param Book $book
227      * @param Chapter|null $chapter
228      * @return \BookStack\Entities\Page
229      * @throws \Throwable
230      */
231     public function getDraftPage(Book $book, Chapter $chapter = null)
232     {
233         $page = $this->entityProvider->page->newInstance();
234         $page->name = trans('entities.pages_initial_name');
235         $page->created_by = user()->id;
236         $page->updated_by = user()->id;
237         $page->draft = true;
238
239         if ($chapter) {
240             $page->chapter_id = $chapter->id;
241         }
242
243         $book->pages()->save($page);
244         $page = $this->entityProvider->page->find($page->id);
245         $this->permissionService->buildJointPermissionsForEntity($page);
246         return $page;
247     }
248
249     /**
250      * Save a page update draft.
251      * @param Page $page
252      * @param array $data
253      * @return PageRevision|Page
254      */
255     public function updatePageDraft(Page $page, array $data = [])
256     {
257         // If the page itself is a draft simply update that
258         if ($page->draft) {
259             $page->fill($data);
260             if (isset($data['html'])) {
261                 $page->text = $this->pageToPlainText($page);
262             }
263             $page->save();
264             return $page;
265         }
266
267         // Otherwise save the data to a revision
268         $userId = user()->id;
269         $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
270
271         if ($drafts->count() > 0) {
272             $draft = $drafts->first();
273         } else {
274             $draft = $this->entityProvider->pageRevision->newInstance();
275             $draft->page_id = $page->id;
276             $draft->slug = $page->slug;
277             $draft->book_slug = $page->book->slug;
278             $draft->created_by = $userId;
279             $draft->type = 'update_draft';
280         }
281
282         $draft->fill($data);
283         if (setting('app-editor') !== 'markdown') {
284             $draft->markdown = '';
285         }
286
287         $draft->save();
288         return $draft;
289     }
290
291     /**
292      * Publish a draft page to make it a normal page.
293      * Sets the slug and updates the content.
294      * @param Page $draftPage
295      * @param array $input
296      * @return Page
297      * @throws \Exception
298      */
299     public function publishPageDraft(Page $draftPage, array $input)
300     {
301         $draftPage->fill($input);
302
303         // Save page tags if present
304         if (isset($input['tags'])) {
305             $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
306         }
307
308         if (isset($input['template']) && userCan('templates-manage')) {
309             $draftPage->template = ($input['template'] === 'true');
310         }
311
312         $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
313         $draftPage->html = $this->formatHtml($input['html']);
314         $draftPage->text = $this->pageToPlainText($draftPage);
315         $draftPage->draft = false;
316         $draftPage->revision_count = 1;
317
318         $draftPage->save();
319         $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
320         $this->searchService->indexEntity($draftPage);
321         return $draftPage;
322     }
323
324     /**
325      * The base query for getting user update drafts.
326      * @param Page $page
327      * @param $userId
328      * @return mixed
329      */
330     protected function userUpdatePageDraftsQuery(Page $page, int $userId)
331     {
332         return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
333             ->where('type', 'update_draft')
334             ->where('page_id', '=', $page->id)
335             ->orderBy('created_at', 'desc');
336     }
337
338     /**
339      * Get the latest updated draft revision for a particular page and user.
340      * @param Page $page
341      * @param $userId
342      * @return PageRevision|null
343      */
344     public function getUserPageDraft(Page $page, int $userId)
345     {
346         return $this->userUpdatePageDraftsQuery($page, $userId)->first();
347     }
348
349     /**
350      * Get the notification message that informs the user that they are editing a draft page.
351      * @param PageRevision $draft
352      * @return string
353      */
354     public function getUserPageDraftMessage(PageRevision $draft)
355     {
356         $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
357         if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
358             return $message;
359         }
360         return $message . "\n" . trans('entities.pages_draft_edited_notification');
361     }
362
363     /**
364      * A query to check for active update drafts on a particular page.
365      * @param Page $page
366      * @param int $minRange
367      * @return mixed
368      */
369     protected function activePageEditingQuery(Page $page, int $minRange = null)
370     {
371         $query = $this->entityProvider->pageRevision->where('type', '=', 'update_draft')
372             ->where('page_id', '=', $page->id)
373             ->where('updated_at', '>', $page->updated_at)
374             ->where('created_by', '!=', user()->id)
375             ->with('createdBy');
376
377         if ($minRange !== null) {
378             $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
379         }
380
381         return $query;
382     }
383
384     /**
385      * Check if a page is being actively editing.
386      * Checks for edits since last page updated.
387      * Passing in a minuted range will check for edits
388      * within the last x minutes.
389      * @param Page $page
390      * @param int $minRange
391      * @return bool
392      */
393     public function isPageEditingActive(Page $page, int $minRange = null)
394     {
395         $draftSearch = $this->activePageEditingQuery($page, $minRange);
396         return $draftSearch->count() > 0;
397     }
398
399     /**
400      * Get a notification message concerning the editing activity on a particular page.
401      * @param Page $page
402      * @param int $minRange
403      * @return string
404      */
405     public function getPageEditingActiveMessage(Page $page, int $minRange = null)
406     {
407         $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
408
409         $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]);
410         $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
411         return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
412     }
413
414     /**
415      * Parse the headers on the page to get a navigation menu
416      * @param string $pageContent
417      * @return array
418      */
419     public function getPageNav(string $pageContent)
420     {
421         if ($pageContent == '') {
422             return [];
423         }
424         libxml_use_internal_errors(true);
425         $doc = new DOMDocument();
426         $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
427         $xPath = new DOMXPath($doc);
428         $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
429
430         if (is_null($headers)) {
431             return [];
432         }
433
434         $tree = collect($headers)->map(function($header) {
435             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
436             $text = mb_substr($text, 0, 100);
437
438             return [
439                 'nodeName' => strtolower($header->nodeName),
440                 'level' => intval(str_replace('h', '', $header->nodeName)),
441                 'link' => '#' . $header->getAttribute('id'),
442                 'text' => $text,
443             ];
444         })->filter(function($header) {
445             return mb_strlen($header['text']) > 0;
446         });
447
448         // Shift headers if only smaller headers have been used
449         $levelChange = ($tree->pluck('level')->min() - 1);
450         $tree = $tree->map(function ($header) use ($levelChange) {
451             $header['level'] -= ($levelChange);
452             return $header;
453         });
454
455         return $tree->toArray();
456     }
457
458     /**
459      * Restores a revision's content back into a page.
460      * @param Page $page
461      * @param Book $book
462      * @param  int $revisionId
463      * @return Page
464      * @throws \Exception
465      */
466     public function restorePageRevision(Page $page, Book $book, int $revisionId)
467     {
468         $page->revision_count++;
469         $this->savePageRevision($page);
470         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
471         $page->fill($revision->toArray());
472         $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
473         $page->text = $this->pageToPlainText($page);
474         $page->updated_by = user()->id;
475         $page->save();
476         $this->searchService->indexEntity($page);
477         return $page;
478     }
479
480     /**
481      * Change the page's parent to the given entity.
482      * @param Page $page
483      * @param Entity $parent
484      * @throws \Throwable
485      */
486     public function changePageParent(Page $page, Entity $parent)
487     {
488         $book = $parent->isA('book') ? $parent : $parent->book;
489         $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
490         $page->save();
491         if ($page->book->id !== $book->id) {
492             $page = $this->changeBook('page', $book->id, $page);
493         }
494         $page->load('book');
495         $this->permissionService->buildJointPermissionsForEntity($book);
496     }
497
498     /**
499      * Create a copy of a page in a new location with a new name.
500      * @param \BookStack\Entities\Page $page
501      * @param \BookStack\Entities\Entity $newParent
502      * @param string $newName
503      * @return \BookStack\Entities\Page
504      * @throws \Throwable
505      */
506     public function copyPage(Page $page, Entity $newParent, string $newName = '')
507     {
508         $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
509         $newChapter = $newParent->isA('chapter') ? $newParent : null;
510         $copyPage = $this->getDraftPage($newBook, $newChapter);
511         $pageData = $page->getAttributes();
512
513         // Update name
514         if (!empty($newName)) {
515             $pageData['name'] = $newName;
516         }
517
518         // Copy tags from previous page if set
519         if ($page->tags) {
520             $pageData['tags'] = [];
521             foreach ($page->tags as $tag) {
522                 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
523             }
524         }
525
526         // Set priority
527         if ($newParent->isA('chapter')) {
528             $pageData['priority'] = $this->getNewChapterPriority($newParent);
529         } else {
530             $pageData['priority'] = $this->getNewBookPriority($newParent);
531         }
532
533         return $this->publishPageDraft($copyPage, $pageData);
534     }
535 }