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