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\Uploads\ImageService;
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;
29 * PageContent constructor.
31 public function __construct(Page $page)
37 * Update the content of the page with new provided HTML.
39 public function setNewHTML(string $html)
41 $html = $this->extractBase64ImagesFromHtml($html);
42 $this->page->html = $this->formatHtml($html);
43 $this->page->text = $this->toPlainText();
44 $this->page->markdown = '';
48 * Update the content of the page with new provided Markdown content.
50 public function setNewMarkdown(string $markdown)
52 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
53 $this->page->markdown = $markdown;
54 $html = $this->markdownToHtml($markdown);
55 $this->page->html = $this->formatHtml($html);
56 $this->page->text = $this->toPlainText();
60 * Convert the given Markdown content to a HTML string.
62 protected function markdownToHtml(string $markdown): string
64 $environment = Environment::createCommonMarkEnvironment();
65 $environment->addExtension(new TableExtension());
66 $environment->addExtension(new TaskListExtension());
67 $environment->addExtension(new CustomStrikeThroughExtension());
68 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
69 $converter = new CommonMarkConverter([], $environment);
71 $environment->addBlockRenderer(ListItem::class, new CustomListItemRenderer(), 10);
73 return $converter->convertToHtml($markdown);
77 * Convert all base64 image data to saved images.
79 protected function extractBase64ImagesFromHtml(string $htmlText): string
81 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
85 $doc = $this->loadDocumentFromHtml($htmlText);
86 $container = $doc->documentElement;
87 $body = $container->childNodes->item(0);
88 $childNodes = $body->childNodes;
89 $xPath = new DOMXPath($doc);
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 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
96 $imageNode->setAttribute('src', $newUrl);
99 // Generate inner html as a string
101 foreach ($childNodes as $childNode) {
102 $html .= $doc->saveHTML($childNode);
109 * Convert all inline base64 content to uploaded image files.
111 protected function extractBase64ImagesFromMarkdown(string $markdown)
114 preg_match_all('/!\[.*?]\(.*?(data:image\/.*?)[)"\s]/', $markdown, $matches);
116 foreach ($matches[1] as $base64Match) {
117 $newUrl = $this->base64ImageUriToUploadedImageUrl($base64Match);
118 $markdown = str_replace($base64Match, $newUrl, $markdown);
125 * Parse the given base64 image URI and return the URL to the created image instance.
126 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
128 protected function base64ImageUriToUploadedImageUrl(string $uri): string
130 $imageRepo = app()->make(ImageRepo::class);
131 $imageInfo = $this->parseBase64ImageUri($uri);
133 // Validate extension and content
134 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
138 // Validate that the content is not over our upload limit
139 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
140 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
144 // Save image from data with a random name
145 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
148 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
149 } catch (ImageUploadException $exception) {
157 * Parse a base64 image URI into the data and extension.
159 * @return array{extension: array, data: string}
161 protected function parseBase64ImageUri(string $uri): array
163 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
164 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
167 'extension' => $extension,
168 'data' => base64_decode($base64ImageData) ?: '',
173 * Formats a page's html to be tagged correctly within the system.
175 protected function formatHtml(string $htmlText): string
177 if (empty($htmlText)) {
181 $doc = $this->loadDocumentFromHtml($htmlText);
182 $container = $doc->documentElement;
183 $body = $container->childNodes->item(0);
184 $childNodes = $body->childNodes;
185 $xPath = new DOMXPath($doc);
187 // Set ids on top-level nodes
189 foreach ($childNodes as $index => $childNode) {
190 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
191 if ($newId && $newId !== $oldId) {
192 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
196 // Ensure no duplicate ids within child items
197 $idElems = $xPath->query('//body//*//*[@id]');
198 foreach ($idElems as $domElem) {
199 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
200 if ($newId && $newId !== $oldId) {
201 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
205 // Generate inner html as a string
207 foreach ($childNodes as $childNode) {
208 $html .= $doc->saveHTML($childNode);
215 * Update the all links to the $old location to instead point to $new.
217 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
219 $old = str_replace('"', '', $old);
220 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
221 foreach ($matchingLinks as $domElem) {
222 $domElem->setAttribute('href', $new);
227 * Set a unique id on the given DOMElement.
228 * A map for existing ID's should be passed in to check for current existence.
229 * Returns a pair of strings in the format [old_id, new_id].
231 protected function setUniqueId(\DOMNode $element, array &$idMap): array
233 if (get_class($element) !== 'DOMElement') {
237 // Stop if there's an existing valid id that has not already been used.
238 $existingId = $element->getAttribute('id');
239 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
240 $idMap[$existingId] = true;
242 return [$existingId, $existingId];
245 // Create an unique id for the element
246 // Uses the content as a basis to ensure output is the same every time
247 // the same content is passed through.
248 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
249 $newId = urlencode($contentId);
252 while (isset($idMap[$newId])) {
253 $newId = urlencode($contentId . '-' . $loopIndex);
257 $element->setAttribute('id', $newId);
258 $idMap[$newId] = true;
260 return [$existingId, $newId];
264 * Get a plain-text visualisation of this page.
266 protected function toPlainText(): string
268 $html = $this->render(true);
270 return html_entity_decode(strip_tags($html));
274 * Render the page for viewing.
276 public function render(bool $blankIncludes = false): string
278 $content = $this->page->html ?? '';
280 if (!config('app.allow_content_scripts')) {
281 $content = HtmlContentFilter::removeScripts($content);
284 if ($blankIncludes) {
285 $content = $this->blankPageIncludes($content);
287 $content = $this->parsePageIncludes($content);
294 * Parse the headers on the page to get a navigation menu.
296 public function getNavigation(string $htmlContent): array
298 if (empty($htmlContent)) {
302 $doc = $this->loadDocumentFromHtml($htmlContent);
303 $xPath = new DOMXPath($doc);
304 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
306 return $headers ? $this->headerNodesToLevelList($headers) : [];
310 * Convert a DOMNodeList into an array of readable header attributes
311 * with levels normalised to the lower header level.
313 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
315 $tree = collect($nodeList)->map(function ($header) {
316 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
317 $text = mb_substr($text, 0, 100);
320 'nodeName' => strtolower($header->nodeName),
321 'level' => intval(str_replace('h', '', $header->nodeName)),
322 'link' => '#' . $header->getAttribute('id'),
325 })->filter(function ($header) {
326 return mb_strlen($header['text']) > 0;
329 // Shift headers if only smaller headers have been used
330 $levelChange = ($tree->pluck('level')->min() - 1);
331 $tree = $tree->map(function ($header) use ($levelChange) {
332 $header['level'] -= ($levelChange);
337 return $tree->toArray();
341 * Remove any page include tags within the given HTML.
343 protected function blankPageIncludes(string $html): string
345 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
349 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
351 protected function parsePageIncludes(string $html): string
354 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
356 foreach ($matches[1] as $index => $includeId) {
357 $fullMatch = $matches[0][$index];
358 $splitInclude = explode('#', $includeId, 2);
360 // Get page id from reference
361 $pageId = intval($splitInclude[0]);
362 if (is_nan($pageId)) {
366 // Find page and skip this if page not found
367 /** @var ?Page $matchedPage */
368 $matchedPage = Page::visible()->find($pageId);
369 if ($matchedPage === null) {
370 $html = str_replace($fullMatch, '', $html);
374 // If we only have page id, just insert all page html and continue.
375 if (count($splitInclude) === 1) {
376 $html = str_replace($fullMatch, $matchedPage->html, $html);
380 // Create and load HTML into a document
381 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
382 $html = str_replace($fullMatch, trim($innerContent), $html);
389 * Fetch the content from a specific section of the given page.
391 protected function fetchSectionOfPage(Page $page, string $sectionId): string
393 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
394 $doc = $this->loadDocumentFromHtml($page->html);
396 // Search included content for the id given and blank out if not exists.
397 $matchingElem = $doc->getElementById($sectionId);
398 if ($matchingElem === null) {
402 // Otherwise replace the content with the found content
403 // Checks if the top-level wrapper should be included by matching on tag types
405 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
407 $innerContent .= $doc->saveHTML($matchingElem);
409 foreach ($matchingElem->childNodes as $childNode) {
410 $innerContent .= $doc->saveHTML($childNode);
413 libxml_clear_errors();
415 return $innerContent;
419 * Create and load a DOMDocument from the given html content.
421 protected function loadDocumentFromHtml(string $html): DOMDocument
423 libxml_use_internal_errors(true);
424 $doc = new DOMDocument();
425 $html = '<body>' . $html . '</body>';
426 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));