1 <?php namespace BookStack\Repos;
7 use BookStack\Exceptions\NotFoundException;
10 use Illuminate\Support\Str;
12 use BookStack\PageRevision;
14 class PageRepo extends EntityRepo
17 protected $pageRevision;
21 * PageRepo constructor.
22 * @param PageRevision $pageRevision
23 * @param TagRepo $tagRepo
25 public function __construct(PageRevision $pageRevision, TagRepo $tagRepo)
27 $this->pageRevision = $pageRevision;
28 $this->tagRepo = $tagRepo;
29 parent::__construct();
33 * Base query for getting pages, Takes restrictions into account.
34 * @param bool $allowDrafts
37 private function pageQuery($allowDrafts = false)
39 $query = $this->permissionService->enforcePageRestrictions($this->page, 'view');
41 $query = $query->where('draft', '=', false);
47 * Get a page via a specific ID.
49 * @param bool $allowDrafts
52 public function getById($id, $allowDrafts = false)
54 return $this->pageQuery($allowDrafts)->findOrFail($id);
58 * Get a page identified by the given slug.
62 * @throws NotFoundException
64 public function getBySlug($slug, $bookId)
66 $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
67 if ($page === null) throw new NotFoundException('Page not found');
72 * Search through page revisions and retrieve
73 * the last page in the current book that
74 * has a slug equal to the one given.
79 public function findPageUsingOldSlug($pageSlug, $bookSlug)
81 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
82 ->whereHas('page', function ($query) {
83 $this->permissionService->enforcePageRestrictions($query);
85 ->where('type', '=', 'version')
86 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
87 ->with('page')->first();
88 return $revision !== null ? $revision->page : null;
92 * Get a new Page instance from the given input.
96 public function newFromInput($input)
98 $page = $this->page->fill($input);
103 * Count the pages with a particular slug within a book.
108 public function countBySlug($slug, $bookId)
110 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
114 * Save a new page into the system.
115 * Input validation must be done beforehand.
116 * @param array $input
118 * @param int $chapterId
121 public function saveNew(array $input, Book $book, $chapterId = null)
123 $page = $this->newFromInput($input);
124 $page->slug = $this->findSuitableSlug($page->name, $book->id);
126 if ($chapterId) $page->chapter_id = $chapterId;
128 $page->html = $this->formatHtml($input['html']);
129 $page->text = strip_tags($page->html);
130 $page->created_by = auth()->user()->id;
131 $page->updated_by = auth()->user()->id;
133 $book->pages()->save($page);
139 * Publish a draft page to make it a normal page.
140 * Sets the slug and updates the content.
141 * @param Page $draftPage
142 * @param array $input
145 public function publishDraft(Page $draftPage, array $input)
147 $draftPage->fill($input);
149 // Save page tags if present
150 if (isset($input['tags'])) {
151 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
154 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
155 $draftPage->html = $this->formatHtml($input['html']);
156 $draftPage->text = strip_tags($draftPage->html);
157 $draftPage->draft = false;
160 $this->saveRevision($draftPage, 'Initial Publish');
166 * Get a new draft page instance.
168 * @param Chapter|bool $chapter
171 public function getDraftPage(Book $book, $chapter = false)
173 $page = $this->page->newInstance();
174 $page->name = 'New Page';
175 $page->created_by = auth()->user()->id;
176 $page->updated_by = auth()->user()->id;
179 if ($chapter) $page->chapter_id = $chapter->id;
181 $book->pages()->save($page);
182 $this->permissionService->buildJointPermissionsForEntity($page);
187 * Formats a page's html to be tagged correctly
189 * @param string $htmlText
192 protected function formatHtml($htmlText)
194 if ($htmlText == '') return $htmlText;
195 libxml_use_internal_errors(true);
196 $doc = new DOMDocument();
197 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
199 $container = $doc->documentElement;
200 $body = $container->childNodes->item(0);
201 $childNodes = $body->childNodes;
203 // Ensure no duplicate ids are used
206 foreach ($childNodes as $index => $childNode) {
207 /** @var \DOMElement $childNode */
208 if (get_class($childNode) !== 'DOMElement') continue;
210 // Overwrite id if not a BookStack custom id
211 if ($childNode->hasAttribute('id')) {
212 $id = $childNode->getAttribute('id');
213 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
219 // Create an unique id for the element
220 // Uses the content as a basis to ensure output is the same every time
221 // the same content is passed through.
222 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
223 $newId = urlencode($contentId);
225 while (in_array($newId, $idArray)) {
226 $newId = urlencode($contentId . '-' . $loopIndex);
230 $childNode->setAttribute('id', $newId);
234 // Generate inner html as a string
236 foreach ($childNodes as $childNode) {
237 $html .= $doc->saveHTML($childNode);
245 * Gets pages by a search term.
246 * Highlights page content for showing in results.
247 * @param string $term
248 * @param array $whereTerms
250 * @param array $paginationAppends
253 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
255 $terms = $this->prepareSearchTerms($term);
256 $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms));
257 $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term);
258 $pages = $pageQuery->paginate($count)->appends($paginationAppends);
260 // Add highlights to page text.
261 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
262 //lookahead/behind assertions ensures cut between words
263 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
265 foreach ($pages as $page) {
266 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
267 //delimiter between occurrences
269 foreach ($matches as $line) {
270 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
273 if (count($results) > $matchLimit) {
274 $results = array_slice($results, 0, $matchLimit);
276 $result = join('... ', $results);
279 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
280 if (strlen($result) < 5) {
281 $result = $page->getExcerpt(80);
283 $page->searchSnippet = $result;
289 * Search for image usage.
290 * @param $imageString
293 public function searchForImage($imageString)
295 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
296 foreach ($pages as $page) {
297 $page->url = $page->getUrl();
301 return count($pages) > 0 ? $pages : false;
305 * Updates a page with any fillable data and saves it into the database.
307 * @param int $book_id
308 * @param string $input
311 public function updatePage(Page $page, $book_id, $input)
313 // Hold the old details to compare later
314 $oldHtml = $page->html;
315 $oldName = $page->name;
317 // Prevent slug being updated if no name change
318 if ($page->name !== $input['name']) {
319 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
322 // Save page tags if present
323 if (isset($input['tags'])) {
324 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
327 // Update with new details
328 $userId = auth()->user()->id;
330 $page->html = $this->formatHtml($input['html']);
331 $page->text = strip_tags($page->html);
332 if (setting('app-editor') !== 'markdown') $page->markdown = '';
333 $page->updated_by = $userId;
336 // Remove all update drafts for this user & page.
337 $this->userUpdateDraftsQuery($page, $userId)->delete();
339 // Save a revision after updating
340 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
341 $this->saveRevision($page, $input['summary']);
348 * Restores a revision's content back into a page.
351 * @param int $revisionId
354 public function restoreRevision(Page $page, Book $book, $revisionId)
356 $this->saveRevision($page);
357 $revision = $this->getRevisionById($revisionId);
358 $page->fill($revision->toArray());
359 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
360 $page->text = strip_tags($page->html);
361 $page->updated_by = auth()->user()->id;
367 * Saves a page revision into the system.
369 * @param null|string $summary
372 public function saveRevision(Page $page, $summary = null)
374 $revision = $this->pageRevision->fill($page->toArray());
375 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
376 $revision->page_id = $page->id;
377 $revision->slug = $page->slug;
378 $revision->book_slug = $page->book->slug;
379 $revision->created_by = auth()->user()->id;
380 $revision->created_at = $page->updated_at;
381 $revision->type = 'version';
382 $revision->summary = $summary;
384 // Clear old revisions
385 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
386 $this->pageRevision->where('page_id', '=', $page->id)
387 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
393 * Save a page update draft.
396 * @return PageRevision
398 public function saveUpdateDraft(Page $page, $data = [])
400 $userId = auth()->user()->id;
401 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
403 if ($drafts->count() > 0) {
404 $draft = $drafts->first();
406 $draft = $this->pageRevision->newInstance();
407 $draft->page_id = $page->id;
408 $draft->slug = $page->slug;
409 $draft->book_slug = $page->book->slug;
410 $draft->created_by = $userId;
411 $draft->type = 'update_draft';
415 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
422 * Update a draft page.
427 public function updateDraftPage(Page $page, $data = [])
431 if (isset($data['html'])) {
432 $page->text = strip_tags($data['html']);
440 * The base query for getting user update drafts.
445 private function userUpdateDraftsQuery(Page $page, $userId)
447 return $this->pageRevision->where('created_by', '=', $userId)
448 ->where('type', 'update_draft')
449 ->where('page_id', '=', $page->id)
450 ->orderBy('created_at', 'desc');
454 * Checks whether a user has a draft version of a particular page or not.
459 public function hasUserGotPageDraft(Page $page, $userId)
461 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
465 * Get the latest updated draft revision for a particular page and user.
470 public function getUserPageDraft(Page $page, $userId)
472 return $this->userUpdateDraftsQuery($page, $userId)->first();
476 * Get the notification message that informs the user that they are editing a draft page.
477 * @param PageRevision $draft
480 public function getUserPageDraftMessage(PageRevision $draft)
482 $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
483 if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
484 $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
490 * Check if a page is being actively editing.
491 * Checks for edits since last page updated.
492 * Passing in a minuted range will check for edits
493 * within the last x minutes.
495 * @param null $minRange
498 public function isPageEditingActive(Page $page, $minRange = null)
500 $draftSearch = $this->activePageEditingQuery($page, $minRange);
501 return $draftSearch->count() > 0;
505 * Get a notification message concerning the editing activity on
508 * @param null $minRange
511 public function getPageEditingActiveMessage(Page $page, $minRange = null)
513 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
514 $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
515 $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
516 $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
517 return sprintf($message, $userMessage, $timeMessage);
521 * A query to check for active update drafts on a particular page.
523 * @param null $minRange
526 private function activePageEditingQuery(Page $page, $minRange = null)
528 $query = $this->pageRevision->where('type', '=', 'update_draft')
529 ->where('page_id', '=', $page->id)
530 ->where('updated_at', '>', $page->updated_at)
531 ->where('created_by', '!=', auth()->user()->id)
534 if ($minRange !== null) {
535 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
542 * Gets a single revision via it's id.
546 public function getRevisionById($id)
548 return $this->pageRevision->findOrFail($id);
552 * Checks if a slug exists within a book already.
555 * @param bool|false $currentId
558 public function doesSlugExist($slug, $bookId, $currentId = false)
560 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
561 if ($currentId) $query = $query->where('id', '!=', $currentId);
562 return $query->count() > 0;
566 * Changes the related book for the specified page.
567 * Changes the book id of any relations to the page that store the book id.
572 public function changeBook($bookId, Page $page)
574 $page->book_id = $bookId;
575 foreach ($page->activity as $activity) {
576 $activity->book_id = $bookId;
579 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
586 * Change the page's parent to the given entity.
588 * @param Entity $parent
590 public function changePageParent(Page $page, Entity $parent)
592 $book = $parent->isA('book') ? $parent : $parent->book;
593 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
595 $page = $this->changeBook($book->id, $page);
597 $this->permissionService->buildJointPermissionsForEntity($book);
601 * Gets a suitable slug for the resource
602 * @param string $name
604 * @param bool|false $currentId
607 public function findSuitableSlug($name, $bookId, $currentId = false)
609 $slug = Str::slug($name);
610 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
611 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
612 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
618 * Destroy a given page along with its dependencies.
621 public function destroy(Page $page)
623 Activity::removeEntity($page);
624 $page->views()->delete();
625 $page->tags()->delete();
626 $page->revisions()->delete();
627 $page->permissions()->delete();
628 $this->permissionService->deleteJointPermissionsForEntity($page);
633 * Get the latest pages added to the system.
636 public function getRecentlyCreatedPaginated($count = 20)
638 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
642 * Get the latest pages added to the system.
645 public function getRecentlyUpdatedPaginated($count = 20)
647 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);