]> BookStack Code Mirror - bookstack/blob - app/Entities/Managers/PageContent.php
Fix build:js:watch not building at first launch in Docker
[bookstack] / app / Entities / Managers / PageContent.php
1 <?php namespace BookStack\Entities\Managers;
2
3 use BookStack\Entities\Page;
4 use DOMDocument;
5 use DOMNodeList;
6 use DOMXPath;
7
8 class PageContent
9 {
10
11     protected $page;
12
13     /**
14      * PageContent constructor.
15      */
16     public function __construct(Page $page)
17     {
18         $this->page = $page;
19     }
20
21     /**
22      * Update the content of the page with new provided HTML.
23      */
24     public function setNewHTML(string $html)
25     {
26         $this->page->html = $this->formatHtml($html);
27         $this->page->text = $this->toPlainText();
28     }
29
30     /**
31      * Formats a page's html to be tagged correctly within the system.
32      */
33     protected function formatHtml(string $htmlText): string
34     {
35         if ($htmlText == '') {
36             return $htmlText;
37         }
38
39         libxml_use_internal_errors(true);
40         $doc = new DOMDocument();
41         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
42
43         $container = $doc->documentElement;
44         $body = $container->childNodes->item(0);
45         $childNodes = $body->childNodes;
46         $xPath = new DOMXPath($doc);
47
48         // Set ids on top-level nodes
49         $idMap = [];
50         foreach ($childNodes as $index => $childNode) {
51             [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
52             if ($newId && $newId !== $oldId) {
53                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
54             }
55         }
56
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);
63             }
64         }
65
66         // Generate inner html as a string
67         $html = '';
68         foreach ($childNodes as $childNode) {
69             $html .= $doc->saveHTML($childNode);
70         }
71
72         return $html;
73     }
74
75     /**
76      * Update the all links to the $old location to instead point to $new.
77      */
78     protected function updateLinks(DOMXPath $xpath, string $old, string $new)
79     {
80         $old = str_replace('"', '', $old);
81         $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
82         foreach ($matchingLinks as $domElem) {
83             $domElem->setAttribute('href', $new);
84         }
85     }
86
87     /**
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]
91      */
92     protected function setUniqueId(\DOMNode $element, array &$idMap): array
93     {
94         if (get_class($element) !== 'DOMElement') {
95             return ['', ''];
96         }
97
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];
103         }
104
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);
110         $loopIndex = 0;
111
112         while (isset($idMap[$newId])) {
113             $newId = urlencode($contentId . '-' . $loopIndex);
114             $loopIndex++;
115         }
116
117         $element->setAttribute('id', $newId);
118         $idMap[$newId] = true;
119         return [$existingId, $newId];
120     }
121
122     /**
123      * Get a plain-text visualisation of this page.
124      */
125     protected function toPlainText(): string
126     {
127         $html = $this->render(true);
128         return html_entity_decode(strip_tags($html));
129     }
130
131     /**
132      * Render the page for viewing
133      */
134     public function render(bool $blankIncludes = false) : string
135     {
136         $content = $this->page->html;
137
138         if (!config('app.allow_content_scripts')) {
139             $content = $this->escapeScripts($content);
140         }
141
142         if ($blankIncludes) {
143             $content = $this->blankPageIncludes($content);
144         } else {
145             $content = $this->parsePageIncludes($content);
146         }
147
148         return $content;
149     }
150
151     /**
152      * Parse the headers on the page to get a navigation menu
153      */
154     public function getNavigation(string $htmlContent): array
155     {
156         if (empty($htmlContent)) {
157             return [];
158         }
159
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");
165
166         return $headers ? $this->headerNodesToLevelList($headers) : [];
167     }
168
169     /**
170      * Convert a DOMNodeList into an array of readable header attributes
171      * with levels normalised to the lower header level.
172      */
173     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
174     {
175         $tree = collect($nodeList)->map(function ($header) {
176             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
177             $text = mb_substr($text, 0, 100);
178
179             return [
180                 'nodeName' => strtolower($header->nodeName),
181                 'level' => intval(str_replace('h', '', $header->nodeName)),
182                 'link' => '#' . $header->getAttribute('id'),
183                 'text' => $text,
184             ];
185         })->filter(function ($header) {
186             return mb_strlen($header['text']) > 0;
187         });
188
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);
193             return $header;
194         });
195
196         return $tree->toArray();
197     }
198
199     /**
200      * Remove any page include tags within the given HTML.
201      */
202     protected function blankPageIncludes(string $html) : string
203     {
204         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
205     }
206
207     /**
208      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
209      */
210     protected function parsePageIncludes(string $html) : string
211     {
212         $matches = [];
213         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
214
215         foreach ($matches[1] as $index => $includeId) {
216             $fullMatch = $matches[0][$index];
217             $splitInclude = explode('#', $includeId, 2);
218
219             // Get page id from reference
220             $pageId = intval($splitInclude[0]);
221             if (is_nan($pageId)) {
222                 continue;
223             }
224
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);
229                 continue;
230             }
231
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);
235                 continue;
236             }
237
238             // Create and load HTML into a document
239             $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
240             $html = str_replace($fullMatch, trim($innerContent), $html);
241         }
242
243         return $html;
244     }
245
246
247     /**
248      * Fetch the content from a specific section of the given page.
249      */
250     protected function fetchSectionOfPage(Page $page, string $sectionId): string
251     {
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'));
256
257         // Search included content for the id given and blank out if not exists.
258         $matchingElem = $doc->getElementById($sectionId);
259         if ($matchingElem === null) {
260             return '';
261         }
262
263         // Otherwise replace the content with the found content
264         // Checks if the top-level wrapper should be included by matching on tag types
265         $innerContent = '';
266         $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
267         if ($isTopLevel) {
268             $innerContent .= $doc->saveHTML($matchingElem);
269         } else {
270             foreach ($matchingElem->childNodes as $childNode) {
271                 $innerContent .= $doc->saveHTML($childNode);
272             }
273         }
274         libxml_clear_errors();
275
276         return $innerContent;
277     }
278
279     /**
280      * Escape script tags within HTML content.
281      */
282     protected function escapeScripts(string $html) : string
283     {
284         if (empty($html)) {
285             return $html;
286         }
287
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);
292
293         // Remove standard script tags
294         $scriptElems = $xPath->query('//script');
295         foreach ($scriptElems as $scriptElem) {
296             $scriptElem->parentNode->removeChild($scriptElem);
297         }
298
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);
303         }
304
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);
311         }
312
313         $html = '';
314         $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
315         foreach ($topElems as $child) {
316             $html .= $doc->saveHTML($child);
317         }
318
319         return $html;
320     }
321 }