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 * Count the pages with a particular slug within a book.
74 public function countBySlug($slug, $bookId)
76 return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count();
80 * Publish a draft page to make it a normal page.
81 * Sets the slug and updates the content.
82 * @param Page $draftPage
86 public function publishDraft(Page $draftPage, array $input)
88 $draftPage->fill($input);
90 // Save page tags if present
91 if (isset($input['tags'])) {
92 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
95 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
96 $draftPage->html = $this->formatHtml($input['html']);
97 $draftPage->text = strip_tags($draftPage->html);
98 $draftPage->draft = false;
101 $this->saveRevision($draftPage, trans('entities.pages_initial_revision'));
107 * Get a new draft page instance.
109 * @param Chapter|bool $chapter
112 public function getDraftPage(Book $book, $chapter = false)
114 $page = $this->page->newInstance();
115 $page->name = trans('entities.pages_initial_name');
116 $page->created_by = user()->id;
117 $page->updated_by = user()->id;
120 if ($chapter) $page->chapter_id = $chapter->id;
122 $book->pages()->save($page);
123 $this->permissionService->buildJointPermissionsForEntity($page);
128 * Parse te headers on the page to get a navigation menu
132 public function getPageNav(Page $page)
134 if ($page->html == '') return null;
135 libxml_use_internal_errors(true);
136 $doc = new DOMDocument();
137 $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8'));
138 $xPath = new DOMXPath($doc);
139 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
141 if (is_null($headers)) return null;
144 foreach ($headers as $header) {
145 $text = $header->nodeValue;
147 'nodeName' => strtolower($header->nodeName),
148 'level' => intval(str_replace('h', '', $header->nodeName)),
149 'link' => '#' . $header->getAttribute('id'),
150 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
157 * Formats a page's html to be tagged correctly
159 * @param string $htmlText
162 protected function formatHtml($htmlText)
164 if ($htmlText == '') return $htmlText;
165 libxml_use_internal_errors(true);
166 $doc = new DOMDocument();
167 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
169 $container = $doc->documentElement;
170 $body = $container->childNodes->item(0);
171 $childNodes = $body->childNodes;
173 // Ensure no duplicate ids are used
176 foreach ($childNodes as $index => $childNode) {
177 /** @var \DOMElement $childNode */
178 if (get_class($childNode) !== 'DOMElement') continue;
180 // Overwrite id if not a BookStack custom id
181 if ($childNode->hasAttribute('id')) {
182 $id = $childNode->getAttribute('id');
183 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
189 // Create an unique id for the element
190 // Uses the content as a basis to ensure output is the same every time
191 // the same content is passed through.
192 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
193 $newId = urlencode($contentId);
195 while (in_array($newId, $idArray)) {
196 $newId = urlencode($contentId . '-' . $loopIndex);
200 $childNode->setAttribute('id', $newId);
204 // Generate inner html as a string
206 foreach ($childNodes as $childNode) {
207 $html .= $doc->saveHTML($childNode);
215 * Search for image usage.
216 * @param $imageString
219 public function searchForImage($imageString)
221 $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get();
222 foreach ($pages as $page) {
223 $page->url = $page->getUrl();
227 return count($pages) > 0 ? $pages : false;
231 * Updates a page with any fillable data and saves it into the database.
233 * @param int $book_id
234 * @param string $input
237 public function updatePage(Page $page, $book_id, $input)
239 // Hold the old details to compare later
240 $oldHtml = $page->html;
241 $oldName = $page->name;
243 // Prevent slug being updated if no name change
244 if ($page->name !== $input['name']) {
245 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
248 // Save page tags if present
249 if (isset($input['tags'])) {
250 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
253 // Update with new details
254 $userId = user()->id;
256 $page->html = $this->formatHtml($input['html']);
257 $page->text = strip_tags($page->html);
258 if (setting('app-editor') !== 'markdown') $page->markdown = '';
259 $page->updated_by = $userId;
262 // Remove all update drafts for this user & page.
263 $this->userUpdateDraftsQuery($page, $userId)->delete();
265 // Save a revision after updating
266 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
267 $this->saveRevision($page, $input['summary']);
274 * Restores a revision's content back into a page.
277 * @param int $revisionId
280 public function restoreRevision(Page $page, Book $book, $revisionId)
282 $this->saveRevision($page);
283 $revision = $this->getRevisionById($revisionId);
284 $page->fill($revision->toArray());
285 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
286 $page->text = strip_tags($page->html);
287 $page->updated_by = user()->id;
293 * Saves a page revision into the system.
295 * @param null|string $summary
298 public function saveRevision(Page $page, $summary = null)
300 $revision = $this->pageRevision->newInstance($page->toArray());
301 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
302 $revision->page_id = $page->id;
303 $revision->slug = $page->slug;
304 $revision->book_slug = $page->book->slug;
305 $revision->created_by = user()->id;
306 $revision->created_at = $page->updated_at;
307 $revision->type = 'version';
308 $revision->summary = $summary;
311 // Clear old revisions
312 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
313 $this->pageRevision->where('page_id', '=', $page->id)
314 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
321 * Save a page update draft.
324 * @return PageRevision
326 public function saveUpdateDraft(Page $page, $data = [])
328 $userId = user()->id;
329 $drafts = $this->userUpdateDraftsQuery($page, $userId)->get();
331 if ($drafts->count() > 0) {
332 $draft = $drafts->first();
334 $draft = $this->pageRevision->newInstance();
335 $draft->page_id = $page->id;
336 $draft->slug = $page->slug;
337 $draft->book_slug = $page->book->slug;
338 $draft->created_by = $userId;
339 $draft->type = 'update_draft';
343 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
350 * Update a draft page.
355 public function updateDraftPage(Page $page, $data = [])
359 if (isset($data['html'])) {
360 $page->text = strip_tags($data['html']);
368 * The base query for getting user update drafts.
373 private function userUpdateDraftsQuery(Page $page, $userId)
375 return $this->pageRevision->where('created_by', '=', $userId)
376 ->where('type', 'update_draft')
377 ->where('page_id', '=', $page->id)
378 ->orderBy('created_at', 'desc');
382 * Checks whether a user has a draft version of a particular page or not.
387 public function hasUserGotPageDraft(Page $page, $userId)
389 return $this->userUpdateDraftsQuery($page, $userId)->count() > 0;
393 * Get the latest updated draft revision for a particular page and user.
398 public function getUserPageDraft(Page $page, $userId)
400 return $this->userUpdateDraftsQuery($page, $userId)->first();
404 * Get the notification message that informs the user that they are editing a draft page.
405 * @param PageRevision $draft
408 public function getUserPageDraftMessage(PageRevision $draft)
410 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
411 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
412 return $message . "\n" . trans('entities.pages_draft_edited_notification');
416 * Check if a page is being actively editing.
417 * Checks for edits since last page updated.
418 * Passing in a minuted range will check for edits
419 * within the last x minutes.
421 * @param null $minRange
424 public function isPageEditingActive(Page $page, $minRange = null)
426 $draftSearch = $this->activePageEditingQuery($page, $minRange);
427 return $draftSearch->count() > 0;
431 * Get a notification message concerning the editing activity on
434 * @param null $minRange
437 public function getPageEditingActiveMessage(Page $page, $minRange = null)
439 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
441 $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]);
442 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
443 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
447 * A query to check for active update drafts on a particular page.
449 * @param null $minRange
452 private function activePageEditingQuery(Page $page, $minRange = null)
454 $query = $this->pageRevision->where('type', '=', 'update_draft')
455 ->where('page_id', '=', $page->id)
456 ->where('updated_at', '>', $page->updated_at)
457 ->where('created_by', '!=', user()->id)
460 if ($minRange !== null) {
461 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
468 * Gets a single revision via it's id.
470 * @return PageRevision
472 public function getRevisionById($id)
474 return $this->pageRevision->findOrFail($id);
478 * Changes the related book for the specified page.
479 * Changes the book id of any relations to the page that store the book id.
484 public function changeBook($bookId, Page $page)
486 $page->book_id = $bookId;
487 foreach ($page->activity as $activity) {
488 $activity->book_id = $bookId;
491 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $bookId);
498 * Change the page's parent to the given entity.
500 * @param Entity $parent
502 public function changePageParent(Page $page, Entity $parent)
504 $book = $parent->isA('book') ? $parent : $parent->book;
505 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
507 $page = $this->changeBook($book->id, $page);
509 $this->permissionService->buildJointPermissionsForEntity($book);
513 * Destroy a given page along with its dependencies.
516 public function destroy(Page $page)
518 Activity::removeEntity($page);
519 $page->views()->delete();
520 $page->tags()->delete();
521 $page->revisions()->delete();
522 $page->permissions()->delete();
523 $this->permissionService->deleteJointPermissionsForEntity($page);
525 // Delete AttachedFiles
526 $attachmentService = app(AttachmentService::class);
527 foreach ($page->attachments as $attachment) {
528 $attachmentService->deleteFile($attachment);
535 * Get the latest pages added to the system.
539 public function getRecentlyCreatedPaginated($count = 20)
541 return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count);
545 * Get the latest pages added to the system.
549 public function getRecentlyUpdatedPaginated($count = 20)
551 return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count);