3 namespace BookStack\Entities\Tools;
5 use BookStack\Activity\Tools\CommentTree;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Entities\Queries\EntityQueries;
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 EntityQueries $queries,
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->queries->pages->visibleTemplates()
39 ->orderBy('name', 'asc')
42 ->withPath('/templates');
44 $draftsEnabled = auth()->check();
46 $isDraftRevision = false;
48 $editActivity = new PageEditActivity($page);
50 if ($editActivity->hasActiveEditing()) {
51 $this->warnings[] = $editActivity->activeEditingMessage();
54 // Check for a current draft version for this user
55 $userDraft = $this->queries->revisions->findLatestCurrentUserDraftsForPageId($page->id);
56 if (!is_null($userDraft)) {
57 $page->forceFill($userDraft->only(['name', 'html', 'markdown']));
58 $isDraftRevision = true;
59 $this->warnings[] = $editActivity->getEditingActiveDraftMessage($userDraft);
62 $editorType = $this->getEditorType($page);
63 $this->updateContentForEditor($page, $editorType);
67 'book' => $page->book,
68 'isDraft' => $isDraft,
69 'isDraftRevision' => $isDraftRevision,
70 'draftsEnabled' => $draftsEnabled,
71 'templates' => $templates,
72 'editor' => $editorType,
73 'comments' => new CommentTree($page),
77 protected function updateContentForEditor(Page $page, PageEditorType $editorType): void
79 $isHtml = !empty($page->html) && empty($page->markdown);
81 // HTML to markdown-clean conversion
82 if ($editorType === PageEditorType::Markdown && $isHtml && $this->requestedEditor === 'markdown-clean') {
83 $page->markdown = (new HtmlToMarkdown($page->html))->convert();
86 // Markdown to HTML conversion if we don't have HTML
87 if ($editorType->isHtmlBased() && !$isHtml) {
88 $page->html = (new MarkdownToHtml($page->markdown))->convert();
93 * Get the type of editor to show for editing the given page.
94 * Defaults based upon the current content of the page otherwise will fall back
95 * to system default but will take a requested type (if provided) if permissions allow.
97 protected function getEditorType(Page $page): PageEditorType
99 $editorType = PageEditorType::forPage($page) ?: PageEditorType::getSystemDefault();
101 // Use requested editor if valid and if we have permission
102 $requestedType = PageEditorType::fromRequestValue($this->requestedEditor);
103 if ($requestedType && userCan('editor-change')) {
104 $editorType = $requestedType;