]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
Opensearch: Fixed XML declaration when php short tags enabled
[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\Queries\PageQueries;
7 use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
8 use BookStack\Exceptions\ImageUploadException;
9 use BookStack\Facades\Theme;
10 use BookStack\Theming\ThemeEvents;
11 use BookStack\Uploads\ImageRepo;
12 use BookStack\Uploads\ImageService;
13 use BookStack\Users\Models\User;
14 use BookStack\Util\HtmlContentFilter;
15 use BookStack\Util\HtmlDocument;
16 use BookStack\Util\WebSafeMimeSniffer;
17 use Closure;
18 use DOMElement;
19 use DOMNode;
20 use DOMNodeList;
21 use Illuminate\Support\Str;
22
23 class PageContent
24 {
25     protected PageQueries $pageQueries;
26
27     public function __construct(
28         protected Page $page
29     ) {
30         $this->pageQueries = app()->make(PageQueries::class);
31     }
32
33     /**
34      * Update the content of the page with new provided HTML.
35      */
36     public function setNewHTML(string $html, User $updater): void
37     {
38         $html = $this->extractBase64ImagesFromHtml($html, $updater);
39         $this->page->html = $this->formatHtml($html);
40         $this->page->text = $this->toPlainText();
41         $this->page->markdown = '';
42     }
43
44     /**
45      * Update the content of the page with new provided Markdown content.
46      */
47     public function setNewMarkdown(string $markdown, User $updater): void
48     {
49         $markdown = $this->extractBase64ImagesFromMarkdown($markdown, $updater);
50         $this->page->markdown = $markdown;
51         $html = (new MarkdownToHtml($markdown))->convert();
52         $this->page->html = $this->formatHtml($html);
53         $this->page->text = $this->toPlainText();
54     }
55
56     /**
57      * Convert all base64 image data to saved images.
58      */
59     protected function extractBase64ImagesFromHtml(string $htmlText, User $updater): string
60     {
61         if (empty($htmlText) || !str_contains($htmlText, 'data:image')) {
62             return $htmlText;
63         }
64
65         $doc = new HtmlDocument($htmlText);
66
67         // Get all img elements with image data blobs
68         $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]');
69         /** @var DOMElement $imageNode */
70         foreach ($imageNodes as $imageNode) {
71             $imageSrc = $imageNode->getAttribute('src');
72             $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater);
73             $imageNode->setAttribute('src', $newUrl);
74         }
75
76         return $doc->getBodyInnerHtml();
77     }
78
79     /**
80      * Convert all inline base64 content to uploaded image files.
81      * Regex is used to locate the start of data-uri definitions then
82      * manual looping over content is done to parse the whole data uri.
83      * Attempting to capture the whole data uri using regex can cause PHP
84      * PCRE limits to be hit with larger, multi-MB, files.
85      */
86     protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string
87     {
88         $matches = [];
89         $contentLength = strlen($markdown);
90         $replacements = [];
91         preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
92
93         foreach ($matches[1] as $base64MatchPair) {
94             [$dataUri, $index] = $base64MatchPair;
95
96             for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
97                 $char = $markdown[$i];
98                 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
99                     break;
100                 }
101                 $dataUri .= $char;
102             }
103
104             $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater);
105             $replacements[] = [$dataUri, $newUrl];
106         }
107
108         foreach ($replacements as [$dataUri, $newUrl]) {
109             $markdown = str_replace($dataUri, $newUrl, $markdown);
110         }
111
112         return $markdown;
113     }
114
115     /**
116      * Parse the given base64 image URI and return the URL to the created image instance.
117      * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
118      */
119     protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string
120     {
121         $imageRepo = app()->make(ImageRepo::class);
122         $imageInfo = $this->parseBase64ImageUri($uri);
123
124         // Validate user has permission to create images
125         if (!$updater->can('image-create-all')) {
126             return '';
127         }
128
129         // Validate extension and content
130         if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
131             return '';
132         }
133
134         // Validate content looks like an image via sniffing mime type
135         $mimeSniffer = new WebSafeMimeSniffer();
136         $mime = $mimeSniffer->sniff($imageInfo['data']);
137         if (!str_starts_with($mime, 'image/')) {
138             return '';
139         }
140
141         // Validate that the content is not over our upload limit
142         $uploadLimitBytes = (config('app.upload_limit') * 1000000);
143         if (strlen($imageInfo['data']) > $uploadLimitBytes) {
144             return '';
145         }
146
147         // Save image from data with a random name
148         $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
149
150         try {
151             $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
152         } catch (ImageUploadException $exception) {
153             return '';
154         }
155
156         return $image->url;
157     }
158
159     /**
160      * Parse a base64 image URI into the data and extension.
161      *
162      * @return array{extension: string, data: string}
163      */
164     protected function parseBase64ImageUri(string $uri): array
165     {
166         [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
167         $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
168
169         return [
170             'extension' => $extension,
171             'data'      => base64_decode($base64ImageData) ?: '',
172         ];
173     }
174
175     /**
176      * Formats a page's html to be tagged correctly within the system.
177      */
178     protected function formatHtml(string $htmlText): string
179     {
180         if (empty($htmlText)) {
181             return $htmlText;
182         }
183
184         $doc = new HtmlDocument($htmlText);
185
186         // Map to hold used ID references
187         $idMap = [];
188         // Map to hold changing ID references
189         $changeMap = [];
190
191         $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
192         $this->updateLinks($doc, $changeMap);
193
194         // Generate inner html as a string & perform required string-level tweaks
195         $html = $doc->getBodyInnerHtml();
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(HtmlDocument $doc, array $changeMap): void
229     {
230         if (empty($changeMap)) {
231             return;
232         }
233
234         $links = $doc->queryXPath('//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         $html = $this->page->html ?? '';
299
300         if (empty($html)) {
301             return $html;
302         }
303
304         $doc = new HtmlDocument($html);
305         $contentProvider = $this->getContentProviderClosure($blankIncludes);
306         $parser = new PageIncludeParser($doc, $contentProvider);
307
308         $nodesAdded = 1;
309         for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) {
310             $nodesAdded = $parser->parse();
311         }
312
313         if ($includeDepth > 1) {
314             $idMap = [];
315             $changeMap = [];
316             $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
317         }
318
319         if (!config('app.allow_content_scripts')) {
320             HtmlContentFilter::removeScriptsFromDocument($doc);
321         }
322
323         return $doc->getBodyInnerHtml();
324     }
325
326     /**
327      * Get the closure used to fetch content for page includes.
328      */
329     protected function getContentProviderClosure(bool $blankIncludes): Closure
330     {
331         $contextPage = $this->page;
332         $queries = $this->pageQueries;
333
334         return function (PageIncludeTag $tag) use ($blankIncludes, $contextPage, $queries): PageIncludeContent {
335             if ($blankIncludes) {
336                 return PageIncludeContent::fromHtmlAndTag('', $tag);
337             }
338
339             $matchedPage = $queries->findVisibleById($tag->getPageId());
340             $content = PageIncludeContent::fromHtmlAndTag($matchedPage->html ?? '', $tag);
341
342             if (Theme::hasListeners(ThemeEvents::PAGE_INCLUDE_PARSE)) {
343                 $themeReplacement = Theme::dispatch(
344                     ThemeEvents::PAGE_INCLUDE_PARSE,
345                     $tag->tagContent,
346                     $content->toHtml(),
347                     clone $contextPage,
348                     $matchedPage ? (clone $matchedPage) : null,
349                 );
350
351                 if ($themeReplacement !== null) {
352                     $content = PageIncludeContent::fromInlineHtml(strval($themeReplacement));
353                 }
354             }
355
356             return $content;
357         };
358     }
359
360     /**
361      * Parse the headers on the page to get a navigation menu.
362      */
363     public function getNavigation(string $htmlContent): array
364     {
365         if (empty($htmlContent)) {
366             return [];
367         }
368
369         $doc = new HtmlDocument($htmlContent);
370         $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6');
371
372         return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers);
373     }
374
375     /**
376      * Convert a DOMNodeList into an array of readable header attributes
377      * with levels normalised to the lower header level.
378      */
379     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
380     {
381         $tree = collect($nodeList)->map(function (DOMElement $header) {
382             $text = trim(str_replace("\xc2\xa0", ' ', $header->nodeValue));
383             $text = mb_substr($text, 0, 100);
384
385             return [
386                 'nodeName' => strtolower($header->nodeName),
387                 'level'    => intval(str_replace('h', '', $header->nodeName)),
388                 'link'     => '#' . $header->getAttribute('id'),
389                 'text'     => $text,
390             ];
391         })->filter(function ($header) {
392             return mb_strlen($header['text']) > 0;
393         });
394
395         // Shift headers if only smaller headers have been used
396         $levelChange = ($tree->pluck('level')->min() - 1);
397         $tree = $tree->map(function ($header) use ($levelChange) {
398             $header['level'] -= ($levelChange);
399
400             return $header;
401         });
402
403         return $tree->toArray();
404     }
405 }