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->permissionService->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->permissionService->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|bool $chapter
160 public function getDraftPage(Book $book, $chapter = false)
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);
171 $this->permissionService->buildJointPermissionsForEntity($page);
176 * Formats a page's html to be tagged correctly
178 * @param string $htmlText
181 protected function formatHtml($htmlText)
183 if ($htmlText == '') return $htmlText;
184 libxml_use_internal_errors(true);
185 $doc = new DOMDocument();
186 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
188 $container = $doc->documentElement;
189 $body = $container->childNodes->item(0);
190 $childNodes = $body->childNodes;
192 // Ensure no duplicate ids are used
195 foreach ($childNodes as $index => $childNode) {
196 /** @var \DOMElement $childNode */
197 if (get_class($childNode) !== 'DOMElement') continue;
199 // Overwrite id if not a BookStack custom id
200 if ($childNode->hasAttribute('id')) {
201 $id = $childNode->getAttribute('id');
202 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
208 // Create an unique id for the element
209 // Uses the content as a basis to ensure output is the same every time
210 // the same content is passed through.
211 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
212 $newId = urlencode($contentId);
214 while (in_array($newId, $idArray)) {
215 $newId = urlencode($contentId . '-' . $loopIndex);
219 $childNode->setAttribute('id', $newId);
223 // Generate inner html as a string
225 foreach ($childNodes as $childNode) {
226 $html .= $doc->saveHTML($childNode);
234 * Gets pages by a search term.
235 * Highlights page content for showing in results.
236 * @param string $term
237 * @param array $whereTerms
239 * @param array $paginationAppends
242 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
244 $terms = $this->prepareSearchTerms($term);
245 $pages = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms))
246 ->paginate($count)->appends($paginationAppends);
248 // Add highlights to page text.
249 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
250 //lookahead/behind assertions ensures cut between words
251 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
253 foreach ($pages as $page) {
254 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
255 //delimiter between occurrences
257 foreach ($matches as $line) {
258 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
261 if (count($results) > $matchLimit) {
262 $results = array_slice($results, 0, $matchLimit);
264 $result = join('... ', $results);
267 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
268 if (strlen($result) < 5) {
269 $result = $page->getExcerpt(80);
271 $page->searchSnippet = $result;
277 * Search for image usage.
278 * @param $imageString
281 public function searchForImage($imageString)
283 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
284 foreach ($pages as $page) {
285 $page->url = $page->getUrl();
289 return count($pages) > 0 ? $pages : false;
293 * Updates a page with any fillable data and saves it into the database.
295 * @param int $book_id
296 * @param string $input
299 public function updatePage(Page $page, $book_id, $input)
301 // Save a revision before updating
302 if ($page->html !== $input['html'] || $page->name !== $input['name']) {
303 $this->saveRevision($page);
306 // Prevent slug being updated if no name change
307 if ($page->name !== $input['name']) {
308 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
311 // Update with new details
312 $userId = auth()->user()->id;
314 $page->html = $this->formatHtml($input['html']);
315 $page->text = strip_tags($page->html);
316 if (setting('app-editor') !== 'markdown') $page->markdown = '';
317 $page->updated_by = $userId;
320 // Remove all update drafts for this user & page.
321 $this->userUpdateDraftsQuery($page, $userId)->delete();
327 * Restores a revision's content back into a page.
330 * @param int $revisionId
333 public function restoreRevision(Page $page, Book $book, $revisionId)
335 $this->saveRevision($page);
336 $revision = $this->getRevisionById($revisionId);
337 $page->fill($revision->toArray());
338 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
339 $page->text = strip_tags($page->html);
340 $page->updated_by = auth()->user()->id;
346 * Saves a page revision into the system.
350 public function saveRevision(Page $page)
352 $revision = $this->pageRevision->fill($page->toArray());
353 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
354 $revision->page_id = $page->id;
355 $revision->slug = $page->slug;
356 $revision->book_slug = $page->book->slug;
357 $revision->created_by = auth()->user()->id;
358 $revision->created_at = $page->updated_at;
359 $revision->type = 'version';
361 // Clear old revisions
362 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
363 $this->pageRevision->where('page_id', '=', $page->id)
364 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
370 * Save a page update draft.
373 * @return PageRevision
375 public function saveUpdateDraft(Page $page, $data = [])
377 $userId = auth()->user()->id;
378 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
380 if ($drafts->count() > 0) {
381 $draft = $drafts->first();
383 $draft = $this->pageRevision->newInstance();
384 $draft->page_id = $page->id;
385 $draft->slug = $page->slug;
386 $draft->book_slug = $page->book->slug;
387 $draft->created_by = $userId;
388 $draft->type = 'update_draft';
392 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
399 * Update a draft page.
404 public function updateDraftPage(Page $page, $data = [])
408 if (isset($data['html'])) {
409 $page->text = strip_tags($data['html']);
417 * The base query for getting user update drafts.
422 private function userUpdateDraftsQuery(Page $page, $userId)
424 return $this->pageRevision->where('created_by', '=', $userId)
425 ->where('type', 'update_draft')
426 ->where('page_id', '=', $page->id)
427 ->orderBy('created_at', 'desc');
431 * Checks whether a user has a draft version of a particular page or not.
436 public function hasUserGotPageDraft(Page $page, $userId)
438 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
442 * Get the latest updated draft revision for a particular page and user.
447 public function getUserPageDraft(Page $page, $userId)
449 return $this->userUpdateDraftsQuery($page, $userId)->first();
453 * Get the notification message that informs the user that they are editing a draft page.
454 * @param PageRevision $draft
457 public function getUserPageDraftMessage(PageRevision $draft)
459 $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.';
460 if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) {
461 $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft.";
467 * Check if a page is being actively editing.
468 * Checks for edits since last page updated.
469 * Passing in a minuted range will check for edits
470 * within the last x minutes.
472 * @param null $minRange
475 public function isPageEditingActive(Page $page, $minRange = null)
477 $draftSearch = $this->activePageEditingQuery($page, $minRange);
478 return $draftSearch->count() > 0;
482 * Get a notification message concerning the editing activity on
485 * @param null $minRange
488 public function getPageEditingActiveMessage(Page $page, $minRange = null)
490 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
491 $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has';
492 $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes';
493 $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!';
494 return sprintf($message, $userMessage, $timeMessage);
498 * A query to check for active update drafts on a particular page.
500 * @param null $minRange
503 private function activePageEditingQuery(Page $page, $minRange = null)
505 $query = $this->pageRevision->where('type', '=', 'update_draft')
506 ->where('page_id', '=', $page->id)
507 ->where('updated_at', '>', $page->updated_at)
508 ->where('created_by', '!=', auth()->user()->id)
511 if ($minRange !== null) {
512 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
519 * Gets a single revision via it's id.
523 public function getRevisionById($id)
525 return $this->pageRevision->findOrFail($id);
529 * Checks if a slug exists within a book already.
532 * @param bool|false $currentId
535 public function doesSlugExist($slug, $bookId, $currentId = false)
537 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
538 if ($currentId) $query = $query->where('id', '!=', $currentId);
539 return $query->count() > 0;
543 * Changes the related book for the specified page.
544 * Changes the book id of any relations to the page that store the book id.
549 public function changeBook($bookId, Page $page)
551 $page->book_id = $bookId;
552 foreach ($page->activity as $activity) {
553 $activity->book_id = $bookId;
556 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
562 * Gets a suitable slug for the resource
565 * @param bool|false $currentId
568 public function findSuitableSlug($name, $bookId, $currentId = false)
570 $slug = Str::slug($name);
571 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
572 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
578 * Destroy a given page along with its dependencies.
581 public function destroy(Page $page)
583 Activity::removeEntity($page);
584 $page->views()->delete();
585 $page->revisions()->delete();
586 $page->permissions()->delete();
587 $this->permissionService->deleteJointPermissionsForEntity($page);
592 * Get the latest pages added to the system.
595 public function getRecentlyCreatedPaginated($count = 20)
597 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
601 * Get the latest pages added to the system.
604 public function getRecentlyUpdatedPaginated($count = 20)
606 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);