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 // Update with new details
75 $page->html = $this->formatHtml($input['html']);
76 $page->text = $this->pageToPlainText($page);
77 if (setting('app-editor') !== 'markdown') {
80 $page->updated_by = $userId;
81 $page->revision_count++;
84 // Remove all update drafts for this user & page.
85 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
87 // Save a revision after updating
88 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
89 $this->savePageRevision($page, $input['summary']);
92 $this->searchService->indexEntity($page);
98 * Saves a page revision into the system.
100 * @param null|string $summary
101 * @return PageRevision
104 public function savePageRevision(Page $page, string $summary = null)
106 $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
107 if (setting('app-editor') !== 'markdown') {
108 $revision->markdown = '';
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;
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();
133 * Formats a page's html to be tagged correctly within the system.
134 * @param string $htmlText
137 protected function formatHtml(string $htmlText)
139 if ($htmlText == '') {
143 libxml_use_internal_errors(true);
144 $doc = new DOMDocument();
145 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
147 $container = $doc->documentElement;
148 $body = $container->childNodes->item(0);
149 $childNodes = $body->childNodes;
151 // Set ids on top-level nodes
153 foreach ($childNodes as $index => $childNode) {
154 $this->setUniqueId($childNode, $idMap);
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);
164 // Generate inner html as a string
166 foreach ($childNodes as $childNode) {
167 $html .= $doc->saveHTML($childNode);
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
179 protected function setUniqueId($element, array &$idMap)
181 if (get_class($element) !== 'DOMElement') {
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;
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);
199 while (isset($idMap[$newId])) {
200 $newId = urlencode($contentId . '-' . $loopIndex);
204 $element->setAttribute('id', $newId);
205 $idMap[$newId] = true;
209 * Get the plain text version of a page's content.
210 * @param \BookStack\Entities\Page $page
213 protected function pageToPlainText(Page $page) : string
215 $html = $this->renderPage($page, true);
216 return strip_tags($html);
220 * Get a new draft page instance.
222 * @param Chapter|null $chapter
223 * @return \BookStack\Entities\Page
226 public function getDraftPage(Book $book, Chapter $chapter = null)
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;
235 $page->chapter_id = $chapter->id;
238 $book->pages()->save($page);
239 $page = $this->entityProvider->page->find($page->id);
240 $this->permissionService->buildJointPermissionsForEntity($page);
245 * Save a page update draft.
248 * @return PageRevision|Page
250 public function updatePageDraft(Page $page, array $data = [])
252 // If the page itself is a draft simply update that
255 if (isset($data['html'])) {
256 $page->text = $this->pageToPlainText($page);
262 // Otherwise save the data to a revision
263 $userId = user()->id;
264 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
266 if ($drafts->count() > 0) {
267 $draft = $drafts->first();
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';
278 if (setting('app-editor') !== 'markdown') {
279 $draft->markdown = '';
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
294 public function publishPageDraft(Page $draftPage, array $input)
296 $draftPage->fill($input);
298 // Save page tags if present
299 if (isset($input['tags'])) {
300 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
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;
310 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
311 $this->searchService->indexEntity($draftPage);
316 * The base query for getting user update drafts.
321 protected function userUpdatePageDraftsQuery(Page $page, int $userId)
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');
330 * Get the latest updated draft revision for a particular page and user.
333 * @return PageRevision|null
335 public function getUserPageDraft(Page $page, int $userId)
337 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
341 * Get the notification message that informs the user that they are editing a draft page.
342 * @param PageRevision $draft
345 public function getUserPageDraftMessage(PageRevision $draft)
347 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
348 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
351 return $message . "\n" . trans('entities.pages_draft_edited_notification');
355 * A query to check for active update drafts on a particular page.
357 * @param int $minRange
360 protected function activePageEditingQuery(Page $page, int $minRange = null)
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)
368 if ($minRange !== null) {
369 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
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.
381 * @param int $minRange
384 public function isPageEditingActive(Page $page, int $minRange = null)
386 $draftSearch = $this->activePageEditingQuery($page, $minRange);
387 return $draftSearch->count() > 0;
391 * Get a notification message concerning the editing activity on a particular page.
393 * @param int $minRange
396 public function getPageEditingActiveMessage(Page $page, int $minRange = null)
398 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
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]);
406 * Parse the headers on the page to get a navigation menu
407 * @param string $pageContent
410 public function getPageNav(string $pageContent)
412 if ($pageContent == '') {
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");
421 if (is_null($headers)) {
425 $tree = collect($headers)->map(function($header) {
426 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
427 $text = mb_substr($text, 0, 100);
430 'nodeName' => strtolower($header->nodeName),
431 'level' => intval(str_replace('h', '', $header->nodeName)),
432 'link' => '#' . $header->getAttribute('id'),
435 })->filter(function($header) {
436 return mb_strlen($header['text']) > 0;
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);
446 return $tree->toArray();
450 * Restores a revision's content back into a page.
453 * @param int $revisionId
457 public function restorePageRevision(Page $page, Book $book, int $revisionId)
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;
467 $this->searchService->indexEntity($page);
472 * Change the page's parent to the given entity.
474 * @param Entity $parent
477 public function changePageParent(Page $page, Entity $parent)
479 $book = $parent->isA('book') ? $parent : $parent->book;
480 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
482 if ($page->book->id !== $book->id) {
483 $page = $this->changeBook('page', $book->id, $page);
486 $this->permissionService->buildJointPermissionsForEntity($book);
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
497 public function copyPage(Page $page, Entity $newParent, string $newName = '')
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();
505 if (!empty($newName)) {
506 $pageData['name'] = $newName;
509 // Copy tags from previous page if set
511 $pageData['tags'] = [];
512 foreach ($page->tags as $tag) {
513 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
518 if ($newParent->isA('chapter')) {
519 $pageData['priority'] = $this->getNewChapterPriority($newParent);
521 $pageData['priority'] = $this->getNewBookPriority($newParent);
524 return $this->publishPageDraft($copyPage, $pageData);