Host.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * Validates a host according to the IPv4, IPv6 and DNS (future) specifications.
  4. */
  5. class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef
  6. {
  7. /**
  8. * Instance of HTMLPurifier_AttrDef_URI_IPv4 sub-validator
  9. */
  10. protected $ipv4;
  11. /**
  12. * Instance of HTMLPurifier_AttrDef_URI_IPv6 sub-validator
  13. */
  14. protected $ipv6;
  15. public function __construct() {
  16. $this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();
  17. $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();
  18. }
  19. public function validate($string, $config, $context) {
  20. $length = strlen($string);
  21. if ($string === '') return '';
  22. if ($length > 1 && $string[0] === '[' && $string[$length-1] === ']') {
  23. //IPv6
  24. $ip = substr($string, 1, $length - 2);
  25. $valid = $this->ipv6->validate($ip, $config, $context);
  26. if ($valid === false) return false;
  27. return '['. $valid . ']';
  28. }
  29. // need to do checks on unusual encodings too
  30. $ipv4 = $this->ipv4->validate($string, $config, $context);
  31. if ($ipv4 !== false) return $ipv4;
  32. // A regular domain name.
  33. // This breaks I18N domain names, but we don't have proper IRI support,
  34. // so force users to insert Punycode. If there's complaining we'll
  35. // try to fix things into an international friendly form.
  36. // The productions describing this are:
  37. $a = '[a-z]'; // alpha
  38. $an = '[a-z0-9]'; // alphanum
  39. $and = '[a-z0-9-]'; // alphanum | "-"
  40. // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  41. $domainlabel = "$an($and*$an)?";
  42. // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
  43. $toplabel = "$a($and*$an)?";
  44. // hostname = *( domainlabel "." ) toplabel [ "." ]
  45. $match = preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string);
  46. if (!$match) return false;
  47. return $string;
  48. }
  49. }
  50. // vim: et sw=4 sts=4