3 namespace BookStack\Entities\Tools;
5 use BookStack\Util\HtmlDocument;
12 class PageIncludeParser
14 protected static string $includeTagRegex = "/{{@\s?([0-9].*?)}}/";
17 * Elements to clean up and remove if left empty after a parsing operation.
20 protected array $toCleanup = [];
22 public function __construct(
23 protected HtmlDocument $doc,
24 protected Closure $pageContentForId,
29 * Parse out the include tags.
30 * Returns the count of new content DOM nodes added to the document.
32 public function parse(): int
35 $tags = $this->locateAndIsolateIncludeTags();
37 foreach ($tags as $tag) {
38 $htmlContent = $this->pageContentForId->call($this, $tag->getPageId());
39 $content = new PageIncludeContent($htmlContent, $tag);
41 if (!$content->isInline()) {
42 $parentP = $this->getParentParagraph($tag->domNode);
43 $isWithinParentP = $parentP === $tag->domNode->parentNode;
44 if ($parentP && $isWithinParentP) {
45 $this->splitNodeAtChildNode($tag->domNode->parentNode, $tag->domNode);
46 } else if ($parentP) {
47 $this->moveTagNodeToBesideParent($tag, $parentP);
51 $replacementNodes = $content->toDomNodes();
52 $nodesAdded += count($replacementNodes);
53 $this->replaceNodeWithNodes($tag->domNode, $replacementNodes);
62 * Locate include tags within the given document, isolating them to their
63 * own nodes in the DOM for future targeted manipulation.
64 * @return PageIncludeTag[]
66 protected function locateAndIsolateIncludeTags(): array
68 $includeHosts = $this->doc->queryXPath("//*[text()[contains(., '{{@')]]");
71 /** @var DOMNode $node */
72 /** @var DOMNode $childNode */
73 foreach ($includeHosts as $node) {
74 foreach ($node->childNodes as $childNode) {
75 if ($childNode->nodeName === '#text') {
76 array_push($includeTags, ...$this->splitTextNodesAtTags($childNode));
85 * Takes a text DOMNode and splits its text content at include tags
86 * into multiple text nodes within the original parent.
87 * Returns found PageIncludeTag references.
88 * @return PageIncludeTag[]
90 protected function splitTextNodesAtTags(DOMNode $textNode): array
93 $text = $textNode->textContent;
94 preg_match_all(static::$includeTagRegex, $text, $matches, PREG_OFFSET_CAPTURE);
97 foreach ($matches[0] as $index => $fullTagMatch) {
98 $tagOuterContent = $fullTagMatch[0];
99 $tagInnerContent = $matches[1][$index][0];
100 $tagStartOffset = $fullTagMatch[1];
102 if ($currentOffset < $tagStartOffset) {
103 $previousText = substr($text, $currentOffset, $tagStartOffset - $currentOffset);
104 $textNode->parentNode->insertBefore(new DOMText($previousText), $textNode);
107 $node = $textNode->parentNode->insertBefore(new DOMText($tagOuterContent), $textNode);
108 $includeTags[] = new PageIncludeTag($tagInnerContent, $node);
109 $currentOffset = $tagStartOffset + strlen($tagOuterContent);
112 if ($currentOffset > 0) {
113 $textNode->textContent = substr($text, $currentOffset);
120 * Replace the given node with all those in $replacements
121 * @param DOMNode[] $replacements
123 protected function replaceNodeWithNodes(DOMNode $toReplace, array $replacements): void
125 /** @var DOMDocument $targetDoc */
126 $targetDoc = $toReplace->ownerDocument;
128 foreach ($replacements as $replacement) {
129 if ($replacement->ownerDocument !== $targetDoc) {
130 $replacement = $targetDoc->importNode($replacement, true);
133 $toReplace->parentNode->insertBefore($replacement, $toReplace);
136 $toReplace->parentNode->removeChild($toReplace);
140 * Move a tag node to become a sibling of the given parent.
141 * Will attempt to guess a position based upon the tag content within the parent.
143 protected function moveTagNodeToBesideParent(PageIncludeTag $tag, DOMNode $parent): void
145 $parentText = $parent->textContent;
146 $tagPos = strpos($parentText, $tag->tagContent);
147 $before = $tagPos < (strlen($parentText) / 2);
148 $this->toCleanup[] = $tag->domNode->parentNode;
151 $parent->parentNode->insertBefore($tag->domNode, $parent);
153 $parent->parentNode->insertBefore($tag->domNode, $parent->nextSibling);
158 * Splits the given $parentNode at the location of the $domNode within it.
159 * Attempts replicate the original $parentNode, moving some of their parent
160 * children in where needed, before adding the $domNode between.
162 protected function splitNodeAtChildNode(DOMElement $parentNode, DOMNode $domNode): void
164 $children = [...$parentNode->childNodes];
165 $splitPos = array_search($domNode, $children, true);
166 if ($splitPos === false) {
167 $splitPos = count($children) - 1;
170 $parentClone = $parentNode->cloneNode();
171 $parentNode->parentNode->insertBefore($parentClone, $parentNode);
172 $parentClone->removeAttribute('id');
174 /** @var DOMNode $child */
175 for ($i = 0; $i < $splitPos; $i++) {
176 $child = $children[$i];
177 $parentClone->appendChild($child);
180 $parentNode->parentNode->insertBefore($domNode, $parentNode);
182 $this->toCleanup[] = $parentNode;
183 $this->toCleanup[] = $parentClone;
187 * Get the parent paragraph of the given node, if existing.
189 protected function getParentParagraph(DOMNode $parent): ?DOMNode
192 if (strtolower($parent->nodeName) === 'p') {
196 $parent = $parent->parentNode;
197 } while ($parent !== null);
203 * Cleanup after a parse operation.
204 * Removes stranded elements we may have left during the parse.
206 protected function cleanup(): void
208 foreach ($this->toCleanup as $element) {
209 $element->normalize();
210 while ($element->parentNode && !$element->hasChildNodes()) {
211 $parent = $element->parentNode;
212 $parent->removeChild($element);