forked from kokororin/typecho-plugin-Access
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Access_Ip.php
89 lines (68 loc) · 2.53 KB
/
Access_Ip.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
if (!defined('__ACCESS_PLUGIN_ROOT__')) {
throw new Exception('Boostrap file not found');
}
class Access_Ip
{
private static $ip = null;
private static $fp = null;
private static $offset = null;
private static $index = null;
private static $cached = array();
public static function find($ip)
{
if (empty($ip) === true) {
return 'N/A';
}
$nip = gethostbyname($ip);
$ipdot = explode('.', $nip);
if ($ipdot[0] < 0 || $ipdot[0] > 255 || count($ipdot) !== 4) {
return 'N/A';
}
if (isset(self::$cached[$nip]) === true) {
return self::$cached[$nip];
}
if (self::$fp === null) {
self::init();
}
$nip2 = pack('N', ip2long($nip));
$tmp_offset = (int) $ipdot[0] * 4;
$start = unpack('Vlen', self::$index[$tmp_offset] . self::$index[$tmp_offset + 1] . self::$index[$tmp_offset + 2] . self::$index[$tmp_offset + 3]);
$index_offset = $index_length = null;
$max_comp_len = self::$offset['len'] - 1024 - 4;
for ($start = $start['len'] * 8 + 1024; $start < $max_comp_len; $start += 8) {
if (self::$index{$start} . self::$index{$start + 1} . self::$index{$start + 2} . self::$index{$start + 3} >= $nip2) {
$index_offset = unpack('Vlen', self::$index{$start + 4} . self::$index{$start + 5} . self::$index{$start + 6} . "\x0");
$index_length = unpack('Clen', self::$index{$start + 7});
break;
}
}
if ($index_offset === null) {
return 'N/A';
}
fseek(self::$fp, self::$offset['len'] + $index_offset['len'] - 1024);
self::$cached[$nip] = explode("\t", fread(self::$fp, $index_length['len']));
return self::$cached[$nip];
}
private static function init()
{
if (self::$fp === null) {
self::$ip = new self();
self::$fp = fopen(__ACCESS_PLUGIN_ROOT__ . '/lib/17monipdb.dat', 'rb');
if (self::$fp === false) {
throw new Exception('Invalid 17monipdb.dat file!');
}
self::$offset = unpack('Nlen', fread(self::$fp, 4));
if (self::$offset['len'] < 4) {
throw new Exception('Invalid 17monipdb.dat file!');
}
self::$index = fread(self::$fp, self::$offset['len'] - 4);
}
}
public function __destruct()
{
if (self::$fp !== null) {
fclose(self::$fp);
}
}
}