1 <?php namespace BookStack\Entities\Tools;
3 use BookStack\Entities\Models\Page;
7 use League\CommonMark\CommonMarkConverter;
8 use League\CommonMark\Environment;
9 use League\CommonMark\Extension\Table\TableExtension;
10 use League\CommonMark\Extension\TaskList\TaskListExtension;
18 * PageContent constructor.
20 public function __construct(Page $page)
26 * Update the content of the page with new provided HTML.
28 public function setNewHTML(string $html)
30 $this->page->html = $this->formatHtml($html);
31 $this->page->text = $this->toPlainText();
32 $this->page->markdown = '';
36 * Update the content of the page with new provided Markdown content.
38 public function setNewMarkdown(string $markdown)
40 $this->page->markdown = $markdown;
41 $html = $this->markdownToHtml($markdown);
42 $this->page->html = $this->formatHtml($html);
43 $this->page->text = $this->toPlainText();
47 * Convert the given Markdown content to a HTML string.
49 protected function markdownToHtml(string $markdown): string
51 $environment = Environment::createCommonMarkEnvironment();
52 $environment->addExtension(new TableExtension());
53 $environment->addExtension(new TaskListExtension());
54 $converter = new CommonMarkConverter([], $environment);
55 return $converter->convertToHtml($markdown);
59 * Formats a page's html to be tagged correctly within the system.
61 protected function formatHtml(string $htmlText): string
63 if ($htmlText == '') {
67 libxml_use_internal_errors(true);
68 $doc = new DOMDocument();
69 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
71 $container = $doc->documentElement;
72 $body = $container->childNodes->item(0);
73 $childNodes = $body->childNodes;
74 $xPath = new DOMXPath($doc);
76 // Set ids on top-level nodes
78 foreach ($childNodes as $index => $childNode) {
79 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
80 if ($newId && $newId !== $oldId) {
81 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
85 // Ensure no duplicate ids within child items
86 $idElems = $xPath->query('//body//*//*[@id]');
87 foreach ($idElems as $domElem) {
88 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
89 if ($newId && $newId !== $oldId) {
90 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
94 // Generate inner html as a string
96 foreach ($childNodes as $childNode) {
97 $html .= $doc->saveHTML($childNode);
104 * Update the all links to the $old location to instead point to $new.
106 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
108 $old = str_replace('"', '', $old);
109 $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
110 foreach ($matchingLinks as $domElem) {
111 $domElem->setAttribute('href', $new);
116 * Set a unique id on the given DOMElement.
117 * A map for existing ID's should be passed in to check for current existence.
118 * Returns a pair of strings in the format [old_id, new_id]
120 protected function setUniqueId(\DOMNode $element, array &$idMap): array
122 if (get_class($element) !== 'DOMElement') {
126 // Stop if there's an existing valid id that has not already been used.
127 $existingId = $element->getAttribute('id');
128 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
129 $idMap[$existingId] = true;
130 return [$existingId, $existingId];
133 // Create an unique id for the element
134 // Uses the content as a basis to ensure output is the same every time
135 // the same content is passed through.
136 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
137 $newId = urlencode($contentId);
140 while (isset($idMap[$newId])) {
141 $newId = urlencode($contentId . '-' . $loopIndex);
145 $element->setAttribute('id', $newId);
146 $idMap[$newId] = true;
147 return [$existingId, $newId];
151 * Get a plain-text visualisation of this page.
153 protected function toPlainText(): string
155 $html = $this->render(true);
156 return html_entity_decode(strip_tags($html));
160 * Render the page for viewing
162 public function render(bool $blankIncludes = false) : string
164 $content = $this->page->html;
166 if (!config('app.allow_content_scripts')) {
167 $content = $this->escapeScripts($content);
170 if ($blankIncludes) {
171 $content = $this->blankPageIncludes($content);
173 $content = $this->parsePageIncludes($content);
180 * Parse the headers on the page to get a navigation menu
182 public function getNavigation(string $htmlContent): array
184 if (empty($htmlContent)) {
188 libxml_use_internal_errors(true);
189 $doc = new DOMDocument();
190 $doc->loadHTML(mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'));
191 $xPath = new DOMXPath($doc);
192 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
194 return $headers ? $this->headerNodesToLevelList($headers) : [];
198 * Convert a DOMNodeList into an array of readable header attributes
199 * with levels normalised to the lower header level.
201 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
203 $tree = collect($nodeList)->map(function ($header) {
204 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
205 $text = mb_substr($text, 0, 100);
208 'nodeName' => strtolower($header->nodeName),
209 'level' => intval(str_replace('h', '', $header->nodeName)),
210 'link' => '#' . $header->getAttribute('id'),
213 })->filter(function ($header) {
214 return mb_strlen($header['text']) > 0;
217 // Shift headers if only smaller headers have been used
218 $levelChange = ($tree->pluck('level')->min() - 1);
219 $tree = $tree->map(function ($header) use ($levelChange) {
220 $header['level'] -= ($levelChange);
224 return $tree->toArray();
228 * Remove any page include tags within the given HTML.
230 protected function blankPageIncludes(string $html) : string
232 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
236 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
238 protected function parsePageIncludes(string $html) : string
241 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
243 foreach ($matches[1] as $index => $includeId) {
244 $fullMatch = $matches[0][$index];
245 $splitInclude = explode('#', $includeId, 2);
247 // Get page id from reference
248 $pageId = intval($splitInclude[0]);
249 if (is_nan($pageId)) {
253 // Find page and skip this if page not found
254 $matchedPage = Page::visible()->find($pageId);
255 if ($matchedPage === null) {
256 $html = str_replace($fullMatch, '', $html);
260 // If we only have page id, just insert all page html and continue.
261 if (count($splitInclude) === 1) {
262 $html = str_replace($fullMatch, $matchedPage->html, $html);
266 // Create and load HTML into a document
267 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
268 $html = str_replace($fullMatch, trim($innerContent), $html);
276 * Fetch the content from a specific section of the given page.
278 protected function fetchSectionOfPage(Page $page, string $sectionId): string
280 $topLevelTags = ['table', 'ul', 'ol'];
281 $doc = new DOMDocument();
282 libxml_use_internal_errors(true);
283 $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
285 // Search included content for the id given and blank out if not exists.
286 $matchingElem = $doc->getElementById($sectionId);
287 if ($matchingElem === null) {
291 // Otherwise replace the content with the found content
292 // Checks if the top-level wrapper should be included by matching on tag types
294 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
296 $innerContent .= $doc->saveHTML($matchingElem);
298 foreach ($matchingElem->childNodes as $childNode) {
299 $innerContent .= $doc->saveHTML($childNode);
302 libxml_clear_errors();
304 return $innerContent;
308 * Escape script tags within HTML content.
310 protected function escapeScripts(string $html) : string
316 libxml_use_internal_errors(true);
317 $doc = new DOMDocument();
318 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
319 $xPath = new DOMXPath($doc);
321 // Remove standard script tags
322 $scriptElems = $xPath->query('//script');
323 foreach ($scriptElems as $scriptElem) {
324 $scriptElem->parentNode->removeChild($scriptElem);
327 // Remove clickable links to JavaScript URI
328 $badLinks = $xPath->query('//*[contains(@href, \'javascript:\')]');
329 foreach ($badLinks as $badLink) {
330 $badLink->parentNode->removeChild($badLink);
333 // Remove forms with calls to JavaScript URI
334 $badForms = $xPath->query('//*[contains(@action, \'javascript:\')] | //*[contains(@formaction, \'javascript:\')]');
335 foreach ($badForms as $badForm) {
336 $badForm->parentNode->removeChild($badForm);
339 // Remove meta tag to prevent external redirects
340 $metaTags = $xPath->query('//meta[contains(@content, \'url\')]');
341 foreach ($metaTags as $metaTag) {
342 $metaTag->parentNode->removeChild($metaTag);
345 // Remove data or JavaScript iFrames
346 $badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
347 foreach ($badIframes as $badIframe) {
348 $badIframe->parentNode->removeChild($badIframe);
351 // Remove 'on*' attributes
352 $onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
353 foreach ($onAttributes as $attr) {
354 /** @var \DOMAttr $attr*/
355 $attrName = $attr->nodeName;
356 $attr->parentNode->removeAttribute($attrName);
360 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
361 foreach ($topElems as $child) {
362 $html .= $doc->saveHTML($child);