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 foreach ($imageNodes as $imageNode) {
66 $imageSrc = $imageNode->getAttribute('src');
67 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater);
68 $imageNode->setAttribute('src', $newUrl);
71 return $doc->getBodyInnerHtml();
75 * Convert all inline base64 content to uploaded image files.
76 * Regex is used to locate the start of data-uri definitions then
77 * manual looping over content is done to parse the whole data uri.
78 * Attempting to capture the whole data uri using regex can cause PHP
79 * PCRE limits to be hit with larger, multi-MB, files.
81 protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string
84 $contentLength = strlen($markdown);
86 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
88 foreach ($matches[1] as $base64MatchPair) {
89 [$dataUri, $index] = $base64MatchPair;
91 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
92 $char = $markdown[$i];
93 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
99 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater);
100 $replacements[] = [$dataUri, $newUrl];
103 foreach ($replacements as [$dataUri, $newUrl]) {
104 $markdown = str_replace($dataUri, $newUrl, $markdown);
111 * Parse the given base64 image URI and return the URL to the created image instance.
112 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
114 protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string
116 $imageRepo = app()->make(ImageRepo::class);
117 $imageInfo = $this->parseBase64ImageUri($uri);
119 // Validate user has permission to create images
120 if (!$updater->can('image-create-all')) {
124 // Validate extension and content
125 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
129 // Validate content looks like an image via sniffing mime type
130 $mimeSniffer = new WebSafeMimeSniffer();
131 $mime = $mimeSniffer->sniff($imageInfo['data']);
132 if (!str_starts_with($mime, 'image/')) {
136 // Validate that the content is not over our upload limit
137 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
138 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
142 // Save image from data with a random name
143 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
146 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
147 } catch (ImageUploadException $exception) {
155 * Parse a base64 image URI into the data and extension.
157 * @return array{extension: string, data: string}
159 protected function parseBase64ImageUri(string $uri): array
161 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
162 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
165 'extension' => $extension,
166 'data' => base64_decode($base64ImageData) ?: '',
171 * Formats a page's html to be tagged correctly within the system.
173 protected function formatHtml(string $htmlText): string
175 if (empty($htmlText)) {
179 $doc = new HtmlDocument($htmlText);
181 // Map to hold used ID references
183 // Map to hold changing ID references
186 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
187 $this->updateLinks($doc, $changeMap);
189 // Generate inner html as a string & perform required string-level tweaks
190 $html = $doc->getBodyInnerHtml();
191 $html = str_replace(' ', ' ', $html);
197 * For the given DOMNode, traverse its children recursively and update IDs
198 * where required (Top-level, headers & elements with IDs).
199 * Will update the provided $changeMap array with changes made, where keys are the old
200 * ids and the corresponding values are the new ids.
202 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
204 /* @var DOMNode $child */
205 foreach ($element->childNodes as $child) {
206 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
207 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
208 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
209 $changeMap[$oldId] = $newId;
213 if ($child->hasChildNodes()) {
214 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
220 * Update the all links in the given xpath to apply requires changes within the
221 * given $changeMap array.
223 protected function updateLinks(HtmlDocument $doc, array $changeMap): void
225 if (empty($changeMap)) {
229 $links = $doc->queryXPath('//body//*//*[@href]');
230 /** @var DOMElement $domElem */
231 foreach ($links as $domElem) {
232 $href = ltrim($domElem->getAttribute('href'), '#');
233 $newHref = $changeMap[$href] ?? null;
235 $domElem->setAttribute('href', '#' . $newHref);
241 * Set a unique id on the given DOMElement.
242 * A map for existing ID's should be passed in to check for current existence,
243 * and this will be updated with any new IDs set upon elements.
244 * Returns a pair of strings in the format [old_id, new_id].
246 protected function setUniqueId(DOMNode $element, array &$idMap): array
248 if (!$element instanceof DOMElement) {
252 // Stop if there's an existing valid id that has not already been used.
253 $existingId = $element->getAttribute('id');
254 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
255 $idMap[$existingId] = true;
257 return [$existingId, $existingId];
260 // Create a unique id for the element
261 // Uses the content as a basis to ensure output is the same every time
262 // the same content is passed through.
263 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
264 $newId = urlencode($contentId);
267 while (isset($idMap[$newId])) {
268 $newId = urlencode($contentId . '-' . $loopIndex);
272 $element->setAttribute('id', $newId);
273 $idMap[$newId] = true;
275 return [$existingId, $newId];
279 * Get a plain-text visualisation of this page.
281 protected function toPlainText(): string
283 $html = $this->render(true);
285 return html_entity_decode(strip_tags($html));
289 * Render the page for viewing.
291 public function render(bool $blankIncludes = false): string
293 $html = $this->page->html ?? '';
299 $doc = new HtmlDocument($html);
300 $contentProvider = $this->getContentProviderClosure($blankIncludes);
301 $parser = new PageIncludeParser($doc, $contentProvider);
304 for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) {
305 $nodesAdded = $parser->parse();
308 if ($includeDepth > 1) {
311 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
314 if (!config('app.allow_content_scripts')) {
315 HtmlContentFilter::removeScriptsFromDocument($doc);
318 return $doc->getBodyInnerHtml();
322 * Get the closure used to fetch content for page includes.
324 protected function getContentProviderClosure(bool $blankIncludes): Closure
326 $contextPage = $this->page;
328 return function (PageIncludeTag $tag) use ($blankIncludes, $contextPage): PageIncludeContent {
329 if ($blankIncludes) {
330 return PageIncludeContent::fromHtmlAndTag('', $tag);
333 $matchedPage = Page::visible()->find($tag->getPageId());
334 $content = PageIncludeContent::fromHtmlAndTag($matchedPage->html ?? '', $tag);
336 if (Theme::hasListeners(ThemeEvents::PAGE_INCLUDE_PARSE)) {
337 $themeReplacement = Theme::dispatch(
338 ThemeEvents::PAGE_INCLUDE_PARSE,
342 $matchedPage ? (clone $matchedPage) : null,
345 if ($themeReplacement !== null) {
346 $content = PageIncludeContent::fromInlineHtml(strval($themeReplacement));
355 * Parse the headers on the page to get a navigation menu.
357 public function getNavigation(string $htmlContent): array
359 if (empty($htmlContent)) {
363 $doc = new HtmlDocument($htmlContent);
364 $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
366 return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
370 * Convert a DOMNodeList into an array of readable header attributes
371 * with levels normalised to the lower header level.
373 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
375 $tree = collect($nodeList)->map(function (DOMElement $header) {
376 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
377 $text = mb_substr($text, 0, 100);
380 'nodeName' => strtolower($header->nodeName),
381 'level' => intval(str_replace('h', '', $header->nodeName)),
382 'link' => '#' . $header->getAttribute('id'),
385 })->filter(function ($header) {
386 return mb_strlen($header['text']) > 0;
389 // Shift headers if only smaller headers have been used
390 $levelChange = ($tree->pluck('level')->min() - 1);
391 $tree = $tree->map(function ($header) use ($levelChange) {
392 $header['level'] -= ($levelChange);
397 return $tree->toArray();