94 lines
No EOL
2.4 KiB
PHP
94 lines
No EOL
2.4 KiB
PHP
<?php
|
|
|
|
/**
|
|
*
|
|
* DB-IP.com database query and management class
|
|
*
|
|
* Copyright (C) 2022 db-ip.com
|
|
*
|
|
* This library is free software; you can redistribute it and/or
|
|
* modify it under the terms of the GNU Lesser General Public
|
|
* License as published by the Free Software Foundation; either
|
|
* version 2.1 of the License, or (at your option) any later version.
|
|
*
|
|
* This library is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
* Lesser General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU Lesser General Public
|
|
* License along with this library; if not, write to the Free Software
|
|
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|
*
|
|
*/
|
|
|
|
namespace App\Services\dbip;
|
|
|
|
use PDO;
|
|
use Exception;
|
|
use PDOException;
|
|
use App\Models\DbipLookup;
|
|
use App\Models\DbipLookup2;
|
|
use App\Models\DbipLookup3;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
|
|
class DBIPException extends Exception {
|
|
|
|
}
|
|
|
|
class MyDBIP {
|
|
|
|
const VERSION = 4;
|
|
|
|
|
|
static public function lookup($addr) {
|
|
if ($ret = self::doLookup(self::addrType($addr), inet_pton($addr))) {
|
|
return $ret;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static public function doLookup($addrType, $addrStart) {
|
|
|
|
$res = DbipLookup::where('addr_type', $addrType)->where('ip_start', '<=', $addrStart)->orderBy('ip_start', 'desc')->first();
|
|
$c1 = isset($res->country) ? $res->country : null;
|
|
|
|
$res = DbipLookup2::where('addr_type', $addrType)->where('ip_start', '<=', $addrStart)->orderBy('ip_start', 'desc')->first();
|
|
$c2 = isset($res->country) ? $res->country : null;
|
|
|
|
if($c1 == $c2){
|
|
return $c1;
|
|
}
|
|
|
|
$res = DbipLookup3::where('addr_type', $addrType)->where('ip_start', '<=', $addrStart)->orderBy('ip_start', 'desc')->first();
|
|
if(isset($res->country)){
|
|
return $res->country;
|
|
}
|
|
|
|
//look in api
|
|
|
|
return false;
|
|
}
|
|
|
|
static private function addrType($addr) {
|
|
if (ip2long($addr) !== false) {
|
|
return "ipv4";
|
|
} else if (preg_match('/^[0-9a-fA-F:]+$/', $addr) && @inet_pton($addr)) {
|
|
return "ipv6";
|
|
}
|
|
throw new DBIPException("unknown address type for {$addr}");
|
|
}
|
|
|
|
static public function insert($addr, $country) {
|
|
|
|
$lookup = new DbipLookup3();
|
|
$lookup->addr_type = self::addrType($addr);
|
|
$lookup->ip_start = inet_pton($addr);
|
|
$lookup->ip_end = inet_pton($addr);
|
|
$lookup->country = strtoupper($country);
|
|
$lookup->save();
|
|
|
|
}
|
|
|
|
} |