|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* IP location provider |
|
5
|
|
|
*/ |
|
6
|
|
|
class IpLocationProvider implements ILocationProvider |
|
7
|
|
|
{ |
|
8
|
|
|
private $apikey; |
|
9
|
|
|
private $database; |
|
10
|
|
|
|
|
11
|
|
|
public function __construct(PdoDatabase $database, $apikey) |
|
12
|
|
|
{ |
|
13
|
|
|
$this->database = $database; |
|
14
|
|
|
$this->apikey = $apikey; |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
public function getIpLocation($address) |
|
18
|
|
|
{ |
|
19
|
|
|
$address = trim($address); |
|
20
|
|
|
|
|
21
|
|
|
// lets look in our database first. |
|
22
|
|
|
$location = GeoLocation::getByAddress($address, $this->database, true); |
|
23
|
|
|
|
|
24
|
|
|
if ($location != null) { |
|
25
|
|
|
// touch cache timer |
|
26
|
|
|
$location->save(); |
|
27
|
|
|
|
|
28
|
|
|
return $location->getData(); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
// OK, it's not there, let's do an IP2Location lookup. |
|
32
|
|
|
$result = $this->getResult($address); |
|
33
|
|
|
|
|
34
|
|
|
if ($result != null) { |
|
35
|
|
|
$location = new GeoLocation(); |
|
36
|
|
|
$location->setDatabase($this->database); |
|
37
|
|
|
$location->setAddress($address); |
|
38
|
|
|
$location->setData($result); |
|
39
|
|
|
$location->save(); |
|
40
|
|
|
|
|
41
|
|
|
return $result; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return null; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
// adapted from http://www.ipinfodb.com/ip_location_api.php |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @param string $ip |
|
51
|
|
|
* @return array|null |
|
52
|
|
|
*/ |
|
53
|
|
|
private function getResult($ip) |
|
54
|
|
|
{ |
|
55
|
|
|
try { |
|
56
|
|
|
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { |
|
57
|
|
|
$xml = @file_get_contents($this->getApiBase() . '?key=' . $this->apikey . '&ip=' . $ip . '&format=xml'); |
|
58
|
|
|
|
|
59
|
|
|
$response = @new SimpleXMLElement($xml); |
|
60
|
|
|
|
|
61
|
|
|
$result = array(); |
|
62
|
|
|
|
|
63
|
|
|
foreach ($response as $field => $value) { |
|
64
|
|
|
$result[(string)$field] = (string)$value; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return $result; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
catch (Exception $ex) { |
|
71
|
|
|
return null; |
|
72
|
|
|
|
|
73
|
|
|
// TODO: do something smart here, or wherever we use this value. |
|
74
|
|
|
// This is just a temp hack to squash errors on the UI for now. |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
return null; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
protected function getApiBase() |
|
81
|
|
|
{ |
|
82
|
|
|
return "http://api.ipinfodb.com/v3/ip-city/"; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|