diff --git a/public/iplookup/lib.php b/public/iplookup/lib.php index 2071ce2f7fc..361fc58565c 100644 --- a/public/iplookup/lib.php +++ b/public/iplookup/lib.php @@ -38,7 +38,11 @@ function iplookup_find_location($ip) { if (!empty($CFG->geoip2file) and file_exists($CFG->geoip2file)) { $reader = new GeoIp2\Database\Reader($CFG->geoip2file); - $record = $reader->city($ip); + try { + $record = $reader->city($ip); + } catch (GeoIp2\Exception\GeoIp2Exception $e) { + $record = null; + } if (empty($record)) { $info['error'] = get_string('iplookupfailed', 'error', $ip); diff --git a/public/iplookup/tests/geoip_test.php b/public/iplookup/tests/geoip_test.php index e136daa52d0..7fa85af7953 100644 --- a/public/iplookup/tests/geoip_test.php +++ b/public/iplookup/tests/geoip_test.php @@ -43,6 +43,27 @@ final class geoip_test extends \advanced_testcase { $CFG->geoip2file = "$CFG->dirroot/iplookup/tests/fixtures/GeoIP2-City-Test.mmdb"; } + /** + * Test that iplookup_find_location doesn't throw up GeoIp2 exceptions. + * + * @covers ::iplookup_find_location + */ + public function test_not_found_ip(): void { + $this->resetAfterTest(); + $this->setup_geoip2file(); + + $result = iplookup_find_location('10.0.0.1'); + + $this->assertIsArray($result); + $this->assertNull($result['latitude']); + $this->assertNull($result['longitude']); + $this->assertNull($result['city']); + $this->assertNull($result['country']); + $this->assertIsArray($result['title']); + $this->assertEmpty($result['title']); + $this->assertEquals('Cannot find geo information about this IP address 10.0.0.1', $result['error']); + } + /** * Test the format of data returned in the iplookup_find_location function. *