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