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