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;
18 use Illuminate\Support\Str;
25 * PageContent constructor.
27 public function __construct(Page $page)
33 * Update the content of the page with new provided HTML.
35 public function setNewHTML(string $html)
37 $html = $this->extractBase64ImagesFromHtml($html);
38 $this->page->html = $this->formatHtml($html);
39 $this->page->text = $this->toPlainText();
40 $this->page->markdown = '';
44 * Update the content of the page with new provided Markdown content.
46 public function setNewMarkdown(string $markdown)
48 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
49 $this->page->markdown = $markdown;
50 $html = (new MarkdownToHtml($markdown))->convert();
51 $this->page->html = $this->formatHtml($html);
52 $this->page->text = $this->toPlainText();
56 * Convert all base64 image data to saved images.
58 protected function extractBase64ImagesFromHtml(string $htmlText): string
60 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
64 $doc = $this->loadDocumentFromHtml($htmlText);
65 $container = $doc->documentElement;
66 $body = $container->childNodes->item(0);
67 $childNodes = $body->childNodes;
68 $xPath = new DOMXPath($doc);
70 // Get all img elements with image data blobs
71 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
72 foreach ($imageNodes as $imageNode) {
73 $imageSrc = $imageNode->getAttribute('src');
74 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
75 $imageNode->setAttribute('src', $newUrl);
78 // Generate inner html as a string
80 foreach ($childNodes as $childNode) {
81 $html .= $doc->saveHTML($childNode);
88 * Convert all inline base64 content to uploaded image files.
89 * Regex is used to locate the start of data-uri definitions then
90 * manual looping over content is done to parse the whole data uri.
91 * Attempting to capture the whole data uri using regex can cause PHP
92 * PCRE limits to be hit with larger, multi-MB, files.
94 protected function extractBase64ImagesFromMarkdown(string $markdown)
97 $contentLength = strlen($markdown);
99 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
101 foreach ($matches[1] as $base64MatchPair) {
102 [$dataUri, $index] = $base64MatchPair;
104 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
105 $char = $markdown[$i];
106 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
112 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
113 $replacements[] = [$dataUri, $newUrl];
116 foreach ($replacements as [$dataUri, $newUrl]) {
117 $markdown = str_replace($dataUri, $newUrl, $markdown);
124 * Parse the given base64 image URI and return the URL to the created image instance.
125 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
127 protected function base64ImageUriToUploadedImageUrl(string $uri): string
129 $imageRepo = app()->make(ImageRepo::class);
130 $imageInfo = $this->parseBase64ImageUri($uri);
132 // Validate extension and content
133 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
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 = $this->loadDocumentFromHtml($htmlText);
181 $container = $doc->documentElement;
182 $body = $container->childNodes->item(0);
183 $childNodes = $body->childNodes;
184 $xPath = new DOMXPath($doc);
186 // Set ids on top-level nodes
188 foreach ($childNodes as $index => $childNode) {
189 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
190 if ($newId && $newId !== $oldId) {
191 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
195 // Set ids on nested header nodes
196 $nestedHeaders = $xPath->query('//body//*//h1|//body//*//h2|//body//*//h3|//body//*//h4|//body//*//h5|//body//*//h6');
197 foreach ($nestedHeaders as $nestedHeader) {
198 [$oldId, $newId] = $this->setUniqueId($nestedHeader, $idMap);
199 if ($newId && $newId !== $oldId) {
200 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
204 // Ensure no duplicate ids within child items
205 $idElems = $xPath->query('//body//*//*[@id]');
206 foreach ($idElems as $domElem) {
207 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
208 if ($newId && $newId !== $oldId) {
209 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
213 // Generate inner html as a string
215 foreach ($childNodes as $childNode) {
216 $html .= $doc->saveHTML($childNode);
219 // Perform required string-level tweaks
220 $html = str_replace(' ', ' ', $html);
226 * Update the all links to the $old location to instead point to $new.
228 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
230 $old = str_replace('"', '', $old);
231 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
232 foreach ($matchingLinks as $domElem) {
233 $domElem->setAttribute('href', $new);
238 * Set a unique id on the given DOMElement.
239 * A map for existing ID's should be passed in to check for current existence.
240 * Returns a pair of strings in the format [old_id, new_id].
242 protected function setUniqueId(DOMNode $element, array &$idMap): array
244 if (!$element instanceof DOMElement) {
248 // Stop if there's an existing valid id that has not already been used.
249 $existingId = $element->getAttribute('id');
250 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
251 $idMap[$existingId] = true;
253 return [$existingId, $existingId];
256 // Create a unique id for the element
257 // Uses the content as a basis to ensure output is the same every time
258 // the same content is passed through.
259 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
260 $newId = urlencode($contentId);
263 while (isset($idMap[$newId])) {
264 $newId = urlencode($contentId . '-' . $loopIndex);
268 $element->setAttribute('id', $newId);
269 $idMap[$newId] = true;
271 return [$existingId, $newId];
275 * Get a plain-text visualisation of this page.
277 protected function toPlainText(): string
279 $html = $this->render(true);
281 return html_entity_decode(strip_tags($html));
285 * Render the page for viewing.
287 public function render(bool $blankIncludes = false): string
289 $content = $this->page->html ?? '';
291 if (!config('app.allow_content_scripts')) {
292 $content = HtmlContentFilter::removeScripts($content);
295 if ($blankIncludes) {
296 $content = $this->blankPageIncludes($content);
298 $content = $this->parsePageIncludes($content);
305 * Parse the headers on the page to get a navigation menu.
307 public function getNavigation(string $htmlContent): array
309 if (empty($htmlContent)) {
313 $doc = $this->loadDocumentFromHtml($htmlContent);
314 $xPath = new DOMXPath($doc);
315 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
317 return $headers ? $this->headerNodesToLevelList($headers) : [];
321 * Convert a DOMNodeList into an array of readable header attributes
322 * with levels normalised to the lower header level.
324 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
326 $tree = collect($nodeList)->map(function (DOMElement $header) {
327 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
328 $text = mb_substr($text, 0, 100);
331 'nodeName' => strtolower($header->nodeName),
332 'level' => intval(str_replace('h', '', $header->nodeName)),
333 'link' => '#' . $header->getAttribute('id'),
336 })->filter(function ($header) {
337 return mb_strlen($header['text']) > 0;
340 // Shift headers if only smaller headers have been used
341 $levelChange = ($tree->pluck('level')->min() - 1);
342 $tree = $tree->map(function ($header) use ($levelChange) {
343 $header['level'] -= ($levelChange);
348 return $tree->toArray();
352 * Remove any page include tags within the given HTML.
354 protected function blankPageIncludes(string $html): string
356 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
360 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
362 protected function parsePageIncludes(string $html): string
365 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
367 foreach ($matches[1] as $index => $includeId) {
368 $fullMatch = $matches[0][$index];
369 $splitInclude = explode('#', $includeId, 2);
371 // Get page id from reference
372 $pageId = intval($splitInclude[0]);
373 if (is_nan($pageId)) {
377 // Find page to use, and default replacement to empty string for non-matches.
378 /** @var ?Page $matchedPage */
379 $matchedPage = Page::visible()->find($pageId);
382 if ($matchedPage && count($splitInclude) === 1) {
383 // If we only have page id, just insert all page html and continue.
384 $replacement = $matchedPage->html;
385 } elseif ($matchedPage && count($splitInclude) > 1) {
386 // Otherwise, if our include tag defines a section, load that specific content
387 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
388 $replacement = trim($innerContent);
391 $themeReplacement = Theme::dispatch(
392 ThemeEvents::PAGE_INCLUDE_PARSE,
396 $matchedPage ? (clone $matchedPage) : null,
399 // Perform the content replacement
400 $html = str_replace($fullMatch, $themeReplacement ?? $replacement, $html);
407 * Fetch the content from a specific section of the given page.
409 protected function fetchSectionOfPage(Page $page, string $sectionId): string
411 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
412 $doc = $this->loadDocumentFromHtml($page->html);
414 // Search included content for the id given and blank out if not exists.
415 $matchingElem = $doc->getElementById($sectionId);
416 if ($matchingElem === null) {
420 // Otherwise replace the content with the found content
421 // Checks if the top-level wrapper should be included by matching on tag types
423 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
425 $innerContent .= $doc->saveHTML($matchingElem);
427 foreach ($matchingElem->childNodes as $childNode) {
428 $innerContent .= $doc->saveHTML($childNode);
431 libxml_clear_errors();
433 return $innerContent;
437 * Create and load a DOMDocument from the given html content.
439 protected function loadDocumentFromHtml(string $html): DOMDocument
441 libxml_use_internal_errors(true);
442 $doc = new DOMDocument();
443 $html = '<body>' . $html . '</body>';
444 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));