3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Tools\Markdown\CustomListItemRenderer;
7 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
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\Util\HtmlContentFilter;
19 use Illuminate\Support\Str;
20 use League\CommonMark\Block\Element\ListItem;
21 use League\CommonMark\CommonMarkConverter;
22 use League\CommonMark\Environment;
23 use League\CommonMark\Extension\Table\TableExtension;
24 use League\CommonMark\Extension\TaskList\TaskListExtension;
31 * PageContent constructor.
33 public function __construct(Page $page)
39 * Update the content of the page with new provided HTML.
41 public function setNewHTML(string $html)
43 $html = $this->extractBase64ImagesFromHtml($html);
44 $this->page->html = $this->formatHtml($html);
45 $this->page->text = $this->toPlainText();
46 $this->page->markdown = '';
50 * Update the content of the page with new provided Markdown content.
52 public function setNewMarkdown(string $markdown)
54 $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
55 $this->page->markdown = $markdown;
56 $html = $this->markdownToHtml($markdown);
57 $this->page->html = $this->formatHtml($html);
58 $this->page->text = $this->toPlainText();
62 * Convert the given Markdown content to a HTML string.
64 protected function markdownToHtml(string $markdown): string
66 $environment = Environment::createCommonMarkEnvironment();
67 $environment->addExtension(new TableExtension());
68 $environment->addExtension(new TaskListExtension());
69 $environment->addExtension(new CustomStrikeThroughExtension());
70 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
71 $converter = new CommonMarkConverter([], $environment);
73 $environment->addBlockRenderer(ListItem::class, new CustomListItemRenderer(), 10);
75 return $converter->convertToHtml($markdown);
79 * Convert all base64 image data to saved images.
81 protected function extractBase64ImagesFromHtml(string $htmlText): string
83 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
87 $doc = $this->loadDocumentFromHtml($htmlText);
88 $container = $doc->documentElement;
89 $body = $container->childNodes->item(0);
90 $childNodes = $body->childNodes;
91 $xPath = new DOMXPath($doc);
93 // Get all img elements with image data blobs
94 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
95 foreach ($imageNodes as $imageNode) {
96 $imageSrc = $imageNode->getAttribute('src');
97 $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
98 $imageNode->setAttribute('src', $newUrl);
101 // Generate inner html as a string
103 foreach ($childNodes as $childNode) {
104 $html .= $doc->saveHTML($childNode);
111 * Convert all inline base64 content to uploaded image files.
112 * Regex is used to locate the start of data-uri definitions then
113 * manual looping over content is done to parse the whole data uri.
114 * Attempting to capture the whole data uri using regex can cause PHP
115 * PCRE limits to be hit with larger, multi-MB, files.
117 protected function extractBase64ImagesFromMarkdown(string $markdown)
120 $contentLength = strlen($markdown);
122 preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
124 foreach ($matches[1] as $base64MatchPair) {
125 [$dataUri, $index] = $base64MatchPair;
127 for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
128 $char = $markdown[$i];
129 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
135 $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
136 $replacements[] = [$dataUri, $newUrl];
139 foreach ($replacements as [$dataUri, $newUrl]) {
140 $markdown = str_replace($dataUri, $newUrl, $markdown);
147 * Parse the given base64 image URI and return the URL to the created image instance.
148 * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
150 protected function base64ImageUriToUploadedImageUrl(string $uri): string
152 $imageRepo = app()->make(ImageRepo::class);
153 $imageInfo = $this->parseBase64ImageUri($uri);
155 // Validate extension and content
156 if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
160 // Validate that the content is not over our upload limit
161 $uploadLimitBytes = (config('app.upload_limit') * 1000000);
162 if (strlen($imageInfo['data']) > $uploadLimitBytes) {
166 // Save image from data with a random name
167 $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
170 $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
171 } catch (ImageUploadException $exception) {
179 * Parse a base64 image URI into the data and extension.
181 * @return array{extension: string, data: string}
183 protected function parseBase64ImageUri(string $uri): array
185 [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
186 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
189 'extension' => $extension,
190 'data' => base64_decode($base64ImageData) ?: '',
195 * Formats a page's html to be tagged correctly within the system.
197 protected function formatHtml(string $htmlText): string
199 if (empty($htmlText)) {
203 $doc = $this->loadDocumentFromHtml($htmlText);
204 $container = $doc->documentElement;
205 $body = $container->childNodes->item(0);
206 $childNodes = $body->childNodes;
207 $xPath = new DOMXPath($doc);
209 // Set ids on top-level nodes
211 foreach ($childNodes as $index => $childNode) {
212 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
213 if ($newId && $newId !== $oldId) {
214 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
218 // Set ids on nested header nodes
219 $nestedHeaders = $xPath->query('//body//*//h1|//body//*//h2|//body//*//h3|//body//*//h4|//body//*//h5|//body//*//h6');
220 foreach ($nestedHeaders as $nestedHeader) {
221 [$oldId, $newId] = $this->setUniqueId($nestedHeader, $idMap);
222 if ($newId && $newId !== $oldId) {
223 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
227 // Ensure no duplicate ids within child items
228 $idElems = $xPath->query('//body//*//*[@id]');
229 foreach ($idElems as $domElem) {
230 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
231 if ($newId && $newId !== $oldId) {
232 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
236 // Generate inner html as a string
238 foreach ($childNodes as $childNode) {
239 $html .= $doc->saveHTML($childNode);
242 // Perform required string-level tweaks
243 $html = str_replace(' ', ' ', $html);
249 * Update the all links to the $old location to instead point to $new.
251 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
253 $old = str_replace('"', '', $old);
254 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
255 foreach ($matchingLinks as $domElem) {
256 $domElem->setAttribute('href', $new);
261 * Set a unique id on the given DOMElement.
262 * A map for existing ID's should be passed in to check for current existence.
263 * Returns a pair of strings in the format [old_id, new_id].
265 protected function setUniqueId(DOMNode $element, array &$idMap): array
267 if (!$element instanceof DOMElement) {
271 // Stop if there's an existing valid id that has not already been used.
272 $existingId = $element->getAttribute('id');
273 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
274 $idMap[$existingId] = true;
276 return [$existingId, $existingId];
279 // Create a unique id for the element
280 // Uses the content as a basis to ensure output is the same every time
281 // the same content is passed through.
282 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
283 $newId = urlencode($contentId);
286 while (isset($idMap[$newId])) {
287 $newId = urlencode($contentId . '-' . $loopIndex);
291 $element->setAttribute('id', $newId);
292 $idMap[$newId] = true;
294 return [$existingId, $newId];
298 * Get a plain-text visualisation of this page.
300 protected function toPlainText(): string
302 $html = $this->render(true);
304 return html_entity_decode(strip_tags($html));
308 * Render the page for viewing.
310 public function render(bool $blankIncludes = false): string
312 $content = $this->page->html ?? '';
314 if (!config('app.allow_content_scripts')) {
315 $content = HtmlContentFilter::removeScripts($content);
318 if ($blankIncludes) {
319 $content = $this->blankPageIncludes($content);
321 $content = $this->parsePageIncludes($content);
328 * Parse the headers on the page to get a navigation menu.
330 public function getNavigation(string $htmlContent): array
332 if (empty($htmlContent)) {
336 $doc = $this->loadDocumentFromHtml($htmlContent);
337 $xPath = new DOMXPath($doc);
338 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
340 return $headers ? $this->headerNodesToLevelList($headers) : [];
344 * Convert a DOMNodeList into an array of readable header attributes
345 * with levels normalised to the lower header level.
347 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
349 $tree = collect($nodeList)->map(function (DOMElement $header) {
350 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
351 $text = mb_substr($text, 0, 100);
354 'nodeName' => strtolower($header->nodeName),
355 'level' => intval(str_replace('h', '', $header->nodeName)),
356 'link' => '#' . $header->getAttribute('id'),
359 })->filter(function ($header) {
360 return mb_strlen($header['text']) > 0;
363 // Shift headers if only smaller headers have been used
364 $levelChange = ($tree->pluck('level')->min() - 1);
365 $tree = $tree->map(function ($header) use ($levelChange) {
366 $header['level'] -= ($levelChange);
371 return $tree->toArray();
375 * Remove any page include tags within the given HTML.
377 protected function blankPageIncludes(string $html): string
379 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
383 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
385 protected function parsePageIncludes(string $html): string
388 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
390 foreach ($matches[1] as $index => $includeId) {
391 $fullMatch = $matches[0][$index];
392 $splitInclude = explode('#', $includeId, 2);
394 // Get page id from reference
395 $pageId = intval($splitInclude[0]);
396 if (is_nan($pageId)) {
400 // Find page and skip this if page not found
401 /** @var ?Page $matchedPage */
402 $matchedPage = Page::visible()->find($pageId);
403 if ($matchedPage === null) {
404 $html = str_replace($fullMatch, '', $html);
408 // If we only have page id, just insert all page html and continue.
409 if (count($splitInclude) === 1) {
410 $html = str_replace($fullMatch, $matchedPage->html, $html);
414 // Create and load HTML into a document
415 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
416 $html = str_replace($fullMatch, trim($innerContent), $html);
423 * Fetch the content from a specific section of the given page.
425 protected function fetchSectionOfPage(Page $page, string $sectionId): string
427 $topLevelTags = ['table', 'ul', 'ol', 'pre'];
428 $doc = $this->loadDocumentFromHtml($page->html);
430 // Search included content for the id given and blank out if not exists.
431 $matchingElem = $doc->getElementById($sectionId);
432 if ($matchingElem === null) {
436 // Otherwise replace the content with the found content
437 // Checks if the top-level wrapper should be included by matching on tag types
439 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
441 $innerContent .= $doc->saveHTML($matchingElem);
443 foreach ($matchingElem->childNodes as $childNode) {
444 $innerContent .= $doc->saveHTML($childNode);
447 libxml_clear_errors();
449 return $innerContent;
453 * Create and load a DOMDocument from the given html content.
455 protected function loadDocumentFromHtml(string $html): DOMDocument
457 libxml_use_internal_errors(true);
458 $doc = new DOMDocument();
459 $html = '<body>' . $html . '</body>';
460 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));