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,32 +1845,71 @@ function checkIPAPI(string $ip): bool {
return false; return false;
} }
$ch = curl_init(); $ret = false;
curl_setopt($ch, CURLOPT_URL, "http://v2.api.iphub.info/ip/$ip"); if ($config['cache']['enabled']) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $ret = cache::get("ip_api_block_$ip");
curl_setopt($ch, CURLOPT_HTTPHEADER, [ "X-Key: $iphub_key" ]); }
$reply = curl_exec($ch);
if ($reply === false) { if ($ret === false) {
$curl_err = curl_error($ch); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://v2.api.iphub.info/ip/$ip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [ "X-Key: $iphub_key" ]);
$reply = curl_exec($ch);
if ($reply === false) {
$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); curl_close($ch);
error_log("IPHub query failed: api call failed with curl error $curl_err"); if (empty($reply)) {
return false; error_log('IPHub query failed: api returned an empty response');
}
curl_close($ch); if ($config['cache']['enabled']) {
if (empty($reply)) { // Store the result for 4 hours.
error_log('IPHub query failed: api returned an empty response'); 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;
}
$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; return false;
} }
$json = json_decode($reply); if ($ret['block'] == 1
if (isset($json->error)) { || array_search($ret['isp'], $config['ip_api']['isp_blacklist']) !== false
error_log("IPHub query failed: $json->error"); || array_search($ret['asn'], $config['ip_api']['asn_blacklist']) !== false) {
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) {
error($config['error']['proxy']); error($config['error']['proxy']);
return true; return true;
} }