3 namespace BookStack\Entities\Tools;
5 use BookStack\Activity\Tools\CommentTree;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Entities\Repos\PageRepo;
8 use BookStack\Entities\Tools\Markdown\HtmlToMarkdown;
9 use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
13 protected array $viewData;
14 protected array $warnings;
16 public function __construct(
18 protected PageRepo $pageRepo,
19 protected string $requestedEditor
21 $this->viewData = $this->build();
24 public function getViewData(): array
26 return $this->viewData;
29 public function getWarnings(): array
31 return $this->warnings;
34 protected function build(): array
36 $page = clone $this->page;
37 $isDraft = boolval($this->page->draft);
38 $templates = $this->pageRepo->getTemplates(10);
39 $draftsEnabled = auth()->check();
41 $isDraftRevision = false;
43 $editActivity = new PageEditActivity($page);
45 if ($editActivity->hasActiveEditing()) {
46 $this->warnings[] = $editActivity->activeEditingMessage();
49 // Check for a current draft version for this user
50 $userDraft = $this->pageRepo->getUserDraft($page);
51 if ($userDraft !== null) {
52 $page->forceFill($userDraft->only(['name', 'html', 'markdown']));
53 $isDraftRevision = true;
54 $this->warnings[] = $editActivity->getEditingActiveDraftMessage($userDraft);
57 $editorType = $this->getEditorType($page);
58 $this->updateContentForEditor($page, $editorType);
62 'book' => $page->book,
63 'isDraft' => $isDraft,
64 'isDraftRevision' => $isDraftRevision,
65 'draftsEnabled' => $draftsEnabled,
66 'templates' => $templates,
67 'editor' => $editorType,
68 'comments' => new CommentTree($page),
72 protected function updateContentForEditor(Page $page, string $editorType): void
74 $isHtml = !empty($page->html) && empty($page->markdown);
76 // HTML to markdown-clean conversion
77 if ($editorType === 'markdown' && $isHtml && $this->requestedEditor === 'markdown-clean') {
78 $page->markdown = (new HtmlToMarkdown($page->html))->convert();
81 // Markdown to HTML conversion if we don't have HTML
82 if ($editorType === 'wysiwyg' && !$isHtml) {
83 $page->html = (new MarkdownToHtml($page->markdown))->convert();
88 * Get the type of editor to show for editing the given page.
89 * Defaults based upon the current content of the page otherwise will fall back
90 * to system default but will take a requested type (if provided) if permissions allow.
92 protected function getEditorType(Page $page): string
94 $editorType = $page->editor ?: self::getSystemDefaultEditor();
96 // Use requested editor if valid and if we have permission
97 $requestedType = explode('-', $this->requestedEditor)[0];
98 if (($requestedType === 'markdown' || $requestedType === 'wysiwyg') && userCan('editor-change')) {
99 $editorType = $requestedType;
106 * Get the configured system default editor.
108 public static function getSystemDefaultEditor(): string
110 return setting('app-editor') === 'markdown' ? 'markdown' : 'wysiwyg';