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 * Publish a draft page to make it a normal page.
115 * Sets the slug and updates the content.
116 * @param Page $draftPage
117 * @param array $input
120 public function publishDraft(Page $draftPage, array $input)
122 $draftPage->fill($input);
124 // Save page tags if present
125 if (isset($input['tags'])) {
126 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
129 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
130 $draftPage->html = $this->formatHtml($input['html']);
131 $draftPage->text = strip_tags($draftPage->html);
132 $draftPage->draft = false;
135 $this->saveRevision($draftPage, 'Initial Publish');
141 * Get a new draft page instance.
143 * @param Chapter|bool $chapter
146 public function getDraftPage(Book $book, $chapter = false)
148 $page = $this->page->newInstance();
149 $page->name = 'New Page';
150 $page->created_by = auth()->user()->id;
151 $page->updated_by = auth()->user()->id;
154 if ($chapter) $page->chapter_id = $chapter->id;
156 $book->pages()->save($page);
157 $this->permissionService->buildJointPermissionsForEntity($page);
162 * Formats a page's html to be tagged correctly
164 * @param string $htmlText
167 protected function formatHtml($htmlText)
169 if ($htmlText == '') return $htmlText;
170 libxml_use_internal_errors(true);
171 $doc = new DOMDocument();
172 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
174 $container = $doc->documentElement;
175 $body = $container->childNodes->item(0);
176 $childNodes = $body->childNodes;
178 // Ensure no duplicate ids are used
181 foreach ($childNodes as $index => $childNode) {
182 /** @var \DOMElement $childNode */
183 if (get_class($childNode) !== 'DOMElement') continue;
185 // Overwrite id if not a BookStack custom id
186 if ($childNode->hasAttribute('id')) {
187 $id = $childNode->getAttribute('id');
188 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
194 // Create an unique id for the element
195 // Uses the content as a basis to ensure output is the same every time
196 // the same content is passed through.
197 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
198 $newId = urlencode($contentId);
200 while (in_array($newId, $idArray)) {
201 $newId = urlencode($contentId . '-' . $loopIndex);
205 $childNode->setAttribute('id', $newId);
209 // Generate inner html as a string
211 foreach ($childNodes as $childNode) {
212 $html .= $doc->saveHTML($childNode);
220 * Gets pages by a search term.
221 * Highlights page content for showing in results.
222 * @param string $term
223 * @param array $whereTerms
225 * @param array $paginationAppends
228 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
230 $terms = $this->prepareSearchTerms($term);
231 $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms));
232 $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term);
233 $pages = $pageQuery->paginate($count)->appends($paginationAppends);
235 // Add highlights to page text.
236 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
237 //lookahead/behind assertions ensures cut between words
238 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
240 foreach ($pages as $page) {
241 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
242 //delimiter between occurrences
244 foreach ($matches as $line) {
245 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
248 if (count($results) > $matchLimit) {
249 $results = array_slice($results, 0, $matchLimit);
251 $result = join('... ', $results);
254 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
255 if (strlen($result) < 5) {
256 $result = $page->getExcerpt(80);
258 $page->searchSnippet = $result;
264 * Search for image usage.
265 * @param $imageString
268 public function searchForImage($imageString)
270 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
271 foreach ($pages as $page) {
272 $page->url = $page->getUrl();
276 return count($pages) > 0 ? $pages : false;
280 * Updates a page with any fillable data and saves it into the database.
282 * @param int $book_id
283 * @param string $input
286 public function updatePage(Page $page, $book_id, $input)
288 // Hold the old details to compare later
289 $oldHtml = $page->html;
290 $oldName = $page->name;
292 // Prevent slug being updated if no name change
293 if ($page->name !== $input['name']) {
294 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
297 // Save page tags if present
298 if (isset($input['tags'])) {
299 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
302 // Update with new details
303 $userId = auth()->user()->id;
305 $page->html = $this->formatHtml($input['html']);
306 $page->text = strip_tags($page->html);
307 if (setting('app-editor') !== 'markdown') $page->markdown = '';
308 $page->updated_by = $userId;
311 // Remove all update drafts for this user & page.
312 $this->userUpdateDraftsQuery($page, $userId)->delete();
314 // Save a revision after updating
315 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
316 $this->saveRevision($page, $input['summary']);
323 * Restores a revision's content back into a page.
326 * @param int $revisionId
329 public function restoreRevision(Page $page, Book $book, $revisionId)
331 $this->saveRevision($page);
332 $revision = $this->getRevisionById($revisionId);
333 $page->fill($revision->toArray());
334 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
335 $page->text = strip_tags($page->html);
336 $page->updated_by = auth()->user()->id;
342 * Saves a page revision into the system.
344 * @param null|string $summary
347 public function saveRevision(Page $page, $summary = null)
349 $revision = $this->pageRevision->newInstance($page->toArray());
350 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
351 $revision->page_id = $page->id;
352 $revision->slug = $page->slug;
353 $revision->book_slug = $page->book->slug;
354 $revision->created_by = auth()->user()->id;
355 $revision->created_at = $page->updated_at;
356 $revision->type = 'version';
357 $revision->summary = $summary;
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();
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);
563 * Change the page's parent to the given entity.
565 * @param Entity $parent
567 public function changePageParent(Page $page, Entity $parent)
569 $book = $parent->isA('book') ? $parent : $parent->book;
570 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
572 $page = $this->changeBook($book->id, $page);
574 $this->permissionService->buildJointPermissionsForEntity($book);
578 * Gets a suitable slug for the resource
579 * @param string $name
581 * @param bool|false $currentId
584 public function findSuitableSlug($name, $bookId, $currentId = false)
586 $slug = Str::slug($name);
587 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
588 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
589 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
595 * Destroy a given page along with its dependencies.
598 public function destroy(Page $page)
600 Activity::removeEntity($page);
601 $page->views()->delete();
602 $page->tags()->delete();
603 $page->revisions()->delete();
604 $page->permissions()->delete();
605 $this->permissionService->deleteJointPermissionsForEntity($page);
610 * Get the latest pages added to the system.
613 public function getRecentlyCreatedPaginated($count = 20)
615 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
619 * Get the latest pages added to the system.
622 public function getRecentlyUpdatedPaginated($count = 20)
624 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);