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 * Get a page via a specific ID.
51 * @param bool $allowDrafts
54 public function getById($id, $allowDrafts = false)
56 return $this->pageQuery($allowDrafts)->findOrFail($id);
60 * Get a page identified by the given slug.
64 * @throws NotFoundException
66 public function getBySlug($slug, $bookId)
68 $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
69 if ($page === null) throw new NotFoundException(trans('errors.page_not_found'));
74 * Search through page revisions and retrieve
75 * the last page in the current book that
76 * has a slug equal to the one given.
81 public function findPageUsingOldSlug($pageSlug, $bookSlug)
83 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
84 ->whereHas('page', function ($query) {
85 $this->permissionService->enforcePageRestrictions($query);
87 ->where('type', '=', 'version')
88 ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
89 ->with('page')->first();
90 return $revision !== null ? $revision->page : null;
94 * Get a new Page instance from the given input.
98 public function newFromInput($input)
100 $page = $this->page->fill($input);
105 * Count the pages with a particular slug within a book.
110 public function countBySlug($slug, $bookId)
112 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
116 * Publish a draft page to make it a normal page.
117 * Sets the slug and updates the content.
118 * @param Page $draftPage
119 * @param array $input
122 public function publishDraft(Page $draftPage, array $input)
124 $draftPage->fill($input);
126 // Save page tags if present
127 if (isset($input['tags'])) {
128 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
131 $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id);
132 $draftPage->html = $this->formatHtml($input['html']);
133 $draftPage->text = strip_tags($draftPage->html);
134 $draftPage->draft = false;
137 $this->saveRevision($draftPage, trans('entities.pages_initial_revision'));
143 * Get a new draft page instance.
145 * @param Chapter|bool $chapter
148 public function getDraftPage(Book $book, $chapter = false)
150 $page = $this->page->newInstance();
151 $page->name = trans('entities.pages_initial_name');
152 $page->created_by = user()->id;
153 $page->updated_by = user()->id;
156 if ($chapter) $page->chapter_id = $chapter->id;
158 $book->pages()->save($page);
159 $this->permissionService->buildJointPermissionsForEntity($page);
164 * Parse te headers on the page to get a navigation menu
168 public function getPageNav(Page $page)
170 if ($page->html == '') return null;
171 libxml_use_internal_errors(true);
172 $doc = new DOMDocument();
173 $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8'));
174 $xPath = new DOMXPath($doc);
175 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
177 if (is_null($headers)) return null;
180 foreach ($headers as $header) {
181 $text = $header->nodeValue;
183 'nodeName' => strtolower($header->nodeName),
184 'level' => intval(str_replace('h', '', $header->nodeName)),
185 'link' => '#' . $header->getAttribute('id'),
186 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
193 * Formats a page's html to be tagged correctly
195 * @param string $htmlText
198 protected function formatHtml($htmlText)
200 if ($htmlText == '') return $htmlText;
201 libxml_use_internal_errors(true);
202 $doc = new DOMDocument();
203 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
205 $container = $doc->documentElement;
206 $body = $container->childNodes->item(0);
207 $childNodes = $body->childNodes;
209 // Ensure no duplicate ids are used
212 foreach ($childNodes as $index => $childNode) {
213 /** @var \DOMElement $childNode */
214 if (get_class($childNode) !== 'DOMElement') continue;
216 // Overwrite id if not a BookStack custom id
217 if ($childNode->hasAttribute('id')) {
218 $id = $childNode->getAttribute('id');
219 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
225 // Create an unique id for the element
226 // Uses the content as a basis to ensure output is the same every time
227 // the same content is passed through.
228 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
229 $newId = urlencode($contentId);
231 while (in_array($newId, $idArray)) {
232 $newId = urlencode($contentId . '-' . $loopIndex);
236 $childNode->setAttribute('id', $newId);
240 // Generate inner html as a string
242 foreach ($childNodes as $childNode) {
243 $html .= $doc->saveHTML($childNode);
251 * Gets pages by a search term.
252 * Highlights page content for showing in results.
253 * @param string $term
254 * @param array $whereTerms
256 * @param array $paginationAppends
259 public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
261 $terms = $this->prepareSearchTerms($term);
262 $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms));
263 $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term);
264 $pages = $pageQuery->paginate($count)->appends($paginationAppends);
266 // Add highlights to page text.
267 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
268 //lookahead/behind assertions ensures cut between words
269 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
271 foreach ($pages as $page) {
272 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
273 //delimiter between occurrences
275 foreach ($matches as $line) {
276 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
279 if (count($results) > $matchLimit) {
280 $results = array_slice($results, 0, $matchLimit);
282 $result = join('... ', $results);
285 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
286 if (strlen($result) < 5) {
287 $result = $page->getExcerpt(80);
289 $page->searchSnippet = $result;
295 * Search for image usage.
296 * @param $imageString
299 public function searchForImage($imageString)
301 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
302 foreach ($pages as $page) {
303 $page->url = $page->getUrl();
307 return count($pages) > 0 ? $pages : false;
311 * Updates a page with any fillable data and saves it into the database.
313 * @param int $book_id
314 * @param string $input
317 public function updatePage(Page $page, $book_id, $input)
319 // Hold the old details to compare later
320 $oldHtml = $page->html;
321 $oldName = $page->name;
323 // Prevent slug being updated if no name change
324 if ($page->name !== $input['name']) {
325 $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id);
328 // Save page tags if present
329 if (isset($input['tags'])) {
330 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
333 // Update with new details
334 $userId = user()->id;
336 $page->html = $this->formatHtml($input['html']);
337 $page->text = strip_tags($page->html);
338 if (setting('app-editor') !== 'markdown') $page->markdown = '';
339 $page->updated_by = $userId;
342 // Remove all update drafts for this user & page.
343 $this->userUpdateDraftsQuery($page, $userId)->delete();
345 // Save a revision after updating
346 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
347 $this->saveRevision($page, $input['summary']);
354 * Restores a revision's content back into a page.
357 * @param int $revisionId
360 public function restoreRevision(Page $page, Book $book, $revisionId)
362 $this->saveRevision($page);
363 $revision = $this->getRevisionById($revisionId);
364 $page->fill($revision->toArray());
365 $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id);
366 $page->text = strip_tags($page->html);
367 $page->updated_by = user()->id;
373 * Saves a page revision into the system.
375 * @param null|string $summary
378 public function saveRevision(Page $page, $summary = null)
380 $revision = $this->pageRevision->newInstance($page->toArray());
381 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
382 $revision->page_id = $page->id;
383 $revision->slug = $page->slug;
384 $revision->book_slug = $page->book->slug;
385 $revision->created_by = user()->id;
386 $revision->created_at = $page->updated_at;
387 $revision->type = 'version';
388 $revision->summary = $summary;
391 // Clear old revisions
392 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
393 $this->pageRevision->where('page_id', '=', $page->id)
394 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
401 * Save a page update draft.
404 * @return PageRevision
406 public function saveUpdateDraft(Page $page, $data = [])
408 $userId = user()->id;
409 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
411 if ($drafts->count() > 0) {
412 $draft = $drafts->first();
414 $draft = $this->pageRevision->newInstance();
415 $draft->page_id = $page->id;
416 $draft->slug = $page->slug;
417 $draft->book_slug = $page->book->slug;
418 $draft->created_by = $userId;
419 $draft->type = 'update_draft';
423 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
430 * Update a draft page.
435 public function updateDraftPage(Page $page, $data = [])
439 if (isset($data['html'])) {
440 $page->text = strip_tags($data['html']);
448 * The base query for getting user update drafts.
453 private function userUpdateDraftsQuery(Page $page, $userId)
455 return $this->pageRevision->where('created_by', '=', $userId)
456 ->where('type', 'update_draft')
457 ->where('page_id', '=', $page->id)
458 ->orderBy('created_at', 'desc');
462 * Checks whether a user has a draft version of a particular page or not.
467 public function hasUserGotPageDraft(Page $page, $userId)
469 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
473 * Get the latest updated draft revision for a particular page and user.
478 public function getUserPageDraft(Page $page, $userId)
480 return $this->userUpdateDraftsQuery($page, $userId)->first();
484 * Get the notification message that informs the user that they are editing a draft page.
485 * @param PageRevision $draft
488 public function getUserPageDraftMessage(PageRevision $draft)
490 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
491 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
492 return $message . "\n" . trans('entities.pages_draft_edited_notification');
496 * Check if a page is being actively editing.
497 * Checks for edits since last page updated.
498 * Passing in a minuted range will check for edits
499 * within the last x minutes.
501 * @param null $minRange
504 public function isPageEditingActive(Page $page, $minRange = null)
506 $draftSearch = $this->activePageEditingQuery($page, $minRange);
507 return $draftSearch->count() > 0;
511 * Get a notification message concerning the editing activity on
514 * @param null $minRange
517 public function getPageEditingActiveMessage(Page $page, $minRange = null)
519 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
521 $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]);
522 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
523 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
527 * A query to check for active update drafts on a particular page.
529 * @param null $minRange
532 private function activePageEditingQuery(Page $page, $minRange = null)
534 $query = $this->pageRevision->where('type', '=', 'update_draft')
535 ->where('page_id', '=', $page->id)
536 ->where('updated_at', '>', $page->updated_at)
537 ->where('created_by', '!=', user()->id)
540 if ($minRange !== null) {
541 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
548 * Gets a single revision via it's id.
550 * @return PageRevision
552 public function getRevisionById($id)
554 return $this->pageRevision->findOrFail($id);
558 * Checks if a slug exists within a book already.
561 * @param bool|false $currentId
564 public function doesSlugExist($slug, $bookId, $currentId = false)
566 $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId);
567 if ($currentId) $query = $query->where('id', '!=', $currentId);
568 return $query->count() > 0;
572 * Changes the related book for the specified page.
573 * Changes the book id of any relations to the page that store the book id.
578 public function changeBook($bookId, Page $page)
580 $page->book_id = $bookId;
581 foreach ($page->activity as $activity) {
582 $activity->book_id = $bookId;
585 $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id);
592 * Change the page's parent to the given entity.
594 * @param Entity $parent
596 public function changePageParent(Page $page, Entity $parent)
598 $book = $parent->isA('book') ? $parent : $parent->book;
599 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
601 $page = $this->changeBook($book->id, $page);
603 $this->permissionService->buildJointPermissionsForEntity($book);
607 * Gets a suitable slug for the resource
608 * @param string $name
610 * @param bool|false $currentId
613 public function findSuitableSlug($name, $bookId, $currentId = false)
615 $slug = $this->nameToSlug($name);
616 while ($this->doesSlugExist($slug, $bookId, $currentId)) {
617 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
623 * Destroy a given page along with its dependencies.
626 public function destroy(Page $page)
628 Activity::removeEntity($page);
629 $page->views()->delete();
630 $page->tags()->delete();
631 $page->revisions()->delete();
632 $page->permissions()->delete();
633 $this->permissionService->deleteJointPermissionsForEntity($page);
635 // Delete AttachedFiles
636 $attachmentService = app(AttachmentService::class);
637 foreach ($page->attachments as $attachment) {
638 $attachmentService->deleteFile($attachment);
645 * Get the latest pages added to the system.
649 public function getRecentlyCreatedPaginated($count = 20)
651 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
655 * Get the latest pages added to the system.
659 public function getRecentlyUpdatedPaginated($count = 20)
661 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);