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;
12 class PageRepo extends EntityRepo
17 * @param string $pageSlug
18 * @param string $bookSlug
20 * @throws \BookStack\Exceptions\NotFoundException
22 public function getPageBySlug(string $pageSlug, string $bookSlug)
24 return $this->getBySlug('page', $pageSlug, $bookSlug);
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
34 public function getPageByOldSlug(string $pageSlug, string $bookSlug)
36 $revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
37 ->whereHas('page', function ($query) {
38 $this->permissionService->enforceEntityRestrictions('page', $query);
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;
48 * Updates a page with any fillable data and saves it into the database.
55 public function updatePage(Page $page, int $book_id, array $input)
57 // Hold the old details to compare later
58 $oldHtml = $page->html;
59 $oldName = $page->name;
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);
66 // Save page tags if present
67 if (isset($input['tags'])) {
68 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
71 // Update with new details
74 $page->html = $this->formatHtml($input['html']);
75 $page->text = $this->pageToPlainText($page);
76 if (setting('app-editor') !== 'markdown') {
79 $page->updated_by = $userId;
80 $page->revision_count++;
83 // Remove all update drafts for this user & page.
84 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
86 // Save a revision after updating
87 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
88 $this->savePageRevision($page, $input['summary']);
91 $this->searchService->indexEntity($page);
97 * Saves a page revision into the system.
99 * @param null|string $summary
100 * @return PageRevision
103 public function savePageRevision(Page $page, string $summary = null)
105 $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
106 if (setting('app-editor') !== 'markdown') {
107 $revision->markdown = '';
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;
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();
132 * Formats a page's html to be tagged correctly
134 * @param string $htmlText
137 protected function formatHtml(string $htmlText)
139 if ($htmlText == '') {
142 libxml_use_internal_errors(true);
143 $doc = new DOMDocument();
144 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
146 $container = $doc->documentElement;
147 $body = $container->childNodes->item(0);
148 $childNodes = $body->childNodes;
150 // Ensure no duplicate ids are used
153 foreach ($childNodes as $index => $childNode) {
154 /** @var \DOMElement $childNode */
155 if (get_class($childNode) !== 'DOMElement') {
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) {
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);
174 while (in_array($newId, $idArray)) {
175 $newId = urlencode($contentId . '-' . $loopIndex);
179 $childNode->setAttribute('id', $newId);
183 // Generate inner html as a string
185 foreach ($childNodes as $childNode) {
186 $html .= $doc->saveHTML($childNode);
193 * Get the plain text version of a page's content.
194 * @param \BookStack\Entities\Page $page
197 protected function pageToPlainText(Page $page) : string
199 $html = $this->renderPage($page, true);
200 return strip_tags($html);
204 * Get a new draft page instance.
206 * @param Chapter|null $chapter
207 * @return \BookStack\Entities\Page
210 public function getDraftPage(Book $book, Chapter $chapter = null)
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;
219 $page->chapter_id = $chapter->id;
222 $book->pages()->save($page);
223 $page = $this->entityProvider->page->find($page->id);
224 $this->permissionService->buildJointPermissionsForEntity($page);
229 * Save a page update draft.
232 * @return PageRevision|Page
234 public function updatePageDraft(Page $page, array $data = [])
236 // If the page itself is a draft simply update that
239 if (isset($data['html'])) {
240 $page->text = $this->pageToPlainText($page);
246 // Otherwise save the data to a revision
247 $userId = user()->id;
248 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
250 if ($drafts->count() > 0) {
251 $draft = $drafts->first();
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';
262 if (setting('app-editor') !== 'markdown') {
263 $draft->markdown = '';
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
278 public function publishPageDraft(Page $draftPage, array $input)
280 $draftPage->fill($input);
282 // Save page tags if present
283 if (isset($input['tags'])) {
284 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
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;
294 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
295 $this->searchService->indexEntity($draftPage);
300 * The base query for getting user update drafts.
305 protected function userUpdatePageDraftsQuery(Page $page, int $userId)
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');
314 * Get the latest updated draft revision for a particular page and user.
317 * @return PageRevision|null
319 public function getUserPageDraft(Page $page, int $userId)
321 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
325 * Get the notification message that informs the user that they are editing a draft page.
326 * @param PageRevision $draft
329 public function getUserPageDraftMessage(PageRevision $draft)
331 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
332 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
335 return $message . "\n" . trans('entities.pages_draft_edited_notification');
339 * A query to check for active update drafts on a particular page.
341 * @param int $minRange
344 protected function activePageEditingQuery(Page $page, int $minRange = null)
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)
352 if ($minRange !== null) {
353 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
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.
365 * @param int $minRange
368 public function isPageEditingActive(Page $page, int $minRange = null)
370 $draftSearch = $this->activePageEditingQuery($page, $minRange);
371 return $draftSearch->count() > 0;
375 * Get a notification message concerning the editing activity on a particular page.
377 * @param int $minRange
380 public function getPageEditingActiveMessage(Page $page, int $minRange = null)
382 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
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]);
390 * Parse the headers on the page to get a navigation menu
391 * @param string $pageContent
394 public function getPageNav(string $pageContent)
396 if ($pageContent == '') {
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");
405 if (is_null($headers)) {
410 foreach ($headers as $header) {
411 $text = $header->nodeValue;
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
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);
428 return $tree->toArray();
432 * Restores a revision's content back into a page.
435 * @param int $revisionId
439 public function restorePageRevision(Page $page, Book $book, int $revisionId)
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;
449 $this->searchService->indexEntity($page);
454 * Change the page's parent to the given entity.
456 * @param Entity $parent
459 public function changePageParent(Page $page, Entity $parent)
461 $book = $parent->isA('book') ? $parent : $parent->book;
462 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
464 if ($page->book->id !== $book->id) {
465 $page = $this->changeBook('page', $book->id, $page);
468 $this->permissionService->buildJointPermissionsForEntity($book);
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
479 public function copyPage(Page $page, Entity $newParent, string $newName = '')
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();
487 if (!empty($newName)) {
488 $pageData['name'] = $newName;
491 // Copy tags from previous page if set
493 $pageData['tags'] = [];
494 foreach ($page->tags as $tag) {
495 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
500 if ($newParent->isA('chapter')) {
501 $pageData['priority'] = $this->getNewChapterPriority($newParent);
503 $pageData['priority'] = $this->getNewBookPriority($newParent);
506 return $this->publishPageDraft($copyPage, $pageData);