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