doc = $doc;
$this->modern = $modern;
}
public static function supports_html5() {
/**
* Filters whether to use PHP 8.4's HTML5 parser (when available).
*
* @param bool $use
*/
return class_exists( '\Dom\HTMLDocument' ) && apply_filters( 'langferry_html5_parser', true );
}
/**
* Parse a full HTML document. Returns null if parsing is unsafe/failed.
*/
public static function parse_document( $html ) {
if ( self::supports_html5() ) {
try {
$doc = \Dom\HTMLDocument::createFromString( $html, LIBXML_NOERROR, 'UTF-8' );
return new self( $doc, true );
} catch ( \Throwable $e ) {
return null;
}
}
if ( ! class_exists( '\DOMDocument' ) ) {
return null;
}
$doc = new \DOMDocument( '1.0', 'UTF-8' );
$previous = libxml_use_internal_errors( true );
$ok = $doc->loadHTML( '' . $html, LIBXML_HTML_NODEFDTD | LIBXML_NONET | LIBXML_PARSEHUGE | LIBXML_COMPACT );
libxml_clear_errors();
libxml_use_internal_errors( $previous );
if ( ! $ok ) {
return null;
}
foreach ( iterator_to_array( $doc->childNodes ) as $child ) {
if ( XML_PI_NODE === $child->nodeType ) {
$doc->removeChild( $child );
}
}
return new self( $doc, false );
}
public function serialize() {
if ( $this->modern ) {
return $this->doc->saveHtml();
}
// libxml's whole-document saveHTML() writes every non-ASCII character as an
// entity; serializing node by node keeps UTF-8 intact.
$out = '';
foreach ( $this->doc->childNodes as $child ) {
if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType ) {
$out .= 'name
. ( $child->publicId ? ' PUBLIC "' . $child->publicId . '"' : '' )
. ( $child->systemId ? ( $child->publicId ? '' : ' SYSTEM' ) . ' "' . $child->systemId . '"' : '' )
. ">\n";
continue;
}
$out .= $this->doc->saveHTML( $child );
}
return $out;
}
public function root() {
return $this->doc->documentElement;
}
public function create_text( $text ) {
return $this->doc->createTextNode( $text );
}
public function create_element( $tag ) {
return $this->doc->createElement( $tag );
}
/**
* Parse an HTML fragment into nodes owned by this document.
*
* @return array|null Node list, or null if the fragment could not be parsed.
*/
public function fragment_nodes( $html ) {
if ( $this->modern ) {
try {
$container = $this->doc->createElement( 'div' );
$container->innerHTML = $html;
return iterator_to_array( $container->childNodes );
} catch ( \Throwable $e ) {
return null;
}
}
$tmp = new \DOMDocument( '1.0', 'UTF-8' );
$previous = libxml_use_internal_errors( true );
$ok = $tmp->loadHTML( '
' . $html . '
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET );
libxml_clear_errors();
libxml_use_internal_errors( $previous );
if ( ! $ok ) {
return null;
}
$root = null;
foreach ( $tmp->childNodes as $child ) {
if ( XML_ELEMENT_NODE === $child->nodeType ) {
$root = $child;
break;
}
}
if ( ! $root ) {
return null;
}
$nodes = array();
foreach ( $root->childNodes as $child ) {
$nodes[] = $this->doc->importNode( $child, true );
}
return $nodes;
}
/**
* A template whose contents hold a script's own placeholders, which translation would break:
* {{ }} and {% %} (Mustache, Twig), <% %> (Underscore, EJS), <# #> (WordPress's wp.template), ${ }.
*/
const SCRIPT_TEMPLATE = '/\{\{|\{%|<%|<%|<#|<#|\$\{/';
/**
* The markup inside an element, as the browser would see it.
*/
public static function inner_html( $el ) {
if ( property_exists( $el, 'innerHTML' ) || $el instanceof \Dom\Element ) {
return (string) $el->innerHTML;
}
$out = '';
foreach ( $el->childNodes as $child ) {
$out .= $el->ownerDocument->saveHTML( $child );
}
return $out;
}
/**
* The markup inside .
*/
public function body_inner_html() {
$body = $this->modern ? $this->doc->body : $this->doc->getElementsByTagName( 'body' )->item( 0 );
return $body ? self::inner_html( $body ) : '';
}
/**
* Visit each 's contents as a document of its own (PHP 8.4+ parser only: there a
* template's contents aren't child nodes; with libxml they are, and are walked like any element).
* $callback( Html $contents, $template, $inner ) returns true to write the changed contents back.
* A template whose markup doesn't survive being parsed on its own (table rows, for instance) is
* never written back, so its markup can't change.
*/
public function each_template( callable $callback ) {
if ( ! $this->modern ) {
return;
}
foreach ( $this->select( 'template' ) as $template ) {
$inner = (string) $template->innerHTML;
if ( '' === trim( $inner ) ) {
continue;
}
$contents = self::parse_document( '' . $inner . '' );
if ( ! $contents || $contents->body_inner_html() !== $inner ) {
continue;
}
if ( true === $callback( $contents, $template, $inner ) ) {
$template->innerHTML = $contents->body_inner_html();
}
}
}
/**
* Elements matching a simple CSS selector list. Supports: tag, .class, #id,
* [attr], [attr=value], and compounds of those (e.g. "div.note[data-x]"),
* comma separated. Descendant combinators are supported on PHP 8.4+ only.
*
* @return array
*/
public function select( $selector ) {
$selector = trim( (string) $selector );
if ( '' === $selector ) {
return array();
}
if ( $this->modern ) {
try {
return iterator_to_array( $this->doc->querySelectorAll( $selector ) );
} catch ( \Throwable $e ) {
return array();
}
}
$xpath = self::selector_to_xpath( $selector );
if ( null === $xpath ) {
return array();
}
if ( null === $this->xpath ) {
$this->xpath = new \DOMXPath( $this->doc );
}
$list = @$this->xpath->query( $xpath ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
return $list ? iterator_to_array( $list ) : array();
}
/**
* Convert a simple selector list to XPath (libxml fallback only).
*/
public static function selector_to_xpath( $selector ) {
$parts = array();
foreach ( explode( ',', $selector ) as $single ) {
$single = trim( $single );
if ( ! preg_match( '/^([a-zA-Z][a-zA-Z0-9-]*|\*)?((?:[.#][\w-]+|\[[\w-]+(?:=["\']?[^"\'\]]*["\']?)?\])*)$/', $single, $m ) || ( '' === ( $m[1] ?? '' ) && '' === ( $m[2] ?? '' ) ) ) {
return null;
}
$tag = ! empty( $m[1] ) ? strtolower( $m[1] ) : '*';
$conds = array();
preg_match_all( '/([.#])([\w-]+)|\[([\w-]+)(?:=["\']?([^"\'\]]*)["\']?)?\]/', $m[2] ?? '', $tokens, PREG_SET_ORDER );
foreach ( $tokens as $t ) {
if ( '.' === $t[1] ) {
$conds[] = "contains(concat(' ', normalize-space(@class), ' '), ' {$t[2]} ')";
} elseif ( '#' === $t[1] ) {
$conds[] = "@id='{$t[2]}'";
} elseif ( isset( $t[4] ) ) {
$value = str_replace( "'", '', $t[4] );
$conds[] = "@{$t[3]}='{$value}'";
} else {
$conds[] = "@{$t[3]}";
}
}
$parts[] = '//' . $tag . ( $conds ? '[' . implode( ' and ', $conds ) . ']' : '' );
}
return implode( ' | ', $parts );
}
/**
* Lowercase tag name for an element node.
*/
public static function tag( $node ) {
return strtolower( isset( $node->localName ) && $node->localName ? $node->localName : $node->nodeName );
}
}