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