Commit IPv6 fix, with majoring factoring out. Thank you Feyd!
[htmlpurifier.git] / library / HTMLPurifier / AttrDef / IPv6.php
blob70cbf79dd859471862fcd41ab020e93158d70704
1 <?php
3 require_once 'HTMLPurifier/AttrDef/IPv4.php';
5 // IPv6 by Feyd, source is in public domain
7 // note that this expects the brackets to be removed from IPv6 addresses
8 // extends from the IPv4 impl. so we can borrow its regex
10 class HTMLPurifier_AttrDef_IPv6 extends HTMLPurifier_AttrDef_IPv4
13 function validate($aIP, $config, &$context) {
15 $original = $aIP;
17 $hex = '[0-9a-fA-F]';
18 $blk = '(?:' . $hex . '{1,4})';
19 $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128
21 // prefix check
22 if (strpos($aIP, '/') !== false)
24 if (preg_match('#' . $pre . '$#s', $aIP, $find))
26 $aIP = substr($aIP, 0, 0-strlen($find[0]));
27 unset($find);
29 else
31 return false;
35 // IPv4-compatiblity check
36 if (preg_match('#(?<=:'.')' . $this->ip4 . '$#s', $aIP, $find))
38 $aIP = substr($aIP, 0, 0-strlen($find[0]));
39 $ip = explode('.', $find[0]);
40 $ip = array_map('dechex', $ip);
41 $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];
42 unset($find, $ip);
45 // compression check
46 $aIP = explode('::', $aIP);
47 $c = count($aIP);
48 if ($c > 2)
50 return false;
52 elseif ($c == 2)
54 list($first, $second) = $aIP;
55 $first = explode(':', $first);
56 $second = explode(':', $second);
58 if (count($first) + count($second) > 8)
60 return false;
63 while(count($first) < 8)
65 array_push($first, '0');
68 array_splice($first, 8 - count($second), 8, $second);
69 $aIP = $first;
70 unset($first,$second);
72 else
74 $aIP = explode(':', $aIP[0]);
76 $c = count($aIP);
78 if ($c != 8)
80 return false;
83 // All the pieces should be 16-bit hex strings. Are they?
84 foreach ($aIP as $piece)
86 if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece)))
88 return false;
92 return $original;