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\HtmlDocument;
15 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 = new HtmlDocument($htmlText);
63 // Get all img elements with image data blobs
64 $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]');
65 /** @var DOMElement $imageNode */
66 foreach ($imageNodes as $imageNode) {
67 $imageSrc = $imageNode->getAttribute('src');
68 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater);
69 $imageNode->setAttribute('src', $newUrl);
72 return $doc->getBodyInnerHtml();
76 * Convert all inline base64 content to uploaded image files.
77 * Regex is used to locate the start of data-uri definitions then
78 * manual looping over content is done to parse the whole data uri.
79 * Attempting to capture the whole data uri using regex can cause PHP
80 * PCRE limits to be hit with larger, multi-MB, files.
82 protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string
85 $contentLength = strlen($markdown);
87 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
89 foreach ($matches[1] as $base64MatchPair) {
90 [$dataUri, $index] = $base64MatchPair;
92 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
93 $char = $markdown[$i];
94 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
100 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater);
101 $replacements[] = [$dataUri, $newUrl];
104 foreach ($replacements as [$dataUri, $newUrl]) {
105 $markdown = str_replace($dataUri, $newUrl, $markdown);
112 * Parse the given base64 image URI and return the URL to the created image instance.
113 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
115 protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string
117 $imageRepo = app()->make(ImageRepo::class);
118 $imageInfo = $this->parseBase64ImageUri($uri);
120 // Validate user has permission to create images
121 if (!$updater->can('image-create-all')) {
125 // Validate extension and content
126 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
130 // Validate content looks like an image via sniffing mime type
131 $mimeSniffer = new WebSafeMimeSniffer();
132 $mime = $mimeSniffer->sniff($imageInfo['data']);
133 if (!str_starts_with($mime, 'image/')) {
137 // Validate that the content is not over our upload limit
138 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
139 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
143 // Save image from data with a random name
144 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
147 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
148 } catch (ImageUploadException $exception) {
156 * Parse a base64 image URI into the data and extension.
158 * @return array{extension: string, data: string}
160 protected function parseBase64ImageUri(string $uri): array
162 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
163 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
166 'extension' => $extension,
167 'data' => base64_decode($base64ImageData) ?: '',
172 * Formats a page's html to be tagged correctly within the system.
174 protected function formatHtml(string $htmlText): string
176 if (empty($htmlText)) {
180 $doc = new HtmlDocument($htmlText);
182 // Map to hold used ID references
184 // Map to hold changing ID references
187 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
188 $this->updateLinks($doc, $changeMap);
190 // Generate inner html as a string & perform required string-level tweaks
191 $html = $doc->getBodyInnerHtml();
192 $html = str_replace(' ', ' ', $html);
198 * For the given DOMNode, traverse its children recursively and update IDs
199 * where required (Top-level, headers & elements with IDs).
200 * Will update the provided $changeMap array with changes made, where keys are the old
201 * ids and the corresponding values are the new ids.
203 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
205 /* @var DOMNode $child */
206 foreach ($element->childNodes as $child) {
207 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
208 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
209 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
210 $changeMap[$oldId] = $newId;
214 if ($child->hasChildNodes()) {
215 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
221 * Update the all links in the given xpath to apply requires changes within the
222 * given $changeMap array.
224 protected function updateLinks(HtmlDocument $doc, array $changeMap): void
226 if (empty($changeMap)) {
230 $links = $doc->queryXPath('//body//*//*[@href]');
231 /** @var DOMElement $domElem */
232 foreach ($links as $domElem) {
233 $href = ltrim($domElem->getAttribute('href'), '#');
234 $newHref = $changeMap[$href] ?? null;
236 $domElem->setAttribute('href', '#' . $newHref);
242 * Set a unique id on the given DOMElement.
243 * A map for existing ID's should be passed in to check for current existence,
244 * and this will be updated with any new IDs set upon elements.
245 * Returns a pair of strings in the format [old_id, new_id].
247 protected function setUniqueId(DOMNode $element, array &$idMap): array
249 if (!$element instanceof DOMElement) {
253 // Stop if there's an existing valid id that has not already been used.
254 $existingId = $element->getAttribute('id');
255 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
256 $idMap[$existingId] = true;
258 return [$existingId, $existingId];
261 // Create a unique id for the element
262 // Uses the content as a basis to ensure output is the same every time
263 // the same content is passed through.
264 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
265 $newId = urlencode($contentId);
268 while (isset($idMap[$newId])) {
269 $newId = urlencode($contentId . '-' . $loopIndex);
273 $element->setAttribute('id', $newId);
274 $idMap[$newId] = true;
276 return [$existingId, $newId];
280 * Get a plain-text visualisation of this page.
282 protected function toPlainText(): string
284 $html = $this->render(true);
286 return html_entity_decode(strip_tags($html));
290 * Render the page for viewing.
292 public function render(bool $blankIncludes = false): string
294 $html = $this->page->html ?? '';
300 $doc = new HtmlDocument($html);
301 $contentProvider = $this->getContentProviderClosure($blankIncludes);
302 $parser = new PageIncludeParser($doc, $contentProvider);
305 for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) {
306 $nodesAdded = $parser->parse();
309 if ($includeDepth > 1) {
312 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
315 if (!config('app.allow_content_scripts')) {
316 HtmlContentFilter::removeScriptsFromDocument($doc);
319 return $doc->getBodyInnerHtml();
323 * Get the closure used to fetch content for page includes.
325 protected function getContentProviderClosure(bool $blankIncludes): Closure
327 $contextPage = $this->page;
329 return function (PageIncludeTag $tag) use ($blankIncludes, $contextPage): PageIncludeContent {
330 if ($blankIncludes) {
331 return PageIncludeContent::fromHtmlAndTag('', $tag);
334 $matchedPage = Page::visible()->find($tag->getPageId());
335 $content = PageIncludeContent::fromHtmlAndTag($matchedPage->html ?? '', $tag);
337 if (Theme::hasListeners(ThemeEvents::PAGE_INCLUDE_PARSE)) {
338 $themeReplacement = Theme::dispatch(
339 ThemeEvents::PAGE_INCLUDE_PARSE,
343 $matchedPage ? (clone $matchedPage) : null,
346 if ($themeReplacement !== null) {
347 $content = PageIncludeContent::fromInlineHtml(strval($themeReplacement));
356 * Parse the headers on the page to get a navigation menu.
358 public function getNavigation(string $htmlContent): array
360 if (empty($htmlContent)) {
364 $doc = new HtmlDocument($htmlContent);
365 $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
367 return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
371 * Convert a DOMNodeList into an array of readable header attributes
372 * with levels normalised to the lower header level.
374 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
376 $tree = collect($nodeList)->map(function (DOMElement $header) {
377 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
378 $text = mb_substr($text, 0, 100);
381 'nodeName' => strtolower($header->nodeName),
382 'level' => intval(str_replace('h', '', $header->nodeName)),
383 'link' => '#' . $header->getAttribute('id'),
386 })->filter(function ($header) {
387 return mb_strlen($header['text']) > 0;
390 // Shift headers if only smaller headers have been used
391 $levelChange = ($tree->pluck('level')->min() - 1);
392 $tree = $tree->map(function ($header) use ($levelChange) {
393 $header['level'] -= ($levelChange);
398 return $tree->toArray();