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 ) ) {
174 $magicWords = new MagicWordArray( [ 'url_path', 'url_query', 'url_wiki' ] );
176 switch ( $magicWords->matchStartToEnd( $arg ) ) {
177 // Encode as though it's a wiki page, '_' for ' '.
179 $func = 'wfUrlencode';
180 $s = str_replace( ' ', '_', $s );
183 // Encode for an HTTP Path, '%20' for ' '.
185 $func = 'rawurlencode';
188 // Encode for HTTP query, '+' for ' '.
193 // See T105242, where the choice to kill markers and various
194 // other options were discussed.
195 return $func( $parser->killMarkers( $s ) );
198 public static function lcfirst( $parser, $s = '' ) {
200 return $wgContLang->lcfirst( $s );
203 public static function ucfirst( $parser, $s = '' ) {
205 return $wgContLang->ucfirst( $s );
209 * @param Parser $parser
213 public static function lc( $parser, $s = '' ) {
215 return $parser->markerSkipCallback( $s, [ $wgContLang, 'lc' ] );
219 * @param Parser $parser
223 public static function uc( $parser, $s = '' ) {
225 return $parser->markerSkipCallback( $s, [ $wgContLang, 'uc' ] );
228 public static function localurl( $parser, $s = '', $arg = null ) {
229 return self
::urlFunction( 'getLocalURL', $s, $arg );
232 public static function localurle( $parser, $s = '', $arg = null ) {
233 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
234 if ( !is_string( $temp ) ) {
237 return htmlspecialchars( $temp );
241 public static function fullurl( $parser, $s = '', $arg = null ) {
242 return self
::urlFunction( 'getFullURL', $s, $arg );
245 public static function fullurle( $parser, $s = '', $arg = null ) {
246 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
247 if ( !is_string( $temp ) ) {
250 return htmlspecialchars( $temp );
254 public static function canonicalurl( $parser, $s = '', $arg = null ) {
255 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
258 public static function canonicalurle( $parser, $s = '', $arg = null ) {
259 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
260 if ( !is_string( $temp ) ) {
263 return htmlspecialchars( $temp );
267 public static function urlFunction( $func, $s = '', $arg = null ) {
268 $title = Title
::newFromText( $s );
269 # Due to order of execution of a lot of bits, the values might be encoded
270 # before arriving here; if that's true, then the title can't be created
271 # and the variable will fail. If we can't get a decent title from the first
272 # attempt, url-decode and try for a second.
273 if ( is_null( $title ) ) {
274 $title = Title
::newFromURL( urldecode( $s ) );
276 if ( !is_null( $title ) ) {
277 # Convert NS_MEDIA -> NS_FILE
278 if ( $title->inNamespace( NS_MEDIA
) ) {
279 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
281 if ( !is_null( $arg ) ) {
282 $text = $title->$func( $arg );
284 $text = $title->$func();
288 return [ 'found' => false ];
293 * @param Parser $parser
295 * @param string|null $arg
298 public static function formatnum( $parser, $num = '', $arg = null ) {
299 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg ) ) {
300 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
302 self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'nocommafysuffix', $arg )
304 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
306 $func = [ $parser->getFunctionLang(), 'formatNum' ];
308 return $parser->markerSkipCallback( $num, $func );
312 * @param Parser $parser
313 * @param string $case
314 * @param string $word
317 public static function grammar( $parser, $case = '', $word = '' ) {
318 $word = $parser->killMarkers( $word );
319 return $parser->getFunctionLang()->convertGrammar( $word, $case );
323 * @param Parser $parser
324 * @param string $username
327 public static function gender( $parser, $username ) {
328 $forms = array_slice( func_get_args(), 2 );
330 // Some shortcuts to avoid loading user data unnecessarily
331 if ( count( $forms ) === 0 ) {
333 } elseif ( count( $forms ) === 1 ) {
337 $username = trim( $username );
340 $gender = User
::getDefaultOption( 'gender' );
342 // allow prefix and normalize (e.g. "*foo" -> "*foo" ).
343 $title = Title
::newFromText( $username, NS_USER
);
345 if ( $title && $title->inNamespace( NS_USER
) ) {
346 $username = $title->getText();
349 // check parameter, or use the ParserOptions if in interface message
350 $user = User
::newFromName( $username );
351 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
353 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
354 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
355 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
357 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
362 * @param Parser $parser
363 * @param string $text
366 public static function plural( $parser, $text = '' ) {
367 $forms = array_slice( func_get_args(), 2 );
368 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
369 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
370 return $parser->getFunctionLang()->convertPlural( $text, $forms );
374 * @param Parser $parser
375 * @param string $text
378 public static function bidi( $parser, $text = '' ) {
379 return $parser->getFunctionLang()->embedBidi( $text );
383 * Override the title of the page when viewed, provided we've been given a
384 * title which will normalise to the canonical title
386 * @param Parser $parser Parent parser
387 * @param string $text Desired title text
388 * @param string $uarg
391 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
392 global $wgRestrictDisplayTitle;
394 static $magicWords = null;
395 if ( is_null( $magicWords ) ) {
396 $magicWords = new MagicWordArray( [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
398 $arg = $magicWords->matchStartToEnd( $uarg );
400 // parse a limited subset of wiki markup (just the single quote items)
401 $text = $parser->doQuotes( $text );
403 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
404 $text = $parser->killMarkers( $text );
406 // list of disallowed tags for DISPLAYTITLE
407 // these will be escaped even though they are allowed in normal wiki text
408 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
409 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
411 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
412 if ( $wgRestrictDisplayTitle ) {
413 $htmlTagsCallback = function ( &$params ) {
414 $decoded = Sanitizer
::decodeTagAttributes( $params );
416 if ( isset( $decoded['style'] ) ) {
417 // this is called later anyway, but we need it right now for the regexes below to be safe
418 // calling it twice doesn't hurt
419 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
421 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
422 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
426 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
429 $htmlTagsCallback = null;
432 // only requested titles that normalize to the actual title are allowed through
433 // if $wgRestrictDisplayTitle is true (it is by default)
434 // mimic the escaping process that occurs in OutputPage::setPageTitle
435 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
442 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
444 if ( !$wgRestrictDisplayTitle ||
445 ( $title instanceof Title
446 && !$title->hasFragment()
447 && $title->equals( $parser->mTitle
) )
449 $old = $parser->mOutput
->getProperty( 'displaytitle' );
450 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
451 $parser->mOutput
->setDisplayTitle( $text );
453 if ( $old !== false && $old !== $text && !$arg ) {
454 $converter = $parser->getTargetLanguage()->getConverter();
455 return '<span class="error">' .
456 wfMessage( 'duplicate-displaytitle',
457 // Message should be parsed, but these params should only be escaped.
458 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
459 $converter->markNoConversion( wfEscapeWikiText( $text ) )
460 )->inContentLanguage()->text() .
466 $converter = $parser->getTargetLanguage()->getConverter();
467 $parser->getOutput()->addWarning(
468 wfMessage( 'restricted-displaytitle',
469 // Message should be parsed, but this param should only be escaped.
470 $converter->markNoConversion( wfEscapeWikiText( $text ) )
473 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
478 * Matches the given value against the value of given magic word
480 * @param MagicWordFactory $magicWordFactory A factory to get the word from, e.g., from
481 * $parser->getMagicWordFactory()
482 * @param string $magicword Magic word key
483 * @param string $value Value to match
484 * @return bool True on successful match
486 private static function matchAgainstMagicword(
487 MagicWordFactory
$magicWordFactory, $magicword, $value
489 $value = trim( strval( $value ) );
490 if ( $value === '' ) {
493 $mwObject = $magicWordFactory->get( $magicword );
494 return $mwObject->matchStartToEnd( $value );
498 * Formats a number according to a language.
500 * @param int|float $num
502 * @param Language|StubUserLang $language
503 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
506 public static function formatRaw(
507 $num, $raw, $language, MagicWordFactory
$magicWordFactory = null
509 if ( $raw !== null && !$magicWordFactory ) {
510 $magicWordFactory = MediaWikiServices
::getInstance()->getMagicWordFactory();
513 $raw !== null && self
::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw )
517 return $language->formatNum( $num );
521 public static function numberofpages( $parser, $raw = null ) {
522 return self
::formatRaw( SiteStats
::pages(), $raw, $parser->getFunctionLang() );
525 public static function numberofusers( $parser, $raw = null ) {
526 return self
::formatRaw( SiteStats
::users(), $raw, $parser->getFunctionLang() );
528 public static function numberofactiveusers( $parser, $raw = null ) {
529 return self
::formatRaw( SiteStats
::activeUsers(), $raw, $parser->getFunctionLang() );
532 public static function numberofarticles( $parser, $raw = null ) {
533 return self
::formatRaw( SiteStats
::articles(), $raw, $parser->getFunctionLang() );
536 public static function numberoffiles( $parser, $raw = null ) {
537 return self
::formatRaw( SiteStats
::images(), $raw, $parser->getFunctionLang() );
540 public static function numberofadmins( $parser, $raw = null ) {
541 return self
::formatRaw(
542 SiteStats
::numberingroup( 'sysop' ),
544 $parser->getFunctionLang()
548 public static function numberofedits( $parser, $raw = null ) {
549 return self
::formatRaw( SiteStats
::edits(), $raw, $parser->getFunctionLang() );
552 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
553 return self
::formatRaw(
554 SiteStats
::pagesInNs( intval( $namespace ) ),
556 $parser->getFunctionLang()
559 public static function numberingroup( $parser, $name = '', $raw = null ) {
560 return self
::formatRaw(
561 SiteStats
::numberingroup( strtolower( $name ) ),
563 $parser->getFunctionLang()
568 * Given a title, return the namespace name that would be given by the
569 * corresponding magic word
570 * Note: function name changed to "mwnamespace" rather than "namespace"
571 * to not break PHP 5.3
572 * @param Parser $parser
573 * @param string|null $title
574 * @return mixed|string
576 public static function mwnamespace( $parser, $title = null ) {
577 $t = Title
::newFromText( $title );
578 if ( is_null( $t ) ) {
581 return str_replace( '_', ' ', $t->getNsText() );
583 public static function namespacee( $parser, $title = null ) {
584 $t = Title
::newFromText( $title );
585 if ( is_null( $t ) ) {
588 return wfUrlencode( $t->getNsText() );
590 public static function namespacenumber( $parser, $title = null ) {
591 $t = Title
::newFromText( $title );
592 if ( is_null( $t ) ) {
595 return $t->getNamespace();
597 public static function talkspace( $parser, $title = null ) {
598 $t = Title
::newFromText( $title );
599 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
602 return str_replace( '_', ' ', $t->getTalkNsText() );
604 public static function talkspacee( $parser, $title = null ) {
605 $t = Title
::newFromText( $title );
606 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
609 return wfUrlencode( $t->getTalkNsText() );
611 public static function subjectspace( $parser, $title = null ) {
612 $t = Title
::newFromText( $title );
613 if ( is_null( $t ) ) {
616 return str_replace( '_', ' ', $t->getSubjectNsText() );
618 public static function subjectspacee( $parser, $title = null ) {
619 $t = Title
::newFromText( $title );
620 if ( is_null( $t ) ) {
623 return wfUrlencode( $t->getSubjectNsText() );
627 * Functions to get and normalize pagenames, corresponding to the magic words
629 * @param Parser $parser
630 * @param string|null $title
633 public static function pagename( $parser, $title = null ) {
634 $t = Title
::newFromText( $title );
635 if ( is_null( $t ) ) {
638 return wfEscapeWikiText( $t->getText() );
640 public static function pagenamee( $parser, $title = null ) {
641 $t = Title
::newFromText( $title );
642 if ( is_null( $t ) ) {
645 return wfEscapeWikiText( $t->getPartialURL() );
647 public static function fullpagename( $parser, $title = null ) {
648 $t = Title
::newFromText( $title );
649 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
652 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() );
661 public static function subpagename( $parser, $title = null ) {
662 $t = Title
::newFromText( $title );
663 if ( is_null( $t ) ) {
666 return wfEscapeWikiText( $t->getSubpageText() );
668 public static function subpagenamee( $parser, $title = null ) {
669 $t = Title
::newFromText( $title );
670 if ( is_null( $t ) ) {
673 return wfEscapeWikiText( $t->getSubpageUrlForm() );
675 public static function rootpagename( $parser, $title = null ) {
676 $t = Title
::newFromText( $title );
677 if ( is_null( $t ) ) {
680 return wfEscapeWikiText( $t->getRootText() );
682 public static function rootpagenamee( $parser, $title = null ) {
683 $t = Title
::newFromText( $title );
684 if ( is_null( $t ) ) {
687 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
689 public static function basepagename( $parser, $title = null ) {
690 $t = Title
::newFromText( $title );
691 if ( is_null( $t ) ) {
694 return wfEscapeWikiText( $t->getBaseText() );
696 public static function basepagenamee( $parser, $title = null ) {
697 $t = Title
::newFromText( $title );
698 if ( is_null( $t ) ) {
701 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
703 public static function talkpagename( $parser, $title = null ) {
704 $t = Title
::newFromText( $title );
705 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
708 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
710 public static function talkpagenamee( $parser, $title = null ) {
711 $t = Title
::newFromText( $title );
712 if ( is_null( $t ) ||
!$t->canHaveTalkPage() ) {
715 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
717 public static function subjectpagename( $parser, $title = null ) {
718 $t = Title
::newFromText( $title );
719 if ( is_null( $t ) ) {
722 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
724 public static function subjectpagenamee( $parser, $title = null ) {
725 $t = Title
::newFromText( $title );
726 if ( is_null( $t ) ) {
729 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
733 * Return the number of pages, files or subcats in the given category,
734 * or 0 if it's nonexistent. This is an expensive parser function and
735 * can't be called too many times per page.
736 * @param Parser $parser
737 * @param string $name
738 * @param string|null $arg1
739 * @param string|null $arg2
742 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
744 static $magicWords = null;
745 if ( is_null( $magicWords ) ) {
746 $magicWords = new MagicWordArray( [
747 'pagesincategory_all',
748 'pagesincategory_pages',
749 'pagesincategory_subcats',
750 'pagesincategory_files'
755 // split the given option to its variable
756 if ( self
::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
757 // {{pagesincategory:|raw[|type]}}
759 $type = $magicWords->matchStartToEnd( $arg2 );
761 // {{pagesincategory:[|type[|raw]]}}
762 $type = $magicWords->matchStartToEnd( $arg1 );
765 if ( !$type ) { // backward compatibility
766 $type = 'pagesincategory_all';
769 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
770 if ( !$title ) { # invalid title
771 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
773 $wgContLang->findVariantLink( $name, $title, true );
775 // Normalize name for cache
776 $name = $title->getDBkey();
778 if ( !isset( $cache[$name] ) ) {
779 $category = Category
::newFromTitle( $title );
781 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
782 if ( $parser->incrementExpensiveFunctionCount() ) {
783 // $allCount is the total number of cat members,
784 // not the count of how many members are normal pages.
785 $allCount = (int)$category->getPageCount();
786 $subcatCount = (int)$category->getSubcatCount();
787 $fileCount = (int)$category->getFileCount();
788 $pagesCount = $allCount - $subcatCount - $fileCount;
790 $cache[$name]['pagesincategory_all'] = $allCount;
791 $cache[$name]['pagesincategory_pages'] = $pagesCount;
792 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
793 $cache[$name]['pagesincategory_files'] = $fileCount;
796 $count = $cache[$name][$type];
797 return self
::formatRaw( $count, $raw, $parser->getFunctionLang() );
801 * Return the size of the given page, or 0 if it's nonexistent. This is an
802 * expensive parser function and can't be called too many times per page.
804 * @param Parser $parser
805 * @param string $page Name of page to check (Default: empty string)
806 * @param string|null $raw Should number be human readable with commas or just number
809 public static function pagesize( $parser, $page = '', $raw = null ) {
810 $title = Title
::newFromText( $page );
812 if ( !is_object( $title ) ) {
813 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
816 // fetch revision from cache/database and return the value
817 $rev = self
::getCachedRevisionObject( $parser, $title );
818 $length = $rev ?
$rev->getSize() : 0;
819 if ( $length === null ) {
820 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
823 return self
::formatRaw( $length, $raw, $parser->getFunctionLang() );
827 * Returns the requested protection level for the current page. This
828 * is an expensive parser function and can't be called too many times
829 * per page, unless the protection levels/expiries for the given title
830 * have already been retrieved
832 * @param Parser $parser
833 * @param string $type
834 * @param string $title
838 public static function protectionlevel( $parser, $type = '', $title = '' ) {
839 $titleObject = Title
::newFromText( $title );
840 if ( !( $titleObject instanceof Title
) ) {
841 $titleObject = $parser->mTitle
;
843 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
844 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
845 # Title::getRestrictions returns an array, its possible it may have
846 # multiple values in the future
847 return implode( ',', $restrictions );
853 * Returns the requested protection expiry for the current page. This
854 * is an expensive parser function and can't be called too many times
855 * per page, unless the protection levels/expiries for the given title
856 * have already been retrieved
858 * @param Parser $parser
859 * @param string $type
860 * @param string $title
864 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
865 $titleObject = Title
::newFromText( $title );
866 if ( !( $titleObject instanceof Title
) ) {
867 $titleObject = $parser->mTitle
;
869 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
870 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
871 // getRestrictionExpiry() returns false on invalid type; trying to
872 // match protectionlevel() function that returns empty string instead
873 if ( $expiry === false ) {
882 * Gives language names.
883 * @param Parser $parser
884 * @param string $code Language code (of which to get name)
885 * @param string $inLanguage Language code (in which to get name)
888 public static function language( $parser, $code = '', $inLanguage = '' ) {
889 $code = strtolower( $code );
890 $inLanguage = strtolower( $inLanguage );
891 $lang = Language
::fetchLanguageName( $code, $inLanguage );
892 return $lang !== '' ?
$lang : LanguageCode
::bcp47( $code );
896 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
897 * @param Parser $parser
898 * @param string $string
899 * @param string $length
900 * @param string $padding
901 * @param int $direction
904 public static function pad(
905 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
907 $padding = $parser->killMarkers( $padding );
908 $lengthOfPadding = mb_strlen( $padding );
909 if ( $lengthOfPadding == 0 ) {
913 # The remaining length to add counts down to 0 as padding is added
914 $length = min( (int)$length, 500 ) - mb_strlen( $string );
915 if ( $length <= 0 ) {
920 # $finalPadding is just $padding repeated enough times so that
921 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
923 while ( $length > 0 ) {
924 # If $length < $lengthofPadding, truncate $padding so we get the
925 # exact length desired.
926 $finalPadding .= mb_substr( $padding, 0, $length );
927 $length -= $lengthOfPadding;
930 if ( $direction == STR_PAD_LEFT
) {
931 return $finalPadding . $string;
933 return $string . $finalPadding;
937 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
938 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
941 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
942 return self
::pad( $parser, $string, $length, $padding );
946 * @param Parser $parser
947 * @param string $text
950 public static function anchorencode( $parser, $text ) {
951 $text = $parser->killMarkers( $text );
952 $section = (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
953 return Sanitizer
::safeEncodeAttribute( $section );
956 public static function special( $parser, $text ) {
957 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
959 $title = SpecialPage
::getTitleFor( $page, $subpage );
960 return $title->getPrefixedText();
962 // unknown special page, just use the given text as its title, if at all possible
963 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
964 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
968 public static function speciale( $parser, $text ) {
969 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
973 * @param Parser $parser
974 * @param string $text The sortkey to use
975 * @param string $uarg Either "noreplace" or "noerror" (in en)
976 * both suppress errors, and noreplace does nothing if
977 * a default sortkey already exists.
980 public static function defaultsort( $parser, $text, $uarg = '' ) {
981 static $magicWords = null;
982 if ( is_null( $magicWords ) ) {
983 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
985 $arg = $magicWords->matchStartToEnd( $uarg );
987 $text = trim( $text );
988 if ( strlen( $text ) == 0 ) {
991 $old = $parser->getCustomDefaultSort();
992 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
993 $parser->setDefaultSort( $text );
996 if ( $old === false ||
$old == $text ||
$arg ) {
999 $converter = $parser->getTargetLanguage()->getConverter();
1000 return '<span class="error">' .
1001 wfMessage( 'duplicate-defaultsort',
1002 // Message should be parsed, but these params should only be escaped.
1003 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
1004 $converter->markNoConversion( wfEscapeWikiText( $text ) )
1005 )->inContentLanguage()->text() .
1011 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
1012 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
1013 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
1015 * @param Parser $parser
1016 * @param string $name
1017 * @param string $argA
1018 * @param string $argB
1019 * @return array|string
1021 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1022 $file = wfFindFile( $name );
1024 if ( $argA == 'nowiki' ) {
1025 // {{filepath: | option [| size] }}
1027 $parsedWidthParam = Parser
::parseWidthParam( $argB );
1029 // {{filepath: [| size [|option]] }}
1030 $parsedWidthParam = Parser
::parseWidthParam( $argA );
1031 $isNowiki = ( $argB == 'nowiki' );
1035 $url = $file->getFullUrl();
1037 // If a size is requested...
1038 if ( count( $parsedWidthParam ) ) {
1039 $mto = $file->transform( $parsedWidthParam );
1041 if ( $mto && !$mto->isError() ) {
1042 // ... change the URL to point to a thumbnail.
1043 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1047 return [ $url, 'nowiki' => true ];
1056 * Parser function to extension tag adaptor
1057 * @param Parser $parser
1058 * @param PPFrame $frame
1059 * @param PPNode[] $args
1062 public static function tagObj( $parser, $frame, $args ) {
1063 if ( !count( $args ) ) {
1066 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1068 if ( count( $args ) ) {
1069 $inner = $frame->expand( array_shift( $args ) );
1075 foreach ( $args as $arg ) {
1076 $bits = $arg->splitArg();
1077 if ( strval( $bits['index'] ) === '' ) {
1078 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1079 $value = trim( $frame->expand( $bits['value'] ) );
1080 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1081 $value = $m[1] ??
'';
1083 $attributes[$name] = $value;
1087 $stripList = $parser->getStripList();
1088 if ( !in_array( $tagName, $stripList ) ) {
1089 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1091 foreach ( $attributes as $name => $value ) {
1092 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1094 if ( $inner === null ) {
1095 return "<$tagName$attrText/>";
1097 return "<$tagName$attrText>$inner</$tagName>";
1103 'attributes' => $attributes,
1104 'close' => "</$tagName>",
1106 return $parser->extensionSubstitution( $params, $frame );
1110 * Fetched the current revision of the given title and return this.
1111 * Will increment the expensive function count and
1112 * add a template link to get the value refreshed on changes.
1113 * For a given title, which is equal to the current parser title,
1114 * the revision object from the parser is used, when that is the current one
1116 * @param Parser $parser
1117 * @param Title $title
1121 private static function getCachedRevisionObject( $parser, $title = null ) {
1122 if ( is_null( $title ) ) {
1126 // Use the revision from the parser itself, when param is the current page
1127 // and the revision is the current one
1128 if ( $title->equals( $parser->getTitle() ) ) {
1129 $parserRev = $parser->getRevisionObject();
1130 if ( $parserRev && $parserRev->isCurrent() ) {
1131 // force reparse after edit with vary-revision flag
1132 $parser->getOutput()->setFlag( 'vary-revision' );
1133 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1138 // Normalize name for cache
1139 $page = $title->getPrefixedDBkey();
1141 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1142 && !$parser->incrementExpensiveFunctionCount() ) {
1145 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1146 $pageID = $rev ?
$rev->getPage() : 0;
1147 $revID = $rev ?
$rev->getId() : 0;
1149 // Register dependency in templatelinks
1150 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1156 * Get the pageid of a specified page
1157 * @param Parser $parser
1158 * @param string|null $title Title to get the pageid from
1159 * @return int|null|string
1162 public static function pageid( $parser, $title = null ) {
1163 $t = Title
::newFromText( $title );
1164 if ( is_null( $t ) ) {
1167 // Use title from parser to have correct pageid after edit
1168 if ( $t->equals( $parser->getTitle() ) ) {
1169 $t = $parser->getTitle();
1170 return $t->getArticleID();
1173 // These can't have ids
1174 if ( !$t->canExist() ||
$t->isExternal() ) {
1178 // Check the link cache, maybe something already looked it up.
1179 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1180 $pdbk = $t->getPrefixedDBkey();
1181 $id = $linkCache->getGoodLinkID( $pdbk );
1183 $parser->mOutput
->addLink( $t, $id );
1186 if ( $linkCache->isBadLink( $pdbk ) ) {
1187 $parser->mOutput
->addLink( $t, 0 );
1191 // We need to load it from the DB, so mark expensive
1192 if ( $parser->incrementExpensiveFunctionCount() ) {
1193 $id = $t->getArticleID();
1194 $parser->mOutput
->addLink( $t, $id );
1201 * Get the id from the last revision of a specified page.
1202 * @param Parser $parser
1203 * @param string|null $title Title to get the id from
1204 * @return int|null|string
1207 public static function revisionid( $parser, $title = null ) {
1208 $t = Title
::newFromText( $title );
1209 if ( is_null( $t ) ) {
1212 // fetch revision from cache/database and return the value
1213 $rev = self
::getCachedRevisionObject( $parser, $t );
1214 return $rev ?
$rev->getId() : '';
1218 * Get the day from the last revision of a specified page.
1219 * @param Parser $parser
1220 * @param string|null $title Title to get the day from
1224 public static function revisionday( $parser, $title = null ) {
1225 $t = Title
::newFromText( $title );
1226 if ( is_null( $t ) ) {
1229 // fetch revision from cache/database and return the value
1230 $rev = self
::getCachedRevisionObject( $parser, $t );
1231 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1235 * Get the day with leading zeros from the last revision of a specified page.
1236 * @param Parser $parser
1237 * @param string|null $title Title to get the day from
1241 public static function revisionday2( $parser, $title = null ) {
1242 $t = Title
::newFromText( $title );
1243 if ( is_null( $t ) ) {
1246 // fetch revision from cache/database and return the value
1247 $rev = self
::getCachedRevisionObject( $parser, $t );
1248 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1252 * Get the month with leading zeros from the last revision of a specified page.
1253 * @param Parser $parser
1254 * @param string|null $title Title to get the month from
1258 public static function revisionmonth( $parser, $title = null ) {
1259 $t = Title
::newFromText( $title );
1260 if ( is_null( $t ) ) {
1263 // fetch revision from cache/database and return the value
1264 $rev = self
::getCachedRevisionObject( $parser, $t );
1265 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1269 * Get the month from the last revision of a specified page.
1270 * @param Parser $parser
1271 * @param string|null $title Title to get the month from
1275 public static function revisionmonth1( $parser, $title = null ) {
1276 $t = Title
::newFromText( $title );
1277 if ( is_null( $t ) ) {
1280 // fetch revision from cache/database and return the value
1281 $rev = self
::getCachedRevisionObject( $parser, $t );
1282 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1286 * Get the year from the last revision of a specified page.
1287 * @param Parser $parser
1288 * @param string|null $title Title to get the year from
1292 public static function revisionyear( $parser, $title = null ) {
1293 $t = Title
::newFromText( $title );
1294 if ( is_null( $t ) ) {
1297 // fetch revision from cache/database and return the value
1298 $rev = self
::getCachedRevisionObject( $parser, $t );
1299 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1303 * Get the timestamp from the last revision of a specified page.
1304 * @param Parser $parser
1305 * @param string|null $title Title to get the timestamp from
1309 public static function revisiontimestamp( $parser, $title = null ) {
1310 $t = Title
::newFromText( $title );
1311 if ( is_null( $t ) ) {
1314 // fetch revision from cache/database and return the value
1315 $rev = self
::getCachedRevisionObject( $parser, $t );
1316 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1320 * Get the user from the last revision of a specified page.
1321 * @param Parser $parser
1322 * @param string|null $title Title to get the user from
1326 public static function revisionuser( $parser, $title = null ) {
1327 $t = Title
::newFromText( $title );
1328 if ( is_null( $t ) ) {
1331 // fetch revision from cache/database and return the value
1332 $rev = self
::getCachedRevisionObject( $parser, $t );
1333 return $rev ?
$rev->getUserText() : '';
1337 * Returns the sources of any cascading protection acting on a specified page.
1338 * Pages will not return their own title unless they transclude themselves.
1339 * This is an expensive parser function and can't be called too many times per page,
1340 * unless cascading protection sources for the page have already been loaded.
1342 * @param Parser $parser
1343 * @param string $title
1348 public static function cascadingsources( $parser, $title = '' ) {
1349 $titleObject = Title
::newFromText( $title );
1350 if ( !( $titleObject instanceof Title
) ) {
1351 $titleObject = $parser->mTitle
;
1353 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1354 ||
$parser->incrementExpensiveFunctionCount()
1357 $sources = $titleObject->getCascadeProtectionSources();
1358 foreach ( $sources[0] as $sourceTitle ) {
1359 $names[] = $sourceTitle->getPrefixedText();
1361 return implode( '|', $names );