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
25 * Various core parser functions, registered in Parser::firstCallInit()
28 class CoreParserFunctions
{
30 * @param Parser $parser
33 public static function register( $parser ) {
34 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36 # Syntax for arguments (see Parser::setFunctionHook):
37 # "name for lookup in localized magic words array",
39 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
40 # instead of {{#int:...}})
42 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
43 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
44 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural', 'bidi',
45 'numberofpages', 'numberofusers', 'numberofactiveusers',
46 'numberofarticles', 'numberoffiles', 'numberofadmins',
47 'numberingroup', 'numberofedits', 'language',
48 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
49 'pagesincategory', 'pagesize', 'protectionlevel', 'protectionexpiry',
50 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
51 'subjectspace', 'subjectspacee', 'pagename', 'pagenamee',
52 'fullpagename', 'fullpagenamee', 'rootpagename', 'rootpagenamee',
53 'basepagename', 'basepagenamee', 'subpagename', 'subpagenamee',
54 'talkpagename', 'talkpagenamee', 'subjectpagename',
55 'subjectpagenamee', 'pageid', 'revisionid', 'revisionday',
56 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
57 'revisiontimestamp', 'revisionuser', 'cascadingsources',
59 foreach ( $noHashFunctions as $func ) {
60 $parser->setFunctionHook( $func, [ __CLASS__
, $func ], Parser
::SFH_NO_HASH
);
63 $parser->setFunctionHook(
65 [ __CLASS__
, 'mwnamespace' ],
68 $parser->setFunctionHook( 'int', [ __CLASS__
, 'intFunction' ], Parser
::SFH_NO_HASH
);
69 $parser->setFunctionHook( 'special', [ __CLASS__
, 'special' ] );
70 $parser->setFunctionHook( 'speciale', [ __CLASS__
, 'speciale' ] );
71 $parser->setFunctionHook( 'tag', [ __CLASS__
, 'tagObj' ], Parser
::SFH_OBJECT_ARGS
);
72 $parser->setFunctionHook( 'formatdate', [ __CLASS__
, 'formatDate' ] );
74 if ( $wgAllowDisplayTitle ) {
75 $parser->setFunctionHook(
77 [ __CLASS__
, 'displaytitle' ],
81 if ( $wgAllowSlowParserFunctions ) {
82 $parser->setFunctionHook(
84 [ __CLASS__
, 'pagesinnamespace' ],
91 * @param Parser $parser
92 * @param string $part1
95 public static function intFunction( $parser, $part1 = '' /*, ... */ ) {
96 if ( strval( $part1 ) !== '' ) {
97 $args = array_slice( func_get_args(), 2 );
98 $message = wfMessage( $part1, $args )
99 ->inLanguage( $parser->getOptions()->getUserLangObj() );
100 if ( !$message->exists() ) {
101 // When message does not exists, the message name is surrounded by angle
102 // and can result in a tag, therefore escape the angles
103 return $message->escaped();
105 return [ $message->plain(), 'noparse' => false ];
107 return [ 'found' => false ];
112 * @param Parser $parser
113 * @param string $date
114 * @param string $defaultPref
118 public static function formatDate( $parser, $date, $defaultPref = null ) {
119 $lang = $parser->getFunctionLang();
120 $df = DateFormatter
::getInstance( $lang );
122 $date = trim( $date );
124 $pref = $parser->getOptions()->getDateFormat();
126 // Specify a different default date format other than the normal default
127 // if the user has 'default' for their setting
128 if ( $pref == 'default' && $defaultPref ) {
129 $pref = $defaultPref;
132 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
136 public static function ns( $parser, $part1 = '' ) {
138 if ( intval( $part1 ) ||
$part1 == "0" ) {
139 $index = intval( $part1 );
141 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
143 if ( $index !== false ) {
144 return $wgContLang->getFormattedNsText( $index );
146 return [ 'found' => false ];
150 public static function nse( $parser, $part1 = '' ) {
151 $ret = self
::ns( $parser, $part1 );
152 if ( is_string( $ret ) ) {
153 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
159 * urlencodes a string according to one of three patterns: (bug 22474)
161 * By default (for HTTP "query" strings), spaces are encoded as '+'.
162 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
163 * For links to "wiki"s, or similar software, spaces are encoded as '_',
165 * @param Parser $parser
166 * @param string $s The text to encode.
167 * @param string $arg (optional): The type of encoding.
170 public static function urlencode( $parser, $s = '', $arg = null ) {
171 static $magicWords = null;
172 if ( is_null( $magicWords ) ) {
173 $magicWords = new MagicWordArray( [ 'url_path', 'url_query', 'url_wiki' ] );
175 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->getNamespace() == 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->getNamespace() == NS_USER
) {
344 $username = $title->getText();
347 // check parameter, or use the ParserOptions if in interface message
348 $user = User
::newFromName( $username );
350 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
351 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
352 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
354 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
359 * @param Parser $parser
360 * @param string $text
363 public static function plural( $parser, $text = '' ) {
364 $forms = array_slice( func_get_args(), 2 );
365 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
366 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
367 return $parser->getFunctionLang()->convertPlural( $text, $forms );
371 * @param Parser $parser
372 * @param string $text
375 public static function bidi( $parser, $text = '' ) {
376 return $parser->getFunctionLang()->embedBidi( $text );
380 * Override the title of the page when viewed, provided we've been given a
381 * title which will normalise to the canonical title
383 * @param Parser $parser Parent parser
384 * @param string $text Desired title text
385 * @param string $uarg
388 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
389 global $wgRestrictDisplayTitle;
391 static $magicWords = null;
392 if ( is_null( $magicWords ) ) {
393 $magicWords = new MagicWordArray( [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
395 $arg = $magicWords->matchStartToEnd( $uarg );
397 // parse a limited subset of wiki markup (just the single quote items)
398 $text = $parser->doQuotes( $text );
400 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
401 $text = $parser->killMarkers( $text );
403 // list of disallowed tags for DISPLAYTITLE
404 // these will be escaped even though they are allowed in normal wiki text
405 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
406 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
408 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
409 if ( $wgRestrictDisplayTitle ) {
410 $htmlTagsCallback = function ( &$params ) {
411 $decoded = Sanitizer
::decodeTagAttributes( $params );
413 if ( isset( $decoded['style'] ) ) {
414 // this is called later anyway, but we need it right now for the regexes below to be safe
415 // calling it twice doesn't hurt
416 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
418 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
419 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
423 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
426 $htmlTagsCallback = null;
429 // only requested titles that normalize to the actual title are allowed through
430 // if $wgRestrictDisplayTitle is true (it is by default)
431 // mimic the escaping process that occurs in OutputPage::setPageTitle
432 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
439 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
441 if ( !$wgRestrictDisplayTitle ||
442 ( $title instanceof Title
443 && !$title->hasFragment()
444 && $title->equals( $parser->mTitle
) )
446 $old = $parser->mOutput
->getProperty( 'displaytitle' );
447 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
448 $parser->mOutput
->setDisplayTitle( $text );
450 if ( $old !== false && $old !== $text && !$arg ) {
451 $converter = $parser->getConverterLanguage()->getConverter();
452 return '<span class="error">' .
453 wfMessage( 'duplicate-displaytitle',
454 // Message should be parsed, but these params should only be escaped.
455 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
456 $converter->markNoConversion( wfEscapeWikiText( $text ) )
457 )->inContentLanguage()->text() .
463 $converter = $parser->getConverterLanguage()->getConverter();
464 return '<span class="error">' .
465 wfMessage( 'restricted-displaytitle',
466 // Message should be parsed, but this param should only be escaped.
467 $converter->markNoConversion( wfEscapeWikiText( $text ) )
468 )->inContentLanguage()->text() .
474 * Matches the given value against the value of given magic word
476 * @param string $magicword Magic word key
477 * @param string $value Value to match
478 * @return bool True on successful match
480 private static function matchAgainstMagicword( $magicword, $value ) {
481 $value = trim( strval( $value ) );
482 if ( $value === '' ) {
485 $mwObject = MagicWord
::get( $magicword );
486 return $mwObject->matchStartToEnd( $value );
489 public static function formatRaw( $num, $raw ) {
490 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
494 return $wgContLang->formatNum( $num );
497 public static function numberofpages( $parser, $raw = null ) {
498 return self
::formatRaw( SiteStats
::pages(), $raw );
500 public static function numberofusers( $parser, $raw = null ) {
501 return self
::formatRaw( SiteStats
::users(), $raw );
503 public static function numberofactiveusers( $parser, $raw = null ) {
504 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
506 public static function numberofarticles( $parser, $raw = null ) {
507 return self
::formatRaw( SiteStats
::articles(), $raw );
509 public static function numberoffiles( $parser, $raw = null ) {
510 return self
::formatRaw( SiteStats
::images(), $raw );
512 public static function numberofadmins( $parser, $raw = null ) {
513 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
515 public static function numberofedits( $parser, $raw = null ) {
516 return self
::formatRaw( SiteStats
::edits(), $raw );
518 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
519 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
521 public static function numberingroup( $parser, $name = '', $raw = null ) {
522 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
526 * Given a title, return the namespace name that would be given by the
527 * corresponding magic word
528 * Note: function name changed to "mwnamespace" rather than "namespace"
529 * to not break PHP 5.3
530 * @param Parser $parser
531 * @param string $title
532 * @return mixed|string
534 public static function mwnamespace( $parser, $title = null ) {
535 $t = Title
::newFromText( $title );
536 if ( is_null( $t ) ) {
539 return str_replace( '_', ' ', $t->getNsText() );
541 public static function namespacee( $parser, $title = null ) {
542 $t = Title
::newFromText( $title );
543 if ( is_null( $t ) ) {
546 return wfUrlencode( $t->getNsText() );
548 public static function namespacenumber( $parser, $title = null ) {
549 $t = Title
::newFromText( $title );
550 if ( is_null( $t ) ) {
553 return $t->getNamespace();
555 public static function talkspace( $parser, $title = null ) {
556 $t = Title
::newFromText( $title );
557 if ( is_null( $t ) ||
!$t->canTalk() ) {
560 return str_replace( '_', ' ', $t->getTalkNsText() );
562 public static function talkspacee( $parser, $title = null ) {
563 $t = Title
::newFromText( $title );
564 if ( is_null( $t ) ||
!$t->canTalk() ) {
567 return wfUrlencode( $t->getTalkNsText() );
569 public static function subjectspace( $parser, $title = null ) {
570 $t = Title
::newFromText( $title );
571 if ( is_null( $t ) ) {
574 return str_replace( '_', ' ', $t->getSubjectNsText() );
576 public static function subjectspacee( $parser, $title = null ) {
577 $t = Title
::newFromText( $title );
578 if ( is_null( $t ) ) {
581 return wfUrlencode( $t->getSubjectNsText() );
585 * Functions to get and normalize pagenames, corresponding to the magic words
587 * @param Parser $parser
588 * @param string $title
591 public static function pagename( $parser, $title = null ) {
592 $t = Title
::newFromText( $title );
593 if ( is_null( $t ) ) {
596 return wfEscapeWikiText( $t->getText() );
598 public static function pagenamee( $parser, $title = null ) {
599 $t = Title
::newFromText( $title );
600 if ( is_null( $t ) ) {
603 return wfEscapeWikiText( $t->getPartialURL() );
605 public static function fullpagename( $parser, $title = null ) {
606 $t = Title
::newFromText( $title );
607 if ( is_null( $t ) ||
!$t->canTalk() ) {
610 return wfEscapeWikiText( $t->getPrefixedText() );
612 public static function fullpagenamee( $parser, $title = null ) {
613 $t = Title
::newFromText( $title );
614 if ( is_null( $t ) ||
!$t->canTalk() ) {
617 return wfEscapeWikiText( $t->getPrefixedURL() );
619 public static function subpagename( $parser, $title = null ) {
620 $t = Title
::newFromText( $title );
621 if ( is_null( $t ) ) {
624 return wfEscapeWikiText( $t->getSubpageText() );
626 public static function subpagenamee( $parser, $title = null ) {
627 $t = Title
::newFromText( $title );
628 if ( is_null( $t ) ) {
631 return wfEscapeWikiText( $t->getSubpageUrlForm() );
633 public static function rootpagename( $parser, $title = null ) {
634 $t = Title
::newFromText( $title );
635 if ( is_null( $t ) ) {
638 return wfEscapeWikiText( $t->getRootText() );
640 public static function rootpagenamee( $parser, $title = null ) {
641 $t = Title
::newFromText( $title );
642 if ( is_null( $t ) ) {
645 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
647 public static function basepagename( $parser, $title = null ) {
648 $t = Title
::newFromText( $title );
649 if ( is_null( $t ) ) {
652 return wfEscapeWikiText( $t->getBaseText() );
654 public static function basepagenamee( $parser, $title = null ) {
655 $t = Title
::newFromText( $title );
656 if ( is_null( $t ) ) {
659 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
661 public static function talkpagename( $parser, $title = null ) {
662 $t = Title
::newFromText( $title );
663 if ( is_null( $t ) ||
!$t->canTalk() ) {
666 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
668 public static function talkpagenamee( $parser, $title = null ) {
669 $t = Title
::newFromText( $title );
670 if ( is_null( $t ) ||
!$t->canTalk() ) {
673 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
675 public static function subjectpagename( $parser, $title = null ) {
676 $t = Title
::newFromText( $title );
677 if ( is_null( $t ) ) {
680 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
682 public static function subjectpagenamee( $parser, $title = null ) {
683 $t = Title
::newFromText( $title );
684 if ( is_null( $t ) ) {
687 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
691 * Return the number of pages, files or subcats in the given category,
692 * or 0 if it's nonexistent. This is an expensive parser function and
693 * can't be called too many times per page.
694 * @param Parser $parser
695 * @param string $name
696 * @param string $arg1
697 * @param string $arg2
700 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
702 static $magicWords = null;
703 if ( is_null( $magicWords ) ) {
704 $magicWords = new MagicWordArray( [
705 'pagesincategory_all',
706 'pagesincategory_pages',
707 'pagesincategory_subcats',
708 'pagesincategory_files'
713 // split the given option to its variable
714 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
715 // {{pagesincategory:|raw[|type]}}
717 $type = $magicWords->matchStartToEnd( $arg2 );
719 // {{pagesincategory:[|type[|raw]]}}
720 $type = $magicWords->matchStartToEnd( $arg1 );
723 if ( !$type ) { // backward compatibility
724 $type = 'pagesincategory_all';
727 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
728 if ( !$title ) { # invalid title
729 return self
::formatRaw( 0, $raw );
731 $wgContLang->findVariantLink( $name, $title, true );
733 // Normalize name for cache
734 $name = $title->getDBkey();
736 if ( !isset( $cache[$name] ) ) {
737 $category = Category
::newFromTitle( $title );
739 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
740 if ( $parser->incrementExpensiveFunctionCount() ) {
741 // $allCount is the total number of cat members,
742 // not the count of how many members are normal pages.
743 $allCount = (int)$category->getPageCount();
744 $subcatCount = (int)$category->getSubcatCount();
745 $fileCount = (int)$category->getFileCount();
746 $pagesCount = $allCount - $subcatCount - $fileCount;
748 $cache[$name]['pagesincategory_all'] = $allCount;
749 $cache[$name]['pagesincategory_pages'] = $pagesCount;
750 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
751 $cache[$name]['pagesincategory_files'] = $fileCount;
754 $count = $cache[$name][$type];
755 return self
::formatRaw( $count, $raw );
759 * Return the size of the given page, or 0 if it's nonexistent. This is an
760 * expensive parser function and can't be called too many times per page.
762 * @param Parser $parser
763 * @param string $page Name of page to check (Default: empty string)
764 * @param string $raw Should number be human readable with commas or just number
767 public static function pagesize( $parser, $page = '', $raw = null ) {
768 $title = Title
::newFromText( $page );
770 if ( !is_object( $title ) ) {
771 return self
::formatRaw( 0, $raw );
774 // fetch revision from cache/database and return the value
775 $rev = self
::getCachedRevisionObject( $parser, $title );
776 $length = $rev ?
$rev->getSize() : 0;
777 return self
::formatRaw( $length, $raw );
781 * Returns the requested protection level for the current page. This
782 * is an expensive parser function and can't be called too many times
783 * per page, unless the protection levels/expiries for the given title
784 * have already been retrieved
786 * @param Parser $parser
787 * @param string $type
788 * @param string $title
792 public static function protectionlevel( $parser, $type = '', $title = '' ) {
793 $titleObject = Title
::newFromText( $title );
794 if ( !( $titleObject instanceof Title
) ) {
795 $titleObject = $parser->mTitle
;
797 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
798 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
799 # Title::getRestrictions returns an array, its possible it may have
800 # multiple values in the future
801 return implode( $restrictions, ',' );
807 * Returns the requested protection expiry for the current page. This
808 * is an expensive parser function and can't be called too many times
809 * per page, unless the protection levels/expiries for the given title
810 * have already been retrieved
812 * @param Parser $parser
813 * @param string $type
814 * @param string $title
818 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
819 $titleObject = Title
::newFromText( $title );
820 if ( !( $titleObject instanceof Title
) ) {
821 $titleObject = $parser->mTitle
;
823 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
824 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
825 // getRestrictionExpiry() returns false on invalid type; trying to
826 // match protectionlevel() function that returns empty string instead
827 if ( $expiry === false ) {
836 * Gives language names.
837 * @param Parser $parser
838 * @param string $code Language code (of which to get name)
839 * @param string $inLanguage Language code (in which to get name)
842 public static function language( $parser, $code = '', $inLanguage = '' ) {
843 $code = strtolower( $code );
844 $inLanguage = strtolower( $inLanguage );
845 $lang = Language
::fetchLanguageName( $code, $inLanguage );
846 return $lang !== '' ?
$lang : wfBCP47( $code );
850 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
851 * @param Parser $parser
852 * @param string $string
854 * @param string $padding
855 * @param int $direction
858 public static function pad(
859 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
861 $padding = $parser->killMarkers( $padding );
862 $lengthOfPadding = mb_strlen( $padding );
863 if ( $lengthOfPadding == 0 ) {
867 # The remaining length to add counts down to 0 as padding is added
868 $length = min( $length, 500 ) - mb_strlen( $string );
869 # $finalPadding is just $padding repeated enough times so that
870 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
872 while ( $length > 0 ) {
873 # If $length < $lengthofPadding, truncate $padding so we get the
874 # exact length desired.
875 $finalPadding .= mb_substr( $padding, 0, $length );
876 $length -= $lengthOfPadding;
879 if ( $direction == STR_PAD_LEFT
) {
880 return $finalPadding . $string;
882 return $string . $finalPadding;
886 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
887 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
890 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
891 return self
::pad( $parser, $string, $length, $padding );
895 * @param Parser $parser
896 * @param string $text
899 public static function anchorencode( $parser, $text ) {
900 $text = $parser->killMarkers( $text );
901 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
904 public static function special( $parser, $text ) {
905 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
907 $title = SpecialPage
::getTitleFor( $page, $subpage );
908 return $title->getPrefixedText();
910 // unknown special page, just use the given text as its title, if at all possible
911 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
912 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
916 public static function speciale( $parser, $text ) {
917 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
921 * @param Parser $parser
922 * @param string $text The sortkey to use
923 * @param string $uarg Either "noreplace" or "noerror" (in en)
924 * both suppress errors, and noreplace does nothing if
925 * a default sortkey already exists.
928 public static function defaultsort( $parser, $text, $uarg = '' ) {
929 static $magicWords = null;
930 if ( is_null( $magicWords ) ) {
931 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
933 $arg = $magicWords->matchStartToEnd( $uarg );
935 $text = trim( $text );
936 if ( strlen( $text ) == 0 ) {
939 $old = $parser->getCustomDefaultSort();
940 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
941 $parser->setDefaultSort( $text );
944 if ( $old === false ||
$old == $text ||
$arg ) {
947 $converter = $parser->getConverterLanguage()->getConverter();
948 return '<span class="error">' .
949 wfMessage( 'duplicate-defaultsort',
950 // Message should be parsed, but these params should only be escaped.
951 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
952 $converter->markNoConversion( wfEscapeWikiText( $text ) )
953 )->inContentLanguage()->text() .
959 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
960 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
961 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
963 * @param Parser $parser
964 * @param string $name
965 * @param string $argA
966 * @param string $argB
967 * @return array|string
969 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
970 $file = wfFindFile( $name );
972 if ( $argA == 'nowiki' ) {
973 // {{filepath: | option [| size] }}
975 $parsedWidthParam = $parser->parseWidthParam( $argB );
977 // {{filepath: [| size [|option]] }}
978 $parsedWidthParam = $parser->parseWidthParam( $argA );
979 $isNowiki = ( $argB == 'nowiki' );
983 $url = $file->getFullUrl();
985 // If a size is requested...
986 if ( count( $parsedWidthParam ) ) {
987 $mto = $file->transform( $parsedWidthParam );
989 if ( $mto && !$mto->isError() ) {
990 // ... change the URL to point to a thumbnail.
991 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
995 return [ $url, 'nowiki' => true ];
1004 * Parser function to extension tag adaptor
1005 * @param Parser $parser
1006 * @param PPFrame $frame
1007 * @param PPNode[] $args
1010 public static function tagObj( $parser, $frame, $args ) {
1011 if ( !count( $args ) ) {
1014 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1016 if ( count( $args ) ) {
1017 $inner = $frame->expand( array_shift( $args ) );
1023 foreach ( $args as $arg ) {
1024 $bits = $arg->splitArg();
1025 if ( strval( $bits['index'] ) === '' ) {
1026 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
1027 $value = trim( $frame->expand( $bits['value'] ) );
1028 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1029 $value = isset( $m[1] ) ?
$m[1] : '';
1031 $attributes[$name] = $value;
1035 $stripList = $parser->getStripList();
1036 if ( !in_array( $tagName, $stripList ) ) {
1037 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1039 foreach ( $attributes as $name => $value ) {
1040 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1042 if ( $inner === null ) {
1043 return "<$tagName$attrText/>";
1045 return "<$tagName$attrText>$inner</$tagName>";
1051 'attributes' => $attributes,
1052 'close' => "</$tagName>",
1054 return $parser->extensionSubstitution( $params, $frame );
1058 * Fetched the current revision of the given title and return this.
1059 * Will increment the expensive function count and
1060 * add a template link to get the value refreshed on changes.
1061 * For a given title, which is equal to the current parser title,
1062 * the revision object from the parser is used, when that is the current one
1064 * @param Parser $parser
1065 * @param Title $title
1069 private static function getCachedRevisionObject( $parser, $title = null ) {
1070 if ( is_null( $title ) ) {
1074 // Use the revision from the parser itself, when param is the current page
1075 // and the revision is the current one
1076 if ( $title->equals( $parser->getTitle() ) ) {
1077 $parserRev = $parser->getRevisionObject();
1078 if ( $parserRev && $parserRev->isCurrent() ) {
1079 // force reparse after edit with vary-revision flag
1080 $parser->getOutput()->setFlag( 'vary-revision' );
1081 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1086 // Normalize name for cache
1087 $page = $title->getPrefixedDBkey();
1089 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1090 && !$parser->incrementExpensiveFunctionCount() ) {
1093 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1094 $pageID = $rev ?
$rev->getPage() : 0;
1095 $revID = $rev ?
$rev->getId() : 0;
1097 // Register dependency in templatelinks
1098 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1104 * Get the pageid of a specified page
1105 * @param Parser $parser
1106 * @param string $title Title to get the pageid from
1107 * @return int|null|string
1110 public static function pageid( $parser, $title = null ) {
1111 $t = Title
::newFromText( $title );
1112 if ( is_null( $t ) ) {
1115 // Use title from parser to have correct pageid after edit
1116 if ( $t->equals( $parser->getTitle() ) ) {
1117 $t = $parser->getTitle();
1118 return $t->getArticleID();
1121 // These can't have ids
1122 if ( !$t->canExist() ||
$t->isExternal() ) {
1126 // Check the link cache, maybe something already looked it up.
1127 $linkCache = LinkCache
::singleton();
1128 $pdbk = $t->getPrefixedDBkey();
1129 $id = $linkCache->getGoodLinkID( $pdbk );
1131 $parser->mOutput
->addLink( $t, $id );
1134 if ( $linkCache->isBadLink( $pdbk ) ) {
1135 $parser->mOutput
->addLink( $t, 0 );
1139 // We need to load it from the DB, so mark expensive
1140 if ( $parser->incrementExpensiveFunctionCount() ) {
1141 $id = $t->getArticleID();
1142 $parser->mOutput
->addLink( $t, $id );
1149 * Get the id from the last revision of a specified page.
1150 * @param Parser $parser
1151 * @param string $title Title to get the id from
1152 * @return int|null|string
1155 public static function revisionid( $parser, $title = null ) {
1156 $t = Title
::newFromText( $title );
1157 if ( is_null( $t ) ) {
1160 // fetch revision from cache/database and return the value
1161 $rev = self
::getCachedRevisionObject( $parser, $t );
1162 return $rev ?
$rev->getId() : '';
1166 * Get the day from the last revision of a specified page.
1167 * @param Parser $parser
1168 * @param string $title Title to get the day from
1172 public static function revisionday( $parser, $title = null ) {
1173 $t = Title
::newFromText( $title );
1174 if ( is_null( $t ) ) {
1177 // fetch revision from cache/database and return the value
1178 $rev = self
::getCachedRevisionObject( $parser, $t );
1179 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1183 * Get the day with leading zeros from the last revision of a specified page.
1184 * @param Parser $parser
1185 * @param string $title Title to get the day from
1189 public static function revisionday2( $parser, $title = null ) {
1190 $t = Title
::newFromText( $title );
1191 if ( is_null( $t ) ) {
1194 // fetch revision from cache/database and return the value
1195 $rev = self
::getCachedRevisionObject( $parser, $t );
1196 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1200 * Get the month with leading zeros from the last revision of a specified page.
1201 * @param Parser $parser
1202 * @param string $title Title to get the month from
1206 public static function revisionmonth( $parser, $title = null ) {
1207 $t = Title
::newFromText( $title );
1208 if ( is_null( $t ) ) {
1211 // fetch revision from cache/database and return the value
1212 $rev = self
::getCachedRevisionObject( $parser, $t );
1213 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1217 * Get the month from the last revision of a specified page.
1218 * @param Parser $parser
1219 * @param string $title Title to get the month from
1223 public static function revisionmonth1( $parser, $title = null ) {
1224 $t = Title
::newFromText( $title );
1225 if ( is_null( $t ) ) {
1228 // fetch revision from cache/database and return the value
1229 $rev = self
::getCachedRevisionObject( $parser, $t );
1230 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1234 * Get the year from the last revision of a specified page.
1235 * @param Parser $parser
1236 * @param string $title Title to get the year from
1240 public static function revisionyear( $parser, $title = null ) {
1241 $t = Title
::newFromText( $title );
1242 if ( is_null( $t ) ) {
1245 // fetch revision from cache/database and return the value
1246 $rev = self
::getCachedRevisionObject( $parser, $t );
1247 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1251 * Get the timestamp from the last revision of a specified page.
1252 * @param Parser $parser
1253 * @param string $title Title to get the timestamp from
1257 public static function revisiontimestamp( $parser, $title = null ) {
1258 $t = Title
::newFromText( $title );
1259 if ( is_null( $t ) ) {
1262 // fetch revision from cache/database and return the value
1263 $rev = self
::getCachedRevisionObject( $parser, $t );
1264 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1268 * Get the user from the last revision of a specified page.
1269 * @param Parser $parser
1270 * @param string $title Title to get the user from
1274 public static function revisionuser( $parser, $title = null ) {
1275 $t = Title
::newFromText( $title );
1276 if ( is_null( $t ) ) {
1279 // fetch revision from cache/database and return the value
1280 $rev = self
::getCachedRevisionObject( $parser, $t );
1281 return $rev ?
$rev->getUserText() : '';
1285 * Returns the sources of any cascading protection acting on a specified page.
1286 * Pages will not return their own title unless they transclude themselves.
1287 * This is an expensive parser function and can't be called too many times per page,
1288 * unless cascading protection sources for the page have already been loaded.
1290 * @param Parser $parser
1291 * @param string $title
1296 public static function cascadingsources( $parser, $title = '' ) {
1297 $titleObject = Title
::newFromText( $title );
1298 if ( !( $titleObject instanceof Title
) ) {
1299 $titleObject = $parser->mTitle
;
1301 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1302 ||
$parser->incrementExpensiveFunctionCount()
1305 $sources = $titleObject->getCascadeProtectionSources();
1306 foreach ( $sources[0] as $sourceTitle ) {
1307 $names[] = $sourceTitle->getPrefixedText();
1309 return implode( $names, '|' );