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 = '' ) {
139 if ( intval( $part1 ) ||
$part1 == "0" ) {
140 $index = intval( $part1 );
142 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
144 if ( $index !== false ) {
145 return $wgContLang->getFormattedNsText( $index );
147 return [ 'found' => false ];
151 public static function nse( $parser, $part1 = '' ) {
152 $ret = self
::ns( $parser, $part1 );
153 if ( is_string( $ret ) ) {
154 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
160 * urlencodes a string according to one of three patterns: (T24474)
162 * By default (for HTTP "query" strings), spaces are encoded as '+'.
163 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
164 * For links to "wiki"s, or similar software, spaces are encoded as '_',
166 * @param Parser $parser
167 * @param string $s The text to encode.
168 * @param string|null $arg (optional): The type of encoding.
171 public static function urlencode( $parser, $s = '', $arg = null ) {
172 static $magicWords = null;
173 if ( is_null( $magicWords ) ) {
175 $parser->getMagicWordFactory()->newArray( [ 'url_path', 'url_query', 'url_wiki' ] );
177 switch ( $magicWords->matchStartToEnd( $arg ) ) {
178 // Encode as though it's a wiki page, '_' for ' '.
180 $func = 'wfUrlencode';
181 $s = str_replace( ' ', '_', $s );
184 // Encode for an HTTP Path, '%20' for ' '.
186 $func = 'rawurlencode';
189 // Encode for HTTP query, '+' for ' '.
194 // See T105242, where the choice to kill markers and various
195 // other options were discussed.
196 return $func( $parser->killMarkers( $s ) );
199 public static function lcfirst( $parser, $s = '' ) {
201 return $wgContLang->lcfirst( $s );
204 public static function ucfirst( $parser, $s = '' ) {
206 return $wgContLang->ucfirst( $s );
210 * @param Parser $parser
214 public static function lc( $parser, $s = '' ) {
216 return $parser->markerSkipCallback( $s, [ $wgContLang, 'lc' ] );
220 * @param Parser $parser
224 public static function uc( $parser, $s = '' ) {
226 return $parser->markerSkipCallback( $s, [ $wgContLang, 'uc' ] );
229 public static function localurl( $parser, $s = '', $arg = null ) {
230 return self
::urlFunction( 'getLocalURL', $s, $arg );
233 public static function localurle( $parser, $s = '', $arg = null ) {
234 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
235 if ( !is_string( $temp ) ) {
238 return htmlspecialchars( $temp );
242 public static function fullurl( $parser, $s = '', $arg = null ) {
243 return self
::urlFunction( 'getFullURL', $s, $arg );
246 public static function fullurle( $parser, $s = '', $arg = null ) {
247 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
248 if ( !is_string( $temp ) ) {
251 return htmlspecialchars( $temp );
255 public static function canonicalurl( $parser, $s = '', $arg = null ) {
256 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
259 public static function canonicalurle( $parser, $s = '', $arg = null ) {
260 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
261 if ( !is_string( $temp ) ) {
264 return htmlspecialchars( $temp );
268 public static function urlFunction( $func, $s = '', $arg = null ) {
269 $title = Title
::newFromText( $s );
270 # Due to order of execution of a lot of bits, the values might be encoded
271 # before arriving here; if that's true, then the title can't be created
272 # and the variable will fail. If we can't get a decent title from the first
273 # attempt, url-decode and try for a second.
274 if ( is_null( $title ) ) {
275 $title = Title
::newFromURL( urldecode( $s ) );
277 if ( !is_null( $title ) ) {
278 # Convert NS_MEDIA -> NS_FILE
279 if ( $title->inNamespace( NS_MEDIA
) ) {
280 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
282 if ( !is_null( $arg ) ) {
283 $text = $title->$func( $arg );
285 $text = $title->$func();
289 return [ 'found' => false ];
294 * @param Parser $parser
296 * @param string|null $arg
299 public static function formatnum( $parser, $num = '', $arg = null ) {
300 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg ) ) {
301 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
303 self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'nocommafysuffix', $arg )
305 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
307 $func = [ $parser->getFunctionLang(), 'formatNum' ];
309 return $parser->markerSkipCallback( $num, $func );
313 * @param Parser $parser
314 * @param string $case
315 * @param string $word
318 public static function grammar( $parser, $case = '', $word = '' ) {
319 $word = $parser->killMarkers( $word );
320 return $parser->getFunctionLang()->convertGrammar( $word, $case );
324 * @param Parser $parser
325 * @param string $username
328 public static function gender( $parser, $username ) {
329 $forms = array_slice( func_get_args(), 2 );
331 // Some shortcuts to avoid loading user data unnecessarily
332 if ( count( $forms ) === 0 ) {
334 } elseif ( count( $forms ) === 1 ) {
338 $username = trim( $username );
341 $gender = User
::getDefaultOption( 'gender' );
343 // allow prefix and normalize (e.g. "*foo" -> "*foo" ).
344 $title = Title
::newFromText( $username, NS_USER
);
346 if ( $title && $title->inNamespace( NS_USER
) ) {
347 $username = $title->getText();
350 // check parameter, or use the ParserOptions if in interface message
351 $user = User
::newFromName( $username );
352 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
354 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
355 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
356 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
358 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
363 * @param Parser $parser
364 * @param string $text
367 public static function plural( $parser, $text = '' ) {
368 $forms = array_slice( func_get_args(), 2 );
369 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
370 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
371 return $parser->getFunctionLang()->convertPlural( $text, $forms );
375 * @param Parser $parser
376 * @param string $text
379 public static function bidi( $parser, $text = '' ) {
380 return $parser->getFunctionLang()->embedBidi( $text );
384 * Override the title of the page when viewed, provided we've been given a
385 * title which will normalise to the canonical title
387 * @param Parser $parser Parent parser
388 * @param string $text Desired title text
389 * @param string $uarg
392 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
393 global $wgRestrictDisplayTitle;
395 static $magicWords = null;
396 if ( is_null( $magicWords ) ) {
397 $magicWords = $parser->getMagicWordFactory()->newArray(
398 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
400 $arg = $magicWords->matchStartToEnd( $uarg );
402 // parse a limited subset of wiki markup (just the single quote items)
403 $text = $parser->doQuotes( $text );
405 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
406 $text = $parser->killMarkers( $text );
408 // list of disallowed tags for DISPLAYTITLE
409 // these will be escaped even though they are allowed in normal wiki text
410 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
411 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
413 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
414 if ( $wgRestrictDisplayTitle ) {
415 $htmlTagsCallback = function ( &$params ) {
416 $decoded = Sanitizer
::decodeTagAttributes( $params );
418 if ( isset( $decoded['style'] ) ) {
419 // this is called later anyway, but we need it right now for the regexes below to be safe
420 // calling it twice doesn't hurt
421 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
423 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
424 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
428 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
431 $htmlTagsCallback = null;
434 // only requested titles that normalize to the actual title are allowed through
435 // if $wgRestrictDisplayTitle is true (it is by default)
436 // mimic the escaping process that occurs in OutputPage::setPageTitle
437 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
444 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
446 if ( !$wgRestrictDisplayTitle ||
447 ( $title instanceof Title
448 && !$title->hasFragment()
449 && $title->equals( $parser->mTitle
) )
451 $old = $parser->mOutput
->getProperty( 'displaytitle' );
452 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
453 $parser->mOutput
->setDisplayTitle( $text );
455 if ( $old !== false && $old !== $text && !$arg ) {
456 $converter = $parser->getTargetLanguage()->getConverter();
457 return '<span class="error">' .
458 wfMessage( 'duplicate-displaytitle',
459 // Message should be parsed, but these params should only be escaped.
460 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
461 $converter->markNoConversion( wfEscapeWikiText( $text ) )
462 )->inContentLanguage()->text() .
468 $converter = $parser->getTargetLanguage()->getConverter();
469 $parser->getOutput()->addWarning(
470 wfMessage( 'restricted-displaytitle',
471 // Message should be parsed, but this param should only be escaped.
472 $converter->markNoConversion( wfEscapeWikiText( $text ) )
475 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
480 * Matches the given value against the value of given magic word
482 * @param MagicWordFactory $magicWordFactory A factory to get the word from, e.g., from
483 * $parser->getMagicWordFactory()
484 * @param string $magicword Magic word key
485 * @param string $value Value to match
486 * @return bool True on successful match
488 private static function matchAgainstMagicword(
489 MagicWordFactory
$magicWordFactory, $magicword, $value
491 $value = trim( strval( $value ) );
492 if ( $value === '' ) {
495 $mwObject = $magicWordFactory->get( $magicword );
496 return $mwObject->matchStartToEnd( $value );
500 * Formats a number according to a language.
502 * @param int|float $num
504 * @param Language|StubUserLang $language
505 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
508 public static function formatRaw(
509 $num, $raw, $language, MagicWordFactory
$magicWordFactory = null
511 if ( $raw !== null && !$magicWordFactory ) {
512 $magicWordFactory = MediaWikiServices
::getInstance()->getMagicWordFactory();
515 $raw !== null && self
::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw )
519 return $language->formatNum( $num );
523 public static function numberofpages( $parser, $raw = null ) {
524 return self
::formatRaw( SiteStats
::pages(), $raw, $parser->getFunctionLang() );
527 public static function numberofusers( $parser, $raw = null ) {
528 return self
::formatRaw( SiteStats
::users(), $raw, $parser->getFunctionLang() );
530 public static function numberofactiveusers( $parser, $raw = null ) {
531 return self
::formatRaw( SiteStats
::activeUsers(), $raw, $parser->getFunctionLang() );
534 public static function numberofarticles( $parser, $raw = null ) {
535 return self
::formatRaw( SiteStats
::articles(), $raw, $parser->getFunctionLang() );
538 public static function numberoffiles( $parser, $raw = null ) {
539 return self
::formatRaw( SiteStats
::images(), $raw, $parser->getFunctionLang() );
542 public static function numberofadmins( $parser, $raw = null ) {
543 return self
::formatRaw(
544 SiteStats
::numberingroup( 'sysop' ),
546 $parser->getFunctionLang()
550 public static function numberofedits( $parser, $raw = null ) {
551 return self
::formatRaw( SiteStats
::edits(), $raw, $parser->getFunctionLang() );
554 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
555 return self
::formatRaw(
556 SiteStats
::pagesInNs( intval( $namespace ) ),
558 $parser->getFunctionLang()
561 public static function numberingroup( $parser, $name = '', $raw = null ) {
562 return self
::formatRaw(
563 SiteStats
::numberingroup( strtolower( $name ) ),
565 $parser->getFunctionLang()
570 * Given a title, return the namespace name that would be given by the
571 * corresponding magic word
572 * Note: function name changed to "mwnamespace" rather than "namespace"
573 * to not break PHP 5.3
574 * @param Parser $parser
575 * @param string|null $title
576 * @return mixed|string
578 public static function mwnamespace( $parser, $title = null ) {
579 $t = Title
::newFromText( $title );
580 if ( is_null( $t ) ) {
583 return str_replace( '_', ' ', $t->getNsText() );
585 public static function namespacee( $parser, $title = null ) {
586 $t = Title
::newFromText( $title );
587 if ( is_null( $t ) ) {
590 return wfUrlencode( $t->getNsText() );
592 public static function namespacenumber( $parser, $title = null ) {
593 $t = Title
::newFromText( $title );
594 if ( is_null( $t ) ) {
597 return $t->getNamespace();
599 public static function talkspace( $parser, $title = null ) {
600 $t = Title
::newFromText( $title );
601 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
604 return str_replace( '_', ' ', $t->getTalkNsText() );
606 public static function talkspacee( $parser, $title = null ) {
607 $t = Title
::newFromText( $title );
608 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
611 return wfUrlencode( $t->getTalkNsText() );
613 public static function subjectspace( $parser, $title = null ) {
614 $t = Title
::newFromText( $title );
615 if ( is_null( $t ) ) {
618 return str_replace( '_', ' ', $t->getSubjectNsText() );
620 public static function subjectspacee( $parser, $title = null ) {
621 $t = Title
::newFromText( $title );
622 if ( is_null( $t ) ) {
625 return wfUrlencode( $t->getSubjectNsText() );
629 * Functions to get and normalize pagenames, corresponding to the magic words
631 * @param Parser $parser
632 * @param string|null $title
635 public static function pagename( $parser, $title = null ) {
636 $t = Title
::newFromText( $title );
637 if ( is_null( $t ) ) {
640 return wfEscapeWikiText( $t->getText() );
642 public static function pagenamee( $parser, $title = null ) {
643 $t = Title
::newFromText( $title );
644 if ( is_null( $t ) ) {
647 return wfEscapeWikiText( $t->getPartialURL() );
649 public static function fullpagename( $parser, $title = null ) {
650 $t = Title
::newFromText( $title );
651 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
654 return wfEscapeWikiText( $t->getPrefixedText() );
656 public static function fullpagenamee( $parser, $title = null ) {
657 $t = Title
::newFromText( $title );
658 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
661 return wfEscapeWikiText( $t->getPrefixedURL() );
663 public static function subpagename( $parser, $title = null ) {
664 $t = Title
::newFromText( $title );
665 if ( is_null( $t ) ) {
668 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() );
677 public static function rootpagename( $parser, $title = null ) {
678 $t = Title
::newFromText( $title );
679 if ( is_null( $t ) ) {
682 return wfEscapeWikiText( $t->getRootText() );
684 public static function rootpagenamee( $parser, $title = null ) {
685 $t = Title
::newFromText( $title );
686 if ( is_null( $t ) ) {
689 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
691 public static function basepagename( $parser, $title = null ) {
692 $t = Title
::newFromText( $title );
693 if ( is_null( $t ) ) {
696 return wfEscapeWikiText( $t->getBaseText() );
698 public static function basepagenamee( $parser, $title = null ) {
699 $t = Title
::newFromText( $title );
700 if ( is_null( $t ) ) {
703 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
705 public static function talkpagename( $parser, $title = null ) {
706 $t = Title
::newFromText( $title );
707 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
710 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
712 public static function talkpagenamee( $parser, $title = null ) {
713 $t = Title
::newFromText( $title );
714 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
717 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
719 public static function subjectpagename( $parser, $title = null ) {
720 $t = Title
::newFromText( $title );
721 if ( is_null( $t ) ) {
724 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
726 public static function subjectpagenamee( $parser, $title = null ) {
727 $t = Title
::newFromText( $title );
728 if ( is_null( $t ) ) {
731 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
735 * Return the number of pages, files or subcats in the given category,
736 * or 0 if it's nonexistent. This is an expensive parser function and
737 * can't be called too many times per page.
738 * @param Parser $parser
739 * @param string $name
740 * @param string|null $arg1
741 * @param string|null $arg2
744 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
746 static $magicWords = null;
747 if ( is_null( $magicWords ) ) {
748 $magicWords = $parser->getMagicWordFactory()->newArray( [
749 'pagesincategory_all',
750 'pagesincategory_pages',
751 'pagesincategory_subcats',
752 'pagesincategory_files'
757 // split the given option to its variable
758 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
759 // {{pagesincategory:|raw[|type]}}
761 $type = $magicWords->matchStartToEnd( $arg2 );
763 // {{pagesincategory:[|type[|raw]]}}
764 $type = $magicWords->matchStartToEnd( $arg1 );
767 if ( !$type ) { // backward compatibility
768 $type = 'pagesincategory_all';
771 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
772 if ( !$title ) { # invalid title
773 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
775 $wgContLang->findVariantLink( $name, $title, true );
777 // Normalize name for cache
778 $name = $title->getDBkey();
780 if ( !isset( $cache[$name] ) ) {
781 $category = Category
::newFromTitle( $title );
783 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
784 if ( $parser->incrementExpensiveFunctionCount() ) {
785 // $allCount is the total number of cat members,
786 // not the count of how many members are normal pages.
787 $allCount = (int)$category->getPageCount();
788 $subcatCount = (int)$category->getSubcatCount();
789 $fileCount = (int)$category->getFileCount();
790 $pagesCount = $allCount - $subcatCount - $fileCount;
792 $cache[$name]['pagesincategory_all'] = $allCount;
793 $cache[$name]['pagesincategory_pages'] = $pagesCount;
794 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
795 $cache[$name]['pagesincategory_files'] = $fileCount;
798 $count = $cache[$name][$type];
799 return self
::formatRaw( $count, $raw, $parser->getFunctionLang() );
803 * Return the size of the given page, or 0 if it's nonexistent. This is an
804 * expensive parser function and can't be called too many times per page.
806 * @param Parser $parser
807 * @param string $page Name of page to check (Default: empty string)
808 * @param string|null $raw Should number be human readable with commas or just number
811 public static function pagesize( $parser, $page = '', $raw = null ) {
812 $title = Title
::newFromText( $page );
814 if ( !is_object( $title ) ) {
815 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
818 // fetch revision from cache/database and return the value
819 $rev = self
::getCachedRevisionObject( $parser, $title );
820 $length = $rev ?
$rev->getSize() : 0;
821 if ( $length === null ) {
822 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
825 return self
::formatRaw( $length, $raw, $parser->getFunctionLang() );
829 * Returns the requested protection level for the current page. This
830 * is an expensive parser function and can't be called too many times
831 * per page, unless the protection levels/expiries for the given title
832 * have already been retrieved
834 * @param Parser $parser
835 * @param string $type
836 * @param string $title
840 public static function protectionlevel( $parser, $type = '', $title = '' ) {
841 $titleObject = Title
::newFromText( $title );
842 if ( !( $titleObject instanceof Title
) ) {
843 $titleObject = $parser->mTitle
;
845 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
846 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
847 # Title::getRestrictions returns an array, its possible it may have
848 # multiple values in the future
849 return implode( ',', $restrictions );
855 * Returns the requested protection expiry for the current page. This
856 * is an expensive parser function and can't be called too many times
857 * per page, unless the protection levels/expiries for the given title
858 * have already been retrieved
860 * @param Parser $parser
861 * @param string $type
862 * @param string $title
866 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
867 $titleObject = Title
::newFromText( $title );
868 if ( !( $titleObject instanceof Title
) ) {
869 $titleObject = $parser->mTitle
;
871 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
872 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
873 // getRestrictionExpiry() returns false on invalid type; trying to
874 // match protectionlevel() function that returns empty string instead
875 if ( $expiry === false ) {
884 * Gives language names.
885 * @param Parser $parser
886 * @param string $code Language code (of which to get name)
887 * @param string $inLanguage Language code (in which to get name)
890 public static function language( $parser, $code = '', $inLanguage = '' ) {
891 $code = strtolower( $code );
892 $inLanguage = strtolower( $inLanguage );
893 $lang = Language
::fetchLanguageName( $code, $inLanguage );
894 return $lang !== '' ?
$lang : LanguageCode
::bcp47( $code );
898 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
899 * @param Parser $parser
900 * @param string $string
901 * @param string $length
902 * @param string $padding
903 * @param int $direction
906 public static function pad(
907 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
909 $padding = $parser->killMarkers( $padding );
910 $lengthOfPadding = mb_strlen( $padding );
911 if ( $lengthOfPadding == 0 ) {
915 # The remaining length to add counts down to 0 as padding is added
916 $length = min( (int)$length, 500 ) - mb_strlen( $string );
917 if ( $length <= 0 ) {
922 # $finalPadding is just $padding repeated enough times so that
923 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
925 while ( $length > 0 ) {
926 # If $length < $lengthofPadding, truncate $padding so we get the
927 # exact length desired.
928 $finalPadding .= mb_substr( $padding, 0, $length );
929 $length -= $lengthOfPadding;
932 if ( $direction == STR_PAD_LEFT
) {
933 return $finalPadding . $string;
935 return $string . $finalPadding;
939 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
940 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
943 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
944 return self
::pad( $parser, $string, $length, $padding );
948 * @param Parser $parser
949 * @param string $text
952 public static function anchorencode( $parser, $text ) {
953 $text = $parser->killMarkers( $text );
954 $section = (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
955 return Sanitizer
::safeEncodeAttribute( $section );
958 public static function special( $parser, $text ) {
959 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
961 $title = SpecialPage
::getTitleFor( $page, $subpage );
962 return $title->getPrefixedText();
964 // unknown special page, just use the given text as its title, if at all possible
965 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
966 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
970 public static function speciale( $parser, $text ) {
971 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
975 * @param Parser $parser
976 * @param string $text The sortkey to use
977 * @param string $uarg Either "noreplace" or "noerror" (in en)
978 * both suppress errors, and noreplace does nothing if
979 * a default sortkey already exists.
982 public static function defaultsort( $parser, $text, $uarg = '' ) {
983 static $magicWords = null;
984 if ( is_null( $magicWords ) ) {
985 $magicWords = $parser->getMagicWordFactory()->newArray(
986 [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
988 $arg = $magicWords->matchStartToEnd( $uarg );
990 $text = trim( $text );
991 if ( strlen( $text ) == 0 ) {
994 $old = $parser->getCustomDefaultSort();
995 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
996 $parser->setDefaultSort( $text );
999 if ( $old === false ||
$old == $text ||
$arg ) {
1002 $converter = $parser->getTargetLanguage()->getConverter();
1003 return '<span class="error">' .
1004 wfMessage( 'duplicate-defaultsort',
1005 // Message should be parsed, but these params should only be escaped.
1006 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
1007 $converter->markNoConversion( wfEscapeWikiText( $text ) )
1008 )->inContentLanguage()->text() .
1014 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
1015 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
1016 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
1018 * @param Parser $parser
1019 * @param string $name
1020 * @param string $argA
1021 * @param string $argB
1022 * @return array|string
1024 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1025 $file = wfFindFile( $name );
1027 if ( $argA == 'nowiki' ) {
1028 // {{filepath: | option [| size] }}
1030 $parsedWidthParam = Parser
::parseWidthParam( $argB );
1032 // {{filepath: [| size [|option]] }}
1033 $parsedWidthParam = Parser
::parseWidthParam( $argA );
1034 $isNowiki = ( $argB == 'nowiki' );
1038 $url = $file->getFullUrl();
1040 // If a size is requested...
1041 if ( count( $parsedWidthParam ) ) {
1042 $mto = $file->transform( $parsedWidthParam );
1044 if ( $mto && !$mto->isError() ) {
1045 // ... change the URL to point to a thumbnail.
1046 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1050 return [ $url, 'nowiki' => true ];
1059 * Parser function to extension tag adaptor
1060 * @param Parser $parser
1061 * @param PPFrame $frame
1062 * @param PPNode[] $args
1065 public static function tagObj( $parser, $frame, $args ) {
1066 if ( !count( $args ) ) {
1069 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1071 if ( count( $args ) ) {
1072 $inner = $frame->expand( array_shift( $args ) );
1078 foreach ( $args as $arg ) {
1079 $bits = $arg->splitArg();
1080 if ( strval( $bits['index'] ) === '' ) {
1081 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1082 $value = trim( $frame->expand( $bits['value'] ) );
1083 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1084 $value = $m[1] ??
'';
1086 $attributes[$name] = $value;
1090 $stripList = $parser->getStripList();
1091 if ( !in_array( $tagName, $stripList ) ) {
1092 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1094 foreach ( $attributes as $name => $value ) {
1095 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1097 if ( $inner === null ) {
1098 return "<$tagName$attrText/>";
1100 return "<$tagName$attrText>$inner</$tagName>";
1106 'attributes' => $attributes,
1107 'close' => "</$tagName>",
1109 return $parser->extensionSubstitution( $params, $frame );
1113 * Fetched the current revision of the given title and return this.
1114 * Will increment the expensive function count and
1115 * add a template link to get the value refreshed on changes.
1116 * For a given title, which is equal to the current parser title,
1117 * the revision object from the parser is used, when that is the current one
1119 * @param Parser $parser
1120 * @param Title $title
1124 private static function getCachedRevisionObject( $parser, $title = null ) {
1125 if ( is_null( $title ) ) {
1129 // Use the revision from the parser itself, when param is the current page
1130 // and the revision is the current one
1131 if ( $title->equals( $parser->getTitle() ) ) {
1132 $parserRev = $parser->getRevisionObject();
1133 if ( $parserRev && $parserRev->isCurrent() ) {
1134 // force reparse after edit with vary-revision flag
1135 $parser->getOutput()->setFlag( 'vary-revision' );
1136 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1141 // Normalize name for cache
1142 $page = $title->getPrefixedDBkey();
1144 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1145 && !$parser->incrementExpensiveFunctionCount() ) {
1148 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1149 $pageID = $rev ?
$rev->getPage() : 0;
1150 $revID = $rev ?
$rev->getId() : 0;
1152 // Register dependency in templatelinks
1153 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1159 * Get the pageid of a specified page
1160 * @param Parser $parser
1161 * @param string|null $title Title to get the pageid from
1162 * @return int|null|string
1165 public static function pageid( $parser, $title = null ) {
1166 $t = Title
::newFromText( $title );
1167 if ( is_null( $t ) ) {
1170 // Use title from parser to have correct pageid after edit
1171 if ( $t->equals( $parser->getTitle() ) ) {
1172 $t = $parser->getTitle();
1173 return $t->getArticleID();
1176 // These can't have ids
1177 if ( !$t->canExist() ||
$t->isExternal() ) {
1181 // Check the link cache, maybe something already looked it up.
1182 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1183 $pdbk = $t->getPrefixedDBkey();
1184 $id = $linkCache->getGoodLinkID( $pdbk );
1186 $parser->mOutput
->addLink( $t, $id );
1189 if ( $linkCache->isBadLink( $pdbk ) ) {
1190 $parser->mOutput
->addLink( $t, 0 );
1194 // We need to load it from the DB, so mark expensive
1195 if ( $parser->incrementExpensiveFunctionCount() ) {
1196 $id = $t->getArticleID();
1197 $parser->mOutput
->addLink( $t, $id );
1204 * Get the id from the last revision of a specified page.
1205 * @param Parser $parser
1206 * @param string|null $title Title to get the id from
1207 * @return int|null|string
1210 public static function revisionid( $parser, $title = null ) {
1211 $t = Title
::newFromText( $title );
1212 if ( is_null( $t ) ) {
1215 // fetch revision from cache/database and return the value
1216 $rev = self
::getCachedRevisionObject( $parser, $t );
1217 return $rev ?
$rev->getId() : '';
1221 * Get the day from the last revision of a specified page.
1222 * @param Parser $parser
1223 * @param string|null $title Title to get the day from
1227 public static function revisionday( $parser, $title = null ) {
1228 $t = Title
::newFromText( $title );
1229 if ( is_null( $t ) ) {
1232 // fetch revision from cache/database and return the value
1233 $rev = self
::getCachedRevisionObject( $parser, $t );
1234 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1238 * Get the day with leading zeros from the last revision of a specified page.
1239 * @param Parser $parser
1240 * @param string|null $title Title to get the day from
1244 public static function revisionday2( $parser, $title = null ) {
1245 $t = Title
::newFromText( $title );
1246 if ( is_null( $t ) ) {
1249 // fetch revision from cache/database and return the value
1250 $rev = self
::getCachedRevisionObject( $parser, $t );
1251 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1255 * Get the month with leading zeros from the last revision of a specified page.
1256 * @param Parser $parser
1257 * @param string|null $title Title to get the month from
1261 public static function revisionmonth( $parser, $title = null ) {
1262 $t = Title
::newFromText( $title );
1263 if ( is_null( $t ) ) {
1266 // fetch revision from cache/database and return the value
1267 $rev = self
::getCachedRevisionObject( $parser, $t );
1268 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1272 * Get the month from the last revision of a specified page.
1273 * @param Parser $parser
1274 * @param string|null $title Title to get the month from
1278 public static function revisionmonth1( $parser, $title = null ) {
1279 $t = Title
::newFromText( $title );
1280 if ( is_null( $t ) ) {
1283 // fetch revision from cache/database and return the value
1284 $rev = self
::getCachedRevisionObject( $parser, $t );
1285 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1289 * Get the year from the last revision of a specified page.
1290 * @param Parser $parser
1291 * @param string|null $title Title to get the year from
1295 public static function revisionyear( $parser, $title = null ) {
1296 $t = Title
::newFromText( $title );
1297 if ( is_null( $t ) ) {
1300 // fetch revision from cache/database and return the value
1301 $rev = self
::getCachedRevisionObject( $parser, $t );
1302 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1306 * Get the timestamp from the last revision of a specified page.
1307 * @param Parser $parser
1308 * @param string|null $title Title to get the timestamp from
1312 public static function revisiontimestamp( $parser, $title = null ) {
1313 $t = Title
::newFromText( $title );
1314 if ( is_null( $t ) ) {
1317 // fetch revision from cache/database and return the value
1318 $rev = self
::getCachedRevisionObject( $parser, $t );
1319 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1323 * Get the user from the last revision of a specified page.
1324 * @param Parser $parser
1325 * @param string|null $title Title to get the user from
1329 public static function revisionuser( $parser, $title = null ) {
1330 $t = Title
::newFromText( $title );
1331 if ( is_null( $t ) ) {
1334 // fetch revision from cache/database and return the value
1335 $rev = self
::getCachedRevisionObject( $parser, $t );
1336 return $rev ?
$rev->getUserText() : '';
1340 * Returns the sources of any cascading protection acting on a specified page.
1341 * Pages will not return their own title unless they transclude themselves.
1342 * This is an expensive parser function and can't be called too many times per page,
1343 * unless cascading protection sources for the page have already been loaded.
1345 * @param Parser $parser
1346 * @param string $title
1351 public static function cascadingsources( $parser, $title = '' ) {
1352 $titleObject = Title
::newFromText( $title );
1353 if ( !( $titleObject instanceof Title
) ) {
1354 $titleObject = $parser->mTitle
;
1356 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1357 ||
$parser->incrementExpensiveFunctionCount()
1360 $sources = $titleObject->getCascadeProtectionSources();
1361 foreach ( $sources[0] as $sourceTitle ) {
1362 $names[] = $sourceTitle->getPrefixedText();
1364 return implode( '|', $names );