3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Repos\PageRepo;
7 use BookStack\Entities\Tools\Markdown\HtmlToMarkdown;
8 use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
13 protected PageRepo $pageRepo;
14 protected string $requestedEditor;
16 protected array $viewData;
17 protected array $warnings;
19 public function __construct(Page $page, PageRepo $pageRepo, string $requestedEditor)
22 $this->pageRepo = $pageRepo;
23 $this->requestedEditor = $requestedEditor;
25 $this->viewData = $this->build();
28 public function getViewData(): array
30 return $this->viewData;
33 public function getWarnings(): array
35 return $this->warnings;
38 protected function build(): array
40 $page = clone $this->page;
41 $isDraft = boolval($this->page->draft);
42 $templates = $this->pageRepo->getTemplates(10);
43 $draftsEnabled = auth()->check();
45 $isDraftRevision = false;
47 $editActivity = new PageEditActivity($page);
49 if ($editActivity->hasActiveEditing()) {
50 $this->warnings[] = $editActivity->activeEditingMessage();
53 // Check for a current draft version for this user
54 $userDraft = $this->pageRepo->getUserDraft($page);
55 if ($userDraft !== null) {
56 $page->forceFill($userDraft->only(['name', 'html', 'markdown']));
57 $isDraftRevision = true;
58 $this->warnings[] = $editActivity->getEditingActiveDraftMessage($userDraft);
61 $editorType = $this->getEditorType($page);
62 $this->updateContentForEditor($page, $editorType);
66 'book' => $page->book,
67 'isDraft' => $isDraft,
68 'isDraftRevision' => $isDraftRevision,
69 'draftsEnabled' => $draftsEnabled,
70 'templates' => $templates,
71 'editor' => $editorType,
75 protected function updateContentForEditor(Page $page, string $editorType): void
77 $isHtml = !empty($page->html) && empty($page->markdown);
79 // HTML to markdown-clean conversion
80 if ($editorType === 'markdown' && $isHtml && $this->requestedEditor === 'markdown-clean') {
81 $page->markdown = (new HtmlToMarkdown($page->html))->convert();
84 // Markdown to HTML conversion if we don't have HTML
85 if ($editorType === 'wysiwyg' && !$isHtml) {
86 $page->html = (new MarkdownToHtml($page->markdown))->convert();
91 * Get the type of editor to show for editing the given page.
92 * Defaults based upon the current content of the page otherwise will fall back
93 * to system default but will take a requested type (if provided) if permissions allow.
95 protected function getEditorType(Page $page): string
97 $editorType = $page->editor ?: self::getSystemDefaultEditor();
99 // Use requested editor if valid and if we have permission
100 $requestedType = explode('-', $this->requestedEditor)[0];
101 if (($requestedType === 'markdown' || $requestedType === 'wysiwyg') && userCan('editor-change')) {
102 $editorType = $requestedType;
109 * Get the configured system default editor.
111 public static function getSystemDefaultEditor(): string
113 return setting('app-editor') === 'markdown' ? 'markdown' : 'wysiwyg';