3 * Parser functions provided by MediaWiki core
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.
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.
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
23 use MediaWiki\MediaWikiServices
;
26 * Various core parser functions, registered in Parser::firstCallInit()
29 class CoreParserFunctions
{
31 * @param Parser $parser
34 public static function register( $parser ) {
35 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
37 # Syntax for arguments (see Parser::setFunctionHook):
38 # "name for lookup in localized magic words array",
40 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
41 # instead of {{#int:...}})
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',
60 foreach ( $noHashFunctions as $func ) {
61 $parser->setFunctionHook( $func, [ __CLASS__
, $func ], Parser
::SFH_NO_HASH
);
64 $parser->setFunctionHook(
66 [ __CLASS__
, 'mwnamespace' ],
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' ] );
75 if ( $wgAllowDisplayTitle ) {
76 $parser->setFunctionHook(
78 [ __CLASS__
, 'displaytitle' ],
82 if ( $wgAllowSlowParserFunctions ) {
83 $parser->setFunctionHook(
85 [ __CLASS__
, 'pagesinnamespace' ],
92 * @param Parser $parser
93 * @param string $part1
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();
106 return [ $message->plain(), 'noparse' => false ];
108 return [ 'found' => false ];
113 * @param Parser $parser
114 * @param string $date
115 * @param string|null $defaultPref
119 public static function formatDate( $parser, $date, $defaultPref = null ) {
120 $lang = $parser->getFunctionLang();
121 $df = DateFormatter
::getInstance( $lang );
123 $date = trim( $date );
125 $pref = $parser->getOptions()->getDateFormat();
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;
133 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
137 public static function ns( $parser, $part1 = '' ) {
138 if ( intval( $part1 ) ||
$part1 == "0" ) {
139 $index = intval( $part1 );
141 $index = $parser->getContentLanguage()->getNsIndex( str_replace( ' ', '_', $part1 ) );
143 if ( $index !== false ) {
144 return $parser->getContentLanguage()->getFormattedNsText( $index );
146 return [ 'found' => false ];
150 public static function nse( $parser, $part1 = '' ) {
151 $ret = self
::ns( $parser, $part1 );
152 if ( is_string( $ret ) ) {
153 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
159 * urlencodes a string according to one of three patterns: (T24474)
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 '_',
165 * @param Parser $parser
166 * @param string $s The text to encode.
167 * @param string|null $arg (optional): The type of encoding.
170 public static function urlencode( $parser, $s = '', $arg = null ) {
171 static $magicWords = null;
172 if ( is_null( $magicWords ) ) {
174 $parser->getMagicWordFactory()->newArray( [ 'url_path', 'url_query', 'url_wiki' ] );
176 switch ( $magicWords->matchStartToEnd( $arg ) ) {
177 // Encode as though it's a wiki page, '_' for ' '.
179 $func = 'wfUrlencode';
180 $s = str_replace( ' ', '_', $s );
183 // Encode for an HTTP Path, '%20' for ' '.
185 $func = 'rawurlencode';
188 // Encode for HTTP query, '+' for ' '.
193 // See T105242, where the choice to kill markers and various
194 // other options were discussed.
195 return $func( $parser->killMarkers( $s ) );
198 public static function lcfirst( $parser, $s = '' ) {
199 return $parser->getContentLanguage()->lcfirst( $s );
202 public static function ucfirst( $parser, $s = '' ) {
203 return $parser->getContentLanguage()->ucfirst( $s );
207 * @param Parser $parser
211 public static function lc( $parser, $s = '' ) {
212 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'lc' ] );
216 * @param Parser $parser
220 public static function uc( $parser, $s = '' ) {
221 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'uc' ] );
224 public static function localurl( $parser, $s = '', $arg = null ) {
225 return self
::urlFunction( 'getLocalURL', $s, $arg );
228 public static function localurle( $parser, $s = '', $arg = null ) {
229 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
230 if ( !is_string( $temp ) ) {
233 return htmlspecialchars( $temp );
237 public static function fullurl( $parser, $s = '', $arg = null ) {
238 return self
::urlFunction( 'getFullURL', $s, $arg );
241 public static function fullurle( $parser, $s = '', $arg = null ) {
242 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
243 if ( !is_string( $temp ) ) {
246 return htmlspecialchars( $temp );
250 public static function canonicalurl( $parser, $s = '', $arg = null ) {
251 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
254 public static function canonicalurle( $parser, $s = '', $arg = null ) {
255 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
256 if ( !is_string( $temp ) ) {
259 return htmlspecialchars( $temp );
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 ) );
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() );
277 if ( !is_null( $arg ) ) {
278 $text = $title->$func( $arg );
280 $text = $title->$func();
284 return [ 'found' => false ];
289 * @param Parser $parser
291 * @param string|null $arg
294 public static function formatnum( $parser, $num = '', $arg = null ) {
295 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg ) ) {
296 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
298 self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'nocommafysuffix', $arg )
300 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
302 $func = [ $parser->getFunctionLang(), 'formatNum' ];
304 return $parser->markerSkipCallback( $num, $func );
308 * @param Parser $parser
309 * @param string $case
310 * @param string $word
313 public static function grammar( $parser, $case = '', $word = '' ) {
314 $word = $parser->killMarkers( $word );
315 return $parser->getFunctionLang()->convertGrammar( $word, $case );
319 * @param Parser $parser
320 * @param string $username
323 public static function gender( $parser, $username ) {
324 $forms = array_slice( func_get_args(), 2 );
326 // Some shortcuts to avoid loading user data unnecessarily
327 if ( count( $forms ) === 0 ) {
329 } elseif ( count( $forms ) === 1 ) {
333 $username = trim( $username );
336 $gender = User
::getDefaultOption( 'gender' );
338 // allow prefix and normalize (e.g. "*foo" -> "*foo" ).
339 $title = Title
::newFromText( $username, NS_USER
);
341 if ( $title && $title->inNamespace( NS_USER
) ) {
342 $username = $title->getText();
345 // check parameter, or use the ParserOptions if in interface message
346 $user = User
::newFromName( $username );
347 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
349 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
350 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
351 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
353 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
358 * @param Parser $parser
359 * @param string $text
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 );
370 * @param Parser $parser
371 * @param string $text
374 public static function bidi( $parser, $text = '' ) {
375 return $parser->getFunctionLang()->embedBidi( $text );
379 * Override the title of the page when viewed, provided we've been given a
380 * title which will normalise to the canonical title
382 * @param Parser $parser Parent parser
383 * @param string $text Desired title text
384 * @param string $uarg
387 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
388 global $wgRestrictDisplayTitle;
390 static $magicWords = null;
391 if ( is_null( $magicWords ) ) {
392 $magicWords = $parser->getMagicWordFactory()->newArray(
393 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
395 $arg = $magicWords->matchStartToEnd( $uarg );
397 // parse a limited subset of wiki markup (just the single quote items)
398 $text = $parser->doQuotes( $text );
400 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
401 $text = $parser->killMarkers( $text );
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' ];
408 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
409 if ( $wgRestrictDisplayTitle ) {
410 $htmlTagsCallback = function ( &$params ) {
411 $decoded = Sanitizer
::decodeTagAttributes( $params );
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'] );
418 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
419 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
423 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
426 $htmlTagsCallback = null;
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(
439 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
441 if ( !$wgRestrictDisplayTitle ||
442 ( $title instanceof Title
443 && !$title->hasFragment()
444 && $title->equals( $parser->mTitle
) )
446 $old = $parser->mOutput
->getProperty( 'displaytitle' );
447 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
448 $parser->mOutput
->setDisplayTitle( $text );
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() .
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 ) )
470 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
475 * Matches the given value against the value of given magic word
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
483 private static function matchAgainstMagicword(
484 MagicWordFactory
$magicWordFactory, $magicword, $value
486 $value = trim( strval( $value ) );
487 if ( $value === '' ) {
490 $mwObject = $magicWordFactory->get( $magicword );
491 return $mwObject->matchStartToEnd( $value );
495 * Formats a number according to a language.
497 * @param int|float $num
499 * @param Language|StubUserLang $language
500 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
503 public static function formatRaw(
504 $num, $raw, $language, MagicWordFactory
$magicWordFactory = null
506 if ( $raw !== null && !$magicWordFactory ) {
507 $magicWordFactory = MediaWikiServices
::getInstance()->getMagicWordFactory();
510 $raw !== null && self
::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw )
514 return $language->formatNum( $num );
518 public static function numberofpages( $parser, $raw = null ) {
519 return self
::formatRaw( SiteStats
::pages(), $raw, $parser->getFunctionLang() );
522 public static function numberofusers( $parser, $raw = null ) {
523 return self
::formatRaw( SiteStats
::users(), $raw, $parser->getFunctionLang() );
525 public static function numberofactiveusers( $parser, $raw = null ) {
526 return self
::formatRaw( SiteStats
::activeUsers(), $raw, $parser->getFunctionLang() );
529 public static function numberofarticles( $parser, $raw = null ) {
530 return self
::formatRaw( SiteStats
::articles(), $raw, $parser->getFunctionLang() );
533 public static function numberoffiles( $parser, $raw = null ) {
534 return self
::formatRaw( SiteStats
::images(), $raw, $parser->getFunctionLang() );
537 public static function numberofadmins( $parser, $raw = null ) {
538 return self
::formatRaw(
539 SiteStats
::numberingroup( 'sysop' ),
541 $parser->getFunctionLang()
545 public static function numberofedits( $parser, $raw = null ) {
546 return self
::formatRaw( SiteStats
::edits(), $raw, $parser->getFunctionLang() );
549 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
550 return self
::formatRaw(
551 SiteStats
::pagesInNs( intval( $namespace ) ),
553 $parser->getFunctionLang()
556 public static function numberingroup( $parser, $name = '', $raw = null ) {
557 return self
::formatRaw(
558 SiteStats
::numberingroup( strtolower( $name ) ),
560 $parser->getFunctionLang()
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
573 public static function mwnamespace( $parser, $title = null ) {
574 $t = Title
::newFromText( $title );
575 if ( is_null( $t ) ) {
578 return str_replace( '_', ' ', $t->getNsText() );
580 public static function namespacee( $parser, $title = null ) {
581 $t = Title
::newFromText( $title );
582 if ( is_null( $t ) ) {
585 return wfUrlencode( $t->getNsText() );
587 public static function namespacenumber( $parser, $title = null ) {
588 $t = Title
::newFromText( $title );
589 if ( is_null( $t ) ) {
592 return $t->getNamespace();
594 public static function talkspace( $parser, $title = null ) {
595 $t = Title
::newFromText( $title );
596 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
599 return str_replace( '_', ' ', $t->getTalkNsText() );
601 public static function talkspacee( $parser, $title = null ) {
602 $t = Title
::newFromText( $title );
603 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
606 return wfUrlencode( $t->getTalkNsText() );
608 public static function subjectspace( $parser, $title = null ) {
609 $t = Title
::newFromText( $title );
610 if ( is_null( $t ) ) {
613 return str_replace( '_', ' ', $t->getSubjectNsText() );
615 public static function subjectspacee( $parser, $title = null ) {
616 $t = Title
::newFromText( $title );
617 if ( is_null( $t ) ) {
620 return wfUrlencode( $t->getSubjectNsText() );
624 * Functions to get and normalize pagenames, corresponding to the magic words
626 * @param Parser $parser
627 * @param string|null $title
630 public static function pagename( $parser, $title = null ) {
631 $t = Title
::newFromText( $title );
632 if ( is_null( $t ) ) {
635 return wfEscapeWikiText( $t->getText() );
637 public static function pagenamee( $parser, $title = null ) {
638 $t = Title
::newFromText( $title );
639 if ( is_null( $t ) ) {
642 return wfEscapeWikiText( $t->getPartialURL() );
644 public static function fullpagename( $parser, $title = null ) {
645 $t = Title
::newFromText( $title );
646 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
649 return wfEscapeWikiText( $t->getPrefixedText() );
651 public static function fullpagenamee( $parser, $title = null ) {
652 $t = Title
::newFromText( $title );
653 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
656 return wfEscapeWikiText( $t->getPrefixedURL() );
658 public static function subpagename( $parser, $title = null ) {
659 $t = Title
::newFromText( $title );
660 if ( is_null( $t ) ) {
663 return wfEscapeWikiText( $t->getSubpageText() );
665 public static function subpagenamee( $parser, $title = null ) {
666 $t = Title
::newFromText( $title );
667 if ( is_null( $t ) ) {
670 return wfEscapeWikiText( $t->getSubpageUrlForm() );
672 public static function rootpagename( $parser, $title = null ) {
673 $t = Title
::newFromText( $title );
674 if ( is_null( $t ) ) {
677 return wfEscapeWikiText( $t->getRootText() );
679 public static function rootpagenamee( $parser, $title = null ) {
680 $t = Title
::newFromText( $title );
681 if ( is_null( $t ) ) {
684 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
686 public static function basepagename( $parser, $title = null ) {
687 $t = Title
::newFromText( $title );
688 if ( is_null( $t ) ) {
691 return wfEscapeWikiText( $t->getBaseText() );
693 public static function basepagenamee( $parser, $title = null ) {
694 $t = Title
::newFromText( $title );
695 if ( is_null( $t ) ) {
698 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
700 public static function talkpagename( $parser, $title = null ) {
701 $t = Title
::newFromText( $title );
702 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
705 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
707 public static function talkpagenamee( $parser, $title = null ) {
708 $t = Title
::newFromText( $title );
709 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
712 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
714 public static function subjectpagename( $parser, $title = null ) {
715 $t = Title
::newFromText( $title );
716 if ( is_null( $t ) ) {
719 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
721 public static function subjectpagenamee( $parser, $title = null ) {
722 $t = Title
::newFromText( $title );
723 if ( is_null( $t ) ) {
726 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
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
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'
751 // split the given option to its variable
752 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
753 // {{pagesincategory:|raw[|type]}}
755 $type = $magicWords->matchStartToEnd( $arg2 );
757 // {{pagesincategory:[|type[|raw]]}}
758 $type = $magicWords->matchStartToEnd( $arg1 );
761 if ( !$type ) { // backward compatibility
762 $type = 'pagesincategory_all';
765 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
766 if ( !$title ) { # invalid title
767 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
769 $parser->getContentLanguage()->findVariantLink( $name, $title, true );
771 // Normalize name for cache
772 $name = $title->getDBkey();
774 if ( !isset( $cache[$name] ) ) {
775 $category = Category
::newFromTitle( $title );
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;
786 $cache[$name]['pagesincategory_all'] = $allCount;
787 $cache[$name]['pagesincategory_pages'] = $pagesCount;
788 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
789 $cache[$name]['pagesincategory_files'] = $fileCount;
792 $count = $cache[$name][$type];
793 return self
::formatRaw( $count, $raw, $parser->getFunctionLang() );
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.
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
805 public static function pagesize( $parser, $page = '', $raw = null ) {
806 $title = Title
::newFromText( $page );
808 if ( !is_object( $title ) ) {
809 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
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
819 return self
::formatRaw( $length, $raw, $parser->getFunctionLang() );
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
828 * @param Parser $parser
829 * @param string $type
830 * @param string $title
834 public static function protectionlevel( $parser, $type = '', $title = '' ) {
835 $titleObject = Title
::newFromText( $title );
836 if ( !( $titleObject instanceof Title
) ) {
837 $titleObject = $parser->mTitle
;
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 );
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
854 * @param Parser $parser
855 * @param string $type
856 * @param string $title
860 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
861 $titleObject = Title
::newFromText( $title );
862 if ( !( $titleObject instanceof Title
) ) {
863 $titleObject = $parser->mTitle
;
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 ) {
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)
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 );
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
900 public static function pad(
901 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
903 $padding = $parser->killMarkers( $padding );
904 $lengthOfPadding = mb_strlen( $padding );
905 if ( $lengthOfPadding == 0 ) {
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 ) {
916 # $finalPadding is just $padding repeated enough times so that
917 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
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;
926 if ( $direction == STR_PAD_LEFT
) {
927 return $finalPadding . $string;
929 return $string . $finalPadding;
933 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
934 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
937 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
938 return self
::pad( $parser, $string, $length, $padding );
942 * @param Parser $parser
943 * @param string $text
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 );
952 public static function special( $parser, $text ) {
953 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
955 $title = SpecialPage
::getTitleFor( $page, $subpage );
956 return $title->getPrefixedText();
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' );
964 public static function speciale( $parser, $text ) {
965 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
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.
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' ] );
982 $arg = $magicWords->matchStartToEnd( $uarg );
984 $text = trim( $text );
985 if ( strlen( $text ) == 0 ) {
988 $old = $parser->getCustomDefaultSort();
989 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
990 $parser->setDefaultSort( $text );
993 if ( $old === false ||
$old == $text ||
$arg ) {
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() .
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}}.
1012 * @param Parser $parser
1013 * @param string $name
1014 * @param string $argA
1015 * @param string $argB
1016 * @return array|string
1018 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1019 $file = wfFindFile( $name );
1021 if ( $argA == 'nowiki' ) {
1022 // {{filepath: | option [| size] }}
1024 $parsedWidthParam = Parser
::parseWidthParam( $argB );
1026 // {{filepath: [| size [|option]] }}
1027 $parsedWidthParam = Parser
::parseWidthParam( $argA );
1028 $isNowiki = ( $argB == 'nowiki' );
1032 $url = $file->getFullUrl();
1034 // If a size is requested...
1035 if ( count( $parsedWidthParam ) ) {
1036 $mto = $file->transform( $parsedWidthParam );
1038 if ( $mto && !$mto->isError() ) {
1039 // ... change the URL to point to a thumbnail.
1040 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1044 return [ $url, 'nowiki' => true ];
1053 * Parser function to extension tag adaptor
1054 * @param Parser $parser
1055 * @param PPFrame $frame
1056 * @param PPNode[] $args
1059 public static function tagObj( $parser, $frame, $args ) {
1060 if ( !count( $args ) ) {
1063 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1065 if ( count( $args ) ) {
1066 $inner = $frame->expand( array_shift( $args ) );
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] ??
'';
1080 $attributes[$name] = $value;
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
1088 foreach ( $attributes as $name => $value ) {
1089 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1091 if ( $inner === null ) {
1092 return "<$tagName$attrText/>";
1094 return "<$tagName$attrText>$inner</$tagName>";
1100 'attributes' => $attributes,
1101 'close' => "</$tagName>",
1103 return $parser->extensionSubstitution( $params, $frame );
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
1113 * @param Parser $parser
1114 * @param Title $title
1118 private static function getCachedRevisionObject( $parser, $title = null ) {
1119 if ( is_null( $title ) ) {
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" );
1135 // Normalize name for cache
1136 $page = $title->getPrefixedDBkey();
1138 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1139 && !$parser->incrementExpensiveFunctionCount() ) {
1142 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1143 $pageID = $rev ?
$rev->getPage() : 0;
1144 $revID = $rev ?
$rev->getId() : 0;
1146 // Register dependency in templatelinks
1147 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
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
1159 public static function pageid( $parser, $title = null ) {
1160 $t = Title
::newFromText( $title );
1161 if ( is_null( $t ) ) {
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();
1170 // These can't have ids
1171 if ( !$t->canExist() ||
$t->isExternal() ) {
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 );
1180 $parser->mOutput
->addLink( $t, $id );
1183 if ( $linkCache->isBadLink( $pdbk ) ) {
1184 $parser->mOutput
->addLink( $t, 0 );
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 );
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
1204 public static function revisionid( $parser, $title = null ) {
1205 $t = Title
::newFromText( $title );
1206 if ( is_null( $t ) ) {
1209 // fetch revision from cache/database and return the value
1210 $rev = self
::getCachedRevisionObject( $parser, $t );
1211 return $rev ?
$rev->getId() : '';
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
1221 public static function revisionday( $parser, $title = null ) {
1222 $t = Title
::newFromText( $title );
1223 if ( is_null( $t ) ) {
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' ) : '';
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
1238 public static function revisionday2( $parser, $title = null ) {
1239 $t = Title
::newFromText( $title );
1240 if ( is_null( $t ) ) {
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' ) : '';
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
1255 public static function revisionmonth( $parser, $title = null ) {
1256 $t = Title
::newFromText( $title );
1257 if ( is_null( $t ) ) {
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' ) : '';
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
1272 public static function revisionmonth1( $parser, $title = null ) {
1273 $t = Title
::newFromText( $title );
1274 if ( is_null( $t ) ) {
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' ) : '';
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
1289 public static function revisionyear( $parser, $title = null ) {
1290 $t = Title
::newFromText( $title );
1291 if ( is_null( $t ) ) {
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' ) : '';
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
1306 public static function revisiontimestamp( $parser, $title = null ) {
1307 $t = Title
::newFromText( $title );
1308 if ( is_null( $t ) ) {
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' ) : '';
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
1323 public static function revisionuser( $parser, $title = null ) {
1324 $t = Title
::newFromText( $title );
1325 if ( is_null( $t ) ) {
1328 // fetch revision from cache/database and return the value
1329 $rev = self
::getCachedRevisionObject( $parser, $t );
1330 return $rev ?
$rev->getUserText() : '';
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.
1339 * @param Parser $parser
1340 * @param string $title
1345 public static function cascadingsources( $parser, $title = '' ) {
1346 $titleObject = Title
::newFromText( $title );
1347 if ( !( $titleObject instanceof Title
) ) {
1348 $titleObject = $parser->mTitle
;
1350 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1351 ||
$parser->incrementExpensiveFunctionCount()
1354 $sources = $titleObject->getCascadeProtectionSources();
1355 foreach ( $sources[0] as $sourceTitle ) {
1356 $names[] = $sourceTitle->getPrefixedText();
1358 return implode( '|', $names );