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