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\Util\HtmlContentFilter;
18 use Illuminate\Support\Str;
22 public function __construct(
28 * Update the content of the page with new provided HTML.
30 public function setNewHTML(string $html): void
32 $html = $this->extractBase64ImagesFromHtml($html);
33 $this->page->html = $this->formatHtml($html);
34 $this->page->text = $this->toPlainText();
35 $this->page->markdown = '';
39 * Update the content of the page with new provided Markdown content.
41 public function setNewMarkdown(string $markdown): void
43 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
44 $this->page->markdown = $markdown;
45 $html = (new MarkdownToHtml($markdown))->convert();
46 $this->page->html = $this->formatHtml($html);
47 $this->page->text = $this->toPlainText();
51 * Convert all base64 image data to saved images.
53 protected function extractBase64ImagesFromHtml(string $htmlText): string
55 if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
59 $doc = $this->loadDocumentFromHtml($htmlText);
60 $container = $doc->documentElement;
61 $body = $container->childNodes->item(0);
62 $childNodes = $body->childNodes;
63 $xPath = new DOMXPath($doc);
65 // Get all img elements with image data blobs
66 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
67 foreach ($imageNodes as $imageNode) {
68 $imageSrc = $imageNode->getAttribute('src');
69 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
70 $imageNode->setAttribute('src', $newUrl);
73 // Generate inner html as a string
75 foreach ($childNodes as $childNode) {
76 $html .= $doc->saveHTML($childNode);
83 * Convert all inline base64 content to uploaded image files.
84 * Regex is used to locate the start of data-uri definitions then
85 * manual looping over content is done to parse the whole data uri.
86 * Attempting to capture the whole data uri using regex can cause PHP
87 * PCRE limits to be hit with larger, multi-MB, files.
89 protected function extractBase64ImagesFromMarkdown(string $markdown): string
92 $contentLength = strlen($markdown);
94 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
96 foreach ($matches[1] as $base64MatchPair) {
97 [$dataUri, $index] = $base64MatchPair;
99 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
100 $char = $markdown[$i];
101 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
107 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
108 $replacements[] = [$dataUri, $newUrl];
111 foreach ($replacements as [$dataUri, $newUrl]) {
112 $markdown = str_replace($dataUri, $newUrl, $markdown);
119 * Parse the given base64 image URI and return the URL to the created image instance.
120 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
122 protected function base64ImageUriToUploadedImageUrl(string $uri): string
124 $imageRepo = app()->make(ImageRepo::class);
125 $imageInfo = $this->parseBase64ImageUri($uri);
127 // Validate extension and content
128 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
132 // Validate that the content is not over our upload limit
133 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
134 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
138 // Save image from data with a random name
139 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
142 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
143 } catch (ImageUploadException $exception) {
151 * Parse a base64 image URI into the data and extension.
153 * @return array{extension: string, data: string}
155 protected function parseBase64ImageUri(string $uri): array
157 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
158 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
161 'extension' => $extension,
162 'data' => base64_decode($base64ImageData) ?: '',
167 * Formats a page's html to be tagged correctly within the system.
169 protected function formatHtml(string $htmlText): string
171 if (empty($htmlText)) {
175 $doc = $this->loadDocumentFromHtml($htmlText);
176 $container = $doc->documentElement;
177 $body = $container->childNodes->item(0);
178 $childNodes = $body->childNodes;
179 $xPath = new DOMXPath($doc);
181 // Map to hold used ID references
183 // Map to hold changing ID references
186 $this->updateIdsRecursively($body, 0, $idMap, $changeMap);
187 $this->updateLinks($xPath, $changeMap);
189 // Generate inner html as a string
191 foreach ($childNodes as $childNode) {
192 $html .= $doc->saveHTML($childNode);
195 // Perform required string-level tweaks
196 $html = str_replace(' ', ' ', $html);
202 * For the given DOMNode, traverse its children recursively and update IDs
203 * where required (Top-level, headers & elements with IDs).
204 * Will update the provided $changeMap array with changes made, where keys are the old
205 * ids and the corresponding values are the new ids.
207 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
209 /* @var DOMNode $child */
210 foreach ($element->childNodes as $child) {
211 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
212 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
213 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
214 $changeMap[$oldId] = $newId;
218 if ($child->hasChildNodes()) {
219 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
225 * Update the all links in the given xpath to apply requires changes within the
226 * given $changeMap array.
228 protected function updateLinks(DOMXPath $xpath, array $changeMap): void
230 if (empty($changeMap)) {
234 $links = $xpath->query('//body//*//*[@href]');
235 /** @var DOMElement $domElem */
236 foreach ($links as $domElem) {
237 $href = ltrim($domElem->getAttribute('href'), '#');
238 $newHref = $changeMap[$href] ?? null;
240 $domElem->setAttribute('href', '#' . $newHref);
246 * Set a unique id on the given DOMElement.
247 * A map for existing ID's should be passed in to check for current existence,
248 * and this will be updated with any new IDs set upon elements.
249 * Returns a pair of strings in the format [old_id, new_id].
251 protected function setUniqueId(DOMNode $element, array &$idMap): array
253 if (!$element instanceof DOMElement) {
257 // Stop if there's an existing valid id that has not already been used.
258 $existingId = $element->getAttribute('id');
259 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
260 $idMap[$existingId] = true;
262 return [$existingId, $existingId];
265 // Create a unique id for the element
266 // Uses the content as a basis to ensure output is the same every time
267 // the same content is passed through.
268 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
269 $newId = urlencode($contentId);
272 while (isset($idMap[$newId])) {
273 $newId = urlencode($contentId . '-' . $loopIndex);
277 $element->setAttribute('id', $newId);
278 $idMap[$newId] = true;
280 return [$existingId, $newId];
284 * Get a plain-text visualisation of this page.
286 protected function toPlainText(): string
288 $html = $this->render(true);
290 return html_entity_decode(strip_tags($html));
294 * Render the page for viewing.
296 public function render(bool $blankIncludes = false): string
298 $content = $this->page->html ?? '';
300 if (!config('app.allow_content_scripts')) {
301 $content = HtmlContentFilter::removeScripts($content);
304 if ($blankIncludes) {
305 $content = $this->blankPageIncludes($content);
307 for ($includeDepth = 0; $includeDepth < 3; $includeDepth++) {
308 $content = $this->parsePageIncludes($content);
316 * Parse the headers on the page to get a navigation menu.
318 public function getNavigation(string $htmlContent): array
320 if (empty($htmlContent)) {
324 $doc = $this->loadDocumentFromHtml($htmlContent);
325 $xPath = new DOMXPath($doc);
326 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
328 return $headers ? $this->headerNodesToLevelList($headers) : [];
332 * Convert a DOMNodeList into an array of readable header attributes
333 * with levels normalised to the lower header level.
335 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
337 $tree = collect($nodeList)->map(function (DOMElement $header) {
338 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
339 $text = mb_substr($text, 0, 100);
342 'nodeName' => strtolower($header->nodeName),
343 'level' => intval(str_replace('h', '', $header->nodeName)),
344 'link' => '#' . $header->getAttribute('id'),
347 })->filter(function ($header) {
348 return mb_strlen($header['text']) > 0;
351 // Shift headers if only smaller headers have been used
352 $levelChange = ($tree->pluck('level')->min() - 1);
353 $tree = $tree->map(function ($header) use ($levelChange) {
354 $header['level'] -= ($levelChange);
359 return $tree->toArray();
363 * Remove any page include tags within the given HTML.
365 protected function blankPageIncludes(string $html): string
367 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
371 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
373 protected function parsePageIncludes(string $html): string
376 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
378 foreach ($matches[1] as $index => $includeId) {
379 $fullMatch = $matches[0][$index];
380 $splitInclude = explode('#', $includeId, 2);
382 // Get page id from reference
383 $pageId = intval($splitInclude[0]);
384 if (is_nan($pageId)) {
388 // Find page to use, and default replacement to empty string for non-matches.
389 /** @var ?Page $matchedPage */
390 $matchedPage = Page::visible()->find($pageId);
393 if ($matchedPage && count($splitInclude) === 1) {
394 // If we only have page id, just insert all page html and continue.
395 $replacement = $matchedPage->html;
396 } elseif ($matchedPage && count($splitInclude) > 1) {
397 // Otherwise, if our include tag defines a section, load that specific content
398 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
399 $replacement = trim($innerContent);
402 $themeReplacement = Theme::dispatch(
403 ThemeEvents::PAGE_INCLUDE_PARSE,
407 $matchedPage ? (clone $matchedPage) : null,
410 // Perform the content replacement
411 $html = str_replace($fullMatch, $themeReplacement ?? $replacement, $html);
418 * Fetch the content from a specific section of the given page.
420 protected function fetchSectionOfPage(Page $page, string $sectionId): string
422 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
423 $doc = $this->loadDocumentFromHtml($page->html);
425 // Search included content for the id given and blank out if not exists.
426 $matchingElem = $doc->getElementById($sectionId);
427 if ($matchingElem === null) {
431 // Otherwise replace the content with the found content
432 // Checks if the top-level wrapper should be included by matching on tag types
434 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
436 $innerContent .= $doc->saveHTML($matchingElem);
438 foreach ($matchingElem->childNodes as $childNode) {
439 $innerContent .= $doc->saveHTML($childNode);
442 libxml_clear_errors();
444 return $innerContent;
448 * Create and load a DOMDocument from the given html content.
450 protected function loadDocumentFromHtml(string $html): DOMDocument
452 libxml_use_internal_errors(true);
453 $doc = new DOMDocument();
454 $html = '<?xml encoding="utf-8" ?><body>' . $html . '</body>';
455 $doc->loadHTML($html);