diff --git a/inc/functions.php b/inc/functions.php index 4a8aa053..b515ef29 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -1845,32 +1845,71 @@ function checkIPAPI(string $ip): bool { return false; } - $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); + $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); + 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); - error_log("IPHub query failed: api call failed with curl error $curl_err"); - return false; - } - curl_close($ch); - if (empty($reply)) { - error_log('IPHub query failed: api returned an empty response'); + 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; + } + + $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; } - $json = json_decode($reply); - if (isset($json->error)) { - error_log("IPHub query failed: $json->error"); - 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) { + 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; }