Finalize html result
@private
@param {jQuery} $html jQuery instance
@param {boolean} needHtmlText pass true if need html text
@returns {string|DocumentFragment} result
488466
function finalizeHtml($html, needHtmlText) {
  let returnValue;

  if (needHtmlText) {
    returnValue = $html[0].innerHTML;
  } else {
    const frag = document.createDocumentFragment();
    const childNodes = util.toArray($html[0].childNodes);
    const {length} = childNodes;

    for (let i = 0; i < length; i += 1) {
      frag.appendChild(childNodes[i]);
    }
    returnValue = frag;
  }

  return returnValue;
}
996053
public static function closeOpenTags($html)
    {
        preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU", $html, $result);
        $openedTags = $result[1];
        preg_match_all("#</([a-z]+)>#iU", $html, $result);
        $closedTags = $result[1];
        $lenOpened = count($openedTags);

        if (count($closedTags) == $lenOpened) {
            return $html;
        }

        $openedTags = array_reverse($openedTags);
        for ($i = 0; $i < $lenOpened; $i++) {
            if (!in_array($openedTags[$i], $closedTags)) {
                $html .= '</' . $openedTags[$i] . '>';
            } else {
                unset($closedTags[array_search($openedTags[$i], $closedTags)]);
            }
        }

        return $html;
    }
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;
    }
1246580
public function loadHTML($html)
    {
        $dom = new \DOMDocument();
        $dom->formatOutput = true;

        // strip illegal XML UTF-8 chars
        // remove all control characters except CR, LF and tab
        $html = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/u', '', $html); // 00-09, 11-31, 127

        $dom->loadHTML($html);
        $this->loadDomDocument($dom);
    }
224982
function(html, element) {
      var template = document.createElement('template');
      template.innerHTML = html;
      var fragment = this.instanceTemplate(template);
      if (element) {
        element.textContent = '';
        element.appendChild(fragment);
      }
      return fragment;
    }
590952
public function loadHTML($html)
    {
        if ($html instanceof Renderable) {
            $html = $html->render();
        }
        $this->html = $html;
        $this->file = null;
        return $this;
    }
216030
public static function htmlToDomDocument($html)
    {
        if (!$html) {
            $html = '';
        }

        // Transform multibyte entities which otherwise display incorrectly.
        $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');

        // Internal errors enabled as HTML5 not fully supported.
        libxml_use_internal_errors(true);

        // Instantiate new DOMDocument object, and then load in UTF-8 HTML.
        $dom = new DOMDocument();
        $dom->encoding = 'UTF-8';
        $dom->loadHTML("<div>$html</div>");

        return $dom;
    }
1367825
function finishGroup(&$group)
    {
        $separator = $group->_separator;
        if (is_array($separator)) {
            $count = count($separator);
            $html  = '';
            for ($i = 0; $i < count($this->_groupElements); $i++) {
                $html .= (0 == $i? '': $separator[($i - 1) % $count]) . $this->_groupElements[$i];
            }
        } else {
            if (is_null($separator)) {
                $separator = '&nbsp;';
            }
            $html = implode((string)$separator, $this->_groupElements);
        }
        if (!empty($this->_groupWrap)) {
            $html = str_replace('{content}', $html, $this->_groupWrap);
        }
        $this->_html   .= str_replace('{element}', $html, $this->_groupTemplate);
        $this->_inGroup = false;
    }
300659
public function html2text($html)
    {
        if (!$this->html2textLoaded) {
            require dirname(__FILE__).'/../Utility/Html2Text.php';
            $this->html2textLoaded = true;
        }
        $html2text = new Html2Text($html);

        return $html2text->get_text();
    }
