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;
164 * Get a new draft page instance.
166 * @param Chapter|bool $chapter
169 public function getDraftPage(Book $book, $chapter = false)
171 $page = $this->page->newInstance();
172 $page->name = 'New Page';
173 $page->created_by = auth()->user()->id;
174 $page->updated_by = auth()->user()->id;
177 if ($chapter) $page->chapter_id = $chapter->id;
179 $book->pages()->save($page);
180 $this->permissionService->buildJointPermissionsForEntity($page);
185 * Formats a page's html to be tagged correctly
187 * @param string $htmlText
190 protected function formatHtml($htmlText)
192 if ($htmlText == '') return $htmlText;
193 libxml_use_internal_errors(true);
194 $doc = new DOMDocument();
195 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
197 $container = $doc->documentElement;
198 $body = $container->childNodes->item(0);
199 $childNodes = $body->childNodes;
201 // Ensure no duplicate ids are used
204 foreach ($childNodes as $index => $childNode) {
205 /** @var \DOMElement $childNode */
206 if (get_class($childNode) !== 'DOMElement') continue;
208 // Overwrite id if not a BookStack custom id
209 if ($childNode->hasAttribute('id')) {
210 $id = $childNode->getAttribute('id');
211 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
217 // Create an unique id for the element
218 // Uses the content as a basis to ensure output is the same every time
219 // the same content is passed through.
220 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
221 $newId = urlencode($contentId);
223 while (in_array($newId, $idArray)) {
224 $newId = urlencode($contentId . '-' . $loopIndex);
228 $childNode->setAttribute('id', $newId);
232 // Generate inner html as a string
234 foreach ($childNodes as $childNode) {
235 $html .= $doc->saveHTML($childNode);
243 * Gets pages by a search term.
244 * Highlights page content for showing in results.
245 * @param string $term
246 * @param array $whereTerms
248 * @param array $paginationAppends
251 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
253 $terms = $this->prepareSearchTerms($term);
254 $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms));
255 $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term);
256 $pages = $pageQuery->paginate($count)->appends($paginationAppends);
258 // Add highlights to page text.
259 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
260 //lookahead/behind assertions ensures cut between words
261 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
263 foreach ($pages as $page) {
264 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
265 //delimiter between occurrences
267 foreach ($matches as $line) {
268 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
271 if (count($results) > $matchLimit) {
272 $results = array_slice($results, 0, $matchLimit);
274 $result = join('... ', $results);
277 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
278 if (strlen($result) < 5) {
279 $result = $page->getExcerpt(80);
281 $page->searchSnippet = $result;
287 * Search for image usage.
288 * @param $imageString
291 public function searchForImage($imageString)
293 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
294 foreach ($pages as $page) {
295 $page->url = $page->getUrl();
299 return count($pages) > 0 ? $pages : false;
303 * Updates a page with any fillable data and saves it into the database.
305 * @param int $book_id
306 * @param string $input
309 public function updatePage(Page $page, $book_id, $input)
311 // Hold the old details to compare later
312 $oldHtml = $page->html;
313 $oldName = $page->name;
315 // Prevent slug being updated if no name change
316 if ($page->name !== $input['name']) {
317 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
320 // Save page tags if present
321 if (isset($input['tags'])) {
322 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
325 // Update with new details
326 $userId = auth()->user()->id;
328 $page->html = $this->formatHtml($input['html']);
329 $page->text = strip_tags($page->html);
330 if (setting('app-editor') !== 'markdown') $page->markdown = '';
331 $page->updated_by = $userId;
334 // Remove all update drafts for this user & page.
335 $this->userUpdateDraftsQuery($page, $userId)->delete();
337 // Save a revision after updating
338 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
339 $this->saveRevision($page, $input['summary']);
346 * Restores a revision's content back into a page.
349 * @param int $revisionId
352 public function restoreRevision(Page $page, Book $book, $revisionId)
354 $this->saveRevision($page);
355 $revision = $this->getRevisionById($revisionId);
356 $page->fill($revision->toArray());
357 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
358 $page->text = strip_tags($page->html);
359 $page->updated_by = auth()->user()->id;
365 * Saves a page revision into the system.
367 * @param null|string $summary
370 public function saveRevision(Page $page, $summary = null)
372 $revision = $this->pageRevision->fill($page->toArray());
373 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
374 $revision->page_id = $page->id;
375 $revision->slug = $page->slug;
376 $revision->book_slug = $page->book->slug;
377 $revision->created_by = auth()->user()->id;
378 $revision->created_at = $page->updated_at;
379 $revision->type = 'version';
380 $revision->summary = $summary;
382 // Clear old revisions
383 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
384 $this->pageRevision->where('page_id', '=', $page->id)
385 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
391 * Save a page update draft.
394 * @return PageRevision
396 public function saveUpdateDraft(Page $page, $data = [])
398 $userId = auth()->user()->id;
399 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
401 if ($drafts->count() > 0) {
402 $draft = $drafts->first();
404 $draft = $this->pageRevision->newInstance();
405 $draft->page_id = $page->id;
406 $draft->slug = $page->slug;
407 $draft->book_slug = $page->book->slug;
408 $draft->created_by = $userId;
409 $draft->type = 'update_draft';
413 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
420 * Update a draft page.
425 public function updateDraftPage(Page $page, $data = [])
429 if (isset($data['html'])) {
430 $page->text = strip_tags($data['html']);
438 * The base query for getting user update drafts.
443 private function userUpdateDraftsQuery(Page $page, $userId)
445 return $this->pageRevision->where('created_by', '=', $userId)
446 ->where('type', 'update_draft')
447 ->where('page_id', '=', $page->id)
448 ->orderBy('created_at', 'desc');
452 * Checks whether a user has a draft version of a particular page or not.
457 public function hasUserGotPageDraft(Page $page, $userId)
459 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
463 * Get the latest updated draft revision for a particular page and user.
468 public function getUserPageDraft(Page $page, $userId)
470 return $this->userUpdateDraftsQuery($page, $userId)->first();
474 * Get the notification message that informs the user that they are editing a draft page.
475 * @param PageRevision $draft
478 public function getUserPageDraftMessage(PageRevision $draft)
480 $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
481 if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
482 $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
488 * Check if a page is being actively editing.
489 * Checks for edits since last page updated.
490 * Passing in a minuted range will check for edits
491 * within the last x minutes.
493 * @param null $minRange
496 public function isPageEditingActive(Page $page, $minRange = null)
498 $draftSearch = $this->activePageEditingQuery($page, $minRange);
499 return $draftSearch->count() > 0;
503 * Get a notification message concerning the editing activity on
506 * @param null $minRange
509 public function getPageEditingActiveMessage(Page $page, $minRange = null)
511 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
512 $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
513 $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
514 $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
515 return sprintf($message, $userMessage, $timeMessage);
519 * A query to check for active update drafts on a particular page.
521 * @param null $minRange
524 private function activePageEditingQuery(Page $page, $minRange = null)
526 $query = $this->pageRevision->where('type', '=', 'update_draft')
527 ->where('page_id', '=', $page->id)
528 ->where('updated_at', '>', $page->updated_at)
529 ->where('created_by', '!=', auth()->user()->id)
532 if ($minRange !== null) {
533 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
540 * Gets a single revision via it's id.
544 public function getRevisionById($id)
546 return $this->pageRevision->findOrFail($id);
550 * Checks if a slug exists within a book already.
553 * @param bool|false $currentId
556 public function doesSlugExist($slug, $bookId, $currentId = false)
558 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
559 if ($currentId) $query = $query->where('id', '!=', $currentId);
560 return $query->count() > 0;
564 * Changes the related book for the specified page.
565 * Changes the book id of any relations to the page that store the book id.
570 public function changeBook($bookId, Page $page)
572 $page->book_id = $bookId;
573 foreach ($page->activity as $activity) {
574 $activity->book_id = $bookId;
577 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
584 * Change the page's parent to the given entity.
586 * @param Entity $parent
588 public function changePageParent(Page $page, Entity $parent)
590 $book = $parent->isA('book') ? $parent : $parent->book;
591 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
593 $page = $this->changeBook($book->id, $page);
595 $this->permissionService->buildJointPermissionsForEntity($book);
599 * Gets a suitable slug for the resource
602 * @param bool|false $currentId
605 public function findSuitableSlug($name, $bookId, $currentId = false)
607 $slug = Str::slug($name);
608 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
609 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
615 * Destroy a given page along with its dependencies.
618 public function destroy(Page $page)
620 Activity::removeEntity($page);
621 $page->views()->delete();
622 $page->tags()->delete();
623 $page->revisions()->delete();
624 $page->permissions()->delete();
625 $this->permissionService->deleteJointPermissionsForEntity($page);
630 * Get the latest pages added to the system.
633 public function getRecentlyCreatedPaginated($count = 20)
635 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
639 * Get the latest pages added to the system.
642 public function getRecentlyUpdatedPaginated($count = 20)
644 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);