theme = $theme; $this->page = $page; $this->pageData = $page->getBuilderData(); $this->shortcodeParser = phpb_instance(ShortcodeParser::class, [$this]); $this->setLanguage(phpb_current_language()); $this->forPageBuilder = $forPageBuilder; } /** * Set which page language variant to use while rendering. * * @param $language */ public function setLanguage($language) { // if the given language is unknown, default the set language to the first available language $blockKeysAreLanguages = true; $supportedLanguages = array_keys($this->pageData['blocks'] ?? []); // check whether keys are valid languages (renderPageBuilderBlock uses pageData without language data) foreach ($supportedLanguages as $supportedLanguage) { if (strlen($supportedLanguage) > 5) { $blockKeysAreLanguages = false; break; } } if ($blockKeysAreLanguages) { $language = (new PageTranslationService())->resolveLocale($language, $supportedLanguages) ?? $language; } $this->language = $language; $this->pageBlocksData = $this->getStoredPageBlocksData(); $this->shortcodeParser->setLanguage($language); } /** * Return the absolute path to the layout view of this page. * * @return string|null */ public function getPageLayoutPath() { $layout = basename($this->page->getLayout()); $layoutPath = $this->theme->getFolder() . '/layouts/' . $layout . '/view.php'; if ($path = Extensions::getLayout($layout)) { $layoutPath = $path . '/view.php'; } return file_exists($layoutPath) ? $layoutPath : null; } /** * Set whether the currently rendered page can be cached. * * @param bool $canBeCached * @param string|null $cacheLifetime */ public static function setCanBeCached(bool $canBeCached, ?int $cacheLifetime = null) { if (! $canBeCached || ($cacheLifetime && intval($cacheLifetime) <= 0)) { static::$canBeCached = false; } elseif ($cacheLifetime) { static::$cacheLifetime = min(static::$cacheLifetime, intval($cacheLifetime)); } } /** * Return whether the rendered page can be cached. * I.e. no blocks were encountered with content that varies per page load. * * @return bool */ public static function canBeCached(): bool { return static::$canBeCached ?? true; } /** * Return the maximum number of minutes the rendered page should be cached. * * @return int */ public static function getCacheLifetime(): int { if (! static::canBeCached()) { return 0; } return static::$cacheLifetime; } /** * Return an array with for each block of this page the stored html and settings data. * * @return array */ public function getStoredPageBlocksData() { return $this->pageData['blocks'][$this->language] ?? $this->pageData['blocks'] ?? []; } /** * Return the rendered version of the page. * * @return string * @throws Exception */ public function render() { // init variables that should be accessible in the view $renderer = $this; $page = $this->page; if ($this->forPageBuilder) { $body = '
'; } else { $body = $this->renderBody(); } $layoutPath = $this->getPageLayoutPath(); if ($layoutPath) { ob_start(); require $layoutPath; $pageHtml = ob_get_contents(); ob_end_clean(); } else { $pageHtml = $body; } // parse any shortcodes present in the page layout $pageHtml = $this->parseShortcodes($pageHtml); return $pageHtml; } public static function appendPreviewTokenToLinks(string $pageHtml, string $token): string { $baseUrl = parse_url(phpb_full_url('/')); if ($token === '' || ! is_array($baseUrl) || empty($baseUrl['host'])) { return $pageHtml; } $document = new \DOMDocument('1.0', 'UTF-8'); $previousLibxmlErrorSetting = libxml_use_internal_errors(true); $loaded = @$document->loadHTML('' . $pageHtml, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED | LIBXML_NONET); libxml_clear_errors(); libxml_use_internal_errors($previousLibxmlErrorSetting); if (! $loaded) { return $pageHtml; } foreach ($document->childNodes as $child) { if ($child->nodeType === XML_PI_NODE) { $document->removeChild($child); } } $rewriteRelativeLinks = true; $baseElement = $document->getElementsByTagName('base')->item(0); if ($baseElement && $baseElement->hasAttribute('href')) { $documentBase = parse_url($baseElement->getAttribute('href')); $rewriteRelativeLinks = is_array($documentBase) && static::isSameSiteUrl($documentBase, $baseUrl); } $preservedUrls = []; foreach ($document->getElementsByTagName('a') as $link) { if ($link->hasAttribute('href')) { $url = $link->getAttribute('href'); if (str_contains($url, '\\')) { $placeholder = '__phpb_preview_link_' . count($preservedUrls) . '__'; while (str_contains($pageHtml, $placeholder)) { $placeholder .= '_'; } $preservedUrls[$placeholder] = $url; $link->setAttribute('href', $placeholder); } else { $link->setAttribute('href', static::appendPreviewTokenToUrl($url, $token, $baseUrl, $rewriteRelativeLinks)); } } } $renderedHtml = $document->saveHTML() ?: $pageHtml; foreach ($preservedUrls as $placeholder => $url) { $renderedHtml = str_replace($placeholder, htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), $renderedHtml); } return $renderedHtml; } public static function appendPreviewTokenToUrl(string $url, string $token, array $baseUrl, bool $rewriteRelativeLinks): string { if ($url === '' || str_starts_with($url, '#') || preg_match('/^[\x00-\x20]/', $url) || str_contains($url, '\\')) { return $url; } $urlParts = parse_url($url); if ($urlParts === false || isset($urlParts['user']) || isset($urlParts['pass'])) { return $url; } if (isset($urlParts['host']) || isset($urlParts['scheme'])) { if (! static::isSameSiteUrl($urlParts, $baseUrl)) { return $url; } } elseif (! $rewriteRelativeLinks || str_starts_with($url, '//')) { return $url; } $fragmentPosition = strpos($url, '#'); $fragment = $fragmentPosition === false ? '' : substr($url, $fragmentPosition); $urlWithoutFragment = $fragmentPosition === false ? $url : substr($url, 0, $fragmentPosition); $queryPosition = strpos($urlWithoutFragment, '?'); $urlPath = $queryPosition === false ? $urlWithoutFragment : substr($urlWithoutFragment, 0, $queryPosition); $query = $queryPosition === false ? '' : substr($urlWithoutFragment, $queryPosition + 1); $queryParts = $query === '' ? [] : explode('&', $query); $queryParts = array_values(array_filter($queryParts, static function (string $part): bool { return urldecode(explode('=', $part, 2)[0]) !== 'previewToken'; })); $queryParts[] = 'previewToken=' . rawurlencode($token); return $urlPath . '?' . implode('&', $queryParts) . $fragment; } private static function isSameSiteUrl(array $urlParts, array $baseUrl): bool { $scheme = strtolower($urlParts['scheme'] ?? ''); $baseScheme = strtolower($baseUrl['scheme'] ?? ''); if (isset($urlParts['user']) || isset($urlParts['pass']) || ($scheme !== '' && ($scheme !== $baseScheme || ! isset($urlParts['host'])))) { return false; } if (! isset($urlParts['host'])) { return $scheme === ''; } return strtolower($urlParts['host']) === strtolower($baseUrl['host']) && static::getUrlPort($urlParts, $scheme ?: $baseScheme) === static::getUrlPort($baseUrl, $baseScheme); } private static function getUrlPort(array $urlParts, string $scheme): int { return $urlParts['port'] ?? ($scheme === 'https' ? 443 : 80); } /** * Return the page body for display on the website. * The body contains all blocks which are put into the selected layout. * * @param int $mainContainerIndex * @return string * @throws Exception */ public function renderBody($mainContainerIndex = 0) { $html = ''; $data = $this->pageData; if (isset($data['html']) && is_array($data['html'])) { $html = $this->parseShortcodes($data['html'][$mainContainerIndex]); // render html for each content container, to ensure all rendered blocks are accessible in the pagebuilder if (phpb_in_editmode()) { foreach ($data['html'] as $contentContainerHtml) { $this->parseShortcodes($contentContainerHtml); } } } // backwards compatibility, html stored for only one layout container (@todo: remove this at the first mayor version) if (isset($data['html']) && is_string($data['html'])) { $html = $this->parseShortcodes($data['html']); } // include any style changes made via the page builder if (isset($data['css'])) { $html .= ''; } return $html; } /** * Return a fully rendered theme block (including children blocks) with the given slug, data instance id and data context. * This method is called while parsing shortcodes. * * @param $slug * @param null $id the id with which data for this block is stored * @param null $context * @param int $maxDepth * @return string * @throws Exception */ public function renderBlock($slug, $id = null, $context = null, $maxDepth = 25) { $themeBlock = ($blockPath = Extensions::getBlock($slug)) ? new ThemeBlock($this->theme, $blockPath, true, $slug) : new ThemeBlock($this->theme, $slug); $id = $id ?? $themeBlock->getSlug(); $context = $context[$id] ?? $this->pageBlocksData[$id] ?? []; $blockRenderer = new BlockRenderer($this->theme, $this->page, $this->forPageBuilder); $renderedBlock = $blockRenderer->render($themeBlock, $context ?? [], $id); // determine the context for rendering nested blocks // if the current block is a html block, the context starts again at full page data // if the current block is a dynamic block, use the nested block data inside the current block's context $context = $context['blocks'] ?? []; if ($themeBlock->isHtmlBlock()) { $context = $this->pageBlocksData; } return $this->shortcodeParser->doShortcodes($renderedBlock, $context, $maxDepth - 1); } /** * Parse the given html with shortcodes to fully rendered html. * * @param string $htmlWithShortcodes * @param array $context the data for each block to be used while parsing the shortcodes * @return string * @throws Exception */ public function parseShortcodes(string $htmlWithShortcodes, ?array $context = null) { $context = $context ?? $this->pageBlocksData; return $this->shortcodeParser->doShortcodes($htmlWithShortcodes, $context); } /** * Return this page's blocks data to be loaded into the page edited inside GrapesJS. * * @return array * @throws Exception */ public function getPageBlocksData() { $initialLanguage = $this->language; // remove the already rendered blocks $this->shortcodeParser->resetRenderedBlocks(); // create the structure of page blocks data for each language $pageBlocks = []; foreach (phpb_active_languages() as $languageCode => $languageTranslation) { $this->setLanguage($languageCode); // for the current language build up a structure of rendered versions and use the stored data for the other languages if ($languageCode === $initialLanguage) { $this->renderBody(); $pageBlocks[$languageCode] = $this->shortcodeParser->getRenderedBlocks()[$languageCode] ?? []; } else { $pageBlocks[$languageCode] = $this->pageBlocksData; } if (empty($pageBlocks[$languageCode])) { $pageBlocks[$languageCode] = null; } } // revert to initial language $this->setLanguage($initialLanguage); // return the rendered html and settings for each block return $pageBlocks; } }