1 <?php namespace BookStack\Repos;
7 use BookStack\Exceptions\NotFoundException;
8 use BookStack\Services\AttachmentService;
12 use Illuminate\Support\Str;
14 use BookStack\PageRevision;
16 class PageRepo extends EntityRepo
19 protected $pageRevision;
23 * PageRepo constructor.
24 * @param PageRevision $pageRevision
25 * @param TagRepo $tagRepo
27 public function __construct(PageRevision $pageRevision, TagRepo $tagRepo)
29 $this->pageRevision = $pageRevision;
30 $this->tagRepo = $tagRepo;
31 parent::__construct();
35 * Base query for getting pages, Takes restrictions into account.
36 * @param bool $allowDrafts
39 private function pageQuery($allowDrafts = false)
41 $query = $this->permissionService->enforcePageRestrictions($this->page, 'view');
43 $query = $query->where('draft', '=', false);
49 * Search through page revisions and retrieve
50 * the last page in the current book that
51 * has a slug equal to the one given.
56 public function findPageUsingOldSlug($pageSlug, $bookSlug)
58 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
59 ->whereHas('page', function ($query) {
60 $this->permissionService->enforcePageRestrictions($query);
62 ->where('type', '=', 'version')
63 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
64 ->with('page')->first();
65 return $revision !== null ? $revision->page : null;
69 * Get a new Page instance from the given input.
73 public function newFromInput($input)
75 $page = $this->page->fill($input);
80 * Count the pages with a particular slug within a book.
85 public function countBySlug($slug, $bookId)
87 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
91 * Publish a draft page to make it a normal page.
92 * Sets the slug and updates the content.
93 * @param Page $draftPage
97 public function publishDraft(Page $draftPage, array $input)
99 $draftPage->fill($input);
101 // Save page tags if present
102 if (isset($input['tags'])) {
103 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
106 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
107 $draftPage->html = $this->formatHtml($input['html']);
108 $draftPage->text = strip_tags($draftPage->html);
109 $draftPage->draft = false;
112 $this->saveRevision($draftPage, trans('entities.pages_initial_revision'));
118 * Get a new draft page instance.
120 * @param Chapter|bool $chapter
123 public function getDraftPage(Book $book, $chapter = false)
125 $page = $this->page->newInstance();
126 $page->name = trans('entities.pages_initial_name');
127 $page->created_by = user()->id;
128 $page->updated_by = user()->id;
131 if ($chapter) $page->chapter_id = $chapter->id;
133 $book->pages()->save($page);
134 $this->permissionService->buildJointPermissionsForEntity($page);
139 * Parse te headers on the page to get a navigation menu
143 public function getPageNav(Page $page)
145 if ($page->html == '') return null;
146 libxml_use_internal_errors(true);
147 $doc = new DOMDocument();
148 $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8'));
149 $xPath = new DOMXPath($doc);
150 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
152 if (is_null($headers)) return null;
155 foreach ($headers as $header) {
156 $text = $header->nodeValue;
158 'nodeName' => strtolower($header->nodeName),
159 'level' => intval(str_replace('h', '', $header->nodeName)),
160 'link' => '#' . $header->getAttribute('id'),
161 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
168 * Formats a page's html to be tagged correctly
170 * @param string $htmlText
173 protected function formatHtml($htmlText)
175 if ($htmlText == '') return $htmlText;
176 libxml_use_internal_errors(true);
177 $doc = new DOMDocument();
178 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
180 $container = $doc->documentElement;
181 $body = $container->childNodes->item(0);
182 $childNodes = $body->childNodes;
184 // Ensure no duplicate ids are used
187 foreach ($childNodes as $index => $childNode) {
188 /** @var \DOMElement $childNode */
189 if (get_class($childNode) !== 'DOMElement') continue;
191 // Overwrite id if not a BookStack custom id
192 if ($childNode->hasAttribute('id')) {
193 $id = $childNode->getAttribute('id');
194 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
200 // Create an unique id for the element
201 // Uses the content as a basis to ensure output is the same every time
202 // the same content is passed through.
203 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
204 $newId = urlencode($contentId);
206 while (in_array($newId, $idArray)) {
207 $newId = urlencode($contentId . '-' . $loopIndex);
211 $childNode->setAttribute('id', $newId);
215 // Generate inner html as a string
217 foreach ($childNodes as $childNode) {
218 $html .= $doc->saveHTML($childNode);
226 * Gets pages by a search term.
227 * Highlights page content for showing in results.
228 * @param string $term
229 * @param array $whereTerms
231 * @param array $paginationAppends
234 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
236 $terms = $this->prepareSearchTerms($term);
237 $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms));
238 $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term);
239 $pages = $pageQuery->paginate($count)->appends($paginationAppends);
241 // Add highlights to page text.
242 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
243 //lookahead/behind assertions ensures cut between words
244 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
246 foreach ($pages as $page) {
247 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
248 //delimiter between occurrences
250 foreach ($matches as $line) {
251 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
254 if (count($results) > $matchLimit) {
255 $results = array_slice($results, 0, $matchLimit);
257 $result = join('... ', $results);
260 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
261 if (strlen($result) < 5) {
262 $result = $page->getExcerpt(80);
264 $page->searchSnippet = $result;
270 * Search for image usage.
271 * @param $imageString
274 public function searchForImage($imageString)
276 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
277 foreach ($pages as $page) {
278 $page->url = $page->getUrl();
282 return count($pages) > 0 ? $pages : false;
286 * Updates a page with any fillable data and saves it into the database.
288 * @param int $book_id
289 * @param string $input
292 public function updatePage(Page $page, $book_id, $input)
294 // Hold the old details to compare later
295 $oldHtml = $page->html;
296 $oldName = $page->name;
298 // Prevent slug being updated if no name change
299 if ($page->name !== $input['name']) {
300 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
303 // Save page tags if present
304 if (isset($input['tags'])) {
305 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
308 // Update with new details
309 $userId = user()->id;
311 $page->html = $this->formatHtml($input['html']);
312 $page->text = strip_tags($page->html);
313 if (setting('app-editor') !== 'markdown') $page->markdown = '';
314 $page->updated_by = $userId;
317 // Remove all update drafts for this user & page.
318 $this->userUpdateDraftsQuery($page, $userId)->delete();
320 // Save a revision after updating
321 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
322 $this->saveRevision($page, $input['summary']);
329 * Restores a revision's content back into a page.
332 * @param int $revisionId
335 public function restoreRevision(Page $page, Book $book, $revisionId)
337 $this->saveRevision($page);
338 $revision = $this->getRevisionById($revisionId);
339 $page->fill($revision->toArray());
340 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
341 $page->text = strip_tags($page->html);
342 $page->updated_by = user()->id;
348 * Saves a page revision into the system.
350 * @param null|string $summary
353 public function saveRevision(Page $page, $summary = null)
355 $revision = $this->pageRevision->newInstance($page->toArray());
356 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
357 $revision->page_id = $page->id;
358 $revision->slug = $page->slug;
359 $revision->book_slug = $page->book->slug;
360 $revision->created_by = user()->id;
361 $revision->created_at = $page->updated_at;
362 $revision->type = 'version';
363 $revision->summary = $summary;
366 // Clear old revisions
367 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
368 $this->pageRevision->where('page_id', '=', $page->id)
369 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
376 * Save a page update draft.
379 * @return PageRevision
381 public function saveUpdateDraft(Page $page, $data = [])
383 $userId = user()->id;
384 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
386 if ($drafts->count() > 0) {
387 $draft = $drafts->first();
389 $draft = $this->pageRevision->newInstance();
390 $draft->page_id = $page->id;
391 $draft->slug = $page->slug;
392 $draft->book_slug = $page->book->slug;
393 $draft->created_by = $userId;
394 $draft->type = 'update_draft';
398 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
405 * Update a draft page.
410 public function updateDraftPage(Page $page, $data = [])
414 if (isset($data['html'])) {
415 $page->text = strip_tags($data['html']);
423 * The base query for getting user update drafts.
428 private function userUpdateDraftsQuery(Page $page, $userId)
430 return $this->pageRevision->where('created_by', '=', $userId)
431 ->where('type', 'update_draft')
432 ->where('page_id', '=', $page->id)
433 ->orderBy('created_at', 'desc');
437 * Checks whether a user has a draft version of a particular page or not.
442 public function hasUserGotPageDraft(Page $page, $userId)
444 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
448 * Get the latest updated draft revision for a particular page and user.
453 public function getUserPageDraft(Page $page, $userId)
455 return $this->userUpdateDraftsQuery($page, $userId)->first();
459 * Get the notification message that informs the user that they are editing a draft page.
460 * @param PageRevision $draft
463 public function getUserPageDraftMessage(PageRevision $draft)
465 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
466 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
467 return $message . "\n" . trans('entities.pages_draft_edited_notification');
471 * Check if a page is being actively editing.
472 * Checks for edits since last page updated.
473 * Passing in a minuted range will check for edits
474 * within the last x minutes.
476 * @param null $minRange
479 public function isPageEditingActive(Page $page, $minRange = null)
481 $draftSearch = $this->activePageEditingQuery($page, $minRange);
482 return $draftSearch->count() > 0;
486 * Get a notification message concerning the editing activity on
489 * @param null $minRange
492 public function getPageEditingActiveMessage(Page $page, $minRange = null)
494 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
496 $userMessage = $pageDraftEdits->count() > 1 ? trans('entities.pages_draft_edit_active.start_a', ['count' => $pageDraftEdits->count()]): trans('entities.pages_draft_edit_active.start_b', ['userName' => $pageDraftEdits->first()->createdBy->name]);
497 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
498 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
502 * A query to check for active update drafts on a particular page.
504 * @param null $minRange
507 private function activePageEditingQuery(Page $page, $minRange = null)
509 $query = $this->pageRevision->where('type', '=', 'update_draft')
510 ->where('page_id', '=', $page->id)
511 ->where('updated_at', '>', $page->updated_at)
512 ->where('created_by', '!=', user()->id)
515 if ($minRange !== null) {
516 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
523 * Gets a single revision via it's id.
525 * @return PageRevision
527 public function getRevisionById($id)
529 return $this->pageRevision->findOrFail($id);
533 * Checks if a slug exists within a book already.
536 * @param bool|false $currentId
539 public function doesSlugExist($slug, $bookId, $currentId = false)
541 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
542 if ($currentId) $query = $query->where('id', '!=', $currentId);
543 return $query->count() > 0;
547 * Changes the related book for the specified page.
548 * Changes the book id of any relations to the page that store the book id.
553 public function changeBook($bookId, Page $page)
555 $page->book_id = $bookId;
556 foreach ($page->activity as $activity) {
557 $activity->book_id = $bookId;
560 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
567 * Change the page's parent to the given entity.
569 * @param Entity $parent
571 public function changePageParent(Page $page, Entity $parent)
573 $book = $parent->isA('book') ? $parent : $parent->book;
574 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
576 $page = $this->changeBook($book->id, $page);
578 $this->permissionService->buildJointPermissionsForEntity($book);
582 * Gets a suitable slug for the resource
583 * @param string $name
585 * @param bool|false $currentId
588 public function findSuitableSlug($name, $bookId, $currentId = false)
590 $slug = $this->nameToSlug($name);
591 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
592 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
598 * Destroy a given page along with its dependencies.
601 public function destroy(Page $page)
603 Activity::removeEntity($page);
604 $page->views()->delete();
605 $page->tags()->delete();
606 $page->revisions()->delete();
607 $page->permissions()->delete();
608 $this->permissionService->deleteJointPermissionsForEntity($page);
610 // Delete AttachedFiles
611 $attachmentService = app(AttachmentService::class);
612 foreach ($page->attachments as $attachment) {
613 $attachmentService->deleteFile($attachment);
620 * Get the latest pages added to the system.
624 public function getRecentlyCreatedPaginated($count = 20)
626 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
630 * Get the latest pages added to the system.
634 public function getRecentlyUpdatedPaginated($count = 20)
636 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);