1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Wrapper for MaxMind GeoLite2 Reader |
4
|
|
|
* |
5
|
|
|
* This class provide an interface to handle geolocation and error handling. |
6
|
|
|
* |
7
|
|
|
* Requires PHP 5.4+. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
defined( 'ABSPATH' ) || exit; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Geolite integration class. |
14
|
|
|
*/ |
15
|
|
|
class Jetpack_Geolite_Integration { |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* MaxMind GeoLite2 database path. |
19
|
|
|
* |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
private $database = ''; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Constructor. |
26
|
|
|
* |
27
|
|
|
* @param string $database MaxMind GeoLite2 database path. |
28
|
|
|
*/ |
29
|
|
|
public function __construct( $database ) { |
30
|
|
|
$this->database = $database; |
31
|
|
|
|
32
|
|
|
if ( ! class_exists( 'MaxMind\\Db\\Reader', false ) ) { |
33
|
|
|
$this->require_geolite_library(); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Get country 2-letters ISO by IP address. |
39
|
|
|
* Retuns empty string when not able to find any ISO code. |
40
|
|
|
* |
41
|
|
|
* @param string $ip_address User IP address. |
42
|
|
|
* @return string |
43
|
|
|
*/ |
44
|
|
|
public function get_country_iso( $ip_address ) { |
45
|
|
|
$iso_code = ''; |
46
|
|
|
|
47
|
|
|
try { |
48
|
|
|
$reader = new MaxMind\Db\Reader( $this->database ); // phpcs:ignore PHPCompatibility.PHP.NewLanguageConstructs.t_ns_separatorFound |
49
|
|
|
$data = $reader->get( $ip_address ); |
50
|
|
|
$iso_code = $data['country']['iso_code']; |
51
|
|
|
|
52
|
|
|
$reader->close(); |
53
|
|
|
} catch ( Exception $e ) { |
54
|
|
|
error_log( $e->getMessage() ); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return sanitize_text_field( strtoupper( $iso_code ) ); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Require geolite library. |
62
|
|
|
*/ |
63
|
|
|
private function require_geolite_library() { |
64
|
|
|
require_once JETPACK__PLUGIN_DIR . '_inc/lib/geolite2/Reader/Decoder.php'; |
65
|
|
|
require_once JETPACK__PLUGIN_DIR . '_inc/lib/geolite2/Reader/InvalidDatabaseException.php'; |
66
|
|
|
require_once JETPACK__PLUGIN_DIR . '_inc/lib/geolite2/Reader/Metadata.php'; |
67
|
|
|
require_once JETPACK__PLUGIN_DIR . '_inc/lib/geolite2/Reader/Util.php'; |
68
|
|
|
require_once JETPACK__PLUGIN_DIR . '_inc/lib/geolite2/Reader.php'; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|