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