URIParser.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Parses a URI into the components and fragment identifier as specified
  4. * by RFC 3986.
  5. */
  6. class HTMLPurifier_URIParser
  7. {
  8. /**
  9. * Instance of HTMLPurifier_PercentEncoder to do normalization with.
  10. */
  11. protected $percentEncoder;
  12. public function __construct() {
  13. $this->percentEncoder = new HTMLPurifier_PercentEncoder();
  14. }
  15. /**
  16. * Parses a URI.
  17. * @param $uri string URI to parse
  18. * @return HTMLPurifier_URI representation of URI. This representation has
  19. * not been validated yet and may not conform to RFC.
  20. */
  21. public function parse($uri) {
  22. $uri = $this->percentEncoder->normalize($uri);
  23. // Regexp is as per Appendix B.
  24. // Note that ["<>] are an addition to the RFC's recommended
  25. // characters, because they represent external delimeters.
  26. $r_URI = '!'.
  27. '(([^:/?#"<>]+):)?'. // 2. Scheme
  28. '(//([^/?#"<>]*))?'. // 4. Authority
  29. '([^?#"<>]*)'. // 5. Path
  30. '(\?([^#"<>]*))?'. // 7. Query
  31. '(#([^"<>]*))?'. // 8. Fragment
  32. '!';
  33. $matches = array();
  34. $result = preg_match($r_URI, $uri, $matches);
  35. if (!$result) return false; // *really* invalid URI
  36. // seperate out parts
  37. $scheme = !empty($matches[1]) ? $matches[2] : null;
  38. $authority = !empty($matches[3]) ? $matches[4] : null;
  39. $path = $matches[5]; // always present, can be empty
  40. $query = !empty($matches[6]) ? $matches[7] : null;
  41. $fragment = !empty($matches[8]) ? $matches[9] : null;
  42. // further parse authority
  43. if ($authority !== null) {
  44. $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/";
  45. $matches = array();
  46. preg_match($r_authority, $authority, $matches);
  47. $userinfo = !empty($matches[1]) ? $matches[2] : null;
  48. $host = !empty($matches[3]) ? $matches[3] : '';
  49. $port = !empty($matches[4]) ? (int) $matches[5] : null;
  50. } else {
  51. $port = $host = $userinfo = null;
  52. }
  53. return new HTMLPurifier_URI(
  54. $scheme, $userinfo, $host, $port, $path, $query, $fragment);
  55. }
  56. }
  57. // vim: et sw=4 sts=4