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