]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
Started work on details/summary blocks
[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      */
113     protected function extractBase64ImagesFromMarkdown(string $markdown)
114     {
115         $matches = [];
116         preg_match_all('/!\[.*?]\(.*?(data:image\/.*?)[)"\s]/', $markdown, $matches);
117
118         foreach ($matches[1] as $base64Match) {
119             $newUrl = $this->base64ImageUriToUploadedImageUrl($base64Match);
120             $markdown = str_replace($base64Match, $newUrl, $markdown);
121         }
122
123         return $markdown;
124     }
125
126     /**
127      * Parse the given base64 image URI and return the URL to the created image instance.
128      * Returns an empty string if the parsed URI is invalid or causes an error upon upload.
129      */
130     protected function base64ImageUriToUploadedImageUrl(string $uri): string
131     {
132         $imageRepo = app()->make(ImageRepo::class);
133         $imageInfo = $this->parseBase64ImageUri($uri);
134
135         // Validate extension and content
136         if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) {
137             return '';
138         }
139
140         // Validate that the content is not over our upload limit
141         $uploadLimitBytes = (config('app.upload_limit') * 1000000);
142         if (strlen($imageInfo['data']) > $uploadLimitBytes) {
143             return '';
144         }
145
146         // Save image from data with a random name
147         $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension'];
148
149         try {
150             $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id);
151         } catch (ImageUploadException $exception) {
152             return '';
153         }
154
155         return $image->url;
156     }
157
158     /**
159      * Parse a base64 image URI into the data and extension.
160      *
161      * @return array{extension: string, data: string}
162      */
163     protected function parseBase64ImageUri(string $uri): array
164     {
165         [$dataDefinition, $base64ImageData] = explode(',', $uri, 2);
166         $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? '');
167
168         return [
169             'extension' => $extension,
170             'data'      => base64_decode($base64ImageData) ?: '',
171         ];
172     }
173
174     /**
175      * Formats a page's html to be tagged correctly within the system.
176      */
177     protected function formatHtml(string $htmlText): string
178     {
179         if (empty($htmlText)) {
180             return $htmlText;
181         }
182
183         $doc = $this->loadDocumentFromHtml($htmlText);
184         $container = $doc->documentElement;
185         $body = $container->childNodes->item(0);
186         $childNodes = $body->childNodes;
187         $xPath = new DOMXPath($doc);
188
189         // Set ids on top-level nodes
190         $idMap = [];
191         foreach ($childNodes as $index => $childNode) {
192             [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
193             if ($newId && $newId !== $oldId) {
194                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
195             }
196         }
197
198         // Set ids on nested header nodes
199         $nestedHeaders = $xPath->query('//body//*//h1|//body//*//h2|//body//*//h3|//body//*//h4|//body//*//h5|//body//*//h6');
200         foreach ($nestedHeaders as $nestedHeader) {
201             [$oldId, $newId] = $this->setUniqueId($nestedHeader, $idMap);
202             if ($newId && $newId !== $oldId) {
203                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
204             }
205         }
206
207         // Ensure no duplicate ids within child items
208         $idElems = $xPath->query('//body//*//*[@id]');
209         foreach ($idElems as $domElem) {
210             [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
211             if ($newId && $newId !== $oldId) {
212                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
213             }
214         }
215
216         // Generate inner html as a string
217         $html = '';
218         foreach ($childNodes as $childNode) {
219             $html .= $doc->saveHTML($childNode);
220         }
221
222         return $html;
223     }
224
225     /**
226      * Update the all links to the $old location to instead point to $new.
227      */
228     protected function updateLinks(DOMXPath $xpath, string $old, string $new)
229     {
230         $old = str_replace('"', '', $old);
231         $matchingLinks = $xpath->query('//body//*//*[@href="' . $old . '"]');
232         foreach ($matchingLinks as $domElem) {
233             $domElem->setAttribute('href', $new);
234         }
235     }
236
237     /**
238      * Set a unique id on the given DOMElement.
239      * A map for existing ID's should be passed in to check for current existence.
240      * Returns a pair of strings in the format [old_id, new_id].
241      */
242     protected function setUniqueId(DOMNode $element, array &$idMap): array
243     {
244         if (!$element instanceof DOMElement) {
245             return ['', ''];
246         }
247
248         // Stop if there's an existing valid id that has not already been used.
249         $existingId = $element->getAttribute('id');
250         if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
251             $idMap[$existingId] = true;
252
253             return [$existingId, $existingId];
254         }
255
256         // Create a unique id for the element
257         // Uses the content as a basis to ensure output is the same every time
258         // the same content is passed through.
259         $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
260         $newId = urlencode($contentId);
261         $loopIndex = 0;
262
263         while (isset($idMap[$newId])) {
264             $newId = urlencode($contentId . '-' . $loopIndex);
265             $loopIndex++;
266         }
267
268         $element->setAttribute('id', $newId);
269         $idMap[$newId] = true;
270
271         return [$existingId, $newId];
272     }
273
274     /**
275      * Get a plain-text visualisation of this page.
276      */
277     protected function toPlainText(): string
278     {
279         $html = $this->render(true);
280
281         return html_entity_decode(strip_tags($html));
282     }
283
284     /**
285      * Render the page for viewing.
286      */
287     public function render(bool $blankIncludes = false): string
288     {
289         $content = $this->page->html ?? '';
290
291         if (!config('app.allow_content_scripts')) {
292             $content = HtmlContentFilter::removeScripts($content);
293         }
294
295         if ($blankIncludes) {
296             $content = $this->blankPageIncludes($content);
297         } else {
298             $content = $this->parsePageIncludes($content);
299         }
300
301         return $content;
302     }
303
304     /**
305      * Parse the headers on the page to get a navigation menu.
306      */
307     public function getNavigation(string $htmlContent): array
308     {
309         if (empty($htmlContent)) {
310             return [];
311         }
312
313         $doc = $this->loadDocumentFromHtml($htmlContent);
314         $xPath = new DOMXPath($doc);
315         $headers = $xPath->query('//h1|//h2|//h3|//h4|//h5|//h6');
316
317         return $headers ? $this->headerNodesToLevelList($headers) : [];
318     }
319
320     /**
321      * Convert a DOMNodeList into an array of readable header attributes
322      * with levels normalised to the lower header level.
323      */
324     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
325     {
326         $tree = collect($nodeList)->map(function (DOMElement $header) {
327             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
328             $text = mb_substr($text, 0, 100);
329
330             return [
331                 'nodeName' => strtolower($header->nodeName),
332                 'level'    => intval(str_replace('h', '', $header->nodeName)),
333                 'link'     => '#' . $header->getAttribute('id'),
334                 'text'     => $text,
335             ];
336         })->filter(function ($header) {
337             return mb_strlen($header['text']) > 0;
338         });
339
340         // Shift headers if only smaller headers have been used
341         $levelChange = ($tree->pluck('level')->min() - 1);
342         $tree = $tree->map(function ($header) use ($levelChange) {
343             $header['level'] -= ($levelChange);
344
345             return $header;
346         });
347
348         return $tree->toArray();
349     }
350
351     /**
352      * Remove any page include tags within the given HTML.
353      */
354     protected function blankPageIncludes(string $html): string
355     {
356         return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
357     }
358
359     /**
360      * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
361      */
362     protected function parsePageIncludes(string $html): string
363     {
364         $matches = [];
365         preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
366
367         foreach ($matches[1] as $index => $includeId) {
368             $fullMatch = $matches[0][$index];
369             $splitInclude = explode('#', $includeId, 2);
370
371             // Get page id from reference
372             $pageId = intval($splitInclude[0]);
373             if (is_nan($pageId)) {
374                 continue;
375             }
376
377             // Find page and skip this if page not found
378             /** @var ?Page $matchedPage */
379             $matchedPage = Page::visible()->find($pageId);
380             if ($matchedPage === null) {
381                 $html = str_replace($fullMatch, '', $html);
382                 continue;
383             }
384
385             // If we only have page id, just insert all page html and continue.
386             if (count($splitInclude) === 1) {
387                 $html = str_replace($fullMatch, $matchedPage->html, $html);
388                 continue;
389             }
390
391             // Create and load HTML into a document
392             $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
393             $html = str_replace($fullMatch, trim($innerContent), $html);
394         }
395
396         return $html;
397     }
398
399     /**
400      * Fetch the content from a specific section of the given page.
401      */
402     protected function fetchSectionOfPage(Page $page, string $sectionId): string
403     {
404         $topLevelTags = ['table', 'ul', 'ol', 'pre'];
405         $doc = $this->loadDocumentFromHtml($page->html);
406
407         // Search included content for the id given and blank out if not exists.
408         $matchingElem = $doc->getElementById($sectionId);
409         if ($matchingElem === null) {
410             return '';
411         }
412
413         // Otherwise replace the content with the found content
414         // Checks if the top-level wrapper should be included by matching on tag types
415         $innerContent = '';
416         $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
417         if ($isTopLevel) {
418             $innerContent .= $doc->saveHTML($matchingElem);
419         } else {
420             foreach ($matchingElem->childNodes as $childNode) {
421                 $innerContent .= $doc->saveHTML($childNode);
422             }
423         }
424         libxml_clear_errors();
425
426         return $innerContent;
427     }
428
429     /**
430      * Create and load a DOMDocument from the given html content.
431      */
432     protected function loadDocumentFromHtml(string $html): DOMDocument
433     {
434         libxml_use_internal_errors(true);
435         $doc = new DOMDocument();
436         $html = '<body>' . $html . '</body>';
437         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
438
439         return $doc;
440     }
441 }