Replace the tokens injected in the generation of the HTML by the correct values.
@param string $HTML The HTML containing tokens to be replaced
@return string The HTML with the tokens replaced, and optionally with corrected HTML
using PHP's Tidy extension.
160860
public function replaceTokens(string $HTML)
    {
        $scripts = $this->resolveAssets($this->scripts, "js");
        $CSS = $this->resolveAssets($this->CSS, "css");

        // Initialize all output variables to null
        $values = new TypedDictionary(
            [
                'css_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]),
                'js_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]),
                'js_inline_document' => new Validator(Type::OBJECT, ['class' => DOMDocument::class]),
                'css_files' => Type::ARRAY,
                'js_files' => Type::ARRAY,
                'js_inline_variables' => Type::ARRAY
            ],
            [
                'js_files' => $scripts,
                'css_files' => $CSS,
                'js_inline_variables' => $this->inline_variables
            ]
        );

        // Allow hooks to modify the scripts and CSS before modifying them
        Hook::execute('Wedeto.HTML.AssetManager.replaceTokens.preRender', $values);

        // Do rendering
        $js = $values->getArray('js_files');
        if (!empty($js) && !$values->has('js_document'))
        {
            $js_doc = new DOMDocument;
            foreach ($js as $script)
            {
                $element = $js_doc->createElement('script');
                $element->setAttribute('src', $script['url']);
                $js_doc->appendChild($element);
            }
            $values['js_document'] = $js_doc;
        }
        
        $jsv = $values->getArray('js_inline_variables');
        if (!empty($jsv) && !$values->has('js_inline_document'))
        {
            $js_inline_doc = new DOMDocument;
            $code_lines = ['window.wdt = {};'];
            foreach ($jsv as $name => $value)
                $code_lines[] = "window.wdt.$name = " . json_encode($value) . ";";
            $variable_el = $js_inline_doc->createElement('script', implode("\n", $code_lines));
            $js_inline_doc->appendChild($variable_el);
            $values['js_inline_document'] = $js_inline_doc;
        }

        $CSS = $values->getArray('css_files');
        if (!empty($CSS) && !$values->has('css_document'))
        {
            $CSS_doc = new DOMDocument;
            foreach ($CSS as $stylesheet)
            {
                $element = $CSS_doc->createElement('link');
                $element->setAttribute('rel', 'stylesheet');
                $element->setAttribute('href', $stylesheet['url']);
                $element->setAttribute('type', 'text/css');
                $CSS_doc->appendChild($element);
            }
            $values['css_document'] = $CSS_doc;
        }

        // Allow hooks to modify the output
        Hook::execute('Wedeto.HTML.AssetManager.replaceTokens.postRender', $values);

        $script_HTML = $values->has('js_document') ? trim($values['js_document']->saveHTML()) : '';
        $CSS_HTML = $values->has('css_document') ? trim($values['css_document']->saveHTML()) : '';
        $inline_script_HTML = $values->has('js_inline_document') ? trim($values['js_inline_document']->saveHTML()) : '';

        $count = 0;
        $HTML = str_replace($this->injectScript(), $script_HTML . $inline_script_HTML, $HTML, $count);
        if ($count === 0 && !empty($script_HTML))
        {
            self::$logger->warning("No Javascript marker found while there are scripts to insert");
            self::$logger->debug("To-be inserted scripts: {0}", $js);
        }

        $count = 0;
        $HTML = str_replace($this->injectCSS(), $CSS_HTML, $HTML, $count);
        if ($count === 0 && !empty($CSS_HTML))
        {
            self::$logger->warning("No CSS marker found while there are stylesheets to insert");
            self::$logger->debug("To-be inserted stylesheets: {0}", [$CSS]);
        }

        // Tidy up HTML when configured and available
        if ($this->tidy)
        {
            if (class_exists("Tidy", false))
            {
                $tidy = new \Tidy();
                $config = array('indent' => true, 'indent-spaces' => 4, 'wrap' => 120, 'markup' => true, 'doctype' => 'omit');
                $HTML = "<!DOCTYPE html>\n" . $tidy->repairString($HTML, $config, "utf8");
            }
            else
            {
                // @codeCoverageIgnoreStart
                self::$logger->warning("Tidy output has been requested, but Tidy extension is not available");
                // @codeCoverageIgnoreEnd
            }
        }
        return $HTML;
    }
