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\Exceptions\ImageUploadException;
9 use BookStack\Facades\Theme;
10 use BookStack\Theming\ThemeEvents;
11 use BookStack\Uploads\ImageRepo;
12 use BookStack\Util\HtmlContentFilter;
16 use Illuminate\Support\Str;
17 use League\CommonMark\Block\Element\ListItem;
18 use League\CommonMark\CommonMarkConverter;
19 use League\CommonMark\Environment;
20 use League\CommonMark\Extension\Table\TableExtension;
21 use League\CommonMark\Extension\TaskList\TaskListExtension;
28 * PageContent constructor.
30 public function __construct(Page $page)
36 * Update the content of the page with new provided HTML.
38 public function setNewHTML(string $html)
40 $html = $this->extractBase64ImagesFromHtml($html);
41 $this->page->html = $this->formatHtml($html);
42 $this->page->text = $this->toPlainText();
43 $this->page->markdown = '';
47 * Update the content of the page with new provided Markdown content.
49 public function setNewMarkdown(string $markdown)
51 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
52 $this->page->markdown = $markdown;
53 $html = $this->markdownToHtml($markdown);
54 $this->page->html = $this->formatHtml($html);
55 $this->page->text = $this->toPlainText();
59 * Convert the given Markdown content to a HTML string.
61 protected function markdownToHtml(string $markdown): string
63 $environment = Environment::createCommonMarkEnvironment();
64 $environment->addExtension(new TableExtension());
65 $environment->addExtension(new TaskListExtension());
66 $environment->addExtension(new CustomStrikeThroughExtension());
67 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
68 $converter = new CommonMarkConverter([], $environment);
70 $environment->addBlockRenderer(ListItem::class, new CustomListItemRenderer(), 10);
72 return $converter->convertToHtml($markdown);
76 * Convert all base64 image data to saved images.
78 protected function extractBase64ImagesFromHtml(string $htmlText): string
80 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
84 $doc = $this->loadDocumentFromHtml($htmlText);
85 $container = $doc->documentElement;
86 $body = $container->childNodes->item(0);
87 $childNodes = $body->childNodes;
88 $xPath = new DOMXPath($doc);
89 $imageRepo = app()->make(ImageRepo::class);
91 // Get all img elements with image data blobs
92 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
93 foreach ($imageNodes as $imageNode) {
94 $imageSrc = $imageNode->getAttribute('src');
95 [$dataDefinition, $base64ImageData] = explode(',', $imageSrc, 2);
96 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png');
99 if (!$imageRepo->imageExtensionSupported($extension)) {
100 $imageNode->setAttribute('src', '');
104 // Save image from data with a random name
105 $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension;
108 $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $this->page->id);
109 $imageNode->setAttribute('src', $image->url);
110 } catch (ImageUploadException $exception) {
111 $imageNode->setAttribute('src', '');
115 // Generate inner html as a string
117 foreach ($childNodes as $childNode) {
118 $html .= $doc->saveHTML($childNode);
125 * Convert all inline base64 content to uploaded image files.
127 protected function extractBase64ImagesFromMarkdown(string $markdown)
129 $imageRepo = app()->make(ImageRepo::class);
131 preg_match_all('/!\[.*?]\(.*?(data:image\/.*?)[)"\s]/', $markdown, $matches);
133 foreach ($matches[1] as $base64Match) {
134 [$dataDefinition, $base64ImageData] = explode(',', $base64Match, 2);
135 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png');
137 // Validate extension
138 if (!$imageRepo->imageExtensionSupported($extension)) {
139 $markdown = str_replace($base64Match, '', $markdown);
143 // Save image from data with a random name
144 $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension;
147 $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $this->page->id);
148 $markdown = str_replace($base64Match, $image->url, $markdown);
149 } catch (ImageUploadException $exception) {
150 $markdown = str_replace($base64Match, '', $markdown);
158 * Formats a page's html to be tagged correctly within the system.
160 protected function formatHtml(string $htmlText): string
162 if (empty($htmlText)) {
166 $doc = $this->loadDocumentFromHtml($htmlText);
167 $container = $doc->documentElement;
168 $body = $container->childNodes->item(0);
169 $childNodes = $body->childNodes;
170 $xPath = new DOMXPath($doc);
172 // Set ids on top-level nodes
174 foreach ($childNodes as $index => $childNode) {
175 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
176 if ($newId && $newId !== $oldId) {
177 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
181 // Ensure no duplicate ids within child items
182 $idElems = $xPath->query('//body//*//*[@id]');
183 foreach ($idElems as $domElem) {
184 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
185 if ($newId && $newId !== $oldId) {
186 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
190 // Generate inner html as a string
192 foreach ($childNodes as $childNode) {
193 $html .= $doc->saveHTML($childNode);
200 * Update the all links to the $old location to instead point to $new.
202 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
204 $old = str_replace('"', '', $old);
205 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
206 foreach ($matchingLinks as $domElem) {
207 $domElem->setAttribute('href', $new);
212 * Set a unique id on the given DOMElement.
213 * A map for existing ID's should be passed in to check for current existence.
214 * Returns a pair of strings in the format [old_id, new_id].
216 protected function setUniqueId(\DOMNode $element, array &$idMap): array
218 if (get_class($element) !== 'DOMElement') {
222 // Stop if there's an existing valid id that has not already been used.
223 $existingId = $element->getAttribute('id');
224 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
225 $idMap[$existingId] = true;
227 return [$existingId, $existingId];
230 // Create an unique id for the element
231 // Uses the content as a basis to ensure output is the same every time
232 // the same content is passed through.
233 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
234 $newId = urlencode($contentId);
237 while (isset($idMap[$newId])) {
238 $newId = urlencode($contentId . '-' . $loopIndex);
242 $element->setAttribute('id', $newId);
243 $idMap[$newId] = true;
245 return [$existingId, $newId];
249 * Get a plain-text visualisation of this page.
251 protected function toPlainText(): string
253 $html = $this->render(true);
255 return html_entity_decode(strip_tags($html));
259 * Render the page for viewing.
261 public function render(bool $blankIncludes = false): string
263 $content = $this->page->html ?? '';
265 if (!config('app.allow_content_scripts')) {
266 $content = HtmlContentFilter::removeScripts($content);
269 if ($blankIncludes) {
270 $content = $this->blankPageIncludes($content);
272 $content = $this->parsePageIncludes($content);
279 * Parse the headers on the page to get a navigation menu.
281 public function getNavigation(string $htmlContent): array
283 if (empty($htmlContent)) {
287 $doc = $this->loadDocumentFromHtml($htmlContent);
288 $xPath = new DOMXPath($doc);
289 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
291 return $headers ? $this->headerNodesToLevelList($headers) : [];
295 * Convert a DOMNodeList into an array of readable header attributes
296 * with levels normalised to the lower header level.
298 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
300 $tree = collect($nodeList)->map(function ($header) {
301 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
302 $text = mb_substr($text, 0, 100);
305 'nodeName' => strtolower($header->nodeName),
306 'level' => intval(str_replace('h', '', $header->nodeName)),
307 'link' => '#' . $header->getAttribute('id'),
310 })->filter(function ($header) {
311 return mb_strlen($header['text']) > 0;
314 // Shift headers if only smaller headers have been used
315 $levelChange = ($tree->pluck('level')->min() - 1);
316 $tree = $tree->map(function ($header) use ($levelChange) {
317 $header['level'] -= ($levelChange);
322 return $tree->toArray();
326 * Remove any page include tags within the given HTML.
328 protected function blankPageIncludes(string $html): string
330 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
334 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
336 protected function parsePageIncludes(string $html): string
339 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
341 foreach ($matches[1] as $index => $includeId) {
342 $fullMatch = $matches[0][$index];
343 $splitInclude = explode('#', $includeId, 2);
345 // Get page id from reference
346 $pageId = intval($splitInclude[0]);
347 if (is_nan($pageId)) {
351 // Find page and skip this if page not found
352 /** @var ?Page $matchedPage */
353 $matchedPage = Page::visible()->find($pageId);
354 if ($matchedPage === null) {
355 $html = str_replace($fullMatch, '', $html);
359 // If we only have page id, just insert all page html and continue.
360 if (count($splitInclude) === 1) {
361 $html = str_replace($fullMatch, $matchedPage->html, $html);
365 // Create and load HTML into a document
366 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
367 $html = str_replace($fullMatch, trim($innerContent), $html);
374 * Fetch the content from a specific section of the given page.
376 protected function fetchSectionOfPage(Page $page, string $sectionId): string
378 $topLevelTags = ['table', 'ul', 'ol'];
379 $doc = $this->loadDocumentFromHtml($page->html);
381 // Search included content for the id given and blank out if not exists.
382 $matchingElem = $doc->getElementById($sectionId);
383 if ($matchingElem === null) {
387 // Otherwise replace the content with the found content
388 // Checks if the top-level wrapper should be included by matching on tag types
390 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
392 $innerContent .= $doc->saveHTML($matchingElem);
394 foreach ($matchingElem->childNodes as $childNode) {
395 $innerContent .= $doc->saveHTML($childNode);
398 libxml_clear_errors();
400 return $innerContent;
404 * Create and load a DOMDocument from the given html content.
406 protected function loadDocumentFromHtml(string $html): DOMDocument
408 libxml_use_internal_errors(true);
409 $doc = new DOMDocument();
410 $html = '<body>' . $html . '</body>';
411 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));