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