forked from simplesamlphp/xml-common
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXPath.php
More file actions
262 lines (222 loc) · 9.34 KB
/
XPath.php
File metadata and controls
262 lines (222 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<?php
declare(strict_types=1);
namespace SimpleSAML\XPath;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMXPath;
use RuntimeException;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Constants as C_XML;
use SimpleSAML\XMLSchema\Constants as C_XS;
/**
* XPath helper functions for the XML library.
*
* @package simplesamlphp/xml-common
*/
class XPath
{
/**
* Search for an element with a certain name among the children of a reference element.
*
* @param \DOMNode $ref The DOMDocument or DOMElement where encrypted data is expected to be found as a child.
* @param string $name The name (possibly prefixed) of the element we are looking for.
*
* @return \DOMElement|false The element we are looking for, or false when not found.
*
* @throws \RuntimeException If no DOM document is available.
*/
public static function findElement(DOMNode $ref, string $name): DOMElement|false
{
$doc = $ref instanceof DOMDocument ? $ref : $ref->ownerDocument;
if ($doc === null) {
throw new RuntimeException('Cannot search, no DOMDocument available');
}
$nodeset = self::getXPath($doc)->query('./' . $name, $ref);
return $nodeset->item(0) ?? false;
}
/**
* Get an instance of DOMXPath associated with a DOMNode
*
* - Reuses a cached DOMXPath per document.
* - Registers core XML-related namespaces: 'xml' and 'xs'.
* - Enriches the XPath with all prefixed xmlns declarations found on the
* current node and its ancestors (up to the document element), so
* custom prefixes declared anywhere up the tree can be used in queries.
*
* @param \DOMNode $node The associated node
* @param bool $autoregister Whether to scan descendant nodes for additional namespace declarations
* @return \DOMXPath
*/
public static function getXPath(DOMNode $node, bool $autoregister = false): DOMXPath
{
static $xpCache = null;
if ($node instanceof DOMDocument) {
$doc = $node;
} else {
$doc = $node->ownerDocument;
Assert::notNull($doc);
}
if ($xpCache === null || !$xpCache->document->isSameNode($doc)) {
$xpCache = new DOMXPath($doc);
}
$xpCache->registerNamespace('xml', C_XML::NS_XML);
$xpCache->registerNamespace('xs', C_XS::NS_XS);
// Enrich with ancestor-declared prefixes for this document context.
$prefixToUri = self::registerAncestorNamespaces($xpCache, $node);
if ($autoregister) {
// Single, bounded subtree scan to pick up descendant-only declarations.
self::registerSubtreePrefixes($xpCache, $node, $prefixToUri);
}
return $xpCache;
}
/**
* Walk from the given node up to the document element, registering all prefixed xmlns declarations.
*
* Safety:
* - Only attributes in the XMLNS namespace (http://www.w3.org/2000/xmlns/).
* - Skip default xmlns (localName === 'xmlns') because XPath requires prefixes.
* - Skip empty URIs.
* - Do not override core 'xml' and 'xs' prefixes (already bound).
* - Nearest binding wins during this pass (prefixes are added once).
*
* @param \DOMXPath $xp
* @param \DOMNode $node
* @return array<string,string> Map of prefix => namespace URI that are bound after this pass
*/
private static function registerAncestorNamespaces(DOMXPath $xp, DOMNode $node): array
{
// Track prefix => uri to feed into subtree scan. Seed with core bindings.
$prefixToUri = [
'xml' => C_XML::NS_XML,
'xs' => C_XS::NS_XS,
];
// Start from the nearest element (or documentElement if a DOMDocument is passed).
$current = $node instanceof DOMDocument
? $node->documentElement
: ($node instanceof DOMElement ? $node : $node->parentNode);
$steps = 0;
while ($current instanceof DOMElement) {
if (++$steps > C_XML::UNBOUNDED_LIMIT) {
throw new RuntimeException(__METHOD__ . ': exceeded ancestor traversal limit');
}
if ($current->hasAttributes()) {
foreach ($current->attributes as $attr) {
if ($attr->namespaceURI !== C_XML::NS_XMLNS) {
continue;
}
$prefix = $attr->localName;
$uri = (string) $attr->nodeValue;
if (
$prefix === null || $prefix === '' ||
$prefix === 'xmlns' || $uri === '' ||
isset($prefixToUri[$prefix])
) {
continue;
}
$xp->registerNamespace($prefix, $uri);
$prefixToUri[$prefix] = $uri;
}
}
$current = $current->parentNode;
}
return $prefixToUri;
}
/**
* Single-pass subtree scan from the context element to bind prefixes used only on descendants.
* - Never rebind an already-registered prefix (collision-safe).
* - Skips 'xmlns' and empty URIs.
* - Bounded by UNBOUNDED_LIMIT.
*
* @param \DOMXPath $xp
* @param \DOMNode $node
* @param array<string,string> $prefixToUri
*/
private static function registerSubtreePrefixes(DOMXPath $xp, DOMNode $node, array $prefixToUri): void
{
$root = $node instanceof DOMDocument
? $node->documentElement
: ($node instanceof DOMElement ? $node : $node->parentNode);
if (!$root instanceof DOMElement) {
return;
}
// $visited = 0;
/** @var array<array{0:\DOMElement,1:int}> $queue */
$queue = [[$root, 0]];
while ($queue) {
/** @var \DOMElement $el */
/** @var int $depth */
[$el, $depth] = array_shift($queue);
// Depth guard: cap traversal at UNBOUNDED_LIMIT (root = depth 0).
// Breaking here halts further descent to avoid pathological depth and excessive work,
// which is safer in production than risking runaway traversal or hard failures.
// Trade-off: deeper descendant-only prefixes may remain unregistered, so some
// prefixed XPath queries might fail; overall processing continues gracefully.
if ($depth >= C_XML::UNBOUNDED_LIMIT) {
break;
}
// if (++$visited > C_XML::UNBOUNDED_LIMIT) {
// // Safety valve: stop further traversal to avoid unbounded work and noisy exceptions.
// // Returning here halts namespace registration for this subtree, which is safer in
// // production than risking pathological O(n) behavior or a hard failure (e.g. throwing
// // \RuntimeException(__METHOD__ . ': exceeded subtree traversal limit')).
// // Trade-off: some descendant-only prefixes may remain unregistered, so related XPath
// // queries might fail, but overall processing continues gracefully.
// break;
// }
// Element prefix
if ($el->prefix && !isset($prefixToUri[$el->prefix])) {
$uri = $el->namespaceURI;
if (is_string($uri) && $uri !== '') {
$xp->registerNamespace($el->prefix, $uri);
$prefixToUri[$el->prefix] = $uri;
}
}
// Attribute prefixes (excluding xmlns)
if ($el->hasAttributes()) {
foreach ($el->attributes as $attr) {
if (
$attr->prefix &&
$attr->prefix !== 'xmlns' &&
!isset($prefixToUri[$attr->prefix])
) {
$uri = $attr->namespaceURI;
if (is_string($uri) && $uri !== '') {
$xp->registerNamespace($attr->prefix, $uri);
$prefixToUri[$attr->prefix] = $uri;
}
} else {
// Optional: collision detection (same prefix, different URI)
// if ($prefixToUri[$pfx] !== $attr->namespaceURI) {
// // Default: skip rebind; could log a debug message here.
// }
}
}
}
// Enqueue children (only DOMElement to keep types precise)
foreach ($el->childNodes as $child) {
if ($child instanceof DOMElement) {
$queue[] = [$child, $depth + 1];
}
}
}
}
/**
* Do an XPath query on an XML node.
*
* @param \DOMNode $node The XML node.
* @param string $query The query.
* @param \DOMXPath $xpCache The DOMXPath object
* @return array<\DOMNode> Array with matching DOM nodes.
*/
public static function xpQuery(DOMNode $node, string $query, DOMXPath $xpCache): array
{
$ret = [];
$results = $xpCache->query($query, $node);
Assert::notFalse($results, 'Malformed XPath query or invalid contextNode provided.');
for ($i = 0; $i < $results->length; $i++) {
$ret[$i] = $results->item($i);
}
return $ret;
}
}