1 <?php namespace BookStack\Entities\Repos;
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;
13 class PageRepo extends EntityRepo
18 * @param string $pageSlug
19 * @param string $bookSlug
21 * @throws \BookStack\Exceptions\NotFoundException
23 public function getPageBySlug(string $pageSlug, string $bookSlug)
25 return $this->getBySlug('page', $pageSlug, $bookSlug);
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
35 public function getPageByOldSlug(string $pageSlug, string $bookSlug)
37 $revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
38 ->whereHas('page', function ($query) {
39 $this->permissionService->enforceEntityRestrictions('page', $query);
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;
49 * Updates a page with any fillable data and saves it into the database.
56 public function updatePage(Page $page, int $book_id, array $input)
58 // Hold the old details to compare later
59 $oldHtml = $page->html;
60 $oldName = $page->name;
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);
67 // Save page tags if present
68 if (isset($input['tags'])) {
69 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
72 if (isset($input['template']) && userCan('templates-manage')) {
73 $page->template = ($input['template'] === 'true');
76 // Update with new details
79 $page->html = $this->formatHtml($input['html']);
80 $page->text = $this->pageToPlainText($page);
81 if (setting('app-editor') !== 'markdown') {
84 $page->updated_by = $userId;
85 $page->revision_count++;
88 // Remove all update drafts for this user & page.
89 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
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);
97 $this->searchService->indexEntity($page);
103 * Saves a page revision into the system.
105 * @param null|string $summary
106 * @return PageRevision
109 public function savePageRevision(Page $page, string $summary = null)
111 $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
112 if (setting('app-editor') !== 'markdown') {
113 $revision->markdown = '';
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;
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();
138 * Formats a page's html to be tagged correctly within the system.
139 * @param string $htmlText
142 protected function formatHtml(string $htmlText)
144 if ($htmlText == '') {
148 libxml_use_internal_errors(true);
149 $doc = new DOMDocument();
150 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
152 $container = $doc->documentElement;
153 $body = $container->childNodes->item(0);
154 $childNodes = $body->childNodes;
156 // Set ids on top-level nodes
158 foreach ($childNodes as $index => $childNode) {
159 $this->setUniqueId($childNode, $idMap);
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);
169 // Generate inner html as a string
171 foreach ($childNodes as $childNode) {
172 $html .= $doc->saveHTML($childNode);
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
184 protected function setUniqueId($element, array &$idMap)
186 if (get_class($element) !== 'DOMElement') {
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;
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);
204 while (isset($idMap[$newId])) {
205 $newId = urlencode($contentId . '-' . $loopIndex);
209 $element->setAttribute('id', $newId);
210 $idMap[$newId] = true;
214 * Get the plain text version of a page's content.
215 * @param \BookStack\Entities\Page $page
218 protected function pageToPlainText(Page $page) : string
220 $html = $this->renderPage($page, true);
221 return strip_tags($html);
225 * Get a new draft page instance.
227 * @param Chapter|null $chapter
228 * @return \BookStack\Entities\Page
231 public function getDraftPage(Book $book, Chapter $chapter = null)
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;
240 $page->chapter_id = $chapter->id;
243 $book->pages()->save($page);
244 $page = $this->entityProvider->page->find($page->id);
245 $this->permissionService->buildJointPermissionsForEntity($page);
250 * Save a page update draft.
253 * @return PageRevision|Page
255 public function updatePageDraft(Page $page, array $data = [])
257 // If the page itself is a draft simply update that
260 if (isset($data['html'])) {
261 $page->text = $this->pageToPlainText($page);
267 // Otherwise save the data to a revision
268 $userId = user()->id;
269 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
271 if ($drafts->count() > 0) {
272 $draft = $drafts->first();
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';
283 if (setting('app-editor') !== 'markdown') {
284 $draft->markdown = '';
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
299 public function publishPageDraft(Page $draftPage, array $input)
301 $draftPage->fill($input);
303 // Save page tags if present
304 if (isset($input['tags'])) {
305 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
308 if (isset($input['template']) && userCan('templates-manage')) {
309 $draftPage->template = ($input['template'] === 'true');
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;
319 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
320 $this->searchService->indexEntity($draftPage);
325 * The base query for getting user update drafts.
330 protected function userUpdatePageDraftsQuery(Page $page, int $userId)
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');
339 * Get the latest updated draft revision for a particular page and user.
342 * @return PageRevision|null
344 public function getUserPageDraft(Page $page, int $userId)
346 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
350 * Get the notification message that informs the user that they are editing a draft page.
351 * @param PageRevision $draft
354 public function getUserPageDraftMessage(PageRevision $draft)
356 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
357 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
360 return $message . "\n" . trans('entities.pages_draft_edited_notification');
364 * A query to check for active update drafts on a particular page.
366 * @param int $minRange
369 protected function activePageEditingQuery(Page $page, int $minRange = null)
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)
377 if ($minRange !== null) {
378 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
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.
390 * @param int $minRange
393 public function isPageEditingActive(Page $page, int $minRange = null)
395 $draftSearch = $this->activePageEditingQuery($page, $minRange);
396 return $draftSearch->count() > 0;
400 * Get a notification message concerning the editing activity on a particular page.
402 * @param int $minRange
405 public function getPageEditingActiveMessage(Page $page, int $minRange = null)
407 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
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]);
415 * Parse the headers on the page to get a navigation menu
416 * @param string $pageContent
419 public function getPageNav(string $pageContent)
421 if ($pageContent == '') {
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");
430 if (is_null($headers)) {
434 $tree = collect($headers)->map(function($header) {
435 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
436 $text = mb_substr($text, 0, 100);
439 'nodeName' => strtolower($header->nodeName),
440 'level' => intval(str_replace('h', '', $header->nodeName)),
441 'link' => '#' . $header->getAttribute('id'),
444 })->filter(function($header) {
445 return mb_strlen($header['text']) > 0;
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);
455 return $tree->toArray();
459 * Restores a revision's content back into a page.
462 * @param int $revisionId
466 public function restorePageRevision(Page $page, Book $book, int $revisionId)
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;
476 $this->searchService->indexEntity($page);
481 * Change the page's parent to the given entity.
483 * @param Entity $parent
486 public function changePageParent(Page $page, Entity $parent)
488 $book = $parent->isA('book') ? $parent : $parent->book;
489 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
491 if ($page->book->id !== $book->id) {
492 $page = $this->changeBook('page', $book->id, $page);
495 $this->permissionService->buildJointPermissionsForEntity($book);
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
506 public function copyPage(Page $page, Entity $newParent, string $newName = '')
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();
514 if (!empty($newName)) {
515 $pageData['name'] = $newName;
518 // Copy tags from previous page if set
520 $pageData['tags'] = [];
521 foreach ($page->tags as $tag) {
522 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
527 if ($newParent->isA('chapter')) {
528 $pageData['priority'] = $this->getNewChapterPriority($newParent);
530 $pageData['priority'] = $this->getNewBookPriority($newParent);
533 return $this->publishPageDraft($copyPage, $pageData);