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