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;
13 use BookStack\Util\HtmlDocument;
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 = new HtmlDocument($htmlText);
61 // Get all img elements with image data blobs
62 $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]');
63 foreach ($imageNodes as $imageNode) {
64 $imageSrc = $imageNode->getAttribute('src');
65 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
66 $imageNode->setAttribute('src', $newUrl);
69 return $doc->getBodyInnerHtml();
73 * Convert all inline base64 content to uploaded image files.
74 * Regex is used to locate the start of data-uri definitions then
75 * manual looping over content is done to parse the whole data uri.
76 * Attempting to capture the whole data uri using regex can cause PHP
77 * PCRE limits to be hit with larger, multi-MB, files.
79 protected function extractBase64ImagesFromMarkdown(string $markdown): string
82 $contentLength = strlen($markdown);
84 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
86 foreach ($matches[1] as $base64MatchPair) {
87 [$dataUri, $index] = $base64MatchPair;
89 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
90 $char = $markdown[$i];
91 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
97 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
98 $replacements[] = [$dataUri, $newUrl];
101 foreach ($replacements as [$dataUri, $newUrl]) {
102 $markdown = str_replace($dataUri, $newUrl, $markdown);
109 * Parse the given base64 image URI and return the URL to the created image instance.
110 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
112 protected function base64ImageUriToUploadedImageUrl(string $uri): string
114 $imageRepo = app()->make(ImageRepo::class);
115 $imageInfo = $this->parseBase64ImageUri($uri);
117 // Validate extension and content
118 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
122 // Validate that the content is not over our upload limit
123 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
124 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
128 // Save image from data with a random name
129 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
132 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
133 } catch (ImageUploadException $exception) {
141 * Parse a base64 image URI into the data and extension.
143 * @return array{extension: string, data: string}
145 protected function parseBase64ImageUri(string $uri): array
147 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
148 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
151 'extension' => $extension,
152 'data' => base64_decode($base64ImageData) ?: '',
157 * Formats a page's html to be tagged correctly within the system.
159 protected function formatHtml(string $htmlText): string
161 if (empty($htmlText)) {
165 $doc = new HtmlDocument($htmlText);
167 // Map to hold used ID references
169 // Map to hold changing ID references
172 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
173 $this->updateLinks($doc, $changeMap);
175 // Generate inner html as a string & perform required string-level tweaks
176 $html = $doc->getBodyInnerHtml();
177 $html = str_replace(' ', ' ', $html);
183 * For the given DOMNode, traverse its children recursively and update IDs
184 * where required (Top-level, headers & elements with IDs).
185 * Will update the provided $changeMap array with changes made, where keys are the old
186 * ids and the corresponding values are the new ids.
188 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
190 /* @var DOMNode $child */
191 foreach ($element->childNodes as $child) {
192 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
193 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
194 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
195 $changeMap[$oldId] = $newId;
199 if ($child->hasChildNodes()) {
200 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
206 * Update the all links in the given xpath to apply requires changes within the
207 * given $changeMap array.
209 protected function updateLinks(HtmlDocument $doc, array $changeMap): void
211 if (empty($changeMap)) {
215 $links = $doc->queryXPath('//body//*//*[@href]');
216 /** @var DOMElement $domElem */
217 foreach ($links as $domElem) {
218 $href = ltrim($domElem->getAttribute('href'), '#');
219 $newHref = $changeMap[$href] ?? null;
221 $domElem->setAttribute('href', '#' . $newHref);
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 * and this will be updated with any new IDs set upon elements.
230 * Returns a pair of strings in the format [old_id, new_id].
232 protected function setUniqueId(DOMNode $element, array &$idMap): array
234 if (!$element instanceof DOMElement) {
238 // Stop if there's an existing valid id that has not already been used.
239 $existingId = $element->getAttribute('id');
240 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
241 $idMap[$existingId] = true;
243 return [$existingId, $existingId];
246 // Create a unique id for the element
247 // Uses the content as a basis to ensure output is the same every time
248 // the same content is passed through.
249 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
250 $newId = urlencode($contentId);
253 while (isset($idMap[$newId])) {
254 $newId = urlencode($contentId . '-' . $loopIndex);
258 $element->setAttribute('id', $newId);
259 $idMap[$newId] = true;
261 return [$existingId, $newId];
265 * Get a plain-text visualisation of this page.
267 protected function toPlainText(): string
269 $html = $this->render(true);
271 return html_entity_decode(strip_tags($html));
275 * Render the page for viewing.
277 public function render(bool $blankIncludes = false): string
279 $html = $this->page->html ?? '';
285 $doc = new HtmlDocument($html);
286 $contentProvider = $this->getContentProviderClosure($blankIncludes);
287 $parser = new PageIncludeParser($doc, $contentProvider);
290 for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) {
291 $nodesAdded = $parser->parse();
294 if ($includeDepth > 1) {
297 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
300 if (!config('app.allow_content_scripts')) {
301 HtmlContentFilter::removeScriptsFromDocument($doc);
304 return $doc->getBodyInnerHtml();
308 * Get the closure used to fetch content for page includes.
310 protected function getContentProviderClosure(bool $blankIncludes): Closure
312 $contextPage = $this->page;
314 return function (PageIncludeTag $tag) use ($blankIncludes, $contextPage): PageIncludeContent {
315 if ($blankIncludes) {
316 return PageIncludeContent::fromHtmlAndTag('', $tag);
319 $matchedPage = Page::visible()->find($tag->getPageId());
320 $content = PageIncludeContent::fromHtmlAndTag($matchedPage->html ?? '', $tag);
322 if (Theme::hasListeners(ThemeEvents::PAGE_INCLUDE_PARSE)) {
323 $themeReplacement = Theme::dispatch(
324 ThemeEvents::PAGE_INCLUDE_PARSE,
328 $matchedPage ? (clone $matchedPage) : null,
331 if ($themeReplacement !== null) {
332 $content = PageIncludeContent::fromInlineHtml(strval($themeReplacement));
341 * Parse the headers on the page to get a navigation menu.
343 public function getNavigation(string $htmlContent): array
345 if (empty($htmlContent)) {
349 $doc = new HtmlDocument($htmlContent);
350 $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
352 return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
356 * Convert a DOMNodeList into an array of readable header attributes
357 * with levels normalised to the lower header level.
359 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
361 $tree = collect($nodeList)->map(function (DOMElement $header) {
362 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
363 $text = mb_substr($text, 0, 100);
366 'nodeName' => strtolower($header->nodeName),
367 'level' => intval(str_replace('h', '', $header->nodeName)),
368 'link' => '#' . $header->getAttribute('id'),
371 })->filter(function ($header) {
372 return mb_strlen($header['text']) > 0;
375 // Shift headers if only smaller headers have been used
376 $levelChange = ($tree->pluck('level')->min() - 1);
377 $tree = $tree->map(function ($header) use ($levelChange) {
378 $header['level'] -= ($levelChange);
383 return $tree->toArray();