3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
7 use BookStack\Exceptions\ImageUploadException;
8 use BookStack\Facades\Theme;
9 use BookStack\Theming\ThemeEvents;
10 use BookStack\Uploads\ImageRepo;
11 use BookStack\Util\HtmlContentFilter;
15 use Illuminate\Support\Str;
16 use League\CommonMark\CommonMarkConverter;
17 use League\CommonMark\Environment;
18 use League\CommonMark\Extension\Table\TableExtension;
19 use League\CommonMark\Extension\TaskList\TaskListExtension;
26 * PageContent constructor.
28 public function __construct(Page $page)
34 * Update the content of the page with new provided HTML.
36 public function setNewHTML(string $html)
38 $html = $this->extractBase64Images($this->page, $html);
39 $this->page->html = $this->formatHtml($html);
40 $this->page->text = $this->toPlainText();
41 $this->page->markdown = '';
45 * Update the content of the page with new provided Markdown content.
47 public function setNewMarkdown(string $markdown)
49 $this->page->markdown = $markdown;
50 $html = $this->markdownToHtml($markdown);
51 $this->page->html = $this->formatHtml($html);
52 $this->page->text = $this->toPlainText();
56 * Convert the given Markdown content to a HTML string.
58 protected function markdownToHtml(string $markdown): string
60 $environment = Environment::createCommonMarkEnvironment();
61 $environment->addExtension(new TableExtension());
62 $environment->addExtension(new TaskListExtension());
63 $environment->addExtension(new CustomStrikeThroughExtension());
64 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
65 $converter = new CommonMarkConverter([], $environment);
67 return $converter->convertToHtml($markdown);
71 * Convert all base64 image data to saved images.
73 public function extractBase64Images(Page $page, string $htmlText): string
75 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
79 $doc = $this->loadDocumentFromHtml($htmlText);
80 $container = $doc->documentElement;
81 $body = $container->childNodes->item(0);
82 $childNodes = $body->childNodes;
83 $xPath = new DOMXPath($doc);
84 $imageRepo = app()->make(ImageRepo::class);
85 $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
87 // Get all img elements with image data blobs
88 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
89 foreach ($imageNodes as $imageNode) {
90 $imageSrc = $imageNode->getAttribute('src');
91 [$dataDefinition, $base64ImageData] = explode(',', $imageSrc, 2);
92 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png');
95 if (!in_array($extension, $allowedExtensions)) {
96 $imageNode->setAttribute('src', '');
100 // Save image from data with a random name
101 $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension;
104 $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $page->id);
105 $imageNode->setAttribute('src', $image->url);
106 } catch (ImageUploadException $exception) {
107 $imageNode->setAttribute('src', '');
111 // Generate inner html as a string
113 foreach ($childNodes as $childNode) {
114 $html .= $doc->saveHTML($childNode);
121 * Formats a page's html to be tagged correctly within the system.
123 protected function formatHtml(string $htmlText): string
125 if (empty($htmlText)) {
129 $doc = $this->loadDocumentFromHtml($htmlText);
130 $container = $doc->documentElement;
131 $body = $container->childNodes->item(0);
132 $childNodes = $body->childNodes;
133 $xPath = new DOMXPath($doc);
135 // Set ids on top-level nodes
137 foreach ($childNodes as $index => $childNode) {
138 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
139 if ($newId && $newId !== $oldId) {
140 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
144 // Ensure no duplicate ids within child items
145 $idElems = $xPath->query('//body//*//*[@id]');
146 foreach ($idElems as $domElem) {
147 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
148 if ($newId && $newId !== $oldId) {
149 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
153 // Generate inner html as a string
155 foreach ($childNodes as $childNode) {
156 $html .= $doc->saveHTML($childNode);
163 * Update the all links to the $old location to instead point to $new.
165 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
167 $old = str_replace('"', '', $old);
168 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
169 foreach ($matchingLinks as $domElem) {
170 $domElem->setAttribute('href', $new);
175 * Set a unique id on the given DOMElement.
176 * A map for existing ID's should be passed in to check for current existence.
177 * Returns a pair of strings in the format [old_id, new_id].
179 protected function setUniqueId(\DOMNode $element, array &$idMap): array
181 if (get_class($element) !== 'DOMElement') {
185 // Stop if there's an existing valid id that has not already been used.
186 $existingId = $element->getAttribute('id');
187 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
188 $idMap[$existingId] = true;
190 return [$existingId, $existingId];
193 // Create an unique id for the element
194 // Uses the content as a basis to ensure output is the same every time
195 // the same content is passed through.
196 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
197 $newId = urlencode($contentId);
200 while (isset($idMap[$newId])) {
201 $newId = urlencode($contentId . '-' . $loopIndex);
205 $element->setAttribute('id', $newId);
206 $idMap[$newId] = true;
208 return [$existingId, $newId];
212 * Get a plain-text visualisation of this page.
214 protected function toPlainText(): string
216 $html = $this->render(true);
218 return html_entity_decode(strip_tags($html));
222 * Render the page for viewing.
224 public function render(bool $blankIncludes = false): string
226 $content = $this->page->html;
228 if (!config('app.allow_content_scripts')) {
229 $content = HtmlContentFilter::removeScripts($content);
232 if ($blankIncludes) {
233 $content = $this->blankPageIncludes($content);
235 $content = $this->parsePageIncludes($content);
242 * Parse the headers on the page to get a navigation menu.
244 public function getNavigation(string $htmlContent): array
246 if (empty($htmlContent)) {
250 $doc = $this->loadDocumentFromHtml($htmlContent);
251 $xPath = new DOMXPath($doc);
252 $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
254 return $headers ? $this->headerNodesToLevelList($headers) : [];
258 * Convert a DOMNodeList into an array of readable header attributes
259 * with levels normalised to the lower header level.
261 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
263 $tree = collect($nodeList)->map(function ($header) {
264 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
265 $text = mb_substr($text, 0, 100);
268 'nodeName' => strtolower($header->nodeName),
269 'level' => intval(str_replace('h', '', $header->nodeName)),
270 'link' => '#' . $header->getAttribute('id'),
273 })->filter(function ($header) {
274 return mb_strlen($header['text']) > 0;
277 // Shift headers if only smaller headers have been used
278 $levelChange = ($tree->pluck('level')->min() - 1);
279 $tree = $tree->map(function ($header) use ($levelChange) {
280 $header['level'] -= ($levelChange);
285 return $tree->toArray();
289 * Remove any page include tags within the given HTML.
291 protected function blankPageIncludes(string $html): string
293 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
297 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
299 protected function parsePageIncludes(string $html): string
302 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
304 foreach ($matches[1] as $index => $includeId) {
305 $fullMatch = $matches[0][$index];
306 $splitInclude = explode('#', $includeId, 2);
308 // Get page id from reference
309 $pageId = intval($splitInclude[0]);
310 if (is_nan($pageId)) {
314 // Find page and skip this if page not found
315 $matchedPage = Page::visible()->find($pageId);
316 if ($matchedPage === null) {
317 $html = str_replace($fullMatch, '', $html);
321 // If we only have page id, just insert all page html and continue.
322 if (count($splitInclude) === 1) {
323 $html = str_replace($fullMatch, $matchedPage->html, $html);
327 // Create and load HTML into a document
328 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
329 $html = str_replace($fullMatch, trim($innerContent), $html);
336 * Fetch the content from a specific section of the given page.
338 protected function fetchSectionOfPage(Page $page, string $sectionId): string
340 $topLevelTags = ['table', 'ul', 'ol'];
341 $doc = $this->loadDocumentFromHtml($page->html);
343 // Search included content for the id given and blank out if not exists.
344 $matchingElem = $doc->getElementById($sectionId);
345 if ($matchingElem === null) {
349 // Otherwise replace the content with the found content
350 // Checks if the top-level wrapper should be included by matching on tag types
352 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
354 $innerContent .= $doc->saveHTML($matchingElem);
356 foreach ($matchingElem->childNodes as $childNode) {
357 $innerContent .= $doc->saveHTML($childNode);
360 libxml_clear_errors();
362 return $innerContent;
366 * Create and load a DOMDocument from the given html content.
368 protected function loadDocumentFromHtml(string $html): DOMDocument
370 libxml_use_internal_errors(true);
371 $doc = new DOMDocument();
372 $html = '<body>' . $html . '</body>';
373 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));