3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Tools\Markdown\CustomListItemRenderer;
7 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
8 use BookStack\Entities\Tools\Markdown\CustomTaskListMarkerRenderer;
9 use BookStack\Exceptions\ImageUploadException;
10 use BookStack\Facades\Theme;
11 use BookStack\Theming\ThemeEvents;
12 use BookStack\Uploads\ImageRepo;
13 use BookStack\Util\HtmlContentFilter;
17 use Illuminate\Support\Str;
18 use League\CommonMark\Block\Element\ListItem;
19 use League\CommonMark\CommonMarkConverter;
20 use League\CommonMark\Environment;
21 use League\CommonMark\Extension\Table\TableExtension;
22 use League\CommonMark\Extension\TaskList\TaskListExtension;
23 use League\CommonMark\Extension\TaskList\TaskListItemMarker;
24 use League\CommonMark\Extension\TaskList\TaskListItemMarkerParser;
25 use League\CommonMark\Extension\TaskList\TaskListItemMarkerRenderer;
32 * PageContent constructor.
34 public function __construct(Page $page)
40 * Update the content of the page with new provided HTML.
42 public function setNewHTML(string $html)
44 $html = $this->extractBase64Images($this->page, $html);
45 $this->page->html = $this->formatHtml($html);
46 $this->page->text = $this->toPlainText();
47 $this->page->markdown = '';
51 * Update the content of the page with new provided Markdown content.
53 public function setNewMarkdown(string $markdown)
55 $this->page->markdown = $markdown;
56 $html = $this->markdownToHtml($markdown);
57 $this->page->html = $this->formatHtml($html);
58 $this->page->text = $this->toPlainText();
62 * Convert the given Markdown content to a HTML string.
64 protected function markdownToHtml(string $markdown): string
66 $environment = Environment::createCommonMarkEnvironment();
67 $environment->addExtension(new TableExtension());
68 $environment->addExtension(new TaskListExtension());
69 $environment->addExtension(new CustomStrikeThroughExtension());
70 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
71 $converter = new CommonMarkConverter([], $environment);
73 $environment->addBlockRenderer(ListItem::class, new CustomListItemRenderer(), 10);
75 return $converter->convertToHtml($markdown);
79 * Convert all base64 image data to saved images.
81 public function extractBase64Images(Page $page, string $htmlText): string
83 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
87 $doc = $this->loadDocumentFromHtml($htmlText);
88 $container = $doc->documentElement;
89 $body = $container->childNodes->item(0);
90 $childNodes = $body->childNodes;
91 $xPath = new DOMXPath($doc);
92 $imageRepo = app()->make(ImageRepo::class);
93 $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
95 // Get all img elements with image data blobs
96 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
97 foreach ($imageNodes as $imageNode) {
98 $imageSrc = $imageNode->getAttribute('src');
99 [$dataDefinition, $base64ImageData] = explode(',', $imageSrc, 2);
100 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png');
102 // Validate extension
103 if (!in_array($extension, $allowedExtensions)) {
104 $imageNode->setAttribute('src', '');
108 // Save image from data with a random name
109 $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension;
112 $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $page->id);
113 $imageNode->setAttribute('src', $image->url);
114 } catch (ImageUploadException $exception) {
115 $imageNode->setAttribute('src', '');
119 // Generate inner html as a string
121 foreach ($childNodes as $childNode) {
122 $html .= $doc->saveHTML($childNode);
129 * Formats a page's html to be tagged correctly within the system.
131 protected function formatHtml(string $htmlText): string
133 if (empty($htmlText)) {
137 $doc = $this->loadDocumentFromHtml($htmlText);
138 $container = $doc->documentElement;
139 $body = $container->childNodes->item(0);
140 $childNodes = $body->childNodes;
141 $xPath = new DOMXPath($doc);
143 // Set ids on top-level nodes
145 foreach ($childNodes as $index => $childNode) {
146 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
147 if ($newId && $newId !== $oldId) {
148 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
152 // Ensure no duplicate ids within child items
153 $idElems = $xPath->query('//body//*//*[@id]');
154 foreach ($idElems as $domElem) {
155 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
156 if ($newId && $newId !== $oldId) {
157 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
161 // Generate inner html as a string
163 foreach ($childNodes as $childNode) {
164 $html .= $doc->saveHTML($childNode);
171 * Update the all links to the $old location to instead point to $new.
173 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
175 $old = str_replace('"', '', $old);
176 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
177 foreach ($matchingLinks as $domElem) {
178 $domElem->setAttribute('href', $new);
183 * Set a unique id on the given DOMElement.
184 * A map for existing ID's should be passed in to check for current existence.
185 * Returns a pair of strings in the format [old_id, new_id].
187 protected function setUniqueId(\DOMNode $element, array &$idMap): array
189 if (get_class($element) !== 'DOMElement') {
193 // Stop if there's an existing valid id that has not already been used.
194 $existingId = $element->getAttribute('id');
195 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
196 $idMap[$existingId] = true;
198 return [$existingId, $existingId];
201 // Create an unique id for the element
202 // Uses the content as a basis to ensure output is the same every time
203 // the same content is passed through.
204 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
205 $newId = urlencode($contentId);
208 while (isset($idMap[$newId])) {
209 $newId = urlencode($contentId . '-' . $loopIndex);
213 $element->setAttribute('id', $newId);
214 $idMap[$newId] = true;
216 return [$existingId, $newId];
220 * Get a plain-text visualisation of this page.
222 protected function toPlainText(): string
224 $html = $this->render(true);
226 return html_entity_decode(strip_tags($html));
230 * Render the page for viewing.
232 public function render(bool $blankIncludes = false): string
234 $content = $this->page->html ?? '';
236 if (!config('app.allow_content_scripts')) {
237 $content = HtmlContentFilter::removeScripts($content);
240 if ($blankIncludes) {
241 $content = $this->blankPageIncludes($content);
243 $content = $this->parsePageIncludes($content);
250 * Parse the headers on the page to get a navigation menu.
252 public function getNavigation(string $htmlContent): array
254 if (empty($htmlContent)) {
258 $doc = $this->loadDocumentFromHtml($htmlContent);
259 $xPath = new DOMXPath($doc);
260 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
262 return $headers ? $this->headerNodesToLevelList($headers) : [];
266 * Convert a DOMNodeList into an array of readable header attributes
267 * with levels normalised to the lower header level.
269 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
271 $tree = collect($nodeList)->map(function ($header) {
272 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
273 $text = mb_substr($text, 0, 100);
276 'nodeName' => strtolower($header->nodeName),
277 'level' => intval(str_replace('h', '', $header->nodeName)),
278 'link' => '#' . $header->getAttribute('id'),
281 })->filter(function ($header) {
282 return mb_strlen($header['text']) > 0;
285 // Shift headers if only smaller headers have been used
286 $levelChange = ($tree->pluck('level')->min() - 1);
287 $tree = $tree->map(function ($header) use ($levelChange) {
288 $header['level'] -= ($levelChange);
293 return $tree->toArray();
297 * Remove any page include tags within the given HTML.
299 protected function blankPageIncludes(string $html): string
301 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
305 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
307 protected function parsePageIncludes(string $html): string
310 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
312 foreach ($matches[1] as $index => $includeId) {
313 $fullMatch = $matches[0][$index];
314 $splitInclude = explode('#', $includeId, 2);
316 // Get page id from reference
317 $pageId = intval($splitInclude[0]);
318 if (is_nan($pageId)) {
322 // Find page and skip this if page not found
323 $matchedPage = Page::visible()->find($pageId);
324 if ($matchedPage === null) {
325 $html = str_replace($fullMatch, '', $html);
329 // If we only have page id, just insert all page html and continue.
330 if (count($splitInclude) === 1) {
331 $html = str_replace($fullMatch, $matchedPage->html, $html);
335 // Create and load HTML into a document
336 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
337 $html = str_replace($fullMatch, trim($innerContent), $html);
344 * Fetch the content from a specific section of the given page.
346 protected function fetchSectionOfPage(Page $page, string $sectionId): string
348 $topLevelTags = ['table', 'ul', 'ol'];
349 $doc = $this->loadDocumentFromHtml($page->html);
351 // Search included content for the id given and blank out if not exists.
352 $matchingElem = $doc->getElementById($sectionId);
353 if ($matchingElem === null) {
357 // Otherwise replace the content with the found content
358 // Checks if the top-level wrapper should be included by matching on tag types
360 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
362 $innerContent .= $doc->saveHTML($matchingElem);
364 foreach ($matchingElem->childNodes as $childNode) {
365 $innerContent .= $doc->saveHTML($childNode);
368 libxml_clear_errors();
370 return $innerContent;
374 * Create and load a DOMDocument from the given html content.
376 protected function loadDocumentFromHtml(string $html): DOMDocument
378 libxml_use_internal_errors(true);
379 $doc = new DOMDocument();
380 $html = '<body>' . $html . '</body>';
381 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));