]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
7f4d695febac8d0880d357aa2e857e807f605dc5
[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         $html = $this->page->html ?? '';
279
280         if (empty($html)) {
281             return $html;
282         }
283
284         $doc = new HtmlDocument($html);
285
286         $contentProvider = function (int $id) use ($blankIncludes) {
287             if ($blankIncludes) {
288                 return '';
289             }
290             return Page::visible()->find($id)->html ?? '';
291         };
292
293         $parser = new PageIncludeParser($doc, $contentProvider);
294         $nodesAdded = 1;
295
296         for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) {
297             $nodesAdded = $parser->parse();
298         }
299
300         if (!config('app.allow_content_scripts')) {
301             HtmlContentFilter::removeScriptsFromDocument($doc);
302         }
303
304         return $doc->getBodyInnerHtml();
305     }
306
307     /**
308      * Parse the headers on the page to get a navigation menu.
309      */
310     public function getNavigation(string $htmlContent): array
311     {
312         if (empty($htmlContent)) {
313             return [];
314         }
315
316         $doc = new HtmlDocument($htmlContent);
317         $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
318
319         return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
320     }
321
322     /**
323      * Convert a DOMNodeList into an array of readable header attributes
324      * with levels normalised to the lower header level.
325      */
326     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
327     {
328         $tree = collect($nodeList)->map(function (DOMElement $header) {
329             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
330             $text = mb_substr($text, 0, 100);
331
332             return [
333                 'nodeName' => strtolower($header->nodeName),
334                 'level'    => intval(str_replace('h', '', $header->nodeName)),
335                 'link'     => '#' . $header->getAttribute('id'),
336                 'text'     => $text,
337             ];
338         })->filter(function ($header) {
339             return mb_strlen($header['text']) > 0;
340         });
341
342         // Shift headers if only smaller headers have been used
343         $levelChange = ($tree->pluck('level')->min() - 1);
344         $tree = $tree->map(function ($header) use ($levelChange) {
345             $header['level'] -= ($levelChange);
346
347             return $header;
348         });
349
350         return $tree->toArray();
351     }
352 }