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