/articles/* /blog/a/b -> /articles/a/b * * A mistake in a regular expression can put a whole site into a redirect * loop; a plain prefix cannot do much worse than redirect too much. Loops * are refused when a rule is saved (see check_rule()), and at request time * the chain is capped (resolve()), so a rule edited behind the plugin's back * redirects nowhere rather than forever. * * Path comparison: a trailing slash never matters, the query string is * ignored when matching and carried onto the target, the host is not part of * a source at all, and the path itself IS case-sensitive (on most servers * /About and /about are different pages). * * @package ABDS_SEO */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Matching, chain resolution and rule validation. */ class ABDS_SEO_Redirect_Matcher { /** * Redirect types a rule may have. 410 (Gone) has no target. */ const TYPES = array( 301, 302, 307, 410 ); /** * Longest chain of rules a request may follow, and the longest one a new * rule may create. */ const MAX_HOPS = 3; /** * Normalizes a path or URL to the form rules are stored and compared in: * no scheme or host, no query or fragment, percent-decoded, a leading * slash, no duplicate or trailing slash (except the root). A trailing "*" * is kept. * * @param string $input Path or URL. * @return string */ public static function normalize_path( string $input ): string { $input = trim( $input ); if ( preg_match( '#^[a-z][a-z0-9+.-]*://[^/]*#i', $input ) ) { $input = (string) preg_replace( '#^[a-z][a-z0-9+.-]*://[^/]*#i', '', $input ); } $cut = strcspn( $input, '?#' ); $path = rawurldecode( substr( $input, 0, $cut ) ); $path = '/' . ltrim( (string) preg_replace( '#/{2,}#', '/', $path ), '/' ); return '/' === $path ? '/' : rtrim( $path, '/' ); } /** * The query string of a path or URL, without the "?" and fragment. * * @param string $input Path or URL. * @return string */ public static function query_of( string $input ): string { $position = strpos( $input, '?' ); if ( false === $position ) { return ''; } $query = substr( $input, $position + 1 ); $hash = strpos( $query, '#' ); return false === $hash ? $query : substr( $query, 0, $hash ); } /** * Whether a source ends in the "*" wildcard. * * @param string $source Normalized source. * @return bool */ public static function is_wildcard( string $source ): bool { return '' !== $source && '*' === substr( $source, -1 ); } /** * The part of $path a rule covers, or null when the rule does not match. * "" for an exact match; for a wildcard rule the text the "*" stands for. * * @param string $source Normalized rule source. * @param string $path Normalized request path. * @return string|null */ public static function match( string $source, string $path ): ?string { if ( self::is_wildcard( $source ) ) { // "/blog/*": the prefix "/blog/" must be followed by something. $prefix = substr( $source, 0, -1 ); return 0 === strpos( $path, $prefix ) && strlen( $path ) > strlen( $prefix ) ? substr( $path, strlen( $prefix ) ) : null; } return $source === $path ? '' : null; } /** * The target a rule sends a match to: a trailing "*" takes the matched * remainder. A 410 has no target. * * @param array $rule Rule ({source, target, type}). * @param string $remainder What the source's "*" matched. * @return string */ public static function target_for( array $rule, string $remainder ): string { $target = (string) ( $rule['target'] ?? '' ); return '*' === substr( $target, -1 ) ? substr( $target, 0, -1 ) . $remainder : $target; } /** * Adds a request's query string to a target (kept when the target has * none of its own, appended when it does). * * @param string $target Target path or URL. * @param string $query Request query string, without "?". * @return string */ public static function carry_query( string $target, string $query ): string { if ( '' === $query ) { return $target; } return $target . ( false === strpos( $target, '?' ) ? '?' : '&' ) . $query; } /** * Follows the rules from a path: a request that reaches a rule whose * target is itself covered by another rule is sent straight to the end * of the chain (one redirect for the visitor, not several), at most * MAX_HOPS rules deep. * * The finder is how rules are looked up (an indexed database read at * request time, an in-memory list when a rule is being validated): it * takes a normalized path and returns the winning rule array or null. * * @param callable $finder fn( string $path ): ?array. * @param string $path Normalized starting path. * @param int $max_hops Hop limit. * @return array{status:string, hops:int, type:int, target:?string, path:?string, first:?array} status is 'none' (no rule), 'ok', 'loop' or 'too_long'; target is the final destination (path or URL), path its normalized path when internal, first the rule the request matched first (the one to credit with the hit). */ public static function resolve( callable $finder, string $path, int $max_hops = self::MAX_HOPS ): array { $seen = array( $path => true ); $current = $path; $hops = 0; $first = null; $result = array( 'status' => 'none', 'hops' => 0, 'type' => 0, 'target' => null, 'path' => null, 'first' => null, ); while ( true ) { $rule = call_user_func( $finder, $current ); if ( ! is_array( $rule ) ) { return $result; } $first = $first ?? $rule; $remainder = self::match( (string) $rule['source'], $current ); ++$hops; if ( $hops > $max_hops ) { return array_merge( $result, array( 'status' => 'too_long', 'hops' => $hops, 'first' => $first, ) ); } $type = (int) $rule['type']; if ( 410 === $type ) { return array( 'status' => 'ok', 'hops' => $hops, 'type' => 410, 'target' => null, 'path' => null, 'first' => $first, ); } $target = self::target_for( $rule, (string) $remainder ); $result = array( 'status' => 'ok', 'hops' => $hops, 'type' => $type, 'target' => $target, 'path' => preg_match( '#^[a-z][a-z0-9+.-]*://#i', $target ) ? null : self::normalize_path( $target ), 'first' => $first, ); // External target: nothing further to follow. if ( null === $result['path'] ) { return $result; } if ( isset( $seen[ $result['path'] ] ) ) { return array_merge( $result, array( 'status' => 'loop' ) ); } $seen[ $result['path'] ] = true; $current = $result['path']; } } /** * Builds a finder over an in-memory rule list: an exact source wins, * otherwise the longest wildcard prefix. Inactive rules are skipped. * * @param array $rules Rules ({source, target, type, active}). * @return callable */ public static function finder_for( array $rules ): callable { $exact = array(); $wildcards = array(); foreach ( $rules as $rule ) { if ( isset( $rule['active'] ) && ! $rule['active'] ) { continue; } $source = (string) $rule['source']; if ( self::is_wildcard( $source ) ) { $wildcards[] = $rule; } else { $exact[ $source ] = $rule; } } usort( $wildcards, static fn( $a, $b ) => strlen( (string) $b['source'] ) <=> strlen( (string) $a['source'] ) ); return static function ( string $path ) use ( $exact, $wildcards ) { if ( isset( $exact[ $path ] ) ) { return $exact[ $path ]; } foreach ( $wildcards as $rule ) { if ( null !== self::match( (string) $rule['source'], $path ) ) { return $rule; } } return null; }; } /** * Host part of a URL, '' when there is none. * * @param string $url URL. * @return string */ protected static function host_of( string $url ): string { // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- this class stays free of WordPress functions (see the file docblock); only the host is read. return (string) parse_url( $url, PHP_URL_HOST ); } /** * Checks a rule about to be saved. Returns null when it may be saved, or * the first problem as a code the caller turns into a message: * * - source_required / source_invalid / wildcard_misplaced / too_broad * - target_required / target_invalid / target_wildcard_without_source * - type_invalid * - self_redirect (the target leads back to the source) * - loop (the rules would send a request round in a circle) * - chain_too_long (more than MAX_HOPS rules in a row) * - duplicate_source (another rule already owns this source) * * The rule is normalized first; the normalized form is what is returned * in 'rule' on success. * * @param array $rule Candidate ({source, target, type, active}); 'id' optional. * @param array $existing All stored rules. * @param string $home_host Host of this site, to recognise absolute links back to it. * @return array{code:?string, rule:array, detail:string} code null means fine. */ public static function check_rule( array $rule, array $existing, string $home_host = '' ): array { $type = (int) ( $rule['type'] ?? 301 ); $id = (int) ( $rule['id'] ?? 0 ); $raw = trim( (string) ( $rule['source'] ?? '' ) ); $target = trim( (string) ( $rule['target'] ?? '' ) ); $fail = static fn( string $code, string $detail = '' ) => array( 'code' => $code, 'rule' => $rule, 'detail' => $detail, ); if ( '' === $raw ) { return $fail( 'source_required' ); } if ( preg_match( '#^[a-z][a-z0-9+.-]*://#i', $raw ) && '' !== $home_host && strtolower( self::host_of( $raw ) ) !== strtolower( $home_host ) ) { return $fail( 'source_invalid', 'other host' ); } $source = self::normalize_path( $raw ); if ( false !== strpos( $source, '*' ) && ( ! self::is_wildcard( $source ) || substr_count( $source, '*' ) > 1 || '/*' !== substr( $source, -2 ) ) ) { return $fail( 'wildcard_misplaced' ); } if ( '/*' === $source ) { return $fail( 'too_broad' ); } if ( ! in_array( $type, self::TYPES, true ) ) { return $fail( 'type_invalid' ); } $wildcard = self::is_wildcard( $source ); if ( 410 === $type ) { $target = ''; } else { if ( '' === $target ) { return $fail( 'target_required' ); } $external = (bool) preg_match( '#^[a-z][a-z0-9+.-]*://#i', $target ); if ( $external && ! preg_match( '#^https?://[^/\s]+#i', $target ) ) { return $fail( 'target_invalid' ); } if ( ! $external && 0 !== strpos( $target, '/' ) ) { return $fail( 'target_invalid' ); } if ( false !== strpos( $target, '*' ) && ( ! $wildcard || '*' !== substr( $target, -1 ) || substr_count( $target, '*' ) > 1 ) ) { return $fail( 'target_wildcard_without_source' ); } // An absolute link to this very site is an internal path. if ( $external && '' !== $home_host && strtolower( self::host_of( $target ) ) === strtolower( $home_host ) ) { $target = self::normalize_path( $target ) . ( '' !== self::query_of( $target ) ? '?' . self::query_of( $target ) : '' ); } } $clean = array( 'id' => $id, 'source' => $source, 'target' => $target, 'type' => $type, 'active' => ! isset( $rule['active'] ) || (bool) $rule['active'], ); foreach ( $existing as $other ) { if ( (int) ( $other['id'] ?? 0 ) !== $id && (string) $other['source'] === $source ) { return array_merge( $fail( 'duplicate_source' ), array( 'rule' => $clean ) ); } } if ( 410 !== $type && ! $wildcard && ! preg_match( '#^[a-z][a-z0-9+.-]*://#i', $target ) && self::normalize_path( $target ) === $source ) { return array_merge( $fail( 'self_redirect' ), array( 'rule' => $clean ) ); } // Everything else: simulate. The candidate joins the stored rules, // replacing its own previous version, and every rule's start path is // followed. $rules = array_values( array_filter( $existing, static fn( $other ) => (int) ( $other['id'] ?? 0 ) !== $id || 0 === $id ) ); $rules[] = $clean; $finder = self::finder_for( $rules ); foreach ( $rules as $candidate ) { if ( isset( $candidate['active'] ) && ! $candidate['active'] ) { continue; } $source_path = (string) $candidate['source']; $start = self::is_wildcard( $source_path ) ? substr( $source_path, 0, -1 ) . 'x' : $source_path; $outcome = self::resolve( $finder, $start, self::MAX_HOPS ); if ( 'loop' === $outcome['status'] ) { return array_merge( $fail( 'loop', (string) $candidate['source'] ), array( 'rule' => $clean ) ); } if ( 'too_long' === $outcome['status'] ) { return array_merge( $fail( 'chain_too_long', (string) $candidate['source'] ), array( 'rule' => $clean ) ); } } return array( 'code' => null, 'rule' => $clean, 'detail' => '', ); } }