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 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 = DateFormatter
::getInstance( $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
318 public static function gender( $parser, $username ) {
319 $forms = array_slice( func_get_args(), 2 );
321 // Some shortcuts to avoid loading user data unnecessarily
322 if ( count( $forms ) === 0 ) {
324 } elseif ( count( $forms ) === 1 ) {
328 $username = trim( $username );
331 $gender = User
::getDefaultOption( 'gender' );
333 // allow prefix and normalize (e.g. "*foo" -> "*foo" ).
334 $title = Title
::newFromText( $username, NS_USER
);
336 if ( $title && $title->inNamespace( NS_USER
) ) {
337 $username = $title->getText();
340 // check parameter, or use the ParserOptions if in interface message
341 $user = User
::newFromName( $username );
342 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
344 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
345 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
346 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
348 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
353 * @param Parser $parser
354 * @param string $text
357 public static function plural( $parser, $text = '' ) {
358 $forms = array_slice( func_get_args(), 2 );
359 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
360 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
361 return $parser->getFunctionLang()->convertPlural( $text, $forms );
365 * @param Parser $parser
366 * @param string $text
369 public static function bidi( $parser, $text = '' ) {
370 return $parser->getFunctionLang()->embedBidi( $text );
374 * Override the title of the page when viewed, provided we've been given a
375 * title which will normalise to the canonical title
377 * @param Parser $parser Parent parser
378 * @param string $text Desired title text
379 * @param string $uarg
382 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
383 global $wgRestrictDisplayTitle;
385 static $magicWords = null;
386 if ( is_null( $magicWords ) ) {
387 $magicWords = $parser->getMagicWordFactory()->newArray(
388 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
390 $arg = $magicWords->matchStartToEnd( $uarg );
392 // parse a limited subset of wiki markup (just the single quote items)
393 $text = $parser->doQuotes( $text );
395 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
396 $text = $parser->killMarkers( $text );
398 // list of disallowed tags for DISPLAYTITLE
399 // these will be escaped even though they are allowed in normal wiki text
400 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
401 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
403 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
404 if ( $wgRestrictDisplayTitle ) {
405 $htmlTagsCallback = function ( &$params ) {
406 $decoded = Sanitizer
::decodeTagAttributes( $params );
408 if ( isset( $decoded['style'] ) ) {
409 // this is called later anyway, but we need it right now for the regexes below to be safe
410 // calling it twice doesn't hurt
411 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
413 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
414 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
418 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
421 $htmlTagsCallback = null;
424 // only requested titles that normalize to the actual title are allowed through
425 // if $wgRestrictDisplayTitle is true (it is by default)
426 // mimic the escaping process that occurs in OutputPage::setPageTitle
427 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
434 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
436 if ( !$wgRestrictDisplayTitle ||
437 ( $title instanceof Title
438 && !$title->hasFragment()
439 && $title->equals( $parser->mTitle
) )
441 $old = $parser->mOutput
->getProperty( 'displaytitle' );
442 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
443 $parser->mOutput
->setDisplayTitle( $text );
445 if ( $old !== false && $old !== $text && !$arg ) {
446 $converter = $parser->getTargetLanguage()->getConverter();
447 return '<span class="error">' .
448 wfMessage( 'duplicate-displaytitle',
449 // Message should be parsed, but these params should only be escaped.
450 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
451 $converter->markNoConversion( wfEscapeWikiText( $text ) )
452 )->inContentLanguage()->text() .
458 $converter = $parser->getTargetLanguage()->getConverter();
459 $parser->getOutput()->addWarning(
460 wfMessage( 'restricted-displaytitle',
461 // Message should be parsed, but this param should only be escaped.
462 $converter->markNoConversion( wfEscapeWikiText( $text ) )
465 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
470 * Matches the given value against the value of given magic word
472 * @param MagicWordFactory $magicWordFactory A factory to get the word from, e.g., from
473 * $parser->getMagicWordFactory()
474 * @param string $magicword Magic word key
475 * @param string $value Value to match
476 * @return bool True on successful match
478 private static function matchAgainstMagicword(
479 MagicWordFactory
$magicWordFactory, $magicword, $value
481 $value = trim( strval( $value ) );
482 if ( $value === '' ) {
485 $mwObject = $magicWordFactory->get( $magicword );
486 return $mwObject->matchStartToEnd( $value );
490 * Formats a number according to a language.
492 * @param int|float $num
494 * @param Language|StubUserLang $language
495 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
498 public static function formatRaw(
499 $num, $raw, $language, MagicWordFactory
$magicWordFactory = null
501 if ( $raw !== null && !$magicWordFactory ) {
502 $magicWordFactory = MediaWikiServices
::getInstance()->getMagicWordFactory();
505 $raw !== null && self
::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw )
509 return $language->formatNum( $num );
513 public static function numberofpages( $parser, $raw = null ) {
514 return self
::formatRaw( SiteStats
::pages(), $raw, $parser->getFunctionLang() );
517 public static function numberofusers( $parser, $raw = null ) {
518 return self
::formatRaw( SiteStats
::users(), $raw, $parser->getFunctionLang() );
520 public static function numberofactiveusers( $parser, $raw = null ) {
521 return self
::formatRaw( SiteStats
::activeUsers(), $raw, $parser->getFunctionLang() );
524 public static function numberofarticles( $parser, $raw = null ) {
525 return self
::formatRaw( SiteStats
::articles(), $raw, $parser->getFunctionLang() );
528 public static function numberoffiles( $parser, $raw = null ) {
529 return self
::formatRaw( SiteStats
::images(), $raw, $parser->getFunctionLang() );
532 public static function numberofadmins( $parser, $raw = null ) {
533 return self
::formatRaw(
534 SiteStats
::numberingroup( 'sysop' ),
536 $parser->getFunctionLang()
540 public static function numberofedits( $parser, $raw = null ) {
541 return self
::formatRaw( SiteStats
::edits(), $raw, $parser->getFunctionLang() );
544 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
545 return self
::formatRaw(
546 SiteStats
::pagesInNs( intval( $namespace ) ),
548 $parser->getFunctionLang()
551 public static function numberingroup( $parser, $name = '', $raw = null ) {
552 return self
::formatRaw(
553 SiteStats
::numberingroup( strtolower( $name ) ),
555 $parser->getFunctionLang()
560 * Given a title, return the namespace name that would be given by the
561 * corresponding magic word
562 * Note: function name changed to "mwnamespace" rather than "namespace"
563 * to not break PHP 5.3
564 * @param Parser $parser
565 * @param string|null $title
566 * @return mixed|string
568 public static function mwnamespace( $parser, $title = null ) {
569 $t = Title
::newFromText( $title );
570 if ( is_null( $t ) ) {
573 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() );
582 public static function namespacenumber( $parser, $title = null ) {
583 $t = Title
::newFromText( $title );
584 if ( is_null( $t ) ) {
587 return $t->getNamespace();
589 public static function talkspace( $parser, $title = null ) {
590 $t = Title
::newFromText( $title );
591 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
594 return str_replace( '_', ' ', $t->getTalkNsText() );
596 public static function talkspacee( $parser, $title = null ) {
597 $t = Title
::newFromText( $title );
598 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
601 return wfUrlencode( $t->getTalkNsText() );
603 public static function subjectspace( $parser, $title = null ) {
604 $t = Title
::newFromText( $title );
605 if ( is_null( $t ) ) {
608 return str_replace( '_', ' ', $t->getSubjectNsText() );
610 public static function subjectspacee( $parser, $title = null ) {
611 $t = Title
::newFromText( $title );
612 if ( is_null( $t ) ) {
615 return wfUrlencode( $t->getSubjectNsText() );
619 * Functions to get and normalize pagenames, corresponding to the magic words
621 * @param Parser $parser
622 * @param string|null $title
625 public static function pagename( $parser, $title = null ) {
626 $t = Title
::newFromText( $title );
627 if ( is_null( $t ) ) {
630 return wfEscapeWikiText( $t->getText() );
632 public static function pagenamee( $parser, $title = null ) {
633 $t = Title
::newFromText( $title );
634 if ( is_null( $t ) ) {
637 return wfEscapeWikiText( $t->getPartialURL() );
639 public static function fullpagename( $parser, $title = null ) {
640 $t = Title
::newFromText( $title );
641 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
644 return wfEscapeWikiText( $t->getPrefixedText() );
646 public static function fullpagenamee( $parser, $title = null ) {
647 $t = Title
::newFromText( $title );
648 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
651 return wfEscapeWikiText( $t->getPrefixedURL() );
653 public static function subpagename( $parser, $title = null ) {
654 $t = Title
::newFromText( $title );
655 if ( is_null( $t ) ) {
658 return wfEscapeWikiText( $t->getSubpageText() );
660 public static function subpagenamee( $parser, $title = null ) {
661 $t = Title
::newFromText( $title );
662 if ( is_null( $t ) ) {
665 return wfEscapeWikiText( $t->getSubpageUrlForm() );
667 public static function rootpagename( $parser, $title = null ) {
668 $t = Title
::newFromText( $title );
669 if ( is_null( $t ) ) {
672 return wfEscapeWikiText( $t->getRootText() );
674 public static function rootpagenamee( $parser, $title = null ) {
675 $t = Title
::newFromText( $title );
676 if ( is_null( $t ) ) {
679 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
681 public static function basepagename( $parser, $title = null ) {
682 $t = Title
::newFromText( $title );
683 if ( is_null( $t ) ) {
686 return wfEscapeWikiText( $t->getBaseText() );
688 public static function basepagenamee( $parser, $title = null ) {
689 $t = Title
::newFromText( $title );
690 if ( is_null( $t ) ) {
693 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
695 public static function talkpagename( $parser, $title = null ) {
696 $t = Title
::newFromText( $title );
697 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
700 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
702 public static function talkpagenamee( $parser, $title = null ) {
703 $t = Title
::newFromText( $title );
704 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
707 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
709 public static function subjectpagename( $parser, $title = null ) {
710 $t = Title
::newFromText( $title );
711 if ( is_null( $t ) ) {
714 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
716 public static function subjectpagenamee( $parser, $title = null ) {
717 $t = Title
::newFromText( $title );
718 if ( is_null( $t ) ) {
721 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
725 * Return the number of pages, files or subcats in the given category,
726 * or 0 if it's nonexistent. This is an expensive parser function and
727 * can't be called too many times per page.
728 * @param Parser $parser
729 * @param string $name
730 * @param string|null $arg1
731 * @param string|null $arg2
734 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
735 static $magicWords = null;
736 if ( is_null( $magicWords ) ) {
737 $magicWords = $parser->getMagicWordFactory()->newArray( [
738 'pagesincategory_all',
739 'pagesincategory_pages',
740 'pagesincategory_subcats',
741 'pagesincategory_files'
746 // split the given option to its variable
747 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
748 // {{pagesincategory:|raw[|type]}}
750 $type = $magicWords->matchStartToEnd( $arg2 );
752 // {{pagesincategory:[|type[|raw]]}}
753 $type = $magicWords->matchStartToEnd( $arg1 );
756 if ( !$type ) { // backward compatibility
757 $type = 'pagesincategory_all';
760 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
761 if ( !$title ) { # invalid title
762 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
764 $parser->getContentLanguage()->findVariantLink( $name, $title, true );
766 // Normalize name for cache
767 $name = $title->getDBkey();
769 if ( !isset( $cache[$name] ) ) {
770 $category = Category
::newFromTitle( $title );
772 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
773 if ( $parser->incrementExpensiveFunctionCount() ) {
774 // $allCount is the total number of cat members,
775 // not the count of how many members are normal pages.
776 $allCount = (int)$category->getPageCount();
777 $subcatCount = (int)$category->getSubcatCount();
778 $fileCount = (int)$category->getFileCount();
779 $pagesCount = $allCount - $subcatCount - $fileCount;
781 $cache[$name]['pagesincategory_all'] = $allCount;
782 $cache[$name]['pagesincategory_pages'] = $pagesCount;
783 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
784 $cache[$name]['pagesincategory_files'] = $fileCount;
787 $count = $cache[$name][$type];
788 return self
::formatRaw( $count, $raw, $parser->getFunctionLang() );
792 * Return the size of the given page, or 0 if it's nonexistent. This is an
793 * expensive parser function and can't be called too many times per page.
795 * @param Parser $parser
796 * @param string $page Name of page to check (Default: empty string)
797 * @param string|null $raw Should number be human readable with commas or just number
800 public static function pagesize( $parser, $page = '', $raw = null ) {
801 $title = Title
::newFromText( $page );
803 if ( !is_object( $title ) ) {
804 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
807 // fetch revision from cache/database and return the value
808 $rev = self
::getCachedRevisionObject( $parser, $title );
809 $length = $rev ?
$rev->getSize() : 0;
810 if ( $length === null ) {
811 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
814 return self
::formatRaw( $length, $raw, $parser->getFunctionLang() );
818 * Returns the requested protection level for the current page. This
819 * is an expensive parser function and can't be called too many times
820 * per page, unless the protection levels/expiries for the given title
821 * have already been retrieved
823 * @param Parser $parser
824 * @param string $type
825 * @param string $title
829 public static function protectionlevel( $parser, $type = '', $title = '' ) {
830 $titleObject = Title
::newFromText( $title );
831 if ( !( $titleObject instanceof Title
) ) {
832 $titleObject = $parser->mTitle
;
834 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
835 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
836 # Title::getRestrictions returns an array, its possible it may have
837 # multiple values in the future
838 return implode( ',', $restrictions );
844 * Returns the requested protection expiry for the current page. This
845 * is an expensive parser function and can't be called too many times
846 * per page, unless the protection levels/expiries for the given title
847 * have already been retrieved
849 * @param Parser $parser
850 * @param string $type
851 * @param string $title
855 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
856 $titleObject = Title
::newFromText( $title );
857 if ( !( $titleObject instanceof Title
) ) {
858 $titleObject = $parser->mTitle
;
860 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
861 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
862 // getRestrictionExpiry() returns false on invalid type; trying to
863 // match protectionlevel() function that returns empty string instead
864 if ( $expiry === false ) {
873 * Gives language names.
874 * @param Parser $parser
875 * @param string $code Language code (of which to get name)
876 * @param string $inLanguage Language code (in which to get name)
879 public static function language( $parser, $code = '', $inLanguage = '' ) {
880 $code = strtolower( $code );
881 $inLanguage = strtolower( $inLanguage );
882 $lang = Language
::fetchLanguageName( $code, $inLanguage );
883 return $lang !== '' ?
$lang : LanguageCode
::bcp47( $code );
887 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
888 * @param Parser $parser
889 * @param string $string
890 * @param string $length
891 * @param string $padding
892 * @param int $direction
895 public static function pad(
896 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
898 $padding = $parser->killMarkers( $padding );
899 $lengthOfPadding = mb_strlen( $padding );
900 if ( $lengthOfPadding == 0 ) {
904 # The remaining length to add counts down to 0 as padding is added
905 $length = min( (int)$length, 500 ) - mb_strlen( $string );
906 if ( $length <= 0 ) {
911 # $finalPadding is just $padding repeated enough times so that
912 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
914 while ( $length > 0 ) {
915 # If $length < $lengthofPadding, truncate $padding so we get the
916 # exact length desired.
917 $finalPadding .= mb_substr( $padding, 0, $length );
918 $length -= $lengthOfPadding;
921 if ( $direction == STR_PAD_LEFT
) {
922 return $finalPadding . $string;
924 return $string . $finalPadding;
928 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
929 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
932 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
933 return self
::pad( $parser, $string, $length, $padding );
937 * @param Parser $parser
938 * @param string $text
941 public static function anchorencode( $parser, $text ) {
942 $text = $parser->killMarkers( $text );
943 $section = (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
944 return Sanitizer
::safeEncodeAttribute( $section );
947 public static function special( $parser, $text ) {
948 list( $page, $subpage ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
949 resolveAlias( $text );
951 $title = SpecialPage
::getTitleFor( $page, $subpage );
952 return $title->getPrefixedText();
954 // unknown special page, just use the given text as its title, if at all possible
955 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
956 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
960 public static function speciale( $parser, $text ) {
961 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
965 * @param Parser $parser
966 * @param string $text The sortkey to use
967 * @param string $uarg Either "noreplace" or "noerror" (in en)
968 * both suppress errors, and noreplace does nothing if
969 * a default sortkey already exists.
972 public static function defaultsort( $parser, $text, $uarg = '' ) {
973 static $magicWords = null;
974 if ( is_null( $magicWords ) ) {
975 $magicWords = $parser->getMagicWordFactory()->newArray(
976 [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
978 $arg = $magicWords->matchStartToEnd( $uarg );
980 $text = trim( $text );
981 if ( strlen( $text ) == 0 ) {
984 $old = $parser->getCustomDefaultSort();
985 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
986 $parser->setDefaultSort( $text );
989 if ( $old === false ||
$old == $text ||
$arg ) {
992 $converter = $parser->getTargetLanguage()->getConverter();
993 return '<span class="error">' .
994 wfMessage( 'duplicate-defaultsort',
995 // Message should be parsed, but these params should only be escaped.
996 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
997 $converter->markNoConversion( wfEscapeWikiText( $text ) )
998 )->inContentLanguage()->text() .
1004 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
1005 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
1006 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
1008 * @param Parser $parser
1009 * @param string $name
1010 * @param string $argA
1011 * @param string $argB
1012 * @return array|string
1014 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1015 $file = wfFindFile( $name );
1017 if ( $argA == 'nowiki' ) {
1018 // {{filepath: | option [| size] }}
1020 $parsedWidthParam = Parser
::parseWidthParam( $argB );
1022 // {{filepath: [| size [|option]] }}
1023 $parsedWidthParam = Parser
::parseWidthParam( $argA );
1024 $isNowiki = ( $argB == 'nowiki' );
1028 $url = $file->getFullUrl();
1030 // If a size is requested...
1031 if ( count( $parsedWidthParam ) ) {
1032 $mto = $file->transform( $parsedWidthParam );
1034 if ( $mto && !$mto->isError() ) {
1035 // ... change the URL to point to a thumbnail.
1036 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1040 return [ $url, 'nowiki' => true ];
1049 * Parser function to extension tag adaptor
1050 * @param Parser $parser
1051 * @param PPFrame $frame
1052 * @param PPNode[] $args
1055 public static function tagObj( $parser, $frame, $args ) {
1056 if ( !count( $args ) ) {
1059 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1061 if ( count( $args ) ) {
1062 $inner = $frame->expand( array_shift( $args ) );
1068 foreach ( $args as $arg ) {
1069 $bits = $arg->splitArg();
1070 if ( strval( $bits['index'] ) === '' ) {
1071 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1072 $value = trim( $frame->expand( $bits['value'] ) );
1073 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1074 $value = $m[1] ??
'';
1076 $attributes[$name] = $value;
1080 $stripList = $parser->getStripList();
1081 if ( !in_array( $tagName, $stripList ) ) {
1082 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1084 foreach ( $attributes as $name => $value ) {
1085 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1087 if ( $inner === null ) {
1088 return "<$tagName$attrText/>";
1090 return "<$tagName$attrText>$inner</$tagName>";
1096 'attributes' => $attributes,
1097 'close' => "</$tagName>",
1099 return $parser->extensionSubstitution( $params, $frame );
1103 * Fetched the current revision of the given title and return this.
1104 * Will increment the expensive function count and
1105 * add a template link to get the value refreshed on changes.
1106 * For a given title, which is equal to the current parser title,
1107 * the revision object from the parser is used, when that is the current one
1109 * @param Parser $parser
1110 * @param Title $title
1114 private static function getCachedRevisionObject( $parser, $title = null ) {
1115 if ( is_null( $title ) ) {
1119 // Use the revision from the parser itself, when param is the current page
1120 // and the revision is the current one
1121 if ( $title->equals( $parser->getTitle() ) ) {
1122 $parserRev = $parser->getRevisionObject();
1123 if ( $parserRev && $parserRev->isCurrent() ) {
1124 // force reparse after edit with vary-revision flag
1125 $parser->getOutput()->setFlag( 'vary-revision' );
1126 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1131 // Normalize name for cache
1132 $page = $title->getPrefixedDBkey();
1134 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1135 && !$parser->incrementExpensiveFunctionCount() ) {
1138 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1139 $pageID = $rev ?
$rev->getPage() : 0;
1140 $revID = $rev ?
$rev->getId() : 0;
1142 // Register dependency in templatelinks
1143 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1149 * Get the pageid of a specified page
1150 * @param Parser $parser
1151 * @param string|null $title Title to get the pageid from
1152 * @return int|null|string
1155 public static function pageid( $parser, $title = null ) {
1156 $t = Title
::newFromText( $title );
1157 if ( is_null( $t ) ) {
1160 // Use title from parser to have correct pageid after edit
1161 if ( $t->equals( $parser->getTitle() ) ) {
1162 $t = $parser->getTitle();
1163 return $t->getArticleID();
1166 // These can't have ids
1167 if ( !$t->canExist() ||
$t->isExternal() ) {
1171 // Check the link cache, maybe something already looked it up.
1172 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1173 $pdbk = $t->getPrefixedDBkey();
1174 $id = $linkCache->getGoodLinkID( $pdbk );
1176 $parser->mOutput
->addLink( $t, $id );
1179 if ( $linkCache->isBadLink( $pdbk ) ) {
1180 $parser->mOutput
->addLink( $t, 0 );
1184 // We need to load it from the DB, so mark expensive
1185 if ( $parser->incrementExpensiveFunctionCount() ) {
1186 $id = $t->getArticleID();
1187 $parser->mOutput
->addLink( $t, $id );
1194 * Get the id from the last revision of a specified page.
1195 * @param Parser $parser
1196 * @param string|null $title Title to get the id from
1197 * @return int|null|string
1200 public static function revisionid( $parser, $title = null ) {
1201 $t = Title
::newFromText( $title );
1202 if ( is_null( $t ) ) {
1205 // fetch revision from cache/database and return the value
1206 $rev = self
::getCachedRevisionObject( $parser, $t );
1207 return $rev ?
$rev->getId() : '';
1211 * Get the day from the last revision of a specified page.
1212 * @param Parser $parser
1213 * @param string|null $title Title to get the day from
1217 public static function revisionday( $parser, $title = null ) {
1218 $t = Title
::newFromText( $title );
1219 if ( is_null( $t ) ) {
1222 // fetch revision from cache/database and return the value
1223 $rev = self
::getCachedRevisionObject( $parser, $t );
1224 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1228 * Get the day with leading zeros from the last revision of a specified page.
1229 * @param Parser $parser
1230 * @param string|null $title Title to get the day from
1234 public static function revisionday2( $parser, $title = null ) {
1235 $t = Title
::newFromText( $title );
1236 if ( is_null( $t ) ) {
1239 // fetch revision from cache/database and return the value
1240 $rev = self
::getCachedRevisionObject( $parser, $t );
1241 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1245 * Get the month with leading zeros from the last revision of a specified page.
1246 * @param Parser $parser
1247 * @param string|null $title Title to get the month from
1251 public static function revisionmonth( $parser, $title = null ) {
1252 $t = Title
::newFromText( $title );
1253 if ( is_null( $t ) ) {
1256 // fetch revision from cache/database and return the value
1257 $rev = self
::getCachedRevisionObject( $parser, $t );
1258 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1262 * Get the month from the last revision of a specified page.
1263 * @param Parser $parser
1264 * @param string|null $title Title to get the month from
1268 public static function revisionmonth1( $parser, $title = null ) {
1269 $t = Title
::newFromText( $title );
1270 if ( is_null( $t ) ) {
1273 // fetch revision from cache/database and return the value
1274 $rev = self
::getCachedRevisionObject( $parser, $t );
1275 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1279 * Get the year from the last revision of a specified page.
1280 * @param Parser $parser
1281 * @param string|null $title Title to get the year from
1285 public static function revisionyear( $parser, $title = null ) {
1286 $t = Title
::newFromText( $title );
1287 if ( is_null( $t ) ) {
1290 // fetch revision from cache/database and return the value
1291 $rev = self
::getCachedRevisionObject( $parser, $t );
1292 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1296 * Get the timestamp from the last revision of a specified page.
1297 * @param Parser $parser
1298 * @param string|null $title Title to get the timestamp from
1302 public static function revisiontimestamp( $parser, $title = null ) {
1303 $t = Title
::newFromText( $title );
1304 if ( is_null( $t ) ) {
1307 // fetch revision from cache/database and return the value
1308 $rev = self
::getCachedRevisionObject( $parser, $t );
1309 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1313 * Get the user from the last revision of a specified page.
1314 * @param Parser $parser
1315 * @param string|null $title Title to get the user from
1319 public static function revisionuser( $parser, $title = null ) {
1320 $t = Title
::newFromText( $title );
1321 if ( is_null( $t ) ) {
1324 // fetch revision from cache/database and return the value
1325 $rev = self
::getCachedRevisionObject( $parser, $t );
1326 return $rev ?
$rev->getUserText() : '';
1330 * Returns the sources of any cascading protection acting on a specified page.
1331 * Pages will not return their own title unless they transclude themselves.
1332 * This is an expensive parser function and can't be called too many times per page,
1333 * unless cascading protection sources for the page have already been loaded.
1335 * @param Parser $parser
1336 * @param string $title
1341 public static function cascadingsources( $parser, $title = '' ) {
1342 $titleObject = Title
::newFromText( $title );
1343 if ( !( $titleObject instanceof Title
) ) {
1344 $titleObject = $parser->mTitle
;
1346 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1347 ||
$parser->incrementExpensiveFunctionCount()
1350 $sources = $titleObject->getCascadeProtectionSources();
1351 foreach ( $sources[0] as $sourceTitle ) {
1352 $names[] = $sourceTitle->getPrefixedText();
1354 return implode( '|', $names );