| 1 |
<?php |
| 2 |
|
| 3 |
class Red_Url_Path { |
| 4 |
private $path; |
| 5 |
|
| 6 |
public function __construct( $path ) { |
| 7 |
$this->path = $this->get_path_component( $path ); |
| 8 |
} |
| 9 |
|
| 10 |
public function is_match( $url, Red_Source_Flags $flags ) { |
| 11 |
$target = new Red_Url_Path( $url ); |
| 12 |
|
| 13 |
$target_path = $target->get(); |
| 14 |
$source_path = $this->get(); |
| 15 |
|
| 16 |
if ( $flags->is_ignore_trailing() ) { |
| 17 |
// Ignore trailing slashes |
| 18 |
$source_path = $this->get_without_trailing_slash(); |
| 19 |
$target_path = $target->get_without_trailing_slash(); |
| 20 |
} |
| 21 |
|
| 22 |
if ( $flags->is_ignore_case() ) { |
| 23 |
// Case insensitive match |
| 24 |
$source_path = Red_Url_Path::to_lower( $source_path ); |
| 25 |
$target_path = Red_Url_Path::to_lower( $target_path ); |
| 26 |
} |
| 27 |
|
| 28 |
return $target_path === $source_path; |
| 29 |
} |
| 30 |
|
| 31 |
public static function to_lower( $url ) { |
| 32 |
if ( function_exists( 'mb_strtolower' ) ) { |
| 33 |
return mb_strtolower( $url ); |
| 34 |
} |
| 35 |
|
| 36 |
return strtolower( $url ); |
| 37 |
} |
| 38 |
|
| 39 |
public function get() { |
| 40 |
return $this->path; |
| 41 |
} |
| 42 |
|
| 43 |
public function get_without_trailing_slash() { |
| 44 |
// Return / or // as-is |
| 45 |
if ( $this->path === '/' ) { |
| 46 |
return $this->path; |
| 47 |
} |
| 48 |
|
| 49 |
// Anything else remove the last / |
| 50 |
return preg_replace( '@/$@', '', $this->get() ); |
| 51 |
} |
| 52 |
|
| 53 |
// parse_url doesn't handle 'incorrect' URLs, such as those with double slashes |
| 54 |
// These are often used in redirects, so we fall back to our own parsing |
| 55 |
private function get_path_component( $url ) { |
| 56 |
$path = $url; |
| 57 |
|
| 58 |
if ( preg_match( '@^https?://@', $url, $matches ) > 0 ) { |
| 59 |
$parts = explode( '://', $url ); |
| 60 |
|
| 61 |
if ( count( $parts ) > 1 ) { |
| 62 |
$rest = explode( '/', $parts[1] ); |
| 63 |
$path = '/' . implode( '/', array_slice( $rest, 1 ) ); |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
return urldecode( $this->get_query_before( $path ) ); |
| 68 |
} |
| 69 |
|
| 70 |
private function get_query_before( $url ) { |
| 71 |
$qpos = strpos( $url, '?' ); |
| 72 |
$qrpos = strpos( $url, '\\?' ); |
| 73 |
|
| 74 |
if ( $qrpos !== false && $qrpos < $qpos ) { |
| 75 |
return substr( $url, 0, $qrpos + strlen( $qrpos ) - 1 ); |
| 76 |
} |
| 77 |
|
| 78 |
if ( $qpos === false ) { |
| 79 |
return $url; |
| 80 |
} |
| 81 |
|
| 82 |
return substr( $url, 0, $qpos ); |
| 83 |
} |
| 84 |
} |
| 85 |
|