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