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