| 1 |
<?php |
| 2 |
|
| 3 |
class Red_Url_Request { |
| 4 |
private $original_url; |
| 5 |
private $decoded_url; |
| 6 |
|
| 7 |
public function __construct( $url ) { |
| 8 |
$this->original_url = apply_filters( 'redirection_url_source', $url ); |
| 9 |
$this->decoded_url = rawurldecode( $this->original_url ); |
| 10 |
|
| 11 |
// Replace the decoded query params with the original ones |
| 12 |
$this->original_url = $this->replace_query_params( $this->original_url, $this->decoded_url ); |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Take the decoded path part, but keep the original query params. This ensures any redirects keep the encoding. |
| 17 |
* |
| 18 |
* @param string $original_url Original unencoded URL. |
| 19 |
* @param string $decoded_url Decoded URL. |
| 20 |
* @return string |
| 21 |
*/ |
| 22 |
private function replace_query_params( $original_url, $decoded_url ) { |
| 23 |
$decoded = explode( '?', $decoded_url ); |
| 24 |
|
| 25 |
if ( count( $decoded ) > 1 ) { |
| 26 |
$original = explode( '?', $original_url ); |
| 27 |
|
| 28 |
if ( count( $original ) > 1 ) { |
| 29 |
return $decoded[0] . '?' . $original[1]; |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
return $decoded_url; |
| 34 |
} |
| 35 |
|
| 36 |
public function get_original_url() { |
| 37 |
return $this->original_url; |
| 38 |
} |
| 39 |
|
| 40 |
public function get_decoded_url() { |
| 41 |
return $this->decoded_url; |
| 42 |
} |
| 43 |
|
| 44 |
public function is_valid() { |
| 45 |
return strlen( $this->get_decoded_url() ) > 0; |
| 46 |
} |
| 47 |
|
| 48 |
/* |
| 49 |
* Protect certain URLs from being redirected. Note we don't need to protect wp-admin, as this code doesn't run there |
| 50 |
*/ |
| 51 |
public function is_protected_url() { |
| 52 |
$rest = wp_parse_url( red_get_rest_api() ); |
| 53 |
$rest_api = $rest['path'] . ( isset( $rest['query'] ) ? '?' . $rest['query'] : '' ); |
| 54 |
|
| 55 |
if ( substr( $this->get_decoded_url(), 0, strlen( $rest_api ) ) === $rest_api ) { |
| 56 |
// Never redirect the REST API |
| 57 |
return true; |
| 58 |
} |
| 59 |
|
| 60 |
return false; |
| 61 |
} |
| 62 |
|
| 63 |
} |
| 64 |
|