) * combinators. * * Anything else returns null and the rule is skipped for that selector — * skipping a fix is always safer than guessing a match. */ class EqualSites_Selector_Xpath { public static function convert( $selector ) { $selector = trim( $selector ); if ( '' === $selector ) { return null; } // 1. Pull quoted attribute values out FIRST so their contents (URLs // with ":" and ".", spaces, parens) can't confuse structural parsing. $values = array(); $selector = preg_replace_callback( '/\[\s*([\w-]+)\s*([~^$*|]?=)\s*"((?:[^"\\\\]|\\\\.)*)"\s*\]/', function ( $m ) use ( &$values ) { $values[] = array( 'attr' => $m[1], 'op' => $m[2], 'value' => preg_replace( '/\\\\(.)/', '$1', $m[3] ), ); return '[__eqv' . ( count( $values ) - 1 ) . '__]'; }, $selector ); if ( null === $selector ) { return null; } // 2. Extract :has(...) / :not(...) innermost-first into bracket // markers, so nesting like :not(:has(x)) resolves outward. $pseudos = array(); for ( $guard_iterations = 0; $guard_iterations < 10; $guard_iterations++ ) { $replaced = preg_replace_callback( '/:(has|not)\(([^()]*)\)/', function ( $m ) use ( &$pseudos ) { $pseudos[] = array( 'fn' => $m[1], 'arg' => $m[2] ); return '[__eqp' . ( count( $pseudos ) - 1 ) . '__]'; }, $selector, -1, $count ); if ( null === $replaced ) { return null; } $selector = $replaced; if ( 0 === $count ) { break; } } // 3. Positional of-type pseudos become bracket markers too. $selector = str_replace( array( ':first-of-type', ':last-of-type' ), array( '[__eqfirst__]', '[__eqlast__]' ), $selector ); // 4. After all extractions the only legal remaining pseudo is // :nth-child(N); strip those, then nothing colon/paren/comma-like may // survive (escaped colons inside identifiers are fine). $residue = preg_replace( '/:nth-child\(\d+\)/', '', $selector ); if ( null === $residue || preg_match( '/[,+~"()]|(?)\s*|\s+/', $selector, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE ); $xpath = ''; $axis = '//'; foreach ( $tokens as $token ) { if ( '>' === $token ) { $axis = '/'; continue; } $step = self::compound_to_xpath( $token, $values, $pseudos ); if ( null === $step ) { return null; } $xpath .= $axis . $step; $axis = '//'; } return $xpath; } private static function compound_to_xpath( $compound, $values, $pseudos ) { $ident = '(?:[\w-]|\\\\.)+'; if ( ! preg_match( '/^([a-zA-Z][\w-]*|\*)?((?:[#.\[:](?:\\\\.|[^#.\[:])*)*)$/', $compound, $m ) ) { return null; } $tag = ( isset( $m[1] ) && '' !== $m[1] ) ? strtolower( $m[1] ) : '*'; $predicates = ''; $rest = isset( $m[2] ) ? $m[2] : ''; if ( ! preg_match_all( "/([#.])({$ident})|\\[([\\w-]+)\\]|:nth-child\\((\\d+)\\)/", $rest, $parts, PREG_SET_ORDER ) && '' !== $rest ) { return null; } $matched_length = 0; foreach ( $parts as $part ) { $matched_length += strlen( $part[0] ); if ( '#' === $part[1] ) { $predicates .= '[@id=' . self::xpath_string( self::unescape( $part[2] ) ) . ']'; } elseif ( '.' === $part[1] ) { $predicates .= "[contains(concat(' ', normalize-space(@class), ' '), " . self::xpath_string( ' ' . self::unescape( $part[2] ) . ' ' ) . ')]'; } elseif ( isset( $part[3] ) && '' !== $part[3] ) { $name = $part[3]; if ( preg_match( '/^__eqv(\d+)__$/', $name, $vm ) ) { $predicate = self::attr_predicate( $values[ (int) $vm[1] ] ); if ( null === $predicate ) { return null; } $predicates .= $predicate; } elseif ( preg_match( '/^__eqp(\d+)__$/', $name, $pm ) ) { $predicate = self::pseudo_predicate( $pseudos[ (int) $pm[1] ], $values, $pseudos ); if ( null === $predicate ) { return null; } $predicates .= $predicate; } elseif ( '__eqfirst__' === $name || '__eqlast__' === $name ) { if ( '*' === $tag ) { return null; // of-type needs a concrete tag } $axis = '__eqfirst__' === $name ? 'preceding-sibling' : 'following-sibling'; $predicates .= sprintf( '[not(%s::%s)]', $axis, $tag ); } else { $predicates .= sprintf( '[@%s]', $name ); } } elseif ( isset( $part[4] ) && '' !== $part[4] ) { $predicates .= sprintf( '[count(preceding-sibling::*) + 1 = %d]', (int) $part[4] ); } } if ( $matched_length !== strlen( $rest ) ) { return null; } return $tag . $predicates; } /** :has(a, b) → [.//a or .//b]; :not([__eqpN__ for a has]) → [not(...)]. */ private static function pseudo_predicate( $pseudo, $values, $pseudos ) { if ( 'has' === $pseudo['fn'] ) { $union = self::has_union( $pseudo['arg'], $values, $pseudos ); return null === $union ? null : '[' . $union . ']'; } // :not(...) — v1 supports exactly :not(): structural exclusion. if ( preg_match( '/^\s*\[__eqp(\d+)__\]\s*$/', $pseudo['arg'], $m ) ) { $inner = $pseudos[ (int) $m[1] ]; if ( 'has' === $inner['fn'] ) { $union = self::has_union( $inner['arg'], $values, $pseudos ); return null === $union ? null : '[not(' . $union . ')]'; } } return null; } private static function has_union( $arg, $values, $pseudos ) { $parts = array(); foreach ( explode( ',', $arg ) as $piece ) { $piece = trim( $piece ); if ( '' === $piece || false !== strpos( $piece, ' ' ) || false !== strpos( $piece, '>' ) ) { return null; // combinators inside :has() unsupported in v1 } $step = self::compound_to_xpath( $piece, $values, $pseudos ); if ( null === $step ) { return null; } $parts[] = './/' . $step; } return implode( ' or ', $parts ); } private static function attr_predicate( $spec ) { $attr = $spec['attr']; $value = self::xpath_string( $spec['value'] ); switch ( $spec['op'] ) { case '=': return sprintf( '[@%s=%s]', $attr, $value ); case '^=': return sprintf( '[starts-with(@%s, %s)]', $attr, $value ); case '$=': $len = strlen( $spec['value'] ); return sprintf( '[substring(@%1$s, string-length(@%1$s) - %2$d + 1) = %3$s]', $attr, $len, $value ); case '*=': return sprintf( '[contains(@%s, %s)]', $attr, $value ); case '~=': return sprintf( "[contains(concat(' ', normalize-space(@%s), ' '), %s)]", $attr, self::xpath_string( ' ' . $spec['value'] . ' ' ) ); case '|=': return sprintf( '[@%1$s=%2$s or starts-with(@%1$s, %3$s)]', $attr, $value, self::xpath_string( $spec['value'] . '-' ) ); default: return null; } } private static function unescape( $ident ) { return preg_replace( '/\\\\(.)/', '$1', $ident ); } /** Quote a string for XPath 1.0 (handles embedded quotes via concat). */ private static function xpath_string( $value ) { if ( false === strpos( $value, "'" ) ) { return "'" . $value . "'"; } if ( false === strpos( $value, '"' ) ) { return '"' . $value . '"'; } return "concat('" . str_replace( "'", "', \"'\", '", $value ) . "')"; } }