1 <?php namespace BookStack\Entities\Managers;
3 use BookStack\Entities\Page;
14 * PageContent constructor.
16 public function __construct(Page $page)
22 * Update the content of the page with new provided HTML.
24 public function setNewHTML(string $html)
26 $this->page->html = $this->formatHtml($html);
27 $this->page->text = $this->toPlainText();
31 * Formats a page's html to be tagged correctly within the system.
33 protected function formatHtml(string $htmlText): string
35 if ($htmlText == '') {
39 libxml_use_internal_errors(true);
40 $doc = new DOMDocument();
41 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
43 $container = $doc->documentElement;
44 $body = $container->childNodes->item(0);
45 $childNodes = $body->childNodes;
46 $xPath = new DOMXPath($doc);
48 // Set ids on top-level nodes
50 foreach ($childNodes as $index => $childNode) {
51 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
52 if ($newId && $newId !== $oldId) {
53 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
57 // Ensure no duplicate ids within child items
58 $idElems = $xPath->query('//body//*//*[@id]');
59 foreach ($idElems as $domElem) {
60 [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
61 if ($newId && $newId !== $oldId) {
62 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
66 // Generate inner html as a string
68 foreach ($childNodes as $childNode) {
69 $html .= $doc->saveHTML($childNode);
76 * Update the all links to the $old location to instead point to $new.
78 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
80 $old = str_replace('"', '', $old);
81 $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
82 foreach ($matchingLinks as $domElem) {
83 $domElem->setAttribute('href', $new);
88 * Set a unique id on the given DOMElement.
89 * A map for existing ID's should be passed in to check for current existence.
90 * Returns a pair of strings in the format [old_id, new_id]
92 protected function setUniqueId(\DOMNode $element, array &$idMap): array
94 if (get_class($element) !== 'DOMElement') {
98 // Stop if there's an existing valid id that has not already been used.
99 $existingId = $element->getAttribute('id');
100 if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
101 $idMap[$existingId] = true;
102 return [$existingId, $existingId];
105 // Create an unique id for the element
106 // Uses the content as a basis to ensure output is the same every time
107 // the same content is passed through.
108 $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
109 $newId = urlencode($contentId);
112 while (isset($idMap[$newId])) {
113 $newId = urlencode($contentId . '-' . $loopIndex);
117 $element->setAttribute('id', $newId);
118 $idMap[$newId] = true;
119 return [$existingId, $newId];
123 * Get a plain-text visualisation of this page.
125 protected function toPlainText(): string
127 $html = $this->render(true);
128 return html_entity_decode(strip_tags($html));
132 * Render the page for viewing
134 public function render(bool $blankIncludes = false) : string
136 $content = $this->page->html;
138 if (!config('app.allow_content_scripts')) {
139 $content = $this->escapeScripts($content);
142 if ($blankIncludes) {
143 $content = $this->blankPageIncludes($content);
145 $content = $this->parsePageIncludes($content);
152 * Parse the headers on the page to get a navigation menu
154 public function getNavigation(string $htmlContent): array
156 if (empty($htmlContent)) {
160 libxml_use_internal_errors(true);
161 $doc = new DOMDocument();
162 $doc->loadHTML(mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'));
163 $xPath = new DOMXPath($doc);
164 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
166 return $headers ? $this->headerNodesToLevelList($headers) : [];
170 * Convert a DOMNodeList into an array of readable header attributes
171 * with levels normalised to the lower header level.
173 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
175 $tree = collect($nodeList)->map(function ($header) {
176 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
177 $text = mb_substr($text, 0, 100);
180 'nodeName' => strtolower($header->nodeName),
181 'level' => intval(str_replace('h', '', $header->nodeName)),
182 'link' => '#' . $header->getAttribute('id'),
185 })->filter(function ($header) {
186 return mb_strlen($header['text']) > 0;
189 // Shift headers if only smaller headers have been used
190 $levelChange = ($tree->pluck('level')->min() - 1);
191 $tree = $tree->map(function ($header) use ($levelChange) {
192 $header['level'] -= ($levelChange);
196 return $tree->toArray();
200 * Remove any page include tags within the given HTML.
202 protected function blankPageIncludes(string $html) : string
204 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
208 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
210 protected function parsePageIncludes(string $html) : string
213 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
215 foreach ($matches[1] as $index => $includeId) {
216 $fullMatch = $matches[0][$index];
217 $splitInclude = explode('#', $includeId, 2);
219 // Get page id from reference
220 $pageId = intval($splitInclude[0]);
221 if (is_nan($pageId)) {
225 // Find page and skip this if page not found
226 $matchedPage = Page::visible()->find($pageId);
227 if ($matchedPage === null) {
228 $html = str_replace($fullMatch, '', $html);
232 // If we only have page id, just insert all page html and continue.
233 if (count($splitInclude) === 1) {
234 $html = str_replace($fullMatch, $matchedPage->html, $html);
238 // Create and load HTML into a document
239 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
240 $html = str_replace($fullMatch, trim($innerContent), $html);
248 * Fetch the content from a specific section of the given page.
250 protected function fetchSectionOfPage(Page $page, string $sectionId): string
252 $topLevelTags = ['table', 'ul', 'ol'];
253 $doc = new DOMDocument();
254 libxml_use_internal_errors(true);
255 $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
257 // Search included content for the id given and blank out if not exists.
258 $matchingElem = $doc->getElementById($sectionId);
259 if ($matchingElem === null) {
263 // Otherwise replace the content with the found content
264 // Checks if the top-level wrapper should be included by matching on tag types
266 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
268 $innerContent .= $doc->saveHTML($matchingElem);
270 foreach ($matchingElem->childNodes as $childNode) {
271 $innerContent .= $doc->saveHTML($childNode);
274 libxml_clear_errors();
276 return $innerContent;
280 * Escape script tags within HTML content.
282 protected function escapeScripts(string $html) : string
288 libxml_use_internal_errors(true);
289 $doc = new DOMDocument();
290 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
291 $xPath = new DOMXPath($doc);
293 // Remove standard script tags
294 $scriptElems = $xPath->query('//script');
295 foreach ($scriptElems as $scriptElem) {
296 $scriptElem->parentNode->removeChild($scriptElem);
299 // Remove data or JavaScript iFrames
300 $badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
301 foreach ($badIframes as $badIframe) {
302 $badIframe->parentNode->removeChild($badIframe);
305 // Remove 'on*' attributes
306 $onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
307 foreach ($onAttributes as $attr) {
308 /** @var \DOMAttr $attr*/
309 $attrName = $attr->nodeName;
310 $attr->parentNode->removeAttribute($attrName);
314 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
315 foreach ($topElems as $child) {
316 $html .= $doc->saveHTML($child);