375578
protected function _convertUrls($html) {
		$fullBaseUrl = Configure::read('App.fullBaseUrl');
		if (!empty($fullBaseUrl)) {
			$html = preg_replace('~(?:src|action|href)=[\'"]\K/(?!/)[^\'"]*~', "$fullBaseUrl$0", $html);
		}

		return $html;
	}
208399
public function replaceExternalCss($html, array $stylesheets)
    {
        foreach ($stylesheets['links'] as $key => $stylesheet) {
            if (!$this->isExternalStylesheet($stylesheet)) {
                $html = str_replace(
                    $stylesheets['tags'][$key],
                    $this->getStylesheetContent($stylesheet),
                    $html
                );
            }
        }

        return $html;
    }
785433
protected function restoreGlobalExclusions($html)
    {
        $html = (string) $html;

        if (!$this->current_global_exclusion_tokens) {
            return $html; // Nothing to restore.
        }
        if (mb_strpos($html, '<htmlc-gxt-') === false) {
            return $html; // Nothing to restore.
        }
        foreach (array_reverse($this->current_global_exclusion_tokens, true) as $_token => $_value) {
            // Must go in reverse order so nested tokens unfold properly.
            $html = str_replace('<htmlc-gxt-'.$_token.' />', $_value, $html);
        } // unset($_token, $_value); // Housekeeping.

        $this->current_global_exclusion_tokens = [];

        return $html;
    }
621980
public function parse(string $html) : TokenCollection
    {
        self::$allHtml = $html;
        $tokens = new TokenCollection();
        $remainingHtml = trim($html);
        while (mb_strlen($remainingHtml) > 0) {
            $token = TokenFactory::buildFromHtml(
                $remainingHtml,
                null,
                $this->throwOnError
            );
            if (!$token instanceof Token) {
                // Error has occurred, so we stop.
                break;
            }

            $remainingHtml = $token->parse($remainingHtml);
            $tokens[] = $token;
        }

        return $tokens;
    }
1049997
public function setHtml($html)
    {
        if (!\is_string($html)) {
            throw new \InvalidArgumentException('The provided HTML must be a string.', 1540403913);
        }
        if ($html === '') {
            throw new \InvalidArgumentException('The provided HTML must not be empty.', 1540403910);
        }

        $this->createUnifiedDomDocument($html);
    }
935695
public function replaceTokens($string)
    {
        foreach ($this->getTokenNames($string) as $token) {
            $string = str_replace("{{$token}}", $this->getTokenValue($token), $string);
        }
        
        return $string;
    }
223464
public function html($newInnerHTML = null)
    {
        if (isset($newInnerHTML)) {
            $this->replace($newInnerHTML);
        }

        return $this->innerHTML;
    }
1283336
protected function tokenizeGlobalExclusions($html)
    {
        $html              = (string) $html;
        $_this             = $this;
        $global_exclusions = [
            '/\<noscript(?:\s[^>]*)?\>.*?\<\/noscript\>/uis',
        ];
        $html = preg_replace_callback(
            $global_exclusions,
            function ($m) use ($_this) {
                $_this->current_global_exclusion_tokens[] = $m[0]; // Tokenize.
                return '<htmlc-gxt-'.(count($_this->current_global_exclusion_tokens) - 1).' />';
            },
            $html // Exclusions replaced by tokens.
        );
        return $html;
    }
