]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PageContent.php
Merge branch 'master' of https://github.com/awarre/BookStack into awarre-master
[bookstack] / app / Entities / Tools / PageContent.php
1 <?php namespace BookStack\Entities\Tools;
2
3 use BookStack\Auth\Permissions\PermissionService;
4 use BookStack\Entities\Models\Page;
5 use BookStack\Entities\Tools\Markdown\CustomStrikeThroughExtension;
6 use BookStack\Facades\Theme;
7 use BookStack\Theming\ThemeEvents;
8 use BookStack\Util\HtmlContentFilter;
9 use BookStack\Uploads\Image;
10 use BookStack\Uploads\ImageRepo;
11 use BookStack\Uploads\ImageService;
12 use DOMDocument;
13 use DOMNodeList;
14 use DOMXPath;
15 use League\CommonMark\CommonMarkConverter;
16 use League\CommonMark\Environment;
17 use League\CommonMark\Extension\Table\TableExtension;
18 use League\CommonMark\Extension\TaskList\TaskListExtension;
19
20 class PageContent
21 {
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->saveBase64Images($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         return $converter->convertToHtml($markdown);
67     }
68
69     /**
70      * Convert all base64 image data to saved images
71      */
72     public function saveBase64Images(Page $page, string $htmlText): string
73     {
74         if ($htmlText == '') {
75             return $htmlText;
76         }
77
78         libxml_use_internal_errors(true);
79         $doc = new DOMDocument();
80         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
81         $container = $doc->documentElement;
82         $body = $container->childNodes->item(0);
83         $childNodes = $body->childNodes;
84         $xPath = new DOMXPath($doc);
85
86         // Get all img elements with image data blobs
87         $imageNodes = $xPath->query('//img[contains(@src, \'data:image\')]');
88         foreach($imageNodes as $imageNode) {
89             $imageSrc = $imageNode->getAttribute('src');
90
91             # Parse base64 data
92             $result = preg_match('"data:image/[a-zA-Z]*(;base64,[a-zA-Z0-9+/\\= ]*)"', $imageSrc, $matches);
93
94             if($result === 1) {
95                 $base64ImageData = $matches[1];
96
97                 $image = new Image();
98                 $imageService = app()->make(ImageService::class);
99                 $permissionService = app(PermissionService::class);
100                 $imageRepo = new ImageRepo(new Image(), $imageService, $permissionService, $page);
101
102                 # Use existing saveDrawing method used for Drawio diagrams
103                 $image = $imageRepo->saveDrawing($base64ImageData, $page->id);
104                 
105                 // Create a new img element with the saved image URI
106                 $newNode = $doc->createElement('img');
107                 $newNode->setAttribute('src', $image->path);
108
109                 // Replace the old img element
110                 $imageNode->parentNode->replaceChild($newNode, $imageNode);
111             }
112         }
113
114         // Generate inner html as a string
115         $html = '';
116         foreach ($childNodes as $childNode) {
117             $html .= $doc->saveHTML($childNode);
118         }
119
120         return $html;
121     }
122
123     /**
124      * Formats a page's html to be tagged correctly within the system.
125      */
126     protected function formatHtml(string $htmlText): string
127     {
128         if ($htmlText == '') {
129             return $htmlText;
130         }
131
132         libxml_use_internal_errors(true);
133         $doc = new DOMDocument();
134         $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
135
136         $container = $doc->documentElement;
137         $body = $container->childNodes->item(0);
138         $childNodes = $body->childNodes;
139         $xPath = new DOMXPath($doc);
140
141         // Set ids on top-level nodes
142         $idMap = [];
143         foreach ($childNodes as $index => $childNode) {
144             [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
145             if ($newId && $newId !== $oldId) {
146                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
147             }
148         }
149
150         // Ensure no duplicate ids within child items
151         $idElems = $xPath->query('//body//*//*[@id]');
152         foreach ($idElems as $domElem) {
153             [$oldId, $newId] = $this->setUniqueId($domElem, $idMap);
154             if ($newId && $newId !== $oldId) {
155                 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
156             }
157         }
158
159         // Generate inner html as a string
160         $html = '';
161         foreach ($childNodes as $childNode) {
162             $html .= $doc->saveHTML($childNode);
163         }
164
165         return $html;
166     }
167
168     /**
169      * Update the all links to the $old location to instead point to $new.
170      */
171     protected function updateLinks(DOMXPath $xpath, string $old, string $new)
172     {
173         $old = str_replace('"', '', $old);
174         $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
175         foreach ($matchingLinks as $domElem) {
176             $domElem->setAttribute('href', $new);
177         }
178     }
179
180     /**
181      * Set a unique id on the given DOMElement.
182      * A map for existing ID's should be passed in to check for current existence.
183      * Returns a pair of strings in the format [old_id, new_id]
184      */
185     protected function setUniqueId(\DOMNode $element, array &$idMap): array
186     {
187         if (get_class($element) !== 'DOMElement') {
188             return ['', ''];
189         }
190
191         // Stop if there's an existing valid id that has not already been used.
192         $existingId = $element->getAttribute('id');
193         if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
194             $idMap[$existingId] = true;
195             return [$existingId, $existingId];
196         }
197
198         // Create an unique id for the element
199         // Uses the content as a basis to ensure output is the same every time
200         // the same content is passed through.
201         $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
202         $newId = urlencode($contentId);
203         $loopIndex = 0;
204
205         while (isset($idMap[$newId])) {
206             $newId = urlencode($contentId . '-' . $loopIndex);
207             $loopIndex++;
208         }
209
210         $element->setAttribute('id', $newId);
211         $idMap[$newId] = true;
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         return html_entity_decode(strip_tags($html));
222     }
223
224     /**
225      * Render the page for viewing
226      */
227     public function render(bool $blankIncludes = false) : string
228     {
229         $content = $this->page->html;
230
231         if (!config('app.allow_content_scripts')) {
232             $content = HtmlContentFilter::removeScripts($content);
233         }
234
235         if ($blankIncludes) {
236             $content = $this->blankPageIncludes($content);
237         } else {
238             $content = $this->parsePageIncludes($content);
239         }
240
241         return $content;
242     }
243
244     /**
245      * Parse the headers on the page to get a navigation menu
246      */
247     public function getNavigation(string $htmlContent): array
248     {
249         if (empty($htmlContent)) {
250             return [];
251         }
252
253         libxml_use_internal_errors(true);
254         $doc = new DOMDocument();
255         $doc->loadHTML(mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'));
256         $xPath = new DOMXPath($doc);
257         $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
258
259         return $headers ? $this->headerNodesToLevelList($headers) : [];
260     }
261
262     /**
263      * Convert a DOMNodeList into an array of readable header attributes
264      * with levels normalised to the lower header level.
265      */
266     protected function headerNodesToLevelList(DOMNodeList $nodeList): array
267     {
268         $tree = collect($nodeList)->map(function ($header) {
269             $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
270             $text = mb_substr($text, 0, 100);
271
272             return [
273                 'nodeName' => strtolower($header->nodeName),
274                 'level' => intval(str_replace('h', '', $header->nodeName)),
275                 'link' => '#' . $header->getAttribute('id'),
276                 'text' => $text,
277             ];
278         })->filter(function ($header) {
279             return mb_strlen($header['text']) > 0;
280         });
281
282         // Shift headers if only smaller headers have been used
283         $levelChange = ($tree->pluck('level')->min() - 1);
284         $tree = $tree->map(function ($header) use ($levelChange) {
285             $header['level'] -= ($levelChange);
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     /**
341      * Fetch the content from a specific section of the given page.
342      */
343     protected function fetchSectionOfPage(Page $page, string $sectionId): string
344     {
345         $topLevelTags = ['table', 'ul', 'ol'];
346         $doc = new DOMDocument();
347         libxml_use_internal_errors(true);
348         $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
349
350         // Search included content for the id given and blank out if not exists.
351         $matchingElem = $doc->getElementById($sectionId);
352         if ($matchingElem === null) {
353             return '';
354         }
355
356         // Otherwise replace the content with the found content
357         // Checks if the top-level wrapper should be included by matching on tag types
358         $innerContent = '';
359         $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
360         if ($isTopLevel) {
361             $innerContent .= $doc->saveHTML($matchingElem);
362         } else {
363             foreach ($matchingElem->childNodes as $childNode) {
364                 $innerContent .= $doc->saveHTML($childNode);
365             }
366         }
367         libxml_clear_errors();
368
369         return $innerContent;
370     }
371 }