- global $wgIP, $wgUsePrivateIPs, $wgCommandLineMode;
-
- # Return cached result
- if ( !empty( $wgIP ) ) {
- return $wgIP;
- }
-
- $ipchain = array();
- $ip = false;
-
- /* collect the originating ips */
- # Client connecting to this webserver
- if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
- $ip = IP::canonicalize( $_SERVER['REMOTE_ADDR'] );
- } elseif( $wgCommandLineMode ) {
- $ip = '127.0.0.1';
- }
- if( $ip ) {
- $ipchain[] = $ip;
- }
-
- # Append XFF on to $ipchain
- $forwardedFor = wfGetForwardedFor();
- if ( isset( $forwardedFor ) ) {
- $xff = array_map( 'trim', explode( ',', $forwardedFor ) );
- $xff = array_reverse( $xff );
- $ipchain = array_merge( $ipchain, $xff );
- }
-
- # Step through XFF list and find the last address in the list which is a trusted server
- # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
- foreach ( $ipchain as $i => $curIP ) {
- $curIP = IP::canonicalize( $curIP );
- if ( wfIsTrustedProxy( $curIP ) ) {
- if ( isset( $ipchain[$i + 1] ) ) {
- if( $wgUsePrivateIPs || IP::isPublic( $ipchain[$i + 1 ] ) ) {
- $ip = $ipchain[$i + 1];
- }
- }
- } else {
- break;
- }
- }
-
- if( !$ip ) {
- throw new MWException( "Unable to determine IP" );
- }
-
- wfDebug( "IP: $ip\n" );
- $wgIP = $ip;
- return $ip;