| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Decode request URLs |
| 5 |
*/ |
| 6 |
class Red_Url_Request { |
| 7 |
/** |
| 8 |
* Original URL |
| 9 |
* |
| 10 |
* @var String |
| 11 |
*/ |
| 12 |
private $original_url; |
| 13 |
|
| 14 |
/** |
| 15 |
* Decoded URL |
| 16 |
* |
| 17 |
* @var String |
| 18 |
*/ |
| 19 |
private $decoded_url; |
| 20 |
|
| 21 |
/** |
| 22 |
* Constructor |
| 23 |
* |
| 24 |
* @param String $url URL. |
| 25 |
*/ |
| 26 |
public function __construct( $url ) { |
| 27 |
$this->original_url = apply_filters( 'redirection_url_source', $url ); |
| 28 |
$this->decoded_url = rawurldecode( $this->original_url ); |
| 29 |
|
| 30 |
// Replace the decoded query params with the original ones |
| 31 |
$this->original_url = $this->replace_query_params( $this->original_url, $this->decoded_url ); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Take the decoded path part, but keep the original query params. This ensures any redirects keep the encoding. |
| 36 |
* |
| 37 |
* @param string $original_url Original unencoded URL. |
| 38 |
* @param string $decoded_url Decoded URL. |
| 39 |
* @return string |
| 40 |
*/ |
| 41 |
private function replace_query_params( $original_url, $decoded_url ) { |
| 42 |
$decoded = explode( '?', $decoded_url ); |
| 43 |
|
| 44 |
if ( count( $decoded ) > 1 ) { |
| 45 |
$original = explode( '?', $original_url ); |
| 46 |
|
| 47 |
if ( count( $original ) > 1 ) { |
| 48 |
return $decoded[0] . '?' . $original[1]; |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
return $decoded_url; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Get the original URL |
| 57 |
* |
| 58 |
* @return String |
| 59 |
*/ |
| 60 |
public function get_original_url() { |
| 61 |
return $this->original_url; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Get the decoded URL |
| 66 |
* |
| 67 |
* @return String |
| 68 |
*/ |
| 69 |
public function get_decoded_url() { |
| 70 |
return $this->decoded_url; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Is this a valid URL? |
| 75 |
* |
| 76 |
* @return boolean |
| 77 |
*/ |
| 78 |
public function is_valid() { |
| 79 |
return strlen( $this->get_decoded_url() ) > 0; |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* Protect certain URLs from being redirected. Note we don't need to protect wp-admin, as this code doesn't run there |
| 84 |
* |
| 85 |
* @return boolean |
| 86 |
*/ |
| 87 |
public function is_protected_url() { |
| 88 |
$rest = wp_parse_url( red_get_rest_api() ); |
| 89 |
$rest_api = $rest['path'] . ( isset( $rest['query'] ) ? '?' . $rest['query'] : '' ); |
| 90 |
|
| 91 |
if ( substr( $this->get_decoded_url(), 0, strlen( $rest_api ) ) === $rest_api ) { |
| 92 |
// Never redirect the REST API |
| 93 |
return true; |
| 94 |
} |
| 95 |
|
| 96 |
return false; |
| 97 |
} |
| 98 |
|
| 99 |
} |
| 100 |
|