]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
Tiny header
[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\CustomListItemRenderer;
7 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
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\Util\HtmlContentFilter;
14 use DOMDocument;
15 use DOMElement;
16 use DOMNode;
17 use DOMNodeList;
18 use DOMXPath;
19 use Illuminate\Support\Str;
20 use League\CommonMark\Block\Element\ListItem;
21 use League\CommonMark\CommonMarkConverter;
22 use League\CommonMark\Environment;
23 use League\CommonMark\Extension\Table\TableExtension;
24 use League\CommonMark\Extension\TaskList\TaskListExtension;
25
26 class PageContent
27 {
28     protected $page;
29
30     /**
31      * PageContent constructor.
32      */
33     public function __construct(Page $page)
34     {
35         $this->page = $page;
36     }
37
38     /**
39      * Update the content of the page with new provided HTML.
40      */
41     public function setNewHTML(string $html)
42     {
43         $html = $this->extractBase64ImagesFromHtml($html);
44         $this->page->html = $this->formatHtml($html);
45         $this->page->text = $this->toPlainText();
46         $this->page->markdown = '';
47     }
48
49     /**
50      * Update the content of the page with new provided Markdown content.
51      */
52     public function setNewMarkdown(string $markdown)
53     {
54         $markdown = $this->extractBase64ImagesFromMarkdown($markdown);
55         $this->page->markdown = $markdown;
56         $html = $this->markdownToHtml($markdown);
57         $this->page->html = $this->formatHtml($html);
58         $this->page->text = $this->toPlainText();
59     }
60
61     /**
62      * Convert the given Markdown content to a HTML string.
63      */
64     protected function markdownToHtml(string $markdown): string
65     {
66         $environment = Environment::createCommonMarkEnvironment();
67         $environment->addExtension(new TableExtension());
68         $environment->addExtension(new TaskListExtension());
69         $environment->addExtension(new CustomStrikeThroughExtension());
70         $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment;
71         $converter = new CommonMarkConverter([], $environment);
72
73         $environment->addBlockRenderer(ListItem::class, new CustomListItemRenderer(), 10);
74
75         return $converter->convertToHtml($markdown);
76     }
77
78     /**
79      * Convert all base64 image data to saved images.
80      */
81     protected function extractBase64ImagesFromHtml(string $htmlText): string
82     {
83         if (empty($htmlText) || strpos($htmlText, 'data:image') === false) {
84             return $htmlText;
85         }
86
87         $doc = $this->loadDocumentFromHtml($htmlText);
88         $container = $doc->documentElement;
89         $body = $container->childNodes->item(0);
90         $childNodes = $body->childNodes;
91         $xPath = new DOMXPath($doc);
92
93         // Get all img elements with image data blobs
94         $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
95         foreach ($imageNodes as $imageNode) {
96             $imageSrc = $imageNode->getAttribute('src');
97             $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc);
98             $imageNode->setAttribute('src', $newUrl);
99         }
100
101         // Generate inner html as a string
102         $html = '';
103         foreach ($childNodes as $childNode) {
104             $html .= $doc->saveHTML($childNode);
105         }
106
107         return $html;
108     }
109
110     /**
111      * Convert all inline base64 content to uploaded image files.
112      * Regex is used to locate the start of data-uri definitions then
113      * manual looping over content is done to parse the whole data uri.
114      * Attempting to capture the whole data uri using regex can cause PHP
115      * PCRE limits to be hit with larger, multi-MB, files.
116      */
117     protected function extractBase64ImagesFromMarkdown(string $markdown)
118     {
119         $matches = [];
120         $contentLength = strlen($markdown);
121         $replacements = [];
122         preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE);
123
124         foreach ($matches[1] as $base64MatchPair) {
125             [$dataUri, $index] = $base64MatchPair;
126
127             for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) {
128                 $char = $markdown[$i];
129                 if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') {
130                     break;
131                 }
132                 $dataUri .= $char;
133             }
134
135             $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri);
136             $replacements[] = [$dataUri, $newUrl];
137         }
138
139         foreach ($replacements as [$dataUri, $newUrl]) {
140             $markdown = str_replace($dataUri, $newUrl, $markdown);
141         }
142
143         return $markdown;
144     }
145
146     /**
147      * Parse the given base64 image URI and return the URL to the created image instance.
148      * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
149      */
150     protected function base64ImageUriToUploadedImageUrl(string $uri): string
151     {
152         $imageRepo = app()->make(ImageRepo::class);
153         $imageInfo = $this->parseBase64ImageUri($uri);
154
155         // Validate extension and content
156         if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
157             return '';
158         }
159
160         // Validate that the content is not over our upload limit
161         $uploadLimitBytes = (config('app.upload_limit') * 1000000);
162         if (strlen($imageInfo['data']) > $uploadLimitBytes) {
163             return '';
164         }
165
166         // Save image from data with a random name
167         $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
168
169         try {
170             $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
171         } catch (ImageUploadException $exception) {
172             return '';
173         }
174
175         return $image->url;
176     }
177
178     /**
179      * Parse a base64 image URI into the data and extension.
180      *
181      * @return array{extension: string, data: string}
182      */
183     protected function parseBase64ImageUri(string $uri): array
184     {
185         [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
186         $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
187
188         return [
189             'extension' => $extension,
190             'data'      => base64_decode($base64ImageData) ?: '',
191         ];
192     }
193
194     /**
195      * Formats a page's html to be tagged correctly within the system.
196      */
197     protected function formatHtml(string $htmlText): string
198     {
199         if (empty($htmlText)) {
200             return $htmlText;
201         }
202
203         $doc = $this->loadDocumentFromHtml($htmlText);
204         $container = $doc->documentElement;
205         $body = $container->childNodes->item(0);
206         $childNodes = $body->childNodes;
207         $xPath = new DOMXPath($doc);
208
209         // Set ids on top-level nodes
210         $idMap = [];
211         foreach ($childNodes as $index => $childNode) {
212             [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
213             if ($newId && $newId !== $oldId) {
214                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
215             }
216         }
217
218         // Set ids on nested header nodes
219         $nestedHeaders = $xPath->query('//body//*//h1|//body//*//h2|//body//*//h3|//body//*//h4|//body//*//h5|//body//*//h6');
220         foreach ($nestedHeaders as $nestedHeader) {
221             [$oldId, $newId] = $this->setUniqueId($nestedHeader, $idMap);
222             if ($newId && $newId !== $oldId) {
223                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
224             }
225         }
226
227         // Ensure no duplicate ids within child items
228         $idElems = $xPath->query('//body//*//*[@id]');
229         foreach ($idElems as $domElem) {
230             [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
231             if ($newId && $newId !== $oldId) {
232                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
233             }
234         }
235
236         // Generate inner html as a string
237         $html = '';
238         foreach ($childNodes as $childNode) {
239             $html .= $doc->saveHTML($childNode);
240         }
241
242         // Perform required string-level tweaks
243         $html = str_replace(' ', '&nbsp;', $html);
244
245         return $html;
246     }
247
248     /**
249      * Update the all links to the $old location to instead point to $new.
250      */
251     protected function updateLinks(DOMXPath $xpath, string $old, string $new)
252     {
253         $old = str_replace('"', '', $old);
254         $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
255         foreach ($matchingLinks as $domElem) {
256             $domElem->setAttribute('href', $new);
257         }
258     }
259
260     /**
261      * Set a unique id on the given DOMElement.
262      * A map for existing ID's should be passed in to check for current existence.
263      * Returns a pair of strings in the format [old_id, new_id].
264      */
265     protected function setUniqueId(DOMNode $element, array &$idMap): array
266     {
267         if (!$element instanceof DOMElement) {
268             return ['', ''];
269         }
270
271         // Stop if there's an existing valid id that has not already been used.
272         $existingId = $element->getAttribute('id');
273         if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
274             $idMap[$existingId] = true;
275
276             return [$existingId, $existingId];
277         }
278
279         // Create a unique id for the element
280         // Uses the content as a basis to ensure output is the same every time
281         // the same content is passed through.
282         $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
283         $newId = urlencode($contentId);
284         $loopIndex = 0;
285
286         while (isset($idMap[$newId])) {
287             $newId = urlencode($contentId . '-' . $loopIndex);
288             $loopIndex++;
289         }
290
291         $element->setAttribute('id', $newId);
292         $idMap[$newId] = true;
293
294         return [$existingId, $newId];
295     }
296
297     /**
298      * Get a plain-text visualisation of this page.
299      */
300     protected function toPlainText(): string
301     {
302         $html = $this->render(true);
303
304         return html_entity_decode(strip_tags($html));
305     }
306
307     /**
308      * Render the page for viewing.
309      */
310     public function render(bool $blankIncludes = false): string
311     {
312         $content = $this->page->html ?? '';
313
314         if (!config('app.allow_content_scripts')) {
315             $content = HtmlContentFilter::removeScripts($content);
316         }
317
318         if ($blankIncludes) {
319             $content = $this->blankPageIncludes($content);
320         } else {
321             $content = $this->parsePageIncludes($content);
322         }
323
324         return $content;
325     }
326
327     /**
328      * Parse the headers on the page to get a navigation menu.
329      */
330     public function getNavigation(string $htmlContent): array
331     {
332         if (empty($htmlContent)) {
333             return [];
334         }
335
336         $doc = $this->loadDocumentFromHtml($htmlContent);
337         $xPath = new DOMXPath($doc);
338         $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
339
340         return $headers ? $this->headerNodesToLevelList($headers) : [];
341     }
342
343     /**
344      * Convert a DOMNodeList into an array of readable header attributes
345      * with levels normalised to the lower header level.
346      */
347     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
348     {
349         $tree = collect($nodeList)->map(function (DOMElement $header) {
350             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
351             $text = mb_substr($text, 0, 100);
352
353             return [
354                 'nodeName' => strtolower($header->nodeName),
355                 'level'    => intval(str_replace('h', '', $header->nodeName)),
356                 'link'     => '#' . $header->getAttribute('id'),
357                 'text'     => $text,
358             ];
359         })->filter(function ($header) {
360             return mb_strlen($header['text']) > 0;
361         });
362
363         // Shift headers if only smaller headers have been used
364         $levelChange = ($tree->pluck('level')->min() - 1);
365         $tree = $tree->map(function ($header) use ($levelChange) {
366             $header['level'] -= ($levelChange);
367
368             return $header;
369         });
370
371         return $tree->toArray();
372     }
373
374     /**
375      * Remove any page include tags within the given HTML.
376      */
377     protected function blankPageIncludes(string $html): string
378     {
379         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
380     }
381
382     /**
383      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
384      */
385     protected function parsePageIncludes(string $html): string
386     {
387         $matches = [];
388         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
389
390         foreach ($matches[1] as $index => $includeId) {
391             $fullMatch = $matches[0][$index];
392             $splitInclude = explode('#', $includeId, 2);
393
394             // Get page id from reference
395             $pageId = intval($splitInclude[0]);
396             if (is_nan($pageId)) {
397                 continue;
398             }
399
400             // Find page and skip this if page not found
401             /** @var ?Page $matchedPage */
402             $matchedPage = Page::visible()->find($pageId);
403             if ($matchedPage === null) {
404                 $html = str_replace($fullMatch, '', $html);
405                 continue;
406             }
407
408             // If we only have page id, just insert all page html and continue.
409             if (count($splitInclude) === 1) {
410                 $html = str_replace($fullMatch, $matchedPage->html, $html);
411                 continue;
412             }
413
414             // Create and load HTML into a document
415             $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
416             $html = str_replace($fullMatch, trim($innerContent), $html);
417         }
418
419         return $html;
420     }
421
422     /**
423      * Fetch the content from a specific section of the given page.
424      */
425     protected function fetchSectionOfPage(Page $page, string $sectionId): string
426     {
427         $topLevelTags = ['table', 'ul', 'ol', 'pre'];
428         $doc = $this->loadDocumentFromHtml($page->html);
429
430         // Search included content for the id given and blank out if not exists.
431         $matchingElem = $doc->getElementById($sectionId);
432         if ($matchingElem === null) {
433             return '';
434         }
435
436         // Otherwise replace the content with the found content
437         // Checks if the top-level wrapper should be included by matching on tag types
438         $innerContent = '';
439         $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
440         if ($isTopLevel) {
441             $innerContent .= $doc->saveHTML($matchingElem);
442         } else {
443             foreach ($matchingElem->childNodes as $childNode) {
444                 $innerContent .= $doc->saveHTML($childNode);
445             }
446         }
447         libxml_clear_errors();
448
449         return $innerContent;
450     }
451
452     /**
453      * Create and load a DOMDocument from the given html content.
454      */
455     protected function loadDocumentFromHtml(string $html): DOMDocument
456     {
457         libxml_use_internal_errors(true);
458         $doc = new DOMDocument();
459         $html = '<body>' . $html . '</body>';
460         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
461
462         return $doc;
463     }
464 }