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 use Illuminate\Support\Collection;
14 class PageRepo extends EntityRepo
19 * @param string $pageSlug
20 * @param string $bookSlug
22 * @throws \BookStack\Exceptions\NotFoundException
24 public function getPageBySlug(string $pageSlug, string $bookSlug)
26 return $this->getBySlug('page', $pageSlug, $bookSlug);
30 * Search through page revisions and retrieve the last page in the
31 * current book that has a slug equal to the one given.
32 * @param string $pageSlug
33 * @param string $bookSlug
36 public function getPageByOldSlug(string $pageSlug, string $bookSlug)
38 $revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
39 ->whereHas('page', function ($query) {
40 $this->permissionService->enforceEntityRestrictions('page', $query);
42 ->where('type', '=', 'version')
43 ->where('book_slug', '=', $bookSlug)
44 ->orderBy('created_at', 'desc')
45 ->with('page')->first();
46 return $revision !== null ? $revision->page : null;
50 * Updates a page with any fillable data and saves it into the database.
57 public function updatePage(Page $page, int $book_id, array $input)
59 // Hold the old details to compare later
60 $oldHtml = $page->html;
61 $oldName = $page->name;
63 // Prevent slug being updated if no name change
64 if ($page->name !== $input['name']) {
65 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
68 // Save page tags if present
69 if (isset($input['tags'])) {
70 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
73 if (isset($input['template']) && userCan('templates-manage')) {
74 $page->template = ($input['template'] === 'true');
77 // Update with new details
80 $page->html = $this->formatHtml($input['html']);
81 $page->text = $this->pageToPlainText($page);
82 if (setting('app-editor') !== 'markdown') {
85 $page->updated_by = $userId;
86 $page->revision_count++;
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 = $this->entityProvider->page->find($page->id);
246 $this->permissionService->buildJointPermissionsForEntity($page);
251 * Save a page update draft.
254 * @return PageRevision|Page
256 public function updatePageDraft(Page $page, array $data = [])
258 // If the page itself is a draft simply update that
261 if (isset($data['html'])) {
262 $page->text = $this->pageToPlainText($page);
268 // Otherwise save the data to a revision
269 $userId = user()->id;
270 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
272 if ($drafts->count() > 0) {
273 $draft = $drafts->first();
275 $draft = $this->entityProvider->pageRevision->newInstance();
276 $draft->page_id = $page->id;
277 $draft->slug = $page->slug;
278 $draft->book_slug = $page->book->slug;
279 $draft->created_by = $userId;
280 $draft->type = 'update_draft';
284 if (setting('app-editor') !== 'markdown') {
285 $draft->markdown = '';
293 * Publish a draft page to make it a normal page.
294 * Sets the slug and updates the content.
295 * @param Page $draftPage
296 * @param array $input
300 public function publishPageDraft(Page $draftPage, array $input)
302 $draftPage->fill($input);
304 // Save page tags if present
305 if (isset($input['tags'])) {
306 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
309 if (isset($input['template']) && userCan('templates-manage')) {
310 $draftPage->template = ($input['template'] === 'true');
313 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
314 $draftPage->html = $this->formatHtml($input['html']);
315 $draftPage->text = $this->pageToPlainText($draftPage);
316 $draftPage->draft = false;
317 $draftPage->revision_count = 1;
320 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
321 $this->searchService->indexEntity($draftPage);
326 * The base query for getting user update drafts.
331 protected function userUpdatePageDraftsQuery(Page $page, int $userId)
333 return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
334 ->where('type', 'update_draft')
335 ->where('page_id', '=', $page->id)
336 ->orderBy('created_at', 'desc');
340 * Get the latest updated draft revision for a particular page and user.
343 * @return PageRevision|null
345 public function getUserPageDraft(Page $page, int $userId)
347 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
351 * Get the notification message that informs the user that they are editing a draft page.
352 * @param PageRevision $draft
355 public function getUserPageDraftMessage(PageRevision $draft)
357 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
358 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
361 return $message . "\n" . trans('entities.pages_draft_edited_notification');
365 * A query to check for active update drafts on a particular page.
367 * @param int $minRange
370 protected function activePageEditingQuery(Page $page, int $minRange = null)
372 $query = $this->entityProvider->pageRevision->where('type', '=', 'update_draft')
373 ->where('page_id', '=', $page->id)
374 ->where('updated_at', '>', $page->updated_at)
375 ->where('created_by', '!=', user()->id)
378 if ($minRange !== null) {
379 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
386 * Check if a page is being actively editing.
387 * Checks for edits since last page updated.
388 * Passing in a minuted range will check for edits
389 * within the last x minutes.
391 * @param int $minRange
394 public function isPageEditingActive(Page $page, int $minRange = null)
396 $draftSearch = $this->activePageEditingQuery($page, $minRange);
397 return $draftSearch->count() > 0;
401 * Get a notification message concerning the editing activity on a particular page.
403 * @param int $minRange
406 public function getPageEditingActiveMessage(Page $page, int $minRange = null)
408 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
410 $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]);
411 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
412 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
416 * Parse the headers on the page to get a navigation menu
417 * @param string $pageContent
420 public function getPageNav(string $pageContent)
422 if ($pageContent == '') {
425 libxml_use_internal_errors(true);
426 $doc = new DOMDocument();
427 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
428 $xPath = new DOMXPath($doc);
429 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
431 if (is_null($headers)) {
435 $tree = collect($headers)->map(function($header) {
436 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
437 $text = mb_substr($text, 0, 100);
440 'nodeName' => strtolower($header->nodeName),
441 'level' => intval(str_replace('h', '', $header->nodeName)),
442 'link' => '#' . $header->getAttribute('id'),
445 })->filter(function($header) {
446 return mb_strlen($header['text']) > 0;
449 // Shift headers if only smaller headers have been used
450 $levelChange = ($tree->pluck('level')->min() - 1);
451 $tree = $tree->map(function ($header) use ($levelChange) {
452 $header['level'] -= ($levelChange);
456 return $tree->toArray();
460 * Restores a revision's content back into a page.
463 * @param int $revisionId
467 public function restorePageRevision(Page $page, Book $book, int $revisionId)
469 $page->revision_count++;
470 $this->savePageRevision($page);
471 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
472 $page->fill($revision->toArray());
473 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
474 $page->text = $this->pageToPlainText($page);
475 $page->updated_by = user()->id;
477 $this->searchService->indexEntity($page);
482 * Change the page's parent to the given entity.
484 * @param Entity $parent
487 public function changePageParent(Page $page, Entity $parent)
489 $book = $parent->isA('book') ? $parent : $parent->book;
490 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
492 if ($page->book->id !== $book->id) {
493 $page = $this->changeBook('page', $book->id, $page);
496 $this->permissionService->buildJointPermissionsForEntity($book);
500 * Create a copy of a page in a new location with a new name.
501 * @param \BookStack\Entities\Page $page
502 * @param \BookStack\Entities\Entity $newParent
503 * @param string $newName
504 * @return \BookStack\Entities\Page
507 public function copyPage(Page $page, Entity $newParent, string $newName = '')
509 $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
510 $newChapter = $newParent->isA('chapter') ? $newParent : null;
511 $copyPage = $this->getDraftPage($newBook, $newChapter);
512 $pageData = $page->getAttributes();
515 if (!empty($newName)) {
516 $pageData['name'] = $newName;
519 // Copy tags from previous page if set
521 $pageData['tags'] = [];
522 foreach ($page->tags as $tag) {
523 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
528 if ($newParent->isA('chapter')) {
529 $pageData['priority'] = $this->getNewChapterPriority($newParent);
531 $pageData['priority'] = $this->getNewBookPriority($newParent);
534 return $this->publishPageDraft($copyPage, $pageData);
538 * Get pages that have been marked as templates.
541 * @param string $search
542 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
544 public function getPageTemplates(int $count = 10, int $page = 1, string $search = '')
546 $query = $this->entityQuery('page')
547 ->where('template', '=', true)
548 ->orderBy('name', 'asc')
549 ->skip( ($page - 1) * $count)
553 $query->where('name', 'like', '%' . $search . '%');
556 $paginator = $query->paginate($count, ['*'], 'page', $page);
557 $paginator->withPath('/templates');