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;
17 use Illuminate\Support\Str;
21 public function __construct(
27 * Update the content of the page with new provided HTML.
29 public function setNewHTML(string $html): void
31 $html = $this->extractBase64ImagesFromHtml($html);
32 $this->page->html = $this->formatHtml($html);
33 $this->page->text = $this->toPlainText();
34 $this->page->markdown = '';
38 * Update the content of the page with new provided Markdown content.
40 public function setNewMarkdown(string $markdown): void
42 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
43 $this->page->markdown = $markdown;
44 $html = (new MarkdownToHtml($markdown))->convert();
45 $this->page->html = $this->formatHtml($html);
46 $this->page->text = $this->toPlainText();
50 * Convert all base64 image data to saved images.
52 protected function extractBase64ImagesFromHtml(string $htmlText): string
54 if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
58 $doc = new HtmlDocument($htmlText);
60 // Get all img elements with image data blobs
61 $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]');
62 foreach ($imageNodes as $imageNode) {
63 $imageSrc = $imageNode->getAttribute('src');
64 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
65 $imageNode->setAttribute('src', $newUrl);
68 return $doc->getBodyInnerHtml();
72 * Convert all inline base64 content to uploaded image files.
73 * Regex is used to locate the start of data-uri definitions then
74 * manual looping over content is done to parse the whole data uri.
75 * Attempting to capture the whole data uri using regex can cause PHP
76 * PCRE limits to be hit with larger, multi-MB, files.
78 protected function extractBase64ImagesFromMarkdown(string $markdown): string
81 $contentLength = strlen($markdown);
83 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
85 foreach ($matches[1] as $base64MatchPair) {
86 [$dataUri, $index] = $base64MatchPair;
88 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
89 $char = $markdown[$i];
90 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
96 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
97 $replacements[] = [$dataUri, $newUrl];
100 foreach ($replacements as [$dataUri, $newUrl]) {
101 $markdown = str_replace($dataUri, $newUrl, $markdown);
108 * Parse the given base64 image URI and return the URL to the created image instance.
109 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
111 protected function base64ImageUriToUploadedImageUrl(string $uri): string
113 $imageRepo = app()->make(ImageRepo::class);
114 $imageInfo = $this->parseBase64ImageUri($uri);
116 // Validate extension and content
117 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
121 // Validate that the content is not over our upload limit
122 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
123 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
127 // Save image from data with a random name
128 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
131 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
132 } catch (ImageUploadException $exception) {
140 * Parse a base64 image URI into the data and extension.
142 * @return array{extension: string, data: string}
144 protected function parseBase64ImageUri(string $uri): array
146 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
147 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
150 'extension' => $extension,
151 'data' => base64_decode($base64ImageData) ?: '',
156 * Formats a page's html to be tagged correctly within the system.
158 protected function formatHtml(string $htmlText): string
160 if (empty($htmlText)) {
164 $doc = new HtmlDocument($htmlText);
166 // Map to hold used ID references
168 // Map to hold changing ID references
171 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
172 $this->updateLinks($doc, $changeMap);
174 // Generate inner html as a string & perform required string-level tweaks
175 $html = $doc->getBodyInnerHtml();
176 $html = str_replace(' ', ' ', $html);
182 * For the given DOMNode, traverse its children recursively and update IDs
183 * where required (Top-level, headers & elements with IDs).
184 * Will update the provided $changeMap array with changes made, where keys are the old
185 * ids and the corresponding values are the new ids.
187 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
189 /* @var DOMNode $child */
190 foreach ($element->childNodes as $child) {
191 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
192 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
193 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
194 $changeMap[$oldId] = $newId;
198 if ($child->hasChildNodes()) {
199 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
205 * Update the all links in the given xpath to apply requires changes within the
206 * given $changeMap array.
208 protected function updateLinks(HtmlDocument $doc, array $changeMap): void
210 if (empty($changeMap)) {
214 $links = $doc->queryXPath('//body//*//*[@href]');
215 /** @var DOMElement $domElem */
216 foreach ($links as $domElem) {
217 $href = ltrim($domElem->getAttribute('href'), '#');
218 $newHref = $changeMap[$href] ?? null;
220 $domElem->setAttribute('href', '#' . $newHref);
226 * Set a unique id on the given DOMElement.
227 * A map for existing ID's should be passed in to check for current existence,
228 * and this will be updated with any new IDs set upon elements.
229 * Returns a pair of strings in the format [old_id, new_id].
231 protected function setUniqueId(DOMNode $element, array &$idMap): array
233 if (!$element instanceof DOMElement) {
237 // Stop if there's an existing valid id that has not already been used.
238 $existingId = $element->getAttribute('id');
239 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
240 $idMap[$existingId] = true;
242 return [$existingId, $existingId];
245 // Create a unique id for the element
246 // Uses the content as a basis to ensure output is the same every time
247 // the same content is passed through.
248 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
249 $newId = urlencode($contentId);
252 while (isset($idMap[$newId])) {
253 $newId = urlencode($contentId . '-' . $loopIndex);
257 $element->setAttribute('id', $newId);
258 $idMap[$newId] = true;
260 return [$existingId, $newId];
264 * Get a plain-text visualisation of this page.
266 protected function toPlainText(): string
268 $html = $this->render(true);
270 return html_entity_decode(strip_tags($html));
274 * Render the page for viewing.
276 public function render(bool $blankIncludes = false): string
278 $content = $this->page->html ?? '';
280 if (!config('app.allow_content_scripts')) {
281 $content = HtmlContentFilter::removeScripts($content);
284 if ($blankIncludes) {
285 $content = $this->blankPageIncludes($content);
287 for ($includeDepth = 0; $includeDepth < 3; $includeDepth++) {
288 $content = $this->parsePageIncludes($content);
296 * Parse the headers on the page to get a navigation menu.
298 public function getNavigation(string $htmlContent): array
300 if (empty($htmlContent)) {
304 $doc = new HtmlDocument($htmlContent);
305 $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
307 return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
311 * Convert a DOMNodeList into an array of readable header attributes
312 * with levels normalised to the lower header level.
314 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
316 $tree = collect($nodeList)->map(function (DOMElement $header) {
317 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
318 $text = mb_substr($text, 0, 100);
321 'nodeName' => strtolower($header->nodeName),
322 'level' => intval(str_replace('h', '', $header->nodeName)),
323 'link' => '#' . $header->getAttribute('id'),
326 })->filter(function ($header) {
327 return mb_strlen($header['text']) > 0;
330 // Shift headers if only smaller headers have been used
331 $levelChange = ($tree->pluck('level')->min() - 1);
332 $tree = $tree->map(function ($header) use ($levelChange) {
333 $header['level'] -= ($levelChange);
338 return $tree->toArray();
342 * Remove any page include tags within the given HTML.
344 protected function blankPageIncludes(string $html): string
346 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
350 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
352 protected function parsePageIncludes(string $html): string
355 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
357 foreach ($matches[1] as $index => $includeId) {
358 $fullMatch = $matches[0][$index];
359 $splitInclude = explode('#', $includeId, 2);
361 // Get page id from reference
362 $pageId = intval($splitInclude[0]);
363 if (is_nan($pageId)) {
367 // Find page to use, and default replacement to empty string for non-matches.
368 /** @var ?Page $matchedPage */
369 $matchedPage = Page::visible()->find($pageId);
372 if ($matchedPage && count($splitInclude) === 1) {
373 // If we only have page id, just insert all page html and continue.
374 $replacement = $matchedPage->html;
375 } elseif ($matchedPage && count($splitInclude) > 1) {
376 // Otherwise, if our include tag defines a section, load that specific content
377 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
378 $replacement = trim($innerContent);
381 $themeReplacement = Theme::dispatch(
382 ThemeEvents::PAGE_INCLUDE_PARSE,
386 $matchedPage ? (clone $matchedPage) : null,
389 // Perform the content replacement
390 $html = str_replace($fullMatch, $themeReplacement ?? $replacement, $html);
397 * Fetch the content from a specific section of the given page.
399 protected function fetchSectionOfPage(Page $page, string $sectionId): string
401 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
402 $doc = new HtmlDocument($page->html);
404 // Search included content for the id given and blank out if not exists.
405 $matchingElem = $doc->getElementById($sectionId);
406 if ($matchingElem === null) {
410 // Otherwise replace the content with the found content
411 // Checks if the top-level wrapper should be included by matching on tag types
412 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
414 return $doc->getNodeOuterHtml($matchingElem);
417 return $doc->getNodeInnerHtml($matchingElem);