1051858
public function processHtml($html)
    {
        if (!is_string($html)) {
            return $html;
        }

        $mediaTags = $this->extractMediaTags($html);
        foreach ($mediaTags as $tagInfo) {
            $pattern = preg_quote($tagInfo['declaration']);
            $generatedMarkup = $this->generateMediaTagMarkup($tagInfo['type'], $tagInfo['src']);
            $html = mb_ereg_replace($pattern, $generatedMarkup, $html);
        }

        return $html;
    }
590952
public function loadHTML($html)
    {
        if ($html instanceof Renderable) {
            $html = $html->render();
        }
        $this->html = $html;
        $this->file = null;
        return $this;
    }
1297648
public function setHtml(string $html): Response
    {
        if ($this->response_finished) {
            return $this;

        }

        $this->response_html = $html;

        return $this;
    }
730593
protected function restore($html)
    {
        foreach ($this->data as $index => $item)
        {
            $key = (string) '$' . $index . '$';

            $html = str_replace($key, $item, $html);
        }

        return (string) $html;
    }
319269
public function fixNonvoidTags($html) {
        return preg_replace_callback('~(<([\w]+)[^>]*?)(\s*/>)~u', function ($matches) {
            // something went wrong
            if(empty($matches[2])) {
                // do nothing
                return $matches[0];
            }
            // regular void elements
            if(in_array($matches[2], array('area','base','br','col','embed','hr','img','input','keygen','link','meta','param','source','track','wbr'))) {
                // do nothing
                return $matches[0];
            }
            // correctly closed element
            return trim(mb_substr($matches[0], 0, -2), 'UTF-8') . '></' . $matches[2] . '>';
        }, $html);
    }
651442
public function replaceInteractiveTags( $html ) {

		$tags = [
			'audio',
			'video',
		];

		// Check for HTML tags, bail if there isn't any
		$found = false;
		foreach ( $tags as $tag ) {
			if ( stripos( $html, "<{$tag}" ) !== false ) {
				$found = true;
				break;
			}
		}
		if ( ! $found ) {
			return $html;
		}

		global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...]

		$html5 = new HtmlParser();
		$dom = $html5->loadHTML( $html );
		foreach ( $tags as $tag ) {
			// Load blade template based on $tag
			$html = $this->blade->render(
				"interactive.{$tag}", [
					'title' => $this->getTitle( $id ),
					'url' => wp_get_shortlink( $id ),
				]
			);
			$fragment = $html5->parser->loadHTMLFragment( $html );

			// Replace
			$elements = $dom->getElementsByTagName( $tag );
			for ( $i = $elements->length; --$i >= 0; ) {  // If you're deleting elements from within a loop, you need to loop backwards
				$iframe = $elements->item( $i );
				$iframe->parentNode->replaceChild( $dom->importNode( $fragment, true ), $iframe );
			}
		}

		$s = $html5->saveHTML( $dom );
		return $s;
	}
1125405
public function injectForms($html)
    {
        preg_match_all("/<form(.*?)>(.*?)<\\/form>/is", $html, $matches, PREG_SET_ORDER);
        if (is_array($matches)) {
            foreach ($matches as $match) {
                if (strpos($match[1], "nocsrf") !== false) {
                    continue;
                }
                $hiddenFields = self::generateHiddenFields();
                $html = str_replace($match[0], "<form{$match[1]}>{$hiddenFields}{$match[2]}</form>", $html);
            }
        }
        return $html;
    }
727873
private function fixLibXML( $html ) {
		// We don't include rules like '&#34;' => '&amp;quot;' because entities had already been
		// normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE!
		$replacements = [
			'&quot;' => '&amp;quot;',
			'&amp;' => '&amp;amp;',
			'&lt;' => '&amp;lt;',
			'&gt;' => '&amp;gt;',
		];
		$html = strtr( $html, $replacements );

		// Just in case the conversion in getDoc() above used named
		// entities that aren't known to html_entity_decode().
		$html = \mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' );
		return $html;
	}