-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIpHandler.php
More file actions
100 lines (84 loc) · 2.33 KB
/
IpHandler.php
File metadata and controls
100 lines (84 loc) · 2.33 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
<?php
namespace BitSensor\Handler;
use Proto\Datapoint;
/**
* Collects the IP address.
* @package BitSensor\Handler
*/
class IpHandler extends AbstractHandler
{
/**
* Source of the IP address of the user, by default to {@see IP_ADDRESS_REMOTE_ADDR}.
*
* One of:
* - {@see IP_ADDRESS_REMOTE_ADDR}
* - {@see IP_ADDRESS_X_FORWARDED_FOR}
* - {@see IP_ADDRESS_MANUAL}
*/
private static $ipAddressSrc = self::IP_ADDRESS_REMOTE_ADDR;
private static $ip;
/**
* Set IP address manually.
*/
const IP_ADDRESS_MANUAL = 'manual';
/**
* Set IP address according to <code>$_SERVER['REMOTE_ADDR']</code>.
*/
const IP_ADDRESS_REMOTE_ADDR = 'remoteAddr';
/**
* Set IP address according to the <code>X-Forwarded-For</code> HTTP header.
*/
const IP_ADDRESS_X_FORWARDED_FOR = 'forwardedFor';
/**
* @param mixed $ipAddressSrc
*/
public static function setIpAddressSrc($ipAddressSrc)
{
self::$ipAddressSrc = $ipAddressSrc;
}
/**
* @param mixed $ip
*/
public static function setIp($ip)
{
self::$ip = $ip;
}
/**
* @param string[] $config
* @return mixed|void
*/
public function configure($config)
{
parent::configure($config);
if (array_key_exists('ipAddressSrc', $config))
self::$ipAddressSrc = $config['ipAddressSrc'];
if (array_key_exists('ipAddress', $config))
self::$ip = $config['ipAddress'];
}
/**
* @param Datapoint $datapoint
*/
public function doHandle(Datapoint $datapoint)
{
$ip = null;
switch (self::$ipAddressSrc) {
case self::IP_ADDRESS_REMOTE_ADDR:
if (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
break;
case self::IP_ADDRESS_X_FORWARDED_FOR:
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip_array = explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR'], 2);
$ip = $ip_array[0];
}
break;
case self::IP_ADDRESS_MANUAL:
$ip = self::$ip;
break;
}
if ($ip !== null) {
$datapoint->getContext()['ip'] = $ip;
}
}
}