Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
33.27% covered (danger)
33.27%
184 / 553
27.78% covered (danger)
27.78%
5 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
TemplateHandler
33.27% covered (danger)
33.27%
184 / 553
27.78% covered (danger)
27.78%
5 / 18
6391.54
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 parserFunctionsWrapper
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 processToString
0.00% covered (danger)
0.00%
0 / 52
0.00% covered (danger)
0.00%
0 / 1
650
 processPreprocToString
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
210
 isSafeSubst
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 resolveTemplateTarget
35.92% covered (danger)
35.92%
37 / 103
0.00% covered (danger)
0.00%
0 / 1
250.27
 convertToString
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
2
 enforceTemplateConstraints
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 expandTemplateNatively
0.00% covered (danger)
0.00%
0 / 48
0.00% covered (danger)
0.00%
0 / 1
90
 processTemplateSource
80.00% covered (warning)
80.00%
12 / 15
0.00% covered (danger)
0.00%
0 / 1
2.03
 encapTokens
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 processTemplateTokens
65.00% covered (warning)
65.00%
13 / 20
0.00% covered (danger)
0.00%
0 / 1
14.29
 fetchTemplateAndTitle
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 processSpecialMagicWord
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 expandTemplate
36.78% covered (danger)
36.78%
64 / 174
0.00% covered (danger)
0.00%
0 / 1
273.80
 onTemplate
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 onTemplateArg
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 onTag
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
1.01
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Assert\UnreachableException;
8use Wikimedia\Parsoid\Config\PageContent;
9use Wikimedia\Parsoid\Core\DomSourceRange;
10use Wikimedia\Parsoid\Core\SourceRange;
11use Wikimedia\Parsoid\Ext\AsyncResult;
12use Wikimedia\Parsoid\Ext\ParsoidExtensionAPI;
13use Wikimedia\Parsoid\Fragments\WikitextPFragment;
14use Wikimedia\Parsoid\Mocks\MockPageContent;
15use Wikimedia\Parsoid\NodeData\TempData;
16use Wikimedia\Parsoid\Tokens\CommentTk;
17use Wikimedia\Parsoid\Tokens\EmptyLineTk;
18use Wikimedia\Parsoid\Tokens\EndTagTk;
19use Wikimedia\Parsoid\Tokens\KV;
20use Wikimedia\Parsoid\Tokens\NlTk;
21use Wikimedia\Parsoid\Tokens\PreprocAngleTk;
22use Wikimedia\Parsoid\Tokens\PreprocTk;
23use Wikimedia\Parsoid\Tokens\PreprocType;
24use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
25use Wikimedia\Parsoid\Tokens\TagTk;
26use Wikimedia\Parsoid\Tokens\Token;
27use Wikimedia\Parsoid\Tokens\XMLTagTk;
28use Wikimedia\Parsoid\Utils\PHPUtils;
29use Wikimedia\Parsoid\Utils\PipelineUtils;
30use Wikimedia\Parsoid\Utils\Title;
31use Wikimedia\Parsoid\Utils\TitleException;
32use Wikimedia\Parsoid\Utils\TokenUtils;
33use Wikimedia\Parsoid\Utils\WTUtils;
34use Wikimedia\Parsoid\Wikitext\Wikitext;
35use Wikimedia\Parsoid\Wt2Html\Frame;
36use Wikimedia\Parsoid\Wt2Html\Params;
37use Wikimedia\Parsoid\Wt2Html\PegTokenizer;
38use Wikimedia\Parsoid\Wt2Html\TokenHandlerPipeline;
39
40/**
41 * Template and template argument handling.
42 */
43class TemplateHandler extends XMLTagBasedHandler {
44    /**
45     * @var bool Should we wrap template tokens with template meta tags?
46     */
47    private $wrapTemplates;
48
49    /**
50     * @var AttributeExpander
51     * Local copy of the attribute expander to deal with template targets
52     * that are templated themselves
53     */
54    private $ae;
55
56    /**
57     * @var ParserFunctions
58     */
59    private $parserFunctions;
60
61    /**
62     * @var bool
63     */
64     private $atMaxArticleSize;
65
66     /** @var string|null */
67     private $safeSubstRegex;
68
69    /**
70     * @param TokenHandlerPipeline $manager
71     * @param array $options
72     *  - ?bool inTemplate Is this being invoked while processing a template?
73     *  - ?bool expandTemplates Should we expand templates encountered here?
74     *  - ?string extTag The name of the extension tag, if any, which is being expanded.
75     */
76    public function __construct( TokenHandlerPipeline $manager, array $options ) {
77        parent::__construct( $manager, $options );
78        $this->parserFunctions = new ParserFunctions( $this->env );
79        $this->ae = new AttributeExpander( $this->manager, [
80            'expandTemplates' => $this->options['expandTemplates'],
81            'inTemplate' => $this->options['inTemplate'],
82            'standalone' => true,
83        ] );
84        $this->wrapTemplates = !$options['inTemplate'];
85
86        // In the legacy parser, the call to replaceVariables from internalParse
87        // returns early if the text is already greater than the $wgMaxArticleSize
88        // We're going to compare and set a boolean here, then do the "early
89        // return" below.
90        $this->atMaxArticleSize = !$this->env->compareWt2HtmlLimit(
91            'wikitextSize',
92            strlen( $this->env->topFrame->getSource()->getSrcText() )
93        );
94    }
95
96    /**
97     * Parser functions also need template wrapping.
98     *
99     * @param array<string|Token> $tokens
100     * @return array<string|Token>
101     */
102    private function parserFunctionsWrapper( array $tokens ): array {
103        $chunkToks = [];
104        if ( $tokens ) {
105            // This is only for the Parsoid native expansion pipeline used in
106            // parser tests. The "" token sometimes changes foster parenting
107            // behavior and trips up some tests.
108            $tokens = array_values( array_filter( $tokens, static function ( $t ) {
109                return $t !== '';
110            } ) );
111
112            // token chunk should be flattened
113            $flat = true;
114            foreach ( $tokens as $t ) {
115                if ( is_array( $t ) ) {
116                    $flat = false;
117                    break;
118                }
119            }
120            Assert::invariant( $flat, "Expected token chunk to be flattened" );
121
122            $chunkToks = $this->processTemplateTokens( $tokens );
123        }
124        return $chunkToks;
125    }
126
127    /**
128     * Take output of tokensToString and further postprocess it.
129     * - If it can be processed to a string which would be a valid template transclusion target,
130     *   the return value will be [ $the_string_value, null ]
131     * - If not, the return value will be [ $partial_string, $unprocessed_token_array ]
132     * The caller can then decide if this would be a valid parser function call
133     * where the unprocessed token array would be part of the first arg to the parser function.
134     * Ex: With "{{uc:foo [[foo]] {{1x|foo}} bar}}", we return
135     *     [ "uc:foo ", [ wikilink-token, " ", template-token, " bar" ] ]
136     *
137     * @param array<string|Token> $tokens
138     * @return list{string, ?array<Token|string>} first element is always a string
139     */
140    private function processToString( array $tokens ): array {
141        // Handle preprocessed input: strip comments and annotations
142        $tokens = $this->processPreprocToString( $tokens );
143        // Now convert the other tokens to string form
144        $maybeTarget = TokenUtils::tokensToString( $tokens, true, [ 'retainNLs' => true ] );
145        if ( !is_array( $maybeTarget ) ) {
146            return [ $maybeTarget, null ];
147        }
148
149        $buf = $maybeTarget[0]; // Will always be a string
150        $tgtTokens = $maybeTarget[1];
151        $preNlContent = null;
152        $i = 0;
153        $n = count( $tgtTokens );
154        while ( $i < $n ) {
155            $ntt = $tgtTokens[$i];
156            if ( is_string( $ntt ) ) {
157                $buf .= $ntt;
158                if ( $preNlContent !== null && !preg_match( '/^\s*$/D', $buf ) ) {
159                    // intervening newline makes this an invalid template target
160                    return [ $preNlContent, array_merge( [ $buf ], array_slice( $tgtTokens, $i ) ) ];
161                }
162            } else {
163                switch ( get_class( $ntt ) ) {
164                    case SelfclosingTagTk::class:
165                        // Quotes are valid template targets
166                        if ( $ntt->getName() === 'mw-quote' ) {
167                            $buf .= $ntt->getAttributeV( 'value' );
168                        } elseif (
169                            !( $ntt instanceof EmptyLineTk ) &&
170                            $ntt->getName() !== 'template' &&
171                            $ntt->getName() !== 'templatearg' &&
172                            // Ignore annotations in template targets
173                            // NOTE(T295834): There's a large discussion about who's responsible
174                            // for stripping these tags in I487baaafcf1ffd771cb6a9e7dd4fb76d6387e412
175                            !(
176                                $ntt->getName() === 'meta' &&
177                                TokenUtils::matchTypeOf( $ntt, WTUtils::ANNOTATION_META_TYPE_REGEXP )
178                            ) &&
179                            // Note that OnlyInclude only converts to metas during TT
180                            // in inTemplate context, but we shouldn't find ourselves
181                            // here in that case.
182                            !(
183                                $ntt->getName() === 'meta' &&
184                                TokenUtils::matchTypeOf( $ntt, '#^mw:Includes/#' )
185                            )
186                        ) {
187                            // We are okay with empty (comment-only) lines,
188                            // {{..}} and {{{..}}} in template targets.
189                            if ( $preNlContent !== null ) {
190                                return [ $preNlContent, array_merge( [ $buf ], array_slice( $tgtTokens, $i ) ) ];
191                            } else {
192                                return [ $buf, array_slice( $tgtTokens, $i ) ];
193                            }
194                        }
195                        break;
196
197                    case TagTk::class:
198                        if ( TokenUtils::isEntitySpanToken( $ntt ) ) {
199                            $buf .= $tgtTokens[$i + 1];
200                            $i += 2;
201                            break;
202                        }
203                        // Fall-through
204                    case EndTagTk::class:
205                        if ( $preNlContent !== null ) {
206                            return [ $preNlContent, array_merge( [ $buf ], array_slice( $tgtTokens, $i ) ) ];
207                        } else {
208                            return [ $buf, array_slice( $tgtTokens, $i ) ];
209                        }
210
211                    case CommentTk::class:
212                        // Ignore comments as well
213                        break;
214
215                    case NlTk::class:
216                        // Ignore only the leading or trailing newlines
217                        // (modulo whitespace and comments)
218                        //
219                        // If we only have whitespace in $buf thus far,
220                        // the newline can be ignored. But, if we have
221                        // non-ws content in $buf, everything that follows
222                        // can only be ws.
223                        if ( preg_match( '/^\s*$/D', $buf ) ) {
224                            $buf .= "\n";
225                            break;
226                        } elseif ( $preNlContent === null ) {
227                            // Buffer accumulated content
228                            $preNlContent = $buf;
229                            $buf = "\n";
230                            break;
231                        } else {
232                            return [ $preNlContent, array_merge( [ $buf ], array_slice( $tgtTokens, $i ) ) ];
233                        }
234
235                    default:
236                        throw new UnreachableException( 'Unexpected token type: ' . get_class( $ntt ) );
237                }
238            }
239            $i++;
240        }
241
242        // All good! No newline / only whitespace/comments post newline.
243        // (Well, annotation metas and template(arg) tokens too)
244        return [ $preNlContent . $buf, null ];
245    }
246
247    private function processPreprocToString( array $tokens, ?array &$result = null ): array {
248        $result ??= [];
249        foreach ( $tokens as $t ) {
250            $includeContents = false;
251            $skip = false;
252            if ( $t instanceof PreprocAngleTk ) {
253                $name = $t->name();
254                switch ( $name ) {
255                    case 'onlyinclude':
256                        $includeContents = true;
257                        break;
258                    case 'noinclude':
259                        if ( $this->options['inTemplate'] ) {
260                            $skip = true;
261                        } else {
262                            $includeContents = true;
263                        }
264                        break;
265                    case 'includeonly':
266                        if ( $this->options['inTemplate'] ) {
267                            $includeContents = true;
268                        } else {
269                            $skip = true;
270                        }
271                        break;
272                    default:
273                        if ( WTUtils::isAnnotationTag( $this->env, $name ) ) {
274                            // Ignore annotations in template targets (T295834)
275                            $includeContents = true;
276                        }
277                        break;
278                }
279            } elseif ( $t instanceof PreprocTk && $t->type === PreprocType::COMMENT ) {
280                $skip = true;
281            }
282            if ( $includeContents ) {
283                $this->processPreprocToString( $t->getContents(), $result );
284            } elseif ( !$skip ) {
285                $result[] = $t;
286            }
287        }
288        return $result;
289    }
290
291    /**
292     * Is the prefix "safesubst"
293     * @param string $prefix
294     * @return bool
295     */
296    private function isSafeSubst( $prefix ): bool {
297        if ( $this->safeSubstRegex === null ) {
298            $this->safeSubstRegex = $this->env->getSiteConfig()->getMagicWordMatcher( 'safesubst' );
299        }
300        return (bool)preg_match( $this->safeSubstRegex, $prefix . ':' );
301    }
302
303    /**
304     * @param TemplateEncapsulator $state
305     * @param string|Token|array $targetToks
306     * @param SourceRange $srcOffsets
307     * @phpcs:ignore Generic.Files.LineLength.TooLong
308     * @return ?array{magicWordType: '!'|null, name: string, title: Title, isVariable?: true, pfArg?: string|list<string|Token>, srcOffsets?: SourceRange, isParserFunction?: true, localName?: string, haveColon?: ?non-empty-string, handler?: \Wikimedia\Parsoid\Ext\PFragmentHandler, handlerOptions?: array}
309     */
310    private function resolveTemplateTarget(
311        TemplateEncapsulator $state, $targetToks, $srcOffsets
312    ): ?array {
313        $additionalToks = null;
314        if ( is_string( $targetToks ) ) {
315            $target = $targetToks;
316        } else {
317            $toks = !is_array( $targetToks ) ? [ $targetToks ] : $targetToks;
318            [ $target, $additionalToks ] = $this->processToString( $toks );
319        }
320
321        $target = trim( $target );
322        $pieces = preg_split( '/[::]/u', $target );
323        $untrimmedPrefix = $pieces[0];
324        $prefix = trim( $pieces[0] );
325
326        // Parser function names usually (not always) start with a hash
327        $hasHash = str_starts_with( $target, '#' ) ||
328            // Japanese uses double-wide hash (T415405)
329            str_starts_with( $target, '#' );
330        // String found after the colon will be the parser function arg
331        $haveColon = count( $pieces ) > 1;
332
333        // safesubst found in content should be treated as if no modifier were
334        // present. See https://en.wikipedia.org/wiki/Help:Substitution#The_safesubst:_modifier
335        if ( $haveColon && $this->isSafeSubst( $prefix ) ) {
336            $target = mb_substr( $target, mb_strlen( $untrimmedPrefix ) + 1 );
337            array_shift( $pieces );
338            $untrimmedPrefix = $pieces[0];
339            $prefix = trim( $pieces[0] );
340            $haveColon = count( $pieces ) > 1;
341        }
342
343        $env = $this->env;
344        $siteConfig = $env->getSiteConfig();
345
346        // Additional tokens are only justifiable in parser functions scenario
347        if ( !$haveColon && $additionalToks ) {
348            return null;
349        }
350
351        $pfArg = '';
352        $colon = '';
353        if ( $haveColon ) {
354            $colon = mb_substr( $target, mb_strlen( $untrimmedPrefix ), 1 );
355            $pfArg = mb_substr( $target, mb_strlen( $untrimmedPrefix ) + 1 );
356            if ( $additionalToks ) {
357                $pfArg = [ $pfArg ];
358                PHPUtils::pushArray( $pfArg, $additionalToks );
359            }
360        }
361
362        // Check if we have a magic variable implemented by the legacy parser
363        $magicWordVar = $siteConfig->getMagicWordForVariable( $prefix );
364        [ 'key' => $canonicalFunctionName, 'isNative' => $isNative ] =
365              $siteConfig->getMagicWordForParserFunction( $prefix );
366        if ( $canonicalFunctionName !== null && !$isNative ) {
367            // Parsoid's PFragmentHandler handles both magic variables (T391063)
368            // and zero-argument parser functions, but in the legacy
369            // parser "nohash" parser functions without a colon must
370            // be magic variables; they won't be invoked as parser
371            // functions.
372            if ( ( !$hasHash ) && ( !$haveColon ) ) {
373                $canonicalFunctionName = null;
374            }
375        }
376        // Ensure that magic words registered by parsoid PFragment handlers
377        // aren't confused for magic variables implemented by the legacy parser
378        if ( $magicWordVar && $canonicalFunctionName === null ) {
379            $state->variableName = $magicWordVar;
380            return [
381                'isVariable' => true,
382                'magicWordType' => $magicWordVar === '!' ? '!' : null,
383                'name' => $magicWordVar,
384                // FIXME: Some made up synthetic title
385                'title' => $env->makeTitleFromURLDecodedStr( "Special:Variable/$magicWordVar" ),
386                'pfArg' => $pfArg,
387                'haveColon' => $colon,
388                'srcOffsets' => new SourceRange(
389                    $srcOffsets->start + strlen( $untrimmedPrefix ) + strlen( $colon ),
390                    $srcOffsets->end,
391                    $srcOffsets->source ),
392            ];
393        }
394
395        // FIXME: Checks for msgnw, msg, raw are missing at this point
396
397        $broken = false;
398        if ( $canonicalFunctionName === null && $hasHash ) {
399            // If the target starts with a '#' it can't possibly be a template
400            // so this must be a "broken" parser function invocation
401            $canonicalFunctionName = mb_substr( $prefix, 1 );
402            $broken = true;
403            // @todo: Flag this as an author error somehow (T314524)
404        }
405        if ( $canonicalFunctionName !== null ) {
406            $state->parserFunctionName = $canonicalFunctionName;
407            // XXX this is made up.
408            $syntheticTitle = $env->makeTitleFromURLDecodedStr(
409                "Special:ParserFunction/$canonicalFunctionName",
410                $env->getSiteConfig()->canonicalNamespaceId( 'Special' ),
411                true // No exceptions
412            );
413            // Note that parserFunctionName/$canonicalFunctionName is not
414            // necessarily a valid title!  Parsing rules are pretty generous
415            // w/r/t valid parser function names.
416            if ( $syntheticTitle === null ) {
417                $syntheticTitle = $env->makeTitleFromText(
418                    'Special:ParserFunction/unknown'
419                );
420            }
421            $ret = [
422                'isParserFunction' => true,
423                'magicWordType' => null,
424                'name' => $canonicalFunctionName,
425                'localName' => $prefix,
426                'title' => $syntheticTitle, // FIXME: Some made up synthetic title
427                'pfArg' => $pfArg,
428                'haveColon' => $colon, // FIXME: T391063
429                'srcOffsets' => new SourceRange(
430                    $srcOffsets->start + strlen( $untrimmedPrefix ) + strlen( $colon ),
431                    $srcOffsets->end,
432                    $srcOffsets->source ),
433            ];
434
435            // Check if we have a Parsoid PFragment handler for this parser func
436            // ($canonicalFunctionName is invalid/not localized if this is
437            // $broken)
438            $pFragmentHandler = ( $broken || !$isNative ) ? null :
439                $siteConfig->getPFragmentHandlerImpl( $canonicalFunctionName );
440            if ( $pFragmentHandler ) {
441                $ret['handler'] = $pFragmentHandler;
442                $ret['handlerOptions'] = $siteConfig->getPFragmentHandlerConfig(
443                    $canonicalFunctionName
444                )['options'] ?? [];
445                $state->isOldParserFunction = false;
446            }
447            return $ret;
448        }
449
450        // We've exhausted the parser-function scenarios, and we still have additional tokens.
451        if ( $additionalToks ) {
452            return null;
453        }
454
455        // Resolve a possibly relative link and
456        // normalize the target before template processing.
457        try {
458            $title = $env->resolveTitle( $target );
459        } catch ( TitleException ) {
460            // Invalid template target!
461            return null;
462        }
463
464        // `resolveTitle()` adds the namespace prefix when it resolves fragments
465        // and relative titles, and a leading colon should resolve to a template
466        // from the main namespace, hence we omit a default when making a title.
467        // In addition, [[../Foo]] resolves relative to the current title and
468        // hence doesn't belong to the Template: namespace either.
469        $namespaceId = strspn( $target, ':#/' ) > 0 || str_starts_with( $target, "../" ) ?
470            null : $siteConfig->canonicalNamespaceId( 'template' );
471
472        // Entities in transclusions aren't decoded in the PHP parser
473        // So, treat the title as a url-decoded string!
474        $title = $env->makeTitleFromURLDecodedStr( $title, $namespaceId, true );
475        if ( !$title ) {
476            // Invalid template target!
477            return null;
478        }
479
480        // data-mw.target.href should be a url
481        $state->templateTarget = $env->makeLink( $title );
482
483        return [
484            'magicWordType' => null,
485            'name' => $title->getPrefixedDBKey(),
486            'title' => $title,
487        ];
488    }
489
490    /**
491     * By default, don't attempt to expand any templates in the wikitext that will be reprocessed.
492     *
493     * @param XMLTagTk $token
494     * @param bool $expandTemplates
495     * @return TemplateExpansionResult
496     */
497    private function convertToString( XMLTagTk $token, bool $expandTemplates = false ): TemplateExpansionResult {
498        $frame = $this->manager->getFrame();
499        $tsr = $token->dataParsoid->tsr;
500        $src = substr( $token->dataParsoid->src, 2, -2 );
501        $startOffset = $tsr->start + 2;
502        $srcOffsets = new SourceRange( $startOffset, $startOffset + strlen( $src ), $tsr->source );
503
504        $toks = PipelineUtils::processContentInPipeline(
505            $this->env, $frame, $src, [
506                'pipelineType' => 'wikitext-to-expanded-tokens',
507                'pipelineOpts' => [
508                    'inTemplate' => $this->options['inTemplate'],
509                    'expandTemplates' => $expandTemplates && $this->options['expandTemplates'],
510                ],
511                'sol' => false,
512                // FIXME: Set toplevel when bailing
513                // 'toplevel' => $this->atTopLevel,
514                'srcOffsets' => $srcOffsets,
515            ]
516        );
517        TokenUtils::stripEOFTkFromTokens( $toks );
518        return new TemplateExpansionResult( array_merge( [ '{{' ], $toks, [ '}}' ] ), true );
519    }
520
521    /**
522     * Enforce template loops / loop depth limit constraints and emit
523     * error message if constraints are violated.
524     *
525     * @param mixed $target
526     * @param Title $title
527     * @param bool $ignoreLoop
528     *
529     * @return ?list<string|Token>
530     */
531    private function enforceTemplateConstraints( $target, Title $title, bool $ignoreLoop ): ?array {
532        $error = $this->manager->getFrame()->loopAndDepthCheck(
533            $title, $this->env->getSiteConfig()->getMaxTemplateDepth(),
534            $ignoreLoop
535        );
536
537        return $error ? [ // Loop detected or depth limit exceeded, abort!
538            new TagTk( 'span', [ new KV( 'class', 'error' ) ] ),
539            $error,
540            new SelfclosingTagTk( 'wikilink', [ new KV( 'href', $target, null, '', '' ) ] ),
541            new EndTagTk( 'span' ),
542        ] : null;
543    }
544
545    /**
546     * Fetch, tokenize and token-transform a template after all arguments and
547     * the target were expanded.
548     *
549     * @param TemplateEncapsulator $state
550     * @param array $resolvedTgt
551     * @param array $attribs
552     * @return TemplateExpansionResult
553     */
554    private function expandTemplateNatively(
555        TemplateEncapsulator $state, array $resolvedTgt, array $attribs
556    ): TemplateExpansionResult {
557        $env = $this->env;
558        $encap = $this->options['expandTemplates'] && $this->wrapTemplates;
559
560        // XXX: wrap attribs in object with .dict() and .named() methods,
561        // and each member (key/value) into object with .tokens(), .dom() and
562        // .wikitext() methods (subclass of Array)
563
564        $target = $resolvedTgt['name'];
565        if ( isset( $resolvedTgt['isParserFunction'] ) || isset( $resolvedTgt['isVariable'] ) ) {
566            // FIXME: HARDCODED to core parser function implementations!
567            // These should go through function hook registrations in the
568            // ParserTests mock setup ideally. But, it is complicated because the
569            // Parsoid core parser function versions have "token" versions
570            // which are incompatible with implementation in FunctionHookHandler
571            // and FunctionArgs. So, we continue down this hacky path for now.
572            if ( $target === '=' ) {
573                $target = 'equal';  // '=' is not a valid character in function names
574            }
575            $target = 'pf_' . $target;
576            // FIXME: Parsoid may not have implemented the parser function natively
577            // Emit an error message, but encapsulate it so it roundtrips back.
578            if ( !is_callable( [ $this->parserFunctions, $target ] ) ) {
579                // FIXME: Consolidate error response format with enforceTemplateConstraints
580                $err = 'Parser function implementation for ' . $target . ' missing in Parsoid.';
581                return new TemplateExpansionResult( [ $err ], false, $encap );
582            }
583
584            $pfAttribs = new Params( $attribs );
585            $pfAttribs->args[0] = new KV(
586                // FIXME: This is bogus, but preserves borked b/c
587                TokenUtils::tokensToString( $resolvedTgt['pfArg'] ), [],
588                $resolvedTgt['srcOffsets']->expandTsrK()
589            );
590            $env->log( 'debug', 'entering prefix', $target, $state->token );
591            $res = $this->parserFunctions->$target(
592                $state->token, $this->manager->getFrame(), $pfAttribs );
593            if ( $this->wrapTemplates ) {
594                $res = $this->parserFunctionsWrapper( $res );
595            }
596            return new TemplateExpansionResult( $res, false, $encap );
597        }
598
599        // Loop detection needs to be enabled since we're doing our own template expansion
600        $error = $this->enforceTemplateConstraints( $target, $resolvedTgt['title'], false );
601        if ( $error ) {
602            // FIXME: Should we be encapsulating here?
603            // Inconsistent with the other place constrainsts are enforced.
604            return new TemplateExpansionResult( $error, false, $encap );
605        }
606
607        // XXX: notes from brooke's mediawiki.parser.environment
608        // resolve template name
609        // load template w/ canonical name
610        // load template w/ variant names (language variants)
611
612        // Fetch template source and expand it
613        $pageContent = $this->fetchTemplateAndTitle( $target, $attribs );
614        if ( $pageContent !== null ) {
615            $state->resolvedTemplateTitle = $env->makeLink(
616                Title::newFromLinkTarget(
617                    $pageContent->getLinkTarget(), $env->getSiteConfig()
618                )
619            );
620            $state->resolvedTemplateRevision = $pageContent->getRevisionId();
621            $toks = $this->processTemplateSource(
622                $this->manager->getFrame(),
623                $state->token,
624                [
625                    'name' => $target,
626                    'title' => $resolvedTgt['title'],
627                    'attribs' => array_slice( $attribs, 1 ), // strip template target
628                ],
629                // FIXME: Hard-coded 'main' role
630                $pageContent->getContent( 'main' ),
631                $this->options
632            );
633            return new TemplateExpansionResult( $toks, true, $encap );
634        } else {
635            // Convert to a wikilink (which will become a redlink after the redlinks pass).
636            $toks = [ new SelfclosingTagTk( 'wikilink' ) ];
637            $hrefSrc = ':' . strtr( $resolvedTgt['name'], '_', ' ' );
638            $toks[0]->attribs[] = new KV( 'href', $hrefSrc, null, null, $hrefSrc );
639            return new TemplateExpansionResult( $toks, false, $encap );
640        }
641    }
642
643    /**
644     * Process a fetched template source to a token stream.
645     *
646     * @return list<string|Token>
647     */
648    private function processTemplateSource(
649        Frame $frame, Token $token, array $tplArgs, string $src,
650        array $options = []
651    ): array {
652        if ( $this->env->hasDumpFlag( 'tplsrc' ) ) {
653            PipelineUtils::dumpTplSrc(
654                $this->env, $token, $tplArgs['name'], $src, false
655            );
656        }
657        $this->env->log( 'debug', 'TemplateHandler.processTemplateSource',
658            $tplArgs['name'], $tplArgs['attribs'] );
659        $toks = PipelineUtils::processTemplateSource(
660            $this->env,
661            $frame,
662            $token,
663            $tplArgs,
664            $src,
665            $options
666        );
667        return $this->processTemplateTokens( $toks );
668    }
669
670    /**
671     * Process the main template element, including the arguments.
672     *
673     * @param TemplateEncapsulator $state
674     * @param array<string|Token> $tokens
675     * @return array<string|Token>
676     */
677    private function encapTokens( TemplateEncapsulator $state, array $tokens ): array {
678        // Template encapsulation normally wouldn't happen in nested context,
679        // since they should have already been expanded, and indeed we set
680        // expandTemplates === false in processTemplateSource.  However,
681        // extension tags from templates can have content that requires wikitext
682        // parsing and, due to precedence, contain unexpanded templates.
683        //
684        // For example, {{1x|hi<ref>{{1x|ho}}</ref>}}
685        //
686        // Since extensions can require template expansion unconditionally, we can
687        // end up here inTemplate, in which case the substrings of env.page.src
688        // used in getArgInfo are no longer accurate, and so tplarginfo should be
689        // omitted.  Presumably, template wrapping in the dom post processor won't
690        // be happening anyways, so this is unnecessary work as it is.
691        Assert::invariant(
692            $this->wrapTemplates, 'Encapsulating tokens when not wrapping!'
693        );
694        return $state->encapTokens( $tokens );
695    }
696
697    /**
698     * Handle chunk emitted from the input pipeline after feeding it a template.
699     *
700     * @param array<string|Token> $chunk
701     * @return array<string|Token>
702     */
703    private function processTemplateTokens( array $chunk ): array {
704        TokenUtils::stripEOFTkFromTokens( $chunk );
705
706        foreach ( $chunk as $i => $t ) {
707            if ( !$t ) {
708                continue;
709            }
710
711            if ( isset( $t->dataParsoid->tsr ) ) {
712                unset( $t->dataParsoid->tsr );
713            }
714            Assert::invariant( !isset( $t->dataParsoid->tmp->endTSR ),
715                "Expected endTSR to not be set on templated content." );
716            if ( $t instanceof SelfclosingTagTk &&
717                strtolower( $t->getName() ) === 'meta' &&
718                TokenUtils::hasTypeOf( $t, 'mw:Placeholder' )
719            ) {
720                // replace with empty string to avoid metas being foster-parented out
721                $chunk[$i] = '';
722            }
723        }
724
725        // FIXME: What is this stuff here? Why do we care about stripping out comments
726        // so much that we create a new token array for every expanded template?
727        // Unlikely to help perf very much.
728        if ( !$this->options['expandTemplates'] ) {
729            // Ignore comments in template transclusion mode
730            $newChunk = [];
731            for ( $i = 0, $n = count( $chunk ); $i < $n;  $i++ ) {
732                if ( !( $chunk[$i] instanceof CommentTk ) ) {
733                    $newChunk[] = $chunk[$i];
734                }
735            }
736            $chunk = $newChunk;
737        }
738
739        $this->env->log( 'debug', 'TemplateHandler.processTemplateTokens', $chunk );
740        return $chunk;
741    }
742
743    /**
744     * Fetch a template.
745     *
746     * @param string $templateName
747     * @param array $attribs
748     * @return ?PageContent
749     */
750    private function fetchTemplateAndTitle( string $templateName, array $attribs ): ?PageContent {
751        $env = $this->env;
752        $title = Title::newFromText( $templateName, $env->getSiteConfig() );
753        if ( isset( $env->pageCache[$templateName] ) ) {
754            return new MockPageContent(
755                [ 'main' => $env->pageCache[$templateName] ],
756                $title,
757                1234
758            );
759        }
760
761        $start = hrtime( true );
762        $pageContent = $env->getDataAccess()->fetchTemplateSource(
763            $env->getPageConfig(),
764            $title
765        );
766        if ( $env->profiling() ) {
767            $profile = $env->getCurrentProfile();
768            $profile->bumpMWTime( "TemplateFetch", hrtime( true ) - $start, "api" );
769            $profile->bumpCount( "TemplateFetch" );
770        }
771
772        return $pageContent;
773    }
774
775    /**
776     * Process the special magic word as specified by $resolvedTgt['magicWordType'].
777     * ```
778     * magicWordType === '!' => {{!}} is the magic word
779     * ```
780     * @param TemplateEncapsulator $state
781     * @param array $resolvedTgt
782     * @return TemplateExpansionResult
783     */
784    private function processSpecialMagicWord(
785        TemplateEncapsulator $state, array $resolvedTgt
786    ): TemplateExpansionResult {
787        // Special case for {{!}} magic word.
788        //
789        // If we tokenized as a magic word, we meant for it to expand to a
790        // string.  The tokenizer has handling for this syntax in table
791        // positions.  However, proceeding to go through template expansion
792        // will reparse it as a table cell token.  Hence this special case
793        // handling to avoid that path.
794        if ( $resolvedTgt['magicWordType'] === '!' ) {
795            // If we're not at the top level, return a table cell. This will always
796            // be the case. Either {{!}} was tokenized as a td, or it was tokenized
797            // as template but the recursive call to fetch its content returns a
798            // single | in an ambiguous context which will again be tokenized as td.
799            // In any case, this should only be relevant for parserTests.
800            if ( $this->options['inTemplate'] ) {
801                $td = new TagTk( 'td' );
802                $td->dataParsoid->getTemp()->attrSrc = '';
803                $td->dataParsoid->setTempFlag( TempData::AT_SRC_START );
804                $toks = [ $td ];
805            } else {
806                $toks = [ '|' ];
807            }
808            return new TemplateExpansionResult( $toks, false, (bool)$this->wrapTemplates );
809        }
810
811        throw new UnreachableException(
812            'Unsupported magic word type: ' . ( $resolvedTgt['magicWordType'] ?? 'null' )
813        );
814    }
815
816    private function expandTemplate( TemplateEncapsulator $state ): TemplateExpansionResult {
817        $env = $this->env;
818        $token = $state->token;
819        $expandTemplates = $this->options['expandTemplates'];
820        $isTemplate3 = ( $token->getName() === 'template3' );
821
822        // Since AttributeExpander runs later in the pipeline than TemplateHandler,
823        // if the template name is templated, use our copy of AttributeExpander
824        // to process the first attribute to tokens, and force reprocessing of this
825        // template token since we will then know the actual template target.
826        // FIXME: we should eventually make this work for template3 tokens,
827        // which would require tokenizing $token->attribs[0]->k and then
828        // converting the result to a string and preprocessing it.
829        if ( $expandTemplates && TokenUtils::hasTemplateToken( $token->attribs[0]->k ) && !$isTemplate3 ) {
830            $ret = $this->ae->expandFirstAttribute( $token );
831            Assert::invariant( $ret === [ $token ],
832                "Expected only the input token as the return value." );
833            // $token is modified in place and $ret is unused after this.
834        }
835
836        if ( $this->atMaxArticleSize ) {
837            // As described above, if we were already greater than $wgMaxArticleSize
838            // we're going to return the tokens without expanding them.
839            // (This case is where the original article as fetched from the DB
840            // or passed to the API exceeded max article size.)
841            return $this->convertToString( $token );
842        }
843
844        // There's no point in proceeding if we've already hit the maximum inclusion size
845        // XXX should this be combined with the previous test?
846        if ( !$env->bumpWt2HtmlResourceUse( 'wikitextSize', 0 ) ) {
847            // FIXME: The legacy parser would try to make this a link and
848            // elsewhere we'd return the $e->getMessage()
849            // (This case is where the template post-expansion accumulation is
850            // over the maximum wikitext size.)
851            // XXX: It could be combined with the previous test, but we might
852            // want to use different error messages in the future.
853            return $this->convertToString( $token );
854        }
855
856        $text = $token->dataParsoid->src ?? '';
857
858        $tgt = $this->resolveTemplateTarget(
859            $state, $token->attribs[0]->k, $token->attribs[0]->srcOffsets->key
860        );
861
862        if ( $expandTemplates && $tgt === null ) {
863            // Target contains tags, convert template braces and pipes back into text
864            // Re-join attribute tokens with '=' and '|'
865            return $this->convertToString( $token, true );
866        }
867
868        if (
869            $env->linting( 'pre-expansion' ) &&
870            ( $this->options['inTemplate'] ?? false ) &&
871            ( $this->options['extTag'] ?? '' ) === 'pre'
872        ) {
873            // T353697: Temporarily lint template expansion in wikitext format
874            // pre extension tags to migrate escape mechanisms
875            $name = PHPUtils::stripPrefix( $env->makeLink(
876                $this->manager->getFrame()->getTitle() ), './'
877            );
878            $lint = [
879                'dsr' => new DomSourceRange( 0, 0, null, null, source: null ),
880                'templateInfo' => [ 'name' => $name ],
881            ];
882            $env->recordLint( 'pre-expansion', $lint );
883        }
884
885        if ( isset( $tgt['magicWordType'] ) ) {
886            return $this->processSpecialMagicWord( $state, $tgt );
887        }
888
889        $frame = $this->manager->getFrame();
890        if ( isset( $tgt['handler'] ) ) {
891            $handler = $tgt['handler'];
892            $extApi = new ParsoidExtensionAPI( $env, [
893                'wt2html' => [
894                    'frame' => $frame,
895                    'parseOpts' => $this->options,
896                ],
897            ] );
898            if ( !$isTemplate3 ) {
899                // Retokenize!
900                $tokenizer = new PegTokenizer( $env );
901                $origToken = $token;
902                $token = $tokenizer->tokenizeTemplate3(
903                    $token->dataParsoid->src, $token->dataParsoid->tsr
904                );
905                if ( $token === false ) {
906                    return $this->convertToString( $origToken );
907                }
908                $state->token = $token;
909            }
910            $args = $token->attribs;
911            if ( isset( $tgt['isVariable'] ) || isset( $tgt['isParserFunction'] ) ) {
912                $hasColon = null;
913                $args = TemplateEncapsulator::adjustParserFunctionArg0( $args, $hasColon );
914                if ( $hasColon !== null ) {
915                    $token->dataParsoid->colon = $hasColon;
916                }
917            }
918            // discard the target
919            array_shift( $args );
920            $arguments = new TemplateHandlerArguments(
921                $args, DomSourceRange::fromTsr( $token->dataParsoid->tsr )
922            );
923            $hasAsyncContent = $tgt['handlerOptions']['hasAsyncContent'] ?? false;
924            if ( $hasAsyncContent ) {
925                // The HAS_ASYNC_CONTENT flag needs to be set by the fragment
926                // handler if this handler can *ever* return async content,
927                // regardless of whether this particular fragment was ready.
928                $env->getMetadata()->setOutputFlag( 'has-async-content' );
929            }
930            $fragment = $handler->sourceToFragment(
931                $extApi,
932                $arguments,
933                tagSyntax: false /* this is using {{ ... }} syntax */
934            );
935            if ( $fragment instanceof AsyncResult ) {
936                Assert::invariant(
937                    $hasAsyncContent,
938                    "returning async result without declaration"
939                );
940                $fragment = PipelineUtils::handleAsyncResult(
941                    $extApi, $fragment,
942                    DomSourceRange::fromTsr( $token->dataParsoid->tsr )
943                );
944            }
945            // Map fragment to parsoid wikitext + embedded markers
946            [
947                'wikitext' => $wikitext,
948            ] = PipelineUtils::preparePFragment(
949                $env,
950                $this->manager->getFrame(),
951                $fragment,
952                [
953                    // options
954                ]
955            );
956            $tplToks = $this->processTemplateSource(
957                $this->manager->getFrame(),
958                $token,
959                [
960                    'name' => $tgt['name'],
961                    'title' => $tgt['title'],
962                    'attribs' => [],
963                ],
964                $wikitext,
965                [
966                    // PFragmentHandlers are expressly allowed to request
967                    // template expansion.  This supports the lazy
968                    // evaluation of arguments and other fun features.
969                    'expandTemplates' => true,
970                ] + $this->options
971            );
972            return new TemplateExpansionResult(
973                $tplToks, true, $this->wrapTemplates
974            );
975        }
976
977        if ( $env->nativeTemplateExpansionEnabled() ) {
978            if ( $isTemplate3 ) {
979                // Retokenize for compatibility
980                $tokenizer = new PegTokenizer( $env );
981                $token = $tokenizer->tokenizeTemplate(
982                    $token->dataParsoid->src, $token->dataParsoid->tsr
983                );
984                Assert::invariant( $token !== false, "Failed to retokenize" );
985                $state->token = $token;
986            }
987            // Expand argument keys
988            $newAttribs = AttributeTransformManager::process(
989                $frame,
990                [ 'expandTemplates' => false, 'inTemplate' => true ],
991                $token->attribs
992            ) ?? $token->attribs;
993            $target = $newAttribs[0]->k;
994            if ( !$target ) {
995                $env->log( 'debug', 'No template target! ', $newAttribs );
996            }
997            // Resolve the template target again now that the template token's
998            // attributes have been expanded by the AttributeTransformManager
999            $resolvedTgt = $this->resolveTemplateTarget( $state, $target, $newAttribs[0]->srcOffsets->key );
1000            if ( $resolvedTgt === null ) {
1001                // Target contains tags, convert template braces and pipes back into text
1002                // Re-join attribute tokens with '=' and '|'
1003                return $this->convertToString( $token, true );
1004            } else {
1005                return $this->expandTemplateNatively( $state, $resolvedTgt, $newAttribs );
1006            }
1007        } elseif ( $expandTemplates ) {
1008            // Use MediaWiki's preprocessor
1009            //
1010            // The tokenizer needs to use `text` as the cache key for caching
1011            // expanded tokens from the expanded transclusion text that we get
1012            // from the preprocessor, since parameter substitution will already
1013            // have taken place.
1014            //
1015            // It's sufficient to pass `[]` in place of attribs since they
1016            // won't be used.  In `usePHPPreProcessor`, there is no parameter
1017            // substitution coming from the frame.
1018
1019            /* If $tgt is not null, target will be present. */
1020            $templateName = $tgt['name'];
1021            $templateTitle = $tgt['title'];
1022            if ( $tgt['haveColon'] ?? false ) {
1023                $token->dataParsoid->colon = $tgt['haveColon'];
1024            }
1025            // FIXME: This is a source of a lot of issues since templateargs
1026            // get looked up from the Frame and yield these tokens which then enter
1027            // the token stream. See T301948 and others from wmf.22
1028            // $attribs = array_slice( $token->attribs, 1 ); // Strip template name
1029            $attribs = [];
1030
1031            // We still need to check for limit violations because of the
1032            // higher precedence of extension tags, which can result in nested
1033            // templates even while using the php preprocessor for expansion.
1034            $error = $this->enforceTemplateConstraints( $templateName, $templateTitle, true );
1035            if ( $error ) {
1036                // FIXME: Should we be encapsulating here?
1037                // Inconsistent with the other place constrainsts are enforced.
1038                return new TemplateExpansionResult( $error );
1039            }
1040
1041            // Fetch and process the template expansion
1042            $error = false;
1043            $fragment = Wikitext::preprocessFragment(
1044                $env, WikitextPFragment::newFromWt( $text, null ), $error
1045            );
1046            if ( $error ) {
1047                return new TemplateExpansionResult(
1048                    [ $fragment->killMarkers() ], false, $this->wrapTemplates
1049                );
1050            } else {
1051                if (
1052                    $fragment instanceof WikitextPFragment &&
1053                    !$fragment->containsMarker() &&
1054                    $fragment->getSrcOffsets() !== null
1055                ) {
1056                    // Optimize simple case
1057                    $wikitext = $fragment->killMarkers();
1058                    $srcOffsets = $fragment->getSrcOffsets();
1059                } else {
1060                    // This is a mixed expansion which contains wikitext and
1061                    // atomic PFragments.  Process this to tokens.
1062                    // (Contrast with the processing of {{#parsoid-fragment}}
1063                    // above, which represents an atomic PFragment.)
1064                    [
1065                        'wikitext' => $wikitext,
1066                        'srcOffsets' => $srcOffsets,
1067                    ] = PipelineUtils::preparePFragment(
1068                        $env,
1069                        $this->manager->getFrame(),
1070                        $fragment,
1071                        [
1072                            // options
1073                        ]
1074                    );
1075                }
1076                $tplToks = $this->processTemplateSource(
1077                    $this->manager->getFrame(),
1078                    $token,
1079                    [
1080                        'name' => $templateName,
1081                        'title' => $templateTitle,
1082                        'attribs' => $attribs
1083                    ],
1084                    $wikitext,
1085                    [
1086                        // Template like content returned from the
1087                        // preprocessor should not be further expanded
1088                        'expandTemplates' => false,
1089                        'srcOffsets' => $srcOffsets,
1090                    ] + $this->options
1091                );
1092                return new TemplateExpansionResult(
1093                    $tplToks, true, $this->wrapTemplates
1094                );
1095            }
1096        } else {
1097            // We don't perform recursive template expansion- something
1098            // template-like that the PHP parser did not expand. This is
1099            // encapsulated already, so just return the plain text.
1100            Assert::invariant( TokenUtils::isTemplateToken( $token ), "Expected template token." );
1101            return $this->convertToString( $token );
1102        }
1103    }
1104
1105    /**
1106     * Main template token handler.
1107     *
1108     * Expands target and arguments (both keys and values) and either directly
1109     * calls or sets up the callback to expandTemplate, which then fetches and
1110     * processes the template.
1111     * @return array<string|Token>
1112     */
1113    private function onTemplate( XMLTagTk $token ): array {
1114        $state = new TemplateEncapsulator(
1115            $this->env, $this->manager->getFrame(), $token, 'mw:Transclusion'
1116        );
1117        $res = $this->expandTemplate( $state );
1118        $toks = $res->tokens;
1119
1120        if ( $res->encap ) {
1121            $toks = $this->encapTokens( $state, $toks );
1122        }
1123        if ( $res->shuttle ) {
1124            // Shuttle tokens to the end of the stage since they've gone through the
1125            // rest of the handlers in the current pipeline in the pipeline above.
1126            $toks = $this->manager->shuttleTokensToEndOfStage( $toks );
1127        }
1128        return $toks;
1129    }
1130
1131    /**
1132     * Expand template arguments with tokens from the containing frame.
1133     * @return array<string|Token>
1134     */
1135    private function onTemplateArg( XMLTagTk $token ): array {
1136        $toks = $this->manager->getFrame()->expandTemplateArg( $token );
1137
1138        if ( $this->wrapTemplates && $this->options['expandTemplates'] ) {
1139            // This is a bare use of template arg syntax at the top level
1140            // outside any template use context.  Wrap this use with RDF attrs.
1141            // so that this chunk can be RT-ed en-masse.
1142            $state = new TemplateEncapsulator(
1143                $this->env, $this->manager->getFrame(), $token, 'mw:Param'
1144            );
1145            $toks = $this->encapTokens( $state, $toks );
1146        }
1147
1148        // Shuttle tokens to the end of the stage since they've gone through the
1149        // rest of the handlers in the current pipeline in the pipeline above.
1150        $toks = $this->manager->shuttleTokensToEndOfStage( $toks );
1151
1152        return $toks;
1153    }
1154
1155    /** @inheritDoc */
1156    public function onTag( XMLTagTk $token ): ?array {
1157        return match ( $token->getName() ) {
1158            'template', 'template3' => $this->onTemplate( $token ),
1159            'templatearg' => $this->onTemplateArg( $token ),
1160            default => null
1161        };
1162    }
1163}