Debian Codegraph @

vendor/wikimedia/parsoid/src/Utils/PipelineUtils.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Utils;
5
6 use Wikimedia\Assert\Assert;
7 use Wikimedia\Assert\UnreachableException;
8 use Wikimedia\Parsoid\Config\Env;
9 use Wikimedia\Parsoid\DOM\Comment;
10 use Wikimedia\Parsoid\DOM\Document;
11 use Wikimedia\Parsoid\DOM\DocumentFragment;
12 use Wikimedia\Parsoid\DOM\Element;
13 use Wikimedia\Parsoid\DOM\Node;
14 use Wikimedia\Parsoid\DOM\NodeList;
15 use Wikimedia\Parsoid\DOM\Text;
16 use Wikimedia\Parsoid\NodeData\DataMw;
17 use Wikimedia\Parsoid\NodeData\DataParsoid;
18 use Wikimedia\Parsoid\NodeData\TempData;
19 use Wikimedia\Parsoid\Tokens\CommentTk;
20 use Wikimedia\Parsoid\Tokens\EndTagTk;
21 use Wikimedia\Parsoid\Tokens\EOFTk;
22 use Wikimedia\Parsoid\Tokens\KV;
23 use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
24 use Wikimedia\Parsoid\Tokens\SourceRange;
25 use Wikimedia\Parsoid\Tokens\TagTk;
26 use Wikimedia\Parsoid\Tokens\Token;
27 use Wikimedia\Parsoid\Wt2Html\Frame;
28
29 /**
30 * This file contains parsing pipeline related utilities.
31 */
32 class PipelineUtils {
33 /**
34 * Creates a dom-fragment-token for processing 'content' (an array of tokens)
35 * in its own subpipeline all the way to DOM. These tokens will be processed
36 * by their own handler (DOMFragmentBuilder) in the last stage of the async
37 * pipeline.
38 *
39 * srcOffsets should always be provided to process top-level page content in a
40 * subpipeline. Without it, DSR computation and template wrapping cannot be done
41 * in the subpipeline. While unpackDOMFragment can do this on unwrapping, that can
42 * be a bit fragile and makes dom-fragments a leaky abstraction by leaking subpipeline
43 * processing into the top-level pipeline.
44 *
45 * @param string|Token|array<Token|string> $content The array of tokens to process.
46 * @param SourceRange $srcOffsets Wikitext source offsets (start/end) of these tokens.
47 * @param array $opts Parsing options.
48 * - Token token The token that generated the content.
49 * - bool inlineContext Is this DOM fragment used in an inline context?
50 * @return SelfclosingTagTk
51 */
52 public static function getDOMFragmentToken(
53 $content, SourceRange $srcOffsets, array $opts = []
54 ): SelfclosingTagTk {
55 $token = $opts['token'];
56 return new SelfclosingTagTk( 'mw:dom-fragment-token', [
57 new KV( 'contextTok', $token, $token->dataParsoid->tsr->expandTsrV() ),
58 new KV( 'content', $content, $srcOffsets->expandTsrV() ),
59 new KV( 'inlineContext', ( $opts['inlineContext'] ?? false ) ? "1" : "0" ),
60 new KV( 'inPHPBlock', ( $opts['inPHPBlock'] ?? false ) ? "1" : "0" ),
61 ] );
62 }
63
64 /**
65 * Processes content (wikitext, array of tokens, whatever) in its own
66 * pipeline based on options.
67 *
68 * @param Env $env The environment/context for the expansion.
69 * @param Frame $frame
70 * The parent frame within which the expansion is taking place.
71 * Used for template expansion and source text tracking.
72 * @param string|Token|array<Token|string>|Element $content
73 * How this content is processed depends on what kind of pipeline
74 * is constructed specified by opts.
75 * @param array $opts
76 * Processing options that specify pipeline-type, opts, and callbacks.
77 * - string pipelineType
78 * - array pipelineOpts
79 * - array tplArgs - if set, defines parameters for the child frame
80 * - string tplArgs['name']
81 * - KV[] tplArgs['attribs']
82 * - string srcText - if set, defines the source text for the expansion
83 * - SourceRange srcOffsets - if set, defines the range within the
84 * source text that $content corresponds to
85 * - bool sol Whether tokens should be processed in start-of-line context.
86 * - bool toplevel Whether the pipeline is considered atTopLevel
87 * @return array<Token|string>|DocumentFragment (depending on pipeline type)
88 */
89 public static function processContentInPipeline(
90 Env $env, Frame $frame, $content, array $opts
91 ) {
92 // Build a pipeline
93 $pipeline = $env->getPipelineFactory()->getPipeline(
94 $opts['pipelineType'],
95 $opts['pipelineOpts']
96 );
97
98 $pipeline->init( [
99 // NOTE: some pipelines force toplevel to true
100 'toplevel' => $opts['toplevel'] ?? false,
101 'frame' => $frame,
102 'tplArgs' => $opts['tplArgs'] ?? null,
103 'srcText' => $opts['srcText'] ?? $frame->getSrcText(),
104 'srcOffsets' => $opts['srcOffsets'] ?? null,
105 ] );
106
107 // Off the starting block ... ready, set, go!
108 return $pipeline->parse( $content, [ 'sol' => $opts['sol'] ] );
109 }
110
111 /**
112 * Expands value all the way to DOM.
113 *
114 * @param Env $env
115 * The environment/context for the expansion.
116 * @param Frame $frame
117 * The parent frame within which the expansion is taking place.
118 * Used for template expansion and source text tracking.
119 * @param array $v
120 * The value to process.
121 * The value is expected to be an associative array with a "html" property.
122 * The html property is expanded to DOM only if it is an array (of tokens).
123 * Non-arrays are passed back unexpanded.
124 * @param bool $expandTemplates
125 * Should any templates encountered here be expanded
126 * (usually false for nested templates since they are never directly editable).
127 * @param bool $inTemplate
128 * Unexpanded templates can occur in the content of extension tags.
129 * @return array
130 */
131 public static function expandAttrValueToDOM(
132 Env $env, Frame $frame, array $v, bool $expandTemplates, bool $inTemplate
133 ): array {
134 if ( is_array( $v['html'] ?? null ) ) {
135 // Set up pipeline options
136 $opts = [
137 'pipelineType' => 'expanded-tokens-to-fragment',
138 'pipelineOpts' => [
139 'attrExpansion' => true,
140 'inlineContext' => true,
141 'expandTemplates' => $expandTemplates,
142 'inTemplate' => $inTemplate
143 ],
144 'srcOffsets' => $v['srcOffsets'],
145 'sol' => true
146 ];
147 $content = array_merge( $v['html'], [ new EOFTk() ] );
148 $domFragment = self::processContentInPipeline(
149 $env, $frame, $content, $opts
150 );
151 // Since we aren't at the top level, data attrs
152 // were not applied in cleanup. However, tmp
153 // was stripped.
154 $v['html'] = ContentUtils::ppToXML(
155 $domFragment, [ 'innerXML' => true ]
156 );
157 }
158 // Remove srcOffsets after value is expanded, so they don't show
159 // up in the output data-mw attribute
160 unset( $v['srcOffsets'] );
161 return $v;
162 }
163
164 /**
165 * @param Env $env
166 * The environment/context for the expansion.
167 * @param Frame $frame
168 * The parent frame within which the expansion is taking place.
169 * Used for template expansion and source text tracking.
170 * @param array $vals
171 * Array of values to expand.
172 * Non-array elements of $vals are passed back unmodified.
173 * If an array element, it is expected to be an associative array with a "html" property.
174 * The html property is expanded to DOM only if it is an array (of tokens).
175 * @param bool $expandTemplates
176 * Should any templates encountered here be expanded
177 * (usually false for nested templates since they are never directly editable).
178 * @param bool $inTemplate
179 * Unexpanded templates can occur in the content of extension tags.
180 * @return array
181 */
182 public static function expandAttrValuesToDOM(
183 Env $env, $frame, array $vals, bool $expandTemplates, bool $inTemplate
184 ): array {
185 $ret = [];
186 foreach ( $vals as $v ) {
187 $ret[] = self::expandAttrValueToDOM( $env, $frame, $v, $expandTemplates, $inTemplate );
188 }
189 return $ret;
190 }
191
192 /**
193 * Convert a DOM node to a token. The node comes from a DOM whose data attributes
194 * are stored outside the DOM.
195 *
196 * @param Element $node
197 * @param array<string,string> $attrs
198 * @return array{attrs:KV[],dataParsoid:?DataParsoid,dataMw:?DataMw}
199 */
200 private static function domAttrsToTagAttrs( Element $node, array $attrs ): array {
201 $out = [];
202 foreach ( $attrs as $name => $value ) {
203 if ( $name !== DOMDataUtils::DATA_OBJECT_ATTR_NAME ) {
204 $out[] = new KV( $name, $value );
205 }
206 }
207 return [
208 'attrs' => $out,
209 'dataParsoid' => DOMDataUtils::getDataParsoid( $node ),
210 'dataMw' =>
211 DOMDataUtils::validDataMw( $node ) ? DOMDataUtils::getDataMw( $node ) : null,
212 ];
213 }
214
215 /**
216 * Convert a DOM to tokens. Data attributes for nodes are stored outside the DOM.
217 *
218 * @param Node $node The root of the DOM tree to convert to tokens
219 * @param array<Token|string> $tokBuf This is where the tokens get stored
220 * @return array
221 */
222 private static function convertDOMtoTokens( Node $node, array $tokBuf ): array {
223 if ( $node instanceof Element ) {
224 $nodeName = DOMCompat::nodeName( $node );
225 $attrInfo = self::domAttrsToTagAttrs( $node, DOMUtils::attributes( $node ) );
226
227 if ( Utils::isVoidElement( $nodeName ) ) {
228 $tokBuf[] = new SelfclosingTagTk(
229 $nodeName, $attrInfo['attrs'],
230 $attrInfo['dataParsoid'], $attrInfo['dataMw']
231 );
232 } else {
233 $tokBuf[] = new TagTk(
234 $nodeName, $attrInfo['attrs'],
235 $attrInfo['dataParsoid'], $attrInfo['dataMw']
236 );
237 for ( $child = $node->firstChild; $child; $child = $child->nextSibling ) {
238 $tokBuf = self::convertDOMtoTokens( $child, $tokBuf );
239 }
240 $endTag = new EndTagTk( $nodeName );
241 // Keep stx parity
242 if ( WTUtils::isLiteralHTMLNode( $node ) ) {
243 $endTag->dataParsoid->stx = 'html';
244 }
245 $tokBuf[] = $endTag;
246 }
247 } elseif ( $node instanceof Text ) {
248 PHPUtils::pushArray( $tokBuf, TokenUtils::newlinesToNlTks( $node->nodeValue ) );
249 } elseif ( $node instanceof Comment ) {
250 $tokBuf[] = new CommentTk( $node->nodeValue );
251 } else {
252 // getWrapperTokens calls convertDOMToTokens with a Element
253 // and children of dom elements are always text/comment/elements
254 // which are all covered above.
255 throw new UnreachableException( "Should never get here!" );
256 }
257
258 return $tokBuf;
259 }
260
261 /**
262 * Get tokens representing a DOM forest (from transclusions, extensions,
263 * whatever that were generated as part of a separate processing pipeline)
264 * in the token stream. These tokens will tunnel the subtree through the
265 * token processing while preserving token stream semantics as if
266 * the DOM had been converted to tokens.
267 *
268 * @param DocumentFragment $domFragment List of DOM nodes that need to be tunneled through.
269 * @param array $opts
270 * @see encapsulateExpansionHTML's doc. for more info about these options.
271 * @return array<Token|string> List of token representatives.
272 */
273 private static function getWrapperTokens(
274 DocumentFragment $domFragment, array $opts
275 ): array {
276 if ( !$domFragment->hasChildNodes() ) {
277 return [ new TagTk( 'span' ), new EndTagTk( 'span' ) ];
278 }
279
280 $node = $domFragment->firstChild;
281
282 // Do we represent this with inline or block elements?
283 // This is to ensure that we get p-wrapping correct.
284 //
285 // * If all content is inline, we use inline-elements to represent this
286 // so that this content gets swallowed into the P tag that wraps
287 // adjacent inline content.
288 //
289 // * If any part of this is a block content, we treat extension content
290 // independent of surrounding content and don't want inline content
291 // here to be swallowed into a P tag that wraps adjacent inline content.
292 //
293 // This behavior ensures that we and clients can "drop-in" extension content
294 // into the DOM without messing with fixing up paragraph tags of surrounding
295 // content. It could potentially introduce minor rendering differences when
296 // compared to PHP parser output, but we'll swallow it for now.
297 $wrapperType = 'INLINE';
298 if ( !empty( $opts['pipelineOpts']['inlineContext'] ) ) {
299 // If the DOM fragment is being processed in the context where P wrapping
300 // has been suppressed, we represent the DOM fragment with inline-tokens.
301 //
302 // FIXME(SSS): Looks like we have some "impedance mismatch" here. But, this
303 // is correct in scenarios where link-content or image-captions are being
304 // processed in a sub-pipeline and we don't want a <div> in the link-caption
305 // to cause the <a>..</a> to get split apart.
306 //
307 // Filed as T49963
308 } elseif ( !$opts['unpackOutput'] ) {
309 // Fragments that won't be unpacked aren't amenable to inspection, since
310 // the ultimate content is unknown. For example, refs shuttle content
311 // through treebuilding that ends up in the references list.
312 //
313 // FIXME(arlolra): Do we need a mechanism to specify content
314 // categories?
315 } else {
316 foreach ( $domFragment->childNodes as $n ) {
317 if (
318 DOMUtils::isWikitextBlockNode( $n ) ||
319 DOMUtils::hasBlockElementDescendant( $n )
320 ) {
321 $wrapperType = 'BLOCK';
322 break;
323 }
324 }
325 }
326
327 $wrapperName = null;
328 if ( $wrapperType === 'BLOCK' && !DOMUtils::isWikitextBlockNode( $node ) ) {
329 $wrapperName = 'div';
330 } elseif ( DOMCompat::nodeName( $node ) === 'a' ) {
331 // Do not use 'A' as a wrapper node because it could
332 // end up getting nested inside another 'A' and the DOM
333 // structure can change where the wrapper tokens are no
334 // longer siblings.
335 // Ex: "[http://foo.com Bad nesting [[Here]]].
336 $wrapperName = 'span';
337 } elseif (
338 in_array( DOMCompat::nodeName( $node ), [ 'style', 'script' ], true ) &&
339 ( $node->nextSibling !== null )
340 ) {
341 // <style>/<script> tags are not fostered, so if we're wrapping
342 // more than a single node, they aren't a good representation for
343 // the content. It can lead to fosterable content being inserted
344 // in a fosterable position after treebuilding is done, which isn't
345 // roundtrippable.
346 $wrapperName = 'span';
347 } elseif ( !( $node instanceof Element ) ) {
348 $wrapperName = 'span';
349 } else {
350 $wrapperName = DOMCompat::nodeName( $node );
351 }
352
353 if ( $node instanceof Element ) {
354 Assert::invariant(
355 // No need to look for data-mw as well.
356 // Nodes that have data-mw also have data-parsoid.
357 !$node->hasAttribute( 'data-parsoid' ),
358 "Expected node to have its data attributes loaded" );
359
360 $nodeData = DOMDataUtils::getNodeData( $node )->cloneNodeData();
361
362 if ( $wrapperName !== DOMCompat::nodeName( $node ) ) {
363 // Create a copy of the node without children
364 $workNode = $node->ownerDocument->createElement( $wrapperName );
365
366 // Copy over attributes
367 foreach ( DOMUtils::attributes( $node ) as $name => $value ) {
368 // "typeof" is ignored since it'll be removed below.
369 if ( $name !== 'typeof' ) {
370 $workNode->setAttribute( $name, $value );
371 }
372 }
373
374 // We are applying a different wrapper.
375 // So, node's data-parsoid isn't applicable.
376 $nodeData->parsoid = new DataParsoid;
377 } else {
378 // Shallow clone since we don't want to convert the whole tree to tokens.
379 $workNode = $node->cloneNode( false );
380
381 // Reset 'tsr' since it isn't applicable. Neither is
382 // any auxiliary info like 'endTSR'.
383 // FIXME: The above comment is only true if we are reusing
384 // DOM fragments from cache from previous revisions in
385 // incremental parsing scenarios. See T98992
386 if ( isset( $nodeData->parsoid->tsr ) ) {
387 $nodeData->parsoid->tsr = null;
388 }
389 if ( isset( $nodeData->parsoid->tmp->endTSR ) ) {
390 unset( $nodeData->parsoid->tmp->endTSR );
391 }
392
393 // The "in transclusion" flag was set on the first child for template
394 // wrapping in the nested pipeline, and doesn't apply to the dom
395 // fragment wrapper in this pipeline. Keeping it around can induce
396 // template wrapping of a foster box if the dom fragment is found in
397 // a fosterable position.
398 if (
399 isset( $nodeData->parsoid ) &&
400 $nodeData->parsoid->getTempFlag( TempData::IN_TRANSCLUSION )
401 ) {
402 $nodeData->parsoid->tmp->setFlag( TempData::IN_TRANSCLUSION, false );
403 }
404 }
405
406 DOMDataUtils::setNodeData( $workNode, $nodeData );
407 } else {
408 $workNode = $node->ownerDocument->createElement( $wrapperName );
409 }
410
411 $tokens = self::convertDOMtoTokens( $workNode, [] );
412
413 // Remove the typeof attribute from the first token.
414 // It will be replaced with mw:DOMFragment.
415 $tokens[0]->removeAttribute( 'typeof' );
416
417 // Remove the about attribute from the first token.
418 // We want to be able to distinguish when this wrapper was template
419 // annotated.
420 $tokens[0]->removeAttribute( 'about' );
421
422 return $tokens;
423 }
424
425 /**
426 * Generates wrapper tokens for a HTML expansion -- the wrapper
427 * tokens are placeholders that adequately represent semantics
428 * of the HTML DOM for the purposes of additional token transformations
429 * that will be applied to them.
430 *
431 * @param Env $env
432 * The active environment/context.
433 * @param Token $token
434 * The token that generated the DOM.
435 * @param array $expansion
436 * - string html HTML of the expansion.
437 * - DocumentFragment domFragment Outermost nodes of the HTML.
438 * @param array $opts
439 * - SourceRange tsr
440 * The TSR to set on the generated tokens. This TSR is
441 * used to compute DSR on the placeholder tokens.
442 * The computed DSR is transferred over to the unpacked DOM
443 * if setDSR is true (see below).
444 * - bool setDSR
445 * When the DOM fragment is unpacked, this option governs
446 * whether the DSR from the placeholder node is transferred
447 * over to the unpacked DOM or not.
448 * For example: Cite, reused transclusions.
449 * - bool fromCache
450 * - array pipelineOpts
451 * - bool unpackOutput
452 * - string wrapperName
453 * @return array<Token|string>
454 */
455 public static function encapsulateExpansionHTML(
456 Env $env, Token $token, array $expansion, array $opts
457 ): array {
458 $opts['unpackOutput'] ??= true; // Default
459 // Get placeholder tokens to get our subdom through the token processing
460 // stages. These will be finally unwrapped on the DOM.
461 $toks = self::getWrapperTokens( $expansion['domFragment'], $opts );
462 $firstWrapperToken = $toks[0];
463
464 // Add the DOMFragment type so that we get unwrapped later.
465 $fragmentType = 'mw:DOMFragment' . ( !$opts['unpackOutput'] ? '/sealed/' . $opts['wrapperName'] : '' );
466 $firstWrapperToken->setAttribute( 'typeof', $fragmentType );
467
468 // Assign the HTML fragment to the data-parsoid.html on the first wrapper token.
469 $firstWrapperToken->dataParsoid->html = $expansion['html'];
470
471 // Pass through setDSR flag
472 if ( !empty( $opts['setDSR'] ) ) {
473 $firstWrapperToken->dataParsoid->setTempFlag(
474 TempData::SET_DSR, $opts['setDSR'] );
475 }
476
477 // Pass through fromCache flag
478 if ( !empty( $opts['fromCache'] ) ) {
479 $firstWrapperToken->dataParsoid->setTempFlag(
480 TempData::FROM_CACHE, $opts['fromCache'] );
481 }
482
483 // Transfer the tsr.
484 // The first token gets the full width, the following tokens zero width.
485 $tokenTsr = $opts['tsr'] ?? $token->dataParsoid->tsr ?? null;
486 if ( $tokenTsr ) {
487 $firstWrapperToken->dataParsoid->tsr = $tokenTsr;
488 $firstWrapperToken->dataParsoid->extTagOffsets = $token->dataParsoid->extTagOffsets ?? null;
489 // XXX to investigate: if $tokenTsr->end is null, then we're losing
490 // the 'hint' we'd like to provide here that this is a zero-width
491 // source range.
492 // ->end can be set to null by WikiLinkHandler::bailTokens()
493 $endTsr = new SourceRange( $tokenTsr->end, $tokenTsr->end );
494 for ( $i = 1; $i < count( $toks ); $i++ ) {
495 $toks[$i]->dataParsoid->tsr = clone $endTsr;
496 }
497 }
498
499 return $toks;
500 }
501
502 private static function wrapAccum(
503 Document $doc, array &$textCommentAccum
504 ): void {
505 // Wrap accumulated nodes in a span
506 $span = $doc->createElement( 'span' );
507 $parentNode = $textCommentAccum[0]->parentNode;
508 $parentNode->insertBefore( $span, $textCommentAccum[0] );
509 foreach ( $textCommentAccum as $n ) {
510 $span->appendChild( $n );
511 }
512 $dp = new DataParsoid;
513 $dp->setTempFlag( TempData::WRAPPER );
514 DOMDataUtils::setDataParsoid( $span, $dp );
515 $textCommentAccum = [];
516 }
517
518 /**
519 * Wrap text and comment nodes in a node list into spans, so that all
520 * top-level nodes are elements.
521 *
522 * @param NodeList $nodes List of DOM nodes to wrap, mix of node types.
523 * @param ?Node $startAt
524 * @param ?Node $stopAt
525 */
526 public static function addSpanWrappers(
527 $nodes,
528 ?Node $startAt = null,
529 ?Node $stopAt = null
530 ): void {
531 $textCommentAccum = [];
532 $doc = $nodes->item( 0 )->ownerDocument;
533
534 // Build a real array out of nodes.
535 //
536 // Operating directly on DOM child-nodes array
537 // and manipulating them by adding span wrappers
538 // changes the traversal itself
539 $nodeBuf = [];
540 foreach ( $nodes as $node ) {
541 $nodeBuf[] = $node;
542 }
543
544 $start = ( $startAt === null );
545 foreach ( $nodeBuf as $node ) {
546 if ( !$start ) {
547 if ( $startAt !== $node ) {
548 continue;
549 }
550 $start = true;
551 }
552 if ( $node instanceof Text || $node instanceof Comment ) {
553 $textCommentAccum[] = $node;
554 } elseif ( count( $textCommentAccum ) ) {
555 self::wrapAccum( $doc, $textCommentAccum );
556 }
557 if ( $node === $stopAt ) {
558 break;
559 }
560 }
561
562 if ( count( $textCommentAccum ) ) {
563 self::wrapAccum( $doc, $textCommentAccum );
564 }
565 }
566
567 /**
568 * Convert a HTML5 DOM into a mw:DOMFragment and generate appropriate
569 * tokens to insert into the token stream for further processing.
570 *
571 * The DOMPostProcessor will unpack the fragment and insert the HTML
572 * back into the DOM.
573 *
574 * @param Env $env
575 * The active environment/context.
576 * @param Token $token
577 * The token that generated the DOM.
578 * @param DocumentFragment $domFragment
579 * The DOM that the token expanded to.
580 * @param array $opts
581 * Options to be passed onto the encapsulation code
582 * See encapsulateExpansionHTML's doc. for more info about these options.
583 * @return array<Token|string>
584 */
585 public static function tunnelDOMThroughTokens(
586 Env $env, Token $token, DocumentFragment $domFragment, array $opts
587 ): array {
588 // Get placeholder tokens to get our subdom through the token processing
589 // stages. These will be finally unwrapped on the DOM.
590 $expansion = self::makeExpansion( $env, $domFragment );
591 return self::encapsulateExpansionHTML( $env, $token, $expansion, $opts );
592 }
593
594 public static function makeExpansion(
595 Env $env, DocumentFragment $domFragment
596 ): array {
597 $fragmentId = $env->newFragmentId();
598 $env->setDOMFragment( $fragmentId, $domFragment );
599 return [ 'domFragment' => $domFragment, 'html' => $fragmentId ];
600 }
601
602 private static function doExtractExpansions( Env $env, array &$expansions, Node $node ): void {
603 $nodes = null;
604 $expAccum = null;
605 while ( $node ) {
606 if ( $node instanceof Element ) {
607 if ( DOMUtils::matchTypeOf( $node, '#^mw:(Transclusion$|Extension/)#' ) &&
608 $node->hasAttribute( 'about' )
609 ) {
610 $dp = DOMDataUtils::getDataParsoid( $node );
611 $about = DOMCompat::getAttribute( $node, 'about' );
612 $nodes = WTUtils::getAboutSiblings( $node, $about );
613 $key = null;
614 if ( DOMUtils::hasTypeOf( $node, 'mw:Transclusion' ) ) {
615 $expAccum = $expansions['transclusions'];
616 $key = $dp->src;
617 } elseif ( DOMUtils::matchTypeOf( $node, '#^mw:Extension/#' ) ) {
618 $expAccum = $expansions['extensions'];
619 $key = $dp->src;
620 } else {
621 $expAccum = $expansions['media'];
622 // XXX gwicke: use proper key that is not
623 // source-based? This also needs to work for
624 // transclusion output.
625 $key = null;
626 }
627
628 if ( $key ) {
629 throw new UnreachableException( 'Callsite was not ported!' );
630 // FIXME: makeExpansion return type changed
631 // $expAccum[$key] = self::makeExpansion( $env, $nodes );
632 }
633
634 $node = end( $nodes );
635 } else {
636 self::doExtractExpansions( $env, $expansions, $node->firstChild );
637 }
638 }
639 $node = $node->nextSibling;
640 }
641 }
642
643 /**
644 * Extract transclusion and extension expansions from a DOM, and return
645 * them in a structure like this:
646 * {
647 * transclusions: {
648 * 'key1': {
649 * html: 'html1',
650 * nodes: [<node1>, <node2>]
651 * }
652 * },
653 * extensions: {
654 * 'key2': {
655 * html: 'html2',
656 * nodes: [<node1>, <node2>]
657 * }
658 * },
659 * files: {
660 * 'key3': {
661 * html: 'html3',
662 * nodes: [<node1>, <node2>]
663 * }
664 * }
665 * }
666 *
667 * @param Env $env
668 * @param Element $body
669 * @return array
670 */
671 public static function extractExpansions( Env $env, Element $body ): array {
672 $expansions = [
673 'transclusions' => [],
674 'extensions' => [],
675 'media' => []
676 ];
677 // Kick off the extraction
678 self::doExtractExpansions( $env, $expansions, $body->firstChild );
679 return $expansions;
680 }
681
682 /**
683 * Fetches output of encapsulations that return HTML from the legacy parser
684 */
685 public static function fetchHTML( Env $env, string $source ): ?DocumentFragment {
686 $ret = $env->getDataAccess()->parseWikitext(
687 $env->getPageConfig(), $env->getMetadata(), $source
688 );
689 return $ret === '' ? null : DOMUtils::parseHTMLToFragment(
690 $env->topLevelDoc, DOMUtils::stripPWrapper( $ret )
691 );
692 }
693 }