|
8 | 8 |
|
9 | 9 | class KmlValidator |
10 | 10 | { |
11 | | - protected string $namespace = 'http://www.opengis.net/kml/2.2'; |
| 11 | + /** |
| 12 | + * The namespaces a KML document is allowed to declare. |
| 13 | + * |
| 14 | + * 2.2 is the OGC standard. The earth.google.com variants predate the OGC |
| 15 | + * taking the format over, and exports carrying them are still in wide |
| 16 | + * circulation, so rejecting them outright rejects valid files. |
| 17 | + * |
| 18 | + * @var array<int, string> |
| 19 | + */ |
| 20 | + public const DEFAULT_NAMESPACES = [ |
| 21 | + 'http://www.opengis.net/kml/2.2', |
| 22 | + 'http://earth.google.com/kml/2.2', |
| 23 | + 'http://earth.google.com/kml/2.1', |
| 24 | + 'http://earth.google.com/kml/2.0', |
| 25 | + ]; |
| 26 | + |
| 27 | + /** @var array<int, string> */ |
| 28 | + protected array $namespaces; |
| 29 | + |
| 30 | + protected string $documentNamespace = ''; |
12 | 31 |
|
13 | 32 | protected SimpleXMLElement $xml; |
14 | 33 |
|
| 34 | + /** |
| 35 | + * @param array<int, string>|null $namespaces Accepted namespaces, defaults to DEFAULT_NAMESPACES. |
| 36 | + */ |
| 37 | + public function __construct(?array $namespaces = null) |
| 38 | + { |
| 39 | + $namespaces = array_values(array_filter($namespaces ?? self::DEFAULT_NAMESPACES)); |
| 40 | + |
| 41 | + $this->namespaces = $namespaces !== [] ? $namespaces : self::DEFAULT_NAMESPACES; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * The namespace declared by the document that was validated last. |
| 46 | + */ |
| 47 | + public function documentNamespace(): string |
| 48 | + { |
| 49 | + return $this->documentNamespace; |
| 50 | + } |
| 51 | + |
15 | 52 | /** |
16 | 53 | * Parse and validate raw KML content. |
17 | 54 | * |
@@ -46,11 +83,18 @@ public function validateDocument(SimpleXMLElement $xml): void |
46 | 83 | $this->xml = $xml; |
47 | 84 |
|
48 | 85 | $namespaces = $xml->getDocNamespaces(); |
49 | | - if (! isset($namespaces['']) || $namespaces[''] !== $this->namespace) { |
| 86 | + $declared = $namespaces[''] ?? null; |
| 87 | + |
| 88 | + if ($declared === null || ! in_array($declared, $this->namespaces, true)) { |
50 | 89 | throw new KmlException('Invalid or missing KML namespace'); |
51 | 90 | } |
52 | 91 |
|
53 | | - $xml->registerXPathNamespace('kml', $this->namespace); |
| 92 | + /* |
| 93 | + * XPath has to run against the namespace the document actually |
| 94 | + * declares, not the one we would have preferred it to use. |
| 95 | + */ |
| 96 | + $this->documentNamespace = $declared; |
| 97 | + $xml->registerXPathNamespace('kml', $declared); |
54 | 98 |
|
55 | 99 | if (empty($xml->Document)) { |
56 | 100 | throw new KmlException('Missing required element: Document'); |
|
0 commit comments