Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 387
0.00% covered (danger)
0.00%
0 / 91
CRAP
0.00% covered (danger)
0.00%
0 / 1
ParserFunctions
0.00% covered (danger)
0.00%
0 / 387
0.00% covered (danger)
0.00%
0 / 91
30102
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 rejoinKV
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
56
 expandV
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 expandKV
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
90
 prefixedTitleText
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_if
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 trimRes
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 noTrimRes
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 switchLookupFallback
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
306
 pf_switch
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 pf_ifeq
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 ifeq_worker
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 pf_expr
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 pf_ifexpr
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 pf_iferror
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 pf_lc
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_uc
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_ucfirst
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 pf_lcfirst
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 pf_padleft
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
56
 pf_padright
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
56
 pf_tag
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 tag_worker
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 pf_currentyear
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localyear
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentmonth
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localmonth
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentmonthname
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localmonthname
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentmonthabbrev
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localmonthabbrev
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentweek
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localweek
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentday
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localday
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentday2
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localday2
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentdow
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localdow
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentdayname
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localdayname
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currenttime
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localtime
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currenthour
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localhour
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currenttimestamp
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localtimestamp
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentmonthnamegen
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_localmonthnamegen
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_time
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_timel
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pfTime_tokens
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pfTimel_tokens
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pfTime
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 pf_localurl
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 pf_formatnum
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pf_currentpage
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pf_pagenamee
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pf_fullpagename
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 pf_fullpagenamee
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 pf_pagelanguage
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 pf_directionmark
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 pf_dirmark
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_fullurl
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 pf_urlencode
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 pf_ifexist
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_pagesize
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_sitename
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 encodeCharEntity
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 pf_anchorencode
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 pf_protectionlevel
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_ns
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 pf_subjectspace
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_talkspace
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_numberofarticles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_language
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_contentlanguage
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 pf_contentlang
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_numberoffiles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_namespace
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 pf_namespacee
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 pf_namespacenumber
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 pf_pagename
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_pagenamebase
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_scriptpath
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 pf_server
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 pf_servername
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_talkpagename
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 pf_defaultsort
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 pf_displaytitle
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 pf_equal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2declare( strict_types = 1 );
3
4// phpcs:disable MediaWiki.Commenting.FunctionComment.MissingDocumentationPublic
5// phpcs:disable MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName
6// phpcs:disable MediaWiki.Commenting.FunctionComment.WrongStyle
7// phpcs:disable MediaWiki.Commenting.FunctionComment.MissingDocumentationPrivate
8// phpcs:disable MediaWiki.Commenting.FunctionComment.MissingParamTag
9
10namespace Wikimedia\Parsoid\Wt2Html\TT;
11
12use DateTime;
13use DateTimeZone;
14use Wikimedia\Parsoid\Config\Env;
15use Wikimedia\Parsoid\Core\Sanitizer;
16use Wikimedia\Parsoid\NodeData\DataParsoid;
17use Wikimedia\Parsoid\Tokens\EndTagTk;
18use Wikimedia\Parsoid\Tokens\KV;
19use Wikimedia\Parsoid\Tokens\SelfclosingTagTk;
20use Wikimedia\Parsoid\Tokens\TagTk;
21use Wikimedia\Parsoid\Tokens\Token;
22use Wikimedia\Parsoid\Utils\PHPUtils;
23use Wikimedia\Parsoid\Utils\TokenUtils;
24use Wikimedia\Parsoid\Utils\Utils;
25use Wikimedia\Parsoid\Wt2Html\Frame;
26use Wikimedia\Parsoid\Wt2Html\Params;
27
28/**
29 * Some parser functions, and quite a bunch of stubs of parser functions.
30 *
31 * IMPORTANT NOTE: These parser functions are only used by the Parsoid-native
32 * template expansion pipeline, which is *not* the default or used in
33 * production. Normally core provides us SiteConfig and DataAccess objects
34 * that provide parser functions and other preprocessor functionality.
35 *
36 * There are still quite a few missing, see
37 * {@link http://www.mediawiki.org/wiki/Help:Magic_words} and
38 * {@link http://www.mediawiki.org/wiki/Help:Extension:ParserFunctions}.
39 * Instantiated and called by the {@link TemplateHandler} extension.
40 * Any `pf_<prefix>`
41 * matching a lower-cased template name prefix up to the first colon will
42 * override that template.
43 *
44 * The only use of this code is currently in parserTests and offline tests.
45 * But, eventually as the two parsers are integrated, the core parser tests
46 * implementation from $mw/includes/parser/CoreParserFunctions.php might
47 * move over here.
48 */
49class ParserFunctions {
50    /** @var Env */
51    private $env;
52
53    public function __construct( Env $env ) {
54        $this->env = $env;
55    }
56
57    // Temporary helper.
58    private function rejoinKV( bool $trim, $k, $v ) {
59        if ( is_string( $k ) && strlen( $k ) > 0 ) {
60            return array_merge( [ $k, '=' ], $v );
61        } elseif ( is_array( $k ) && count( $k ) > 0 ) {
62            $k[] = '=';
63            return array_merge( $k, $v );
64        } else {
65            return $trim ? ( is_string( $v ) ? trim( $v ) : TokenUtils::tokenTrim( $v ) ) : $v;
66        }
67    }
68
69    private function expandV( $v, Frame $frame ) {
70        // FIXME: This hasn't been implemented on the JS side
71        return $v;
72    }
73
74    // XXX: move to frame?
75    private function expandKV(
76        $kv, Frame $frame, $defaultValue = null, ?string $type = null, bool $trim = false
77    ): array {
78        if ( $type === null ) {
79            $type = 'expanded-tokens-to-fragment';
80        }
81
82        if ( $kv === null ) {
83            return [ $defaultValue ?: '' ];
84        } elseif ( is_string( $kv ) ) {
85            return [ $kv ];
86        } elseif ( is_string( $kv->k ) && is_string( $kv->v ) ) {
87            if ( $kv->k ) {
88                return [ $kv->k . '=' . $kv->v ];
89            } else {
90                return [ $trim ? trim( $kv->v ) : $kv->v ];
91            }
92        } else {
93            $v = $this->expandV( $kv->v, $frame );
94            return $this->rejoinKV( $trim, $kv->k, $v );
95        }
96    }
97
98    private function prefixedTitleText(): string {
99        return $this->env->getContextTitle()->getPrefixedText();
100    }
101
102    public function pf_if( $token, Frame $frame, Params $params ): array {
103        $args = $params->args;
104        if ( trim( $args[0]->k ) !== '' ) {
105            return $this->expandKV( $args[1] ?? null, $frame );
106        } else {
107            return $this->expandKV( $args[2] ?? null, $frame );
108        }
109    }
110
111    private function trimRes( $res ) {
112        if ( is_string( $res ) ) {
113            return [ trim( $res ) ];
114        } elseif ( is_array( $res ) ) {
115            return TokenUtils::tokenTrim( $res );
116        } else {
117            return $res;
118        }
119    }
120
121    private function noTrimRes( $res ): array {
122        if ( is_string( $res ) ) {
123            return [ $res ];
124        } elseif ( is_array( $res ) ) {
125            return $res;
126        } else {
127            $this->env->log( 'error', 'Unprocessable res in ParserFunctions:noTrimRes', $res );
128            return [];
129        }
130    }
131
132    private function switchLookupFallback(
133        Frame $frame, array $kvs, string $key, array $dict, $v = null
134    ): array {
135        $l = count( $kvs );
136        $this->env->log( 'debug', 'switchLookupFallback', $key, $v );
137        // 'v' need not be a string in cases where it is the last fall-through case
138        $vStr = $v ? TokenUtils::tokensToString( $v ) : null;
139        if ( $vStr && $key === trim( $vStr ) ) {
140            // This handles fall-through switch cases:
141            //
142            //   {{#switch:<key>
143            //     | c1 | c2 | c3 = <res>
144            //     ...
145            //   }}
146            //
147            // So if <key> matched c1, we want to return <res>.
148            // Hence, we are looking for the next entry with a non-empty key.
149            $this->env->log( 'debug', 'switch found' );
150            foreach ( $kvs as $kv ) {
151                // XXX: make sure the key is always one of these!
152                if ( count( $kv->k ) > 0 ) {
153                    return $this->trimRes( $this->expandV( $kv->v, $frame ) );
154                }
155            }
156
157            // No value found, return empty string? XXX: check this
158            return [];
159        } elseif ( count( $kvs ) > 0 ) {
160            // search for value-only entry which matches
161            $i = 0;
162            if ( $v ) {
163                $i = 1;
164            }
165            for ( ;  $i < $l;  $i++ ) {
166                $kv = $kvs[$i];
167                if ( count( $kv->k ) || !count( $kv->v ) ) {
168                    // skip entries with keys or empty values
169                    continue;
170                } else {
171                    // We found a value-only entry.  However, we have to verify
172                    // if we have any fall-through cases that this matches.
173                    //
174                    //   {{#switch:<key>
175                    //     | c1 | c2 | c3 = <res>
176                    //     ...
177                    //   }}
178                    //
179                    // In the switch example above, if we found 'c1', that is
180                    // not the fallback value -- we have to check for fall-through
181                    // cases.  Hence the recursive callback to switchLookupFallback.
182                    //
183                    //   {{#switch:<key>
184                    //     | c1 = <..>
185                    //     | c2 = <..>
186                    //     | [[Foo]]</div>
187                    //   }}
188                    //
189                    // 'val' may be an array of tokens rather than a string as in the
190                    // example above where 'val' is indeed the final return value.
191                    // Hence 'expanded-tokens-to-fragment' type below.
192                    $v = $this->expandV( $kv->v, $frame );
193                    return $this->switchLookupFallback( $frame, array_slice( $kvs, $i + 1 ), $key, $dict, $v );
194                }
195            }
196
197            // value not found!
198            if ( isset( $dict['#default'] ) ) {
199                return $this->trimRes( $this->expandV( $dict['#default'], $frame ) );
200            } elseif ( count( $kvs ) ) {
201                $lastKV = $kvs[count( $kvs ) - 1];
202                if ( $lastKV && !count( $lastKV->k ) ) {
203                    return $this->noTrimRes( $this->expandV( $lastKV->v, $frame ) );
204                } else {
205                    return [];
206                }
207            } else {
208                // nothing found at all.
209                return [];
210            }
211        } elseif ( $v ) {
212            return is_array( $v ) ? $v : [ $v ];
213        } else {
214            // nothing found at all.
215            return [];
216        }
217    }
218
219    public function pf_switch( $token, Frame $frame, Params $params ): array {
220        // TODO: Implement http://www.mediawiki.org/wiki/Help:Extension:ParserFunctions#Grouping_results
221        $args = $params->args;
222        $target = trim( $args[0]->k );
223        $this->env->log( 'debug', 'switch enter', $target, $token );
224        // create a dict from the remaining args
225        array_shift( $args );
226        $dict = $params->dict();
227        if ( $target && $dict[$target] !== null ) {
228            $this->env->log( 'debug', 'switch found: ', $target, $dict, ' res=', $dict[$target] );
229            $v = $this->expandV( $dict[$target], $frame );
230            return $this->trimRes( $v );
231        } else {
232            return $this->switchLookupFallback( $frame, $args, $target, $dict );
233        }
234    }
235
236    public function pf_ifeq( $token, Frame $frame, Params $params ): array {
237        $args = $params->args;
238        if ( count( $args ) < 3 ) {
239            return [];
240        } else {
241            $v = $this->expandV( $args[1]->v, $frame );
242            return $this->ifeq_worker( $frame, $args, $v );
243        }
244    }
245
246    private function ifeq_worker( Frame $frame, array $args, $b ): array {
247        if ( trim( $args[0]->k ) === trim( $b ) ) {
248            return $this->expandKV( $args[2], $frame );
249        } else {
250            return $this->expandKV( $args[3], $frame );
251        }
252    }
253
254    /**
255     * @return list{string}
256     */
257    public function pf_expr( $token, Frame $frame, Params $params ): array {
258        $args = $params->args;
259        $target = $args[0]->k;
260        if ( $target ) {
261            try {
262                // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.eval
263                $res = eval( $target );
264            } catch ( \Exception ) {
265                $res = null;
266            }
267        } else {
268            $res = '';
269        }
270
271        // Avoid crashes
272        if ( $res === null ) {
273            return [ 'class="error" in expression ' . $target ];
274        }
275
276        return [ (string)$res ];
277    }
278
279    public function pf_ifexpr( $token, Frame $frame, Params $params ): array {
280        $args = $params->args;
281        $this->env->log( 'debug', '#ifexp: ', $args );
282        $target = $args[0]->k;
283        $res = null;
284        if ( $target ) {
285            try {
286                // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.eval
287                $res = eval( $target );
288            } catch ( \Exception ) {
289                return [ 'class="error" in expression ' . $target ];
290            }
291        }
292        if ( $res ) {
293            return $this->expandKV( $args[1], $frame );
294        } else {
295            return $this->expandKV( $args[2], $frame );
296        }
297    }
298
299    public function pf_iferror( $token, Frame $frame, Params $params ): array {
300        $args = $params->args;
301        $target = $args[0]->k;
302        if ( in_array( 'class="error"', $target, true ) ) {
303            return $this->expandKV( $args[1], $frame );
304        } else {
305            return $this->expandKV( $args[1], $frame, $target );
306        }
307    }
308
309    /**
310     * @return list{string}
311     */
312    public function pf_lc( $token, Frame $frame, Params $params ): array {
313        $args = $params->args;
314        return [ mb_strtolower( $args[0]->k ) ];
315    }
316
317    /**
318     * @return list{string}
319     */
320    public function pf_uc( $token, Frame $frame, Params $params ): array {
321        $args = $params->args;
322        return [ mb_strtoupper( $args[0]->k ) ];
323    }
324
325    /**
326     * @return list{0?: string}
327     */
328    public function pf_ucfirst( $token, Frame $frame, Params $params ): array {
329        $args = $params->args;
330        $target = $args[0]->k;
331        '@phan-var string $target';
332        if ( $target ) {
333            return [ $this->env->getSiteConfig()->ucfirst( $target ) ];
334        } else {
335            return [];
336        }
337    }
338
339    /**
340     * @return list{0?: string}
341     */
342    public function pf_lcfirst( $token, Frame $frame, Params $params ): array {
343        $args = $params->args;
344        $target = $args[0]->k;
345        '@phan-var string $target';
346        if ( $target ) {
347            return [ mb_strtolower( mb_substr( $target, 0, 1 ) ) . mb_substr( $target, 1 ) ];
348        } else {
349            return [];
350        }
351    }
352
353    /**
354     * @return list{0?: string}
355     */
356    public function pf_padleft( $token, Frame $frame, Params $params ): array {
357        $args = $params->args;
358        $target = $args[0]->k;
359        $env = $this->env;
360        if ( !$args[1] ) {
361            return [];
362        }
363        // expand parameters 1 and 2
364        $args = $params->getSlice( 1, 3 );
365        $n = +( $args[0]->v );
366        if ( $n > 0 ) {
367            $pad = '0';
368            if ( isset( $args[1] ) && $args[1]->v !== '' ) {
369                $pad = $args[1]->v;
370            }
371            $padLength = mb_strlen( $pad );
372            $extra = '';
373            while ( ( mb_strlen( $target ) + mb_strlen( $extra ) + $padLength ) < $n ) {
374                $extra .= $pad;
375            }
376            if ( mb_strlen( $target ) + mb_strlen( $extra ) < $n ) {
377                $extra .= mb_substr( $pad, 0, $n - mb_strlen( $target ) - mb_strlen( $extra ) );
378            }
379            return [ $extra . $target ];
380        } else {
381            $env->log( 'debug', 'padleft no pad width', $args );
382            return [];
383        }
384    }
385
386    /**
387     * @return list<string|Token|list<string|Token>>
388     */
389    public function pf_padright( $token, Frame $frame, Params $params ): array {
390        $args = $params->args;
391        $target = $args[0]->k;
392        $env = $this->env;
393        if ( !$args[1] ) {
394            return [];
395        }
396
397        // expand parameters 1 and 2
398        $args = $params->getSlice( 1, 3 );
399        $n = +( $args[0]->v );
400        if ( $n > 0 ) {
401            $pad = '0';
402            if ( isset( $args[1] ) && $args[1]->v !== '' ) {
403                $pad = $args[1]->v;
404            }
405            $padLength = mb_strlen( $pad );
406            while ( ( mb_strlen( $target ) + $padLength ) < $n ) {
407                $target .= $pad;
408            }
409            if ( mb_strlen( $target ) < $n ) {
410                $target .= mb_substr( $pad, 0, $n - mb_strlen( $target ) );
411            }
412            return [ $target ];
413        } else {
414            $env->log( 'debug', 'padright no pad width', $args );
415            return [];
416        }
417    }
418
419    public function pf_tag( $token, Frame $frame, Params $params ): array {
420        $args = $params->args;
421        // Check http://www.mediawiki.org/wiki/Extension:TagParser for more info
422        // about the #tag parser function.
423        $target = $args[0]->k;
424        if ( !$target ) {
425            return [];
426        } else {
427            // remove tag-name
428            array_shift( $args );
429            $ret = $this->tag_worker( $target, $args );
430            return $ret;
431        }
432    }
433
434    private function tag_worker( $target, array $kvs ): array {
435        $tagTk = new TagTk( $target );
436        $toks = [ $tagTk ];
437        $tagAttribs = [];
438        foreach ( $kvs as $kv ) {
439            if ( $kv->k === '' ) {
440                if ( is_array( $kv->v ) ) {
441                    PHPUtils::pushArray( $toks, $kv->v );
442                } else {
443                    $toks[] = $kv->v;
444                }
445            } else {
446                $tagAttribs[] = $kv;
447            }
448        }
449
450        $tagTk->attribs = $tagAttribs;
451        $toks[] = new EndTagTk( $target );
452        return $toks;
453    }
454
455    public function pf_currentyear( $token, Frame $frame, Params $params ): array {
456        return $this->pfTime_tokens( 'Y', [] );
457    }
458
459    public function pf_localyear( $token, Frame $frame, Params $params ): array {
460        return $this->pfTimel_tokens( 'Y', [] );
461    }
462
463    public function pf_currentmonth( $token, Frame $frame, Params $params ): array {
464        return $this->pfTime_tokens( 'm', [] );
465    }
466
467    public function pf_localmonth( $token, Frame $frame, Params $params ): array {
468        return $this->pfTimel_tokens( 'm', [] );
469    }
470
471    public function pf_currentmonthname( $token, Frame $frame, Params $params ): array {
472        return $this->pfTime_tokens( 'F', [] );
473    }
474
475    public function pf_localmonthname( $token, Frame $frame, Params $params ): array {
476        return $this->pfTimel_tokens( 'F', [] );
477    }
478
479    public function pf_currentmonthabbrev( $token, Frame $frame, Params $params ): array {
480        return $this->pfTime_tokens( 'M', [] );
481    }
482
483    public function pf_localmonthabbrev( $token, Frame $frame, Params $params ): array {
484        return $this->pfTimel_tokens( 'M', [] );
485    }
486
487    public function pf_currentweek( $token, Frame $frame, Params $params ): array {
488        $toks = $this->pfTime_tokens( 'W', [] );
489        // Cast to int to remove padding, as in core
490        $toks[0] = (string)(int)$toks[0];
491        return $toks;
492    }
493
494    public function pf_localweek( $token, Frame $frame, Params $params ): array {
495        $toks = $this->pfTimel_tokens( 'W', [] );
496        // Cast to int to remove padding, as in core
497        $toks[0] = (string)(int)$toks[0];
498        return $toks;
499    }
500
501    public function pf_currentday( $token, Frame $frame, Params $params ): array {
502        return $this->pfTime_tokens( 'j', [] );
503    }
504
505    public function pf_localday( $token, Frame $frame, Params $params ): array {
506        return $this->pfTimel_tokens( 'j', [] );
507    }
508
509    public function pf_currentday2( $token, Frame $frame, Params $params ): array {
510        return $this->pfTime_tokens( 'd', [] );
511    }
512
513    public function pf_localday2( $token, Frame $frame, Params $params ): array {
514        return $this->pfTimel_tokens( 'd', [] );
515    }
516
517    public function pf_currentdow( $token, Frame $frame, Params $params ): array {
518        return $this->pfTime_tokens( 'w', [] );
519    }
520
521    public function pf_localdow( $token, Frame $frame, Params $params ): array {
522        return $this->pfTimel_tokens( 'w', [] );
523    }
524
525    public function pf_currentdayname( $token, Frame $frame, Params $params ): array {
526        return $this->pfTime_tokens( 'l', [] );
527    }
528
529    public function pf_localdayname( $token, Frame $frame, Params $params ): array {
530        return $this->pfTimel_tokens( 'l', [] );
531    }
532
533    public function pf_currenttime( $token, Frame $frame, Params $params ): array {
534        return $this->pfTime_tokens( 'H:i', [] );
535    }
536
537    public function pf_localtime( $token, Frame $frame, Params $params ): array {
538        return $this->pfTimel_tokens( 'H:i', [] );
539    }
540
541    public function pf_currenthour( $token, Frame $frame, Params $params ): array {
542        return $this->pfTime_tokens( 'H', [] );
543    }
544
545    public function pf_localhour( $token, Frame $frame, Params $params ): array {
546        return $this->pfTimel_tokens( 'H', [] );
547    }
548
549    public function pf_currenttimestamp( $token, Frame $frame, Params $params ): array {
550        return $this->pfTime_tokens( 'YmdHis', [] );
551    }
552
553    public function pf_localtimestamp( $token, Frame $frame, Params $params ): array {
554        return $this->pfTimel_tokens( 'YmdHis', [] );
555    }
556
557    public function pf_currentmonthnamegen( $token, Frame $frame, Params $params ): array {
558        // XXX Actually use genitive form!
559        return $this->pfTime_tokens( 'F', [] );
560    }
561
562    public function pf_localmonthnamegen( $token, Frame $frame, Params $params ): array {
563        return $this->pfTimel_tokens( 'F', [] );
564    }
565
566    /*
567     * A first approximation of time stuff.
568     * TODO: Implement time spec (+ 1 day etc), check if formats are complete etc.
569     * See http://www.mediawiki.org/wiki/Help:Extension:ParserFunctions#.23time
570     * for the full list of requirements!
571     *
572     * First (very rough) approximation below based on
573     * http://jacwright.com/projects/javascript/date_format/, MIT licensed.
574     */
575    public function pf_time( $token, Frame $frame, Params $params ): array {
576        $args = $params->args;
577        return $this->pfTime( $args[0]->k, array_slice( $args, 1 ) );
578    }
579
580    public function pf_timel( $token, Frame $frame, Params $params ): array {
581        $args = $params->args;
582        return $this->pfTime( $args[0]->k, array_slice( $args, 1 ), true );
583    }
584
585    private function pfTime_tokens( $target, $args ) {
586        return $this->pfTime( $target, $args );
587    }
588
589    private function pfTimel_tokens( $target, $args ) {
590        return $this->pfTime( $target, $args, true );
591    }
592
593    /**
594     * @return list{string}
595     */
596    private function pfTime( $target, $args, $isLocal = false ): array {
597        $date = new DateTime( "now", new DateTimeZone( "UTC" ) );
598
599        $timestamp = $this->env->getSiteConfig()->fakeTimestamp();
600        if ( $timestamp ) {
601            $date->setTimestamp( $timestamp );
602        }
603        if ( $isLocal ) {
604            $date->setTimezone( new DateTimeZone( "-" . $this->env->getSiteConfig()->timezoneOffset() ) );
605        }
606
607        try {
608            return [ $date->format( trim( $target ) ) ];
609        } catch ( \Exception $e2 ) {
610            $this->env->log( 'error', '#time ' . $e2 );
611            return [ $date->format( 'D, d M Y H:i:s O' ) ];
612        }
613    }
614
615    /**
616     * @return list{string}
617     */
618    public function pf_localurl( $token, Frame $frame, Params $params ): array {
619        $args = $params->args;
620        $target = $args[0]->k;
621        $env = $this->env;
622        $args = array_slice( $args, 1 );
623        $accum = [];
624        foreach ( $args as $item ) {
625            // FIXME: we are swallowing all errors
626            $res = $this->expandKV( $item, $frame, '', 'expanded-tokens-to-fragment', false );
627            PHPUtils::pushArray( $accum, $res );
628        }
629
630        return [
631            $env->getSiteConfig()->script() . '?title=' .
632            $env->normalizedTitleKey( $target ) . '&' .
633            implode( '&', $accum )
634        ];
635    }
636
637    /* Stub section: Pick any of these and actually implement them!  */
638
639    /**
640     * @return list<string|Token|list<string|Token>>
641     */
642    public function pf_formatnum( $token, Frame $frame, Params $params ): array {
643        $args = $params->args;
644        $target = $args[0]->k;
645        return [ $target ];
646    }
647
648    /**
649     * @return list<string|Token|list<string|Token>>
650     */
651    public function pf_currentpage( $token, Frame $frame, Params $params ): array {
652        $args = $params->args;
653        $target = $args[0]->k;
654        return [ $target ];
655    }
656
657    /**
658     * @return list{string}
659     */
660    public function pf_pagenamee( $token, Frame $frame, Params $params ): array {
661        $args = $params->args;
662        $target = $args[0]->k;
663        return [ explode( ':', $target, 2 )[1] ?? '' ];
664    }
665
666    /**
667     * @return list<string|Token|list<string|Token>>
668     */
669    public function pf_fullpagename( $token, Frame $frame, Params $params ): array {
670        $args = $params->args;
671        $target = $args[0]->k;
672        return [ $target ?: ( $this->prefixedTitleText() ) ];
673    }
674
675    /**
676     * @return list<string|Token|list<string|Token>>
677     */
678    public function pf_fullpagenamee( $token, Frame $frame, Params $params ): array {
679        $args = $params->args;
680        $target = $args[0]->k;
681        return [ $target ?: ( $this->prefixedTitleText() ) ];
682    }
683
684    /**
685     * @return list{string}
686     */
687    public function pf_pagelanguage( $token, Frame $frame, Params $params ): array {
688        // The language (code) of the current page.
689        // Note: this is exposed as a mediawiki-internal code.
690        $code = Utils::bcp47ToMwCode(
691            $this->env->getPageConfig()->getPageLanguageBcp47()
692        );
693        return [ $code ];
694    }
695
696    /**
697     * @return list{string}
698     */
699    public function pf_directionmark( $token, Frame $frame, Params $args ): array {
700        // The directionality of the current page.
701        $dir = $this->env->getPageConfig()->getPageLanguageDir();
702        $mark = $dir === 'rtl' ? '&rlm;' : '&lrm;';
703        // See Parser.php::getVariableValue()
704        return [ Utils::decodeWtEntities( $mark ) ];
705    }
706
707    public function pf_dirmark( $token, Frame $frame, Params $args ): array {
708        return $this->pf_directionmark( $token, $frame, $args );
709    }
710
711    /**
712     * @return list{string}
713     */
714    public function pf_fullurl( $token, Frame $frame, Params $params ): array {
715        $args = $params->args;
716        $target = $args[0]->k;
717        $target = str_replace( ' ', '_', $target ?: ( $this->prefixedTitleText() ) );
718        $wikiConf = $this->env->getSiteConfig();
719        if ( $args[1] ) {
720            $url = $wikiConf->server() .
721                $wikiConf->script() .
722                '?title=' . PHPUtils::encodeURIComponent( $target ) .
723                '&' . $args[1]->k . '=' . $args[1]->v;
724        } else {
725            $url = $wikiConf->baseURI() .
726                implode( '/',
727                    array_map( [ PHPUtils::class, 'encodeURIComponent' ],
728                        explode( '/', str_replace( ' ', '_', $target ) ) )
729                );
730        }
731
732        return [ $url ];
733    }
734
735    /**
736     * @return list{string}
737     */
738    public function pf_urlencode( $token, Frame $frame, Params $params ): array {
739        $args = $params->args;
740        $target = $args[0]->k;
741        return [ PHPUtils::encodeURIComponent( trim( $target ) ) ];
742    }
743
744    /*
745     * The following items all depends on information from the Wiki, so are hard
746     * to implement independently. Some might require using action=parse in the
747     * API to get the value. See
748     * http://www.mediawiki.org/wiki/Parsoid#Token_stream_transforms,
749     * http://etherpad.wikimedia.org/ParserNotesExtensions and
750     * http://www.mediawiki.org/wiki/Wikitext_parser/Environment.
751     * There might be better solutions for some of these.
752     */
753    public function pf_ifexist( $token, Frame $frame, Params $params ): array {
754        $args = $params->args;
755        return $this->expandKV( $args[1], $frame );
756    }
757
758    /**
759     * @return list{string}
760     */
761    public function pf_pagesize( $token, Frame $frame, Params $params ): array {
762        return [ '100' ];
763    }
764
765    /**
766     * @return list{string}
767     */
768    public function pf_sitename( $token, Frame $frame, Params $params ): array {
769        return [ 'MediaWiki' ];
770    }
771
772    private function encodeCharEntity( string $c, array &$tokens ): void {
773        $enc = Utils::entityEncodeAll( $c );
774        $dp = new DataParsoid;
775        $dp->src = $enc;
776        $dp->srcContent = $c;
777        $tokens[] = new TagTk( 'span',
778            [ new KV( 'typeof', 'mw:Entity' ) ],
779            $dp
780        );
781        $tokens[] = $c;
782        $tokens[] = new EndTagTk( 'span', [], new DataParsoid );
783    }
784
785    public function pf_anchorencode( $token, Frame $frame, Params $params ): array {
786        $args = $params->args;
787        $target = $args[0]->k;
788
789        // Parser::guessSectionNameFromWikiText, which invokes
790        // Sanitizer::normalizeSectionNameWhitespace and
791        // Sanitizer::escapeIdForLink, then calls
792        // Sanitizer::safeEncodeAttribute on the result. See: T179544
793        $target = trim( preg_replace( '/[ _]+/', ' ', $target ) );
794        $target = Sanitizer::decodeCharReferences( $target );
795        $target = Sanitizer::escapeIdForLink( $target );
796        $pieces = preg_split(
797            "/([\\{\\}\\[\\]|]|''|ISBN|RFC|PMID|__)/", $target, -1, PREG_SPLIT_DELIM_CAPTURE );
798
799        $tokens = [];
800        foreach ( $pieces as $i => $p ) {
801            if ( ( $i % 2 ) === 0 ) {
802                $tokens[] = $p;
803            } elseif ( $p === "''" ) {
804                $this->encodeCharEntity( $p[0], $tokens );
805                $this->encodeCharEntity( $p[1], $tokens );
806            } else {
807                $this->encodeCharEntity( $p[0], $tokens );
808                $tokens[] = substr( $p, 1 );
809            }
810        }
811
812        return $tokens;
813    }
814
815    /**
816     * @return list{string}
817     */
818    public function pf_protectionlevel( $token, Frame $frame, Params $params ): array {
819        return [ '' ];
820    }
821
822    /**
823     * @return list<string|Token|list<string|Token>>
824     */
825    public function pf_ns( $token, Frame $frame, Params $params ): array {
826        $args = $params->args;
827        $nsid = null;
828        $target = $args[0]->k;
829        $normalizedTarget = str_replace( ' ', '_', mb_strtolower( $target ) );
830
831        $siteConfig = $this->env->getSiteConfig();
832        if ( $siteConfig->namespaceId( $normalizedTarget ) !== null ) {
833            $nsid = $siteConfig->namespaceId( $normalizedTarget );
834        } elseif ( $siteConfig->canonicalNamespaceId( $normalizedTarget ) ) {
835            $nsid = $siteConfig->canonicalNamespaceId( $normalizedTarget );
836        }
837
838        if ( $nsid !== null && $siteConfig->namespaceName( $nsid ) ) {
839            $target = $siteConfig->namespaceName( $nsid );
840        }
841        // FIXME: What happens in the else case above?
842        return [ $target ];
843    }
844
845    /**
846     * @return list{string}
847     */
848    public function pf_subjectspace( $token, Frame $frame, Params $params ): array {
849        return [ 'Main' ];
850    }
851
852    /**
853     * @return list{string}
854     */
855    public function pf_talkspace( $token, Frame $frame, Params $params ): array {
856        return [ 'Talk' ];
857    }
858
859    /**
860     * @return list{string}
861     */
862    public function pf_numberofarticles( $token, Frame $frame, Params $params ): array {
863        return [ '1' ];
864    }
865
866    /**
867     * @return list<string|Token|list<string|Token>>
868     */
869    public function pf_language( $token, Frame $frame, Params $params ): array {
870        $args = $params->args;
871        return [ $args[0]->k ];
872    }
873
874    /**
875     * @return list{string}
876     */
877    public function pf_contentlanguage( $token, Frame $frame, Params $params ): array {
878        // Despite the name, this returns the wiki's default interface language
879        // ($wgLanguageCode), *not* the language of the current page content.
880        // Note: this is exposed as a mediawiki-internal code.
881        $code = Utils::bcp47ToMwCode(
882            $this->env->getSiteConfig()->langBcp47()
883        );
884        return [ $code ];
885    }
886
887    public function pf_contentlang( $token, Frame $frame, Params $params ): array {
888        return $this->pf_contentlanguage( $token, $frame, $params );
889    }
890
891    /**
892     * @return list{string}
893     */
894    public function pf_numberoffiles( $token, Frame $frame, Params $params ): array {
895        return [ '2' ];
896    }
897
898    /**
899     * @return list{string}
900     */
901    public function pf_namespace( $token, Frame $frame, Params $params ): array {
902        $args = $params->args;
903        $target = $args[0]->k;
904        // The JS implementation is broken
905        $pieces = explode( ':', $target );
906        return [ count( $pieces ) > 1 ? $pieces[0] : 'Main' ];
907    }
908
909    /**
910     * @return list{string}
911     */
912    public function pf_namespacee( $token, Frame $frame, Params $params ): array {
913        $args = $params->args;
914        $target = $args[0]->k;
915        // The JS implementation is broken
916        $pieces = explode( ':', $target );
917        return [ count( $pieces ) > 1 ? $pieces[0] : 'Main' ];
918    }
919
920    /**
921     * @return list{string}
922     */
923    public function pf_namespacenumber( $token, Frame $frame, Params $params ): array {
924        $args = $params->args;
925        $a = explode( ':', $args[0]->k );
926        $target = array_pop( $a );
927        return [ (string)$this->env->getSiteConfig()->namespaceId( $target ) ];
928    }
929
930    /**
931     * @return list{string}
932     */
933    public function pf_pagename( $token, Frame $frame, Params $params ): array {
934        return [ $this->prefixedTitleText() ];
935    }
936
937    /**
938     * @return list{string}
939     */
940    public function pf_pagenamebase( $token, Frame $frame, Params $params ): array {
941        return [ $this->prefixedTitleText() ];
942    }
943
944    /**
945     * @return list{string}
946     */
947    public function pf_scriptpath( $token, Frame $frame, Params $params ): array {
948        return [ $this->env->getSiteConfig()->scriptpath() ];
949    }
950
951    /**
952     * @return list{TagTk, string, EndTagTk}
953     */
954    public function pf_server( $token, Frame $frame, Params $params ): array {
955        $dataParsoid = clone $token->dataParsoid;
956        return [
957            new TagTk( 'a', [
958                    new KV( 'rel', 'nofollow' ),
959                    new KV( 'class', 'external free' ),
960                    new KV( 'href', $this->env->getSiteConfig()->server() ),
961                    new KV( 'typeof', 'mw:ExtLink/URL' )
962                ], $dataParsoid
963            ),
964            $this->env->getSiteConfig()->server(),
965            new EndTagTk( 'a' )
966        ];
967    }
968
969    /**
970     * @return list{string}
971     */
972    public function pf_servername( $token, Frame $frame, Params $params ): array {
973        $server = $this->env->getSiteConfig()->server();
974        return [ preg_replace( '#^https?://#', '', $server, 1 ) ];
975    }
976
977    /**
978     * @return list{string}
979     */
980    public function pf_talkpagename( $token, Frame $frame, Params $params ): array {
981        $title = $this->prefixedTitleText();
982        return [ preg_replace( '/^[^:]:/', 'Talk:', $title, 1 ) ];
983    }
984
985    /**
986     * @return list{SelfclosingTagTk}
987     */
988    public function pf_defaultsort( $token, Frame $frame, Params $params ): array {
989        $args = $params->args;
990        $key = $args[0]->k;
991        return [
992            new SelfclosingTagTk( 'meta', [
993                    new KV( 'property', 'mw:PageProp/categorydefaultsort' ),
994                    new KV( 'content', trim( $key ) )
995                ]
996            )
997        ];
998    }
999
1000    /**
1001     * @return list{SelfclosingTagTk}
1002     */
1003    public function pf_displaytitle( $token, Frame $frame, Params $params ): array {
1004        $args = $params->args;
1005        $key = $args[0]->k;
1006        return [
1007            new SelfclosingTagTk( 'meta', [
1008                    new KV( 'property', 'mw:PageProp/displaytitle' ),
1009                    new KV( 'content', trim( $key ) )
1010                ]
1011            )
1012        ];
1013    }
1014
1015    /**
1016     * @return list{string}
1017     */
1018    public function pf_equal( $token, Frame $frame, Params $params ): array {
1019        return [ '=' ];
1020    }
1021
1022    // TODO: #titleparts, SUBJECTPAGENAME, BASEPAGENAME. SUBPAGENAME, DEFAULTSORT
1023}