Host.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // empty hostname is OK; it's usually semantically equivalent:
  22. // the default host as defined by a URI scheme is used:
  23. //
  24. // If the URI scheme defines a default for host, then that
  25. // default applies when the host subcomponent is undefined
  26. // or when the registered name is empty (zero length).
  27. if ($string === '') return '';
  28. if ($length > 1 && $string[0] === '[' && $string[$length-1] === ']') {
  29. //IPv6
  30. $ip = substr($string, 1, $length - 2);
  31. $valid = $this->ipv6->validate($ip, $config, $context);
  32. if ($valid === false) return false;
  33. return '['. $valid . ']';
  34. }
  35. // need to do checks on unusual encodings too
  36. $ipv4 = $this->ipv4->validate($string, $config, $context);
  37. if ($ipv4 !== false) return $ipv4;
  38. // A regular domain name.
  39. // This breaks I18N domain names, but we don't have proper IRI support,
  40. // so force users to insert Punycode. If there's complaining we'll
  41. // try to fix things into an international friendly form.
  42. // The productions describing this are:
  43. $a = '[a-z]'; // alpha
  44. $an = '[a-z0-9]'; // alphanum
  45. $and = '[a-z0-9-]'; // alphanum | "-"
  46. // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  47. $domainlabel = "$an($and*$an)?";
  48. // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
  49. $toplabel = "$a($and*$an)?";
  50. // hostname = *( domainlabel "." ) toplabel [ "." ]
  51. $match = preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string);
  52. if (!$match) return false;
  53. return $string;
  54. }
  55. }
  56. // vim: et sw=4 sts=4