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\Util\HtmlContentFilter;
16 use Illuminate\Support\Str;
17 use League\CommonMark\Block\Element\ListItem;
18 use League\CommonMark\CommonMarkConverter;
19 use League\CommonMark\Environment;
20 use League\CommonMark\Extension\Table\TableExtension;
21 use League\CommonMark\Extension\TaskList\TaskListExtension;
28 * PageContent constructor.
30 public function __construct(Page $page)
36 * Update the content of the page with new provided HTML.
38 public function setNewHTML(string $html)
40 $html = $this->extractBase64Images($this->page, $html);
41 $this->page->html = $this->formatHtml($html);
42 $this->page->text = $this->toPlainText();
43 $this->page->markdown = '';
47 * Update the content of the page with new provided Markdown content.
49 public function setNewMarkdown(string $markdown)
51 $this->page->markdown = $markdown;
52 $html = $this->markdownToHtml($markdown);
53 $this->page->html = $this->formatHtml($html);
54 $this->page->text = $this->toPlainText();
58 * Convert the given Markdown content to a HTML string.
60 protected function markdownToHtml(string $markdown): string
62 $environment = Environment::createCommonMarkEnvironment();
63 $environment->addExtension(new TableExtension());
64 $environment->addExtension(new TaskListExtension());
65 $environment->addExtension(new CustomStrikeThroughExtension());
66 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
67 $converter = new CommonMarkConverter([], $environment);
69 $environment->addBlockRenderer(ListItem::class, new CustomListItemRenderer(), 10);
71 return $converter->convertToHtml($markdown);
75 * Convert all base64 image data to saved images.
77 public function extractBase64Images(Page $page, string $htmlText): string
79 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
83 $doc = $this->loadDocumentFromHtml($htmlText);
84 $container = $doc->documentElement;
85 $body = $container->childNodes->item(0);
86 $childNodes = $body->childNodes;
87 $xPath = new DOMXPath($doc);
88 $imageRepo = app()->make(ImageRepo::class);
89 $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
91 // Get all img elements with image data blobs
92 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
93 foreach ($imageNodes as $imageNode) {
94 $imageSrc = $imageNode->getAttribute('src');
95 [$dataDefinition, $base64ImageData] = explode(',', $imageSrc, 2);
96 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png');
99 if (!in_array($extension, $allowedExtensions)) {
100 $imageNode->setAttribute('src', '');
104 // Save image from data with a random name
105 $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension;
108 $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $page->id);
109 $imageNode->setAttribute('src', $image->url);
110 } catch (ImageUploadException $exception) {
111 $imageNode->setAttribute('src', '');
115 // Generate inner html as a string
117 foreach ($childNodes as $childNode) {
118 $html .= $doc->saveHTML($childNode);
125 * Formats a page's html to be tagged correctly within the system.
127 protected function formatHtml(string $htmlText): string
129 if (empty($htmlText)) {
133 $doc = $this->loadDocumentFromHtml($htmlText);
134 $container = $doc->documentElement;
135 $body = $container->childNodes->item(0);
136 $childNodes = $body->childNodes;
137 $xPath = new DOMXPath($doc);
139 // Set ids on top-level nodes
141 foreach ($childNodes as $index => $childNode) {
142 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
143 if ($newId && $newId !== $oldId) {
144 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
148 // Ensure no duplicate ids within child items
149 $idElems = $xPath->query('//body//*//*[@id]');
150 foreach ($idElems as $domElem) {
151 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
152 if ($newId && $newId !== $oldId) {
153 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
157 // Generate inner html as a string
159 foreach ($childNodes as $childNode) {
160 $html .= $doc->saveHTML($childNode);
167 * Update the all links to the $old location to instead point to $new.
169 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
171 $old = str_replace('"', '', $old);
172 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
173 foreach ($matchingLinks as $domElem) {
174 $domElem->setAttribute('href', $new);
179 * Set a unique id on the given DOMElement.
180 * A map for existing ID's should be passed in to check for current existence.
181 * Returns a pair of strings in the format [old_id, new_id].
183 protected function setUniqueId(\DOMNode $element, array &$idMap): array
185 if (get_class($element) !== 'DOMElement') {
189 // Stop if there's an existing valid id that has not already been used.
190 $existingId = $element->getAttribute('id');
191 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
192 $idMap[$existingId] = true;
194 return [$existingId, $existingId];
197 // Create an unique id for the element
198 // Uses the content as a basis to ensure output is the same every time
199 // the same content is passed through.
200 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
201 $newId = urlencode($contentId);
204 while (isset($idMap[$newId])) {
205 $newId = urlencode($contentId . '-' . $loopIndex);
209 $element->setAttribute('id', $newId);
210 $idMap[$newId] = true;
212 return [$existingId, $newId];
216 * Get a plain-text visualisation of this page.
218 protected function toPlainText(): string
220 $html = $this->render(true);
222 return html_entity_decode(strip_tags($html));
226 * Render the page for viewing.
228 public function render(bool $blankIncludes = false): string
230 $content = $this->page->html ?? '';
232 if (!config('app.allow_content_scripts')) {
233 $content = HtmlContentFilter::removeScripts($content);
236 if ($blankIncludes) {
237 $content = $this->blankPageIncludes($content);
239 $content = $this->parsePageIncludes($content);
246 * Parse the headers on the page to get a navigation menu.
248 public function getNavigation(string $htmlContent): array
250 if (empty($htmlContent)) {
254 $doc = $this->loadDocumentFromHtml($htmlContent);
255 $xPath = new DOMXPath($doc);
256 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
258 return $headers ? $this->headerNodesToLevelList($headers) : [];
262 * Convert a DOMNodeList into an array of readable header attributes
263 * with levels normalised to the lower header level.
265 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
267 $tree = collect($nodeList)->map(function ($header) {
268 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
269 $text = mb_substr($text, 0, 100);
272 'nodeName' => strtolower($header->nodeName),
273 'level' => intval(str_replace('h', '', $header->nodeName)),
274 'link' => '#' . $header->getAttribute('id'),
277 })->filter(function ($header) {
278 return mb_strlen($header['text']) > 0;
281 // Shift headers if only smaller headers have been used
282 $levelChange = ($tree->pluck('level')->min() - 1);
283 $tree = $tree->map(function ($header) use ($levelChange) {
284 $header['level'] -= ($levelChange);
289 return $tree->toArray();
293 * Remove any page include tags within the given HTML.
295 protected function blankPageIncludes(string $html): string
297 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
301 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
303 protected function parsePageIncludes(string $html): string
306 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
308 foreach ($matches[1] as $index => $includeId) {
309 $fullMatch = $matches[0][$index];
310 $splitInclude = explode('#', $includeId, 2);
312 // Get page id from reference
313 $pageId = intval($splitInclude[0]);
314 if (is_nan($pageId)) {
318 // Find page and skip this if page not found
319 $matchedPage = Page::visible()->find($pageId);
320 if ($matchedPage === null) {
321 $html = str_replace($fullMatch, '', $html);
325 // If we only have page id, just insert all page html and continue.
326 if (count($splitInclude) === 1) {
327 $html = str_replace($fullMatch, $matchedPage->html, $html);
331 // Create and load HTML into a document
332 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
333 $html = str_replace($fullMatch, trim($innerContent), $html);
340 * Fetch the content from a specific section of the given page.
342 protected function fetchSectionOfPage(Page $page, string $sectionId): string
344 $topLevelTags = ['table', 'ul', 'ol'];
345 $doc = $this->loadDocumentFromHtml($page->html);
347 // Search included content for the id given and blank out if not exists.
348 $matchingElem = $doc->getElementById($sectionId);
349 if ($matchingElem === null) {
353 // Otherwise replace the content with the found content
354 // Checks if the top-level wrapper should be included by matching on tag types
356 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
358 $innerContent .= $doc->saveHTML($matchingElem);
360 foreach ($matchingElem->childNodes as $childNode) {
361 $innerContent .= $doc->saveHTML($childNode);
364 libxml_clear_errors();
366 return $innerContent;
370 * Create and load a DOMDocument from the given html content.
372 protected function loadDocumentFromHtml(string $html): DOMDocument
374 libxml_use_internal_errors(true);
375 $doc = new DOMDocument();
376 $html = '<body>' . $html . '</body>';
377 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));