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 // Save a revision before updating
312 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
313 $this->saveRevision($page);
316 // Prevent slug being updated if no name change
317 if ($page->name !== $input['name']) {
318 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
321 // Save page tags if present
322 if (isset($input['tags'])) {
323 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
326 // Update with new details
327 $userId = auth()->user()->id;
329 $page->html = $this->formatHtml($input['html']);
330 $page->text = strip_tags($page->html);
331 if (setting('app-editor') !== 'markdown') $page->markdown = '';
332 $page->updated_by = $userId;
335 // Remove all update drafts for this user & page.
336 $this->userUpdateDraftsQuery($page, $userId)->delete();
342 * Restores a revision's content back into a page.
345 * @param int $revisionId
348 public function restoreRevision(Page $page, Book $book, $revisionId)
350 $this->saveRevision($page);
351 $revision = $this->getRevisionById($revisionId);
352 $page->fill($revision->toArray());
353 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
354 $page->text = strip_tags($page->html);
355 $page->updated_by = auth()->user()->id;
361 * Saves a page revision into the system.
365 public function saveRevision(Page $page)
367 $revision = $this->pageRevision->fill($page->toArray());
368 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
369 $revision->page_id = $page->id;
370 $revision->slug = $page->slug;
371 $revision->book_slug = $page->book->slug;
372 $revision->created_by = auth()->user()->id;
373 $revision->created_at = $page->updated_at;
374 $revision->type = 'version';
376 // Clear old revisions
377 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
378 $this->pageRevision->where('page_id', '=', $page->id)
379 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
385 * Save a page update draft.
388 * @return PageRevision
390 public function saveUpdateDraft(Page $page, $data = [])
392 $userId = auth()->user()->id;
393 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
395 if ($drafts->count() > 0) {
396 $draft = $drafts->first();
398 $draft = $this->pageRevision->newInstance();
399 $draft->page_id = $page->id;
400 $draft->slug = $page->slug;
401 $draft->book_slug = $page->book->slug;
402 $draft->created_by = $userId;
403 $draft->type = 'update_draft';
407 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
414 * Update a draft page.
419 public function updateDraftPage(Page $page, $data = [])
423 if (isset($data['html'])) {
424 $page->text = strip_tags($data['html']);
432 * The base query for getting user update drafts.
437 private function userUpdateDraftsQuery(Page $page, $userId)
439 return $this->pageRevision->where('created_by', '=', $userId)
440 ->where('type', 'update_draft')
441 ->where('page_id', '=', $page->id)
442 ->orderBy('created_at', 'desc');
446 * Checks whether a user has a draft version of a particular page or not.
451 public function hasUserGotPageDraft(Page $page, $userId)
453 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
457 * Get the latest updated draft revision for a particular page and user.
462 public function getUserPageDraft(Page $page, $userId)
464 return $this->userUpdateDraftsQuery($page, $userId)->first();
468 * Get the notification message that informs the user that they are editing a draft page.
469 * @param PageRevision $draft
472 public function getUserPageDraftMessage(PageRevision $draft)
474 $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
475 if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
476 $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
482 * Check if a page is being actively editing.
483 * Checks for edits since last page updated.
484 * Passing in a minuted range will check for edits
485 * within the last x minutes.
487 * @param null $minRange
490 public function isPageEditingActive(Page $page, $minRange = null)
492 $draftSearch = $this->activePageEditingQuery($page, $minRange);
493 return $draftSearch->count() > 0;
497 * Get a notification message concerning the editing activity on
500 * @param null $minRange
503 public function getPageEditingActiveMessage(Page $page, $minRange = null)
505 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
506 $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
507 $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
508 $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
509 return sprintf($message, $userMessage, $timeMessage);
513 * A query to check for active update drafts on a particular page.
515 * @param null $minRange
518 private function activePageEditingQuery(Page $page, $minRange = null)
520 $query = $this->pageRevision->where('type', '=', 'update_draft')
521 ->where('page_id', '=', $page->id)
522 ->where('updated_at', '>', $page->updated_at)
523 ->where('created_by', '!=', auth()->user()->id)
526 if ($minRange !== null) {
527 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
534 * Gets a single revision via it's id.
538 public function getRevisionById($id)
540 return $this->pageRevision->findOrFail($id);
544 * Checks if a slug exists within a book already.
547 * @param bool|false $currentId
550 public function doesSlugExist($slug, $bookId, $currentId = false)
552 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
553 if ($currentId) $query = $query->where('id', '!=', $currentId);
554 return $query->count() > 0;
558 * Changes the related book for the specified page.
559 * Changes the book id of any relations to the page that store the book id.
564 public function changeBook($bookId, Page $page)
566 $page->book_id = $bookId;
567 foreach ($page->activity as $activity) {
568 $activity->book_id = $bookId;
571 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
578 * Change the page's parent to the given entity.
580 * @param Entity $parent
582 public function changePageParent(Page $page, Entity $parent)
584 $book = $parent->isA('book') ? $parent : $parent->book;
585 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
587 $page = $this->changeBook($book->id, $page);
589 $this->permissionService->buildJointPermissionsForEntity($book);
593 * Gets a suitable slug for the resource
594 * @param string $name
596 * @param bool|false $currentId
599 public function findSuitableSlug($name, $bookId, $currentId = false)
601 $slug = Str::slug($name);
602 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
603 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
604 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
610 * Destroy a given page along with its dependencies.
613 public function destroy(Page $page)
615 Activity::removeEntity($page);
616 $page->views()->delete();
617 $page->tags()->delete();
618 $page->revisions()->delete();
619 $page->permissions()->delete();
620 $this->permissionService->deleteJointPermissionsForEntity($page);
625 * Get the latest pages added to the system.
628 public function getRecentlyCreatedPaginated($count = 20)
630 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
634 * Get the latest pages added to the system.
637 public function getRecentlyUpdatedPaginated($count = 20)
639 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);