-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAPI.php
More file actions
294 lines (254 loc) · 8.47 KB
/
API.php
File metadata and controls
294 lines (254 loc) · 8.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
<?php
/**
* Piwik - free/libre analytics platform.
*
* @see https://matomo.org
*
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\IP2Proxy;
use Exception;
use Piwik\API\Request;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\DataTable;
use Piwik\Db;
use Piwik\Piwik;
use Piwik\Http;
const EMPTY_HOSTNAME = '-';
/**
* API for plugin IP2Proxy.
*
* @method static \Piwik\Plugins\IP2Proxy\API getInstance()
*/
class API extends \Piwik\Plugin\API
{
public $database;
public $ioApiKey;
private $staticContainer;
public function __construct(StaticContainer $staticContainer)
{
// Get settings
$systemSettings = new \Piwik\Plugins\IP2Proxy\SystemSettings();
$this->database = $systemSettings->database->getValue();
$this->ioApiKey = $systemSettings->ioApiKey->getValue();
$this->staticContainer = $staticContainer;
}
/**
* Returns a data table with the visits.
*
* @param int $idSite
* @param string $period
* @param string $date
* @param bool|string $segment
* @param int $filterLimit
*
* @return DataTable
*/
public function getProxyDetails($idSite, $period, $date, $segment = false, $filterLimit = 200)
{
Piwik::checkUserHasViewAccess($idSite);
$logger = $this->staticContainer->getContainer()->get('Psr\Log\LoggerInterface');
$response = Request::processRequest('Live.getLastVisitsDetails', [
'idSite' => $idSite,
'period' => $period,
'date' => $date,
'segment' => $segment,
'flat' => false,
'doNotFetchActions' => false,
'countVisitorsToFetch' => $filterLimit,
]);
$response->applyQueuedFilters();
$result = $response->getEmptyClone($keepFilters = false);
if (!file_exists($this->database)) {
return $result;
}
if (empty($this->ioApiKey)) {
require_once PIWIK_INCLUDE_PATH . '/plugins/IP2Proxy/lib/IP2Proxy.php';
$db = new \IP2Proxy\Database($this->database, \IP2Proxy\Database::FILE_IO);
}
foreach ($response->getRows() as $visitRow) {
$visitIp = $visitRow->getColumn('visitIp');
if (empty($this->ioApiKey)) {
// Get proxy details by the IP
$records = $db->lookup($visitIp, \IP2PROXY\Database::ALL);
} else {
if (($json = json_decode(Http::sendHttpRequest('https://api.ip2location.io/?key=' . $this->ioApiKey . '&ip=' . $visitIp, 30))) !== null) {
$records['isProxy'] = ($json->is_proxy) ? 1 : 0;
$records['proxyType'] = $json->proxy_type ?? 'N/A';
$records['countryName'] = $json->country_name ?? 'N/A';
$records['regionName'] = $json->region_name ?? 'N/A';
$records['cityName'] = $json->city_name ?? 'N/A';
$records['isp'] = $json->isp ?? 'N/A';
$records['domain'] = $json->domain ?? 'N/A';
$records['usageType'] = $json->usage_type ?? 'N/A';
$records['asn'] = $json->asn ?? 'N/A';
$records['threat'] = $json->threat ?? 'N/A';
}
}
foreach ($records as $key => $value) {
if (preg_match('/NOT SUPPORTED/', $value)) {
$records[$key] = 'N/A';
}
}
$result->addRowFromSimpleArray([
'IP' => $visitIp,
'proxy' => ($records['isProxy'] == 1) ? 'Yes' : 'No',
'proxy_type' => $records['proxyType'],
'country' => $records['countryName'],
'region' => $records['regionName'],
'city' => $records['cityName'],
'isp' => $records['isp'],
'domain' => $records['domain'],
'usage_type' => $records['usageType'],
'asn' => ($records['asn'] != '-') ? ('AS' . $records['asn']) : '',
'threat' => $records['threat'],
'last_visit_time' => $visitRow->getColumn('lastActionDateTime'),
'type' => $visitRow->getColumn('visitorType'),
'nb_visits' => $visitRow->getColumn('visitCount'),
'last_visit_duration' => $visitRow->getColumn('visitDurationPretty'),
'referrer_type' => $visitRow->getColumn('referrerType'),
'referrer_name' => $visitRow->getColumn('referrerName'),
'device' => $visitRow->getColumn('deviceType'),
]);
}
return $result;
}
/**
* Another example method that returns a data table.
*
* @param string $ip
* @param mixed $ipList
* @param mixed $dbList
*
* @return array
*/
private function getIPDetails($ip, $ipList, $dbList)
{
$itemFound = false;
$companyName = null;
$hostname = filter_var($ip, FILTER_VALIDATE_IP) ? gethostbyaddr($ip) : EMPTY_HOSTNAME;
if (!isset($ipList[$ip])) {
$delay = new \Datetime();
$delay->sub(new \DateInterval('P' . $this->cacheLifeTimeForResults . 'W'));
// Check if the IP address exists in the DB and if the record is younger than the defined cache
foreach ($dbList as $item) {
$itemDate = new \Datetime($item['updated_at']);
if (($item['ip'] == $ip) && ($delay <= $itemDate)) {
$ipList[$ip] = $item['as_name'];
$itemFound = true;
} elseif (($item['ip'] == $ip) && ($itemDate < $delay)) {
$companyDetails = $this->getCompanyDetails($ip);
$companyName = $companyDetails['as_name'];
$itemFound = $companyName ? true : false;
$ipList[$ip] = $companyName ? $companyName : ($hostname === $ip ? EMPTY_HOSTNAME : $hostname);
// We update the DB only if we got results from the getCompanyDetails method.
if (($ipList[$ip] != $hostname) && $companyName) {
$this->updateCompanyDetails($item, [
'as_number' => $companyDetails['as_number'],
'as_name' => $companyDetails['as_name'],
]);
}
}
}
}
// If the IP doesn't exist in the DB, and if it is a valid IP, try to get the details
if (!isset($ipList[$ip]) && !$itemFound && filter_var($ip, FILTER_VALIDATE_IP)) {
$companyDetails = $this->getCompanyDetails($ip);
$companyName = $companyDetails['as_name'];
$itemFound = $companyName ? true : false;
$ipList[$ip] = $companyName ? $companyName : ($hostname === $ip ? EMPTY_HOSTNAME : $hostname);
// We insert the item in the DB only if we got results from the getCompanyDetails method.
if (($ipList[$ip] != $hostname) && $companyName) {
$this->insertCompanyDetails([
'ip' => $ip,
'as_number' => $companyDetails['as_number'],
'as_name' => $companyDetails['as_name'],
]);
}
}
// If the IP is not valid, just return the empty hostname
elseif (!filter_var($ip, FILTER_VALIDATE_IP)) {
$ipList[$ip] = EMPTY_HOSTNAME;
}
return $ipList;
}
/**
* Another example method that returns a data table.
*
* @param string $ip
*
* @return array
*/
private function getCompanyDetails($ip)
{
return [
'as_name' => mt_rand(10000, 99999),
'as_number' => mt_rand(1000, 9999),
];
$ipInfo = new IPInfo();
// If no token has been set, stop here.
if (!$ipInfo->accessToken) {
return [
'as_name' => null,
'as_number' => null,
];
}
$details = $ipInfo->getDetails($ip);
$details = json_decode($details);
$companyName = null;
$asNumber = null;
if (isset($details->company) && isset($details->company->name)) {
$companyName = $details->company->name;
if ($details->company->domain) {
$companyName .= ' (' . $details->company->domain . ')';
}
} elseif (isset($details->org) && !isset($details->org->name)) {
$orgElements = explode(' ', $details->org);
$asNumber = array_shift($orgElements);
$asName = \count($orgElements) > 1 ? implode(' ', $orgElements) : $orgElements[0];
$companyName = $asName;
}
return [
'as_name' => $companyName,
'as_number' => $asNumber,
];
}
/**
* A private methode to update the company details that we found in the DB.
*
* @param array $item
* @param array $data
*
* @return bool
*/
private function updateCompanyDetails($item, $data)
{
try {
$query = 'UPDATE ' . Common::prefixTable('ip_to_company') . ' SET as_number = ?, as_name = ? WHERE id = ?';
$bind = array($data['as_number'], $data['as_name'], $item['id']);
Db::query($query, $bind);
} catch (Exception $e) {
throw $e;
}
return true;
}
/**
* A private methode to save the company details in the DB.
*
* @param array $data
*
* @return bool
*/
private function insertCompanyDetails($data)
{
try {
$query = 'INSERT INTO ' . Common::prefixTable('ip_to_company') . ' (ip, as_number, as_name) VALUES (?, ?, ?)';
$bind = array($data['ip'], $data['as_number'], $data['as_name']);
Db::query($query, $bind);
} catch (Exception $e) {
throw $e;
}
return true;
}
}