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