-
- /**
- * Remove any page include tags within the given HTML.
- */
- protected function blankPageIncludes(string $html): string
- {
- return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
- }
-
- /**
- * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
- */
- protected function parsePageIncludes(string $html): string
- {
- $matches = [];
- preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
-
- foreach ($matches[1] as $index => $includeId) {
- $fullMatch = $matches[0][$index];
- $splitInclude = explode('#', $includeId, 2);
-
- // Get page id from reference
- $pageId = intval($splitInclude[0]);
- if (is_nan($pageId)) {
- continue;
- }
-
- // Find page and skip this if page not found
- /** @var ?Page $matchedPage */
- $matchedPage = Page::visible()->find($pageId);
- if ($matchedPage === null) {
- $html = str_replace($fullMatch, '', $html);
- continue;
- }
-
- // If we only have page id, just insert all page html and continue.
- if (count($splitInclude) === 1) {
- $html = str_replace($fullMatch, $matchedPage->html, $html);
- continue;
- }
-
- // Create and load HTML into a document
- $innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
- $html = str_replace($fullMatch, trim($innerContent), $html);
- }
-
- return $html;
- }
-
- /**
- * Fetch the content from a specific section of the given page.
- */
- protected function fetchSectionOfPage(Page $page, string $sectionId): string
- {
- $topLevelTags = ['table', 'ul', 'ol'];
- $doc = $this->loadDocumentFromHtml($page->html);
-
- // Search included content for the id given and blank out if not exists.
- $matchingElem = $doc->getElementById($sectionId);
- if ($matchingElem === null) {
- return '';
- }
-
- // Otherwise replace the content with the found content
- // Checks if the top-level wrapper should be included by matching on tag types
- $innerContent = '';
- $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
- if ($isTopLevel) {
- $innerContent .= $doc->saveHTML($matchingElem);
- } else {
- foreach ($matchingElem->childNodes as $childNode) {
- $innerContent .= $doc->saveHTML($childNode);
- }
- }
- libxml_clear_errors();
-
- return $innerContent;
- }
-
- /**
- * Create and load a DOMDocument from the given html content.
- */
- protected function loadDocumentFromHtml(string $html): DOMDocument
- {
- libxml_use_internal_errors(true);
- $doc = new DOMDocument();
- $html = '<body>' . $html . '</body>';
- $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
-
- return $doc;
- }