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