1070321
private function parseContents(string $html): string
    {
        if (\trim($html) === '') {
            return '';
        }

        // Determine value.
        $this->value = $html;
        if (\preg_match("/(.*)<\/\s*" . $this->name . "\s*>/iU", $html, $valueMatches) === 1) {
            $this->value = $valueMatches[1];
        }

        // Don't parse contents of "iframe" element.
        if ($this->name === 'iframe') {
            return $this->parseNoContents('iframe', $html);
        }

        // Only TEXT inside a "script" element.
        if ($this->name === 'script') {
            return $this->parseForeignContents('script', $html);
        }

        // Only TEXT inside a "style" element.
        if ($this->name === 'style') {
            return $this->parseForeignContents('style', $html);
        }

        // Parse contents one token at a time.
        $remainingHtml = $html;
        while ($this->isAnotherTokenPresent($remainingHtml)) {
            $token = Tokenizer::buildFromHtml($remainingHtml, $this);

            if (!$token instanceof TokenInterface || $token->isClosingElementImplied($remainingHtml)) {
                return $remainingHtml;
            }

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

        $this->removeLastTokenIfContainsOnlyWhitespace();

        // Remove remaining closing tag.
        $posOfClosingBracket = \mb_strpos($remainingHtml, '>');

        return \mb_substr($remainingHtml, $posOfClosingBracket + 1);
    }
948873
protected static function processSetSkin($html){
    $pattern = '~<p>SETSKIN:([\w_-]+):NIKSTES<\/p>~m';
    if( preg_match_all($pattern, $html, $matches, PREG_SET_ORDER) ){
      $skin = array_pop($matches);

      //if OutputPageBeforeHTML isn't called before RequestContextCreateSkin
      //then this will have no effect... need a way to hack around the problem...
      self::$pageSkin = $skin[1];

      $html = preg_replace($pattern, '', $html);
    }
    return $html;
  }
201682
public function readability_html( $html )
	{
		$data = $this->post_call('/readability', ['html' => $html ] );

		return ( !empty($data['readability']) ) ? $data['readability'] : null;
	}
116761
public function parseString($html)
    {
        /** TODO: custom markdown-extra options, e.g. titles & classes **/
        // <sup id="fnref:..."><a href"#fn..." rel="footnote">...</a></sup>
        // => <fnref target="..." />
        $html = preg_replace('@<sup id="fnref:([^"]+)">\s*<a href="#fn:\1" rel="footnote">\s*\d+\s*</a>\s*</sup>@Us', '<fnref target="$1" />', $html);
        // <div class="footnotes">
        // <hr />
        // <ol>
        //
        // <li id="fn:...">...</li>
        // ...
        //
        // </ol>
        // </div>
        // =>
        // <footnotes>
        //   <fn name="...">...</fn>
        //   ...
        // </footnotes>
        $html = preg_replace_callback('#<div class="footnotes">\s*<hr />\s*<ol>\s*(.+)\s*</ol>\s*</div>#Us', [&$this, '_makeFootnotes'], $html);

        return parent::parseString($html);
    }
1352507
function getHTMLWH(html) {
  const temp = document.createElement('template');
  const span = document.createElement('span');
  temp.innerHTML = html;
  document.body.appendChild(span);
  if (temp.content) {
    span.appendChild(temp.content, span.lastElementChild);
  } else {
    span.insertAdjacentHTML('beforeend', html);
  }
  span.style.position = 'absolute';
  span.style.zIndex = '-1';
  span.style.display = 'block';
  const whArray = getDomWH(span);
  const result = {
    width: whArray[0],
    height: whArray[1],
  };
  span.parentNode.removeChild(span);
  return result;
}
979683
function parseString($html) {
    $this->parser->html = $html;
    $this->parse();
    return $this->output;
  }
935583
public function convert($html) {
    if (preg_match('/^\s*$/u', $html)) {
      return '';
    }
    $html = '<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head>' . $html . '</body></html>';
    $this->dom = new \DOMDocument();
    if (!$this->dom->loadHTML($html)) {
      return NULL;
    }
    $xp = new \DOMXPath($this->dom);
    return implode(self::BLOCK_DELIMITER, $this->getBlocks(
      $xp->query('/html/body')->item(0)->childNodes
    ));
  }
1353265
public function get($html = null)
    {
        if (null === $html) {
            if (file_exists($this->_path)) {
                $html = file_get_contents($this->_path);
            }
        }

        $this->_path = null;

        return $this->parse($html);
    }