3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
7 use BookStack\Exceptions\ImageUploadException;
8 use BookStack\Facades\Theme;
9 use BookStack\Theming\ThemeEvents;
10 use BookStack\Uploads\ImageRepo;
11 use BookStack\Uploads\ImageService;
12 use BookStack\Users\Models\User;
13 use BookStack\Util\HtmlContentFilter;
14 use BookStack\Util\WebSafeMimeSniffer;
20 use Illuminate\Support\Str;
24 public function __construct(
30 * Update the content of the page with new provided HTML.
32 public function setNewHTML(string $html, User $updater): void
34 $html = $this->extractBase64ImagesFromHtml($html, $updater);
35 $this->page->html = $this->formatHtml($html);
36 $this->page->text = $this->toPlainText();
37 $this->page->markdown = '';
41 * Update the content of the page with new provided Markdown content.
43 public function setNewMarkdown(string $markdown, User $updater): void
45 $markdown = $this->extractBase64ImagesFromMarkdown($markdown, $updater);
46 $this->page->markdown = $markdown;
47 $html = (new MarkdownToHtml($markdown))->convert();
48 $this->page->html = $this->formatHtml($html);
49 $this->page->text = $this->toPlainText();
53 * Convert all base64 image data to saved images.
55 protected function extractBase64ImagesFromHtml(string $htmlText, User $updater): string
57 if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
61 $doc = $this->loadDocumentFromHtml($htmlText);
62 $container = $doc->documentElement;
63 $body = $container->childNodes->item(0);
64 $childNodes = $body->childNodes;
65 $xPath = new DOMXPath($doc);
67 // Get all img elements with image data blobs
68 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
69 foreach ($imageNodes as $imageNode) {
70 $imageSrc = $imageNode->getAttribute('src');
71 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater);
72 $imageNode->setAttribute('src', $newUrl);
75 // Generate inner html as a string
77 foreach ($childNodes as $childNode) {
78 $html .= $doc->saveHTML($childNode);
85 * Convert all inline base64 content to uploaded image files.
86 * Regex is used to locate the start of data-uri definitions then
87 * manual looping over content is done to parse the whole data uri.
88 * Attempting to capture the whole data uri using regex can cause PHP
89 * PCRE limits to be hit with larger, multi-MB, files.
91 protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string
94 $contentLength = strlen($markdown);
96 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
98 foreach ($matches[1] as $base64MatchPair) {
99 [$dataUri, $index] = $base64MatchPair;
101 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
102 $char = $markdown[$i];
103 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
109 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater);
110 $replacements[] = [$dataUri, $newUrl];
113 foreach ($replacements as [$dataUri, $newUrl]) {
114 $markdown = str_replace($dataUri, $newUrl, $markdown);
121 * Parse the given base64 image URI and return the URL to the created image instance.
122 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
124 protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string
126 $imageRepo = app()->make(ImageRepo::class);
127 $imageInfo = $this->parseBase64ImageUri($uri);
129 // Validate user has permission to create images
130 if (!$updater->can('image-create-all')) {
134 // Validate extension and content
135 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
139 // Validate content looks like an image via sniffing mime type
140 $mimeSniffer = new WebSafeMimeSniffer();
141 $mime = $mimeSniffer->sniff($imageInfo['data']);
142 if (!str_starts_with($mime, 'image/')) {
146 // Validate that the content is not over our upload limit
147 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
148 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
152 // Save image from data with a random name
153 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
156 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
157 } catch (ImageUploadException $exception) {
165 * Parse a base64 image URI into the data and extension.
167 * @return array{extension: string, data: string}
169 protected function parseBase64ImageUri(string $uri): array
171 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
172 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
175 'extension' => $extension,
176 'data' => base64_decode($base64ImageData) ?: '',
181 * Formats a page's html to be tagged correctly within the system.
183 protected function formatHtml(string $htmlText): string
185 if (empty($htmlText)) {
189 $doc = $this->loadDocumentFromHtml($htmlText);
190 $container = $doc->documentElement;
191 $body = $container->childNodes->item(0);
192 $childNodes = $body->childNodes;
193 $xPath = new DOMXPath($doc);
195 // Map to hold used ID references
197 // Map to hold changing ID references
200 $this->updateIdsRecursively($body, 0, $idMap, $changeMap);
201 $this->updateLinks($xPath, $changeMap);
203 // Generate inner html as a string
205 foreach ($childNodes as $childNode) {
206 $html .= $doc->saveHTML($childNode);
209 // Perform required string-level tweaks
210 $html = str_replace(' ', ' ', $html);
216 * For the given DOMNode, traverse its children recursively and update IDs
217 * where required (Top-level, headers & elements with IDs).
218 * Will update the provided $changeMap array with changes made, where keys are the old
219 * ids and the corresponding values are the new ids.
221 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
223 /* @var DOMNode $child */
224 foreach ($element->childNodes as $child) {
225 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
226 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
227 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
228 $changeMap[$oldId] = $newId;
232 if ($child->hasChildNodes()) {
233 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
239 * Update the all links in the given xpath to apply requires changes within the
240 * given $changeMap array.
242 protected function updateLinks(DOMXPath $xpath, array $changeMap): void
244 if (empty($changeMap)) {
248 $links = $xpath->query('//body//*//*[@href]');
249 /** @var DOMElement $domElem */
250 foreach ($links as $domElem) {
251 $href = ltrim($domElem->getAttribute('href'), '#');
252 $newHref = $changeMap[$href] ?? null;
254 $domElem->setAttribute('href', '#' . $newHref);
260 * Set a unique id on the given DOMElement.
261 * A map for existing ID's should be passed in to check for current existence,
262 * and this will be updated with any new IDs set upon elements.
263 * Returns a pair of strings in the format [old_id, new_id].
265 protected function setUniqueId(DOMNode $element, array &$idMap): array
267 if (!$element instanceof DOMElement) {
271 // Stop if there's an existing valid id that has not already been used.
272 $existingId = $element->getAttribute('id');
273 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
274 $idMap[$existingId] = true;
276 return [$existingId, $existingId];
279 // Create a unique id for the element
280 // Uses the content as a basis to ensure output is the same every time
281 // the same content is passed through.
282 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
283 $newId = urlencode($contentId);
286 while (isset($idMap[$newId])) {
287 $newId = urlencode($contentId . '-' . $loopIndex);
291 $element->setAttribute('id', $newId);
292 $idMap[$newId] = true;
294 return [$existingId, $newId];
298 * Get a plain-text visualisation of this page.
300 protected function toPlainText(): string
302 $html = $this->render(true);
304 return html_entity_decode(strip_tags($html));
308 * Render the page for viewing.
310 public function render(bool $blankIncludes = false): string
312 $content = $this->page->html ?? '';
314 if (!config('app.allow_content_scripts')) {
315 $content = HtmlContentFilter::removeScripts($content);
318 if ($blankIncludes) {
319 $content = $this->blankPageIncludes($content);
321 for ($includeDepth = 0; $includeDepth < 3; $includeDepth++) {
322 $content = $this->parsePageIncludes($content);
330 * Parse the headers on the page to get a navigation menu.
332 public function getNavigation(string $htmlContent): array
334 if (empty($htmlContent)) {
338 $doc = $this->loadDocumentFromHtml($htmlContent);
339 $xPath = new DOMXPath($doc);
340 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
342 return $headers ? $this->headerNodesToLevelList($headers) : [];
346 * Convert a DOMNodeList into an array of readable header attributes
347 * with levels normalised to the lower header level.
349 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
351 $tree = collect($nodeList)->map(function (DOMElement $header) {
352 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
353 $text = mb_substr($text, 0, 100);
356 'nodeName' => strtolower($header->nodeName),
357 'level' => intval(str_replace('h', '', $header->nodeName)),
358 'link' => '#' . $header->getAttribute('id'),
361 })->filter(function ($header) {
362 return mb_strlen($header['text']) > 0;
365 // Shift headers if only smaller headers have been used
366 $levelChange = ($tree->pluck('level')->min() - 1);
367 $tree = $tree->map(function ($header) use ($levelChange) {
368 $header['level'] -= ($levelChange);
373 return $tree->toArray();
377 * Remove any page include tags within the given HTML.
379 protected function blankPageIncludes(string $html): string
381 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
385 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
387 protected function parsePageIncludes(string $html): string
390 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
392 foreach ($matches[1] as $index => $includeId) {
393 $fullMatch = $matches[0][$index];
394 $splitInclude = explode('#', $includeId, 2);
396 // Get page id from reference
397 $pageId = intval($splitInclude[0]);
398 if (is_nan($pageId)) {
402 // Find page to use, and default replacement to empty string for non-matches.
403 /** @var ?Page $matchedPage */
404 $matchedPage = Page::visible()->find($pageId);
407 if ($matchedPage && count($splitInclude) === 1) {
408 // If we only have page id, just insert all page html and continue.
409 $replacement = $matchedPage->html;
410 } elseif ($matchedPage && count($splitInclude) > 1) {
411 // Otherwise, if our include tag defines a section, load that specific content
412 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
413 $replacement = trim($innerContent);
416 $themeReplacement = Theme::dispatch(
417 ThemeEvents::PAGE_INCLUDE_PARSE,
421 $matchedPage ? (clone $matchedPage) : null,
424 // Perform the content replacement
425 $html = str_replace($fullMatch, $themeReplacement ?? $replacement, $html);
432 * Fetch the content from a specific section of the given page.
434 protected function fetchSectionOfPage(Page $page, string $sectionId): string
436 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
437 $doc = $this->loadDocumentFromHtml($page->html);
439 // Search included content for the id given and blank out if not exists.
440 $matchingElem = $doc->getElementById($sectionId);
441 if ($matchingElem === null) {
445 // Otherwise replace the content with the found content
446 // Checks if the top-level wrapper should be included by matching on tag types
448 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
450 $innerContent .= $doc->saveHTML($matchingElem);
452 foreach ($matchingElem->childNodes as $childNode) {
453 $innerContent .= $doc->saveHTML($childNode);
456 libxml_clear_errors();
458 return $innerContent;
462 * Create and load a DOMDocument from the given html content.
464 protected function loadDocumentFromHtml(string $html): DOMDocument
466 libxml_use_internal_errors(true);
467 $doc = new DOMDocument();
468 $html = '<?xml encoding="utf-8" ?><body>' . $html . '</body>';
469 $doc->loadHTML($html);