| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Check the request IP |
| 5 |
*/ |
| 6 |
class IP_Match extends Red_Match { |
| 7 |
use FromNotFrom_Match; |
| 8 |
|
| 9 |
/** |
| 10 |
* Array of IP addresses |
| 11 |
* |
| 12 |
* @var string[] |
| 13 |
*/ |
| 14 |
public $ip = []; |
| 15 |
|
| 16 |
public function name() { |
| 17 |
return __( 'URL and IP', 'redirection' ); |
| 18 |
} |
| 19 |
|
| 20 |
public function save( array $details, $no_target_url = false ) { |
| 21 |
$data = array( 'ip' => isset( $details['ip'] ) && is_array( $details['ip'] ) ? $this->sanitize_ips( $details['ip'] ) : [] ); |
| 22 |
|
| 23 |
return $this->save_data( $details, $no_target_url, $data ); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Sanitize a single IP |
| 28 |
* |
| 29 |
* @param string $ip IP. |
| 30 |
* @return string|false |
| 31 |
*/ |
| 32 |
private function sanitize_single_ip( $ip ) { |
| 33 |
$ip = @inet_pton( trim( sanitize_text_field( $ip ) ) ); |
| 34 |
if ( $ip !== false ) { |
| 35 |
return @inet_ntop( $ip ); // Convert back to string |
| 36 |
} |
| 37 |
|
| 38 |
return false; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Sanitize a list of IPs |
| 43 |
* |
| 44 |
* @param string[] $ips List of IPs. |
| 45 |
* @return string[] |
| 46 |
*/ |
| 47 |
private function sanitize_ips( array $ips ) { |
| 48 |
$ips = array_map( array( $this, 'sanitize_single_ip' ), $ips ); |
| 49 |
return array_values( array_filter( array_unique( $ips ) ) ); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Get a list of IPs that match. |
| 54 |
* |
| 55 |
* @param string $match_ip IP to match. |
| 56 |
* @return string[] |
| 57 |
*/ |
| 58 |
private function get_matching_ips( $match_ip ) { |
| 59 |
$current_ip = @inet_pton( $match_ip ); |
| 60 |
|
| 61 |
return array_filter( $this->ip, function( $ip ) use ( $current_ip ) { |
| 62 |
return @inet_pton( $ip ) === $current_ip; |
| 63 |
} ); |
| 64 |
} |
| 65 |
|
| 66 |
public function is_match( $url ) { |
| 67 |
$matched = $this->get_matching_ips( Redirection_Request::get_ip() ); |
| 68 |
|
| 69 |
return count( $matched ) > 0; |
| 70 |
} |
| 71 |
|
| 72 |
public function get_data() { |
| 73 |
return array_merge( array( |
| 74 |
'ip' => $this->ip, |
| 75 |
), $this->get_from_data() ); |
| 76 |
} |
| 77 |
|
| 78 |
public function load( $values ) { |
| 79 |
$values = $this->load_data( $values ); |
| 80 |
$this->ip = isset( $values['ip'] ) ? $values['ip'] : []; |
| 81 |
} |
| 82 |
} |
| 83 |
|