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 Message key
94 * @param mixed ...$params To pass to wfMessage()
97 public static function intFunction( $parser, $part1 = '', ...$params ) {
98 if ( strval( $part1 ) !== '' ) {
99 $message = wfMessage( $part1, $params )
100 ->inLanguage( $parser->getOptions()->getUserLangObj() );
101 return [ $message->plain(), 'noparse' => false ];
103 return [ 'found' => false ];
108 * @param Parser $parser
109 * @param string $date
110 * @param string|null $defaultPref
114 public static function formatDate( $parser, $date, $defaultPref = null ) {
115 $lang = $parser->getFunctionLang();
116 $df = MediaWikiServices
::getInstance()->getDateFormatterFactory()->get( $lang );
118 $date = trim( $date );
120 $pref = $parser->getOptions()->getDateFormat();
122 // Specify a different default date format other than the normal default
123 // if the user has 'default' for their setting
124 if ( $pref == 'default' && $defaultPref ) {
125 $pref = $defaultPref;
128 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
132 public static function ns( $parser, $part1 = '' ) {
133 if ( intval( $part1 ) ||
$part1 == "0" ) {
134 $index = intval( $part1 );
136 $index = $parser->getContentLanguage()->getNsIndex( str_replace( ' ', '_', $part1 ) );
138 if ( $index !== false ) {
139 return $parser->getContentLanguage()->getFormattedNsText( $index );
141 return [ 'found' => false ];
145 public static function nse( $parser, $part1 = '' ) {
146 $ret = self
::ns( $parser, $part1 );
147 if ( is_string( $ret ) ) {
148 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
154 * urlencodes a string according to one of three patterns: (T24474)
156 * By default (for HTTP "query" strings), spaces are encoded as '+'.
157 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
158 * For links to "wiki"s, or similar software, spaces are encoded as '_',
160 * @param Parser $parser
161 * @param string $s The text to encode.
162 * @param string|null $arg (optional): The type of encoding.
165 public static function urlencode( $parser, $s = '', $arg = null ) {
166 static $magicWords = null;
167 if ( is_null( $magicWords ) ) {
169 $parser->getMagicWordFactory()->newArray( [ 'url_path', 'url_query', 'url_wiki' ] );
171 switch ( $magicWords->matchStartToEnd( $arg ) ) {
172 // Encode as though it's a wiki page, '_' for ' '.
174 $func = 'wfUrlencode';
175 $s = str_replace( ' ', '_', $s );
178 // Encode for an HTTP Path, '%20' for ' '.
180 $func = 'rawurlencode';
183 // Encode for HTTP query, '+' for ' '.
188 // See T105242, where the choice to kill markers and various
189 // other options were discussed.
190 return $func( $parser->killMarkers( $s ) );
193 public static function lcfirst( $parser, $s = '' ) {
194 return $parser->getContentLanguage()->lcfirst( $s );
197 public static function ucfirst( $parser, $s = '' ) {
198 return $parser->getContentLanguage()->ucfirst( $s );
202 * @param Parser $parser
206 public static function lc( $parser, $s = '' ) {
207 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'lc' ] );
211 * @param Parser $parser
215 public static function uc( $parser, $s = '' ) {
216 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'uc' ] );
219 public static function localurl( $parser, $s = '', $arg = null ) {
220 return self
::urlFunction( 'getLocalURL', $s, $arg );
223 public static function localurle( $parser, $s = '', $arg = null ) {
224 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
225 if ( !is_string( $temp ) ) {
228 return htmlspecialchars( $temp );
232 public static function fullurl( $parser, $s = '', $arg = null ) {
233 return self
::urlFunction( 'getFullURL', $s, $arg );
236 public static function fullurle( $parser, $s = '', $arg = null ) {
237 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
238 if ( !is_string( $temp ) ) {
241 return htmlspecialchars( $temp );
245 public static function canonicalurl( $parser, $s = '', $arg = null ) {
246 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
249 public static function canonicalurle( $parser, $s = '', $arg = null ) {
250 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
251 if ( !is_string( $temp ) ) {
254 return htmlspecialchars( $temp );
258 public static function urlFunction( $func, $s = '', $arg = null ) {
259 $title = Title
::newFromText( $s );
260 # Due to order of execution of a lot of bits, the values might be encoded
261 # before arriving here; if that's true, then the title can't be created
262 # and the variable will fail. If we can't get a decent title from the first
263 # attempt, url-decode and try for a second.
264 if ( is_null( $title ) ) {
265 $title = Title
::newFromURL( urldecode( $s ) );
267 if ( !is_null( $title ) ) {
268 # Convert NS_MEDIA -> NS_FILE
269 if ( $title->inNamespace( NS_MEDIA
) ) {
270 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
272 if ( !is_null( $arg ) ) {
273 $text = $title->$func( $arg );
275 $text = $title->$func();
279 return [ 'found' => false ];
284 * @param Parser $parser
286 * @param string|null $arg
289 public static function formatnum( $parser, $num = '', $arg = null ) {
290 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg ) ) {
291 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
293 self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'nocommafysuffix', $arg )
295 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
297 $func = [ $parser->getFunctionLang(), 'formatNum' ];
299 return $parser->markerSkipCallback( $num, $func );
303 * @param Parser $parser
304 * @param string $case
305 * @param string $word
308 public static function grammar( $parser, $case = '', $word = '' ) {
309 $word = $parser->killMarkers( $word );
310 return $parser->getFunctionLang()->convertGrammar( $word, $case );
314 * @param Parser $parser
315 * @param string $username
316 * @param string ...$forms What to output for each gender
319 public static function gender( $parser, $username, ...$forms ) {
320 // Some shortcuts to avoid loading user data unnecessarily
321 if ( count( $forms ) === 0 ) {
323 } elseif ( count( $forms ) === 1 ) {
327 $username = trim( $username );
329 $gender = User
::getDefaultOption( 'gender' );
331 // allow prefix and normalize (e.g. "*foo" -> "*foo" ).
332 $title = Title
::newFromText( $username, NS_USER
);
334 if ( $title && $title->inNamespace( NS_USER
) ) {
335 $username = $title->getText();
338 // check parameter, or use the ParserOptions if in interface message
339 $user = User
::newFromName( $username );
340 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
342 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
343 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
344 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
346 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
351 * @param Parser $parser
352 * @param string $text
353 * @param string ...$forms What to output for each number (singular, dual, plural, etc.)
356 public static function plural( $parser, $text = '', ...$forms ) {
357 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
358 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
359 return $parser->getFunctionLang()->convertPlural( $text, $forms );
363 * @param Parser $parser
364 * @param string $text
367 public static function bidi( $parser, $text = '' ) {
368 return $parser->getFunctionLang()->embedBidi( $text );
372 * Override the title of the page when viewed, provided we've been given a
373 * title which will normalise to the canonical title
375 * @param Parser $parser Parent parser
376 * @param string $text Desired title text
377 * @param string $uarg
380 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
381 global $wgRestrictDisplayTitle;
383 static $magicWords = null;
384 if ( is_null( $magicWords ) ) {
385 $magicWords = $parser->getMagicWordFactory()->newArray(
386 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
388 $arg = $magicWords->matchStartToEnd( $uarg );
390 // parse a limited subset of wiki markup (just the single quote items)
391 $text = $parser->doQuotes( $text );
393 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
394 $text = $parser->killMarkers( $text );
396 // list of disallowed tags for DISPLAYTITLE
397 // these will be escaped even though they are allowed in normal wiki text
398 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
399 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
401 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
402 if ( $wgRestrictDisplayTitle ) {
403 $htmlTagsCallback = function ( &$params ) {
404 $decoded = Sanitizer
::decodeTagAttributes( $params );
406 if ( isset( $decoded['style'] ) ) {
407 // this is called later anyway, but we need it right now for the regexes below to be safe
408 // calling it twice doesn't hurt
409 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
411 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
412 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
416 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
419 $htmlTagsCallback = null;
422 // only requested titles that normalize to the actual title are allowed through
423 // if $wgRestrictDisplayTitle is true (it is by default)
424 // mimic the escaping process that occurs in OutputPage::setPageTitle
425 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
432 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
434 if ( !$wgRestrictDisplayTitle ||
435 ( $title instanceof Title
436 && !$title->hasFragment()
437 && $title->equals( $parser->mTitle
) )
439 $old = $parser->mOutput
->getProperty( 'displaytitle' );
440 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
441 $parser->mOutput
->setDisplayTitle( $text );
443 if ( $old !== false && $old !== $text && !$arg ) {
444 $converter = $parser->getTargetLanguage()->getConverter();
445 return '<span class="error">' .
446 wfMessage( 'duplicate-displaytitle',
447 // Message should be parsed, but these params should only be escaped.
448 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
449 $converter->markNoConversion( wfEscapeWikiText( $text ) )
450 )->inContentLanguage()->text() .
456 $parser->getOutput()->addWarning(
457 wfMessage( 'restricted-displaytitle',
458 // Message should be parsed, but this param should only be escaped.
459 wfEscapeWikiText( $text )
462 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
467 * Matches the given value against the value of given magic word
469 * @param MagicWordFactory $magicWordFactory A factory to get the word from, e.g., from
470 * $parser->getMagicWordFactory()
471 * @param string $magicword Magic word key
472 * @param string $value Value to match
473 * @return bool True on successful match
475 private static function matchAgainstMagicword(
476 MagicWordFactory
$magicWordFactory, $magicword, $value
478 $value = trim( strval( $value ) );
479 if ( $value === '' ) {
482 $mwObject = $magicWordFactory->get( $magicword );
483 return $mwObject->matchStartToEnd( $value );
487 * Formats a number according to a language.
489 * @param int|float $num
491 * @param Language|StubUserLang $language
492 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
495 public static function formatRaw(
496 $num, $raw, $language, MagicWordFactory
$magicWordFactory = null
498 if ( $raw !== null && !$magicWordFactory ) {
499 $magicWordFactory = MediaWikiServices
::getInstance()->getMagicWordFactory();
502 $raw !== null && self
::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw )
506 return $language->formatNum( $num );
510 public static function numberofpages( $parser, $raw = null ) {
511 return self
::formatRaw( SiteStats
::pages(), $raw, $parser->getFunctionLang() );
514 public static function numberofusers( $parser, $raw = null ) {
515 return self
::formatRaw( SiteStats
::users(), $raw, $parser->getFunctionLang() );
518 public static function numberofactiveusers( $parser, $raw = null ) {
519 return self
::formatRaw( SiteStats
::activeUsers(), $raw, $parser->getFunctionLang() );
522 public static function numberofarticles( $parser, $raw = null ) {
523 return self
::formatRaw( SiteStats
::articles(), $raw, $parser->getFunctionLang() );
526 public static function numberoffiles( $parser, $raw = null ) {
527 return self
::formatRaw( SiteStats
::images(), $raw, $parser->getFunctionLang() );
530 public static function numberofadmins( $parser, $raw = null ) {
531 return self
::formatRaw(
532 SiteStats
::numberingroup( 'sysop' ),
534 $parser->getFunctionLang()
538 public static function numberofedits( $parser, $raw = null ) {
539 return self
::formatRaw( SiteStats
::edits(), $raw, $parser->getFunctionLang() );
542 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
543 return self
::formatRaw(
544 SiteStats
::pagesInNs( intval( $namespace ) ),
546 $parser->getFunctionLang()
550 public static function numberingroup( $parser, $name = '', $raw = null ) {
551 return self
::formatRaw(
552 SiteStats
::numberingroup( strtolower( $name ) ),
554 $parser->getFunctionLang()
559 * Given a title, return the namespace name that would be given by the
560 * corresponding magic word
561 * Note: function name changed to "mwnamespace" rather than "namespace"
562 * to not break PHP 5.3
563 * @param Parser $parser
564 * @param string|null $title
565 * @return mixed|string
567 public static function mwnamespace( $parser, $title = null ) {
568 $t = Title
::newFromText( $title );
569 if ( is_null( $t ) ) {
572 return str_replace( '_', ' ', $t->getNsText() );
575 public static function namespacee( $parser, $title = null ) {
576 $t = Title
::newFromText( $title );
577 if ( is_null( $t ) ) {
580 return wfUrlencode( $t->getNsText() );
583 public static function namespacenumber( $parser, $title = null ) {
584 $t = Title
::newFromText( $title );
585 if ( is_null( $t ) ) {
588 return $t->getNamespace();
591 public static function talkspace( $parser, $title = null ) {
592 $t = Title
::newFromText( $title );
593 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
596 return str_replace( '_', ' ', $t->getTalkNsText() );
599 public static function talkspacee( $parser, $title = null ) {
600 $t = Title
::newFromText( $title );
601 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
604 return wfUrlencode( $t->getTalkNsText() );
607 public static function subjectspace( $parser, $title = null ) {
608 $t = Title
::newFromText( $title );
609 if ( is_null( $t ) ) {
612 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() );
638 public static function pagenamee( $parser, $title = null ) {
639 $t = Title
::newFromText( $title );
640 if ( is_null( $t ) ) {
643 return wfEscapeWikiText( $t->getPartialURL() );
646 public static function fullpagename( $parser, $title = null ) {
647 $t = Title
::newFromText( $title );
648 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
651 return wfEscapeWikiText( $t->getPrefixedText() );
654 public static function fullpagenamee( $parser, $title = null ) {
655 $t = Title
::newFromText( $title );
656 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
659 return wfEscapeWikiText( $t->getPrefixedURL() );
662 public static function subpagename( $parser, $title = null ) {
663 $t = Title
::newFromText( $title );
664 if ( is_null( $t ) ) {
667 return wfEscapeWikiText( $t->getSubpageText() );
670 public static function subpagenamee( $parser, $title = null ) {
671 $t = Title
::newFromText( $title );
672 if ( is_null( $t ) ) {
675 return wfEscapeWikiText( $t->getSubpageUrlForm() );
678 public static function rootpagename( $parser, $title = null ) {
679 $t = Title
::newFromText( $title );
680 if ( is_null( $t ) ) {
683 return wfEscapeWikiText( $t->getRootText() );
686 public static function rootpagenamee( $parser, $title = null ) {
687 $t = Title
::newFromText( $title );
688 if ( is_null( $t ) ) {
691 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
694 public static function basepagename( $parser, $title = null ) {
695 $t = Title
::newFromText( $title );
696 if ( is_null( $t ) ) {
699 return wfEscapeWikiText( $t->getBaseText() );
702 public static function basepagenamee( $parser, $title = null ) {
703 $t = Title
::newFromText( $title );
704 if ( is_null( $t ) ) {
707 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
710 public static function talkpagename( $parser, $title = null ) {
711 $t = Title
::newFromText( $title );
712 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
715 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
718 public static function talkpagenamee( $parser, $title = null ) {
719 $t = Title
::newFromText( $title );
720 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
723 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
726 public static function subjectpagename( $parser, $title = null ) {
727 $t = Title
::newFromText( $title );
728 if ( is_null( $t ) ) {
731 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
734 public static function subjectpagenamee( $parser, $title = null ) {
735 $t = Title
::newFromText( $title );
736 if ( is_null( $t ) ) {
739 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
743 * Return the number of pages, files or subcats in the given category,
744 * or 0 if it's nonexistent. This is an expensive parser function and
745 * can't be called too many times per page.
746 * @param Parser $parser
747 * @param string $name
748 * @param string|null $arg1
749 * @param string|null $arg2
752 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
753 static $magicWords = null;
754 if ( is_null( $magicWords ) ) {
755 $magicWords = $parser->getMagicWordFactory()->newArray( [
756 'pagesincategory_all',
757 'pagesincategory_pages',
758 'pagesincategory_subcats',
759 'pagesincategory_files'
764 // split the given option to its variable
765 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
766 // {{pagesincategory:|raw[|type]}}
768 $type = $magicWords->matchStartToEnd( $arg2 );
770 // {{pagesincategory:[|type[|raw]]}}
771 $type = $magicWords->matchStartToEnd( $arg1 );
774 if ( !$type ) { // backward compatibility
775 $type = 'pagesincategory_all';
778 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
779 if ( !$title ) { # invalid title
780 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
782 $parser->getContentLanguage()->findVariantLink( $name, $title, true );
784 // Normalize name for cache
785 $name = $title->getDBkey();
787 if ( !isset( $cache[$name] ) ) {
788 $category = Category
::newFromTitle( $title );
790 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
791 if ( $parser->incrementExpensiveFunctionCount() ) {
792 // $allCount is the total number of cat members,
793 // not the count of how many members are normal pages.
794 $allCount = (int)$category->getPageCount();
795 $subcatCount = (int)$category->getSubcatCount();
796 $fileCount = (int)$category->getFileCount();
797 $pagesCount = $allCount - $subcatCount - $fileCount;
799 $cache[$name]['pagesincategory_all'] = $allCount;
800 $cache[$name]['pagesincategory_pages'] = $pagesCount;
801 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
802 $cache[$name]['pagesincategory_files'] = $fileCount;
805 $count = $cache[$name][$type];
806 return self
::formatRaw( $count, $raw, $parser->getFunctionLang() );
810 * Return the size of the given page, or 0 if it's nonexistent. This is an
811 * expensive parser function and can't be called too many times per page.
813 * @param Parser $parser
814 * @param string $page Name of page to check (Default: empty string)
815 * @param string|null $raw Should number be human readable with commas or just number
818 public static function pagesize( $parser, $page = '', $raw = null ) {
819 $title = Title
::newFromText( $page );
821 if ( !is_object( $title ) ) {
822 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
825 // fetch revision from cache/database and return the value
826 $rev = self
::getCachedRevisionObject( $parser, $title );
827 $length = $rev ?
$rev->getSize() : 0;
828 if ( $length === null ) {
829 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
832 return self
::formatRaw( $length, $raw, $parser->getFunctionLang() );
836 * Returns the requested protection level for the current page. This
837 * is an expensive parser function and can't be called too many times
838 * per page, unless the protection levels/expiries for the given title
839 * have already been retrieved
841 * @param Parser $parser
842 * @param string $type
843 * @param string $title
847 public static function protectionlevel( $parser, $type = '', $title = '' ) {
848 $titleObject = Title
::newFromText( $title );
849 if ( !( $titleObject instanceof Title
) ) {
850 $titleObject = $parser->mTitle
;
852 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
853 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
854 # Title::getRestrictions returns an array, its possible it may have
855 # multiple values in the future
856 return implode( ',', $restrictions );
862 * Returns the requested protection expiry for the current page. This
863 * is an expensive parser function and can't be called too many times
864 * per page, unless the protection levels/expiries for the given title
865 * have already been retrieved
867 * @param Parser $parser
868 * @param string $type
869 * @param string $title
873 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
874 $titleObject = Title
::newFromText( $title );
875 if ( !( $titleObject instanceof Title
) ) {
876 $titleObject = $parser->mTitle
;
878 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
879 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
880 // getRestrictionExpiry() returns false on invalid type; trying to
881 // match protectionlevel() function that returns empty string instead
882 if ( $expiry === false ) {
891 * Gives language names.
892 * @param Parser $parser
893 * @param string $code Language code (of which to get name)
894 * @param string $inLanguage Language code (in which to get name)
897 public static function language( $parser, $code = '', $inLanguage = '' ) {
898 $code = strtolower( $code );
899 $inLanguage = strtolower( $inLanguage );
900 $lang = Language
::fetchLanguageName( $code, $inLanguage );
901 return $lang !== '' ?
$lang : LanguageCode
::bcp47( $code );
905 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
906 * @param Parser $parser
907 * @param string $string
908 * @param string $length
909 * @param string $padding
910 * @param int $direction
913 public static function pad(
914 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
916 $padding = $parser->killMarkers( $padding );
917 $lengthOfPadding = mb_strlen( $padding );
918 if ( $lengthOfPadding == 0 ) {
922 # The remaining length to add counts down to 0 as padding is added
923 $length = min( (int)$length, 500 ) - mb_strlen( $string );
924 if ( $length <= 0 ) {
929 # $finalPadding is just $padding repeated enough times so that
930 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
932 while ( $length > 0 ) {
933 # If $length < $lengthofPadding, truncate $padding so we get the
934 # exact length desired.
935 $finalPadding .= mb_substr( $padding, 0, $length );
936 $length -= $lengthOfPadding;
939 if ( $direction == STR_PAD_LEFT
) {
940 return $finalPadding . $string;
942 return $string . $finalPadding;
946 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
947 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
950 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
951 return self
::pad( $parser, $string, $length, $padding );
955 * @param Parser $parser
956 * @param string $text
959 public static function anchorencode( $parser, $text ) {
960 $text = $parser->killMarkers( $text );
961 $section = (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
962 return Sanitizer
::safeEncodeAttribute( $section );
965 public static function special( $parser, $text ) {
966 list( $page, $subpage ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
967 resolveAlias( $text );
969 $title = SpecialPage
::getTitleFor( $page, $subpage );
970 return $title->getPrefixedText();
972 // unknown special page, just use the given text as its title, if at all possible
973 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
974 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
978 public static function speciale( $parser, $text ) {
979 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
983 * @param Parser $parser
984 * @param string $text The sortkey to use
985 * @param string $uarg Either "noreplace" or "noerror" (in en)
986 * both suppress errors, and noreplace does nothing if
987 * a default sortkey already exists.
990 public static function defaultsort( $parser, $text, $uarg = '' ) {
991 static $magicWords = null;
992 if ( is_null( $magicWords ) ) {
993 $magicWords = $parser->getMagicWordFactory()->newArray(
994 [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
996 $arg = $magicWords->matchStartToEnd( $uarg );
998 $text = trim( $text );
999 if ( strlen( $text ) == 0 ) {
1002 $old = $parser->getCustomDefaultSort();
1003 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
1004 $parser->setDefaultSort( $text );
1007 if ( $old === false ||
$old == $text ||
$arg ) {
1010 $converter = $parser->getTargetLanguage()->getConverter();
1011 return '<span class="error">' .
1012 wfMessage( 'duplicate-defaultsort',
1013 // Message should be parsed, but these params should only be escaped.
1014 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
1015 $converter->markNoConversion( wfEscapeWikiText( $text ) )
1016 )->inContentLanguage()->text() .
1022 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
1023 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
1024 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
1026 * @param Parser $parser
1027 * @param string $name
1028 * @param string $argA
1029 * @param string $argB
1030 * @return array|string
1032 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1033 $file = wfFindFile( $name );
1035 if ( $argA == 'nowiki' ) {
1036 // {{filepath: | option [| size] }}
1038 $parsedWidthParam = Parser
::parseWidthParam( $argB );
1040 // {{filepath: [| size [|option]] }}
1041 $parsedWidthParam = Parser
::parseWidthParam( $argA );
1042 $isNowiki = ( $argB == 'nowiki' );
1046 $url = $file->getFullUrl();
1048 // If a size is requested...
1049 if ( count( $parsedWidthParam ) ) {
1050 $mto = $file->transform( $parsedWidthParam );
1052 if ( $mto && !$mto->isError() ) {
1053 // ... change the URL to point to a thumbnail.
1054 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1058 return [ $url, 'nowiki' => true ];
1067 * Parser function to extension tag adaptor
1068 * @param Parser $parser
1069 * @param PPFrame $frame
1070 * @param PPNode[] $args
1073 public static function tagObj( $parser, $frame, $args ) {
1074 if ( !count( $args ) ) {
1077 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1079 if ( count( $args ) ) {
1080 $inner = $frame->expand( array_shift( $args ) );
1086 foreach ( $args as $arg ) {
1087 $bits = $arg->splitArg();
1088 if ( strval( $bits['index'] ) === '' ) {
1089 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1090 $value = trim( $frame->expand( $bits['value'] ) );
1091 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1092 $value = $m[1] ??
'';
1094 $attributes[$name] = $value;
1098 $stripList = $parser->getStripList();
1099 if ( !in_array( $tagName, $stripList ) ) {
1100 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1102 foreach ( $attributes as $name => $value ) {
1103 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1105 if ( $inner === null ) {
1106 return "<$tagName$attrText/>";
1108 return "<$tagName$attrText>$inner</$tagName>";
1114 'attributes' => $attributes,
1115 'close' => "</$tagName>",
1117 return $parser->extensionSubstitution( $params, $frame );
1121 * Fetched the current revision of the given title and return this.
1122 * Will increment the expensive function count and
1123 * add a template link to get the value refreshed on changes.
1124 * For a given title, which is equal to the current parser title,
1125 * the revision object from the parser is used, when that is the current one
1127 * @param Parser $parser
1128 * @param Title $title
1132 private static function getCachedRevisionObject( $parser, $title = null ) {
1133 if ( is_null( $title ) ) {
1137 // Use the revision from the parser itself, when param is the current page
1138 // and the revision is the current one
1139 if ( $title->equals( $parser->getTitle() ) ) {
1140 $parserRev = $parser->getRevisionObject();
1141 if ( $parserRev && $parserRev->isCurrent() ) {
1142 // force reparse after edit with vary-revision flag
1143 $parser->getOutput()->setFlag( 'vary-revision' );
1144 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1149 // Normalize name for cache
1150 $page = $title->getPrefixedDBkey();
1152 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1153 && !$parser->incrementExpensiveFunctionCount() ) {
1156 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1157 $pageID = $rev ?
$rev->getPage() : 0;
1158 $revID = $rev ?
$rev->getId() : 0;
1160 // Register dependency in templatelinks
1161 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1167 * Get the pageid of a specified page
1168 * @param Parser $parser
1169 * @param string|null $title Title to get the pageid from
1170 * @return int|null|string
1173 public static function pageid( $parser, $title = null ) {
1174 $t = Title
::newFromText( $title );
1175 if ( is_null( $t ) ) {
1178 // Use title from parser to have correct pageid after edit
1179 if ( $t->equals( $parser->getTitle() ) ) {
1180 $t = $parser->getTitle();
1181 return $t->getArticleID();
1184 // These can't have ids
1185 if ( !$t->canExist() ||
$t->isExternal() ) {
1189 // Check the link cache, maybe something already looked it up.
1190 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1191 $pdbk = $t->getPrefixedDBkey();
1192 $id = $linkCache->getGoodLinkID( $pdbk );
1194 $parser->mOutput
->addLink( $t, $id );
1197 if ( $linkCache->isBadLink( $pdbk ) ) {
1198 $parser->mOutput
->addLink( $t, 0 );
1202 // We need to load it from the DB, so mark expensive
1203 if ( $parser->incrementExpensiveFunctionCount() ) {
1204 $id = $t->getArticleID();
1205 $parser->mOutput
->addLink( $t, $id );
1212 * Get the id from the last revision of a specified page.
1213 * @param Parser $parser
1214 * @param string|null $title Title to get the id from
1215 * @return int|null|string
1218 public static function revisionid( $parser, $title = null ) {
1219 $t = Title
::newFromText( $title );
1220 if ( is_null( $t ) ) {
1223 // fetch revision from cache/database and return the value
1224 $rev = self
::getCachedRevisionObject( $parser, $t );
1225 return $rev ?
$rev->getId() : '';
1229 * Get the day from the last revision of a specified page.
1230 * @param Parser $parser
1231 * @param string|null $title Title to get the day from
1235 public static function revisionday( $parser, $title = null ) {
1236 $t = Title
::newFromText( $title );
1237 if ( is_null( $t ) ) {
1240 // fetch revision from cache/database and return the value
1241 $rev = self
::getCachedRevisionObject( $parser, $t );
1242 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1246 * Get the day with leading zeros from the last revision of a specified page.
1247 * @param Parser $parser
1248 * @param string|null $title Title to get the day from
1252 public static function revisionday2( $parser, $title = null ) {
1253 $t = Title
::newFromText( $title );
1254 if ( is_null( $t ) ) {
1257 // fetch revision from cache/database and return the value
1258 $rev = self
::getCachedRevisionObject( $parser, $t );
1259 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1263 * Get the month with leading zeros from the last revision of a specified page.
1264 * @param Parser $parser
1265 * @param string|null $title Title to get the month from
1269 public static function revisionmonth( $parser, $title = null ) {
1270 $t = Title
::newFromText( $title );
1271 if ( is_null( $t ) ) {
1274 // fetch revision from cache/database and return the value
1275 $rev = self
::getCachedRevisionObject( $parser, $t );
1276 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1280 * Get the month from the last revision of a specified page.
1281 * @param Parser $parser
1282 * @param string|null $title Title to get the month from
1286 public static function revisionmonth1( $parser, $title = null ) {
1287 $t = Title
::newFromText( $title );
1288 if ( is_null( $t ) ) {
1291 // fetch revision from cache/database and return the value
1292 $rev = self
::getCachedRevisionObject( $parser, $t );
1293 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1297 * Get the year from the last revision of a specified page.
1298 * @param Parser $parser
1299 * @param string|null $title Title to get the year from
1303 public static function revisionyear( $parser, $title = null ) {
1304 $t = Title
::newFromText( $title );
1305 if ( is_null( $t ) ) {
1308 // fetch revision from cache/database and return the value
1309 $rev = self
::getCachedRevisionObject( $parser, $t );
1310 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1314 * Get the timestamp from the last revision of a specified page.
1315 * @param Parser $parser
1316 * @param string|null $title Title to get the timestamp from
1320 public static function revisiontimestamp( $parser, $title = null ) {
1321 $t = Title
::newFromText( $title );
1322 if ( is_null( $t ) ) {
1325 // fetch revision from cache/database and return the value
1326 $rev = self
::getCachedRevisionObject( $parser, $t );
1327 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1331 * Get the user from the last revision of a specified page.
1332 * @param Parser $parser
1333 * @param string|null $title Title to get the user from
1337 public static function revisionuser( $parser, $title = null ) {
1338 $t = Title
::newFromText( $title );
1339 if ( is_null( $t ) ) {
1342 // fetch revision from cache/database and return the value
1343 $rev = self
::getCachedRevisionObject( $parser, $t );
1344 return $rev ?
$rev->getUserText() : '';
1348 * Returns the sources of any cascading protection acting on a specified page.
1349 * Pages will not return their own title unless they transclude themselves.
1350 * This is an expensive parser function and can't be called too many times per page,
1351 * unless cascading protection sources for the page have already been loaded.
1353 * @param Parser $parser
1354 * @param string $title
1359 public static function cascadingsources( $parser, $title = '' ) {
1360 $titleObject = Title
::newFromText( $title );
1361 if ( !( $titleObject instanceof Title
) ) {
1362 $titleObject = $parser->mTitle
;
1364 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1365 ||
$parser->incrementExpensiveFunctionCount()
1368 $sources = $titleObject->getCascadeProtectionSources();
1369 foreach ( $sources[0] as $sourceTitle ) {
1370 $names[] = $sourceTitle->getPrefixedText();
1372 return implode( '|', $names );