]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
Images: Prevented base64 extraction without permission
[bookstack] / app / Entities / Tools / PageContent.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
7 use BookStack\Exceptions\ImageUploadException;
8 use BookStack\Facades\Theme;
9 use BookStack\Theming\ThemeEvents;
10 use BookStack\Uploads\ImageRepo;
11 use BookStack\Uploads\ImageService;
12 use BookStack\Users\Models\User;
13 use BookStack\Util\HtmlContentFilter;
14 use BookStack\Util\WebSafeMimeSniffer;
15 use DOMDocument;
16 use DOMElement;
17 use DOMNode;
18 use DOMNodeList;
19 use DOMXPath;
20 use Illuminate\Support\Str;
21
22 class PageContent
23 {
24     public function __construct(
25         protected Page $page
26     ) {
27     }
28
29     /**
30      * Update the content of the page with new provided HTML.
31      */
32     public function setNewHTML(string $html, User $updater): void
33     {
34         $html = $this->extractBase64ImagesFromHtml($html, $updater);
35         $this->page->html = $this->formatHtml($html);
36         $this->page->text = $this->toPlainText();
37         $this->page->markdown = '';
38     }
39
40     /**
41      * Update the content of the page with new provided Markdown content.
42      */
43     public function setNewMarkdown(string $markdown, User $updater): void
44     {
45         $markdown = $this->extractBase64ImagesFromMarkdown($markdown, $updater);
46         $this->page->markdown = $markdown;
47         $html = (new MarkdownToHtml($markdown))->convert();
48         $this->page->html = $this->formatHtml($html);
49         $this->page->text = $this->toPlainText();
50     }
51
52     /**
53      * Convert all base64 image data to saved images.
54      */
55     protected function extractBase64ImagesFromHtml(string $htmlText, User $updater): string
56     {
57         if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
58             return $htmlText;
59         }
60
61         $doc = $this->loadDocumentFromHtml($htmlText);
62         $container = $doc->documentElement;
63         $body = $container->childNodes->item(0);
64         $childNodes = $body->childNodes;
65         $xPath = new DOMXPath($doc);
66
67         // Get all img elements with image data blobs
68         $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
69         foreach ($imageNodes as $imageNode) {
70             $imageSrc = $imageNode->getAttribute('src');
71             $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater);
72             $imageNode->setAttribute('src', $newUrl);
73         }
74
75         // Generate inner html as a string
76         $html = '';
77         foreach ($childNodes as $childNode) {
78             $html .= $doc->saveHTML($childNode);
79         }
80
81         return $html;
82     }
83
84     /**
85      * Convert all inline base64 content to uploaded image files.
86      * Regex is used to locate the start of data-uri definitions then
87      * manual looping over content is done to parse the whole data uri.
88      * Attempting to capture the whole data uri using regex can cause PHP
89      * PCRE limits to be hit with larger, multi-MB, files.
90      */
91     protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string
92     {
93         $matches = [];
94         $contentLength = strlen($markdown);
95         $replacements = [];
96         preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
97
98         foreach ($matches[1] as $base64MatchPair) {
99             [$dataUri, $index] = $base64MatchPair;
100
101             for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
102                 $char = $markdown[$i];
103                 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
104                     break;
105                 }
106                 $dataUri .= $char;
107             }
108
109             $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater);
110             $replacements[] = [$dataUri, $newUrl];
111         }
112
113         foreach ($replacements as [$dataUri, $newUrl]) {
114             $markdown = str_replace($dataUri, $newUrl, $markdown);
115         }
116
117         return $markdown;
118     }
119
120     /**
121      * Parse the given base64 image URI and return the URL to the created image instance.
122      * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
123      */
124     protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string
125     {
126         $imageRepo = app()->make(ImageRepo::class);
127         $imageInfo = $this->parseBase64ImageUri($uri);
128
129         // Validate user has permission to create images
130         if (!$updater->can('image-create-all')) {
131             return '';
132         }
133
134         // Validate extension and content
135         if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
136             return '';
137         }
138
139         // Validate content looks like an image via sniffing mime type
140         $mimeSniffer = new WebSafeMimeSniffer();
141         $mime = $mimeSniffer->sniff($imageInfo['data']);
142         if (!str_starts_with($mime, 'image/')) {
143             return '';
144         }
145
146         // Validate that the content is not over our upload limit
147         $uploadLimitBytes = (config('app.upload_limit') * 1000000);
148         if (strlen($imageInfo['data']) > $uploadLimitBytes) {
149             return '';
150         }
151
152         // Save image from data with a random name
153         $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
154
155         try {
156             $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
157         } catch (ImageUploadException $exception) {
158             return '';
159         }
160
161         return $image->url;
162     }
163
164     /**
165      * Parse a base64 image URI into the data and extension.
166      *
167      * @return array{extension: string, data: string}
168      */
169     protected function parseBase64ImageUri(string $uri): array
170     {
171         [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
172         $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
173
174         return [
175             'extension' => $extension,
176             'data'      => base64_decode($base64ImageData) ?: '',
177         ];
178     }
179
180     /**
181      * Formats a page's html to be tagged correctly within the system.
182      */
183     protected function formatHtml(string $htmlText): string
184     {
185         if (empty($htmlText)) {
186             return $htmlText;
187         }
188
189         $doc = $this->loadDocumentFromHtml($htmlText);
190         $container = $doc->documentElement;
191         $body = $container->childNodes->item(0);
192         $childNodes = $body->childNodes;
193         $xPath = new DOMXPath($doc);
194
195         // Map to hold used ID references
196         $idMap = [];
197         // Map to hold changing ID references
198         $changeMap = [];
199
200         $this->updateIdsRecursively($body, 0, $idMap, $changeMap);
201         $this->updateLinks($xPath, $changeMap);
202
203         // Generate inner html as a string
204         $html = '';
205         foreach ($childNodes as $childNode) {
206             $html .= $doc->saveHTML($childNode);
207         }
208
209         // Perform required string-level tweaks
210         $html = str_replace(' ', '&nbsp;', $html);
211
212         return $html;
213     }
214
215     /**
216      * For the given DOMNode, traverse its children recursively and update IDs
217      * where required (Top-level, headers & elements with IDs).
218      * Will update the provided $changeMap array with changes made, where keys are the old
219      * ids and the corresponding values are the new ids.
220      */
221     protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
222     {
223         /* @var DOMNode $child */
224         foreach ($element->childNodes as $child) {
225             if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
226                 [$oldId, $newId] = $this->setUniqueId($child, $idMap);
227                 if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
228                     $changeMap[$oldId] = $newId;
229                 }
230             }
231
232             if ($child->hasChildNodes()) {
233                 $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
234             }
235         }
236     }
237
238     /**
239      * Update the all links in the given xpath to apply requires changes within the
240      * given $changeMap array.
241      */
242     protected function updateLinks(DOMXPath $xpath, array $changeMap): void
243     {
244         if (empty($changeMap)) {
245             return;
246         }
247
248         $links = $xpath->query('//body//*//*[@href]');
249         /** @var DOMElement $domElem */
250         foreach ($links as $domElem) {
251             $href = ltrim($domElem->getAttribute('href'), '#');
252             $newHref = $changeMap[$href] ?? null;
253             if ($newHref) {
254                 $domElem->setAttribute('href', '#' . $newHref);
255             }
256         }
257     }
258
259     /**
260      * Set a unique id on the given DOMElement.
261      * A map for existing ID's should be passed in to check for current existence,
262      * and this will be updated with any new IDs set upon elements.
263      * Returns a pair of strings in the format [old_id, new_id].
264      */
265     protected function setUniqueId(DOMNode $element, array &$idMap): array
266     {
267         if (!$element instanceof DOMElement) {
268             return ['', ''];
269         }
270
271         // Stop if there's an existing valid id that has not already been used.
272         $existingId = $element->getAttribute('id');
273         if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) {
274             $idMap[$existingId] = true;
275
276             return [$existingId, $existingId];
277         }
278
279         // Create a unique id for the element
280         // Uses the content as a basis to ensure output is the same every time
281         // the same content is passed through.
282         $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
283         $newId = urlencode($contentId);
284         $loopIndex = 1;
285
286         while (isset($idMap[$newId])) {
287             $newId = urlencode($contentId . '-' . $loopIndex);
288             $loopIndex++;
289         }
290
291         $element->setAttribute('id', $newId);
292         $idMap[$newId] = true;
293
294         return [$existingId, $newId];
295     }
296
297     /**
298      * Get a plain-text visualisation of this page.
299      */
300     protected function toPlainText(): string
301     {
302         $html = $this->render(true);
303
304         return html_entity_decode(strip_tags($html));
305     }
306
307     /**
308      * Render the page for viewing.
309      */
310     public function render(bool $blankIncludes = false): string
311     {
312         $content = $this->page->html ?? '';
313
314         if (!config('app.allow_content_scripts')) {
315             $content = HtmlContentFilter::removeScripts($content);
316         }
317
318         if ($blankIncludes) {
319             $content = $this->blankPageIncludes($content);
320         } else {
321             for ($includeDepth = 0; $includeDepth < 3; $includeDepth++) {
322                 $content = $this->parsePageIncludes($content);
323             }
324         }
325
326         return $content;
327     }
328
329     /**
330      * Parse the headers on the page to get a navigation menu.
331      */
332     public function getNavigation(string $htmlContent): array
333     {
334         if (empty($htmlContent)) {
335             return [];
336         }
337
338         $doc = $this->loadDocumentFromHtml($htmlContent);
339         $xPath = new DOMXPath($doc);
340         $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
341
342         return $headers ? $this->headerNodesToLevelList($headers) : [];
343     }
344
345     /**
346      * Convert a DOMNodeList into an array of readable header attributes
347      * with levels normalised to the lower header level.
348      */
349     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
350     {
351         $tree = collect($nodeList)->map(function (DOMElement $header) {
352             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
353             $text = mb_substr($text, 0, 100);
354
355             return [
356                 'nodeName' => strtolower($header->nodeName),
357                 'level'    => intval(str_replace('h', '', $header->nodeName)),
358                 'link'     => '#' . $header->getAttribute('id'),
359                 'text'     => $text,
360             ];
361         })->filter(function ($header) {
362             return mb_strlen($header['text']) > 0;
363         });
364
365         // Shift headers if only smaller headers have been used
366         $levelChange = ($tree->pluck('level')->min() - 1);
367         $tree = $tree->map(function ($header) use ($levelChange) {
368             $header['level'] -= ($levelChange);
369
370             return $header;
371         });
372
373         return $tree->toArray();
374     }
375
376     /**
377      * Remove any page include tags within the given HTML.
378      */
379     protected function blankPageIncludes(string $html): string
380     {
381         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
382     }
383
384     /**
385      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
386      */
387     protected function parsePageIncludes(string $html): string
388     {
389         $matches = [];
390         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
391
392         foreach ($matches[1] as $index => $includeId) {
393             $fullMatch = $matches[0][$index];
394             $splitInclude = explode('#', $includeId, 2);
395
396             // Get page id from reference
397             $pageId = intval($splitInclude[0]);
398             if (is_nan($pageId)) {
399                 continue;
400             }
401
402             // Find page to use, and default replacement to empty string for non-matches.
403             /** @var ?Page $matchedPage */
404             $matchedPage = Page::visible()->find($pageId);
405             $replacement = '';
406
407             if ($matchedPage && count($splitInclude) === 1) {
408                 // If we only have page id, just insert all page html and continue.
409                 $replacement = $matchedPage->html;
410             } elseif ($matchedPage && count($splitInclude) > 1) {
411                 // Otherwise, if our include tag defines a section, load that specific content
412                 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
413                 $replacement = trim($innerContent);
414             }
415
416             $themeReplacement = Theme::dispatch(
417                 ThemeEvents::PAGE_INCLUDE_PARSE,
418                 $includeId,
419                 $replacement,
420                 clone $this->page,
421                 $matchedPage ? (clone $matchedPage) : null,
422             );
423
424             // Perform the content replacement
425             $html = str_replace($fullMatch, $themeReplacement ?? $replacement, $html);
426         }
427
428         return $html;
429     }
430
431     /**
432      * Fetch the content from a specific section of the given page.
433      */
434     protected function fetchSectionOfPage(Page $page, string $sectionId): string
435     {
436         $topLevelTags = ['table', 'ul', 'ol', 'pre'];
437         $doc = $this->loadDocumentFromHtml($page->html);
438
439         // Search included content for the id given and blank out if not exists.
440         $matchingElem = $doc->getElementById($sectionId);
441         if ($matchingElem === null) {
442             return '';
443         }
444
445         // Otherwise replace the content with the found content
446         // Checks if the top-level wrapper should be included by matching on tag types
447         $innerContent = '';
448         $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
449         if ($isTopLevel) {
450             $innerContent .= $doc->saveHTML($matchingElem);
451         } else {
452             foreach ($matchingElem->childNodes as $childNode) {
453                 $innerContent .= $doc->saveHTML($childNode);
454             }
455         }
456         libxml_clear_errors();
457
458         return $innerContent;
459     }
460
461     /**
462      * Create and load a DOMDocument from the given html content.
463      */
464     protected function loadDocumentFromHtml(string $html): DOMDocument
465     {
466         libxml_use_internal_errors(true);
467         $doc = new DOMDocument();
468         $html = '<?xml encoding="utf-8" ?><body>' . $html . '</body>';
469         $doc->loadHTML($html);
470
471         return $doc;
472     }
473 }