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