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 $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 $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
298 public static function formatnum( $parser, $num = '', $arg = null ) {
299 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
300 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
301 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
302 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
304 $func = [ $parser->getFunctionLang(), 'formatNum' ];
306 return $parser->markerSkipCallback( $num, $func );
310 * @param Parser $parser
311 * @param string $case
312 * @param string $word
315 public static function grammar( $parser, $case = '', $word = '' ) {
316 $word = $parser->killMarkers( $word );
317 return $parser->getFunctionLang()->convertGrammar( $word, $case );
321 * @param Parser $parser
322 * @param string $username
325 public static function gender( $parser, $username ) {
326 $forms = array_slice( func_get_args(), 2 );
328 // Some shortcuts to avoid loading user data unnecessarily
329 if ( count( $forms ) === 0 ) {
331 } elseif ( count( $forms ) === 1 ) {
335 $username = trim( $username );
338 $gender = User
::getDefaultOption( 'gender' );
341 $title = Title
::newFromText( $username );
343 if ( $title && $title->inNamespace( NS_USER
) ) {
344 $username = $title->getText();
347 // check parameter, or use the ParserOptions if in interface message
348 $user = User
::newFromName( $username );
349 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
351 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
352 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
353 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
355 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
360 * @param Parser $parser
361 * @param string $text
364 public static function plural( $parser, $text = '' ) {
365 $forms = array_slice( func_get_args(), 2 );
366 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
367 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
368 return $parser->getFunctionLang()->convertPlural( $text, $forms );
372 * @param Parser $parser
373 * @param string $text
376 public static function bidi( $parser, $text = '' ) {
377 return $parser->getFunctionLang()->embedBidi( $text );
381 * Override the title of the page when viewed, provided we've been given a
382 * title which will normalise to the canonical title
384 * @param Parser $parser Parent parser
385 * @param string $text Desired title text
386 * @param string $uarg
389 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
390 global $wgRestrictDisplayTitle;
392 static $magicWords = null;
393 if ( is_null( $magicWords ) ) {
394 $magicWords = new MagicWordArray( [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
396 $arg = $magicWords->matchStartToEnd( $uarg );
398 // parse a limited subset of wiki markup (just the single quote items)
399 $text = $parser->doQuotes( $text );
401 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
402 $text = $parser->killMarkers( $text );
404 // list of disallowed tags for DISPLAYTITLE
405 // these will be escaped even though they are allowed in normal wiki text
406 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
407 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
409 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
410 if ( $wgRestrictDisplayTitle ) {
411 $htmlTagsCallback = function ( &$params ) {
412 $decoded = Sanitizer
::decodeTagAttributes( $params );
414 if ( isset( $decoded['style'] ) ) {
415 // this is called later anyway, but we need it right now for the regexes below to be safe
416 // calling it twice doesn't hurt
417 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
419 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
420 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
424 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
427 $htmlTagsCallback = null;
430 // only requested titles that normalize to the actual title are allowed through
431 // if $wgRestrictDisplayTitle is true (it is by default)
432 // mimic the escaping process that occurs in OutputPage::setPageTitle
433 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
440 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
442 if ( !$wgRestrictDisplayTitle ||
443 ( $title instanceof Title
444 && !$title->hasFragment()
445 && $title->equals( $parser->mTitle
) )
447 $old = $parser->mOutput
->getProperty( 'displaytitle' );
448 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
449 $parser->mOutput
->setDisplayTitle( $text );
451 if ( $old !== false && $old !== $text && !$arg ) {
452 $converter = $parser->getConverterLanguage()->getConverter();
453 return '<span class="error">' .
454 wfMessage( 'duplicate-displaytitle',
455 // Message should be parsed, but these params should only be escaped.
456 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
457 $converter->markNoConversion( wfEscapeWikiText( $text ) )
458 )->inContentLanguage()->text() .
464 $converter = $parser->getConverterLanguage()->getConverter();
465 $parser->getOutput()->addWarning(
466 wfMessage( 'restricted-displaytitle',
467 // Message should be parsed, but this param should only be escaped.
468 $converter->markNoConversion( wfEscapeWikiText( $text ) )
471 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
476 * Matches the given value against the value of given magic word
478 * @param string $magicword Magic word key
479 * @param string $value Value to match
480 * @return bool True on successful match
482 private static function matchAgainstMagicword( $magicword, $value ) {
483 $value = trim( strval( $value ) );
484 if ( $value === '' ) {
487 $mwObject = MagicWord
::get( $magicword );
488 return $mwObject->matchStartToEnd( $value );
492 * Formats a number according to a language.
494 * @param int|float $num
496 * @param Language|StubUserLang $language
499 public static function formatRaw( $num, $raw, $language ) {
500 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
503 return $language->formatNum( $num );
507 public static function numberofpages( $parser, $raw = null ) {
508 return self
::formatRaw( SiteStats
::pages(), $raw, $parser->getFunctionLang() );
511 public static function numberofusers( $parser, $raw = null ) {
512 return self
::formatRaw( SiteStats
::users(), $raw, $parser->getFunctionLang() );
514 public static function numberofactiveusers( $parser, $raw = null ) {
515 return self
::formatRaw( SiteStats
::activeUsers(), $raw, $parser->getFunctionLang() );
518 public static function numberofarticles( $parser, $raw = null ) {
519 return self
::formatRaw( SiteStats
::articles(), $raw, $parser->getFunctionLang() );
522 public static function numberoffiles( $parser, $raw = null ) {
523 return self
::formatRaw( SiteStats
::images(), $raw, $parser->getFunctionLang() );
526 public static function numberofadmins( $parser, $raw = null ) {
527 return self
::formatRaw(
528 SiteStats
::numberingroup( 'sysop' ),
530 $parser->getFunctionLang()
534 public static function numberofedits( $parser, $raw = null ) {
535 return self
::formatRaw( SiteStats
::edits(), $raw, $parser->getFunctionLang() );
538 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
539 return self
::formatRaw(
540 SiteStats
::pagesInNs( intval( $namespace ) ),
542 $parser->getFunctionLang()
545 public static function numberingroup( $parser, $name = '', $raw = null ) {
546 return self
::formatRaw(
547 SiteStats
::numberingroup( strtolower( $name ) ),
549 $parser->getFunctionLang()
554 * Given a title, return the namespace name that would be given by the
555 * corresponding magic word
556 * Note: function name changed to "mwnamespace" rather than "namespace"
557 * to not break PHP 5.3
558 * @param Parser $parser
559 * @param string $title
560 * @return mixed|string
562 public static function mwnamespace( $parser, $title = null ) {
563 $t = Title
::newFromText( $title );
564 if ( is_null( $t ) ) {
567 return str_replace( '_', ' ', $t->getNsText() );
569 public static function namespacee( $parser, $title = null ) {
570 $t = Title
::newFromText( $title );
571 if ( is_null( $t ) ) {
574 return wfUrlencode( $t->getNsText() );
576 public static function namespacenumber( $parser, $title = null ) {
577 $t = Title
::newFromText( $title );
578 if ( is_null( $t ) ) {
581 return $t->getNamespace();
583 public static function talkspace( $parser, $title = null ) {
584 $t = Title
::newFromText( $title );
585 if ( is_null( $t ) ||
!$t->canTalk() ) {
588 return str_replace( '_', ' ', $t->getTalkNsText() );
590 public static function talkspacee( $parser, $title = null ) {
591 $t = Title
::newFromText( $title );
592 if ( is_null( $t ) ||
!$t->canTalk() ) {
595 return wfUrlencode( $t->getTalkNsText() );
597 public static function subjectspace( $parser, $title = null ) {
598 $t = Title
::newFromText( $title );
599 if ( is_null( $t ) ) {
602 return str_replace( '_', ' ', $t->getSubjectNsText() );
604 public static function subjectspacee( $parser, $title = null ) {
605 $t = Title
::newFromText( $title );
606 if ( is_null( $t ) ) {
609 return wfUrlencode( $t->getSubjectNsText() );
613 * Functions to get and normalize pagenames, corresponding to the magic words
615 * @param Parser $parser
616 * @param string $title
619 public static function pagename( $parser, $title = null ) {
620 $t = Title
::newFromText( $title );
621 if ( is_null( $t ) ) {
624 return wfEscapeWikiText( $t->getText() );
626 public static function pagenamee( $parser, $title = null ) {
627 $t = Title
::newFromText( $title );
628 if ( is_null( $t ) ) {
631 return wfEscapeWikiText( $t->getPartialURL() );
633 public static function fullpagename( $parser, $title = null ) {
634 $t = Title
::newFromText( $title );
635 if ( is_null( $t ) ||
!$t->canTalk() ) {
638 return wfEscapeWikiText( $t->getPrefixedText() );
640 public static function fullpagenamee( $parser, $title = null ) {
641 $t = Title
::newFromText( $title );
642 if ( is_null( $t ) ||
!$t->canTalk() ) {
645 return wfEscapeWikiText( $t->getPrefixedURL() );
647 public static function subpagename( $parser, $title = null ) {
648 $t = Title
::newFromText( $title );
649 if ( is_null( $t ) ) {
652 return wfEscapeWikiText( $t->getSubpageText() );
654 public static function subpagenamee( $parser, $title = null ) {
655 $t = Title
::newFromText( $title );
656 if ( is_null( $t ) ) {
659 return wfEscapeWikiText( $t->getSubpageUrlForm() );
661 public static function rootpagename( $parser, $title = null ) {
662 $t = Title
::newFromText( $title );
663 if ( is_null( $t ) ) {
666 return wfEscapeWikiText( $t->getRootText() );
668 public static function rootpagenamee( $parser, $title = null ) {
669 $t = Title
::newFromText( $title );
670 if ( is_null( $t ) ) {
673 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
675 public static function basepagename( $parser, $title = null ) {
676 $t = Title
::newFromText( $title );
677 if ( is_null( $t ) ) {
680 return wfEscapeWikiText( $t->getBaseText() );
682 public static function basepagenamee( $parser, $title = null ) {
683 $t = Title
::newFromText( $title );
684 if ( is_null( $t ) ) {
687 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
689 public static function talkpagename( $parser, $title = null ) {
690 $t = Title
::newFromText( $title );
691 if ( is_null( $t ) ||
!$t->canTalk() ) {
694 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
696 public static function talkpagenamee( $parser, $title = null ) {
697 $t = Title
::newFromText( $title );
698 if ( is_null( $t ) ||
!$t->canTalk() ) {
701 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
703 public static function subjectpagename( $parser, $title = null ) {
704 $t = Title
::newFromText( $title );
705 if ( is_null( $t ) ) {
708 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
710 public static function subjectpagenamee( $parser, $title = null ) {
711 $t = Title
::newFromText( $title );
712 if ( is_null( $t ) ) {
715 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
719 * Return the number of pages, files or subcats in the given category,
720 * or 0 if it's nonexistent. This is an expensive parser function and
721 * can't be called too many times per page.
722 * @param Parser $parser
723 * @param string $name
724 * @param string $arg1
725 * @param string $arg2
728 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
730 static $magicWords = null;
731 if ( is_null( $magicWords ) ) {
732 $magicWords = new MagicWordArray( [
733 'pagesincategory_all',
734 'pagesincategory_pages',
735 'pagesincategory_subcats',
736 'pagesincategory_files'
741 // split the given option to its variable
742 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
743 // {{pagesincategory:|raw[|type]}}
745 $type = $magicWords->matchStartToEnd( $arg2 );
747 // {{pagesincategory:[|type[|raw]]}}
748 $type = $magicWords->matchStartToEnd( $arg1 );
751 if ( !$type ) { // backward compatibility
752 $type = 'pagesincategory_all';
755 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
756 if ( !$title ) { # invalid title
757 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
759 $wgContLang->findVariantLink( $name, $title, true );
761 // Normalize name for cache
762 $name = $title->getDBkey();
764 if ( !isset( $cache[$name] ) ) {
765 $category = Category
::newFromTitle( $title );
767 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
768 if ( $parser->incrementExpensiveFunctionCount() ) {
769 // $allCount is the total number of cat members,
770 // not the count of how many members are normal pages.
771 $allCount = (int)$category->getPageCount();
772 $subcatCount = (int)$category->getSubcatCount();
773 $fileCount = (int)$category->getFileCount();
774 $pagesCount = $allCount - $subcatCount - $fileCount;
776 $cache[$name]['pagesincategory_all'] = $allCount;
777 $cache[$name]['pagesincategory_pages'] = $pagesCount;
778 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
779 $cache[$name]['pagesincategory_files'] = $fileCount;
782 $count = $cache[$name][$type];
783 return self
::formatRaw( $count, $raw, $parser->getFunctionLang() );
787 * Return the size of the given page, or 0 if it's nonexistent. This is an
788 * expensive parser function and can't be called too many times per page.
790 * @param Parser $parser
791 * @param string $page Name of page to check (Default: empty string)
792 * @param string $raw Should number be human readable with commas or just number
795 public static function pagesize( $parser, $page = '', $raw = null ) {
796 $title = Title
::newFromText( $page );
798 if ( !is_object( $title ) ) {
799 return self
::formatRaw( 0, $raw, $parser->getFunctionLang() );
802 // fetch revision from cache/database and return the value
803 $rev = self
::getCachedRevisionObject( $parser, $title );
804 $length = $rev ?
$rev->getSize() : 0;
805 if ( $length === null ) {
806 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
809 return self
::formatRaw( $length, $raw, $parser->getFunctionLang() );
813 * Returns the requested protection level for the current page. This
814 * is an expensive parser function and can't be called too many times
815 * per page, unless the protection levels/expiries for the given title
816 * have already been retrieved
818 * @param Parser $parser
819 * @param string $type
820 * @param string $title
824 public static function protectionlevel( $parser, $type = '', $title = '' ) {
825 $titleObject = Title
::newFromText( $title );
826 if ( !( $titleObject instanceof Title
) ) {
827 $titleObject = $parser->mTitle
;
829 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
830 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
831 # Title::getRestrictions returns an array, its possible it may have
832 # multiple values in the future
833 return implode( $restrictions, ',' );
839 * Returns the requested protection expiry for the current page. This
840 * is an expensive parser function and can't be called too many times
841 * per page, unless the protection levels/expiries for the given title
842 * have already been retrieved
844 * @param Parser $parser
845 * @param string $type
846 * @param string $title
850 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
851 $titleObject = Title
::newFromText( $title );
852 if ( !( $titleObject instanceof Title
) ) {
853 $titleObject = $parser->mTitle
;
855 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
856 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
857 // getRestrictionExpiry() returns false on invalid type; trying to
858 // match protectionlevel() function that returns empty string instead
859 if ( $expiry === false ) {
868 * Gives language names.
869 * @param Parser $parser
870 * @param string $code Language code (of which to get name)
871 * @param string $inLanguage Language code (in which to get name)
874 public static function language( $parser, $code = '', $inLanguage = '' ) {
875 $code = strtolower( $code );
876 $inLanguage = strtolower( $inLanguage );
877 $lang = Language
::fetchLanguageName( $code, $inLanguage );
878 return $lang !== '' ?
$lang : wfBCP47( $code );
882 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
883 * @param Parser $parser
884 * @param string $string
886 * @param string $padding
887 * @param int $direction
890 public static function pad(
891 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
893 $padding = $parser->killMarkers( $padding );
894 $lengthOfPadding = mb_strlen( $padding );
895 if ( $lengthOfPadding == 0 ) {
899 # The remaining length to add counts down to 0 as padding is added
900 $length = min( $length, 500 ) - mb_strlen( $string );
901 # $finalPadding is just $padding repeated enough times so that
902 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
904 while ( $length > 0 ) {
905 # If $length < $lengthofPadding, truncate $padding so we get the
906 # exact length desired.
907 $finalPadding .= mb_substr( $padding, 0, $length );
908 $length -= $lengthOfPadding;
911 if ( $direction == STR_PAD_LEFT
) {
912 return $finalPadding . $string;
914 return $string . $finalPadding;
918 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
919 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
922 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
923 return self
::pad( $parser, $string, $length, $padding );
927 * @param Parser $parser
928 * @param string $text
931 public static function anchorencode( $parser, $text ) {
932 $text = $parser->killMarkers( $text );
933 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
936 public static function special( $parser, $text ) {
937 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
939 $title = SpecialPage
::getTitleFor( $page, $subpage );
940 return $title->getPrefixedText();
942 // unknown special page, just use the given text as its title, if at all possible
943 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
944 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
948 public static function speciale( $parser, $text ) {
949 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
953 * @param Parser $parser
954 * @param string $text The sortkey to use
955 * @param string $uarg Either "noreplace" or "noerror" (in en)
956 * both suppress errors, and noreplace does nothing if
957 * a default sortkey already exists.
960 public static function defaultsort( $parser, $text, $uarg = '' ) {
961 static $magicWords = null;
962 if ( is_null( $magicWords ) ) {
963 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
965 $arg = $magicWords->matchStartToEnd( $uarg );
967 $text = trim( $text );
968 if ( strlen( $text ) == 0 ) {
971 $old = $parser->getCustomDefaultSort();
972 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
973 $parser->setDefaultSort( $text );
976 if ( $old === false ||
$old == $text ||
$arg ) {
979 $converter = $parser->getConverterLanguage()->getConverter();
980 return '<span class="error">' .
981 wfMessage( 'duplicate-defaultsort',
982 // Message should be parsed, but these params should only be escaped.
983 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
984 $converter->markNoConversion( wfEscapeWikiText( $text ) )
985 )->inContentLanguage()->text() .
991 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
992 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
993 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
995 * @param Parser $parser
996 * @param string $name
997 * @param string $argA
998 * @param string $argB
999 * @return array|string
1001 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1002 $file = wfFindFile( $name );
1004 if ( $argA == 'nowiki' ) {
1005 // {{filepath: | option [| size] }}
1007 $parsedWidthParam = $parser->parseWidthParam( $argB );
1009 // {{filepath: [| size [|option]] }}
1010 $parsedWidthParam = $parser->parseWidthParam( $argA );
1011 $isNowiki = ( $argB == 'nowiki' );
1015 $url = $file->getFullUrl();
1017 // If a size is requested...
1018 if ( count( $parsedWidthParam ) ) {
1019 $mto = $file->transform( $parsedWidthParam );
1021 if ( $mto && !$mto->isError() ) {
1022 // ... change the URL to point to a thumbnail.
1023 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1027 return [ $url, 'nowiki' => true ];
1036 * Parser function to extension tag adaptor
1037 * @param Parser $parser
1038 * @param PPFrame $frame
1039 * @param PPNode[] $args
1042 public static function tagObj( $parser, $frame, $args ) {
1043 if ( !count( $args ) ) {
1046 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1048 if ( count( $args ) ) {
1049 $inner = $frame->expand( array_shift( $args ) );
1055 foreach ( $args as $arg ) {
1056 $bits = $arg->splitArg();
1057 if ( strval( $bits['index'] ) === '' ) {
1058 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1059 $value = trim( $frame->expand( $bits['value'] ) );
1060 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1061 $value = isset( $m[1] ) ?
$m[1] : '';
1063 $attributes[$name] = $value;
1067 $stripList = $parser->getStripList();
1068 if ( !in_array( $tagName, $stripList ) ) {
1069 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1071 foreach ( $attributes as $name => $value ) {
1072 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1074 if ( $inner === null ) {
1075 return "<$tagName$attrText/>";
1077 return "<$tagName$attrText>$inner</$tagName>";
1083 'attributes' => $attributes,
1084 'close' => "</$tagName>",
1086 return $parser->extensionSubstitution( $params, $frame );
1090 * Fetched the current revision of the given title and return this.
1091 * Will increment the expensive function count and
1092 * add a template link to get the value refreshed on changes.
1093 * For a given title, which is equal to the current parser title,
1094 * the revision object from the parser is used, when that is the current one
1096 * @param Parser $parser
1097 * @param Title $title
1101 private static function getCachedRevisionObject( $parser, $title = null ) {
1102 if ( is_null( $title ) ) {
1106 // Use the revision from the parser itself, when param is the current page
1107 // and the revision is the current one
1108 if ( $title->equals( $parser->getTitle() ) ) {
1109 $parserRev = $parser->getRevisionObject();
1110 if ( $parserRev && $parserRev->isCurrent() ) {
1111 // force reparse after edit with vary-revision flag
1112 $parser->getOutput()->setFlag( 'vary-revision' );
1113 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1118 // Normalize name for cache
1119 $page = $title->getPrefixedDBkey();
1121 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1122 && !$parser->incrementExpensiveFunctionCount() ) {
1125 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1126 $pageID = $rev ?
$rev->getPage() : 0;
1127 $revID = $rev ?
$rev->getId() : 0;
1129 // Register dependency in templatelinks
1130 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1136 * Get the pageid of a specified page
1137 * @param Parser $parser
1138 * @param string $title Title to get the pageid from
1139 * @return int|null|string
1142 public static function pageid( $parser, $title = null ) {
1143 $t = Title
::newFromText( $title );
1144 if ( is_null( $t ) ) {
1147 // Use title from parser to have correct pageid after edit
1148 if ( $t->equals( $parser->getTitle() ) ) {
1149 $t = $parser->getTitle();
1150 return $t->getArticleID();
1153 // These can't have ids
1154 if ( !$t->canExist() ||
$t->isExternal() ) {
1158 // Check the link cache, maybe something already looked it up.
1159 $linkCache = LinkCache
::singleton();
1160 $pdbk = $t->getPrefixedDBkey();
1161 $id = $linkCache->getGoodLinkID( $pdbk );
1163 $parser->mOutput
->addLink( $t, $id );
1166 if ( $linkCache->isBadLink( $pdbk ) ) {
1167 $parser->mOutput
->addLink( $t, 0 );
1171 // We need to load it from the DB, so mark expensive
1172 if ( $parser->incrementExpensiveFunctionCount() ) {
1173 $id = $t->getArticleID();
1174 $parser->mOutput
->addLink( $t, $id );
1181 * Get the id from the last revision of a specified page.
1182 * @param Parser $parser
1183 * @param string $title Title to get the id from
1184 * @return int|null|string
1187 public static function revisionid( $parser, $title = null ) {
1188 $t = Title
::newFromText( $title );
1189 if ( is_null( $t ) ) {
1192 // fetch revision from cache/database and return the value
1193 $rev = self
::getCachedRevisionObject( $parser, $t );
1194 return $rev ?
$rev->getId() : '';
1198 * Get the day from the last revision of a specified page.
1199 * @param Parser $parser
1200 * @param string $title Title to get the day from
1204 public static function revisionday( $parser, $title = null ) {
1205 $t = Title
::newFromText( $title );
1206 if ( is_null( $t ) ) {
1209 // fetch revision from cache/database and return the value
1210 $rev = self
::getCachedRevisionObject( $parser, $t );
1211 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1215 * Get the day with leading zeros from the last revision of a specified page.
1216 * @param Parser $parser
1217 * @param string $title Title to get the day from
1221 public static function revisionday2( $parser, $title = null ) {
1222 $t = Title
::newFromText( $title );
1223 if ( is_null( $t ) ) {
1226 // fetch revision from cache/database and return the value
1227 $rev = self
::getCachedRevisionObject( $parser, $t );
1228 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1232 * Get the month with leading zeros from the last revision of a specified page.
1233 * @param Parser $parser
1234 * @param string $title Title to get the month from
1238 public static function revisionmonth( $parser, $title = null ) {
1239 $t = Title
::newFromText( $title );
1240 if ( is_null( $t ) ) {
1243 // fetch revision from cache/database and return the value
1244 $rev = self
::getCachedRevisionObject( $parser, $t );
1245 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1249 * Get the month from the last revision of a specified page.
1250 * @param Parser $parser
1251 * @param string $title Title to get the month from
1255 public static function revisionmonth1( $parser, $title = null ) {
1256 $t = Title
::newFromText( $title );
1257 if ( is_null( $t ) ) {
1260 // fetch revision from cache/database and return the value
1261 $rev = self
::getCachedRevisionObject( $parser, $t );
1262 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1266 * Get the year from the last revision of a specified page.
1267 * @param Parser $parser
1268 * @param string $title Title to get the year from
1272 public static function revisionyear( $parser, $title = null ) {
1273 $t = Title
::newFromText( $title );
1274 if ( is_null( $t ) ) {
1277 // fetch revision from cache/database and return the value
1278 $rev = self
::getCachedRevisionObject( $parser, $t );
1279 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1283 * Get the timestamp from the last revision of a specified page.
1284 * @param Parser $parser
1285 * @param string $title Title to get the timestamp from
1289 public static function revisiontimestamp( $parser, $title = null ) {
1290 $t = Title
::newFromText( $title );
1291 if ( is_null( $t ) ) {
1294 // fetch revision from cache/database and return the value
1295 $rev = self
::getCachedRevisionObject( $parser, $t );
1296 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1300 * Get the user from the last revision of a specified page.
1301 * @param Parser $parser
1302 * @param string $title Title to get the user from
1306 public static function revisionuser( $parser, $title = null ) {
1307 $t = Title
::newFromText( $title );
1308 if ( is_null( $t ) ) {
1311 // fetch revision from cache/database and return the value
1312 $rev = self
::getCachedRevisionObject( $parser, $t );
1313 return $rev ?
$rev->getUserText() : '';
1317 * Returns the sources of any cascading protection acting on a specified page.
1318 * Pages will not return their own title unless they transclude themselves.
1319 * This is an expensive parser function and can't be called too many times per page,
1320 * unless cascading protection sources for the page have already been loaded.
1322 * @param Parser $parser
1323 * @param string $title
1328 public static function cascadingsources( $parser, $title = '' ) {
1329 $titleObject = Title
::newFromText( $title );
1330 if ( !( $titleObject instanceof Title
) ) {
1331 $titleObject = $parser->mTitle
;
1333 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1334 ||
$parser->incrementExpensiveFunctionCount()
1337 $sources = $titleObject->getCascadeProtectionSources();
1338 foreach ( $sources[0] as $sourceTitle ) {
1339 $names[] = $sourceTitle->getPrefixedText();
1341 return implode( $names, '|' );