Debian Codegraph @

vendor/wikimedia/parsoid/src/Wt2Html/DOM/Handlers/UnpackDOMFragments.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Wt2Html\DOM\Handlers;
5
6 use Wikimedia\Assert\Assert;
7 use Wikimedia\Parsoid\Config\Env;
8 use Wikimedia\Parsoid\Core\DomSourceRange;
9 use Wikimedia\Parsoid\DOM\DocumentFragment;
10 use Wikimedia\Parsoid\DOM\Element;
11 use Wikimedia\Parsoid\DOM\Node;
12 use Wikimedia\Parsoid\NodeData\TempData;
13 use Wikimedia\Parsoid\Utils\ContentUtils;
14 use Wikimedia\Parsoid\Utils\DOMCompat;
15 use Wikimedia\Parsoid\Utils\DOMDataUtils;
16 use Wikimedia\Parsoid\Utils\DOMTraverser;
17 use Wikimedia\Parsoid\Utils\DOMUtils;
18 use Wikimedia\Parsoid\Utils\DTState;
19 use Wikimedia\Parsoid\Utils\PipelineUtils;
20 use Wikimedia\Parsoid\Utils\Utils;
21
22 class UnpackDOMFragments {
23
24 private static function hasBadNesting(
25 Node $targetNode, DocumentFragment $fragment
26 ): bool {
27 // T165098: This is not entirely correct. This is only
28 // looking for nesting of identical tags. But, HTML tree building
29 // has lot more restrictions on nesting. It seems the simplest way
30 // to get all the rules right is to (serialize + reparse).
31
32 // A-tags cannot ever be nested inside each other at any level.
33 // This is the one scenario we definitely have to handle right now.
34 // We need a generic robust solution for other nesting scenarios.
35 //
36 // In the general case, we need to be walking up the ancestor chain
37 // of $targetNode to see if there is any 'A' tag there. But, since
38 // all link text is handled as DOM fragments, if there is any instance
39 // where that fragment generates A-tags, we'll always catch it.
40 //
41 // The only scenario we would miss would be if there were an A-tag whose
42 // link text wasn't a fragment but which had an embedded dom-fragment
43 // that generated an A-tag. Consider this example below:
44 // "<ext-X>...<div><ext-Y>..</ext-Y></div>..</ext-X>"
45 // If ext-X generates an A-tag and ext-Y also generates an A-tag, then
46 // when we unpack ext-Y's dom fragment, the simple check below would
47 // miss the misnesting.
48 return DOMCompat::nodeName( $targetNode ) === 'a' &&
49 DOMUtils::treeHasElement( $fragment, 'a' );
50 }
51
52 private static function fixAbouts( Env $env, Node $node, array &$aboutIdMap = [] ): void {
53 $c = $node->firstChild;
54 while ( $c ) {
55 if ( $c instanceof Element ) {
56 $cAbout = DOMCompat::getAttribute( $c, 'about' );
57 if ( $cAbout !== null ) {
58 // Update about
59 $newAbout = $aboutIdMap[$cAbout] ?? null;
60 if ( !$newAbout ) {
61 $newAbout = $env->newAboutId();
62 $aboutIdMap[$cAbout] = $newAbout;
63 }
64 $c->setAttribute( 'about', $newAbout );
65 }
66 self::fixAbouts( $env, $c, $aboutIdMap );
67 }
68 $c = $c->nextSibling;
69 }
70 }
71
72 private static function makeChildrenEncapWrappers(
73 DocumentFragment $domFragment, string $about
74 ): void {
75 PipelineUtils::addSpanWrappers( $domFragment->childNodes );
76
77 $c = $domFragment->firstChild;
78 while ( $c ) {
79 /**
80 * We just span wrapped the child nodes, so it's safe to assume
81 * they're all Elements.
82 *
83 * @var Element $c
84 */
85 '@phan-var Element $c';
86 // FIXME: This unconditionally sets about on children
87 // This is currently safe since all of them are nested
88 // inside a transclusion, but do we need future-proofing?
89 $c->setAttribute( 'about', $about );
90 $c = $c->nextSibling;
91 }
92 }
93
94 private static function markMisnested( Env $env, Element $n, ?int &$newOffset ): void {
95 $dp = DOMDataUtils::getDataParsoid( $n );
96 if ( $newOffset === null ) {
97 // We end up here when $placeholderParent is part of encapsulated content.
98 // Till we add logic to prevent that from happening, we need this fallback.
99 if ( isset( $dp->dsr->start ) ) {
100 $newOffset = $dp->dsr->start;
101 }
102
103 // If still null, set to some dummy value that is larger
104 // than page size to avoid pointing to something in source.
105 // Trying to fetch outside page source returns "".
106 if ( $newOffset === null ) {
107 $newOffset = strlen( $env->topFrame->getSrcText() ) + 1;
108 }
109 }
110 $dp->dsr = new DomSourceRange( $newOffset, $newOffset, null, null );
111 $dp->misnested = true;
112 }
113
114 /**
115 * DOMTraverser handler that unpacks DOM fragments which were injected in the
116 * token pipeline.
117 * @param Node $placeholder
118 * @param DTState $state
119 * @return bool|Node
120 */
121 public static function handler( Node $placeholder, DTState $state ) {
122 if ( !$placeholder instanceof Element ) {
123 return true;
124 }
125
126 // Sealed fragments shouldn't make it past this point
127 if ( !DOMUtils::hasTypeOf( $placeholder, 'mw:DOMFragment' ) ) {
128 return true;
129 }
130
131 $env = $state->env;
132 $placeholderDP = DOMDataUtils::getDataParsoid( $placeholder );
133 Assert::invariant( str_starts_with( $placeholderDP->html, 'mwf' ), '' );
134 $fragmentDOM = $env->getDOMFragment( $placeholderDP->html );
135 $fragmentContent = $fragmentDOM->firstChild;
136 $placeholderParent = $placeholder->parentNode;
137
138 // FIXME: What about mw:Param?
139 $isTransclusion = DOMUtils::hasTypeOf( $placeholder, 'mw:Transclusion' );
140 if ( $isTransclusion ) {
141 // Ensure our `firstChild` is an element to add annotation. At present,
142 // we're unlikely to end up with translusion annotations on fragments
143 // where span wrapping hasn't occurred (ie. link contents, since that's
144 // placed on the anchor itself) but in the future, nowiki spans may be
145 // omitted or new uses for dom fragments found. For now, the test case
146 // necessitating this is an edgy link-in-link scenario:
147 // [[Test|{{1x|[[Hmm|Something <sup>strange</sup>]]}}]]
148 // A new use of dom fragments is for parser functions returning html
149 // (special page transclusions) which don't do span wrapping.
150 PipelineUtils::addSpanWrappers( $fragmentDOM->childNodes );
151 // Reset `fragmentContent`, since the `firstChild` may have changed in
152 // span wrapping.
153 $fragmentContent = $fragmentDOM->firstChild;
154 DOMUtils::assertElt( $fragmentContent );
155 // Transfer typeof, data-mw, and param info
156 // about attributes are transferred below.
157 DOMDataUtils::setDataMw( $fragmentContent, Utils::clone( DOMDataUtils::getDataMw( $placeholder ) ) );
158 DOMUtils::addTypeOf( $fragmentContent, 'mw:Transclusion' );
159 DOMDataUtils::getDataParsoid( $fragmentContent )->pi = $placeholderDP->pi ?? null;
160 }
161
162 // Update DSR:
163 //
164 // - Only update DSR for content that came from cache.
165 // - For new DOM fragments from this pipeline,
166 // previously-computed DSR is valid.
167 // - EXCEPTION: fostered content from tables get their DSR reset
168 // to zero-width.
169 // - EXCEPTION: if we just transferred a transclusion marker,
170 // bring along the associated DSR.
171 // - FIXME: We seem to also be doing this for new extension content,
172 // which is the only place still using `setDSR`.
173 //
174 // There is currently no DSR for DOMFragments nested inside
175 // transclusion / extension content (extension inside template
176 // content etc).
177 // FIXME: Is that always the case? TSR info is stripped from tokens
178 // in transclusion but DSR computation happens before template wrapping
179 // and seems to sometimes assign DSR to DOMFragments regardless of having
180 // not having TSR set.
181 // TODO: Make sure that is the only reason for not having a DSR here.
182 $placeholderDSR = $placeholderDP->dsr ?? null;
183 if ( $placeholderDSR && (
184 $placeholderDP->getTempFlag( TempData::SET_DSR ) ||
185 $placeholderDP->getTempFlag( TempData::FROM_CACHE ) ||
186 !empty( $placeholderDP->fostered ) ||
187 $isTransclusion
188 ) ) {
189 DOMUtils::assertElt( $fragmentContent );
190 $fragmentDP = DOMDataUtils::getDataParsoid( $fragmentContent );
191 if ( $isTransclusion ) {
192 // FIXME: An old comment from c28f137 said we just use dsr->start and
193 // dsr->end since tag-widths will be incorrect for reuse of template
194 // expansions. The comment was removed in ca9e760.
195 $fragmentDP->dsr = new DomSourceRange( $placeholderDSR->start, $placeholderDSR->end, null, null );
196 } elseif (
197 DOMUtils::matchTypeOf( $fragmentContent, '/^mw:(Nowiki|Extension(\/\S+))$/' ) !== null
198 ) {
199 $fragmentDP->dsr = $placeholderDSR;
200 } else { // non-transcluded images
201 $fragmentDP->dsr = new DomSourceRange( $placeholderDSR->start, $placeholderDSR->end, 2, 2 );
202 }
203 }
204
205 if ( $placeholderDP->getTempFlag( TempData::FROM_CACHE ) ) {
206 // Replace old about-id with new about-id that is
207 // unique to the global page environment object.
208 //
209 // <figure>s are reused from cache. Note that figure captions
210 // can contain multiple independent transclusions. Each one
211 // of those individual transclusions should get a new unique
212 // about id. Hence a need for an aboutIdMap and the need to
213 // walk the entire tree.
214 self::fixAbouts( $env, $fragmentDOM );
215 }
216
217 // If the fragment wrapper has an about id, it came from template
218 // annotating (the wrapper was an about sibling) and should be transferred
219 // to top-level nodes after span wrapping. This should happen regardless
220 // of whether we're coming `fromCache` or not.
221 // FIXME: Presumably we have a nesting issue here if this is a cached
222 // transclusion.
223 $about = DOMCompat::getAttribute( $placeholder, 'about' );
224 if ( $about !== null ) {
225 // Span wrapping may not have happened for the transclusion above if
226 // the fragment is not the first encapsulation wrapper node.
227 PipelineUtils::addSpanWrappers( $fragmentDOM->childNodes );
228 $c = $fragmentDOM->firstChild;
229 while ( $c ) {
230 DOMUtils::assertElt( $c );
231 $c->setAttribute( 'about', $about );
232 $c = $c->nextSibling;
233 }
234 }
235
236 $nextNode = $placeholder->nextSibling;
237
238 if ( self::hasBadNesting( $placeholderParent, $fragmentDOM ) ) {
239 $nodeName = DOMCompat::nodeName( $placeholderParent );
240 Assert::invariant( $nodeName === 'a', "Unsupported Bad Nesting scenario for $nodeName" );
241 /* -----------------------------------------------------------------------
242 * If placeholderParent is an A element and fragmentDOM contains another
243 * A element, we have an invalid nesting of A elements and needs fixing up.
244 *
245 * $doc1: ... $placeholderParent -> [... $placeholder=mw:DOMFragment, ...] ...
246 *
247 * 1. Change doc1:$placeholderParent -> [... "#unique-hash-code", ...] by replacing
248 * $placeholder with the "#unique-hash-code" text string
249 *
250 * 2. $str = $placeholderParent->str_replace(#unique-hash-code, $placeholderHTML)
251 * We now have a HTML string with the bad nesting. We will now use the HTML5
252 * parser to parse this HTML string and give us the fixed up DOM
253 *
254 * 3. ParseHTML(str) to get
255 * $doc2: [BODY -> [[placeholderParent -> [...], nested-A-tag-from-placeholder, ...]]]
256 *
257 * 4. Replace $placeholderParent (in $doc1) with $doc2->body->childNodes
258 * ----------------------------------------------------------------------- */
259 // FIXME: This is not the most robust hashcode function to use here.
260 // With a granularity of a second, if replacements aren't done right away,
261 // you can get hash conflicts. It is also conceivable that there is a use
262 // of a parser function that returns the value of time and that may lead to
263 // hashcode conflicts as well.
264 $hashCode = (string)time();
265 $placeholderParent->replaceChild( $placeholder->ownerDocument->createTextNode( $hashCode ), $placeholder );
266
267 // If placeholderParent has an about, it presumably is nested inside a template
268 // Post fixup, its children will surface to the encapsulation wrapper level.
269 // So, we have to fix them up so they dont break the encapsulation.
270 //
271 // Ex: {{1x|[http://foo.com This is [[bad]], very bad]}}
272 //
273 // In this example, the <a> corresponding to Foo is placeholderParent and has an about.
274 // dummyNode is the DOM corresponding to "This is [[bad]], very bad". Post-fixup
275 // "[[bad]], very bad" are at encapsulation level and need about ids.
276 DOMUtils::assertElt( $placeholderParent ); // satisfy phan
277 $about = DOMCompat::getAttribute( $placeholderParent, 'about' );
278 if ( $about !== null ) {
279 self::makeChildrenEncapWrappers( $fragmentDOM, $about );
280 }
281
282 $fragmentHTML = ContentUtils::ppToXML( $fragmentDOM, [
283 'innerXML' => true,
284 // We just added some span wrappers and we need to keep
285 // that tmp info so the unnecessary ones get stripped.
286 // Should be fine since tmp was stripped before packing.
287 'keepTmp' => true
288 ]
289 );
290
291 $markerNode = $placeholderParent->previousSibling;
292
293 // We rely on HTML5 parser to fixup the bad nesting (see big comment above)
294 $placeholderParentHTML = ContentUtils::ppToXML( $placeholderParent );
295 $unpackedMisnestedHTML = str_replace( $hashCode, $fragmentHTML, $placeholderParentHTML );
296 $unpackedFragment = DOMUtils::parseHTMLToFragment(
297 $placeholderParent->ownerDocument, $unpackedMisnestedHTML
298 );
299
300 DOMUtils::migrateChildren(
301 $unpackedFragment, $placeholderParent->parentNode, $placeholderParent
302 );
303
304 // Identify the new link node. All following siblings till placeholderParent
305 // are nodes that have been hoisted out of the link.
306 // - Add span wrappers where necessary
307 // - Load data-attribs
308 // - Zero-out DSR
309
310 if ( $markerNode ) {
311 $linkNode = $markerNode->nextSibling;
312 } else {
313 $linkNode = $placeholderParent->parentNode->firstChild;
314 }
315 PipelineUtils::addSpanWrappers(
316 $linkNode->parentNode->childNodes, $linkNode->nextSibling, $placeholderParent );
317
318 $newOffset = null;
319 $node = $linkNode;
320 while ( $node !== $placeholderParent ) {
321 DOMDataUtils::visitAndLoadDataAttribs( $node );
322
323 if ( $node === $linkNode ) {
324 $newOffset = DOMDataUtils::getDataParsoid( $linkNode )->dsr->end ?? null;
325 } else {
326 $dsrFixer = new DOMTraverser();
327 $dsrFixer->addHandler( null, static function ( Node $n ) use( $env, &$newOffset ) {
328 if ( $n instanceof Element ) {
329 self::markMisnested( $env, $n, $newOffset );
330 }
331 return true;
332 } );
333 $dsrFixer->traverse( null, $node );
334 }
335
336 $node = $node->nextSibling;
337 }
338
339 // Set nextNode to the previous-sibling of former placeholderParent (which will get deleted)
340 // This will ensure that all nodes will get handled
341 $nextNode = $placeholderParent->previousSibling;
342
343 // placeholderParent itself is useless now
344 $placeholderParent->parentNode->removeChild( $placeholderParent );
345 } else {
346 // Preserve fostered flag from DOM fragment
347 if ( $fragmentContent instanceof Element ) {
348 if ( !empty( $placeholderDP->fostered ) ) {
349 $n = $fragmentContent;
350 while ( $n ) {
351 $dp = DOMDataUtils::getDataParsoid( $n );
352 $dp->fostered = true;
353 $n = $n->nextSibling;
354 }
355 }
356 }
357
358 // Move the content nodes over and delete the placeholder node
359 DOMUtils::migrateChildren( $fragmentDOM, $placeholderParent, $placeholder );
360 $placeholderParent->removeChild( $placeholder );
361
362 }
363
364 // Empty out $fragmentDOM since the call below asserts it
365 DOMCompat::replaceChildren( $fragmentDOM );
366 $env->removeDOMFragment( $placeholderDP->html );
367
368 return $nextNode;
369 }
370 }