Completed
Pull Request — master (#526)
by Michael
02:11
created

XffTrustProvider::isTrusted()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
nc 8
nop 2
dl 0
loc 34
rs 8.7537
c 0
b 0
f 0
ccs 0
cts 12
cp 0
crap 42
1
<?php
2
3
/**
4
 * XffTrustProvider short summary.
5
 *
6
 * XffTrustProvider description.
7
 *
8
 * @version 1.0
9
 * @author stwalkerster
10
 */
11
class XffTrustProvider implements IXffTrustProvider
12
{
13
	/**
14
	 * Array of IP addresses which are TRUSTED proxies
15
	 * @var string[]
16
	 */
17
	private $trustedCache = array();
18
19
	/**
20
	 * Array of IP addresses which are UNTRUSTED proxies
21
	 * @var string[]
22
	 */
23
	private $untrustedCache = array();
24
25
	/**
26
	 * Creates a new instance of the trust provider
27
	 * @param string[] $squidIpList List of IP addresses to pre-approve
28
	 */
29
	public function __construct($squidIpList)
30
	{
31
		$this->trustedCache = $squidIpList;
32
	}
33
34
	/**
35
	 * Returns a value if the IP address is a trusted proxy
36
	 * @param string $ip
37
	 * @param PdoDatabase $database
38
	 * @return bool
39
	 */
40
	public function isTrusted($ip, PdoDatabase $database = null)
41
	{
42
		if (in_array($ip, $this->trustedCache)) {
43
			return true;
44
		}
45
46
		if (in_array($ip, $this->untrustedCache)) {
47
			return false;
48
		}
49
50
		if ($database == null) {
51
			$database = gGetDb();
52
		}
53
54
		$query = "SELECT COUNT(*) FROM xfftrustcache WHERE ip = :ip;";
55
		$statement = $database->prepare($query);
56
		$statement->execute(array(":ip" => $ip));
57
		$result = $statement->fetchColumn();
58
		$statement->closeCursor();
59
60
		if ($result == 0) {
61
			$this->untrustedCache[] = $ip;
62
			return false;
63
		}
64
65
		if ($result >= 1) {
66
			$this->trustedCache[] = $ip;
67
			return true;
68
		}
69
70
		// something weird has happened if we've got here.
71
		// default to untrusted.
72
		return false;
73
	}
74
}
75