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