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