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