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: (bug 22474)
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 ) ) {
178 // Encode as though it's a wiki page, '_' for ' '.
180 $func = 'wfUrlencode';
181 $s = str_replace( ' ', '_', $s );
184 // Encode for an HTTP Path, '%20' for ' '.
186 $func = 'rawurlencode';
189 // Encode for HTTP query, '+' for ' '.
194 // See T105242, where the choice to kill markers and various
195 // other options were discussed.
196 return $func( $parser->killMarkers( $s ) );
199 public static function lcfirst( $parser, $s = '' ) {
201 return $wgContLang->lcfirst( $s );
204 public static function ucfirst( $parser, $s = '' ) {
206 return $wgContLang->ucfirst( $s );
210 * @param Parser $parser
214 public static function lc( $parser, $s = '' ) {
216 return $parser->markerSkipCallback( $s, [ $wgContLang, 'lc' ] );
220 * @param Parser $parser
224 public static function uc( $parser, $s = '' ) {
226 return $parser->markerSkipCallback( $s, [ $wgContLang, 'uc' ] );
229 public static function localurl( $parser, $s = '', $arg = null ) {
230 return self
::urlFunction( 'getLocalURL', $s, $arg );
233 public static function localurle( $parser, $s = '', $arg = null ) {
234 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
235 if ( !is_string( $temp ) ) {
238 return htmlspecialchars( $temp );
242 public static function fullurl( $parser, $s = '', $arg = null ) {
243 return self
::urlFunction( 'getFullURL', $s, $arg );
246 public static function fullurle( $parser, $s = '', $arg = null ) {
247 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
248 if ( !is_string( $temp ) ) {
251 return htmlspecialchars( $temp );
255 public static function canonicalurl( $parser, $s = '', $arg = null ) {
256 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
259 public static function canonicalurle( $parser, $s = '', $arg = null ) {
260 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
261 if ( !is_string( $temp ) ) {
264 return htmlspecialchars( $temp );
268 public static function urlFunction( $func, $s = '', $arg = null ) {
269 $title = Title
::newFromText( $s );
270 # Due to order of execution of a lot of bits, the values might be encoded
271 # before arriving here; if that's true, then the title can't be created
272 # and the variable will fail. If we can't get a decent title from the first
273 # attempt, url-decode and try for a second.
274 if ( is_null( $title ) ) {
275 $title = Title
::newFromURL( urldecode( $s ) );
277 if ( !is_null( $title ) ) {
278 # Convert NS_MEDIA -> NS_FILE
279 if ( $title->getNamespace() == NS_MEDIA
) {
280 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
282 if ( !is_null( $arg ) ) {
283 $text = $title->$func( $arg );
285 $text = $title->$func();
289 return [ 'found' => false ];
294 * @param Parser $parser
299 public static function formatnum( $parser, $num = '', $arg = null ) {
300 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
301 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
302 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
303 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
305 $func = [ $parser->getFunctionLang(), 'formatNum' ];
307 return $parser->markerSkipCallback( $num, $func );
311 * @param Parser $parser
312 * @param string $case
313 * @param string $word
316 public static function grammar( $parser, $case = '', $word = '' ) {
317 $word = $parser->killMarkers( $word );
318 return $parser->getFunctionLang()->convertGrammar( $word, $case );
322 * @param Parser $parser
323 * @param string $username
326 public static function gender( $parser, $username ) {
327 $forms = array_slice( func_get_args(), 2 );
329 // Some shortcuts to avoid loading user data unnecessarily
330 if ( count( $forms ) === 0 ) {
332 } elseif ( count( $forms ) === 1 ) {
336 $username = trim( $username );
339 $gender = User
::getDefaultOption( 'gender' );
342 $title = Title
::newFromText( $username );
344 if ( $title && $title->getNamespace() == NS_USER
) {
345 $username = $title->getText();
348 // check parameter, or use the ParserOptions if in interface message
349 $user = User
::newFromName( $username );
350 $genderCache = MediaWikiServices
::getInstance()->getGenderCache();
352 $gender = $genderCache->getGenderOf( $user, __METHOD__
);
353 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
354 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
356 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
361 * @param Parser $parser
362 * @param string $text
365 public static function plural( $parser, $text = '' ) {
366 $forms = array_slice( func_get_args(), 2 );
367 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
368 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
369 return $parser->getFunctionLang()->convertPlural( $text, $forms );
373 * @param Parser $parser
374 * @param string $text
377 public static function bidi( $parser, $text = '' ) {
378 return $parser->getFunctionLang()->embedBidi( $text );
382 * Override the title of the page when viewed, provided we've been given a
383 * title which will normalise to the canonical title
385 * @param Parser $parser Parent parser
386 * @param string $text Desired title text
387 * @param string $uarg
390 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
391 global $wgRestrictDisplayTitle;
393 static $magicWords = null;
394 if ( is_null( $magicWords ) ) {
395 $magicWords = new MagicWordArray( [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
397 $arg = $magicWords->matchStartToEnd( $uarg );
399 // parse a limited subset of wiki markup (just the single quote items)
400 $text = $parser->doQuotes( $text );
402 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
403 $text = $parser->killMarkers( $text );
405 // list of disallowed tags for DISPLAYTITLE
406 // these will be escaped even though they are allowed in normal wiki text
407 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
408 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
410 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
411 if ( $wgRestrictDisplayTitle ) {
412 $htmlTagsCallback = function ( &$params ) {
413 $decoded = Sanitizer
::decodeTagAttributes( $params );
415 if ( isset( $decoded['style'] ) ) {
416 // this is called later anyway, but we need it right now for the regexes below to be safe
417 // calling it twice doesn't hurt
418 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
420 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
421 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
425 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
428 $htmlTagsCallback = null;
431 // only requested titles that normalize to the actual title are allowed through
432 // if $wgRestrictDisplayTitle is true (it is by default)
433 // mimic the escaping process that occurs in OutputPage::setPageTitle
434 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
441 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
443 if ( !$wgRestrictDisplayTitle ||
444 ( $title instanceof Title
445 && !$title->hasFragment()
446 && $title->equals( $parser->mTitle
) )
448 $old = $parser->mOutput
->getProperty( 'displaytitle' );
449 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
450 $parser->mOutput
->setDisplayTitle( $text );
452 if ( $old !== false && $old !== $text && !$arg ) {
453 $converter = $parser->getConverterLanguage()->getConverter();
454 return '<span class="error">' .
455 wfMessage( 'duplicate-displaytitle',
456 // Message should be parsed, but these params should only be escaped.
457 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
458 $converter->markNoConversion( wfEscapeWikiText( $text ) )
459 )->inContentLanguage()->text() .
465 $converter = $parser->getConverterLanguage()->getConverter();
466 $parser->getOutput()->addWarning(
467 wfMessage( 'restricted-displaytitle',
468 // Message should be parsed, but this param should only be escaped.
469 $converter->markNoConversion( wfEscapeWikiText( $text ) )
472 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
477 * Matches the given value against the value of given magic word
479 * @param string $magicword Magic word key
480 * @param string $value Value to match
481 * @return bool True on successful match
483 private static function matchAgainstMagicword( $magicword, $value ) {
484 $value = trim( strval( $value ) );
485 if ( $value === '' ) {
488 $mwObject = MagicWord
::get( $magicword );
489 return $mwObject->matchStartToEnd( $value );
492 public static function formatRaw( $num, $raw ) {
493 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
497 return $wgContLang->formatNum( $num );
500 public static function numberofpages( $parser, $raw = null ) {
501 return self
::formatRaw( SiteStats
::pages(), $raw );
503 public static function numberofusers( $parser, $raw = null ) {
504 return self
::formatRaw( SiteStats
::users(), $raw );
506 public static function numberofactiveusers( $parser, $raw = null ) {
507 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
509 public static function numberofarticles( $parser, $raw = null ) {
510 return self
::formatRaw( SiteStats
::articles(), $raw );
512 public static function numberoffiles( $parser, $raw = null ) {
513 return self
::formatRaw( SiteStats
::images(), $raw );
515 public static function numberofadmins( $parser, $raw = null ) {
516 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
518 public static function numberofedits( $parser, $raw = null ) {
519 return self
::formatRaw( SiteStats
::edits(), $raw );
521 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
522 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
524 public static function numberingroup( $parser, $name = '', $raw = null ) {
525 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
529 * Given a title, return the namespace name that would be given by the
530 * corresponding magic word
531 * Note: function name changed to "mwnamespace" rather than "namespace"
532 * to not break PHP 5.3
533 * @param Parser $parser
534 * @param string $title
535 * @return mixed|string
537 public static function mwnamespace( $parser, $title = null ) {
538 $t = Title
::newFromText( $title );
539 if ( is_null( $t ) ) {
542 return str_replace( '_', ' ', $t->getNsText() );
544 public static function namespacee( $parser, $title = null ) {
545 $t = Title
::newFromText( $title );
546 if ( is_null( $t ) ) {
549 return wfUrlencode( $t->getNsText() );
551 public static function namespacenumber( $parser, $title = null ) {
552 $t = Title
::newFromText( $title );
553 if ( is_null( $t ) ) {
556 return $t->getNamespace();
558 public static function talkspace( $parser, $title = null ) {
559 $t = Title
::newFromText( $title );
560 if ( is_null( $t ) ||
!$t->canTalk() ) {
563 return str_replace( '_', ' ', $t->getTalkNsText() );
565 public static function talkspacee( $parser, $title = null ) {
566 $t = Title
::newFromText( $title );
567 if ( is_null( $t ) ||
!$t->canTalk() ) {
570 return wfUrlencode( $t->getTalkNsText() );
572 public static function subjectspace( $parser, $title = null ) {
573 $t = Title
::newFromText( $title );
574 if ( is_null( $t ) ) {
577 return str_replace( '_', ' ', $t->getSubjectNsText() );
579 public static function subjectspacee( $parser, $title = null ) {
580 $t = Title
::newFromText( $title );
581 if ( is_null( $t ) ) {
584 return wfUrlencode( $t->getSubjectNsText() );
588 * Functions to get and normalize pagenames, corresponding to the magic words
590 * @param Parser $parser
591 * @param string $title
594 public static function pagename( $parser, $title = null ) {
595 $t = Title
::newFromText( $title );
596 if ( is_null( $t ) ) {
599 return wfEscapeWikiText( $t->getText() );
601 public static function pagenamee( $parser, $title = null ) {
602 $t = Title
::newFromText( $title );
603 if ( is_null( $t ) ) {
606 return wfEscapeWikiText( $t->getPartialURL() );
608 public static function fullpagename( $parser, $title = null ) {
609 $t = Title
::newFromText( $title );
610 if ( is_null( $t ) ||
!$t->canTalk() ) {
613 return wfEscapeWikiText( $t->getPrefixedText() );
615 public static function fullpagenamee( $parser, $title = null ) {
616 $t = Title
::newFromText( $title );
617 if ( is_null( $t ) ||
!$t->canTalk() ) {
620 return wfEscapeWikiText( $t->getPrefixedURL() );
622 public static function subpagename( $parser, $title = null ) {
623 $t = Title
::newFromText( $title );
624 if ( is_null( $t ) ) {
627 return wfEscapeWikiText( $t->getSubpageText() );
629 public static function subpagenamee( $parser, $title = null ) {
630 $t = Title
::newFromText( $title );
631 if ( is_null( $t ) ) {
634 return wfEscapeWikiText( $t->getSubpageUrlForm() );
636 public static function rootpagename( $parser, $title = null ) {
637 $t = Title
::newFromText( $title );
638 if ( is_null( $t ) ) {
641 return wfEscapeWikiText( $t->getRootText() );
643 public static function rootpagenamee( $parser, $title = null ) {
644 $t = Title
::newFromText( $title );
645 if ( is_null( $t ) ) {
648 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
650 public static function basepagename( $parser, $title = null ) {
651 $t = Title
::newFromText( $title );
652 if ( is_null( $t ) ) {
655 return wfEscapeWikiText( $t->getBaseText() );
657 public static function basepagenamee( $parser, $title = null ) {
658 $t = Title
::newFromText( $title );
659 if ( is_null( $t ) ) {
662 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
664 public static function talkpagename( $parser, $title = null ) {
665 $t = Title
::newFromText( $title );
666 if ( is_null( $t ) ||
!$t->canTalk() ) {
669 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
671 public static function talkpagenamee( $parser, $title = null ) {
672 $t = Title
::newFromText( $title );
673 if ( is_null( $t ) ||
!$t->canTalk() ) {
676 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
678 public static function subjectpagename( $parser, $title = null ) {
679 $t = Title
::newFromText( $title );
680 if ( is_null( $t ) ) {
683 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
685 public static function subjectpagenamee( $parser, $title = null ) {
686 $t = Title
::newFromText( $title );
687 if ( is_null( $t ) ) {
690 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
694 * Return the number of pages, files or subcats in the given category,
695 * or 0 if it's nonexistent. This is an expensive parser function and
696 * can't be called too many times per page.
697 * @param Parser $parser
698 * @param string $name
699 * @param string $arg1
700 * @param string $arg2
703 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
705 static $magicWords = null;
706 if ( is_null( $magicWords ) ) {
707 $magicWords = new MagicWordArray( [
708 'pagesincategory_all',
709 'pagesincategory_pages',
710 'pagesincategory_subcats',
711 'pagesincategory_files'
716 // split the given option to its variable
717 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
718 // {{pagesincategory:|raw[|type]}}
720 $type = $magicWords->matchStartToEnd( $arg2 );
722 // {{pagesincategory:[|type[|raw]]}}
723 $type = $magicWords->matchStartToEnd( $arg1 );
726 if ( !$type ) { // backward compatibility
727 $type = 'pagesincategory_all';
730 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
731 if ( !$title ) { # invalid title
732 return self
::formatRaw( 0, $raw );
734 $wgContLang->findVariantLink( $name, $title, true );
736 // Normalize name for cache
737 $name = $title->getDBkey();
739 if ( !isset( $cache[$name] ) ) {
740 $category = Category
::newFromTitle( $title );
742 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
743 if ( $parser->incrementExpensiveFunctionCount() ) {
744 // $allCount is the total number of cat members,
745 // not the count of how many members are normal pages.
746 $allCount = (int)$category->getPageCount();
747 $subcatCount = (int)$category->getSubcatCount();
748 $fileCount = (int)$category->getFileCount();
749 $pagesCount = $allCount - $subcatCount - $fileCount;
751 $cache[$name]['pagesincategory_all'] = $allCount;
752 $cache[$name]['pagesincategory_pages'] = $pagesCount;
753 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
754 $cache[$name]['pagesincategory_files'] = $fileCount;
757 $count = $cache[$name][$type];
758 return self
::formatRaw( $count, $raw );
762 * Return the size of the given page, or 0 if it's nonexistent. This is an
763 * expensive parser function and can't be called too many times per page.
765 * @param Parser $parser
766 * @param string $page Name of page to check (Default: empty string)
767 * @param string $raw Should number be human readable with commas or just number
770 public static function pagesize( $parser, $page = '', $raw = null ) {
771 $title = Title
::newFromText( $page );
773 if ( !is_object( $title ) ) {
774 return self
::formatRaw( 0, $raw );
777 // fetch revision from cache/database and return the value
778 $rev = self
::getCachedRevisionObject( $parser, $title );
779 $length = $rev ?
$rev->getSize() : 0;
780 if ( $length === null ) {
781 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
784 return self
::formatRaw( $length, $raw );
788 * Returns the requested protection level for the current page. This
789 * is an expensive parser function and can't be called too many times
790 * per page, unless the protection levels/expiries for the given title
791 * have already been retrieved
793 * @param Parser $parser
794 * @param string $type
795 * @param string $title
799 public static function protectionlevel( $parser, $type = '', $title = '' ) {
800 $titleObject = Title
::newFromText( $title );
801 if ( !( $titleObject instanceof Title
) ) {
802 $titleObject = $parser->mTitle
;
804 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
805 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
806 # Title::getRestrictions returns an array, its possible it may have
807 # multiple values in the future
808 return implode( $restrictions, ',' );
814 * Returns the requested protection expiry for the current page. This
815 * is an expensive parser function and can't be called too many times
816 * per page, unless the protection levels/expiries for the given title
817 * have already been retrieved
819 * @param Parser $parser
820 * @param string $type
821 * @param string $title
825 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
826 $titleObject = Title
::newFromText( $title );
827 if ( !( $titleObject instanceof Title
) ) {
828 $titleObject = $parser->mTitle
;
830 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
831 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
832 // getRestrictionExpiry() returns false on invalid type; trying to
833 // match protectionlevel() function that returns empty string instead
834 if ( $expiry === false ) {
843 * Gives language names.
844 * @param Parser $parser
845 * @param string $code Language code (of which to get name)
846 * @param string $inLanguage Language code (in which to get name)
849 public static function language( $parser, $code = '', $inLanguage = '' ) {
850 $code = strtolower( $code );
851 $inLanguage = strtolower( $inLanguage );
852 $lang = Language
::fetchLanguageName( $code, $inLanguage );
853 return $lang !== '' ?
$lang : wfBCP47( $code );
857 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
858 * @param Parser $parser
859 * @param string $string
861 * @param string $padding
862 * @param int $direction
865 public static function pad(
866 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
868 $padding = $parser->killMarkers( $padding );
869 $lengthOfPadding = mb_strlen( $padding );
870 if ( $lengthOfPadding == 0 ) {
874 # The remaining length to add counts down to 0 as padding is added
875 $length = min( $length, 500 ) - mb_strlen( $string );
876 # $finalPadding is just $padding repeated enough times so that
877 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
879 while ( $length > 0 ) {
880 # If $length < $lengthofPadding, truncate $padding so we get the
881 # exact length desired.
882 $finalPadding .= mb_substr( $padding, 0, $length );
883 $length -= $lengthOfPadding;
886 if ( $direction == STR_PAD_LEFT
) {
887 return $finalPadding . $string;
889 return $string . $finalPadding;
893 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
894 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
897 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
898 return self
::pad( $parser, $string, $length, $padding );
902 * @param Parser $parser
903 * @param string $text
906 public static function anchorencode( $parser, $text ) {
907 $text = $parser->killMarkers( $text );
908 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
911 public static function special( $parser, $text ) {
912 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
914 $title = SpecialPage
::getTitleFor( $page, $subpage );
915 return $title->getPrefixedText();
917 // unknown special page, just use the given text as its title, if at all possible
918 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
919 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
923 public static function speciale( $parser, $text ) {
924 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
928 * @param Parser $parser
929 * @param string $text The sortkey to use
930 * @param string $uarg Either "noreplace" or "noerror" (in en)
931 * both suppress errors, and noreplace does nothing if
932 * a default sortkey already exists.
935 public static function defaultsort( $parser, $text, $uarg = '' ) {
936 static $magicWords = null;
937 if ( is_null( $magicWords ) ) {
938 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
940 $arg = $magicWords->matchStartToEnd( $uarg );
942 $text = trim( $text );
943 if ( strlen( $text ) == 0 ) {
946 $old = $parser->getCustomDefaultSort();
947 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
948 $parser->setDefaultSort( $text );
951 if ( $old === false ||
$old == $text ||
$arg ) {
954 $converter = $parser->getConverterLanguage()->getConverter();
955 return '<span class="error">' .
956 wfMessage( 'duplicate-defaultsort',
957 // Message should be parsed, but these params should only be escaped.
958 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
959 $converter->markNoConversion( wfEscapeWikiText( $text ) )
960 )->inContentLanguage()->text() .
966 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
967 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
968 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
970 * @param Parser $parser
971 * @param string $name
972 * @param string $argA
973 * @param string $argB
974 * @return array|string
976 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
977 $file = wfFindFile( $name );
979 if ( $argA == 'nowiki' ) {
980 // {{filepath: | option [| size] }}
982 $parsedWidthParam = $parser->parseWidthParam( $argB );
984 // {{filepath: [| size [|option]] }}
985 $parsedWidthParam = $parser->parseWidthParam( $argA );
986 $isNowiki = ( $argB == 'nowiki' );
990 $url = $file->getFullUrl();
992 // If a size is requested...
993 if ( count( $parsedWidthParam ) ) {
994 $mto = $file->transform( $parsedWidthParam );
996 if ( $mto && !$mto->isError() ) {
997 // ... change the URL to point to a thumbnail.
998 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
1002 return [ $url, 'nowiki' => true ];
1011 * Parser function to extension tag adaptor
1012 * @param Parser $parser
1013 * @param PPFrame $frame
1014 * @param PPNode[] $args
1017 public static function tagObj( $parser, $frame, $args ) {
1018 if ( !count( $args ) ) {
1021 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1023 if ( count( $args ) ) {
1024 $inner = $frame->expand( array_shift( $args ) );
1030 foreach ( $args as $arg ) {
1031 $bits = $arg->splitArg();
1032 if ( strval( $bits['index'] ) === '' ) {
1033 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1034 $value = trim( $frame->expand( $bits['value'] ) );
1035 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1036 $value = isset( $m[1] ) ?
$m[1] : '';
1038 $attributes[$name] = $value;
1042 $stripList = $parser->getStripList();
1043 if ( !in_array( $tagName, $stripList ) ) {
1044 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1046 foreach ( $attributes as $name => $value ) {
1047 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1049 if ( $inner === null ) {
1050 return "<$tagName$attrText/>";
1052 return "<$tagName$attrText>$inner</$tagName>";
1058 'attributes' => $attributes,
1059 'close' => "</$tagName>",
1061 return $parser->extensionSubstitution( $params, $frame );
1065 * Fetched the current revision of the given title and return this.
1066 * Will increment the expensive function count and
1067 * add a template link to get the value refreshed on changes.
1068 * For a given title, which is equal to the current parser title,
1069 * the revision object from the parser is used, when that is the current one
1071 * @param Parser $parser
1072 * @param Title $title
1076 private static function getCachedRevisionObject( $parser, $title = null ) {
1077 if ( is_null( $title ) ) {
1081 // Use the revision from the parser itself, when param is the current page
1082 // and the revision is the current one
1083 if ( $title->equals( $parser->getTitle() ) ) {
1084 $parserRev = $parser->getRevisionObject();
1085 if ( $parserRev && $parserRev->isCurrent() ) {
1086 // force reparse after edit with vary-revision flag
1087 $parser->getOutput()->setFlag( 'vary-revision' );
1088 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1093 // Normalize name for cache
1094 $page = $title->getPrefixedDBkey();
1096 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1097 && !$parser->incrementExpensiveFunctionCount() ) {
1100 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1101 $pageID = $rev ?
$rev->getPage() : 0;
1102 $revID = $rev ?
$rev->getId() : 0;
1104 // Register dependency in templatelinks
1105 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1111 * Get the pageid of a specified page
1112 * @param Parser $parser
1113 * @param string $title Title to get the pageid from
1114 * @return int|null|string
1117 public static function pageid( $parser, $title = null ) {
1118 $t = Title
::newFromText( $title );
1119 if ( is_null( $t ) ) {
1122 // Use title from parser to have correct pageid after edit
1123 if ( $t->equals( $parser->getTitle() ) ) {
1124 $t = $parser->getTitle();
1125 return $t->getArticleID();
1128 // These can't have ids
1129 if ( !$t->canExist() ||
$t->isExternal() ) {
1133 // Check the link cache, maybe something already looked it up.
1134 $linkCache = LinkCache
::singleton();
1135 $pdbk = $t->getPrefixedDBkey();
1136 $id = $linkCache->getGoodLinkID( $pdbk );
1138 $parser->mOutput
->addLink( $t, $id );
1141 if ( $linkCache->isBadLink( $pdbk ) ) {
1142 $parser->mOutput
->addLink( $t, 0 );
1146 // We need to load it from the DB, so mark expensive
1147 if ( $parser->incrementExpensiveFunctionCount() ) {
1148 $id = $t->getArticleID();
1149 $parser->mOutput
->addLink( $t, $id );
1156 * Get the id from the last revision of a specified page.
1157 * @param Parser $parser
1158 * @param string $title Title to get the id from
1159 * @return int|null|string
1162 public static function revisionid( $parser, $title = null ) {
1163 $t = Title
::newFromText( $title );
1164 if ( is_null( $t ) ) {
1167 // fetch revision from cache/database and return the value
1168 $rev = self
::getCachedRevisionObject( $parser, $t );
1169 return $rev ?
$rev->getId() : '';
1173 * Get the day from the last revision of a specified page.
1174 * @param Parser $parser
1175 * @param string $title Title to get the day from
1179 public static function revisionday( $parser, $title = null ) {
1180 $t = Title
::newFromText( $title );
1181 if ( is_null( $t ) ) {
1184 // fetch revision from cache/database and return the value
1185 $rev = self
::getCachedRevisionObject( $parser, $t );
1186 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1190 * Get the day with leading zeros from the last revision of a specified page.
1191 * @param Parser $parser
1192 * @param string $title Title to get the day from
1196 public static function revisionday2( $parser, $title = null ) {
1197 $t = Title
::newFromText( $title );
1198 if ( is_null( $t ) ) {
1201 // fetch revision from cache/database and return the value
1202 $rev = self
::getCachedRevisionObject( $parser, $t );
1203 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1207 * Get the month with leading zeros from the last revision of a specified page.
1208 * @param Parser $parser
1209 * @param string $title Title to get the month from
1213 public static function revisionmonth( $parser, $title = null ) {
1214 $t = Title
::newFromText( $title );
1215 if ( is_null( $t ) ) {
1218 // fetch revision from cache/database and return the value
1219 $rev = self
::getCachedRevisionObject( $parser, $t );
1220 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1224 * Get the month from the last revision of a specified page.
1225 * @param Parser $parser
1226 * @param string $title Title to get the month from
1230 public static function revisionmonth1( $parser, $title = null ) {
1231 $t = Title
::newFromText( $title );
1232 if ( is_null( $t ) ) {
1235 // fetch revision from cache/database and return the value
1236 $rev = self
::getCachedRevisionObject( $parser, $t );
1237 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1241 * Get the year from the last revision of a specified page.
1242 * @param Parser $parser
1243 * @param string $title Title to get the year from
1247 public static function revisionyear( $parser, $title = null ) {
1248 $t = Title
::newFromText( $title );
1249 if ( is_null( $t ) ) {
1252 // fetch revision from cache/database and return the value
1253 $rev = self
::getCachedRevisionObject( $parser, $t );
1254 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1258 * Get the timestamp from the last revision of a specified page.
1259 * @param Parser $parser
1260 * @param string $title Title to get the timestamp from
1264 public static function revisiontimestamp( $parser, $title = null ) {
1265 $t = Title
::newFromText( $title );
1266 if ( is_null( $t ) ) {
1269 // fetch revision from cache/database and return the value
1270 $rev = self
::getCachedRevisionObject( $parser, $t );
1271 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1275 * Get the user from the last revision of a specified page.
1276 * @param Parser $parser
1277 * @param string $title Title to get the user from
1281 public static function revisionuser( $parser, $title = null ) {
1282 $t = Title
::newFromText( $title );
1283 if ( is_null( $t ) ) {
1286 // fetch revision from cache/database and return the value
1287 $rev = self
::getCachedRevisionObject( $parser, $t );
1288 return $rev ?
$rev->getUserText() : '';
1292 * Returns the sources of any cascading protection acting on a specified page.
1293 * Pages will not return their own title unless they transclude themselves.
1294 * This is an expensive parser function and can't be called too many times per page,
1295 * unless cascading protection sources for the page have already been loaded.
1297 * @param Parser $parser
1298 * @param string $title
1303 public static function cascadingsources( $parser, $title = '' ) {
1304 $titleObject = Title
::newFromText( $title );
1305 if ( !( $titleObject instanceof Title
) ) {
1306 $titleObject = $parser->mTitle
;
1308 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1309 ||
$parser->incrementExpensiveFunctionCount()
1312 $sources = $titleObject->getCascadeProtectionSources();
1313 foreach ( $sources[0] as $sourceTitle ) {
1314 $names[] = $sourceTitle->getPrefixedText();
1316 return implode( $names, '|' );