1 <?php namespace BookStack\Entities\Tools;
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;
15 use League\CommonMark\CommonMarkConverter;
16 use League\CommonMark\Environment;
17 use League\CommonMark\Extension\Table\TableExtension;
18 use League\CommonMark\Extension\TaskList\TaskListExtension;
26 * PageContent constructor.
28 public function __construct(Page $page)
34 * Update the content of the page with new provided HTML.
36 public function setNewHTML(string $html)
38 $html = $this->saveBase64Images($this->page, $html);
39 $this->page->html = $this->formatHtml($html);
40 $this->page->text = $this->toPlainText();
41 $this->page->markdown = '';
45 * Update the content of the page with new provided Markdown content.
47 public function setNewMarkdown(string $markdown)
49 $this->page->markdown = $markdown;
50 $html = $this->markdownToHtml($markdown);
51 $this->page->html = $this->formatHtml($html);
52 $this->page->text = $this->toPlainText();
56 * Convert the given Markdown content to a HTML string.
58 protected function markdownToHtml(string $markdown): string
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);
70 * Convert all base64 image data to saved images
72 public function saveBase64Images(Page $page, string $htmlText): string
74 if ($htmlText == '') {
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);
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');
92 $result = preg_match('"data:image/[a-zA-Z]*(;base64,[a-zA-Z0-9+/\\= ]*)"', $imageSrc, $matches);
95 $base64ImageData = $matches[1];
98 $imageService = app()->make(ImageService::class);
99 $permissionService = app(PermissionService::class);
100 $imageRepo = new ImageRepo(new Image(), $imageService, $permissionService, $page);
102 # Use existing saveDrawing method used for Drawio diagrams
103 $image = $imageRepo->saveDrawing($base64ImageData, $page->id);
105 // Create a new img element with the saved image URI
106 $newNode = $doc->createElement('img');
107 $newNode->setAttribute('src', $image->path);
109 // Replace the old img element
110 $imageNode->parentNode->replaceChild($newNode, $imageNode);
114 // Generate inner html as a string
116 foreach ($childNodes as $childNode) {
117 $html .= $doc->saveHTML($childNode);
124 * Formats a page's html to be tagged correctly within the system.
126 protected function formatHtml(string $htmlText): string
128 if ($htmlText == '') {
132 libxml_use_internal_errors(true);
133 $doc = new DOMDocument();
134 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
136 $container = $doc->documentElement;
137 $body = $container->childNodes->item(0);
138 $childNodes = $body->childNodes;
139 $xPath = new DOMXPath($doc);
141 // Set ids on top-level nodes
143 foreach ($childNodes as $index => $childNode) {
144 [$oldId, $newId] = $this->setUniqueId($childNode, $idMap);
145 if ($newId && $newId !== $oldId) {
146 $this->updateLinks($xPath, '#' . $oldId, '#' . $newId);
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);
159 // Generate inner html as a string
161 foreach ($childNodes as $childNode) {
162 $html .= $doc->saveHTML($childNode);
169 * Update the all links to the $old location to instead point to $new.
171 protected function updateLinks(DOMXPath $xpath, string $old, string $new)
173 $old = str_replace('"', '', $old);
174 $matchingLinks = $xpath->query('//body//*//*[@href="'.$old.'"]');
175 foreach ($matchingLinks as $domElem) {
176 $domElem->setAttribute('href', $new);
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]
185 protected function setUniqueId(\DOMNode $element, array &$idMap): array
187 if (get_class($element) !== 'DOMElement') {
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];
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);
205 while (isset($idMap[$newId])) {
206 $newId = urlencode($contentId . '-' . $loopIndex);
210 $element->setAttribute('id', $newId);
211 $idMap[$newId] = true;
212 return [$existingId, $newId];
216 * Get a plain-text visualisation of this page.
218 protected function toPlainText(): string
220 $html = $this->render(true);
221 return html_entity_decode(strip_tags($html));
225 * Render the page for viewing
227 public function render(bool $blankIncludes = false) : string
229 $content = $this->page->html;
231 if (!config('app.allow_content_scripts')) {
232 $content = HtmlContentFilter::removeScripts($content);
235 if ($blankIncludes) {
236 $content = $this->blankPageIncludes($content);
238 $content = $this->parsePageIncludes($content);
245 * Parse the headers on the page to get a navigation menu
247 public function getNavigation(string $htmlContent): array
249 if (empty($htmlContent)) {
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");
259 return $headers ? $this->headerNodesToLevelList($headers) : [];
263 * Convert a DOMNodeList into an array of readable header attributes
264 * with levels normalised to the lower header level.
266 protected function headerNodesToLevelList(DOMNodeList $nodeList): array
268 $tree = collect($nodeList)->map(function ($header) {
269 $text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
270 $text = mb_substr($text, 0, 100);
273 'nodeName' => strtolower($header->nodeName),
274 'level' => intval(str_replace('h', '', $header->nodeName)),
275 'link' => '#' . $header->getAttribute('id'),
278 })->filter(function ($header) {
279 return mb_strlen($header['text']) > 0;
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);
289 return $tree->toArray();
293 * Remove any page include tags within the given HTML.
295 protected function blankPageIncludes(string $html) : string
297 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
301 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
303 protected function parsePageIncludes(string $html) : string
306 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
308 foreach ($matches[1] as $index => $includeId) {
309 $fullMatch = $matches[0][$index];
310 $splitInclude = explode('#', $includeId, 2);
312 // Get page id from reference
313 $pageId = intval($splitInclude[0]);
314 if (is_nan($pageId)) {
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);
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);
331 // Create and load HTML into a document
332 $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
333 $html = str_replace($fullMatch, trim($innerContent), $html);
341 * Fetch the content from a specific section of the given page.
343 protected function fetchSectionOfPage(Page $page, string $sectionId): string
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'));
350 // Search included content for the id given and blank out if not exists.
351 $matchingElem = $doc->getElementById($sectionId);
352 if ($matchingElem === null) {
356 // Otherwise replace the content with the found content
357 // Checks if the top-level wrapper should be included by matching on tag types
359 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
361 $innerContent .= $doc->saveHTML($matchingElem);
363 foreach ($matchingElem->childNodes as $childNode) {
364 $innerContent .= $doc->saveHTML($childNode);
367 libxml_clear_errors();
369 return $innerContent;