| 1 |
<?php |
| 2 |
/** |
| 3 |
* GeoIP functionality for WP Defender. |
| 4 |
* |
| 5 |
* @package WP_Defender\Extra |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Extra; |
| 9 |
|
| 10 |
use MaxMind\Db\Reader; |
| 11 |
|
| 12 |
/** |
| 13 |
* GeoIP class for IP geolocation functionality. |
| 14 |
*/ |
| 15 |
class GeoIp { |
| 16 |
/** |
| 17 |
* MaxMind database reader instance. |
| 18 |
* |
| 19 |
* @var Reader |
| 20 |
*/ |
| 21 |
protected $provider; |
| 22 |
|
| 23 |
/** |
| 24 |
* Constructor. |
| 25 |
* |
| 26 |
* @param string $db_path Path to the MaxMind database file. |
| 27 |
*/ |
| 28 |
public function __construct( $db_path ) { |
| 29 |
$this->provider = new Reader( $db_path ); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Convert IP address to country information. |
| 34 |
* |
| 35 |
* @param string $ip IP address to lookup. |
| 36 |
* |
| 37 |
* @return array<string, string>|false Country data array with 'iso' and 'name' keys, or false on failure. |
| 38 |
* @throws Reader\InvalidDatabaseException When database format is invalid. |
| 39 |
*/ |
| 40 |
public function ip_to_country( $ip ) { |
| 41 |
$info = $this->provider->get( $ip ); |
| 42 |
|
| 43 |
// Try country first, then fall back to registered_country. |
| 44 |
$country_data = null; |
| 45 |
if ( isset( $info['country'] ) && is_array( $info['country'] ) ) { |
| 46 |
$country_data = $info['country']; |
| 47 |
} elseif ( isset( $info['registered_country'] ) && is_array( $info['registered_country'] ) ) { |
| 48 |
$country_data = $info['registered_country']; |
| 49 |
} |
| 50 |
|
| 51 |
if ( null === $country_data ) { |
| 52 |
return false; |
| 53 |
} |
| 54 |
|
| 55 |
return array( |
| 56 |
'iso' => $country_data['iso_code'] ?? '', |
| 57 |
'name' => $country_data['names']['en'] ?? '', |
| 58 |
); |
| 59 |
} |
| 60 |
} |
| 61 |
|