functions.php: add caching to IP api checks

This commit is contained in:
Zankaria 2024-10-06 13:00:00 +02:00
parent a422122dd4
commit 61d58d7707

View file

@ -1845,6 +1845,12 @@ function checkIPAPI(string $ip): bool {
return false;
}
$ret = false;
if ($config['cache']['enabled']) {
$ret = cache::get("ip_api_block_$ip");
}
if ($ret === false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://v2.api.iphub.info/ip/$ip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@ -1854,23 +1860,56 @@ function checkIPAPI(string $ip): bool {
$curl_err = curl_error($ch);
curl_close($ch);
error_log("IPHub query failed: api call failed with curl error $curl_err");
if ($config['cache']['enabled']) {
// Store the result for 4 hours.
cache::set("ip_api_block_$ip", 'api_error', 14400);
}
return false;
}
curl_close($ch);
if (empty($reply)) {
error_log('IPHub query failed: api returned an empty response');
if ($config['cache']['enabled']) {
// Store the result for 4 hours.
cache::set("ip_api_block_$ip", 'api_error', 14400);
}
return false;
}
$json = json_decode($reply);
if (isset($json->error)) {
error_log("IPHub query failed: $json->error");
if ($config['cache']['enabled']) {
// Store the result for 4 hours.
cache::set("ip_api_block_$ip", 'api_error', 14400);
}
return false;
}
if ($json->block == 1
|| array_search($json->isp, $config['ip_api']['isp_blacklist']) !== false
|| array_search($json->asn, $config['ip_api']['asn_blacklist']) !== false) {
$ret = [
'block' => $json['block'],
'isp' => $json['isp'],
'asn' => $json['asn']
];
if ($config['cache']['enabled']) {
// Store the result for 2 days.
cache::set("ip_api_block_$ip", $ret, 172800);
}
} elseif (!is_array($ret)) {
// Cache previously reported an error, just return.
return false;
}
if ($ret['block'] == 1
|| array_search($ret['isp'], $config['ip_api']['isp_blacklist']) !== false
|| array_search($ret['asn'], $config['ip_api']['asn_blacklist']) !== false) {
error($config['error']['proxy']);
return true;
}