Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
60.55% covered (warning)
60.55%
66 / 109
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
UnpackDOMFragments
60.55% covered (warning)
60.55%
66 / 109
25.00% covered (danger)
25.00%
1 / 4
90.00
0.00% covered (danger)
0.00%
0 / 1
 hasBadNesting
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 makeChildrenEncapWrappers
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 markMisnested
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
7.19
 handler
63.44% covered (warning)
63.44%
59 / 93
0.00% covered (danger)
0.00%
0 / 1
45.65
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\DOM\Handlers;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Parsoid\Config\Env;
8use Wikimedia\Parsoid\Core\DOMCompat;
9use Wikimedia\Parsoid\Core\DomSourceRange;
10use Wikimedia\Parsoid\DOM\DocumentFragment;
11use Wikimedia\Parsoid\DOM\Element;
12use Wikimedia\Parsoid\DOM\Node;
13use Wikimedia\Parsoid\NodeData\TempData;
14use Wikimedia\Parsoid\Utils\ContentUtils;
15use Wikimedia\Parsoid\Utils\DOMDataUtils;
16use Wikimedia\Parsoid\Utils\DOMTraverser;
17use Wikimedia\Parsoid\Utils\DOMUtils;
18use Wikimedia\Parsoid\Utils\DTState;
19use Wikimedia\Parsoid\Utils\PipelineUtils;
20use Wikimedia\Parsoid\Utils\WTUtils;
21
22class 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 DOMUtils::nodeName( $targetNode ) === 'a' &&
49            DOMUtils::treeHasElement( $fragment, 'a' );
50    }
51
52    private static function makeChildrenEncapWrappers(
53        DocumentFragment $domFragment, string $about
54    ): void {
55        PipelineUtils::addSpanWrappers( DOMUtils::childNodes( $domFragment ) );
56
57        $c = $domFragment->firstChild;
58        while ( $c ) {
59            /**
60             * We just span wrapped the child nodes, so it's safe to assume
61             * they're all Elements.
62             *
63             * @var Element $c
64             */
65            '@phan-var Element $c';
66            // FIXME: This unconditionally sets about on children
67            // This is currently safe since all of them are nested
68            // inside a transclusion, but do we need future-proofing?
69            $c->setAttribute( 'about', $about );
70            $c = $c->nextSibling;
71        }
72    }
73
74    private static function markMisnested( Env $env, Element $n, ?int &$newOffset ): void {
75        $dp = DOMDataUtils::getDataParsoid( $n );
76        // XXX T405759 "top frame source" doesn't seem right in the general case
77        $source = $dp->dsr->source ?? $env->topFrame->getSource();
78        if ( $newOffset === null ) {
79            // We end up here when $placeholderParent is part of encapsulated content.
80            // Till we add logic to prevent that from happening, we need this fallback.
81            if ( isset( $dp->dsr ) && $dp->dsr->start !== null ) {
82                $newOffset = $dp->dsr->start;
83            }
84
85            // If still null, set to some dummy value that is larger
86            // than page size to avoid pointing to something in source.
87            // Trying to fetch outside page source returns "".
88            if ( $newOffset === null ) {
89                $newOffset = strlen( $source->getSrcText() ) + 1;
90            }
91        }
92        $dp->dsr = new DomSourceRange( $newOffset, $newOffset, null, null, source: $source );
93        $dp->misnested = true;
94    }
95
96    /**
97     * DOMTraverser handler that unpacks DOM fragments which were injected in the
98     * token pipeline.
99     *
100     * @param Node $placeholder
101     * @param DTState $state
102     * @return bool|?Node
103     */
104    public static function handler( Node $placeholder, DTState $state ) {
105        if ( !$placeholder instanceof Element ) {
106            return true;
107        }
108
109        // Sealed fragments shouldn't make it past this point
110        if ( !DOMUtils::hasTypeOf( $placeholder, 'mw:DOMFragment' ) ) {
111            return true;
112        }
113
114        $env = $state->env;
115        $placeholderDP = DOMDataUtils::getDataParsoid( $placeholder );
116        $fragmentDOM = WTUtils::getDOMFragmentContents( $placeholder, clearAfter: true );
117        $fragmentContent = $fragmentDOM->firstChild;
118        $placeholderParent = $placeholder->parentNode;
119
120        // FIXME: What about mw:Param?
121        $isTransclusion = DOMUtils::hasTypeOf( $placeholder, 'mw:Transclusion' );
122        if ( $isTransclusion ) {
123            // Ensure our `firstChild` is an element to add annotation.  At present,
124            // we're unlikely to end up with translusion annotations on fragments
125            // where span wrapping hasn't occurred (ie. link contents, since that's
126            // placed on the anchor itself) but in the future, nowiki spans may be
127            // omitted or new uses for dom fragments found.  For now, the test case
128            // necessitating this is an edgy link-in-link scenario:
129            //   [[Test|{{1x|[[Hmm|Something <sup>strange</sup>]]}}]]
130            // A new use of dom fragments is for parser functions returning html
131            // (special page transclusions) which don't do span wrapping.
132            PipelineUtils::addSpanWrappers( DOMUtils::childNodes( $fragmentDOM ) );
133            // Reset `fragmentContent`, since the `firstChild` may have changed in
134            // span wrapping.
135            $fragmentContent = $fragmentDOM->firstChild;
136            '@phan-var Element $fragmentContent'; // @var Element $fragmentContent
137            // Transfer typeof, data-mw, and param info
138            // about attributes are transferred below.
139            DOMDataUtils::setDataMw( $fragmentContent, clone DOMDataUtils::getDataMw( $placeholder ) );
140            DOMUtils::addTypeOf( $fragmentContent, 'mw:Transclusion' );
141            // It should be impossible to have a single DOMFragment represent
142            // the output from multiple parser functions
143            $key = WTUtils::getPFragmentHandlerKey( $placeholder );
144            if ( $key !== null ) {
145                DOMUtils::addTypeOf( $fragmentContent, "mw:ParserFunction/$key" );
146            }
147            DOMDataUtils::getDataParsoid( $fragmentContent )->pi = $placeholderDP->pi ?? null;
148        }
149
150        // If the fragment wrapper has an about id, it came from template
151        // annotating (the wrapper was an about sibling) and should be transferred
152        // to top-level nodes after span wrapping.
153        $about = DOMCompat::getAttribute( $placeholder, 'about' );
154        if ( $about !== null ) {
155            // Span wrapping may not have happened for the transclusion above if
156            // the fragment is not the first encapsulation wrapper node.
157            PipelineUtils::addSpanWrappers( DOMUtils::childNodes( $fragmentDOM ) );
158            // Reset `fragmentContent`, since the `firstChild` may have changed in
159            // span wrapping.
160            $c = $fragmentContent = $fragmentDOM->firstChild;
161            while ( $c ) {
162                '@phan-var Element $c'; // @var Element $c
163                $c->setAttribute( 'about', $about );
164                $c = $c->nextSibling;
165            }
166        }
167
168        // Preserve fostered flag from DOM fragment
169        if ( !empty( $placeholderDP->fostered ) ) {
170            PipelineUtils::addSpanWrappers( DOMUtils::childNodes( $fragmentDOM ) );
171            // Reset `fragmentContent`, since the `firstChild` may have changed in
172            // span wrapping.
173            $n = $fragmentContent = $fragmentDOM->firstChild;
174            while ( $n ) {
175                '@phan-var Element $n'; // @var Element $n
176                $dp = DOMDataUtils::getDataParsoid( $n );
177                $dp->fostered = true;
178                $n = $n->nextSibling;
179            }
180        }
181
182        // Update DSR:
183        //
184        // - For new DOM fragments from this pipeline,
185        //   previously-computed DSR is valid.
186        // - EXCEPTION: fostered content from tables get their DSR reset
187        //   to zero-width.
188        // - EXCEPTION: if we just transferred a transclusion marker,
189        //   bring along the associated DSR.
190        // - FIXME: We seem to also be doing this for new extension content,
191        //   which is the only place still using `setDSR`.
192        //
193        // There is currently no DSR for DOMFragments nested inside
194        // transclusion / extension content (extension inside template
195        // content etc).
196        // FIXME: Is that always the case?  TSR info is stripped from tokens
197        // in transclusion but DSR computation happens before template wrapping
198        // and seems to sometimes assign DSR to DOMFragments regardless of having
199        // not having TSR set.
200        // TODO: Make sure that is the only reason for not having a DSR here.
201        $placeholderDSR = $placeholderDP->dsr ?? null;
202        if ( $placeholderDSR && (
203            $placeholderDP->getTempFlag( TempData::SET_DSR ) ||
204            !empty( $placeholderDP->fostered ) ||
205            $isTransclusion
206        ) ) {
207            '@phan-var Element $fragmentContent'; // @var Element $fragmentContent
208            $fragmentDP = DOMDataUtils::getDataParsoid( $fragmentContent );
209            if ( $isTransclusion ) {
210                // FIXME: An old comment from c28f137 said we just use dsr->start and
211                // dsr->end since tag-widths will be incorrect for reuse of template
212                // expansions.  The comment was removed in ca9e760.
213                $fragmentDP->dsr = new DomSourceRange(
214                    $placeholderDSR->start, $placeholderDSR->end, null, null,
215                    source: $placeholderDSR->source
216                );
217            } elseif (
218                DOMUtils::matchTypeOf( $fragmentContent, '/^mw:(Nowiki|Extension(\/\S+))$/' ) !== null
219            ) {
220                $fragmentDP->dsr = $placeholderDSR;
221            } else { // non-transcluded images
222                // FIXME: Presumably, all the fostered content gets DSR reset,
223                // not just $fragmentContent
224                $fragmentDP->dsr = new DomSourceRange(
225                    $placeholderDSR->start, $placeholderDSR->end, 2, 2,
226                    source: $placeholderDSR->source
227                );
228            }
229        }
230
231        $nextNode = $placeholder->nextSibling;
232
233        if ( self::hasBadNesting( $placeholderParent, $fragmentDOM ) ) {
234            $nodeName = DOMUtils::nodeName( $placeholderParent );
235            Assert::invariant( $nodeName === 'a', "Unsupported Bad Nesting scenario for $nodeName" );
236            /* -----------------------------------------------------------------------
237             * If placeholderParent is an A element and fragmentDOM contains another
238             * A element, we have an invalid nesting of A elements and needs fixing up.
239             * ----------------------------------------------------------------------- */
240
241            // If placeholderParent has an about, it presumably is nested inside a template
242            // Post fixup, its children will surface to the encapsulation wrapper level.
243            // So, we have to fix them up so they dont break the encapsulation.
244            //
245            // Ex: {{1x|[http://foo.com This is [[bad]], very bad]}}
246            //
247            // In this example, the <a> corresponding to Foo is placeholderParent and has an about.
248            // dummyNode is the DOM corresponding to "This is [[bad]], very bad". Post-fixup
249            // "[[bad]], very bad" are at encapsulation level and need about ids.
250            '@phan-var Element $placeholderParent'; // @var Element $placeholderParent
251            $about = DOMCompat::getAttribute( $placeholderParent, 'about' );
252            if ( $about !== null ) {
253                self::makeChildrenEncapWrappers( $fragmentDOM, $about );
254            }
255
256            // $fragmentDOM is "prepared and loaded".  We're going to make the
257            // fragment into an HTML string in order to let the HTML parser
258            // loose on it.  We don't need to store data attributes, though,
259            // since the data-object-id attributes will still link them up
260            // properly after the round trip through the HTML parser.
261            // (We just added some span wrappers and we need to keep
262            // that tmp info so the unnecessary ones get stripped.)
263            while ( $fragmentDOM->firstChild ) {
264                $placeholderParent->insertBefore( $fragmentDOM->firstChild, $placeholder );
265            }
266            $placeholderParent->removeChild( $placeholder );
267
268            $markerNode = $placeholderParent->previousSibling;
269
270            // We rely on HTML5 parser to fixup the bad nesting (see big comment above)
271            // Again, we don't need to store data-attributes as long as the
272            // data-object-ids are preserved.
273            $placeholderParentHTML = ContentUtils::toXML( $placeholderParent );
274            $unpackedFragment = DOMUtils::parseHTMLToFragment(
275                $placeholderParent->ownerDocument, $placeholderParentHTML
276            );
277
278            // Nodes can be copied during HTML parsing, for example elements
279            // on the "active formatting list" will be copied when elements
280            // are misnested.  Check the data-object-ids of all the nodes we
281            // just created and renumber & clone the node data for any which
282            // got copied.
283            // XXX: annotation ranges and about ids will get merged, since we
284            // can't tell which nodes were copied from the active formatting
285            // list and which were 'original'.
286            DOMDataUtils::dedupeNodeData( $unpackedFragment );
287
288            DOMUtils::migrateChildren(
289                $unpackedFragment, $placeholderParent->parentNode, $placeholderParent
290            );
291
292            // Identify the new link node. All following siblings till placeholderParent
293            // are nodes that have been hoisted out of the link.
294            // - Add span wrappers where necessary
295            // - Load data-attribs
296            // - Zero-out DSR
297
298            if ( $markerNode ) {
299                $linkNode = $markerNode->nextSibling;
300            } else {
301                $linkNode = $placeholderParent->parentNode->firstChild;
302            }
303            PipelineUtils::addSpanWrappers(
304                DOMUtils::childNodes( $linkNode->parentNode ), $linkNode->nextSibling, $placeholderParent );
305
306            $newOffset = null;
307            $node = $linkNode;
308            while ( $node !== $placeholderParent ) {
309
310                if ( $node === $linkNode ) {
311                    $newOffset = DOMDataUtils::getDataParsoid( $linkNode )->dsr->end ?? null;
312                } else {
313                    $dsrFixer = new DOMTraverser();
314                    $dsrFixer->addHandler( null, static function ( Node $n ) use( $env, &$newOffset ) {
315                        if ( $n instanceof Element ) {
316                            self::markMisnested( $env, $n, $newOffset );
317                        }
318                        return true;
319                    } );
320                    $dsrFixer->traverse( null, $node );
321                }
322
323                $node = $node->nextSibling;
324            }
325
326            // Set nextNode to the previous-sibling of former placeholderParent (which will get deleted)
327            // This will ensure that all nodes will get handled
328            $nextNode = $placeholderParent->previousSibling;
329
330            // placeholderParent itself is useless now
331            $placeholderParent->parentNode->removeChild( $placeholderParent );
332        } else {
333            // Move the content nodes over and delete the placeholder node
334            DOMUtils::migrateChildren( $fragmentDOM, $placeholderParent, $placeholder );
335            $placeholderParent->removeChild( $placeholder );
336
337        }
338
339        // Empty out $fragmentDOM since the call below asserts it
340        DOMCompat::replaceChildren( $fragmentDOM );
341
342        return $nextNode;
343    }
344}