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