Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.40% covered (warning)
87.40%
222 / 254
54.55% covered (warning)
54.55%
6 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
WikifunctionsPFragmentHandler
87.40% covered (warning)
87.40%
222 / 254
54.55% covered (warning)
54.55%
6 / 11
63.50
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 sourceToFragment
89.53% covered (warning)
89.53%
77 / 86
0.00% covered (danger)
0.00%
0 / 1
13.19
 queueRevalidateJob
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 fillEmptyArgsWithDefaultValues
95.24% covered (success)
95.24%
40 / 42
0.00% covered (danger)
0.00%
0 / 1
14
 addToLimitReport
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
9
 fetchFunctionFromWikifunctionsApi
60.87% covered (warning)
60.87%
28 / 46
0.00% covered (danger)
0.00%
0 / 1
6.50
 extractWikifunctionCallArguments
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
7
 convertPFragmentToZFunctionCallParameter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getSanitisedHtmlFragment
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 decodeHtmlFragmentValue
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 createErrorfulFragment
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3/**
4 * WikiLambda extension Parsoid handler for our parser function
5 *
6 * @file
7 * @ingroup Extensions
8 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
9 * @license MIT
10 */
11
12namespace MediaWiki\Extension\WikiLambda\ParserFunction;
13
14use MediaWiki\Config\Config;
15use MediaWiki\Extension\WikiLambda\AbstractContent\AbstractContentUtils;
16use MediaWiki\Extension\WikiLambda\ClientStorage\WikifunctionsClientStore;
17use MediaWiki\Extension\WikiLambda\ClientStorage\WikifunctionsFragmentStore;
18use MediaWiki\Extension\WikiLambda\Jobs\WikifunctionsClientRequestJob;
19use MediaWiki\Extension\WikiLambda\Registry\ZTypeRegistry;
20use MediaWiki\Extension\WikiLambda\Renderer\WikifunctionsFragmentRenderer;
21use MediaWiki\Extension\WikiLambda\UIUtils;
22use MediaWiki\Extension\WikiLambda\WikiLambdaServices;
23use MediaWiki\Extension\WikiLambda\ZObjectUtils;
24use MediaWiki\Html\Html;
25use MediaWiki\Http\HttpRequestFactory;
26use MediaWiki\JobQueue\JobQueueGroup;
27use MediaWiki\Logger\LoggerFactory;
28use MediaWiki\Parser\ParserOutput;
29use MediaWiki\Registration\ExtensionRegistry;
30use MediaWiki\WikiMap\WikiMap;
31use Psr\Log\LoggerInterface;
32use Wikimedia\Parsoid\Ext\Arguments;
33use Wikimedia\Parsoid\Ext\ParsoidExtensionAPI;
34use Wikimedia\Parsoid\Ext\PFragmentHandler;
35use Wikimedia\Parsoid\Fragments\HtmlPFragment;
36use Wikimedia\Parsoid\Fragments\PFragment;
37use Wikimedia\Stats\Metrics\NullMetric;
38use Wikimedia\Stats\Metrics\TimingMetric;
39use Wikimedia\Stats\StatsFactory;
40
41class WikifunctionsPFragmentHandler extends PFragmentHandler {
42
43    /** Timeout in milliseconds to fetch a Function from Wikifunctions, to find default values. */
44    private const FETCH_FUNCTION_TIMEOUT_MS = 1000;
45
46    private LoggerInterface $logger;
47    /**
48     * @var TimingMetric|NullMetric (might be a NullMetric in some circumstances)
49     */
50    private $statsFactoryTimer;
51    private StatsFactory $statsFactory;
52
53    public function __construct(
54        StatsFactory $statsFactory,
55        private readonly Config $config,
56        private readonly JobQueueGroup $jobQueueGroup,
57        private readonly HttpRequestFactory $httpRequestFactory,
58        private readonly WikifunctionsFragmentRenderer $renderer,
59        private readonly WikifunctionsClientStore $clientObjectStore,
60        private readonly WikifunctionsFragmentStore $clientFragmentStore,
61    ) {
62        // Non-injected items
63        $this->logger = LoggerFactory::getInstance( 'WikiLambdaClient' );
64
65        $this->statsFactory = $statsFactory->withComponent( 'WikiLambdaClient' );
66        $this->statsFactoryTimer = $this->statsFactory
67            // Will end up as 'mediawiki.WikiLambdaClient.parsoid_to_fragment_handler_seconds{response=…}'
68            ->getTiming( 'parsoid_to_fragment_handler_seconds' )
69            ->setLabel( 'wiki', WikiMap::getCurrentWikiId() );
70    }
71
72    /**
73     * @inheritDoc
74     */
75    public function sourceToFragment( ParsoidExtensionAPI $extApi, Arguments $callArgs, bool $tagSyntax ) {
76        // Use the returned RunningTimer, not the shared metric, for start/stop: this method can
77        // re-enter itself when a `{{#function:…}}` is nested inside another call's argument (Parsoid
78        // expands the argument, executing the inner parser function), and the metric object is
79        // process-global. A per-invocation RunningTimer keeps each call's timing and labels isolated.
80        $timer = $this->statsFactoryTimer->start();
81
82        // Note: We can't hint this as `: PFragment|AsyncResult` as we're still in PHP 7.4-land
83        // If client mode isn't enabled on this wiki, there's nothing to do, just show an error message
84        if ( !WikiLambdaServices::getMode()->isClient() ) {
85            // TODO: Make this a proper error box or inline error.
86            $errorMsgString = wfMessage(
87                'wikilambda-functioncall-error-message',
88                [
89                    wfMessage( 'wikilambda-functioncall-error-disabled' )->text()
90                ]
91            )->text();
92
93            $timer->setLabel( 'response', 'disabled' )->stop();
94            return WikifunctionsPFragment::newFromLiteral( $errorMsgString );
95        }
96
97        // Extract arguments:
98        $expansion = $this->extractWikifunctionCallArguments( $extApi, $callArgs );
99
100        // Fill empty arguments with default values:
101        $expansion = $this->fillEmptyArgsWithDefaultValues( $extApi, $expansion );
102
103        // On Wikibase client wikis, loop over each argument, in case it's a Wikidata item reference,
104        // and mark us as a user of said item if so. Doing this after default value filling, in case
105        // the default value ends up being a Wikidata item reference (e.g. item for current page).
106        if ( ExtensionRegistry::getInstance()->isLoaded( 'WikibaseClient' ) ) {
107            // Note: An absolute reference to avoid CI issues with references to unknown classes.
108            $wikibaseEntityParser = \Wikibase\Client\WikibaseClient::getEntityIdParser();
109
110            $parserOutputProvider = new ParsoidWrappingParserOutputProvider( $extApi->getMetadata() );
111            $usageAccumulator = \Wikibase\Client\WikibaseClient::getUsageAccumulatorFactory()
112                ->newFromParserOutputProvider( $parserOutputProvider );
113
114            foreach ( $expansion['arguments'] as $key => $value ) {
115                if ( AbstractContentUtils::isValidWikidataItemReference( $value ) ) {
116                    try {
117                        // Convert the string into a Wikidata `EntityId`
118                        $itemId = $wikibaseEntityParser->parse( $value );
119
120                        // TODO (T385631): Only track some usage, somehow?
121                        $usageAccumulator->addAllUsage( $itemId );
122
123                    } catch ( \Wikibase\DataModel\Entity\EntityIdParsingException ) {
124                        // Not a valid Wikidata reference (e.g. "X123"), so treat as a string.
125                    }
126                }
127            }
128        }
129
130        // Record the call as a page property. These properties are the only record of which Functions
131        // a page uses: the legacy parser does not run this handler, so nothing else sees the call.
132        // ClientHooks::onParserCacheSaveComplete (which requires ParserCache to be enabled on the wiki,
133        // always true for Wikimedia production) reads them back when the render is cached and writes
134        // the cross-wiki usage table from them, which iswhy they are set before the call is made and
135        // whatever its result.
136
137        // (T434194) Don't track for invalid ZIDs, `{{#function:foo}}` doesn't trigger orchestrator load
138        if ( ZObjectUtils::isValidZObjectReference( $expansion['target'] ) ) {
139            // (T414848) Set a special flag on the page, so that we can track usage of pages with function calls, and
140            // find pages that use a lot of them.
141
142            // Note: Page properties must be strings for Parsoid's StubMetadataCollector to be happy; this also works
143            $newWikifunctionsUseCount = strval( intval(
144                // @phan-suppress-next-line PhanUndeclaredMethod — not in ContentMetadataCollector interface, but exists
145                $extApi->getMetadata()->getPageProperty( 'wikilambda' ) ?? 0
146            ) + 1 );
147            $extApi->getMetadata()->setNumericPageProperty( 'wikilambda', $newWikifunctionsUseCount );
148
149            // (T414848) Also track specifically usage of our target ZID
150            $targetFunctionPageProp = 'wikilambda-' . $expansion['target'];
151            $newTargetUseCount = strval( intval(
152                // @phan-suppress-next-line PhanUndeclaredMethod — not in ContentMetadataCollector interface, but exists
153                $extApi->getMetadata()->getPageProperty( $targetFunctionPageProp ) ?? 0
154             ) + 1 );
155            $extApi->getMetadata()->setNumericPageProperty( $targetFunctionPageProp, $newTargetUseCount );
156        }
157
158        // Generalize log context
159        $logContext = [
160            'targetFunction' => $expansion['target'],
161            'params' => json_encode( $expansion ),
162            'page' => $extApi->getPageConfig()->getLinkTarget()->__toString(),
163        ];
164
165        $this->logger->debug( 'WikiLambda client call made for {targetFunction} on {page}', $logContext );
166
167        // Add content and style modules to the page, we know they're likely to be used somewhere
168        $extApi->getMetadata()->addModules( [ 'ext.wikilambda.content' ] );
169        $extApi->getMetadata()->addModuleStyles( [ 'ext.wikilambda.content.styles' ] );
170
171        $cachedValue = $this->clientFragmentStore->getRenderedFragment( $expansion );
172
173        if ( $cachedValue ) {
174            // Good news, this request has already been cached; examine what it is
175
176            // If the stored value is outdated, queue a rerender job
177            if ( $this->clientFragmentStore->isStaleFragment( $expansion, $cachedValue ) ) {
178                $this->queueRevalidateJob( $expansion );
179            }
180
181            if ( $cachedValue['success'] === true ) {
182                // It was a successful run!
183                // If output type is Z89, return as HTML fragment;
184                if (
185                    isset( $cachedValue['type'] )
186                    && $cachedValue['type'] === ZTypeRegistry::Z_HTML_FRAGMENT
187                ) {
188                    $html = $this->getSanitisedHtmlFragment( $cachedValue['value'] ?? '', [
189                        'function' => $expansion['target'],
190                        'page' => $extApi->getPageConfig()->getLinkTarget()->__toString(),
191                    ] );
192                    $this->addToLimitReport( $extApi, 'cached' );
193                    $timer->setLabel( 'response', 'cached' )->stop();
194                    return HtmlPFragment::newFromHtmlString( $html, null );
195                }
196                // Otherwise, return as literal
197                $this->addToLimitReport( $extApi, 'cached' );
198                $timer->setLabel( 'response', 'cached' )->stop();
199                return WikifunctionsPFragment::newFromLiteral( $cachedValue['value'] );
200            }
201
202            // It failed for some reason; show the error message instead
203            $errorMessageKey = $cachedValue['errorMessageKey'];
204
205            $extApi->addTrackingCategory( $errorMessageKey . '-category' );
206
207            $this->logger->info(
208                'WikiLambda client request failed, returned {error} for request to {targetFunction} on {page}',
209                $logContext + [ 'error' => $errorMessageKey ]
210            );
211
212            // Load ext.wikilambda.inlineerrors css. We pass the enum's string value because
213            // Parsoid's StubMetadataCollector::appendOutputStrings() only accepts a string
214            // (unlike ParserOutput which accepts string|ParserOutputStringSets).
215            $extApi->getMetadata()->appendOutputStrings(
216                \MediaWiki\Parser\ParserOutputStringSets::MODULE->value,
217                [ 'ext.wikilambda.inlineerrors' ]
218            );
219
220            $this->addToLimitReport( $extApi, 'cachedError' );
221            $timer->setLabel( 'response', 'cachedError' )->stop();
222
223            return $this->createErrorfulFragment( $extApi, $errorMessageKey );
224        }
225
226        // At this point, we know our request hasn't yet been stored in the cache, so we need to trigger it,
227        // and return a placeholder for now
228
229        $this->logger->info(
230            'WikiLambda client request was uncached for request to {targetFunction} on {page}',
231            $logContext
232        );
233
234        // Check if SRE have set this wiki (probably all wikis) temporarily to not try to use Wikifunctions.
235        if ( WikiLambdaServices::getMode()->isClientOffline() ) {
236            $this->addToLimitReport( $extApi, 'offline' );
237            $timer->setLabel( 'response', 'offline' )->stop();
238            return HtmlPFragment::newFromHtmlString( Html::errorBox(
239                wfMessage( 'wikilambda-fragment-disabled' )->text()
240            ), null );
241        }
242
243        // This job triggers the request, will store the result in the cache. We don't pass in the location of
244        // the usage, as that's the responsibility of this class (to add tracking categories etc.) or of Parsoid
245        // (to purge the page once our fragment is available etc.).
246        $this->queueRevalidateJob( $expansion );
247
248        // As we're async, return a "sorry, no content yet" fragment
249        $this->addToLimitReport( $extApi, 'pending' );
250        $timer->setLabel( 'response', 'pending' )->stop();
251        return new WikifunctionsPendingFragment(
252            $extApi->getPageConfig()->getPageLanguageBcp47(), null
253        );
254    }
255
256    /**
257     * @param array $fragment
258     */
259    private function queueRevalidateJob( array $fragment ): void {
260        $revalidateJob = new WikifunctionsClientRequestJob( [
261            'request' => $fragment
262        ] );
263
264        $this->jobQueueGroup->lazyPush( $revalidateJob );
265    }
266
267    /**
268     * Sets empty arguments with their default value (if available)
269     *
270     * @param ParsoidExtensionAPI $extApi
271     * @param array $functionCall
272     * @return array
273     */
274    private function fillEmptyArgsWithDefaultValues( ParsoidExtensionAPI $extApi, array $functionCall ): array {
275        // 1. See if there's an empty string arg
276        // 2. If there's any:
277        //  2.1. fetch Function Zid from Memcached
278        //  2.2. fetch Function Zid from Wikifunctions
279        //  2.3. look into the argument key
280        //  2.4. check if it has a default value callback
281        //  2.5. generate default value
282        //  2.6. keep record of temporal arguments
283        // 3. Then proceed, with new arg set for cache key, etc.
284
285        // Initialize record of arguments that will always contain today's date
286        $functionCall[ 'temporalArgs' ] = [];
287
288        // Fetch the Function only once, and only if an arg is empty and the target can be a Function
289        $firstEmptyArgKey = array_search( '', $functionCall[ 'arguments' ], true );
290        if ( $firstEmptyArgKey === false || !ZObjectUtils::isValidZObjectReference( $functionCall[ 'target' ] ) ) {
291            return $functionCall;
292        }
293
294        // 2.1. Fetch Function Zid from Memcached
295        $zobject = $this->clientObjectStore->fetchFromZObjectCache( $functionCall[ 'target' ] );
296        if ( !$zobject ) {
297            // 2.2. Fetch Function Zid from Wikifunctions
298            $this->logger->info(
299                __METHOD__ . ' cache miss while fetching {zid} for empty argument {arg}, falling back to API',
300                [
301                    'zid' => $functionCall[ 'target' ],
302                    'arg' => $firstEmptyArgKey
303                ]
304            );
305            $zobject = $this->fetchFunctionFromWikifunctionsApi( $functionCall[ 'target' ], $firstEmptyArgKey );
306        }
307
308        // If function is not found, return:
309        if ( !$zobject ) {
310            return $functionCall;
311        }
312
313        // If object is not a function, return:
314        $function = $zobject[ ZTypeRegistry::Z_PERSISTENTOBJECT_VALUE ];
315        if ( $function[ ZTypeRegistry::Z_OBJECT_TYPE ] !== ZTypeRegistry::Z_FUNCTION ) {
316            return $functionCall;
317        }
318        $args = array_slice( $function[ ZTypeRegistry::Z_FUNCTION_ARGUMENTS ], 1 );
319
320        foreach ( $functionCall[ 'arguments' ] as $argKey => $argValue ) {
321            // If argValue is not empty, continue
322            if ( $argValue !== '' ) {
323                continue;
324            }
325
326            // 2.3. Get argument type zid
327            $matches = array_filter( $args, static function ( $item ) use ( $argKey ) {
328                return isset( $item[ ZTypeRegistry::Z_ARGUMENTDECLARATION_ID ] ) &&
329                    $item[ ZTypeRegistry::Z_ARGUMENTDECLARATION_ID ] === $argKey;
330            } );
331            $arg = reset( $matches ) ?: null;
332
333            // If argKey is not found, continue
334            if ( !$arg ) {
335                continue;
336            }
337
338            $argType = $arg[ ZTypeRegistry::Z_ARGUMENTDECLARATION_TYPE ];
339
340            // 2.4. Check if the argument type has a default value callback defined
341            if ( is_string( $argType ) && WikifunctionsCallDefaultValues::hasDefaultValueCallback( $argType ) ) {
342                $defaultValueCallback = WikifunctionsCallDefaultValues::getDefaultValueForType( $argType );
343                $defaultValueContext = [
344                    'contentMetadataCollector' => $extApi->getMetadata(),
345                    'linkTarget' => $extApi->getPageConfig()->getLinkTarget(),
346                    'pageLanguage' => $extApi->getPageConfig()->getPageLanguageBcp47()->toBcp47Code(),
347                ];
348                // 2.5. Generate the default value
349                $functionCall[ 'arguments' ][ $argKey ] = $defaultValueCallback( $defaultValueContext );
350                // 2.6. Keep a record of those arguments with default values that change over time
351                if ( WikifunctionsCallDefaultValues::isTemporalType( $argType ) ) {
352                    $functionCall[ 'temporalArgs' ][] = $argKey;
353                }
354            }
355        }
356
357        return $functionCall;
358    }
359
360    /**
361     * Count this call in the parser limit report, and record when the page goes over a threshold.
362     *
363     * @param ParsoidExtensionAPI $extApi
364     * @param string $response One of 'cached', 'cachedError', 'offline' or 'pending'
365     */
366    private function addToLimitReport( ParsoidExtensionAPI $extApi, string $response ): void {
367        $metadata = $extApi->getMetadata();
368        // Parsoid's StubMetadataCollector (e.g. in tests) cannot read back limit report data.
369        if ( !( $metadata instanceof ParserOutput ) ) {
370            return;
371        }
372
373        $increments = [
374            'total' => 1,
375            'failed' => $response === 'cachedError' ? 1 : 0,
376            'uncached' => $response === 'offline' || $response === 'pending' ? 1 : 0,
377        ];
378        $existingData = $metadata->getLimitReportData();
379        $thresholds = $this->config->get( 'WikiLambdaClientCallThresholds' );
380
381        foreach ( $increments as $type => $increment ) {
382            // The following messages are used here:
383            // * wikilambda-limitreport-totalcalls
384            // * wikilambda-limitreport-failedcalls
385            // * wikilambda-limitreport-uncachedcalls
386            $key = "wikilambda-limitreport-{$type}calls";
387            $count = ( $existingData[$key] ?? 0 ) + $increment;
388            $metadata->setLimitReportData( $key, $count );
389
390            // Record only the call that crosses the threshold, so each parse counts once.
391            if ( $increment && isset( $thresholds[$type] ) && $count === $thresholds[$type] + 1 ) {
392                $this->statsFactory->getCounter( 'parse_over_call_threshold_total' )
393                    ->setLabel( 'wiki', WikiMap::getCurrentWikiId() )
394                    ->setLabel( 'calls', $type )
395                    ->increment();
396            }
397        }
398    }
399
400    /**
401     * Requests the given function Zid from the Wikifunctions ActionAPI.
402     * Returns null if the function Zid is not found.
403     *
404     * @param string $zid
405     * @param string $argKey
406     * @return ?array
407     */
408    private function fetchFunctionFromWikifunctionsApi( $zid, $argKey ): ?array {
409        $requestParams = [
410            'action' => 'wikilambda_fetch',
411            'format' => 'json',
412            'zids' => $zid,
413            'formatversion' => 2,
414        ];
415        $baseUrl = WikifunctionsClientRequestJob::getClientTargetUrl( $this->config, $this->logger );
416        $apiUrl = wfAppendQuery( $baseUrl . wfScript( 'api' ), $requestParams );
417        $request = $this->httpRequestFactory->create(
418            $apiUrl,
419            // The parse waits for this request, so do not use the longer default timeout.
420            [ 'method' => 'GET', 'timeout' => self::FETCH_FUNCTION_TIMEOUT_MS / 1000 ],
421            __METHOD__
422        );
423
424        if ( !$request ) {
425            $this->logger->error(
426                __METHOD__ . ' failed to create a request to {url}',
427                [
428                    'url' => $apiUrl
429                ]
430            );
431            return null;
432        }
433
434        // Execute request:
435        $status = $request->execute();
436        $response = json_decode( $request->getContent() );
437
438        // Failed request:
439        if ( !$response || !$status->isOK() ) {
440            $httpStatusCode = $request->getStatus();
441            $this->logger->warning(
442                __METHOD__ . ' received error {status} while fetching {zid} for empty argument {arg}: {request}',
443                [
444                    'status' => $httpStatusCode,
445                    'zid' => $zid,
446                    'arg' => $argKey,
447                    'request' => $request->getFinalUrl()
448                ]
449            );
450            return null;
451        }
452
453        // Successful request:
454        $json = json_decode( $response->{ $zid }->wikilambda_fetch, true );
455        if ( !$json ) {
456            $this->logger->warning(
457                __METHOD__ . ' failed parsing the Json response to fetching    {zid} for empty argument {arg}: {request}',
458                [
459                    'zid' => $zid,
460                    'arg' => $argKey,
461                    'request' => $request->getFinalUrl()
462                ]
463            );
464        }
465
466        // Return successfully parsed Json or null
467        return $json;
468    }
469
470    /**
471     * Extracts the arguments from the wikitext and turn it into the request we'll need
472     *
473     * @param ParsoidExtensionAPI $extApi
474     * @param Arguments $arguments
475     */
476    private function extractWikifunctionCallArguments( $extApi, $arguments ): array {
477        // Get the arguments from the wikitext with the HTML entities decoded and with whitespace trimmed.
478        // E.g.:
479        // * unnamed arguments:
480        //   given an input of `{{#function:Z802 | Z41 | h&eacute;llõ |   1234}}`
481        //   $cleanedArgs will be: [ 'Z802', 'héllõ', '1234' ]
482        // * named arguments (renderlang and parselang):
483        //   given an input of `{{#function:Z802|Z41|hello|1234|renderlang=es}}`
484        //   $cleanedArgs will be: [ 'Z802', 'hello', '1234', 'renderlang=es' ]
485        // * trim all arguments except when arg is all whitespaces:
486        //   given an input of ``{{#function:Z15175| hello |world | }}
487        //   $cleanedArgs will be [ 'Z15175', 'hello', 'world', ' ' ]
488
489        // First call to getOrderedArgs with trim=false to find the only-whitespace arguments:
490        $rawArgs = $arguments->getOrderedArgs( $extApi, false );
491        $isOnlyWhitespace = array_map( static function ( $v ) use ( $extApi ) {
492            return trim( $v->toRawText( $extApi ) ) !== '';
493        }, array_values( $rawArgs ) );
494
495        // TODO (T390344): Switch to getNamedArgs() once Parsoid supports that
496        // All arguments are expanded and trimmed, except for those which are just a whitespace
497        $cleanedArgs = $arguments->getOrderedArgs( $extApi, $isOnlyWhitespace );
498
499        // Parse and render languages are set to Parsoid's page target language by default.
500        $parseLang = $extApi->getPageConfig()->getPageLanguageBcp47()->toBcp47Code();
501        $renderLang = $parseLang;
502
503        // We allow users to specify language in-line, e.g. if you want something copy-pastable
504        // or to demonstrate content in different languages. This is expected to be primarily useful for
505        // multi-lingual wikis.
506        // TODO (T390344): This won't work for now, we we only have ordered arguments, not named ones.
507        // if ( array_key_exists( 'parselang', $cleanedArgs ) && $cleanedArgs['parselang'] instanceof PFragment ) {
508        //     $parseLang = $cleanedArgs['parselang']->killMarkers();
509        // }
510        // if ( array_key_exists( 'renderlang', $cleanedArgs ) && $cleanedArgs['renderlang'] instanceof PFragment ) {
511        //     $renderLang = $cleanedArgs['renderlang']->killMarkers();
512        // }
513
514        // Get the target function from the first argument.
515        // e.g. given an input of `{{#function:Z802|Z41|héllõ|1234}}`, $cleanedArgs[0] will be: 'Z802'
516        $targetFunction = $cleanedArgs[0]->killMarkers();
517
518        // Convert the raw unnamed arguments into the keys for the function call.
519        // e.g. given an input of `{{#function:Z802|Z41|hello|1234}}`, $arguments will be:
520        // [ 'Z802K1' => 'Z41', 'Z802K2' => 'hello', 'Z802K3' => '1234' ]
521        $unkeyedArguments = array_slice( $cleanedArgs, 1 );
522        $arguments = [];
523        foreach ( $unkeyedArguments as $key => $value ) {
524            if ( !( $value instanceof PFragment ) ) {
525                // Ignore any non-PFragment arguments that have somehow snuck in (probably nulls?)
526                continue;
527            }
528
529            $valueText = $this->convertPFragmentToZFunctionCallParameter( $value, $extApi );
530            $argKey = $targetFunction . 'K' . ( $key + 1 );
531
532            // named argument (e.g. 1=hello, foo=bar, renderlang=en)
533            if ( strpos( $valueText, '=' ) !== false ) {
534                $argKeyParts = explode( '=', $valueText, 2 );
535                // key is not numeric:
536                // * renderlang=es (save as $renderLang)
537                // * parselang=es (save as $parseLang)
538                // * any=other (ignore)
539                if ( !is_numeric( $argKeyParts[0] ) ) {
540                    if ( $argKeyParts[0] === 'parselang' ) {
541                        $parseLang = $argKeyParts[1];
542                    } elseif ( $argKeyParts[0] === 'renderlang' ) {
543                        $renderLang = $argKeyParts[1];
544                    }
545                    continue;
546                }
547                // key is numeric:
548                // * trust the key, keep the value
549                $argKey = $targetFunction . 'K' . $argKeyParts[0];
550                $valueText = $argKeyParts[1];
551            }
552
553            $arguments[$argKey] = $valueText;
554        }
555
556        return [
557            'target' => $targetFunction,
558            'arguments' => $arguments,
559            'parseLang' => $parseLang,
560            'renderLang' => $renderLang
561        ];
562    }
563
564    /**
565     * Coerce an PFragment into a string to be used as a parameter in the ZObject function call.
566     *
567     * For now this is a trivial conversion, but in the future we may want to do smarter things (e.g. for
568     * whitespace handling, see T362251).
569     *
570     * @param PFragment $value
571     * @param ParsoidExtensionAPI $extApi
572     * @return string
573     */
574    private function convertPFragmentToZFunctionCallParameter( PFragment $value, ParsoidExtensionAPI $extApi ): string {
575        return $value->toRawText( $extApi );
576    }
577
578    /**
579     * Decode and sanitise a possibly JSON-encoded HTML fragment string.
580     *
581     * @param string $value
582     * @param array $logContext Log context identifying the function and page, so that elements
583     *   the sanitiser rejects can be traced back to what produced them
584     * @return string
585     */
586    private function getSanitisedHtmlFragment( string $value, array $logContext = [] ): string {
587        $html = $this->decodeHtmlFragmentValue( $value );
588        return $this->renderer->render( $html, $logContext );
589    }
590
591    /**
592     * Decode a possibly JSON-encoded HTML fragment string.
593     *
594     * @param string $value
595     * @return string
596     */
597    private function decodeHtmlFragmentValue( string $value ): string {
598        if ( $value === '' ) {
599            return '';
600        }
601        // Try to decode as JSON, but only use the result if it's a string
602        $decoded = json_decode( $value, true );
603        if ( is_string( $decoded ) ) {
604            return $decoded;
605        }
606        // If not JSON or not a string, return as-is
607        return $value;
608    }
609
610    /**
611     * Helper to create an error fragment for failed function calls.
612     */
613    private function createErrorfulFragment( ParsoidExtensionAPI $extApi, ?string $errorMessageKey ): HTMLPFragment {
614        $cmc = $extApi->getMetadata();
615        if ( $cmc instanceof ParserOutput ) {
616            // Make sure our fragment's cache expiry is set to at most 1 hour, as we're adding an errorful piece of
617            // content that is likely to be fixed next time around, but we don't want to slam the server.
618            $cmc->updateRuntimeAdaptiveExpiry( 60 * 60 );
619        }
620
621        return HtmlPFragment::newFromHtmlString(
622            UIUtils::createErrorChip(
623                'wikilambda-visualeditor-wikifunctionscall-error',
624                $errorMessageKey ?? ''
625            ),
626            null
627        );
628    }
629}