fix some issues with phpdoc
[lhc/web/wiklou.git] / includes / ProxyTools.php
1 <?php
2 /**
3 * Functions for dealing with proxies
4 * @package MediaWiki
5 */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 die();
9 }
10
11 /** Work out the IP address based on various globals */
12 function wfGetIP() {
13 global $wgSquidServers, $wgSquidServersNoPurge;
14
15 /* collect the originating ips */
16 # Client connecting to this webserver
17 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
18 $ipchain = array( $_SERVER['REMOTE_ADDR'] );
19 } else {
20 # Running on CLI?
21 $ipchain = array( '127.0.0.1' );
22 }
23 $ip = $ipchain[0];
24
25 # Get list of trusted proxies
26 # Flipped for quicker access
27 $trustedProxies = array_flip( array_merge( $wgSquidServers, $wgSquidServersNoPurge ) );
28 if ( count( $trustedProxies ) ) {
29 # Append XFF on to $ipchain
30 if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
31 $xff = array_map( 'trim', explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
32 $xff = array_reverse( $xff );
33 $ipchain = array_merge( $ipchain, $xff );
34 }
35 # Step through XFF list and find the last address in the list which is a trusted server
36 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
37 foreach ( $ipchain as $i => $curIP ) {
38 if ( array_key_exists( $curIP, $trustedProxies ) ) {
39 if ( isset( $ipchain[$i + 1] ) && wfIsIPPublic( $ipchain[$i + 1] ) ) {
40 $ip = $ipchain[$i + 1];
41 }
42 } else {
43 break;
44 }
45 }
46 }
47
48 return $ip;
49 }
50
51 /** */
52 function wfIP2Unsigned( $ip ) {
53 $n = ip2long( $ip );
54 if ( $n == -1 ) {
55 $n = false;
56 } elseif ( $n < 0 ) {
57 $n += pow( 2, 32 );
58 }
59 return $n;
60 }
61
62 /**
63 * Determine if an IP address really is an IP address, and if it is public,
64 * i.e. not RFC 1918 or similar
65 */
66 function wfIsIPPublic( $ip ) {
67 $n = wfIP2Unsigned( $ip );
68 if ( !$n ) {
69 return false;
70 }
71
72 static $privateRanges = false;
73 if ( !$privateRanges ) {
74 $privateRanges = array(
75 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
76 array( '172.16.0.0', '172.31.255.255' ), # "
77 array( '192.168.0.0', '192.168.255.255' ), # "
78 array( '0.0.0.0', '0.255.255.255' ), # this network
79 array( '127.0.0.0', '127.255.255.255' ), # loopback
80 );
81 }
82
83 foreach ( $privateRanges as $r ) {
84 $start = wfIP2Unsigned( $r[0] );
85 $end = wfIP2Unsigned( $r[1] );
86 if ( $n >= $start && $n <= $end ) {
87 return false;
88 }
89 }
90 return true;
91 }
92
93 ?>