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\Uploads\ImageRepo;
9 use BookStack\Uploads\ImageService;
10 use BookStack\Util\HtmlContentFilter;
11 use BookStack\Util\HtmlDocument;
15 use Illuminate\Support\Str;
19 public function __construct(
25 * Update the content of the page with new provided HTML.
27 public function setNewHTML(string $html): void
29 $html = $this->extractBase64ImagesFromHtml($html);
30 $this->page->html = $this->formatHtml($html);
31 $this->page->text = $this->toPlainText();
32 $this->page->markdown = '';
36 * Update the content of the page with new provided Markdown content.
38 public function setNewMarkdown(string $markdown): void
40 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
41 $this->page->markdown = $markdown;
42 $html = (new MarkdownToHtml($markdown))->convert();
43 $this->page->html = $this->formatHtml($html);
44 $this->page->text = $this->toPlainText();
48 * Convert all base64 image data to saved images.
50 protected function extractBase64ImagesFromHtml(string $htmlText): string
52 if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
56 $doc = new HtmlDocument($htmlText);
58 // Get all img elements with image data blobs
59 $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]');
60 foreach ($imageNodes as $imageNode) {
61 $imageSrc = $imageNode->getAttribute('src');
62 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
63 $imageNode->setAttribute('src', $newUrl);
66 return $doc->getBodyInnerHtml();
70 * Convert all inline base64 content to uploaded image files.
71 * Regex is used to locate the start of data-uri definitions then
72 * manual looping over content is done to parse the whole data uri.
73 * Attempting to capture the whole data uri using regex can cause PHP
74 * PCRE limits to be hit with larger, multi-MB, files.
76 protected function extractBase64ImagesFromMarkdown(string $markdown): string
79 $contentLength = strlen($markdown);
81 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
83 foreach ($matches[1] as $base64MatchPair) {
84 [$dataUri, $index] = $base64MatchPair;
86 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
87 $char = $markdown[$i];
88 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
94 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
95 $replacements[] = [$dataUri, $newUrl];
98 foreach ($replacements as [$dataUri, $newUrl]) {
99 $markdown = str_replace($dataUri, $newUrl, $markdown);
106 * Parse the given base64 image URI and return the URL to the created image instance.
107 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
109 protected function base64ImageUriToUploadedImageUrl(string $uri): string
111 $imageRepo = app()->make(ImageRepo::class);
112 $imageInfo = $this->parseBase64ImageUri($uri);
114 // Validate extension and content
115 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
119 // Validate that the content is not over our upload limit
120 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
121 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
125 // Save image from data with a random name
126 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
129 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
130 } catch (ImageUploadException $exception) {
138 * Parse a base64 image URI into the data and extension.
140 * @return array{extension: string, data: string}
142 protected function parseBase64ImageUri(string $uri): array
144 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
145 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
148 'extension' => $extension,
149 'data' => base64_decode($base64ImageData) ?: '',
154 * Formats a page's html to be tagged correctly within the system.
156 protected function formatHtml(string $htmlText): string
158 if (empty($htmlText)) {
162 $doc = new HtmlDocument($htmlText);
164 // Map to hold used ID references
166 // Map to hold changing ID references
169 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
170 $this->updateLinks($doc, $changeMap);
172 // Generate inner html as a string & perform required string-level tweaks
173 $html = $doc->getBodyInnerHtml();
174 $html = str_replace(' ', ' ', $html);
180 * For the given DOMNode, traverse its children recursively and update IDs
181 * where required (Top-level, headers & elements with IDs).
182 * Will update the provided $changeMap array with changes made, where keys are the old
183 * ids and the corresponding values are the new ids.
185 protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
187 /* @var DOMNode $child */
188 foreach ($element->childNodes as $child) {
189 if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
190 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
191 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
192 $changeMap[$oldId] = $newId;
196 if ($child->hasChildNodes()) {
197 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
203 * Update the all links in the given xpath to apply requires changes within the
204 * given $changeMap array.
206 protected function updateLinks(HtmlDocument $doc, array $changeMap): void
208 if (empty($changeMap)) {
212 $links = $doc->queryXPath('//body//*//*[@href]');
213 /** @var DOMElement $domElem */
214 foreach ($links as $domElem) {
215 $href = ltrim($domElem->getAttribute('href'), '#');
216 $newHref = $changeMap[$href] ?? null;
218 $domElem->setAttribute('href', '#' . $newHref);
224 * Set a unique id on the given DOMElement.
225 * A map for existing ID's should be passed in to check for current existence,
226 * and this will be updated with any new IDs set upon elements.
227 * Returns a pair of strings in the format [old_id, new_id].
229 protected function setUniqueId(DOMNode $element, array &$idMap): array
231 if (!$element instanceof DOMElement) {
235 // Stop if there's an existing valid id that has not already been used.
236 $existingId = $element->getAttribute('id');
237 if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
238 $idMap[$existingId] = true;
240 return [$existingId, $existingId];
243 // Create a unique id for the element
244 // Uses the content as a basis to ensure output is the same every time
245 // the same content is passed through.
246 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
247 $newId = urlencode($contentId);
250 while (isset($idMap[$newId])) {
251 $newId = urlencode($contentId . '-' . $loopIndex);
255 $element->setAttribute('id', $newId);
256 $idMap[$newId] = true;
258 return [$existingId, $newId];
262 * Get a plain-text visualisation of this page.
264 protected function toPlainText(): string
266 $html = $this->render(true);
268 return html_entity_decode(strip_tags($html));
272 * Render the page for viewing.
274 public function render(bool $blankIncludes = false): string
276 $html = $this->page->html ?? '';
282 $doc = new HtmlDocument($html);
284 $contentProvider = function (int $id) use ($blankIncludes) {
285 if ($blankIncludes) {
288 return Page::visible()->find($id)->html ?? '';
291 $parser = new PageIncludeParser($doc, $contentProvider);
294 for ($includeDepth = 0; $includeDepth < 1 && $nodesAdded !== 0; $includeDepth++) {
295 $nodesAdded = $parser->parse();
298 if ($includeDepth > 1) {
301 $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
304 if (!config('app.allow_content_scripts')) {
305 HtmlContentFilter::removeScriptsFromDocument($doc);
308 return $doc->getBodyInnerHtml();
312 * Parse the headers on the page to get a navigation menu.
314 public function getNavigation(string $htmlContent): array
316 if (empty($htmlContent)) {
320 $doc = new HtmlDocument($htmlContent);
321 $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
323 return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
327 * Convert a DOMNodeList into an array of readable header attributes
328 * with levels normalised to the lower header level.
330 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
332 $tree = collect($nodeList)->map(function (DOMElement $header) {
333 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
334 $text = mb_substr($text, 0, 100);
337 'nodeName' => strtolower($header->nodeName),
338 'level' => intval(str_replace('h', '', $header->nodeName)),
339 'link' => '#' . $header->getAttribute('id'),
342 })->filter(function ($header) {
343 return mb_strlen($header['text']) > 0;
346 // Shift headers if only smaller headers have been used
347 $levelChange = ($tree->pluck('level')->min() - 1);
348 $tree = $tree->map(function ($header) use ($levelChange) {
349 $header['level'] -= ($levelChange);
354 return $tree->toArray();