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