-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathAbstractHtmlNodeProcessor.class.php
More file actions
450 lines (386 loc) · 14.7 KB
/
AbstractHtmlNodeProcessor.class.php
File metadata and controls
450 lines (386 loc) · 14.7 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<?php
namespace wcf\system\html\node;
use wcf\system\html\IHtmlProcessor;
/**
* Default implementation for html node processors.
*
* @author Alexander Ebert
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @since 3.0
*/
abstract class AbstractHtmlNodeProcessor implements IHtmlNodeProcessor
{
/**
* active DOM document
* @var \DOMDocument
*/
protected $document;
/**
* html processor instance
* @var IHtmlProcessor
*/
protected $htmlProcessor;
/**
* required interface for html nodes
* @var string
*/
protected $nodeInterface = '';
/**
* storage for node replacements
* @var list<array{data: array<string, mixed>, identifier: string, object: IHtmlNode}>
*/
protected $nodeData = [];
/**
* XPath instance
* @var ?\DOMXPath
*/
protected $xpath;
/**
* @inheritDoc
*/
public function load(IHtmlProcessor $htmlProcessor, $html)
{
$this->htmlProcessor = $htmlProcessor;
$this->document = new \DOMDocument('1.0', 'UTF-8');
$this->xpath = null;
$html = $this->maskLineBreaksInsideCode($html);
// strip UTF-8 zero-width whitespace
$html = \preg_replace('~\x{200B}~u', '', $html);
// discard any non-breaking spaces
$html = \str_replace(' ', ' ', $html);
// work-around for a libxml bug that causes a single space between
// some inline elements to be dropped
$html = \str_replace('> <', '> <', $html);
// Ignore all errors when loading the HTML string, because DOMDocument does not
// provide a proper way to add custom HTML elements (even though explicitly allowed
// in HTML5) and the input HTML has already been sanitized by HTMLPurifier.
//
// We're also injecting a bogus meta tag that magically enables DOMDocument
// to handle UTF-8 properly. This avoids encoding non-ASCII characters as it
// would conflict with already existing entities when reverting them.
$useInternalErrors = \libxml_use_internal_errors(true);
$this->document->loadHTML(
'<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $html . '</body></html>'
);
// flush libxml's error buffer, after all we don't care for any errors caused
// by the `loadHTML()` call above anyway
\libxml_clear_errors();
\libxml_use_internal_errors($useInternalErrors);
// fix the `<pre>` linebreaks again
$pres = $this->document->getElementsByTagName('pre');
for ($i = 0, $length = $pres->length; $i < $length; $i++) {
/** @var \DOMNode $node */
foreach ($this->getXPath()->query('./text()', $pres->item($i)) as $node) {
if (\str_contains($node->textContent, '@@@WCF_PRE_LINEBREAK@@@')) {
$node->nodeValue = \str_replace('@@@WCF_PRE_LINEBREAK@@@', "\n", $node->textContent);
}
}
}
$this->nodeData = [];
}
/**
* Replaces line breaks inside code blocks with a symbol to prevent them
* being mangled by libxml.
*
* This method splits up the HTML into chunks that effectively end with
* `</pre>`. This allows us to use a simple regex to find the start of the
* pre tag and treating everything inbetween as the content of the block.
*
* The previous approach used a lazy match for the pre content which could
* hit the backtracking limit for extremely large payloads.
*/
private function maskLineBreaksInsideCode(string $html): string
{
$segments = \preg_split('~</pre>~s', $html, flags: \PREG_SPLIT_NO_EMPTY);
$html = '';
foreach ($segments as $segment) {
$hasMatch = false;
$html .= \preg_replace_callback(
'~(?<openingTag><pre[^>]*>)(?<content>.*+)$~s',
static function ($matches) use (&$hasMatch) {
$hasMatch = true;
return $matches['openingTag'] . \preg_replace('~\r?\n~', '@@@WCF_PRE_LINEBREAK@@@', $matches['content']) . '</pre>';
},
$segment,
limit: 1
);
if (!$hasMatch && \str_contains($segment, '<pre')) {
$html .= '</pre>';
}
}
return $html;
}
/**
* @inheritDoc
*/
public function getHtml()
{
$html = $this->document->saveHTML($this->document->getElementsByTagName('body')->item(0));
// remove nuisance added by PHP
$html = \preg_replace('~^<!DOCTYPE[^>]+>\n~', '', $html);
$html = \preg_replace('~^<body>~', '', $html);
$html = \preg_replace('~</body>$~', '', $html);
foreach ($this->nodeData as $data) {
$html = \preg_replace_callback(
'~<wcfNode-' . $data['identifier'] . '>(?P<content>[\s\S]*)</wcfNode-' . $data['identifier'] . '>~',
static function ($matches) use ($data) {
/** @var IHtmlNode $obj */
$obj = $data['object'];
$string = $obj->replaceTag($data['data']);
// @phpstan-ignore function.alreadyNarrowedType, function.alreadyNarrowedType, booleanAnd.alwaysFalse
if (!\is_string($string) && !\is_numeric($string)) {
throw new \RuntimeException(
\sprintf(
"%s::replaceTag() returned %s but a string or number was expected.",
\get_class($obj),
\gettype($string),
),
);
}
if (!isset($data['data']['skipInnerContent']) || $data['data']['skipInnerContent'] !== true) {
if (\str_contains($string, '<!-- META_CODE_INNER_CONTENT -->')) {
return \str_replace('<!-- META_CODE_INNER_CONTENT -->', $matches['content'], $string);
} elseif (\str_contains($string, '<!-- META_CODE_INNER_CONTENT -->')) {
return \str_replace(
'<!-- META_CODE_INNER_CONTENT -->',
$matches['content'],
$string
);
}
}
return $string;
},
$html
);
}
// work-around for a libxml bug that causes a single space between
// some inline elements to be dropped
$html = \str_replace(' ', ' ', $html);
return \preg_replace('~>\x{00A0}<~u', '> <', $html);
}
/**
* @inheritDoc
*/
public function getDocument()
{
return $this->document;
}
/**
* Returns a XPath instance for the current DOM document.
*
* @return \DOMXPath XPath instance
*/
public function getXPath()
{
if ($this->xpath === null) {
$this->xpath = new \DOMXPath($this->getDocument());
}
return $this->xpath;
}
/**
* Renames a tag by creating a new element, moving all child nodes and
* eventually removing the original element.
*
* @param \DOMElement $element old element
* @param string $tagName tag name for the new element
* @param bool $preserveAttributes retain attributes for the new element
* @return \DOMElement newly created element
*/
public function renameTag(\DOMElement $element, $tagName, $preserveAttributes = false)
{
$newElement = $this->document->createElement($tagName);
if ($preserveAttributes) {
/** @var \DOMNode $attribute */
foreach ($element->attributes as $attribute) {
$newElement->setAttribute($attribute->nodeName, $attribute->nodeValue);
}
}
$element->parentNode->insertBefore($newElement, $element);
while ($element->hasChildNodes()) {
$newElement->appendChild($element->firstChild);
}
$element->parentNode->removeChild($element);
return $newElement;
}
/**
* Replaces an element with plain text.
*
* @param \DOMElement $element target element
* @param string $text text used to replace target
* @param bool $isBlockElement true if element is a block element
* @return void
*/
public function replaceElementWithText(\DOMElement $element, $text, $isBlockElement)
{
$textNode = $element->ownerDocument->createTextNode($text);
$element->parentNode->insertBefore($textNode, $element);
if ($isBlockElement) {
for ($i = 0; $i < 2; $i++) {
$br = $element->ownerDocument->createElement('br');
$element->parentNode->insertBefore($br, $element);
}
}
$element->parentNode->removeChild($element);
}
/**
* Removes an element but preserves child nodes by moving them into
* its original position.
*
* @param \DOMElement $element element to be removed
* @return void
*/
public function unwrapContent(\DOMElement $element)
{
while ($element->hasChildNodes()) {
$element->parentNode->insertBefore($element->firstChild, $element);
}
$element->parentNode->removeChild($element);
}
/**
* Adds node replacement data.
*
* @param IHtmlNode $htmlNode node processor instance
* @param string $nodeIdentifier replacement node identifier
* @param array<string, mixed> $data replacement data
* @return void
*/
public function addNodeData(IHtmlNode $htmlNode, $nodeIdentifier, array $data)
{
$this->nodeData[] = [
'data' => $data,
'identifier' => $nodeIdentifier,
'object' => $htmlNode,
];
}
/**
* Parses an attribute string.
*
* @param string $attributes base64 and JSON encoded attributes
* @return array<string|int, string|int|bool|null> parsed attributes
*/
public function parseAttributes($attributes)
{
if ($attributes !== '') {
$parsedAttributes = \base64_decode($attributes, true);
if ($parsedAttributes !== false) {
try {
$parsedAttributes = \json_decode($parsedAttributes, true, flags: \JSON_THROW_ON_ERROR);
} catch (\JsonException) {
/* parse errors can occur if user provided malicious content - ignore them */
$parsedAttributes = [];
}
return $parsedAttributes;
}
}
return [];
}
/**
* @inheritDoc
*/
public function getHtmlProcessor()
{
return $this->htmlProcessor;
}
/**
* Invokes a html node processor.
*
* @param IHtmlNode $htmlNode html node processor
* @return void
*/
protected function invokeHtmlNode(IHtmlNode $htmlNode)
{
if (!($htmlNode instanceof $this->nodeInterface)) {
throw new \InvalidArgumentException(
"Node '" . \get_class($htmlNode) . "' does not implement the interface '" . $this->nodeInterface . "'."
);
}
$tagName = $htmlNode->getTagName();
if (empty($tagName)) {
throw new \UnexpectedValueException("Missing tag name for " . \get_class($htmlNode));
}
$elements = [];
foreach ($this->getXPath()->query("//{$tagName}") as $element) {
/** @var \DOMElement $element */
$elements[] = $element;
}
if (!empty($elements)) {
$htmlNode->process($elements, $this);
}
}
/**
* Invokes possible html node processors based on found element tag names.
*
* @param string $classNamePattern full namespace pattern for class guessing
* @param string[] $skipTags list of tag names that should be ignored
* @param callable $callback optional callback
* @return void
*/
protected function invokeNodeHandlers($classNamePattern, array $skipTags = [], ?callable $callback = null)
{
static $handlerClassExists = [];
$skipTags = \array_merge($skipTags, ['html', 'head', 'title', 'meta', 'body', 'link']);
$tags = [];
/** @var \DOMElement $tag */
foreach ($this->getXPath()->query("//*") as $tag) {
$tagName = $tag->nodeName;
if (!isset($tags[$tagName])) {
$tags[$tagName] = $tagName;
}
}
foreach ($tags as $tagName) {
if (
\in_array($tagName, $skipTags)
|| \str_starts_with($tagName, 'wcfNode-')
) {
continue;
}
$tagName = \preg_replace_callback('/-([a-z])/', static function ($matches) {
return \ucfirst($matches[1]);
}, $tagName);
$className = $classNamePattern . \ucfirst($tagName);
// The `\class_exists()` call has to go through the autoloader which
// can become quite expensive when dealing with a lot of tags and
// messages within one request.
if (!isset($handlerClassExists[$className])) {
$handlerClassExists[$className] = \class_exists($className);
}
if ($handlerClassExists[$className]) {
if ($callback === null) {
$this->invokeHtmlNode(new $className());
} else {
$callback(new $className());
}
}
}
}
/**
* Returns a randomly generated tagName+identifier pair for <wcfNode-*> tags.
*
* @return array{0: string, 1: string}
* @since 6.2
*/
public function getWcfNodeIdentifier(): array
{
static $counter = 0;
static $prefix = null;
if ($prefix === null) {
// The `x` is appended to visually separate the prefix and the
// counter to aid in debugging in case the random prefix ends with
// one or more numeric characters.
$prefix = \bin2hex(\random_bytes(16)) . 'x';
}
$identifier = $prefix . $counter++;
return [$identifier, "wcfNode-{$identifier}"];
}
/**
* Returns a randomly generated tagName+identifier pair for <wcfNode-*> tags.
*
* @return array{0: string, 1: string}
* @deprecated 6.2 Use `getWcfNodeIdentifier` instead.
*/
public function getWcfNodeIdentifer(): array
{
return $this->getWcfNodeIdentifier();
}
}