]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
Update TrashCan.php
[bookstack] / app / Entities / Tools / PageContent.php
1 <?php namespace BookStack\Entities\Tools;
2
3 use BookStack\Entities\Models\Page;
4 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
5 use DOMDocument;
6 use DOMNodeList;
7 use DOMXPath;
8 use League\CommonMark\CommonMarkConverter;
9 use League\CommonMark\Environment;
10 use League\CommonMark\Extension\Table\TableExtension;
11 use League\CommonMark\Extension\TaskList\TaskListExtension;
12
13 class PageContent
14 {
15
16     protected $page;
17
18     /**
19      * PageContent constructor.
20      */
21     public function __construct(Page $page)
22     {
23         $this->page = $page;
24     }
25
26     /**
27      * Update the content of the page with new provided HTML.
28      */
29     public function setNewHTML(string $html)
30     {
31         $this->page->html = $this->formatHtml($html);
32         $this->page->text = $this->toPlainText();
33         $this->page->markdown = '';
34     }
35
36     /**
37      * Update the content of the page with new provided Markdown content.
38      */
39     public function setNewMarkdown(string $markdown)
40     {
41         $this->page->markdown = $markdown;
42         $html = $this->markdownToHtml($markdown);
43         $this->page->html = $this->formatHtml($html);
44         $this->page->text = $this->toPlainText();
45     }
46
47     /**
48      * Convert the given Markdown content to a HTML string.
49      */
50     protected function markdownToHtml(string $markdown): string
51     {
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);
58     }
59
60     /**
61      * Formats a page's html to be tagged correctly within the system.
62      */
63     protected function formatHtml(string $htmlText): string
64     {
65         if ($htmlText == '') {
66             return $htmlText;
67         }
68
69         libxml_use_internal_errors(true);
70         $doc = new DOMDocument();
71         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
72
73         $container = $doc->documentElement;
74         $body = $container->childNodes->item(0);
75         $childNodes = $body->childNodes;
76         $xPath = new DOMXPath($doc);
77
78         // Set ids on top-level nodes
79         $idMap = [];
80         foreach ($childNodes as $index => $childNode) {
81             [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
82             if ($newId && $newId !== $oldId) {
83                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
84             }
85         }
86
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);
93             }
94         }
95
96         // Generate inner html as a string
97         $html = '';
98         foreach ($childNodes as $childNode) {
99             $html .= $doc->saveHTML($childNode);
100         }
101
102         return $html;
103     }
104
105     /**
106      * Update the all links to the $old location to instead point to $new.
107      */
108     protected function updateLinks(DOMXPath $xpath, string $old, string $new)
109     {
110         $old = str_replace('"', '', $old);
111         $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
112         foreach ($matchingLinks as $domElem) {
113             $domElem->setAttribute('href', $new);
114         }
115     }
116
117     /**
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]
121      */
122     protected function setUniqueId(\DOMNode $element, array &$idMap): array
123     {
124         if (get_class($element) !== 'DOMElement') {
125             return ['', ''];
126         }
127
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];
133         }
134
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);
140         $loopIndex = 0;
141
142         while (isset($idMap[$newId])) {
143             $newId = urlencode($contentId . '-' . $loopIndex);
144             $loopIndex++;
145         }
146
147         $element->setAttribute('id', $newId);
148         $idMap[$newId] = true;
149         return [$existingId, $newId];
150     }
151
152     /**
153      * Get a plain-text visualisation of this page.
154      */
155     protected function toPlainText(): string
156     {
157         $html = $this->render(true);
158         return html_entity_decode(strip_tags($html));
159     }
160
161     /**
162      * Render the page for viewing
163      */
164     public function render(bool $blankIncludes = false) : string
165     {
166         $content = $this->page->html;
167
168         if (!config('app.allow_content_scripts')) {
169             $content = $this->escapeScripts($content);
170         }
171
172         if ($blankIncludes) {
173             $content = $this->blankPageIncludes($content);
174         } else {
175             $content = $this->parsePageIncludes($content);
176         }
177
178         return $content;
179     }
180
181     /**
182      * Parse the headers on the page to get a navigation menu
183      */
184     public function getNavigation(string $htmlContent): array
185     {
186         if (empty($htmlContent)) {
187             return [];
188         }
189
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");
195
196         return $headers ? $this->headerNodesToLevelList($headers) : [];
197     }
198
199     /**
200      * Convert a DOMNodeList into an array of readable header attributes
201      * with levels normalised to the lower header level.
202      */
203     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
204     {
205         $tree = collect($nodeList)->map(function ($header) {
206             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
207             $text = mb_substr($text, 0, 100);
208
209             return [
210                 'nodeName' => strtolower($header->nodeName),
211                 'level' => intval(str_replace('h', '', $header->nodeName)),
212                 'link' => '#' . $header->getAttribute('id'),
213                 'text' => $text,
214             ];
215         })->filter(function ($header) {
216             return mb_strlen($header['text']) > 0;
217         });
218
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);
223             return $header;
224         });
225
226         return $tree->toArray();
227     }
228
229     /**
230      * Remove any page include tags within the given HTML.
231      */
232     protected function blankPageIncludes(string $html) : string
233     {
234         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
235     }
236
237     /**
238      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
239      */
240     protected function parsePageIncludes(string $html) : string
241     {
242         $matches = [];
243         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
244
245         foreach ($matches[1] as $index => $includeId) {
246             $fullMatch = $matches[0][$index];
247             $splitInclude = explode('#', $includeId, 2);
248
249             // Get page id from reference
250             $pageId = intval($splitInclude[0]);
251             if (is_nan($pageId)) {
252                 continue;
253             }
254
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);
259                 continue;
260             }
261
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);
265                 continue;
266             }
267
268             // Create and load HTML into a document
269             $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
270             $html = str_replace($fullMatch, trim($innerContent), $html);
271         }
272
273         return $html;
274     }
275
276
277     /**
278      * Fetch the content from a specific section of the given page.
279      */
280     protected function fetchSectionOfPage(Page $page, string $sectionId): string
281     {
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'));
286
287         // Search included content for the id given and blank out if not exists.
288         $matchingElem = $doc->getElementById($sectionId);
289         if ($matchingElem === null) {
290             return '';
291         }
292
293         // Otherwise replace the content with the found content
294         // Checks if the top-level wrapper should be included by matching on tag types
295         $innerContent = '';
296         $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
297         if ($isTopLevel) {
298             $innerContent .= $doc->saveHTML($matchingElem);
299         } else {
300             foreach ($matchingElem->childNodes as $childNode) {
301                 $innerContent .= $doc->saveHTML($childNode);
302             }
303         }
304         libxml_clear_errors();
305
306         return $innerContent;
307     }
308
309     /**
310      * Escape script tags within HTML content.
311      */
312     protected function escapeScripts(string $html) : string
313     {
314         if (empty($html)) {
315             return $html;
316         }
317
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);
322
323         // Remove standard script tags
324         $scriptElems = $xPath->query('//script');
325         foreach ($scriptElems as $scriptElem) {
326             $scriptElem->parentNode->removeChild($scriptElem);
327         }
328
329         // Remove clickable links to JavaScript URI
330         $badLinks = $xPath->query('//*[contains(@href, \'javascript:\')]');
331         foreach ($badLinks as $badLink) {
332             $badLink->parentNode->removeChild($badLink);
333         }
334
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);
339         }
340
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);
345         }
346
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);
351         }
352
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);
359         }
360
361         $html = '';
362         $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
363         foreach ($topElems as $child) {
364             $html .= $doc->saveHTML($child);
365         }
366
367         return $html;
368     }
369 }