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;
19 use Illuminate\Support\Str;
20 use League\CommonMark\Block\Element\ListItem;
21 use League\CommonMark\CommonMarkConverter;
22 use League\CommonMark\Environment;
23 use League\CommonMark\Extension\Table\TableExtension;
24 use League\CommonMark\Extension\TaskList\TaskListExtension;
31 * PageContent constructor.
33 public function __construct(Page $page)
39 * Update the content of the page with new provided HTML.
41 public function setNewHTML(string $html)
43 $html = $this->extractBase64ImagesFromHtml($html);
44 $this->page->html = $this->formatHtml($html);
45 $this->page->text = $this->toPlainText();
46 $this->page->markdown = '';
50 * Update the content of the page with new provided Markdown content.
52 public function setNewMarkdown(string $markdown)
54 $markdown = $this->extractBase64ImagesFromMarkdown($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 protected function extractBase64ImagesFromHtml(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);
93 // Get all img elements with image data blobs
94 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
95 foreach ($imageNodes as $imageNode) {
96 $imageSrc = $imageNode->getAttribute('src');
97 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
98 $imageNode->setAttribute('src', $newUrl);
101 // Generate inner html as a string
103 foreach ($childNodes as $childNode) {
104 $html .= $doc->saveHTML($childNode);
111 * Convert all inline base64 content to uploaded image files.
113 protected function extractBase64ImagesFromMarkdown(string $markdown)
116 preg_match_all('/!\[.*?]\(.*?(data:image\/.*?)[)"\s]/', $markdown, $matches);
118 foreach ($matches[1] as $base64Match) {
119 $newUrl = $this->base64ImageUriToUploadedImageUrl($base64Match);
120 $markdown = str_replace($base64Match, $newUrl, $markdown);
127 * Parse the given base64 image URI and return the URL to the created image instance.
128 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
130 protected function base64ImageUriToUploadedImageUrl(string $uri): string
132 $imageRepo = app()->make(ImageRepo::class);
133 $imageInfo = $this->parseBase64ImageUri($uri);
135 // Validate extension and content
136 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
140 // Validate that the content is not over our upload limit
141 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
142 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
146 // Save image from data with a random name
147 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
150 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
151 } catch (ImageUploadException $exception) {
159 * Parse a base64 image URI into the data and extension.
161 * @return array{extension: string, data: string}
163 protected function parseBase64ImageUri(string $uri): array
165 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
166 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
169 'extension' => $extension,
170 'data' => base64_decode($base64ImageData) ?: '',
175 * Formats a page's html to be tagged correctly within the system.
177 protected function formatHtml(string $htmlText): string
179 if (empty($htmlText)) {
183 $doc = $this->loadDocumentFromHtml($htmlText);
184 $container = $doc->documentElement;
185 $body = $container->childNodes->item(0);
186 $childNodes = $body->childNodes;
187 $xPath = new DOMXPath($doc);
189 // Set ids on top-level nodes
191 foreach ($childNodes as $index => $childNode) {
192 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
193 if ($newId && $newId !== $oldId) {
194 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
198 // Set ids on nested header nodes
199 $nestedHeaders = $xPath->query('//body//*//h1|//body//*//h2|//body//*//h3|//body//*//h4|//body//*//h5|//body//*//h6');
200 foreach ($nestedHeaders as $nestedHeader) {
201 [$oldId, $newId] = $this->setUniqueId($nestedHeader, $idMap);
202 if ($newId && $newId !== $oldId) {
203 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
207 // Ensure no duplicate ids within child items
208 $idElems = $xPath->query('//body//*//*[@id]');
209 foreach ($idElems as $domElem) {
210 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
211 if ($newId && $newId !== $oldId) {
212 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
216 // Generate inner html as a string
218 foreach ($childNodes as $childNode) {
219 $html .= $doc->saveHTML($childNode);
226 * Update the all links to the $old location to instead point to $new.
228 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
230 $old = str_replace('"', '', $old);
231 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
232 foreach ($matchingLinks as $domElem) {
233 $domElem->setAttribute('href', $new);
238 * Set a unique id on the given DOMElement.
239 * A map for existing ID's should be passed in to check for current existence.
240 * Returns a pair of strings in the format [old_id, new_id].
242 protected function setUniqueId(DOMNode $element, array &$idMap): array
244 if (!$element instanceof DOMElement) {
248 // Stop if there's an existing valid id that has not already been used.
249 $existingId = $element->getAttribute('id');
250 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
251 $idMap[$existingId] = true;
253 return [$existingId, $existingId];
256 // Create a unique id for the element
257 // Uses the content as a basis to ensure output is the same every time
258 // the same content is passed through.
259 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
260 $newId = urlencode($contentId);
263 while (isset($idMap[$newId])) {
264 $newId = urlencode($contentId . '-' . $loopIndex);
268 $element->setAttribute('id', $newId);
269 $idMap[$newId] = true;
271 return [$existingId, $newId];
275 * Get a plain-text visualisation of this page.
277 protected function toPlainText(): string
279 $html = $this->render(true);
281 return html_entity_decode(strip_tags($html));
285 * Render the page for viewing.
287 public function render(bool $blankIncludes = false): string
289 $content = $this->page->html ?? '';
291 if (!config('app.allow_content_scripts')) {
292 $content = HtmlContentFilter::removeScripts($content);
295 if ($blankIncludes) {
296 $content = $this->blankPageIncludes($content);
298 $content = $this->parsePageIncludes($content);
305 * Parse the headers on the page to get a navigation menu.
307 public function getNavigation(string $htmlContent): array
309 if (empty($htmlContent)) {
313 $doc = $this->loadDocumentFromHtml($htmlContent);
314 $xPath = new DOMXPath($doc);
315 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
317 return $headers ? $this->headerNodesToLevelList($headers) : [];
321 * Convert a DOMNodeList into an array of readable header attributes
322 * with levels normalised to the lower header level.
324 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
326 $tree = collect($nodeList)->map(function (DOMElement $header) {
327 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
328 $text = mb_substr($text, 0, 100);
331 'nodeName' => strtolower($header->nodeName),
332 'level' => intval(str_replace('h', '', $header->nodeName)),
333 'link' => '#' . $header->getAttribute('id'),
336 })->filter(function ($header) {
337 return mb_strlen($header['text']) > 0;
340 // Shift headers if only smaller headers have been used
341 $levelChange = ($tree->pluck('level')->min() - 1);
342 $tree = $tree->map(function ($header) use ($levelChange) {
343 $header['level'] -= ($levelChange);
348 return $tree->toArray();
352 * Remove any page include tags within the given HTML.
354 protected function blankPageIncludes(string $html): string
356 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
360 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
362 protected function parsePageIncludes(string $html): string
365 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
367 foreach ($matches[1] as $index => $includeId) {
368 $fullMatch = $matches[0][$index];
369 $splitInclude = explode('#', $includeId, 2);
371 // Get page id from reference
372 $pageId = intval($splitInclude[0]);
373 if (is_nan($pageId)) {
377 // Find page and skip this if page not found
378 /** @var ?Page $matchedPage */
379 $matchedPage = Page::visible()->find($pageId);
380 if ($matchedPage === null) {
381 $html = str_replace($fullMatch, '', $html);
385 // If we only have page id, just insert all page html and continue.
386 if (count($splitInclude) === 1) {
387 $html = str_replace($fullMatch, $matchedPage->html, $html);
391 // Create and load HTML into a document
392 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
393 $html = str_replace($fullMatch, trim($innerContent), $html);
400 * Fetch the content from a specific section of the given page.
402 protected function fetchSectionOfPage(Page $page, string $sectionId): string
404 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
405 $doc = $this->loadDocumentFromHtml($page->html);
407 // Search included content for the id given and blank out if not exists.
408 $matchingElem = $doc->getElementById($sectionId);
409 if ($matchingElem === null) {
413 // Otherwise replace the content with the found content
414 // Checks if the top-level wrapper should be included by matching on tag types
416 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
418 $innerContent .= $doc->saveHTML($matchingElem);
420 foreach ($matchingElem->childNodes as $childNode) {
421 $innerContent .= $doc->saveHTML($childNode);
424 libxml_clear_errors();
426 return $innerContent;
430 * Create and load a DOMDocument from the given html content.
432 protected function loadDocumentFromHtml(string $html): DOMDocument
434 libxml_use_internal_errors(true);
435 $doc = new DOMDocument();
436 $html = '<body>' . $html . '</body>';
437 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));