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 == '') {
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 // Ensure no duplicate ids are used
154 foreach ($childNodes as $index => $childNode) {
155 /** @var \DOMElement $childNode */
156 if (get_class($childNode) !== 'DOMElement') {
160 // Overwrite id if not a BookStack custom id
161 if ($childNode->hasAttribute('id')) {
162 $id = $childNode->getAttribute('id');
163 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
169 // Create an unique id for the element
170 // Uses the content as a basis to ensure output is the same every time
171 // the same content is passed through.
172 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
173 $newId = urlencode($contentId);
175 while (in_array($newId, $idArray)) {
176 $newId = urlencode($contentId . '-' . $loopIndex);
180 $childNode->setAttribute('id', $newId);
184 // Generate inner html as a string
186 foreach ($childNodes as $childNode) {
187 $html .= $doc->saveHTML($childNode);
194 * Get the plain text version of a page's content.
195 * @param \BookStack\Entities\Page $page
198 protected function pageToPlainText(Page $page) : string
200 $html = $this->renderPage($page, true);
201 return strip_tags($html);
205 * Get a new draft page instance.
207 * @param Chapter|null $chapter
208 * @return \BookStack\Entities\Page
211 public function getDraftPage(Book $book, Chapter $chapter = null)
213 $page = $this->entityProvider->page->newInstance();
214 $page->name = trans('entities.pages_initial_name');
215 $page->created_by = user()->id;
216 $page->updated_by = user()->id;
220 $page->chapter_id = $chapter->id;
223 $book->pages()->save($page);
224 $page = $this->entityProvider->page->find($page->id);
225 $this->permissionService->buildJointPermissionsForEntity($page);
230 * Save a page update draft.
233 * @return PageRevision|Page
235 public function updatePageDraft(Page $page, array $data = [])
237 // If the page itself is a draft simply update that
240 if (isset($data['html'])) {
241 $page->text = $this->pageToPlainText($page);
247 // Otherwise save the data to a revision
248 $userId = user()->id;
249 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
251 if ($drafts->count() > 0) {
252 $draft = $drafts->first();
254 $draft = $this->entityProvider->pageRevision->newInstance();
255 $draft->page_id = $page->id;
256 $draft->slug = $page->slug;
257 $draft->book_slug = $page->book->slug;
258 $draft->created_by = $userId;
259 $draft->type = 'update_draft';
263 if (setting('app-editor') !== 'markdown') {
264 $draft->markdown = '';
272 * Publish a draft page to make it a normal page.
273 * Sets the slug and updates the content.
274 * @param Page $draftPage
275 * @param array $input
279 public function publishPageDraft(Page $draftPage, array $input)
281 $draftPage->fill($input);
283 // Save page tags if present
284 if (isset($input['tags'])) {
285 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
288 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
289 $draftPage->html = $this->formatHtml($input['html']);
290 $draftPage->text = $this->pageToPlainText($draftPage);
291 $draftPage->draft = false;
292 $draftPage->revision_count = 1;
295 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
296 $this->searchService->indexEntity($draftPage);
301 * The base query for getting user update drafts.
306 protected function userUpdatePageDraftsQuery(Page $page, int $userId)
308 return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
309 ->where('type', 'update_draft')
310 ->where('page_id', '=', $page->id)
311 ->orderBy('created_at', 'desc');
315 * Get the latest updated draft revision for a particular page and user.
318 * @return PageRevision|null
320 public function getUserPageDraft(Page $page, int $userId)
322 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
326 * Get the notification message that informs the user that they are editing a draft page.
327 * @param PageRevision $draft
330 public function getUserPageDraftMessage(PageRevision $draft)
332 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
333 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
336 return $message . "\n" . trans('entities.pages_draft_edited_notification');
340 * A query to check for active update drafts on a particular page.
342 * @param int $minRange
345 protected function activePageEditingQuery(Page $page, int $minRange = null)
347 $query = $this->entityProvider->pageRevision->where('type', '=', 'update_draft')
348 ->where('page_id', '=', $page->id)
349 ->where('updated_at', '>', $page->updated_at)
350 ->where('created_by', '!=', user()->id)
353 if ($minRange !== null) {
354 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
361 * Check if a page is being actively editing.
362 * Checks for edits since last page updated.
363 * Passing in a minuted range will check for edits
364 * within the last x minutes.
366 * @param int $minRange
369 public function isPageEditingActive(Page $page, int $minRange = null)
371 $draftSearch = $this->activePageEditingQuery($page, $minRange);
372 return $draftSearch->count() > 0;
376 * Get a notification message concerning the editing activity on a particular page.
378 * @param int $minRange
381 public function getPageEditingActiveMessage(Page $page, int $minRange = null)
383 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
385 $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]);
386 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
387 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
391 * Parse the headers on the page to get a navigation menu
392 * @param string $pageContent
395 public function getPageNav(string $pageContent)
397 if ($pageContent == '') {
400 libxml_use_internal_errors(true);
401 $doc = new DOMDocument();
402 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
403 $xPath = new DOMXPath($doc);
404 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
406 if (is_null($headers)) {
411 foreach ($headers as $header) {
412 $text = $header->nodeValue;
414 'nodeName' => strtolower($header->nodeName),
415 'level' => intval(str_replace('h', '', $header->nodeName)),
416 'link' => '#' . $header->getAttribute('id'),
417 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
421 // Normalise headers if only smaller headers have been used
422 if (count($tree) > 0) {
423 $minLevel = $tree->pluck('level')->min();
424 $tree = $tree->map(function ($header) use ($minLevel) {
425 $header['level'] -= ($minLevel - 2);
429 return $tree->toArray();
433 * Restores a revision's content back into a page.
436 * @param int $revisionId
440 public function restorePageRevision(Page $page, Book $book, int $revisionId)
442 $page->revision_count++;
443 $this->savePageRevision($page);
444 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
445 $page->fill($revision->toArray());
446 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
447 $page->text = $this->pageToPlainText($page);
448 $page->updated_by = user()->id;
450 $this->searchService->indexEntity($page);
455 * Change the page's parent to the given entity.
457 * @param Entity $parent
460 public function changePageParent(Page $page, Entity $parent)
462 $book = $parent->isA('book') ? $parent : $parent->book;
463 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
465 if ($page->book->id !== $book->id) {
466 $page = $this->changeBook('page', $book->id, $page);
469 $this->permissionService->buildJointPermissionsForEntity($book);
473 * Create a copy of a page in a new location with a new name.
474 * @param \BookStack\Entities\Page $page
475 * @param \BookStack\Entities\Entity $newParent
476 * @param string $newName
477 * @return \BookStack\Entities\Page
480 public function copyPage(Page $page, Entity $newParent, string $newName = '')
482 $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
483 $newChapter = $newParent->isA('chapter') ? $newParent : null;
484 $copyPage = $this->getDraftPage($newBook, $newChapter);
485 $pageData = $page->getAttributes();
488 if (!empty($newName)) {
489 $pageData['name'] = $newName;
492 // Copy tags from previous page if set
494 $pageData['tags'] = [];
495 foreach ($page->tags as $tag) {
496 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
501 if ($newParent->isA('chapter')) {
502 $pageData['priority'] = $this->getNewChapterPriority($newParent);
504 $pageData['priority'] = $this->getNewBookPriority($newParent);
507 return $this->publishPageDraft($copyPage, $pageData);