1 <?php namespace BookStack\Entities\Tools;
3 use BookStack\Entities\Models\Page;
4 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
5 use BookStack\Exceptions\ImageUploadException;
6 use BookStack\Facades\Theme;
7 use BookStack\Theming\ThemeEvents;
8 use BookStack\Util\HtmlContentFilter;
9 use BookStack\Uploads\ImageRepo;
13 use Illuminate\Support\Str;
14 use League\CommonMark\CommonMarkConverter;
15 use League\CommonMark\Environment;
16 use League\CommonMark\Extension\Table\TableExtension;
17 use League\CommonMark\Extension\TaskList\TaskListExtension;
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->extractBase64Images($this->page, $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 $this->page->markdown = $markdown;
49 $html = $this->markdownToHtml($markdown);
50 $this->page->html = $this->formatHtml($html);
51 $this->page->text = $this->toPlainText();
55 * Convert the given Markdown content to a HTML string.
57 protected function markdownToHtml(string $markdown): string
59 $environment = Environment::createCommonMarkEnvironment();
60 $environment->addExtension(new TableExtension());
61 $environment->addExtension(new TaskListExtension());
62 $environment->addExtension(new CustomStrikeThroughExtension());
63 $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
64 $converter = new CommonMarkConverter([], $environment);
65 return $converter->convertToHtml($markdown);
69 * Convert all base64 image data to saved images
71 public function extractBase64Images(Page $page, string $htmlText): string
73 if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
77 $doc = $this->loadDocumentFromHtml($htmlText);
78 $container = $doc->documentElement;
79 $body = $container->childNodes->item(0);
80 $childNodes = $body->childNodes;
81 $xPath = new DOMXPath($doc);
82 $imageRepo = app()->make(ImageRepo::class);
83 $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
85 // Get all img elements with image data blobs
86 $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
87 foreach ($imageNodes as $imageNode) {
88 $imageSrc = $imageNode->getAttribute('src');
89 [$dataDefinition, $base64ImageData] = explode(',', $imageSrc, 2);
90 $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? 'png');
93 if (!in_array($extension, $allowedExtensions)) {
94 $imageNode->setAttribute('src', '');
98 // Save image from data with a random name
99 $imageName = 'embedded-image-' . Str::random(8) . '.' . $extension;
101 $image = $imageRepo->saveNewFromData($imageName, base64_decode($base64ImageData), 'gallery', $page->id);
102 $imageNode->setAttribute('src', $image->url);
103 } catch (ImageUploadException $exception) {
104 $imageNode->setAttribute('src', '');
108 // Generate inner html as a string
110 foreach ($childNodes as $childNode) {
111 $html .= $doc->saveHTML($childNode);
118 * Formats a page's html to be tagged correctly within the system.
120 protected function formatHtml(string $htmlText): string
122 if (empty($htmlText)) {
126 $doc = $this->loadDocumentFromHtml($htmlText);
127 $container = $doc->documentElement;
128 $body = $container->childNodes->item(0);
129 $childNodes = $body->childNodes;
130 $xPath = new DOMXPath($doc);
132 // Set ids on top-level nodes
134 foreach ($childNodes as $index => $childNode) {
135 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
136 if ($newId && $newId !== $oldId) {
137 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
141 // Ensure no duplicate ids within child items
142 $idElems = $xPath->query('//body//*//*[@id]');
143 foreach ($idElems as $domElem) {
144 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
145 if ($newId && $newId !== $oldId) {
146 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
150 // Generate inner html as a string
152 foreach ($childNodes as $childNode) {
153 $html .= $doc->saveHTML($childNode);
160 * Update the all links to the $old location to instead point to $new.
162 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
164 $old = str_replace('"', '', $old);
165 $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
166 foreach ($matchingLinks as $domElem) {
167 $domElem->setAttribute('href', $new);
172 * Set a unique id on the given DOMElement.
173 * A map for existing ID's should be passed in to check for current existence.
174 * Returns a pair of strings in the format [old_id, new_id]
176 protected function setUniqueId(\DOMNode $element, array &$idMap): array
178 if (get_class($element) !== 'DOMElement') {
182 // Stop if there's an existing valid id that has not already been used.
183 $existingId = $element->getAttribute('id');
184 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
185 $idMap[$existingId] = true;
186 return [$existingId, $existingId];
189 // Create an unique id for the element
190 // Uses the content as a basis to ensure output is the same every time
191 // the same content is passed through.
192 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
193 $newId = urlencode($contentId);
196 while (isset($idMap[$newId])) {
197 $newId = urlencode($contentId . '-' . $loopIndex);
201 $element->setAttribute('id', $newId);
202 $idMap[$newId] = true;
203 return [$existingId, $newId];
207 * Get a plain-text visualisation of this page.
209 protected function toPlainText(): string
211 $html = $this->render(true);
212 return html_entity_decode(strip_tags($html));
216 * Render the page for viewing
218 public function render(bool $blankIncludes = false): string
220 $content = $this->page->html;
222 if (!config('app.allow_content_scripts')) {
223 $content = HtmlContentFilter::removeScripts($content);
226 if ($blankIncludes) {
227 $content = $this->blankPageIncludes($content);
229 $content = $this->parsePageIncludes($content);
236 * Parse the headers on the page to get a navigation menu
238 public function getNavigation(string $htmlContent): array
240 if (empty($htmlContent)) {
244 $doc = $this->loadDocumentFromHtml($htmlContent);
245 $xPath = new DOMXPath($doc);
246 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
248 return $headers ? $this->headerNodesToLevelList($headers) : [];
252 * Convert a DOMNodeList into an array of readable header attributes
253 * with levels normalised to the lower header level.
255 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
257 $tree = collect($nodeList)->map(function ($header) {
258 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
259 $text = mb_substr($text, 0, 100);
262 'nodeName' => strtolower($header->nodeName),
263 'level' => intval(str_replace('h', '', $header->nodeName)),
264 'link' => '#' . $header->getAttribute('id'),
267 })->filter(function ($header) {
268 return mb_strlen($header['text']) > 0;
271 // Shift headers if only smaller headers have been used
272 $levelChange = ($tree->pluck('level')->min() - 1);
273 $tree = $tree->map(function ($header) use ($levelChange) {
274 $header['level'] -= ($levelChange);
278 return $tree->toArray();
282 * Remove any page include tags within the given HTML.
284 protected function blankPageIncludes(string $html): string
286 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
290 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
292 protected function parsePageIncludes(string $html): string
295 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
297 foreach ($matches[1] as $index => $includeId) {
298 $fullMatch = $matches[0][$index];
299 $splitInclude = explode('#', $includeId, 2);
301 // Get page id from reference
302 $pageId = intval($splitInclude[0]);
303 if (is_nan($pageId)) {
307 // Find page and skip this if page not found
308 $matchedPage = Page::visible()->find($pageId);
309 if ($matchedPage === null) {
310 $html = str_replace($fullMatch, '', $html);
314 // If we only have page id, just insert all page html and continue.
315 if (count($splitInclude) === 1) {
316 $html = str_replace($fullMatch, $matchedPage->html, $html);
320 // Create and load HTML into a document
321 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
322 $html = str_replace($fullMatch, trim($innerContent), $html);
330 * Fetch the content from a specific section of the given page.
332 protected function fetchSectionOfPage(Page $page, string $sectionId): string
334 $topLevelTags = ['table', 'ul', 'ol'];
335 $doc = $this->loadDocumentFromHtml($page->html);
337 // Search included content for the id given and blank out if not exists.
338 $matchingElem = $doc->getElementById($sectionId);
339 if ($matchingElem === null) {
343 // Otherwise replace the content with the found content
344 // Checks if the top-level wrapper should be included by matching on tag types
346 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
348 $innerContent .= $doc->saveHTML($matchingElem);
350 foreach ($matchingElem->childNodes as $childNode) {
351 $innerContent .= $doc->saveHTML($childNode);
354 libxml_clear_errors();
356 return $innerContent;
360 * Create and load a DOMDocument from the given html content.
362 protected function loadDocumentFromHtml(string $html): DOMDocument
364 libxml_use_internal_errors(true);
365 $doc = new DOMDocument();
366 $html = '<body>' . $html . '</body>';
367 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));