Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 251
0.00% covered (danger)
0.00%
0 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
TemplateEncapsulator
0.00% covered (danger)
0.00%
0 / 251
0.00% covered (danger)
0.00%
0 / 11
3782
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 encapTokens
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
72
 getTemplateInfo
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
72
 preparePfParamInfos
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
56
 prepareTemplate3ParamInfos
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
30
 adjustParserFunctionArg0
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
12
 prepareTplParamInfos
0.00% covered (danger)
0.00%
0 / 48
0.00% covered (danger)
0.00%
0 / 1
240
 getEncapsulationInfo
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 getEncapsulationInfoEndTag
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 isSimpleParam
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
42
 getParamHTML
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid\Wt2Html\TT;
5
6use Wikimedia\Assert\Assert;
7use Wikimedia\Parsoid\Config\Env;
8use Wikimedia\Parsoid\Core\Source;
9use Wikimedia\Parsoid\Core\SourceRange;
10use Wikimedia\Parsoid\DOM\Element;
11use Wikimedia\Parsoid\NodeData\DataParsoid;
12use Wikimedia\Parsoid\NodeData\ParamInfo;
13use Wikimedia\Parsoid\NodeData\TemplateInfo;
14use Wikimedia\Parsoid\Tokens\CommentTk;
15use Wikimedia\Parsoid\Tokens\KV;
16use Wikimedia\Parsoid\Tokens\NlTk;
17use Wikimedia\Parsoid\Tokens\PreprocTk;
18use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
19use Wikimedia\Parsoid\Tokens\Token;
20use Wikimedia\Parsoid\Tokens\XMLTagTk;
21use Wikimedia\Parsoid\Utils\ContentUtils;
22use Wikimedia\Parsoid\Utils\DOMDataUtils;
23use Wikimedia\Parsoid\Utils\DOMUtils;
24use Wikimedia\Parsoid\Utils\PipelineUtils;
25use Wikimedia\Parsoid\Utils\TokenUtils;
26use Wikimedia\Parsoid\Wt2Html\Frame;
27use Wikimedia\Parsoid\Wt2Html\PegTokenizer;
28
29/**
30 * A helper class for TemplateHandler that encapsulates template-like syntax
31 * with the appropriate meta tags, adding argument info data.
32 */
33class TemplateEncapsulator {
34    private Env $env;
35    private Frame $frame;
36    private PegTokenizer $tokenizer;
37    private string $wrapperType;
38    private string $aboutId;
39    public XMLTagTk $token;
40    public ?string $variableName = null;
41    public ?string $parserFunctionName = null;
42    public ?string $templateTarget = null;
43    public ?string $resolvedTemplateTitle = null;
44    public ?int $resolvedTemplateRevision = null;
45    // Should we use the "legacy" parser function format?
46    public bool $isOldParserFunction = true;
47
48    public function __construct( Env $env, Frame $frame, XMLTagTk $token, string $wrapperType ) {
49        $this->env = $env;
50        $this->frame = $frame;
51        $this->tokenizer = new PegTokenizer( $env );
52        $this->token = $token;
53        $this->wrapperType = $wrapperType;
54        $this->aboutId = $env->newAboutId();
55        /*
56         * Are we generating v3 parser function output for all parser functions
57         * or just for the output of PFragmentHandlers?
58         */
59        // @phan-suppress-next-line PhanDeprecatedFunction
60        if ( (bool)$this->env->getSiteConfig()->getMWConfigValue(
61            'ParsoidExperimentalParserFunctionOutput'
62        ) ) {
63            $this->isOldParserFunction = false;
64        }
65    }
66
67    /**
68     * Main entry point.
69     * Encapsulate the template element, including the arguments.
70     *
71     * @param array<string|Token> $tokens
72     * @return array<string|Token>
73     */
74    public function encapTokens( array $tokens ): array {
75        $toks = $this->getEncapsulationInfo( $tokens );
76        $toks[] = $this->getEncapsulationInfoEndTag();
77        $tplInfo = $this->getTemplateInfo();
78
79        if ( $this->env->getSiteConfig()->addHTMLTemplateParameters() ) {
80            // Parse the parameters that need parsing
81            foreach ( $tplInfo->paramInfos as $paramInfo ) {
82                if ( $paramInfo->named ) {
83                    $paramTokens = $this->token->getAttributeV( $paramInfo->k );
84                } else {
85                    $paramTokens = $this->token->attribs[$paramInfo->k]->v;
86                }
87
88                // No need to pass through a whole sub-pipeline to get the
89                // html if the param is either a single string, or if it's
90                // just text, comments or newlines.
91                if ( $paramTokens &&
92                    ( is_string( $paramTokens ) || self::isSimpleParam( $paramTokens ) )
93                ) {
94                    $paramInfo->html = $paramInfo->valueWt;
95                } elseif (
96                    // FIXME: this should not have its own regex parsing separate from the PEG
97                    preg_match( '#^https?://[^[\]{}\s]*$#D', $paramInfo->valueWt )
98                ) {
99                    // If the param is just a simple URL, we can process it to
100                    // HTML directly without going through a sub-pipeline.
101                    $paramInfo->html = "<a rel='mw:ExtLink' href='" .
102                        str_replace( "'", '&#39;', $paramInfo->valueWt ) . "'>" .
103                        $paramInfo->valueWt . '</a>';
104                } else {
105                    $this->getParamHTML( $paramInfo );
106                }
107            }
108        } else {
109            // Don't add the HTML template parameters, just use their wikitext
110        }
111
112        $toks[0]->dataParsoid->getTemp()->tplarginfo = $tplInfo;
113
114        $this->env->log( 'debug', 'TemplateEncapsulator.encapTokens', $toks );
115        return $toks;
116    }
117
118    /**
119     * Get the public data-mw structure that exposes the template name and
120     * parameters.
121     *
122     * @return TemplateInfo
123     */
124    private function getTemplateInfo(): TemplateInfo {
125        $ret = new TemplateInfo;
126        $src = $this->frame->getSource();
127        $params = $this->token->attribs;
128
129        // Add in tpl-target/pf-name info
130        // Only one of these will be set.
131        if ( $this->variableName !== null ) {
132            $ret->func = $this->variableName;
133            $ret->type = 'old-parserfunction';
134        } elseif ( $this->parserFunctionName !== null ) {
135            $ret->func = $this->parserFunctionName;
136            $ret->type = $this->isOldParserFunction ?
137                'old-parserfunction' : 'parserfunction';
138        } elseif ( $this->templateTarget !== null ) {
139            $ret->href = $this->templateTarget;
140            $ret->resolvedTitle = $this->resolvedTemplateTitle;
141            $ret->resolvedRevId = $this->resolvedTemplateRevision;
142        }
143
144        // If this was tokenized as a 'template3' the ParamInfos are
145        // prepared from the "preprocessed" arguments.
146        if ( $this->token->getName() === 'template3' ) {
147            $ret->paramInfos =
148                $this->prepareTemplate3ParamInfos( $src, $ret, $params );
149            return $ret;
150        }
151
152        // For 'template' tokens we need to construct ParamInfo from
153        // the the tokenized arguments.
154        $tgtSrcOffsets = $params[0]->srcOffsets;
155        if ( $tgtSrcOffsets ) {
156            $tplTgtWT = $tgtSrcOffsets->key->substr( $src );
157            $ret->targetWt = $tplTgtWT;
158        }
159
160        // Parser functions in the legacy parser do not support named
161        // parameters (T204307).  (Our new V3 parser functions do,
162        // but only if tokenized as a 'template3'.)
163        $onlyNumericParams = $ret->func;
164
165        $ret->paramInfos = $onlyNumericParams ?
166            $this->preparePfParamInfos( $src, $ret, $params ) :
167            $this->prepareTplParamInfos( $src, $params );
168
169        return $ret;
170    }
171
172    /**
173     * Prepare TemplateInfo/ParamInfo information for a parser function
174     * transclusion.
175     *
176     * @param Source $src
177     * @param TemplateInfo $ti Used to update $ti->targetWt when the
178     *   first argument is delimited by a colon.
179     * @param array<KV> $params
180     * @return list<ParamInfo>
181     */
182    private function preparePfParamInfos( Source $src, TemplateInfo $ti, array $params ): array {
183        $paramInfos = [];
184        $argIndex = 1;
185
186        // Use `preproc_pieces` rule to split off colon-separated first
187        // argument.
188        $targetTsr = $params[0]->srcOffsets?->key;
189        $targetContents = $this->tokenizer->tokenizeAs(
190            $ti->targetWt, "preproc_pieces", false
191        );
192        '@phan-var false|array<string|PreprocTk> $targetContents';
193        [ $name, $colon, $arg0 ] = $targetContents !== false ? array_pad(
194            PreprocTk::splitContentsBy(
195                // Japanese uses a double-wide colon to separate parser
196                // function arguments.
197                [ ':', ':' ],
198                PreprocTk::newContentsKV( $targetContents, $targetTsr ),
199                1
200            ), 3, null
201        ) : [ null, null, null ];
202        if ( $colon ) {
203            $ti->targetWt = PreprocTk::printContents( $name, false );
204            $arg0 = PreprocTk::printContents( $arg0, false );
205            $srcOffsets = null;
206            if ( $targetTsr ) {
207                $srcOffsets = (
208                    new SourceRange(
209                        $targetTsr->end - strlen( $arg0 ), $targetTsr->end,
210                        $targetTsr->source
211                    )
212                )->expandTsrV();
213            }
214            $k = (string)$argIndex;
215            $argIndex++;
216            $paramInfo = new ParamInfo( $k, $srcOffsets );
217            $paramInfo->valueWt = $arg0;
218            $paramInfos[] = $paramInfo;
219        }
220
221        // $params[0] was the colon-separated combination of the pf name
222        // and the first argument; we've handled that already.  Start with
223        // $params[1]
224        for ( $i = 1, $n = count( $params );  $i < $n;  $i++ ) {
225            $param = $params[$i];
226
227            $srcOffsets = $param->srcOffsets?->span()->expandTsrV();
228            if ( $srcOffsets !== null ) {
229                $vSrc = $srcOffsets->value->substr( $src );
230            } else {
231                $vSrc = ( $param->k ? $param->k . '=' : '' ) . $param->v;
232            }
233
234            $k = (string)$argIndex;
235            $argIndex++;
236
237            $paramInfo = new ParamInfo( $k, $srcOffsets );
238            $paramInfo->valueWt = $vSrc;
239
240            $paramInfos[] = $paramInfo;
241        }
242
243        return $paramInfos;
244    }
245
246    /**
247     * Prepare TemplateInfo/ParamInfo information for a transclusion
248     * tokenized as `template3`.
249     *
250     * @param Source $src
251     * @param TemplateInfo $ti Used to update $ti->targetWt when the
252     *   first argument is delimited by a colon.
253     * @param array<KV> $params
254     * @return list<ParamInfo>
255     */
256    private function prepareTemplate3ParamInfos(
257        Source $src, TemplateInfo $ti, array $params
258    ): array {
259        // For parser functions, split first argument at colon
260        $hasColon = null;
261        if ( $ti->func ) {
262            $params = self::adjustParserFunctionArg0( $params, $hasColon );
263        }
264        $arg0 = array_shift( $params );
265        $ti->targetWt = PreprocTk::printContents(
266            PreprocTk::newContentsKV( $arg0->k, null ), false
267        );
268        // Create argument ParamInfo
269        $stringify = static fn ( $contents ) => PreprocTk::printContents(
270            PreprocTk::newContentsKV( $contents, null ), false
271        );
272        $unnamedIdx = 1;
273        $paramInfos = array_map( function ( $param ) use ( $stringify, &$unnamedIdx ) {
274            $named = $param->srcOffsets->key->end !== $param->srcOffsets->value->start;
275            $v = $stringify( $param->v );
276            $srcOffsets = $param->srcOffsets;
277            if ( $this->isOldParserFunction && $named ) {
278                // We don't support named parameters for "old" parser functions
279                $v = $stringify( $param->k ) . '=' . $v;
280                $srcOffsets = $srcOffsets->span()->expandTsrV();
281                $named = false;
282            }
283            // Assign positional parameters
284            $key = $named ? $stringify( $param->k ) : strval( $unnamedIdx++ );
285            $p = new ParamInfo( $key, $srcOffsets );
286            $p->valueWt = $v;
287            $p->named = $named;
288            return $p;
289        }, $params );
290        return $paramInfos;
291    }
292
293    /**
294     * Split the first colon-delimited argument from `$params[0]`.
295     * @param list<KV> $params
296     * @param ?string &$hasColon
297     * @return list<KV>
298     */
299    public static function adjustParserFunctionArg0( array $params, ?string &$hasColon ): array {
300        // Make a 'mw:contents' style KV from the first parameter
301        $arg0 = PreprocTk::newContentsKV(
302            $params[0]->k, $params[0]->srcOffsets?->key
303        );
304        [ $name, $hasColonKV, $rest ] = array_pad( PreprocTk::splitContentsBy(
305            [ ':', ':' ], $arg0, 1
306        ), 3, null );
307        if ( $hasColonKV === null ) {
308            // Nothing needs to be done: either there's no argument or
309            // this uses "modern" `|` separators for the first argument.
310            $hasColon = null;
311            return $params;
312        }
313        // Convert $colon back from 'mw:contents' style
314        $hasColon = $hasColonKV->v[0];
315        // Convert $name back from 'mw:contents' style
316        $name = new KV(
317            $name->v, '',
318            $name->srcOffsets?->value->expandTsrK()
319        );
320        // Split the new $arg0 on colon, maybe this is a named param.
321        [ $key, $eq, $value ] = array_pad( PreprocTk::splitContentsBy(
322            '=', $rest, 1
323        ), -3, null );
324        if ( $key === null ) {
325            $rest->k = [ '' ];
326        } else {
327            $rest = new KV(
328                $key->v, $value->v,
329                $key->srcOffsets?->value->join( $value->srcOffsets->value )
330            );
331        }
332        array_splice( $params, 0, 1, [ $name, $rest ] );
333        return $params;
334    }
335
336    /**
337     * Prepare TemplateInfo/ParamInfo information for a template
338     * transclusion.
339     *
340     * @param Source $src
341     * @param array<KV> $params
342     * @return list<ParamInfo>
343     */
344    private function prepareTplParamInfos( Source $src, array $params ): array {
345        $paramInfos = [];
346        $argIndex = 1;
347
348        // Use source offsets to extract arg-name and arg-value wikitext
349        // since the 'k' and 'v' values in params could be expanded tokens
350        //
351        // Ignore params[0] -- that is the template name
352        for ( $i = 1, $n = count( $params );  $i < $n;  $i++ ) {
353            $param = $params[$i];
354            $srcOffsets = $param->srcOffsets;
355            if ( $srcOffsets !== null ) {
356                $kSrc = $srcOffsets->key->substr( $src );
357                $vSrc = $srcOffsets->value->substr( $src );
358            } else {
359                $kSrc = $param->k;
360                $vSrc = $param->v;
361            }
362
363            $kWt = trim( $kSrc );
364            $k = TokenUtils::tokensToString( $param->k, true, [ 'stripEmptyLines' => true ] );
365            if ( is_array( $k ) ) {
366                // The PHP parser only removes comments and whitespace to construct
367                // the real parameter name, so if there were other tokens, use the
368                // original text
369                $k = $kWt;
370            } else {
371                $k = trim( $k );
372            }
373            $v = $vSrc;
374
375            // Even if k is empty, we need to check v immediately follows. If not,
376            // it's a blank parameter name (which is valid) and we shouldn't make it
377            // positional.
378            if ( $k === '' &&
379                $srcOffsets &&
380                $srcOffsets->key->end === $srcOffsets->value->start
381            ) {
382                $isPositional = true;
383                $k = (string)$argIndex;
384                $argIndex++;
385            } else {
386                $isPositional = false;
387                // strip ws from named parameter values
388                $v = trim( $v );
389            }
390
391            $paramInfo = new ParamInfo( $k, $srcOffsets );
392
393            Assert::invariant(
394                preg_match( '/^(\s*)(?:.*\S)?(\s*)$/sD', $kSrc, $keySpaceMatch ),
395                'Template argument whitespace match failed.'
396            );
397            $valueSpaceMatch = null;
398
399            if ( $isPositional ) {
400                // PHP parser does not strip whitespace around
401                // positional params and neither will we.
402                $valueSpaceMatch = [ null, '', '' ];
403            } else {
404                $paramInfo->named = true;
405                if ( $v !== '' ) {
406                    Assert::invariant(
407                        preg_match( '/^(\s*)(?:.*\S)?(\s*)$/sD', $vSrc, $valueSpaceMatch ),
408                        'Template argument whitespace match failed.'
409                    );
410                } else {
411                    $valueSpaceMatch = [ null, '', $vSrc ];
412                }
413            }
414
415            // Preserve key and value space prefix / postfix, if any.
416            // "=" is the default spacing used by the serializer,
417            if ( $keySpaceMatch[1] || $keySpaceMatch[2] || $valueSpaceMatch[1] || $valueSpaceMatch[2] ) {
418                // Remember non-standard spacing
419                $paramInfo->spc = [
420                    $keySpaceMatch[1], $keySpaceMatch[2],
421                    $valueSpaceMatch[1], $valueSpaceMatch[2]
422                ];
423            }
424
425            $paramInfo->valueWt = $v;
426            // Only add the original parameter wikitext if named and different from
427            // the actual parameter.
428            if ( !$isPositional && $kWt !== $k ) {
429                $paramInfo->keyWt = $kWt;
430            }
431            $paramInfos[] = $paramInfo;
432        }
433
434        return $paramInfos;
435    }
436
437    /**
438     * @return array<string|Token>
439     */
440    private function getEncapsulationInfo( ?array $chunk = null ): array {
441        // TODO
442        // * only add this information for top-level includes, but track parameter
443        // expansion in lower-level templates
444        // * ref all tables to this (just add about)
445        // * ref end token to this, add property="mw:Transclusion/End"
446
447        $attrs = [
448            new KV( 'typeof', $this->wrapperType ),
449            new KV( 'about', $this->aboutId )
450        ];
451        $dp = new DataParsoid;
452        $dp->tsr = clone $this->token->dataParsoid->tsr;
453        $dp->src = $this->token->dataParsoid->src;
454        if ( isset( $this->token->dataParsoid->colon ) ) {
455            $dp->colon = $this->token->dataParsoid->colon;
456        }
457
458        $meta = [ new SelfclosingTagTk( 'meta', $attrs, $dp ) ];
459        $chunk = $chunk ? array_merge( $meta, $chunk ) : $meta;
460        return $chunk;
461    }
462
463    private function getEncapsulationInfoEndTag(): Token {
464        $tsr = $this->token->dataParsoid->tsr ?? null;
465        $dp = new DataParsoid;
466        $dp->tsr = new SourceRange( null, $tsr?->end, $tsr?->source );
467        return new SelfclosingTagTk( 'meta',
468            [
469                new KV( 'typeof', $this->wrapperType . '/End' ),
470                new KV( 'about', $this->aboutId )
471            ],
472            $dp
473        );
474    }
475
476    /**
477     * Parameter processing helpers.
478     *
479     * @param mixed $tokens
480     * @return bool
481     */
482    private static function isSimpleParam( $tokens ): bool {
483        if ( !is_array( $tokens ) ) {
484            $tokens = [ $tokens ];
485        }
486        foreach ( $tokens as $t ) {
487            if ( !is_string( $t ) && !( $t instanceof CommentTk ) && !( $t instanceof NlTk ) ) {
488                return false;
489            }
490        }
491        return true;
492    }
493
494    /**
495     * Add its HTML conversion to a parameter
496     *
497     * @param ParamInfo $paramInfo
498     */
499    private function getParamHTML( ParamInfo $paramInfo ): void {
500        $srcStart = $paramInfo->srcOffsets->value->start;
501        $srcEnd = $paramInfo->srcOffsets->value->end;
502        if ( $paramInfo->spc !== null ) {
503            $srcStart += strlen( $paramInfo->spc[2] );
504            $srcEnd -= strlen( $paramInfo->spc[3] );
505        }
506
507        $domFragment = PipelineUtils::processContentInPipeline(
508            $this->env, $this->frame,
509            $paramInfo->valueWt,
510            [
511                'pipelineType' => 'fullparse-wikitext-to-dom',
512                'pipelineOpts' => [
513                    'expandTemplates' => true,
514                    // No need to do paragraph-wrapping here
515                    'inlineContext' => true
516                ],
517                'srcOffsets' => new SourceRange( $srcStart, $srcEnd, $paramInfo->srcOffsets->value->source ),
518                'sol' => true
519            ]
520        );
521        // FIXME: We're better off setting a pipeline option above
522        // to skip dsr computation to begin with.  Worth revisiting
523        // if / when `addHTMLTemplateParameters` is enabled.
524        // Remove DSR from children
525        DOMUtils::visitDOM( $domFragment, static function ( $node ) {
526            if ( !( $node instanceof Element ) ) {
527                return;
528            }
529            $dp = DOMDataUtils::getDataParsoid( $node );
530            $dp->dsr = null;
531        } );
532        $paramInfo->html = ContentUtils::ppToXML(
533            $domFragment, [ 'innerXML' => true, 'fragment' => true, ]
534        );
535    }
536
537}