Refactor backend PHP code (#362)

* refactor getIP.php moving functionality into separate functions

* add some error checks

* remove closing php tags

* uniformly use single quotes for strings

most strings already used single quotes, some used double quotes

* refactor garbage moving functionality into functions
This commit is contained in:
Bernd Stellwag 2020-10-10 07:08:17 +02:00 committed by GitHub
parent d6877577d5
commit a69a70f5f4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 376 additions and 155 deletions

View file

@ -1,12 +1,14 @@
<?php
header( "HTTP/1.1 200 OK" );
if(isset($_GET["cors"])){
header('HTTP/1.1 200 OK');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Encoding, Content-Type');
}
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);
header("Pragma: no-cache");
header("Connection: keep-alive");
?>
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);
header('Pragma: no-cache');
header('Connection: keep-alive');

View file

@ -1,31 +1,63 @@
<?php
// Disable Compression
@ini_set('zlib.output_compression', 'Off');
@ini_set('output_buffering', 'Off');
@ini_set('output_handler', '');
// Headers
header('HTTP/1.1 200 OK');
if(isset($_GET["cors"])){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
/**
* @return int
*/
function getChunkCount()
{
if (
!array_key_exists('ckSize', $_GET)
|| !ctype_digit($_GET['ckSize'])
|| (int) $_GET['ckSize'] <= 0
) {
return 4;
}
if ((int) $_GET['ckSize'] > 1024) {
return 1024;
}
return (int) $_GET['ckSize'];
}
// Download follows...
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=random.dat');
header('Content-Transfer-Encoding: binary');
// Never cache me
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);
header('Pragma: no-cache');
/**
* @return void
*/
function sendHeaders()
{
header('HTTP/1.1 200 OK');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
// Indicate a file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=random.dat');
header('Content-Transfer-Encoding: binary');
// Cache settings: never cache this request
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);
header('Pragma: no-cache');
}
// Determine how much data we should send
$chunks = getChunkCount();
// Generate data
$data=openssl_random_pseudo_bytes(1048576);
$data = openssl_random_pseudo_bytes(1048576);
// Deliver chunks of 1048576 bytes
$chunks=isset($_GET['ckSize']) ? intval($_GET['ckSize']) : 4;
if(empty($chunks)){$chunks = 4;}
if($chunks>1024){$chunks = 1024;}
for($i=0;$i<$chunks;$i++){
sendHeaders();
for ($i = 0; $i < $chunks; $i++) {
echo $data;
flush();
}
?>

View file

@ -1,59 +1,171 @@
<?php
/*
This script detects the client's IP address and fetches ISP info from ipinfo.io/
Output from this script is a JSON string composed of 2 objects: a string called processedString which contains the combined IP, ISP, Contry and distance as it can be presented to the user; and an object called rawIspInfo which contains the raw data from ipinfo.io (will be empty if isp detection is disabled).
Client side, the output of this script can be treated as JSON or as regular text. If the output is regular text, it will be shown to the user as is.
*/
* This script detects the client's IP address and fetches ISP info from ipinfo.io/
* Output from this script is a JSON string composed of 2 objects: a string called processedString which contains the combined IP, ISP, Contry and distance as it can be presented to the user; and an object called rawIspInfo which contains the raw data from ipinfo.io (will be empty if isp detection is disabled).
* Client side, the output of this script can be treated as JSON or as regular text. If the output is regular text, it will be shown to the user as is.
*/
error_reporting(0);
$ip = "";
header('Content-Type: application/json; charset=utf-8');
if(isset($_GET["cors"])){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
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);
header('Pragma: no-cache');
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['X-Real-IP'])) {
$ip = $_SERVER['X-Real-IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = preg_replace("/,.*/", "", $ip); # hosts are comma-separated, client is first
} else {
$ip = $_SERVER['REMOTE_ADDR'];
define('API_KEY_FILE', 'getIP_ipInfo_apikey.php');
define('SERVER_LOCATION_CACHE_FILE', 'getIP_serverLocation.php');
/**
* @return string
*/
function getClientIp()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['X-Real-IP'])) {
$ip = $_SERVER['X-Real-IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip = preg_replace('/,.*/', '', $ip); # hosts are comma-separated, client is first
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return preg_replace('/^::ffff:/', '', $ip);
}
$ip = preg_replace("/^::ffff:/", "", $ip);
/**
* @param string $ip
*
* @return string|null
*/
function getLocalOrPrivateIpInfo($ip)
{
// ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
if ('::1' === $ip) {
return 'localhost IPv6 access';
}
if ($ip == "::1") { // ::1/128 is the only localhost ipv6 address. there are no others, no need to strpos this
echo json_encode(['processedString' => $ip . " - localhost IPv6 access", 'rawIspInfo' => ""]);
die();
// simplified IPv6 link-local address (should match fe80::/10)
if (stripos($ip, 'fe80:') === 0) {
return 'link-local IPv6 access';
}
// anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
if (strpos($ip, '127.') === 0) {
return 'localhost IPv4 access';
}
// 10/8 private IPv4
if (strpos($ip, '10.') === 0) {
return 'private IPv4 access';
}
// 172.16/12 private IPv4
if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) {
return 'private IPv4 access';
}
// 192.168/16 private IPv4
if (strpos($ip, '192.168.') === 0) {
return 'private IPv4 access';
}
// IPv4 link-local
if (strpos($ip, '169.254.') === 0) {
return 'link-local IPv4 access';
}
return null;
}
if (stripos($ip, 'fe80:') === 0) { // simplified IPv6 link-local address (should match fe80::/10)
echo json_encode(['processedString' => $ip . " - link-local IPv6 access", 'rawIspInfo' => ""]);
die();
/**
* @return string
*/
function getIpInfoTokenString()
{
if (!file_exists(API_KEY_FILE)) {
return '';
}
require API_KEY_FILE;
if (empty($IPINFO_APIKEY)) {
return '';
}
return '?token='.$IPINFO_APIKEY;
}
if (strpos($ip, '127.') === 0) { //anything within the 127/8 range is localhost ipv4, the ip must start with 127.0
echo json_encode(['processedString' => $ip . " - localhost IPv4 access", 'rawIspInfo' => ""]);
die();
/**
* @param string $ip
*
* @return array|null
*/
function getIspInfo($ip)
{
$json = file_get_contents('https://ipinfo.io/'.$ip.'/json'.getIpInfoTokenString());
if (!is_string($json)) {
return null;
}
$data = json_decode($json, true);
if (!is_array($data)) {
return null;
}
return $data;
}
if (strpos($ip, '10.') === 0) { // 10/8 private IPv4
echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]);
die();
/**
* @param array|null $rawIspInfo
*
* @return string
*/
function getIsp($rawIspInfo)
{
if (
!is_array($rawIspInfo)
|| !array_key_exists('org', $rawIspInfo)
|| !is_string($rawIspInfo['org'])
|| empty($rawIspInfo['org'])
) {
return 'Unknown ISP';
}
// Remove AS##### from ISP name, if present
return preg_replace('/AS\\d+\\s/', '', $rawIspInfo['org']);
}
if (preg_match('/^172\.(1[6-9]|2\d|3[01])\./', $ip) === 1) { // 172.16/12 private IPv4
echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]);
die();
}
if (strpos($ip, '192.168.') === 0) { // 192.168/16 private IPv4
echo json_encode(['processedString' => $ip . " - private IPv4 access", 'rawIspInfo' => ""]);
die();
}
if (strpos($ip, '169.254.') === 0) { // IPv4 link-local
echo json_encode(['processedString' => $ip . " - link-local IPv4 access", 'rawIspInfo' => ""]);
die();
/**
* @return string|null
*/
function getServerLocation()
{
$serverLoc = null;
if (file_exists(SERVER_LOCATION_CACHE_FILE)) {
require SERVER_LOCATION_CACHE_FILE;
}
if (is_string($serverLoc) && !empty($serverLoc)) {
return $serverLoc;
}
$json = file_get_contents('https://ipinfo.io/json'.getIpInfoTokenString());
if (!is_string($json)) {
return null;
}
$details = json_decode($json, true);
if (
!is_array($details)
|| !array_key_exists('loc', $details)
|| !is_string($details['loc'])
|| empty($details['loc'])
) {
return null;
}
$serverLoc = $details['loc'];
$cacheData = "<?php\n\n\$serverLoc = '".addslashes($serverLoc)."';\n";
file_put_contents(SERVER_LOCATION_CACHE_FILE, $cacheData);
return $serverLoc;
}
/**
@ -66,89 +178,163 @@ if (strpos($ip, '169.254.') === 0) { // IPv4 link-local
*
* @return float [km]
*/
function distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) {
function distance(
$latitudeFrom,
$longitudeFrom,
$latitudeTo,
$longitudeTo
) {
$rad = M_PI / 180;
$theta = $longitudeFrom - $longitudeTo;
$dist = sin($latitudeFrom * $rad) * sin($latitudeTo * $rad) + cos($latitudeFrom * $rad) * cos($latitudeTo * $rad) * cos($theta * $rad);
$dist = sin($latitudeFrom * $rad)
* sin($latitudeTo * $rad)
+ cos($latitudeFrom * $rad)
* cos($latitudeTo * $rad)
* cos($theta * $rad);
return acos($dist) / $rad * 60 * 1.853;
}
function getIpInfoTokenString(){
$apikeyFile="getIP_ipInfo_apikey.php";
if(!file_exists($apikeyFile)) return "";
require $apikeyFile;
if(empty($IPINFO_APIKEY)) return "";
return "?token=".$IPINFO_APIKEY;
}
if (isset($_GET["isp"])) {
$isp = "";
$rawIspInfo=null;
try {
$json = file_get_contents("https://ipinfo.io/" . $ip . "/json".getIpInfoTokenString());
$details = json_decode($json, true);
$rawIspInfo=$details;
if (array_key_exists("org", $details)){
$isp .= $details["org"];
$isp=preg_replace("/AS\d{1,}\s/","",$isp); //Remove AS##### from ISP name, if present
}else{
$isp .= "Unknown ISP";
}
if (array_key_exists("country", $details)){
$isp .= ", " . $details["country"];
}
$clientLoc = NULL;
$serverLoc = NULL;
if (array_key_exists("loc", $details)){
$clientLoc = $details["loc"];
}
if (isset($_GET["distance"])) {
if ($clientLoc) {
$locFile="getIP_serverLocation.php";
$serverLoc=null;
if(file_exists($locFile)){
require $locFile;
}else{
$json = file_get_contents("https://ipinfo.io/json".getIpInfoTokenString());
$details = json_decode($json, true);
if (array_key_exists("loc", $details)){
$serverLoc = $details["loc"];
}
if($serverLoc){
$lf=fopen($locFile,"w");
fwrite($lf,chr(60)."?php\n");
fwrite($lf,'$serverLoc="'.addslashes($serverLoc).'";');
fwrite($lf,"\n");
fwrite($lf,"?".chr(62));
fclose($lf);
}
}
if ($serverLoc) {
try {
$clientLoc = explode(",", $clientLoc);
$serverLoc = explode(",", $serverLoc);
$dist = distance($clientLoc[0], $clientLoc[1], $serverLoc[0], $serverLoc[1]);
if ($_GET["distance"] == "mi") {
$dist /= 1.609344;
$dist = round($dist, -1);
if ($dist < 15)
$dist = "<15";
$isp .= " (" . $dist . " mi)";
}else if ($_GET["distance"] == "km") {
$dist = round($dist, -1);
if ($dist < 20)
$dist = "<20";
$isp .= " (" . $dist . " km)";
}
} catch (Exception $e) {
}
}
}
}
} catch (Exception $ex) {
$isp = "Unknown ISP";
/**
* @param array|null $rawIspInfo
*
* @return string|null
*/
function getDistance($rawIspInfo)
{
if (
!is_array($rawIspInfo)
|| !array_key_exists('loc', $rawIspInfo)
|| !isset($_GET['distance'])
|| !in_array($_GET['distance'], ['mi', 'km'], true)
) {
return null;
}
echo json_encode(['processedString' => $ip . " - " . $isp, 'rawIspInfo' => $rawIspInfo]);
} else {
echo json_encode(['processedString' => $ip, 'rawIspInfo' => ""]);
$unit = $_GET['distance'];
$clientLocation = $rawIspInfo['loc'];
$serverLocation = getServerLocation();
if (!is_string($serverLocation)) {
return null;
}
return calculateDistance(
$serverLocation,
$clientLocation,
$unit
);
}
?>
/**
* @param string $clientLocation
* @param string $serverLocation
* @param string $unit
*
* @return string
*/
function calculateDistance($clientLocation, $serverLocation, $unit)
{
list($clientLatitude, $clientLongitude) = explode(',', $clientLocation);
list($serverLatitude, $serverLongitude) = explode(',', $serverLocation);
$dist = distance(
$clientLatitude,
$clientLongitude,
$serverLatitude,
$serverLongitude
);
if ('mi' === $unit) {
$dist /= 1.609344;
$dist = round($dist, -1);
if ($dist < 15) {
$dist = '<15';
}
return $dist.' mi';
}
if ('km' === $unit) {
$dist = round($dist, -1);
if ($dist < 20) {
$dist = '<20';
}
return $dist.' km';
}
return null;
}
/**
* @return void
*/
function sendHeaders()
{
header('Content-Type: application/json; charset=utf-8');
if (isset($_GET['cors'])) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
}
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);
header('Pragma: no-cache');
}
/**
* @param string $ip
* @param string|null $ipInfo
* @param string|null $distance
* @param array|null $rawIspInfo
*
* @return void
*/
function sendResponse(
$ip,
$ipInfo = null,
$distance = null,
$rawIspInfo = null
) {
$processedString = $ip;
if (is_string($ipInfo)) {
$processedString .= ' - '.$ipInfo;
}
if (
is_array($rawIspInfo)
&& array_key_exists('country', $rawIspInfo)
) {
$processedString .= ', '.$rawIspInfo['country'];
}
if (is_string($distance)) {
$processedString .= ' ('.$distance.')';
}
sendHeaders();
echo json_encode([
'processedString' => $processedString,
'rawIspInfo' => $rawIspInfo ?: '',
]);
}
$ip = getClientIp();
$localIpInfo = getLocalOrPrivateIpInfo($ip);
// local ip, no need to fetch further information
if (is_string($localIpInfo)) {
sendResponse($ip, $localIpInfo);
exit;
}
if (!isset($_GET['isp'])) {
sendResponse($ip);
exit;
}
$rawIspInfo = getIspInfo($ip);
$isp = getIsp($rawIspInfo);
$distance = getDistance($rawIspInfo);
sendResponse($ip, $isp, $distance, $rawIspInfo);

View file

@ -1,3 +1,4 @@
<?php
$IPINFO_APIKEY=""; //put your token between the quotes if you have one
?>
// put your token between the quotes if you have one
$IPINFO_APIKEY = '';