From c86570f0f11ccd697b6b74144bf939552229ac53 Mon Sep 17 00:00:00 2001 From: Mespeet Date: Wed, 2 Oct 2024 02:53:44 +0200 Subject: [PATCH] Improved code structure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Improved the overall code structure of backend/getIp.php. Really suggest going with a more oop based code tbh but I guess this works. ㄟ( ▔, ▔ )ㄏ --- backend/getIP.php | 308 +++++++++++++++++++++------------------------- 1 file changed, 141 insertions(+), 167 deletions(-) diff --git a/backend/getIP.php b/backend/getIP.php index d7bc4fa81..d7f018af4 100755 --- a/backend/getIP.php +++ b/backend/getIP.php @@ -1,9 +1,10 @@ ['timeout' => 5]]; + $context = stream_context_create($options); + $response = @file_get_contents($url, false, $context); + + if ($response === false) return null; + + $data = json_decode($response, true); + if (!is_array($data)) return null; + + $isp = $data['org'] ?? $data['asn']['name'] ?? null; + $isp = preg_replace('/AS\\d+\\s/', '', $isp); // Clean up AS info + + $country = $data['country'] ?? null; + + $distance = calculateDistance($data['loc'] ?? '', $ip); + + $processedString = buildProcessedString($ip, $isp, $country, $distance); + + return [ 'processedString' => $processedString, - 'rawIspInfo' => $data ?: '', - ]); + 'rawIspInfo' => $data, + ]; } -if (PHP_MAJOR_VERSION >= 8){ - require_once("geoip2.phar"); -} -function getIspInfo_ipinfoOfflineDb($ip){ - if (PHP_MAJOR_VERSION < 8 || !file_exists(OFFLINE_IPINFO_DB_FILE) || !is_readable(OFFLINE_IPINFO_DB_FILE)){ - return null; - } - $reader = new MaxMind\Db\Reader(OFFLINE_IPINFO_DB_FILE); - $data = $reader->get($ip); - if(!is_array($data)){ - return null; +/** + * Calculate the distance between the client and server based on location data. + * @param string $clientLoc + * @param string $ip + * @return string|null + */ +function calculateDistance(string $clientLoc, string $ip): ?string { + if (!isset($_GET['distance']) || empty($clientLoc)) return null; + + $unit = $_GET['distance']; + if ($unit !== 'mi' && $unit !== 'km') return null; + + $serverLoc = getServerLocation(); + if (empty($serverLoc)) return null; + + [$clientLatitude, $clientLongitude] = explode(',', $clientLoc); + [$serverLatitude, $serverLongitude] = explode(',', $serverLoc); + + // Calculate distance using haversine formula + $rad = M_PI / 180; + $dist = acos(sin($clientLatitude * $rad) * sin($serverLatitude * $rad) + + cos($clientLatitude * $rad) * cos($serverLatitude * $rad) + * cos(($clientLongitude - $serverLongitude) * $rad)) * 60 * 1.853; + + if ($unit === 'mi') { + $dist /= 1.609344; + $dist = round($dist, -1); + $distance = $dist < 15 ? '<15 mi' : "{$dist} mi"; + } else { + $dist = round($dist, -1); + $distance = $dist < 20 ? '<20 km' : "{$dist} km"; } - $processedString = $ip.' - ' . $data['as_name'] . ', ' . $data['country_name']; - return json_encode([ - 'processedString' => $processedString, - 'rawIspInfo' => $data ?: '', - ]); + + return $distance; } -function formatResponse_simple($ip,$ispName=null){ - $processedString=$ip; - if(is_string($ispName)){ - $processedString.=' - '.$ispName; +/** + * Get server location for distance calculation. + * @return string|null + */ +function getServerLocation(): ?string { + if (file_exists(SERVER_LOCATION_CACHE_FILE) && is_readable(SERVER_LOCATION_CACHE_FILE)) { + require SERVER_LOCATION_CACHE_FILE; + return $serverLoc ?? null; } - return json_encode([ - 'processedString' => $processedString, - 'rawIspInfo' => '', - ]); + return null; } -header('Content-Type: application/json; charset=utf-8'); -if (isset($_GET['cors'])) { - header('Access-Control-Allow-Origin: *'); - header('Access-Control-Allow-Methods: GET, POST'); +/** + * Build the processed string with IP, ISP, country, and distance. + * @param string $ip + * @param string|null $isp + * @param string|null $country + * @param string|null $distance + * @return string + */ +function buildProcessedString(string $ip, ?string $isp, ?string $country, ?string $distance): string { + $output = $ip; + if ($isp) $output .= " - $isp"; + if ($country) $output .= ", $country"; + if ($distance) $output .= " ($distance)"; + return $output; } -header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, s-maxage=0'); -header('Cache-Control: post-check=0, pre-check=0', false); + +/** + * Simple IP response if ISP detection is not requested or fails. + * @param string $ip + * @param string|null $ispName + * @return array + */ +function formatSimpleResponse(string $ip, ?string $ispName = null): array { + $processedString = $ispName ? "$ip - $ispName" : $ip; + return ['processedString' => $processedString, 'rawIspInfo' => '']; +} + +// Response handling +header('Content-Type: application/json; charset=utf-8'); +header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Pragma: no-cache'); $ip = getClientIp(); -//if the user requested the ISP info, we first try to fetch it using ipinfo.io (if there is no api key set it fails without sending data, it can also fail because of rate limiting or invalid responses), then we try with the offline db, if that also fails (or if ISP info was not requested) we just respond with the IP address -if(isset($_GET['isp'])){ + +if (isset($_GET['isp'])) { $localIpInfo = getLocalOrPrivateIpInfo($ip); - //local ip, no need to fetch further information - if (is_string($localIpInfo)) { - echo formatResponse_simple($ip,$localIpInfo); - }else{ - $r=getIspInfo_ipinfoApi($ip); - if(!is_null($r)){ - echo $r; - }else{ - $r=getIspInfo_ipinfoOfflineDb($ip); - if(!is_null($r)){ - echo $r; - }else{ - echo formatResponse_simple($ip); - } - } - } -}else{ - echo formatResponse_simple($ip); -} + if ($localIpInfo) { + echo json_encode(formatSimpleResponse($ip, $localIpInfo)); + } else { + $ispInfo = getIspInfo_ipinfoApi($ip); + echo json_encode($ispInfo ?? formatSimpleResponse($ip)); + } +} else { + echo json_encode(formatSimpleResponse($ip)); +} \ No newline at end of file