2018-11-04 15:15:42 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace CookieWarning;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
2022-12-11 13:18:17 +00:00
|
|
|
use MediaWiki\Http\HttpRequestFactory;
|
2020-03-14 09:01:36 +00:00
|
|
|
use Wikimedia\IPUtils;
|
2018-11-04 15:15:42 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Implements the GeoLocation class, which allows to locate the user based on the IP address.
|
|
|
|
*/
|
|
|
|
class HttpGeoLocation implements GeoLocation {
|
2024-06-04 07:28:46 +00:00
|
|
|
/** @var string */
|
2018-11-04 15:15:42 +00:00
|
|
|
private $geoIPServiceURL;
|
2024-06-04 07:28:46 +00:00
|
|
|
/** @var array */
|
2018-11-04 15:15:42 +00:00
|
|
|
private $locatedIPs = [];
|
|
|
|
|
2022-12-11 13:18:17 +00:00
|
|
|
/** @var HttpRequestFactory */
|
|
|
|
private $httpRequestFactory;
|
|
|
|
|
2018-11-04 15:15:42 +00:00
|
|
|
/**
|
|
|
|
* @param string $geoIPServiceURL
|
2022-12-11 13:18:17 +00:00
|
|
|
* @param HttpRequestFactory $httpRequestFactory
|
2018-11-04 15:15:42 +00:00
|
|
|
*/
|
2022-12-11 13:18:17 +00:00
|
|
|
public function __construct( $geoIPServiceURL, HttpRequestFactory $httpRequestFactory ) {
|
2018-11-04 15:15:42 +00:00
|
|
|
if ( !is_string( $geoIPServiceURL ) || !$geoIPServiceURL ) {
|
|
|
|
throw new InvalidArgumentException( 'The geoIPServiceUL is invalid' );
|
|
|
|
}
|
|
|
|
$this->geoIPServiceURL = $geoIPServiceURL;
|
2022-12-11 13:18:17 +00:00
|
|
|
$this->httpRequestFactory = $httpRequestFactory;
|
2018-11-04 15:15:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
* @param string $ip The IP address to lookup
|
|
|
|
* @return string|null
|
|
|
|
*/
|
|
|
|
public function locate( $ip ) {
|
|
|
|
if ( isset( $this->locatedIPs[$ip] ) ) {
|
|
|
|
return $this->locatedIPs[$ip];
|
|
|
|
}
|
2020-03-14 09:01:36 +00:00
|
|
|
if ( !IPUtils::isValid( $ip ) ) {
|
2018-11-04 15:15:42 +00:00
|
|
|
throw new InvalidArgumentException( "$ip is not a valid IP address." );
|
|
|
|
}
|
|
|
|
if ( substr( $this->geoIPServiceURL, -1 ) !== '/' ) {
|
|
|
|
$this->geoIPServiceURL .= '/';
|
|
|
|
}
|
2022-12-11 13:18:17 +00:00
|
|
|
$json = $this->httpRequestFactory->get( $this->geoIPServiceURL . $ip, [
|
2018-11-04 15:15:42 +00:00
|
|
|
'timeout' => '2',
|
|
|
|
] );
|
|
|
|
if ( !$json ) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
$returnObject = json_decode( $json );
|
|
|
|
if ( $returnObject === null || !property_exists( $returnObject, 'country_code' ) ) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
$this->locatedIPs[$ip] = $returnObject->country_code;
|
|
|
|
|
|
|
|
return $this->locatedIPs[$ip];
|
|
|
|
}
|
|
|
|
}
|