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 getBySlug(string $pageSlug, string $bookSlug)
25 return $this->getEntityBySlug('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 // Save page tags if present
63 if (isset($input['tags'])) {
64 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
67 if (isset($input['template']) && userCan('templates-manage')) {
68 $page->template = ($input['template'] === 'true');
71 // Update with new details
74 $page->html = $this->formatHtml($input['html']);
75 $page->text = $this->pageToPlainText($page);
76 $page->updated_by = $userId;
77 $page->revision_count++;
79 if (setting('app-editor') !== 'markdown') {
83 if ($page->isDirty('name')) {
89 // Remove all update drafts for this user & page.
90 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
92 // Save a revision after updating
93 $summary = $input['summary'] ?? null;
94 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
95 $this->savePageRevision($page, $summary);
98 $this->searchService->indexEntity($page);
104 * Saves a page revision into the system.
106 * @param null|string $summary
107 * @return PageRevision
110 public function savePageRevision(Page $page, string $summary = null)
112 $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
113 if (setting('app-editor') !== 'markdown') {
114 $revision->markdown = '';
116 $revision->page_id = $page->id;
117 $revision->slug = $page->slug;
118 $revision->book_slug = $page->book->slug;
119 $revision->created_by = user()->id;
120 $revision->created_at = $page->updated_at;
121 $revision->type = 'version';
122 $revision->summary = $summary;
123 $revision->revision_number = $page->revision_count;
126 $revisionLimit = config('app.revision_limit');
127 if ($revisionLimit !== false) {
128 $revisionsToDelete = $this->entityProvider->pageRevision->where('page_id', '=', $page->id)
129 ->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
130 if ($revisionsToDelete->count() > 0) {
131 $this->entityProvider->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
139 * Formats a page's html to be tagged correctly within the system.
140 * @param string $htmlText
143 protected function formatHtml(string $htmlText)
145 if ($htmlText == '') {
149 libxml_use_internal_errors(true);
150 $doc = new DOMDocument();
151 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
153 $container = $doc->documentElement;
154 $body = $container->childNodes->item(0);
155 $childNodes = $body->childNodes;
157 // Set ids on top-level nodes
159 foreach ($childNodes as $index => $childNode) {
160 $this->setUniqueId($childNode, $idMap);
163 // Ensure no duplicate ids within child items
164 $xPath = new DOMXPath($doc);
165 $idElems = $xPath->query('//body//*//*[@id]');
166 foreach ($idElems as $domElem) {
167 $this->setUniqueId($domElem, $idMap);
170 // Generate inner html as a string
172 foreach ($childNodes as $childNode) {
173 $html .= $doc->saveHTML($childNode);
180 * Set a unique id on the given DOMElement.
181 * A map for existing ID's should be passed in to check for current existence.
182 * @param DOMElement $element
183 * @param array $idMap
185 protected function setUniqueId($element, array &$idMap)
187 if (get_class($element) !== 'DOMElement') {
191 // Overwrite id if not a BookStack custom id
192 $existingId = $element->getAttribute('id');
193 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
194 $idMap[$existingId] = true;
198 // Create an unique id for the element
199 // Uses the content as a basis to ensure output is the same every time
200 // the same content is passed through.
201 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
202 $newId = urlencode($contentId);
205 while (isset($idMap[$newId])) {
206 $newId = urlencode($contentId . '-' . $loopIndex);
210 $element->setAttribute('id', $newId);
211 $idMap[$newId] = true;
215 * Get the plain text version of a page's content.
216 * @param \BookStack\Entities\Page $page
219 protected function pageToPlainText(Page $page) : string
221 $html = $this->renderPage($page, true);
222 return strip_tags($html);
226 * Get a new draft page instance.
228 * @param Chapter|null $chapter
229 * @return \BookStack\Entities\Page
232 public function getDraftPage(Book $book, Chapter $chapter = null)
234 $page = $this->entityProvider->page->newInstance();
235 $page->name = trans('entities.pages_initial_name');
236 $page->created_by = user()->id;
237 $page->updated_by = user()->id;
241 $page->chapter_id = $chapter->id;
244 $book->pages()->save($page);
245 $page->refresh()->rebuildPermissions();
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->html = $this->formatHtml($input['html']);
313 $draftPage->text = $this->pageToPlainText($draftPage);
314 $draftPage->draft = false;
315 $draftPage->revision_count = 1;
316 $draftPage->refreshSlug();
318 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
319 $this->searchService->indexEntity($draftPage);
324 * The base query for getting user update drafts.
329 protected function userUpdatePageDraftsQuery(Page $page, int $userId)
331 return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
332 ->where('type', 'update_draft')
333 ->where('page_id', '=', $page->id)
334 ->orderBy('created_at', 'desc');
338 * Get the latest updated draft revision for a particular page and user.
341 * @return PageRevision|null
343 public function getUserPageDraft(Page $page, int $userId)
345 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
349 * Get the notification message that informs the user that they are editing a draft page.
350 * @param PageRevision $draft
353 public function getUserPageDraftMessage(PageRevision $draft)
355 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
356 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
359 return $message . "\n" . trans('entities.pages_draft_edited_notification');
363 * A query to check for active update drafts on a particular page.
365 * @param int $minRange
368 protected function activePageEditingQuery(Page $page, int $minRange = null)
370 $query = $this->entityProvider->pageRevision->where('type', '=', 'update_draft')
371 ->where('page_id', '=', $page->id)
372 ->where('updated_at', '>', $page->updated_at)
373 ->where('created_by', '!=', user()->id)
376 if ($minRange !== null) {
377 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
384 * Check if a page is being actively editing.
385 * Checks for edits since last page updated.
386 * Passing in a minuted range will check for edits
387 * within the last x minutes.
389 * @param int $minRange
392 public function isPageEditingActive(Page $page, int $minRange = null)
394 $draftSearch = $this->activePageEditingQuery($page, $minRange);
395 return $draftSearch->count() > 0;
399 * Get a notification message concerning the editing activity on a particular page.
401 * @param int $minRange
404 public function getPageEditingActiveMessage(Page $page, int $minRange = null)
406 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
408 $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]);
409 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
410 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
414 * Parse the headers on the page to get a navigation menu
415 * @param string $pageContent
418 public function getPageNav(string $pageContent)
420 if ($pageContent == '') {
423 libxml_use_internal_errors(true);
424 $doc = new DOMDocument();
425 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
426 $xPath = new DOMXPath($doc);
427 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
429 if (is_null($headers)) {
433 $tree = collect($headers)->map(function ($header) {
434 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
435 $text = mb_substr($text, 0, 100);
438 'nodeName' => strtolower($header->nodeName),
439 'level' => intval(str_replace('h', '', $header->nodeName)),
440 'link' => '#' . $header->getAttribute('id'),
443 })->filter(function ($header) {
444 return mb_strlen($header['text']) > 0;
447 // Shift headers if only smaller headers have been used
448 $levelChange = ($tree->pluck('level')->min() - 1);
449 $tree = $tree->map(function ($header) use ($levelChange) {
450 $header['level'] -= ($levelChange);
454 return $tree->toArray();
458 * Restores a revision's content back into a page.
461 * @param int $revisionId
465 public function restorePageRevision(Page $page, Book $book, int $revisionId)
467 $page->revision_count++;
468 $this->savePageRevision($page);
470 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
471 $page->fill($revision->toArray());
472 $page->text = $this->pageToPlainText($page);
473 $page->updated_by = user()->id;
474 $page->refreshSlug();
477 $this->searchService->indexEntity($page);
482 * Change the page's parent to the given entity.
484 * @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;
492 if ($page->book->id !== $book->id) {
493 $page = $this->changeBook($page, $book->id);
497 $book->rebuildPermissions();
501 * Create a copy of a page in a new location with a new name.
502 * @param \BookStack\Entities\Page $page
503 * @param \BookStack\Entities\Entity $newParent
504 * @param string $newName
505 * @return \BookStack\Entities\Page
508 public function copyPage(Page $page, Entity $newParent, string $newName = '')
510 $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
511 $newChapter = $newParent->isA('chapter') ? $newParent : null;
512 $copyPage = $this->getDraftPage($newBook, $newChapter);
513 $pageData = $page->getAttributes();
516 if (!empty($newName)) {
517 $pageData['name'] = $newName;
520 // Copy tags from previous page if set
522 $pageData['tags'] = [];
523 foreach ($page->tags as $tag) {
524 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
529 if ($newParent->isA('chapter')) {
530 $pageData['priority'] = $this->getNewChapterPriority($newParent);
532 $pageData['priority'] = $this->getNewBookPriority($newParent);
535 return $this->publishPageDraft($copyPage, $pageData);
539 * Get pages that have been marked as templates.
542 * @param string $search
543 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
545 public function getPageTemplates(int $count = 10, int $page = 1, string $search = '')
547 $query = $this->entityQuery('page')
548 ->where('template', '=', true)
549 ->orderBy('name', 'asc')
550 ->skip(($page - 1) * $count)
554 $query->where('name', 'like', '%' . $search . '%');
557 $paginator = $query->paginate($count, ['*'], 'page', $page);
558 $paginator->withPath('/templates');