3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Queries\PageQueries;
7 use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
8 use BookStack\Exceptions\ImageUploadException;
9 use BookStack\Facades\Theme;
10 use BookStack\Theming\ThemeEvents;
11 use BookStack\Uploads\ImageRepo;
12 use BookStack\Uploads\ImageService;
13 use BookStack\Users\Models\User;
14 use BookStack\Util\HtmlContentFilter;
15 use BookStack\Util\HtmlDocument;
16 use BookStack\Util\WebSafeMimeSniffer;
21 use Illuminate\Support\Str;
25 protected PageQueries $pageQueries;
27 public function __construct(
30 $this->pageQueries = app()->make(PageQueries::class);
34 * Update the content of the page with new provided HTML.
36 public function setNewHTML(string $html, User $updater): void
38 $html = $this->extractBase64ImagesFromHtml($html, $updater);
39 $this->page->html = $this->formatHtml($html);
40 $this->page->text = $this->toPlainText();
41 $this->page->markdown = '';
45 * Update the content of the page with new provided Markdown content.
47 public function setNewMarkdown(string $markdown, User $updater): void
49 $markdown = $this->extractBase64ImagesFromMarkdown($markdown, $updater);
50 $this->page->markdown = $markdown;
51 $html = (new MarkdownToHtml($markdown))->convert();
52 $this->page->html = $this->formatHtml($html);
53 $this->page->text = $this->toPlainText();
57 * Convert all base64 image data to saved images.
59 protected function extractBase64ImagesFromHtml(string $htmlText, User $updater): string
61 if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
65 $doc = new HtmlDocument($htmlText);
67 // Get all img elements with image data blobs
68 $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]');
69 /** @var DOMElement $imageNode */
70 foreach ($imageNodes as $imageNode) {
71 $imageSrc = $imageNode->getAttribute('src');
72 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater);
73 $imageNode->setAttribute('src', $newUrl);
76 return $doc->getBodyInnerHtml();
80 * Convert all inline base64 content to uploaded image files.
81 * Regex is used to locate the start of data-uri definitions then
82 * manual looping over content is done to parse the whole data uri.
83 * Attempting to capture the whole data uri using regex can cause PHP
84 * PCRE limits to be hit with larger, multi-MB, files.
86 protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string
89 $contentLength = strlen($markdown);
91 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
93 foreach ($matches[1] as $base64MatchPair) {
94 [$dataUri, $index] = $base64MatchPair;
96 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
97 $char = $markdown[$i];
98 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
104 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater);
105 $replacements[] = [$dataUri, $newUrl];
108 foreach ($replacements as [$dataUri, $newUrl]) {
109 $markdown = str_replace($dataUri, $newUrl, $markdown);
116 * Parse the given base64 image URI and return the URL to the created image instance.
117 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
119 protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string
121 $imageRepo = app()->make(ImageRepo::class);
122 $imageInfo = $this->parseBase64ImageUri($uri);
124 // Validate user has permission to create images
125 if (!$updater->can('image-create-all')) {
129 // Validate extension and content
130 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
134 // Validate content looks like an image via sniffing mime type
135 $mimeSniffer = new WebSafeMimeSniffer();
136 $mime = $mimeSniffer->sniff($imageInfo['data']);
137 if (!str_starts_with($mime, 'image/')) {
141 // Validate that the content is not over our upload limit
142 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
143 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
147 // Save image from data with a random name
148 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
151 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
152 } catch (ImageUploadException $exception) {
160 * Parse a base64 image URI into the data and extension.
162 * @return array{extension: string, data: string}
164 protected function parseBase64ImageUri(string $uri): array
166 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
167 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
170 'extension' => $extension,
171 'data' => base64_decode($base64ImageData) ?: '',
176 * Formats a page's html to be tagged correctly within the system.
178 protected function formatHtml(string $htmlText): string
180 if (empty($htmlText)) {
184 $doc = new HtmlDocument($htmlText);
186 // Map to hold used ID references
188 // Map to hold changing ID references
191 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
192 $this->updateLinks($doc, $changeMap);
194 // Generate inner html as a string & perform required string-level tweaks
195 $html = $doc->getBodyInnerHtml();
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(HtmlDocument $doc, array $changeMap): void
230 if (empty($changeMap)) {
234 $links = $doc->queryXPath('//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 $html = $this->page->html ?? '';
304 $doc = new HtmlDocument($html);
305 $contentProvider = $this->getContentProviderClosure($blankIncludes);
306 $parser = new PageIncludeParser($doc, $contentProvider);
309 for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) {
310 $nodesAdded = $parser->parse();
313 if ($includeDepth > 1) {
316 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
319 if (!config('app.allow_content_scripts')) {
320 HtmlContentFilter::removeScriptsFromDocument($doc);
323 return $doc->getBodyInnerHtml();
327 * Get the closure used to fetch content for page includes.
329 protected function getContentProviderClosure(bool $blankIncludes): Closure
331 $contextPage = $this->page;
332 $queries = $this->pageQueries;
334 return function (PageIncludeTag $tag) use ($blankIncludes, $contextPage, $queries): PageIncludeContent {
335 if ($blankIncludes) {
336 return PageIncludeContent::fromHtmlAndTag('', $tag);
339 $matchedPage = $queries->findVisibleById($tag->getPageId());
340 $content = PageIncludeContent::fromHtmlAndTag($matchedPage->html ?? '', $tag);
342 if (Theme::hasListeners(ThemeEvents::PAGE_INCLUDE_PARSE)) {
343 $themeReplacement = Theme::dispatch(
344 ThemeEvents::PAGE_INCLUDE_PARSE,
348 $matchedPage ? (clone $matchedPage) : null,
351 if ($themeReplacement !== null) {
352 $content = PageIncludeContent::fromInlineHtml(strval($themeReplacement));
361 * Parse the headers on the page to get a navigation menu.
363 public function getNavigation(string $htmlContent): array
365 if (empty($htmlContent)) {
369 $doc = new HtmlDocument($htmlContent);
370 $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
372 return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
376 * Convert a DOMNodeList into an array of readable header attributes
377 * with levels normalised to the lower header level.
379 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
381 $tree = collect($nodeList)->map(function (DOMElement $header) {
382 $text = trim(str_replace("\xc2\xa0", ' ', $header->nodeValue));
383 $text = mb_substr($text, 0, 100);
386 'nodeName' => strtolower($header->nodeName),
387 'level' => intval(str_replace('h', '', $header->nodeName)),
388 'link' => '#' . $header->getAttribute('id'),
391 })->filter(function ($header) {
392 return mb_strlen($header['text']) > 0;
395 // Shift headers if only smaller headers have been used
396 $levelChange = ($tree->pluck('level')->min() - 1);
397 $tree = $tree->map(function ($header) use ($levelChange) {
398 $header['level'] -= ($levelChange);
403 return $tree->toArray();