1 <?php namespace BookStack\Repos;
6 use BookStack\Exceptions\NotFoundException;
9 use Illuminate\Support\Str;
11 use BookStack\PageRevision;
13 class PageRepo extends EntityRepo
16 protected $pageRevision;
19 * PageRepo constructor.
20 * @param PageRevision $pageRevision
22 public function __construct(PageRevision $pageRevision)
24 $this->pageRevision = $pageRevision;
25 parent::__construct();
29 * Base query for getting pages, Takes restrictions into account.
30 * @param bool $allowDrafts
33 private function pageQuery($allowDrafts = false)
35 $query = $this->restrictionService->enforcePageRestrictions($this->page, 'view');
37 $query = $query->where('draft', '=', false);
43 * Get a page via a specific ID.
45 * @param bool $allowDrafts
48 public function getById($id, $allowDrafts = false)
50 return $this->pageQuery($allowDrafts)->findOrFail($id);
54 * Get a page identified by the given slug.
58 * @throws NotFoundException
60 public function getBySlug($slug, $bookId)
62 $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
63 if ($page === null) throw new NotFoundException('Page not found');
68 * Search through page revisions and retrieve
69 * the last page in the current book that
70 * has a slug equal to the one given.
75 public function findPageUsingOldSlug($pageSlug, $bookSlug)
77 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
78 ->whereHas('page', function ($query) {
79 $this->restrictionService->enforcePageRestrictions($query);
81 ->where('type', '=', 'version')
82 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
83 ->with('page')->first();
84 return $revision !== null ? $revision->page : null;
88 * Get a new Page instance from the given input.
92 public function newFromInput($input)
94 $page = $this->page->fill($input);
99 * Count the pages with a particular slug within a book.
104 public function countBySlug($slug, $bookId)
106 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
110 * Save a new page into the system.
111 * Input validation must be done beforehand.
112 * @param array $input
114 * @param int $chapterId
117 public function saveNew(array $input, Book $book, $chapterId = null)
119 $page = $this->newFromInput($input);
120 $page->slug = $this->findSuitableSlug($page->name, $book->id);
122 if ($chapterId) $page->chapter_id = $chapterId;
124 $page->html = $this->formatHtml($input['html']);
125 $page->text = strip_tags($page->html);
126 $page->created_by = auth()->user()->id;
127 $page->updated_by = auth()->user()->id;
129 $book->pages()->save($page);
135 * Publish a draft page to make it a normal page.
136 * Sets the slug and updates the content.
137 * @param Page $draftPage
138 * @param array $input
141 public function publishDraft(Page $draftPage, array $input)
143 $draftPage->fill($input);
145 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
146 $draftPage->html = $this->formatHtml($input['html']);
147 $draftPage->text = strip_tags($draftPage->html);
148 $draftPage->draft = false;
155 * Get a new draft page instance.
157 * @param Chapter|null $chapter
160 public function getDraftPage(Book $book, $chapter)
162 $page = $this->page->newInstance();
163 $page->name = 'New Page';
164 $page->created_by = auth()->user()->id;
165 $page->updated_by = auth()->user()->id;
168 if ($chapter) $page->chapter_id = $chapter->id;
170 $book->pages()->save($page);
175 * Formats a page's html to be tagged correctly
177 * @param string $htmlText
180 protected function formatHtml($htmlText)
182 if ($htmlText == '') return $htmlText;
183 libxml_use_internal_errors(true);
184 $doc = new DOMDocument();
185 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
187 $container = $doc->documentElement;
188 $body = $container->childNodes->item(0);
189 $childNodes = $body->childNodes;
191 // Ensure no duplicate ids are used
194 foreach ($childNodes as $index => $childNode) {
195 /** @var \DOMElement $childNode */
196 if (get_class($childNode) !== 'DOMElement') continue;
198 // Overwrite id if not a BookStack custom id
199 if ($childNode->hasAttribute('id')) {
200 $id = $childNode->getAttribute('id');
201 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
207 // Create an unique id for the element
208 // Uses the content as a basis to ensure output is the same every time
209 // the same content is passed through.
210 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
211 $newId = urlencode($contentId);
213 while (in_array($newId, $idArray)) {
214 $newId = urlencode($contentId . '-' . $loopIndex);
218 $childNode->setAttribute('id', $newId);
222 // Generate inner html as a string
224 foreach ($childNodes as $childNode) {
225 $html .= $doc->saveHTML($childNode);
233 * Gets pages by a search term.
234 * Highlights page content for showing in results.
235 * @param string $term
236 * @param array $whereTerms
238 * @param array $paginationAppends
241 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
243 $terms = $this->prepareSearchTerms($term);
244 $pages = $this->restrictionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
245 ->paginate($count)->appends($paginationAppends);
247 // Add highlights to page text.
248 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
249 //lookahead/behind assertions ensures cut between words
250 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
252 foreach ($pages as $page) {
253 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
254 //delimiter between occurrences
256 foreach ($matches as $line) {
257 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
260 if (count($results) > $matchLimit) {
261 $results = array_slice($results, 0, $matchLimit);
263 $result = join('... ', $results);
266 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
267 if (strlen($result) < 5) {
268 $result = $page->getExcerpt(80);
270 $page->searchSnippet = $result;
276 * Search for image usage.
277 * @param $imageString
280 public function searchForImage($imageString)
282 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
283 foreach ($pages as $page) {
284 $page->url = $page->getUrl();
288 return count($pages) > 0 ? $pages : false;
292 * Updates a page with any fillable data and saves it into the database.
294 * @param int $book_id
295 * @param string $input
298 public function updatePage(Page $page, $book_id, $input)
300 // Save a revision before updating
301 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
302 $this->saveRevision($page);
305 // Prevent slug being updated if no name change
306 if ($page->name !== $input['name']) {
307 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
310 // Update with new details
311 $userId = auth()->user()->id;
313 $page->html = $this->formatHtml($input['html']);
314 $page->text = strip_tags($page->html);
315 if (setting('app-editor') !== 'markdown') $page->markdown = '';
316 $page->updated_by = $userId;
319 // Remove all update drafts for this user & page.
320 $this->userUpdateDraftsQuery($page, $userId)->delete();
326 * Restores a revision's content back into a page.
329 * @param int $revisionId
332 public function restoreRevision(Page $page, Book $book, $revisionId)
334 $this->saveRevision($page);
335 $revision = $this->getRevisionById($revisionId);
336 $page->fill($revision->toArray());
337 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
338 $page->text = strip_tags($page->html);
339 $page->updated_by = auth()->user()->id;
345 * Saves a page revision into the system.
349 public function saveRevision(Page $page)
351 $revision = $this->pageRevision->fill($page->toArray());
352 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
353 $revision->page_id = $page->id;
354 $revision->slug = $page->slug;
355 $revision->book_slug = $page->book->slug;
356 $revision->created_by = auth()->user()->id;
357 $revision->created_at = $page->updated_at;
358 $revision->type = 'version';
360 // Clear old revisions
361 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
362 $this->pageRevision->where('page_id', '=', $page->id)
363 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
369 * Save a page update draft.
372 * @return PageRevision
374 public function saveUpdateDraft(Page $page, $data = [])
376 $userId = auth()->user()->id;
377 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
379 if ($drafts->count() > 0) {
380 $draft = $drafts->first();
382 $draft = $this->pageRevision->newInstance();
383 $draft->page_id = $page->id;
384 $draft->slug = $page->slug;
385 $draft->book_slug = $page->book->slug;
386 $draft->created_by = $userId;
387 $draft->type = 'update_draft';
391 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
398 * Update a draft page.
403 public function updateDraftPage(Page $page, $data = [])
407 if (isset($data['html'])) {
408 $page->text = strip_tags($data['html']);
416 * The base query for getting user update drafts.
421 private function userUpdateDraftsQuery(Page $page, $userId)
423 return $this->pageRevision->where('created_by', '=', $userId)
424 ->where('type', 'update_draft')
425 ->where('page_id', '=', $page->id)
426 ->orderBy('created_at', 'desc');
430 * Checks whether a user has a draft version of a particular page or not.
435 public function hasUserGotPageDraft(Page $page, $userId)
437 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
441 * Get the latest updated draft revision for a particular page and user.
446 public function getUserPageDraft(Page $page, $userId)
448 return $this->userUpdateDraftsQuery($page, $userId)->first();
452 * Get the notification message that informs the user that they are editing a draft page.
453 * @param PageRevision $draft
456 public function getUserPageDraftMessage(PageRevision $draft)
458 $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
459 if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
460 $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
466 * Check if a page is being actively editing.
467 * Checks for edits since last page updated.
468 * Passing in a minuted range will check for edits
469 * within the last x minutes.
471 * @param null $minRange
474 public function isPageEditingActive(Page $page, $minRange = null)
476 $draftSearch = $this->activePageEditingQuery($page, $minRange);
477 return $draftSearch->count() > 0;
481 * Get a notification message concerning the editing activity on
484 * @param null $minRange
487 public function getPageEditingActiveMessage(Page $page, $minRange = null)
489 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
490 $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
491 $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
492 $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
493 return sprintf($message, $userMessage, $timeMessage);
497 * A query to check for active update drafts on a particular page.
499 * @param null $minRange
502 private function activePageEditingQuery(Page $page, $minRange = null)
504 $query = $this->pageRevision->where('type', '=', 'update_draft')
505 ->where('page_id', '=', $page->id)
506 ->where('updated_at', '>', $page->updated_at)
507 ->where('created_by', '!=', auth()->user()->id)
510 if ($minRange !== null) {
511 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
518 * Gets a single revision via it's id.
522 public function getRevisionById($id)
524 return $this->pageRevision->findOrFail($id);
528 * Checks if a slug exists within a book already.
531 * @param bool|false $currentId
534 public function doesSlugExist($slug, $bookId, $currentId = false)
536 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
537 if ($currentId) $query = $query->where('id', '!=', $currentId);
538 return $query->count() > 0;
542 * Changes the related book for the specified page.
543 * Changes the book id of any relations to the page that store the book id.
548 public function changeBook($bookId, Page $page)
550 $page->book_id = $bookId;
551 foreach ($page->activity as $activity) {
552 $activity->book_id = $bookId;
555 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
561 * Gets a suitable slug for the resource
564 * @param bool|false $currentId
567 public function findSuitableSlug($name, $bookId, $currentId = false)
569 $slug = Str::slug($name);
570 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
571 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
577 * Destroy a given page along with its dependencies.
580 public function destroy($page)
582 Activity::removeEntity($page);
583 $page->views()->delete();
584 $page->revisions()->delete();
585 $page->restrictions()->delete();
590 * Get the latest pages added to the system.
593 public function getRecentlyCreatedPaginated($count = 20)
595 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
599 * Get the latest pages added to the system.
602 public function getRecentlyUpdatedPaginated($count = 20)
604 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);