1 <?php namespace BookStack\Entities\Tools;
3 use BookStack\Entities\Models\Page;
4 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
8 use League\CommonMark\CommonMarkConverter;
9 use League\CommonMark\Environment;
10 use League\CommonMark\Extension\Table\TableExtension;
11 use League\CommonMark\Extension\TaskList\TaskListExtension;
19 * PageContent constructor.
21 public function __construct(Page $page)
27 * Update the content of the page with new provided HTML.
29 public function setNewHTML(string $html)
31 $this->page->html = $this->formatHtml($html);
32 $this->page->text = $this->toPlainText();
33 $this->page->markdown = '';
37 * Update the content of the page with new provided Markdown content.
39 public function setNewMarkdown(string $markdown)
41 $this->page->markdown = $markdown;
42 $html = $this->markdownToHtml($markdown);
43 $this->page->html = $this->formatHtml($html);
44 $this->page->text = $this->toPlainText();
48 * Convert the given Markdown content to a HTML string.
50 protected function markdownToHtml(string $markdown): string
52 $environment = Environment::createCommonMarkEnvironment();
53 $environment->addExtension(new TableExtension());
54 $environment->addExtension(new TaskListExtension());
55 $environment->addExtension(new CustomStrikeThroughExtension());
56 $converter = new CommonMarkConverter([], $environment);
57 return $converter->convertToHtml($markdown);
61 * Formats a page's html to be tagged correctly within the system.
63 protected function formatHtml(string $htmlText): string
65 if ($htmlText == '') {
69 libxml_use_internal_errors(true);
70 $doc = new DOMDocument();
71 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
73 $container = $doc->documentElement;
74 $body = $container->childNodes->item(0);
75 $childNodes = $body->childNodes;
76 $xPath = new DOMXPath($doc);
78 // Set ids on top-level nodes
80 foreach ($childNodes as $index => $childNode) {
81 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
82 if ($newId && $newId !== $oldId) {
83 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
87 // Ensure no duplicate ids within child items
88 $idElems = $xPath->query('//body//*//*[@id]');
89 foreach ($idElems as $domElem) {
90 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
91 if ($newId && $newId !== $oldId) {
92 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
96 // Generate inner html as a string
98 foreach ($childNodes as $childNode) {
99 $html .= $doc->saveHTML($childNode);
106 * Update the all links to the $old location to instead point to $new.
108 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
110 $old = str_replace('"', '', $old);
111 $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
112 foreach ($matchingLinks as $domElem) {
113 $domElem->setAttribute('href', $new);
118 * Set a unique id on the given DOMElement.
119 * A map for existing ID's should be passed in to check for current existence.
120 * Returns a pair of strings in the format [old_id, new_id]
122 protected function setUniqueId(\DOMNode $element, array &$idMap): array
124 if (get_class($element) !== 'DOMElement') {
128 // Stop if there's an existing valid id that has not already been used.
129 $existingId = $element->getAttribute('id');
130 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
131 $idMap[$existingId] = true;
132 return [$existingId, $existingId];
135 // Create an unique id for the element
136 // Uses the content as a basis to ensure output is the same every time
137 // the same content is passed through.
138 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
139 $newId = urlencode($contentId);
142 while (isset($idMap[$newId])) {
143 $newId = urlencode($contentId . '-' . $loopIndex);
147 $element->setAttribute('id', $newId);
148 $idMap[$newId] = true;
149 return [$existingId, $newId];
153 * Get a plain-text visualisation of this page.
155 protected function toPlainText(): string
157 $html = $this->render(true);
158 return html_entity_decode(strip_tags($html));
162 * Render the page for viewing
164 public function render(bool $blankIncludes = false) : string
166 $content = $this->page->html;
168 if (!config('app.allow_content_scripts')) {
169 $content = $this->escapeScripts($content);
172 if ($blankIncludes) {
173 $content = $this->blankPageIncludes($content);
175 $content = $this->parsePageIncludes($content);
182 * Parse the headers on the page to get a navigation menu
184 public function getNavigation(string $htmlContent): array
186 if (empty($htmlContent)) {
190 libxml_use_internal_errors(true);
191 $doc = new DOMDocument();
192 $doc->loadHTML(mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'));
193 $xPath = new DOMXPath($doc);
194 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
196 return $headers ? $this->headerNodesToLevelList($headers) : [];
200 * Convert a DOMNodeList into an array of readable header attributes
201 * with levels normalised to the lower header level.
203 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
205 $tree = collect($nodeList)->map(function ($header) {
206 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
207 $text = mb_substr($text, 0, 100);
210 'nodeName' => strtolower($header->nodeName),
211 'level' => intval(str_replace('h', '', $header->nodeName)),
212 'link' => '#' . $header->getAttribute('id'),
215 })->filter(function ($header) {
216 return mb_strlen($header['text']) > 0;
219 // Shift headers if only smaller headers have been used
220 $levelChange = ($tree->pluck('level')->min() - 1);
221 $tree = $tree->map(function ($header) use ($levelChange) {
222 $header['level'] -= ($levelChange);
226 return $tree->toArray();
230 * Remove any page include tags within the given HTML.
232 protected function blankPageIncludes(string $html) : string
234 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
238 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
240 protected function parsePageIncludes(string $html) : string
243 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
245 foreach ($matches[1] as $index => $includeId) {
246 $fullMatch = $matches[0][$index];
247 $splitInclude = explode('#', $includeId, 2);
249 // Get page id from reference
250 $pageId = intval($splitInclude[0]);
251 if (is_nan($pageId)) {
255 // Find page and skip this if page not found
256 $matchedPage = Page::visible()->find($pageId);
257 if ($matchedPage === null) {
258 $html = str_replace($fullMatch, '', $html);
262 // If we only have page id, just insert all page html and continue.
263 if (count($splitInclude) === 1) {
264 $html = str_replace($fullMatch, $matchedPage->html, $html);
268 // Create and load HTML into a document
269 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
270 $html = str_replace($fullMatch, trim($innerContent), $html);
278 * Fetch the content from a specific section of the given page.
280 protected function fetchSectionOfPage(Page $page, string $sectionId): string
282 $topLevelTags = ['table', 'ul', 'ol'];
283 $doc = new DOMDocument();
284 libxml_use_internal_errors(true);
285 $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
287 // Search included content for the id given and blank out if not exists.
288 $matchingElem = $doc->getElementById($sectionId);
289 if ($matchingElem === null) {
293 // Otherwise replace the content with the found content
294 // Checks if the top-level wrapper should be included by matching on tag types
296 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
298 $innerContent .= $doc->saveHTML($matchingElem);
300 foreach ($matchingElem->childNodes as $childNode) {
301 $innerContent .= $doc->saveHTML($childNode);
304 libxml_clear_errors();
306 return $innerContent;
310 * Escape script tags within HTML content.
312 protected function escapeScripts(string $html) : string
318 libxml_use_internal_errors(true);
319 $doc = new DOMDocument();
320 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
321 $xPath = new DOMXPath($doc);
323 // Remove standard script tags
324 $scriptElems = $xPath->query('//script');
325 foreach ($scriptElems as $scriptElem) {
326 $scriptElem->parentNode->removeChild($scriptElem);
329 // Remove clickable links to JavaScript URI
330 $badLinks = $xPath->query('//*[contains(@href, \'javascript:\')]');
331 foreach ($badLinks as $badLink) {
332 $badLink->parentNode->removeChild($badLink);
335 // Remove forms with calls to JavaScript URI
336 $badForms = $xPath->query('//*[contains(@action, \'javascript:\')] | //*[contains(@formaction, \'javascript:\')]');
337 foreach ($badForms as $badForm) {
338 $badForm->parentNode->removeChild($badForm);
341 // Remove meta tag to prevent external redirects
342 $metaTags = $xPath->query('//meta[contains(@content, \'url\')]');
343 foreach ($metaTags as $metaTag) {
344 $metaTag->parentNode->removeChild($metaTag);
347 // Remove data or JavaScript iFrames
348 $badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
349 foreach ($badIframes as $badIframe) {
350 $badIframe->parentNode->removeChild($badIframe);
353 // Remove 'on*' attributes
354 $onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
355 foreach ($onAttributes as $attr) {
356 /** @var \DOMAttr $attr*/
357 $attrName = $attr->nodeName;
358 $attr->parentNode->removeAttribute($attrName);
362 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
363 foreach ($topElems as $child) {
364 $html .= $doc->saveHTML($child);