Merge "Add PHPUnit test to ApiQueryDisabled"
[lhc/web/wiklou.git] / includes / parser / CoreParserFunctions.php
1 <?php
2 /**
3 * Parser functions provided by MediaWiki core
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Parser
22 */
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Various core parser functions, registered in Parser::firstCallInit()
27 * @ingroup Parser
28 */
29 class CoreParserFunctions {
30 /**
31 * @param Parser $parser
32 * @return void
33 */
34 public static function register( $parser ) {
35 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36
37 # Syntax for arguments (see Parser::setFunctionHook):
38 # "name for lookup in localized magic words array",
39 # function callback,
40 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
41 # instead of {{#int:...}})
42 $noHashFunctions = [
43 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
44 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
45 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural', 'bidi',
46 'numberofpages', 'numberofusers', 'numberofactiveusers',
47 'numberofarticles', 'numberoffiles', 'numberofadmins',
48 'numberingroup', 'numberofedits', 'language',
49 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
50 'pagesincategory', 'pagesize', 'protectionlevel', 'protectionexpiry',
51 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
52 'subjectspace', 'subjectspacee', 'pagename', 'pagenamee',
53 'fullpagename', 'fullpagenamee', 'rootpagename', 'rootpagenamee',
54 'basepagename', 'basepagenamee', 'subpagename', 'subpagenamee',
55 'talkpagename', 'talkpagenamee', 'subjectpagename',
56 'subjectpagenamee', 'pageid', 'revisionid', 'revisionday',
57 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
58 'revisiontimestamp', 'revisionuser', 'cascadingsources',
59 ];
60 foreach ( $noHashFunctions as $func ) {
61 $parser->setFunctionHook( $func, [ __CLASS__, $func ], Parser::SFH_NO_HASH );
62 }
63
64 $parser->setFunctionHook(
65 'namespace',
66 [ __CLASS__, 'mwnamespace' ],
67 Parser::SFH_NO_HASH
68 );
69 $parser->setFunctionHook( 'int', [ __CLASS__, 'intFunction' ], Parser::SFH_NO_HASH );
70 $parser->setFunctionHook( 'special', [ __CLASS__, 'special' ] );
71 $parser->setFunctionHook( 'speciale', [ __CLASS__, 'speciale' ] );
72 $parser->setFunctionHook( 'tag', [ __CLASS__, 'tagObj' ], Parser::SFH_OBJECT_ARGS );
73 $parser->setFunctionHook( 'formatdate', [ __CLASS__, 'formatDate' ] );
74
75 if ( $wgAllowDisplayTitle ) {
76 $parser->setFunctionHook(
77 'displaytitle',
78 [ __CLASS__, 'displaytitle' ],
79 Parser::SFH_NO_HASH
80 );
81 }
82 if ( $wgAllowSlowParserFunctions ) {
83 $parser->setFunctionHook(
84 'pagesinnamespace',
85 [ __CLASS__, 'pagesinnamespace' ],
86 Parser::SFH_NO_HASH
87 );
88 }
89 }
90
91 /**
92 * @param Parser $parser
93 * @param string $part1
94 * @return array
95 */
96 public static function intFunction( $parser, $part1 = '' /*, ... */ ) {
97 if ( strval( $part1 ) !== '' ) {
98 $args = array_slice( func_get_args(), 2 );
99 $message = wfMessage( $part1, $args )
100 ->inLanguage( $parser->getOptions()->getUserLangObj() );
101 if ( !$message->exists() ) {
102 // When message does not exists, the message name is surrounded by angle
103 // and can result in a tag, therefore escape the angles
104 return $message->escaped();
105 }
106 return [ $message->plain(), 'noparse' => false ];
107 } else {
108 return [ 'found' => false ];
109 }
110 }
111
112 /**
113 * @param Parser $parser
114 * @param string $date
115 * @param string|null $defaultPref
116 *
117 * @return string
118 */
119 public static function formatDate( $parser, $date, $defaultPref = null ) {
120 $lang = $parser->getFunctionLang();
121 $df = DateFormatter::getInstance( $lang );
122
123 $date = trim( $date );
124
125 $pref = $parser->getOptions()->getDateFormat();
126
127 // Specify a different default date format other than the normal default
128 // if the user has 'default' for their setting
129 if ( $pref == 'default' && $defaultPref ) {
130 $pref = $defaultPref;
131 }
132
133 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
134 return $date;
135 }
136
137 public static function ns( $parser, $part1 = '' ) {
138 if ( intval( $part1 ) || $part1 == "0" ) {
139 $index = intval( $part1 );
140 } else {
141 $index = $parser->getContentLanguage()->getNsIndex( str_replace( ' ', '_', $part1 ) );
142 }
143 if ( $index !== false ) {
144 return $parser->getContentLanguage()->getFormattedNsText( $index );
145 } else {
146 return [ 'found' => false ];
147 }
148 }
149
150 public static function nse( $parser, $part1 = '' ) {
151 $ret = self::ns( $parser, $part1 );
152 if ( is_string( $ret ) ) {
153 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
154 }
155 return $ret;
156 }
157
158 /**
159 * urlencodes a string according to one of three patterns: (T24474)
160 *
161 * By default (for HTTP "query" strings), spaces are encoded as '+'.
162 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
163 * For links to "wiki"s, or similar software, spaces are encoded as '_',
164 *
165 * @param Parser $parser
166 * @param string $s The text to encode.
167 * @param string|null $arg (optional): The type of encoding.
168 * @return string
169 */
170 public static function urlencode( $parser, $s = '', $arg = null ) {
171 static $magicWords = null;
172 if ( is_null( $magicWords ) ) {
173 $magicWords =
174 $parser->getMagicWordFactory()->newArray( [ 'url_path', 'url_query', 'url_wiki' ] );
175 }
176 switch ( $magicWords->matchStartToEnd( $arg ) ) {
177 // Encode as though it's a wiki page, '_' for ' '.
178 case 'url_wiki':
179 $func = 'wfUrlencode';
180 $s = str_replace( ' ', '_', $s );
181 break;
182
183 // Encode for an HTTP Path, '%20' for ' '.
184 case 'url_path':
185 $func = 'rawurlencode';
186 break;
187
188 // Encode for HTTP query, '+' for ' '.
189 case 'url_query':
190 default:
191 $func = 'urlencode';
192 }
193 // See T105242, where the choice to kill markers and various
194 // other options were discussed.
195 return $func( $parser->killMarkers( $s ) );
196 }
197
198 public static function lcfirst( $parser, $s = '' ) {
199 return $parser->getContentLanguage()->lcfirst( $s );
200 }
201
202 public static function ucfirst( $parser, $s = '' ) {
203 return $parser->getContentLanguage()->ucfirst( $s );
204 }
205
206 /**
207 * @param Parser $parser
208 * @param string $s
209 * @return string
210 */
211 public static function lc( $parser, $s = '' ) {
212 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'lc' ] );
213 }
214
215 /**
216 * @param Parser $parser
217 * @param string $s
218 * @return string
219 */
220 public static function uc( $parser, $s = '' ) {
221 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'uc' ] );
222 }
223
224 public static function localurl( $parser, $s = '', $arg = null ) {
225 return self::urlFunction( 'getLocalURL', $s, $arg );
226 }
227
228 public static function localurle( $parser, $s = '', $arg = null ) {
229 $temp = self::urlFunction( 'getLocalURL', $s, $arg );
230 if ( !is_string( $temp ) ) {
231 return $temp;
232 } else {
233 return htmlspecialchars( $temp );
234 }
235 }
236
237 public static function fullurl( $parser, $s = '', $arg = null ) {
238 return self::urlFunction( 'getFullURL', $s, $arg );
239 }
240
241 public static function fullurle( $parser, $s = '', $arg = null ) {
242 $temp = self::urlFunction( 'getFullURL', $s, $arg );
243 if ( !is_string( $temp ) ) {
244 return $temp;
245 } else {
246 return htmlspecialchars( $temp );
247 }
248 }
249
250 public static function canonicalurl( $parser, $s = '', $arg = null ) {
251 return self::urlFunction( 'getCanonicalURL', $s, $arg );
252 }
253
254 public static function canonicalurle( $parser, $s = '', $arg = null ) {
255 $temp = self::urlFunction( 'getCanonicalURL', $s, $arg );
256 if ( !is_string( $temp ) ) {
257 return $temp;
258 } else {
259 return htmlspecialchars( $temp );
260 }
261 }
262
263 public static function urlFunction( $func, $s = '', $arg = null ) {
264 $title = Title::newFromText( $s );
265 # Due to order of execution of a lot of bits, the values might be encoded
266 # before arriving here; if that's true, then the title can't be created
267 # and the variable will fail. If we can't get a decent title from the first
268 # attempt, url-decode and try for a second.
269 if ( is_null( $title ) ) {
270 $title = Title::newFromURL( urldecode( $s ) );
271 }
272 if ( !is_null( $title ) ) {
273 # Convert NS_MEDIA -> NS_FILE
274 if ( $title->inNamespace( NS_MEDIA ) ) {
275 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
276 }
277 if ( !is_null( $arg ) ) {
278 $text = $title->$func( $arg );
279 } else {
280 $text = $title->$func();
281 }
282 return $text;
283 } else {
284 return [ 'found' => false ];
285 }
286 }
287
288 /**
289 * @param Parser $parser
290 * @param string $num
291 * @param string|null $arg
292 * @return string
293 */
294 public static function formatnum( $parser, $num = '', $arg = null ) {
295 if ( self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg ) ) {
296 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
297 } elseif (
298 self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'nocommafysuffix', $arg )
299 ) {
300 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
301 } else {
302 $func = [ $parser->getFunctionLang(), 'formatNum' ];
303 }
304 return $parser->markerSkipCallback( $num, $func );
305 }
306
307 /**
308 * @param Parser $parser
309 * @param string $case
310 * @param string $word
311 * @return string
312 */
313 public static function grammar( $parser, $case = '', $word = '' ) {
314 $word = $parser->killMarkers( $word );
315 return $parser->getFunctionLang()->convertGrammar( $word, $case );
316 }
317
318 /**
319 * @param Parser $parser
320 * @param string $username
321 * @return string
322 */
323 public static function gender( $parser, $username ) {
324 $forms = array_slice( func_get_args(), 2 );
325
326 // Some shortcuts to avoid loading user data unnecessarily
327 if ( count( $forms ) === 0 ) {
328 return '';
329 } elseif ( count( $forms ) === 1 ) {
330 return $forms[0];
331 }
332
333 $username = trim( $username );
334
335 // default
336 $gender = User::getDefaultOption( 'gender' );
337
338 // allow prefix and normalize (e.g. "&#42;foo" -> "*foo" ).
339 $title = Title::newFromText( $username, NS_USER );
340
341 if ( $title && $title->inNamespace( NS_USER ) ) {
342 $username = $title->getText();
343 }
344
345 // check parameter, or use the ParserOptions if in interface message
346 $user = User::newFromName( $username );
347 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
348 if ( $user ) {
349 $gender = $genderCache->getGenderOf( $user, __METHOD__ );
350 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
351 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
352 }
353 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
354 return $ret;
355 }
356
357 /**
358 * @param Parser $parser
359 * @param string $text
360 * @return string
361 */
362 public static function plural( $parser, $text = '' ) {
363 $forms = array_slice( func_get_args(), 2 );
364 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
365 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
366 return $parser->getFunctionLang()->convertPlural( $text, $forms );
367 }
368
369 /**
370 * @param Parser $parser
371 * @param string $text
372 * @return string
373 */
374 public static function bidi( $parser, $text = '' ) {
375 return $parser->getFunctionLang()->embedBidi( $text );
376 }
377
378 /**
379 * Override the title of the page when viewed, provided we've been given a
380 * title which will normalise to the canonical title
381 *
382 * @param Parser $parser Parent parser
383 * @param string $text Desired title text
384 * @param string $uarg
385 * @return string
386 */
387 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
388 global $wgRestrictDisplayTitle;
389
390 static $magicWords = null;
391 if ( is_null( $magicWords ) ) {
392 $magicWords = $parser->getMagicWordFactory()->newArray(
393 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
394 }
395 $arg = $magicWords->matchStartToEnd( $uarg );
396
397 // parse a limited subset of wiki markup (just the single quote items)
398 $text = $parser->doQuotes( $text );
399
400 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
401 $text = $parser->killMarkers( $text );
402
403 // list of disallowed tags for DISPLAYTITLE
404 // these will be escaped even though they are allowed in normal wiki text
405 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
406 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
407
408 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
409 if ( $wgRestrictDisplayTitle ) {
410 $htmlTagsCallback = function ( &$params ) {
411 $decoded = Sanitizer::decodeTagAttributes( $params );
412
413 if ( isset( $decoded['style'] ) ) {
414 // this is called later anyway, but we need it right now for the regexes below to be safe
415 // calling it twice doesn't hurt
416 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
417
418 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
419 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
420 }
421 }
422
423 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
424 };
425 } else {
426 $htmlTagsCallback = null;
427 }
428
429 // only requested titles that normalize to the actual title are allowed through
430 // if $wgRestrictDisplayTitle is true (it is by default)
431 // mimic the escaping process that occurs in OutputPage::setPageTitle
432 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
433 $text,
434 $htmlTagsCallback,
435 [],
436 [],
437 $bad
438 ) );
439 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
440
441 if ( !$wgRestrictDisplayTitle ||
442 ( $title instanceof Title
443 && !$title->hasFragment()
444 && $title->equals( $parser->mTitle ) )
445 ) {
446 $old = $parser->mOutput->getProperty( 'displaytitle' );
447 if ( $old === false || $arg !== 'displaytitle_noreplace' ) {
448 $parser->mOutput->setDisplayTitle( $text );
449 }
450 if ( $old !== false && $old !== $text && !$arg ) {
451 $converter = $parser->getTargetLanguage()->getConverter();
452 return '<span class="error">' .
453 wfMessage( 'duplicate-displaytitle',
454 // Message should be parsed, but these params should only be escaped.
455 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
456 $converter->markNoConversion( wfEscapeWikiText( $text ) )
457 )->inContentLanguage()->text() .
458 '</span>';
459 } else {
460 return '';
461 }
462 } else {
463 $converter = $parser->getTargetLanguage()->getConverter();
464 $parser->getOutput()->addWarning(
465 wfMessage( 'restricted-displaytitle',
466 // Message should be parsed, but this param should only be escaped.
467 $converter->markNoConversion( wfEscapeWikiText( $text ) )
468 )->text()
469 );
470 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
471 }
472 }
473
474 /**
475 * Matches the given value against the value of given magic word
476 *
477 * @param MagicWordFactory $magicWordFactory A factory to get the word from, e.g., from
478 * $parser->getMagicWordFactory()
479 * @param string $magicword Magic word key
480 * @param string $value Value to match
481 * @return bool True on successful match
482 */
483 private static function matchAgainstMagicword(
484 MagicWordFactory $magicWordFactory, $magicword, $value
485 ) {
486 $value = trim( strval( $value ) );
487 if ( $value === '' ) {
488 return false;
489 }
490 $mwObject = $magicWordFactory->get( $magicword );
491 return $mwObject->matchStartToEnd( $value );
492 }
493
494 /**
495 * Formats a number according to a language.
496 *
497 * @param int|float $num
498 * @param string $raw
499 * @param Language|StubUserLang $language
500 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
501 * @return string
502 */
503 public static function formatRaw(
504 $num, $raw, $language, MagicWordFactory $magicWordFactory = null
505 ) {
506 if ( $raw !== null && !$magicWordFactory ) {
507 $magicWordFactory = MediaWikiServices::getInstance()->getMagicWordFactory();
508 }
509 if (
510 $raw !== null && self::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw )
511 ) {
512 return $num;
513 } else {
514 return $language->formatNum( $num );
515 }
516 }
517
518 public static function numberofpages( $parser, $raw = null ) {
519 return self::formatRaw( SiteStats::pages(), $raw, $parser->getFunctionLang() );
520 }
521
522 public static function numberofusers( $parser, $raw = null ) {
523 return self::formatRaw( SiteStats::users(), $raw, $parser->getFunctionLang() );
524 }
525 public static function numberofactiveusers( $parser, $raw = null ) {
526 return self::formatRaw( SiteStats::activeUsers(), $raw, $parser->getFunctionLang() );
527 }
528
529 public static function numberofarticles( $parser, $raw = null ) {
530 return self::formatRaw( SiteStats::articles(), $raw, $parser->getFunctionLang() );
531 }
532
533 public static function numberoffiles( $parser, $raw = null ) {
534 return self::formatRaw( SiteStats::images(), $raw, $parser->getFunctionLang() );
535 }
536
537 public static function numberofadmins( $parser, $raw = null ) {
538 return self::formatRaw(
539 SiteStats::numberingroup( 'sysop' ),
540 $raw,
541 $parser->getFunctionLang()
542 );
543 }
544
545 public static function numberofedits( $parser, $raw = null ) {
546 return self::formatRaw( SiteStats::edits(), $raw, $parser->getFunctionLang() );
547 }
548
549 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
550 return self::formatRaw(
551 SiteStats::pagesInNs( intval( $namespace ) ),
552 $raw,
553 $parser->getFunctionLang()
554 );
555 }
556 public static function numberingroup( $parser, $name = '', $raw = null ) {
557 return self::formatRaw(
558 SiteStats::numberingroup( strtolower( $name ) ),
559 $raw,
560 $parser->getFunctionLang()
561 );
562 }
563
564 /**
565 * Given a title, return the namespace name that would be given by the
566 * corresponding magic word
567 * Note: function name changed to "mwnamespace" rather than "namespace"
568 * to not break PHP 5.3
569 * @param Parser $parser
570 * @param string|null $title
571 * @return mixed|string
572 */
573 public static function mwnamespace( $parser, $title = null ) {
574 $t = Title::newFromText( $title );
575 if ( is_null( $t ) ) {
576 return '';
577 }
578 return str_replace( '_', ' ', $t->getNsText() );
579 }
580 public static function namespacee( $parser, $title = null ) {
581 $t = Title::newFromText( $title );
582 if ( is_null( $t ) ) {
583 return '';
584 }
585 return wfUrlencode( $t->getNsText() );
586 }
587 public static function namespacenumber( $parser, $title = null ) {
588 $t = Title::newFromText( $title );
589 if ( is_null( $t ) ) {
590 return '';
591 }
592 return $t->getNamespace();
593 }
594 public static function talkspace( $parser, $title = null ) {
595 $t = Title::newFromText( $title );
596 if ( is_null( $t ) || !$t->canHaveTalkPage() ) {
597 return '';
598 }
599 return str_replace( '_', ' ', $t->getTalkNsText() );
600 }
601 public static function talkspacee( $parser, $title = null ) {
602 $t = Title::newFromText( $title );
603 if ( is_null( $t ) || !$t->canHaveTalkPage() ) {
604 return '';
605 }
606 return wfUrlencode( $t->getTalkNsText() );
607 }
608 public static function subjectspace( $parser, $title = null ) {
609 $t = Title::newFromText( $title );
610 if ( is_null( $t ) ) {
611 return '';
612 }
613 return str_replace( '_', ' ', $t->getSubjectNsText() );
614 }
615 public static function subjectspacee( $parser, $title = null ) {
616 $t = Title::newFromText( $title );
617 if ( is_null( $t ) ) {
618 return '';
619 }
620 return wfUrlencode( $t->getSubjectNsText() );
621 }
622
623 /**
624 * Functions to get and normalize pagenames, corresponding to the magic words
625 * of the same names
626 * @param Parser $parser
627 * @param string|null $title
628 * @return string
629 */
630 public static function pagename( $parser, $title = null ) {
631 $t = Title::newFromText( $title );
632 if ( is_null( $t ) ) {
633 return '';
634 }
635 return wfEscapeWikiText( $t->getText() );
636 }
637 public static function pagenamee( $parser, $title = null ) {
638 $t = Title::newFromText( $title );
639 if ( is_null( $t ) ) {
640 return '';
641 }
642 return wfEscapeWikiText( $t->getPartialURL() );
643 }
644 public static function fullpagename( $parser, $title = null ) {
645 $t = Title::newFromText( $title );
646 if ( is_null( $t ) || !$t->canHaveTalkPage() ) {
647 return '';
648 }
649 return wfEscapeWikiText( $t->getPrefixedText() );
650 }
651 public static function fullpagenamee( $parser, $title = null ) {
652 $t = Title::newFromText( $title );
653 if ( is_null( $t ) || !$t->canHaveTalkPage() ) {
654 return '';
655 }
656 return wfEscapeWikiText( $t->getPrefixedURL() );
657 }
658 public static function subpagename( $parser, $title = null ) {
659 $t = Title::newFromText( $title );
660 if ( is_null( $t ) ) {
661 return '';
662 }
663 return wfEscapeWikiText( $t->getSubpageText() );
664 }
665 public static function subpagenamee( $parser, $title = null ) {
666 $t = Title::newFromText( $title );
667 if ( is_null( $t ) ) {
668 return '';
669 }
670 return wfEscapeWikiText( $t->getSubpageUrlForm() );
671 }
672 public static function rootpagename( $parser, $title = null ) {
673 $t = Title::newFromText( $title );
674 if ( is_null( $t ) ) {
675 return '';
676 }
677 return wfEscapeWikiText( $t->getRootText() );
678 }
679 public static function rootpagenamee( $parser, $title = null ) {
680 $t = Title::newFromText( $title );
681 if ( is_null( $t ) ) {
682 return '';
683 }
684 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
685 }
686 public static function basepagename( $parser, $title = null ) {
687 $t = Title::newFromText( $title );
688 if ( is_null( $t ) ) {
689 return '';
690 }
691 return wfEscapeWikiText( $t->getBaseText() );
692 }
693 public static function basepagenamee( $parser, $title = null ) {
694 $t = Title::newFromText( $title );
695 if ( is_null( $t ) ) {
696 return '';
697 }
698 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
699 }
700 public static function talkpagename( $parser, $title = null ) {
701 $t = Title::newFromText( $title );
702 if ( is_null( $t ) || !$t->canHaveTalkPage() ) {
703 return '';
704 }
705 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
706 }
707 public static function talkpagenamee( $parser, $title = null ) {
708 $t = Title::newFromText( $title );
709 if ( is_null( $t ) || !$t->canHaveTalkPage() ) {
710 return '';
711 }
712 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
713 }
714 public static function subjectpagename( $parser, $title = null ) {
715 $t = Title::newFromText( $title );
716 if ( is_null( $t ) ) {
717 return '';
718 }
719 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
720 }
721 public static function subjectpagenamee( $parser, $title = null ) {
722 $t = Title::newFromText( $title );
723 if ( is_null( $t ) ) {
724 return '';
725 }
726 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
727 }
728
729 /**
730 * Return the number of pages, files or subcats in the given category,
731 * or 0 if it's nonexistent. This is an expensive parser function and
732 * can't be called too many times per page.
733 * @param Parser $parser
734 * @param string $name
735 * @param string|null $arg1
736 * @param string|null $arg2
737 * @return string
738 */
739 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
740 static $magicWords = null;
741 if ( is_null( $magicWords ) ) {
742 $magicWords = $parser->getMagicWordFactory()->newArray( [
743 'pagesincategory_all',
744 'pagesincategory_pages',
745 'pagesincategory_subcats',
746 'pagesincategory_files'
747 ] );
748 }
749 static $cache = [];
750
751 // split the given option to its variable
752 if ( self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
753 // {{pagesincategory:|raw[|type]}}
754 $raw = $arg1;
755 $type = $magicWords->matchStartToEnd( $arg2 );
756 } else {
757 // {{pagesincategory:[|type[|raw]]}}
758 $type = $magicWords->matchStartToEnd( $arg1 );
759 $raw = $arg2;
760 }
761 if ( !$type ) { // backward compatibility
762 $type = 'pagesincategory_all';
763 }
764
765 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
766 if ( !$title ) { # invalid title
767 return self::formatRaw( 0, $raw, $parser->getFunctionLang() );
768 }
769 $parser->getContentLanguage()->findVariantLink( $name, $title, true );
770
771 // Normalize name for cache
772 $name = $title->getDBkey();
773
774 if ( !isset( $cache[$name] ) ) {
775 $category = Category::newFromTitle( $title );
776
777 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
778 if ( $parser->incrementExpensiveFunctionCount() ) {
779 // $allCount is the total number of cat members,
780 // not the count of how many members are normal pages.
781 $allCount = (int)$category->getPageCount();
782 $subcatCount = (int)$category->getSubcatCount();
783 $fileCount = (int)$category->getFileCount();
784 $pagesCount = $allCount - $subcatCount - $fileCount;
785 }
786 $cache[$name]['pagesincategory_all'] = $allCount;
787 $cache[$name]['pagesincategory_pages'] = $pagesCount;
788 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
789 $cache[$name]['pagesincategory_files'] = $fileCount;
790 }
791
792 $count = $cache[$name][$type];
793 return self::formatRaw( $count, $raw, $parser->getFunctionLang() );
794 }
795
796 /**
797 * Return the size of the given page, or 0 if it's nonexistent. This is an
798 * expensive parser function and can't be called too many times per page.
799 *
800 * @param Parser $parser
801 * @param string $page Name of page to check (Default: empty string)
802 * @param string|null $raw Should number be human readable with commas or just number
803 * @return string
804 */
805 public static function pagesize( $parser, $page = '', $raw = null ) {
806 $title = Title::newFromText( $page );
807
808 if ( !is_object( $title ) ) {
809 return self::formatRaw( 0, $raw, $parser->getFunctionLang() );
810 }
811
812 // fetch revision from cache/database and return the value
813 $rev = self::getCachedRevisionObject( $parser, $title );
814 $length = $rev ? $rev->getSize() : 0;
815 if ( $length === null ) {
816 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
817 $length = 0;
818 }
819 return self::formatRaw( $length, $raw, $parser->getFunctionLang() );
820 }
821
822 /**
823 * Returns the requested protection level for the current page. This
824 * is an expensive parser function and can't be called too many times
825 * per page, unless the protection levels/expiries for the given title
826 * have already been retrieved
827 *
828 * @param Parser $parser
829 * @param string $type
830 * @param string $title
831 *
832 * @return string
833 */
834 public static function protectionlevel( $parser, $type = '', $title = '' ) {
835 $titleObject = Title::newFromText( $title );
836 if ( !( $titleObject instanceof Title ) ) {
837 $titleObject = $parser->mTitle;
838 }
839 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
840 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
841 # Title::getRestrictions returns an array, its possible it may have
842 # multiple values in the future
843 return implode( ',', $restrictions );
844 }
845 return '';
846 }
847
848 /**
849 * Returns the requested protection expiry for the current page. This
850 * is an expensive parser function and can't be called too many times
851 * per page, unless the protection levels/expiries for the given title
852 * have already been retrieved
853 *
854 * @param Parser $parser
855 * @param string $type
856 * @param string $title
857 *
858 * @return string
859 */
860 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
861 $titleObject = Title::newFromText( $title );
862 if ( !( $titleObject instanceof Title ) ) {
863 $titleObject = $parser->mTitle;
864 }
865 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
866 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
867 // getRestrictionExpiry() returns false on invalid type; trying to
868 // match protectionlevel() function that returns empty string instead
869 if ( $expiry === false ) {
870 $expiry = '';
871 }
872 return $expiry;
873 }
874 return '';
875 }
876
877 /**
878 * Gives language names.
879 * @param Parser $parser
880 * @param string $code Language code (of which to get name)
881 * @param string $inLanguage Language code (in which to get name)
882 * @return string
883 */
884 public static function language( $parser, $code = '', $inLanguage = '' ) {
885 $code = strtolower( $code );
886 $inLanguage = strtolower( $inLanguage );
887 $lang = Language::fetchLanguageName( $code, $inLanguage );
888 return $lang !== '' ? $lang : LanguageCode::bcp47( $code );
889 }
890
891 /**
892 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
893 * @param Parser $parser
894 * @param string $string
895 * @param string $length
896 * @param string $padding
897 * @param int $direction
898 * @return string
899 */
900 public static function pad(
901 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
902 ) {
903 $padding = $parser->killMarkers( $padding );
904 $lengthOfPadding = mb_strlen( $padding );
905 if ( $lengthOfPadding == 0 ) {
906 return $string;
907 }
908
909 # The remaining length to add counts down to 0 as padding is added
910 $length = min( (int)$length, 500 ) - mb_strlen( $string );
911 if ( $length <= 0 ) {
912 // Nothing to add
913 return $string;
914 }
915
916 # $finalPadding is just $padding repeated enough times so that
917 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
918 $finalPadding = '';
919 while ( $length > 0 ) {
920 # If $length < $lengthofPadding, truncate $padding so we get the
921 # exact length desired.
922 $finalPadding .= mb_substr( $padding, 0, $length );
923 $length -= $lengthOfPadding;
924 }
925
926 if ( $direction == STR_PAD_LEFT ) {
927 return $finalPadding . $string;
928 } else {
929 return $string . $finalPadding;
930 }
931 }
932
933 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
934 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
935 }
936
937 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
938 return self::pad( $parser, $string, $length, $padding );
939 }
940
941 /**
942 * @param Parser $parser
943 * @param string $text
944 * @return string
945 */
946 public static function anchorencode( $parser, $text ) {
947 $text = $parser->killMarkers( $text );
948 $section = (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
949 return Sanitizer::safeEncodeAttribute( $section );
950 }
951
952 public static function special( $parser, $text ) {
953 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
954 if ( $page ) {
955 $title = SpecialPage::getTitleFor( $page, $subpage );
956 return $title->getPrefixedText();
957 } else {
958 // unknown special page, just use the given text as its title, if at all possible
959 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
960 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
961 }
962 }
963
964 public static function speciale( $parser, $text ) {
965 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
966 }
967
968 /**
969 * @param Parser $parser
970 * @param string $text The sortkey to use
971 * @param string $uarg Either "noreplace" or "noerror" (in en)
972 * both suppress errors, and noreplace does nothing if
973 * a default sortkey already exists.
974 * @return string
975 */
976 public static function defaultsort( $parser, $text, $uarg = '' ) {
977 static $magicWords = null;
978 if ( is_null( $magicWords ) ) {
979 $magicWords = $parser->getMagicWordFactory()->newArray(
980 [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
981 }
982 $arg = $magicWords->matchStartToEnd( $uarg );
983
984 $text = trim( $text );
985 if ( strlen( $text ) == 0 ) {
986 return '';
987 }
988 $old = $parser->getCustomDefaultSort();
989 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
990 $parser->setDefaultSort( $text );
991 }
992
993 if ( $old === false || $old == $text || $arg ) {
994 return '';
995 } else {
996 $converter = $parser->getTargetLanguage()->getConverter();
997 return '<span class="error">' .
998 wfMessage( 'duplicate-defaultsort',
999 // Message should be parsed, but these params should only be escaped.
1000 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
1001 $converter->markNoConversion( wfEscapeWikiText( $text ) )
1002 )->inContentLanguage()->text() .
1003 '</span>';
1004 }
1005 }
1006
1007 /**
1008 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
1009 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
1010 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
1011 *
1012 * @param Parser $parser
1013 * @param string $name
1014 * @param string $argA
1015 * @param string $argB
1016 * @return array|string
1017 */
1018 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1019 $file = wfFindFile( $name );
1020
1021 if ( $argA == 'nowiki' ) {
1022 // {{filepath: | option [| size] }}
1023 $isNowiki = true;
1024 $parsedWidthParam = Parser::parseWidthParam( $argB );
1025 } else {
1026 // {{filepath: [| size [|option]] }}
1027 $parsedWidthParam = Parser::parseWidthParam( $argA );
1028 $isNowiki = ( $argB == 'nowiki' );
1029 }
1030
1031 if ( $file ) {
1032 $url = $file->getFullUrl();
1033
1034 // If a size is requested...
1035 if ( count( $parsedWidthParam ) ) {
1036 $mto = $file->transform( $parsedWidthParam );
1037 // ... and we can
1038 if ( $mto && !$mto->isError() ) {
1039 // ... change the URL to point to a thumbnail.
1040 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
1041 }
1042 }
1043 if ( $isNowiki ) {
1044 return [ $url, 'nowiki' => true ];
1045 }
1046 return $url;
1047 } else {
1048 return '';
1049 }
1050 }
1051
1052 /**
1053 * Parser function to extension tag adaptor
1054 * @param Parser $parser
1055 * @param PPFrame $frame
1056 * @param PPNode[] $args
1057 * @return string
1058 */
1059 public static function tagObj( $parser, $frame, $args ) {
1060 if ( !count( $args ) ) {
1061 return '';
1062 }
1063 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1064
1065 if ( count( $args ) ) {
1066 $inner = $frame->expand( array_shift( $args ) );
1067 } else {
1068 $inner = null;
1069 }
1070
1071 $attributes = [];
1072 foreach ( $args as $arg ) {
1073 $bits = $arg->splitArg();
1074 if ( strval( $bits['index'] ) === '' ) {
1075 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1076 $value = trim( $frame->expand( $bits['value'] ) );
1077 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1078 $value = $m[1] ?? '';
1079 }
1080 $attributes[$name] = $value;
1081 }
1082 }
1083
1084 $stripList = $parser->getStripList();
1085 if ( !in_array( $tagName, $stripList ) ) {
1086 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1087 $attrText = '';
1088 foreach ( $attributes as $name => $value ) {
1089 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1090 }
1091 if ( $inner === null ) {
1092 return "<$tagName$attrText/>";
1093 }
1094 return "<$tagName$attrText>$inner</$tagName>";
1095 }
1096
1097 $params = [
1098 'name' => $tagName,
1099 'inner' => $inner,
1100 'attributes' => $attributes,
1101 'close' => "</$tagName>",
1102 ];
1103 return $parser->extensionSubstitution( $params, $frame );
1104 }
1105
1106 /**
1107 * Fetched the current revision of the given title and return this.
1108 * Will increment the expensive function count and
1109 * add a template link to get the value refreshed on changes.
1110 * For a given title, which is equal to the current parser title,
1111 * the revision object from the parser is used, when that is the current one
1112 *
1113 * @param Parser $parser
1114 * @param Title $title
1115 * @return Revision
1116 * @since 1.23
1117 */
1118 private static function getCachedRevisionObject( $parser, $title = null ) {
1119 if ( is_null( $title ) ) {
1120 return null;
1121 }
1122
1123 // Use the revision from the parser itself, when param is the current page
1124 // and the revision is the current one
1125 if ( $title->equals( $parser->getTitle() ) ) {
1126 $parserRev = $parser->getRevisionObject();
1127 if ( $parserRev && $parserRev->isCurrent() ) {
1128 // force reparse after edit with vary-revision flag
1129 $parser->getOutput()->setFlag( 'vary-revision' );
1130 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
1131 return $parserRev;
1132 }
1133 }
1134
1135 // Normalize name for cache
1136 $page = $title->getPrefixedDBkey();
1137
1138 if ( !( $parser->currentRevisionCache && $parser->currentRevisionCache->has( $page ) )
1139 && !$parser->incrementExpensiveFunctionCount() ) {
1140 return null;
1141 }
1142 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1143 $pageID = $rev ? $rev->getPage() : 0;
1144 $revID = $rev ? $rev->getId() : 0;
1145
1146 // Register dependency in templatelinks
1147 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1148
1149 return $rev;
1150 }
1151
1152 /**
1153 * Get the pageid of a specified page
1154 * @param Parser $parser
1155 * @param string|null $title Title to get the pageid from
1156 * @return int|null|string
1157 * @since 1.23
1158 */
1159 public static function pageid( $parser, $title = null ) {
1160 $t = Title::newFromText( $title );
1161 if ( is_null( $t ) ) {
1162 return '';
1163 }
1164 // Use title from parser to have correct pageid after edit
1165 if ( $t->equals( $parser->getTitle() ) ) {
1166 $t = $parser->getTitle();
1167 return $t->getArticleID();
1168 }
1169
1170 // These can't have ids
1171 if ( !$t->canExist() || $t->isExternal() ) {
1172 return 0;
1173 }
1174
1175 // Check the link cache, maybe something already looked it up.
1176 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1177 $pdbk = $t->getPrefixedDBkey();
1178 $id = $linkCache->getGoodLinkID( $pdbk );
1179 if ( $id != 0 ) {
1180 $parser->mOutput->addLink( $t, $id );
1181 return $id;
1182 }
1183 if ( $linkCache->isBadLink( $pdbk ) ) {
1184 $parser->mOutput->addLink( $t, 0 );
1185 return $id;
1186 }
1187
1188 // We need to load it from the DB, so mark expensive
1189 if ( $parser->incrementExpensiveFunctionCount() ) {
1190 $id = $t->getArticleID();
1191 $parser->mOutput->addLink( $t, $id );
1192 return $id;
1193 }
1194 return null;
1195 }
1196
1197 /**
1198 * Get the id from the last revision of a specified page.
1199 * @param Parser $parser
1200 * @param string|null $title Title to get the id from
1201 * @return int|null|string
1202 * @since 1.23
1203 */
1204 public static function revisionid( $parser, $title = null ) {
1205 $t = Title::newFromText( $title );
1206 if ( is_null( $t ) ) {
1207 return '';
1208 }
1209 // fetch revision from cache/database and return the value
1210 $rev = self::getCachedRevisionObject( $parser, $t );
1211 return $rev ? $rev->getId() : '';
1212 }
1213
1214 /**
1215 * Get the day from the last revision of a specified page.
1216 * @param Parser $parser
1217 * @param string|null $title Title to get the day from
1218 * @return string
1219 * @since 1.23
1220 */
1221 public static function revisionday( $parser, $title = null ) {
1222 $t = Title::newFromText( $title );
1223 if ( is_null( $t ) ) {
1224 return '';
1225 }
1226 // fetch revision from cache/database and return the value
1227 $rev = self::getCachedRevisionObject( $parser, $t );
1228 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1229 }
1230
1231 /**
1232 * Get the day with leading zeros from the last revision of a specified page.
1233 * @param Parser $parser
1234 * @param string|null $title Title to get the day from
1235 * @return string
1236 * @since 1.23
1237 */
1238 public static function revisionday2( $parser, $title = null ) {
1239 $t = Title::newFromText( $title );
1240 if ( is_null( $t ) ) {
1241 return '';
1242 }
1243 // fetch revision from cache/database and return the value
1244 $rev = self::getCachedRevisionObject( $parser, $t );
1245 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1246 }
1247
1248 /**
1249 * Get the month with leading zeros from the last revision of a specified page.
1250 * @param Parser $parser
1251 * @param string|null $title Title to get the month from
1252 * @return string
1253 * @since 1.23
1254 */
1255 public static function revisionmonth( $parser, $title = null ) {
1256 $t = Title::newFromText( $title );
1257 if ( is_null( $t ) ) {
1258 return '';
1259 }
1260 // fetch revision from cache/database and return the value
1261 $rev = self::getCachedRevisionObject( $parser, $t );
1262 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1263 }
1264
1265 /**
1266 * Get the month from the last revision of a specified page.
1267 * @param Parser $parser
1268 * @param string|null $title Title to get the month from
1269 * @return string
1270 * @since 1.23
1271 */
1272 public static function revisionmonth1( $parser, $title = null ) {
1273 $t = Title::newFromText( $title );
1274 if ( is_null( $t ) ) {
1275 return '';
1276 }
1277 // fetch revision from cache/database and return the value
1278 $rev = self::getCachedRevisionObject( $parser, $t );
1279 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1280 }
1281
1282 /**
1283 * Get the year from the last revision of a specified page.
1284 * @param Parser $parser
1285 * @param string|null $title Title to get the year from
1286 * @return string
1287 * @since 1.23
1288 */
1289 public static function revisionyear( $parser, $title = null ) {
1290 $t = Title::newFromText( $title );
1291 if ( is_null( $t ) ) {
1292 return '';
1293 }
1294 // fetch revision from cache/database and return the value
1295 $rev = self::getCachedRevisionObject( $parser, $t );
1296 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1297 }
1298
1299 /**
1300 * Get the timestamp from the last revision of a specified page.
1301 * @param Parser $parser
1302 * @param string|null $title Title to get the timestamp from
1303 * @return string
1304 * @since 1.23
1305 */
1306 public static function revisiontimestamp( $parser, $title = null ) {
1307 $t = Title::newFromText( $title );
1308 if ( is_null( $t ) ) {
1309 return '';
1310 }
1311 // fetch revision from cache/database and return the value
1312 $rev = self::getCachedRevisionObject( $parser, $t );
1313 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1314 }
1315
1316 /**
1317 * Get the user from the last revision of a specified page.
1318 * @param Parser $parser
1319 * @param string|null $title Title to get the user from
1320 * @return string
1321 * @since 1.23
1322 */
1323 public static function revisionuser( $parser, $title = null ) {
1324 $t = Title::newFromText( $title );
1325 if ( is_null( $t ) ) {
1326 return '';
1327 }
1328 // fetch revision from cache/database and return the value
1329 $rev = self::getCachedRevisionObject( $parser, $t );
1330 return $rev ? $rev->getUserText() : '';
1331 }
1332
1333 /**
1334 * Returns the sources of any cascading protection acting on a specified page.
1335 * Pages will not return their own title unless they transclude themselves.
1336 * This is an expensive parser function and can't be called too many times per page,
1337 * unless cascading protection sources for the page have already been loaded.
1338 *
1339 * @param Parser $parser
1340 * @param string $title
1341 *
1342 * @return string
1343 * @since 1.23
1344 */
1345 public static function cascadingsources( $parser, $title = '' ) {
1346 $titleObject = Title::newFromText( $title );
1347 if ( !( $titleObject instanceof Title ) ) {
1348 $titleObject = $parser->mTitle;
1349 }
1350 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1351 || $parser->incrementExpensiveFunctionCount()
1352 ) {
1353 $names = [];
1354 $sources = $titleObject->getCascadeProtectionSources();
1355 foreach ( $sources[0] as $sourceTitle ) {
1356 $names[] = $sourceTitle->getPrefixedText();
1357 }
1358 return implode( '|', $names );
1359 }
1360 return '';
1361 }
1362
1363 }