Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / parser / CoreParserFunctions.php
blob6aa3accebe4c027e18c09d3882ed68970b0ab724
1 <?php
2 /**
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
20 * @file
21 * @ingroup Parser
23 use MediaWiki\MediaWikiServices;
25 /**
26 * Various core parser functions, registered in Parser::firstCallInit()
27 * @ingroup Parser
29 class CoreParserFunctions {
30 /**
31 * @param Parser $parser
32 * @return void
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",
39 # function callback,
40 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
41 # instead of {{#int:...}})
42 $noHashFunctions = [
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(
65 'namespace',
66 [ __CLASS__, 'mwnamespace' ],
67 Parser::SFH_NO_HASH
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(
77 'displaytitle',
78 [ __CLASS__, 'displaytitle' ],
79 Parser::SFH_NO_HASH
82 if ( $wgAllowSlowParserFunctions ) {
83 $parser->setFunctionHook(
84 'pagesinnamespace',
85 [ __CLASS__, 'pagesinnamespace' ],
86 Parser::SFH_NO_HASH
91 /**
92 * @param Parser $parser
93 * @param string $part1
94 * @return array
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 ];
107 } else {
108 return [ 'found' => false ];
113 * @param Parser $parser
114 * @param string $date
115 * @param string $defaultPref
117 * @return string
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' ] );
134 return $date;
137 public static function ns( $parser, $part1 = '' ) {
138 global $wgContLang;
139 if ( intval( $part1 ) || $part1 == "0" ) {
140 $index = intval( $part1 );
141 } else {
142 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
144 if ( $index !== false ) {
145 return $wgContLang->getFormattedNsText( $index );
146 } else {
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 ) );
156 return $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.
169 * @return string
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 ' '.
179 case 'url_wiki':
180 $func = 'wfUrlencode';
181 $s = str_replace( ' ', '_', $s );
182 break;
184 // Encode for an HTTP Path, '%20' for ' '.
185 case 'url_path':
186 $func = 'rawurlencode';
187 break;
189 // Encode for HTTP query, '+' for ' '.
190 case 'url_query':
191 default:
192 $func = 'urlencode';
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 = '' ) {
200 global $wgContLang;
201 return $wgContLang->lcfirst( $s );
204 public static function ucfirst( $parser, $s = '' ) {
205 global $wgContLang;
206 return $wgContLang->ucfirst( $s );
210 * @param Parser $parser
211 * @param string $s
212 * @return string
214 public static function lc( $parser, $s = '' ) {
215 global $wgContLang;
216 return $parser->markerSkipCallback( $s, [ $wgContLang, 'lc' ] );
220 * @param Parser $parser
221 * @param string $s
222 * @return string
224 public static function uc( $parser, $s = '' ) {
225 global $wgContLang;
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 ) ) {
236 return $temp;
237 } else {
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 ) ) {
249 return $temp;
250 } else {
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 ) ) {
262 return $temp;
263 } else {
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->inNamespace( NS_MEDIA ) ) {
280 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
282 if ( !is_null( $arg ) ) {
283 $text = $title->$func( $arg );
284 } else {
285 $text = $title->$func();
287 return $text;
288 } else {
289 return [ 'found' => false ];
294 * @param Parser $parser
295 * @param string $num
296 * @param string $arg
297 * @return string
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' ];
304 } else {
305 $func = [ $parser->getFunctionLang(), 'formatNum' ];
307 return $parser->markerSkipCallback( $num, $func );
311 * @param Parser $parser
312 * @param string $case
313 * @param string $word
314 * @return string
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
324 * @return string
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 ) {
331 return '';
332 } elseif ( count( $forms ) === 1 ) {
333 return $forms[0];
336 $username = trim( $username );
338 // default
339 $gender = User::getDefaultOption( 'gender' );
341 // allow prefix.
342 $title = Title::newFromText( $username );
344 if ( $title && $title->inNamespace( 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();
351 if ( $user ) {
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 );
357 return $ret;
361 * @param Parser $parser
362 * @param string $text
363 * @return string
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
375 * @return string
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
388 * @return string
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 );
427 } else {
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(
435 $text,
436 $htmlTagsCallback,
439 $bad
440 ) );
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() .
460 '</span>';
461 } else {
462 return '';
464 } else {
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 ) )
470 )->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 === '' ) {
486 return false;
488 $mwObject = MagicWord::get( $magicword );
489 return $mwObject->matchStartToEnd( $value );
493 * Formats a number according to a language.
495 * @param int|float $num
496 * @param string $raw
497 * @param Language|StubUserLang $language
498 * @return string
500 public static function formatRaw( $num, $raw, $language ) {
501 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
502 return $num;
503 } else {
504 return $language->formatNum( $num );
508 public static function numberofpages( $parser, $raw = null ) {
509 return self::formatRaw( SiteStats::pages(), $raw, $parser->getFunctionLang() );
512 public static function numberofusers( $parser, $raw = null ) {
513 return self::formatRaw( SiteStats::users(), $raw, $parser->getFunctionLang() );
515 public static function numberofactiveusers( $parser, $raw = null ) {
516 return self::formatRaw( SiteStats::activeUsers(), $raw, $parser->getFunctionLang() );
519 public static function numberofarticles( $parser, $raw = null ) {
520 return self::formatRaw( SiteStats::articles(), $raw, $parser->getFunctionLang() );
523 public static function numberoffiles( $parser, $raw = null ) {
524 return self::formatRaw( SiteStats::images(), $raw, $parser->getFunctionLang() );
527 public static function numberofadmins( $parser, $raw = null ) {
528 return self::formatRaw(
529 SiteStats::numberingroup( 'sysop' ),
530 $raw,
531 $parser->getFunctionLang()
535 public static function numberofedits( $parser, $raw = null ) {
536 return self::formatRaw( SiteStats::edits(), $raw, $parser->getFunctionLang() );
539 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
540 return self::formatRaw(
541 SiteStats::pagesInNs( intval( $namespace ) ),
542 $raw,
543 $parser->getFunctionLang()
546 public static function numberingroup( $parser, $name = '', $raw = null ) {
547 return self::formatRaw(
548 SiteStats::numberingroup( strtolower( $name ) ),
549 $raw,
550 $parser->getFunctionLang()
555 * Given a title, return the namespace name that would be given by the
556 * corresponding magic word
557 * Note: function name changed to "mwnamespace" rather than "namespace"
558 * to not break PHP 5.3
559 * @param Parser $parser
560 * @param string $title
561 * @return mixed|string
563 public static function mwnamespace( $parser, $title = null ) {
564 $t = Title::newFromText( $title );
565 if ( is_null( $t ) ) {
566 return '';
568 return str_replace( '_', ' ', $t->getNsText() );
570 public static function namespacee( $parser, $title = null ) {
571 $t = Title::newFromText( $title );
572 if ( is_null( $t ) ) {
573 return '';
575 return wfUrlencode( $t->getNsText() );
577 public static function namespacenumber( $parser, $title = null ) {
578 $t = Title::newFromText( $title );
579 if ( is_null( $t ) ) {
580 return '';
582 return $t->getNamespace();
584 public static function talkspace( $parser, $title = null ) {
585 $t = Title::newFromText( $title );
586 if ( is_null( $t ) || !$t->canTalk() ) {
587 return '';
589 return str_replace( '_', ' ', $t->getTalkNsText() );
591 public static function talkspacee( $parser, $title = null ) {
592 $t = Title::newFromText( $title );
593 if ( is_null( $t ) || !$t->canTalk() ) {
594 return '';
596 return wfUrlencode( $t->getTalkNsText() );
598 public static function subjectspace( $parser, $title = null ) {
599 $t = Title::newFromText( $title );
600 if ( is_null( $t ) ) {
601 return '';
603 return str_replace( '_', ' ', $t->getSubjectNsText() );
605 public static function subjectspacee( $parser, $title = null ) {
606 $t = Title::newFromText( $title );
607 if ( is_null( $t ) ) {
608 return '';
610 return wfUrlencode( $t->getSubjectNsText() );
614 * Functions to get and normalize pagenames, corresponding to the magic words
615 * of the same names
616 * @param Parser $parser
617 * @param string $title
618 * @return string
620 public static function pagename( $parser, $title = null ) {
621 $t = Title::newFromText( $title );
622 if ( is_null( $t ) ) {
623 return '';
625 return wfEscapeWikiText( $t->getText() );
627 public static function pagenamee( $parser, $title = null ) {
628 $t = Title::newFromText( $title );
629 if ( is_null( $t ) ) {
630 return '';
632 return wfEscapeWikiText( $t->getPartialURL() );
634 public static function fullpagename( $parser, $title = null ) {
635 $t = Title::newFromText( $title );
636 if ( is_null( $t ) || !$t->canTalk() ) {
637 return '';
639 return wfEscapeWikiText( $t->getPrefixedText() );
641 public static function fullpagenamee( $parser, $title = null ) {
642 $t = Title::newFromText( $title );
643 if ( is_null( $t ) || !$t->canTalk() ) {
644 return '';
646 return wfEscapeWikiText( $t->getPrefixedURL() );
648 public static function subpagename( $parser, $title = null ) {
649 $t = Title::newFromText( $title );
650 if ( is_null( $t ) ) {
651 return '';
653 return wfEscapeWikiText( $t->getSubpageText() );
655 public static function subpagenamee( $parser, $title = null ) {
656 $t = Title::newFromText( $title );
657 if ( is_null( $t ) ) {
658 return '';
660 return wfEscapeWikiText( $t->getSubpageUrlForm() );
662 public static function rootpagename( $parser, $title = null ) {
663 $t = Title::newFromText( $title );
664 if ( is_null( $t ) ) {
665 return '';
667 return wfEscapeWikiText( $t->getRootText() );
669 public static function rootpagenamee( $parser, $title = null ) {
670 $t = Title::newFromText( $title );
671 if ( is_null( $t ) ) {
672 return '';
674 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
676 public static function basepagename( $parser, $title = null ) {
677 $t = Title::newFromText( $title );
678 if ( is_null( $t ) ) {
679 return '';
681 return wfEscapeWikiText( $t->getBaseText() );
683 public static function basepagenamee( $parser, $title = null ) {
684 $t = Title::newFromText( $title );
685 if ( is_null( $t ) ) {
686 return '';
688 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
690 public static function talkpagename( $parser, $title = null ) {
691 $t = Title::newFromText( $title );
692 if ( is_null( $t ) || !$t->canTalk() ) {
693 return '';
695 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
697 public static function talkpagenamee( $parser, $title = null ) {
698 $t = Title::newFromText( $title );
699 if ( is_null( $t ) || !$t->canTalk() ) {
700 return '';
702 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
704 public static function subjectpagename( $parser, $title = null ) {
705 $t = Title::newFromText( $title );
706 if ( is_null( $t ) ) {
707 return '';
709 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
711 public static function subjectpagenamee( $parser, $title = null ) {
712 $t = Title::newFromText( $title );
713 if ( is_null( $t ) ) {
714 return '';
716 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
720 * Return the number of pages, files or subcats in the given category,
721 * or 0 if it's nonexistent. This is an expensive parser function and
722 * can't be called too many times per page.
723 * @param Parser $parser
724 * @param string $name
725 * @param string $arg1
726 * @param string $arg2
727 * @return string
729 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
730 global $wgContLang;
731 static $magicWords = null;
732 if ( is_null( $magicWords ) ) {
733 $magicWords = new MagicWordArray( [
734 'pagesincategory_all',
735 'pagesincategory_pages',
736 'pagesincategory_subcats',
737 'pagesincategory_files'
738 ] );
740 static $cache = [];
742 // split the given option to its variable
743 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
744 // {{pagesincategory:|raw[|type]}}
745 $raw = $arg1;
746 $type = $magicWords->matchStartToEnd( $arg2 );
747 } else {
748 // {{pagesincategory:[|type[|raw]]}}
749 $type = $magicWords->matchStartToEnd( $arg1 );
750 $raw = $arg2;
752 if ( !$type ) { // backward compatibility
753 $type = 'pagesincategory_all';
756 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
757 if ( !$title ) { # invalid title
758 return self::formatRaw( 0, $raw, $parser->getFunctionLang() );
760 $wgContLang->findVariantLink( $name, $title, true );
762 // Normalize name for cache
763 $name = $title->getDBkey();
765 if ( !isset( $cache[$name] ) ) {
766 $category = Category::newFromTitle( $title );
768 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
769 if ( $parser->incrementExpensiveFunctionCount() ) {
770 // $allCount is the total number of cat members,
771 // not the count of how many members are normal pages.
772 $allCount = (int)$category->getPageCount();
773 $subcatCount = (int)$category->getSubcatCount();
774 $fileCount = (int)$category->getFileCount();
775 $pagesCount = $allCount - $subcatCount - $fileCount;
777 $cache[$name]['pagesincategory_all'] = $allCount;
778 $cache[$name]['pagesincategory_pages'] = $pagesCount;
779 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
780 $cache[$name]['pagesincategory_files'] = $fileCount;
783 $count = $cache[$name][$type];
784 return self::formatRaw( $count, $raw, $parser->getFunctionLang() );
788 * Return the size of the given page, or 0 if it's nonexistent. This is an
789 * expensive parser function and can't be called too many times per page.
791 * @param Parser $parser
792 * @param string $page Name of page to check (Default: empty string)
793 * @param string $raw Should number be human readable with commas or just number
794 * @return string
796 public static function pagesize( $parser, $page = '', $raw = null ) {
797 $title = Title::newFromText( $page );
799 if ( !is_object( $title ) ) {
800 return self::formatRaw( 0, $raw, $parser->getFunctionLang() );
803 // fetch revision from cache/database and return the value
804 $rev = self::getCachedRevisionObject( $parser, $title );
805 $length = $rev ? $rev->getSize() : 0;
806 if ( $length === null ) {
807 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
808 $length = 0;
810 return self::formatRaw( $length, $raw, $parser->getFunctionLang() );
814 * Returns the requested protection level 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
823 * @return string
825 public static function protectionlevel( $parser, $type = '', $title = '' ) {
826 $titleObject = Title::newFromText( $title );
827 if ( !( $titleObject instanceof Title ) ) {
828 $titleObject = $parser->mTitle;
830 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
831 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
832 # Title::getRestrictions returns an array, its possible it may have
833 # multiple values in the future
834 return implode( $restrictions, ',' );
836 return '';
840 * Returns the requested protection expiry for the current page. This
841 * is an expensive parser function and can't be called too many times
842 * per page, unless the protection levels/expiries for the given title
843 * have already been retrieved
845 * @param Parser $parser
846 * @param string $type
847 * @param string $title
849 * @return string
851 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
852 $titleObject = Title::newFromText( $title );
853 if ( !( $titleObject instanceof Title ) ) {
854 $titleObject = $parser->mTitle;
856 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
857 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
858 // getRestrictionExpiry() returns false on invalid type; trying to
859 // match protectionlevel() function that returns empty string instead
860 if ( $expiry === false ) {
861 $expiry = '';
863 return $expiry;
865 return '';
869 * Gives language names.
870 * @param Parser $parser
871 * @param string $code Language code (of which to get name)
872 * @param string $inLanguage Language code (in which to get name)
873 * @return string
875 public static function language( $parser, $code = '', $inLanguage = '' ) {
876 $code = strtolower( $code );
877 $inLanguage = strtolower( $inLanguage );
878 $lang = Language::fetchLanguageName( $code, $inLanguage );
879 return $lang !== '' ? $lang : wfBCP47( $code );
883 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
884 * @param Parser $parser
885 * @param string $string
886 * @param int $length
887 * @param string $padding
888 * @param int $direction
889 * @return string
891 public static function pad(
892 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
894 $padding = $parser->killMarkers( $padding );
895 $lengthOfPadding = mb_strlen( $padding );
896 if ( $lengthOfPadding == 0 ) {
897 return $string;
900 # The remaining length to add counts down to 0 as padding is added
901 $length = min( $length, 500 ) - mb_strlen( $string );
902 # $finalPadding is just $padding repeated enough times so that
903 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
904 $finalPadding = '';
905 while ( $length > 0 ) {
906 # If $length < $lengthofPadding, truncate $padding so we get the
907 # exact length desired.
908 $finalPadding .= mb_substr( $padding, 0, $length );
909 $length -= $lengthOfPadding;
912 if ( $direction == STR_PAD_LEFT ) {
913 return $finalPadding . $string;
914 } else {
915 return $string . $finalPadding;
919 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
920 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
923 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
924 return self::pad( $parser, $string, $length, $padding );
928 * @param Parser $parser
929 * @param string $text
930 * @return string
932 public static function anchorencode( $parser, $text ) {
933 $text = $parser->killMarkers( $text );
934 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
937 public static function special( $parser, $text ) {
938 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
939 if ( $page ) {
940 $title = SpecialPage::getTitleFor( $page, $subpage );
941 return $title->getPrefixedText();
942 } else {
943 // unknown special page, just use the given text as its title, if at all possible
944 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
945 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
949 public static function speciale( $parser, $text ) {
950 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
954 * @param Parser $parser
955 * @param string $text The sortkey to use
956 * @param string $uarg Either "noreplace" or "noerror" (in en)
957 * both suppress errors, and noreplace does nothing if
958 * a default sortkey already exists.
959 * @return string
961 public static function defaultsort( $parser, $text, $uarg = '' ) {
962 static $magicWords = null;
963 if ( is_null( $magicWords ) ) {
964 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
966 $arg = $magicWords->matchStartToEnd( $uarg );
968 $text = trim( $text );
969 if ( strlen( $text ) == 0 ) {
970 return '';
972 $old = $parser->getCustomDefaultSort();
973 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
974 $parser->setDefaultSort( $text );
977 if ( $old === false || $old == $text || $arg ) {
978 return '';
979 } else {
980 $converter = $parser->getConverterLanguage()->getConverter();
981 return '<span class="error">' .
982 wfMessage( 'duplicate-defaultsort',
983 // Message should be parsed, but these params should only be escaped.
984 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
985 $converter->markNoConversion( wfEscapeWikiText( $text ) )
986 )->inContentLanguage()->text() .
987 '</span>';
992 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
993 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
994 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
996 * @param Parser $parser
997 * @param string $name
998 * @param string $argA
999 * @param string $argB
1000 * @return array|string
1002 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1003 $file = wfFindFile( $name );
1005 if ( $argA == 'nowiki' ) {
1006 // {{filepath: | option [| size] }}
1007 $isNowiki = true;
1008 $parsedWidthParam = $parser->parseWidthParam( $argB );
1009 } else {
1010 // {{filepath: [| size [|option]] }}
1011 $parsedWidthParam = $parser->parseWidthParam( $argA );
1012 $isNowiki = ( $argB == 'nowiki' );
1015 if ( $file ) {
1016 $url = $file->getFullUrl();
1018 // If a size is requested...
1019 if ( count( $parsedWidthParam ) ) {
1020 $mto = $file->transform( $parsedWidthParam );
1021 // ... and we can
1022 if ( $mto && !$mto->isError() ) {
1023 // ... change the URL to point to a thumbnail.
1024 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
1027 if ( $isNowiki ) {
1028 return [ $url, 'nowiki' => true ];
1030 return $url;
1031 } else {
1032 return '';
1037 * Parser function to extension tag adaptor
1038 * @param Parser $parser
1039 * @param PPFrame $frame
1040 * @param PPNode[] $args
1041 * @return string
1043 public static function tagObj( $parser, $frame, $args ) {
1044 if ( !count( $args ) ) {
1045 return '';
1047 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1049 if ( count( $args ) ) {
1050 $inner = $frame->expand( array_shift( $args ) );
1051 } else {
1052 $inner = null;
1055 $attributes = [];
1056 foreach ( $args as $arg ) {
1057 $bits = $arg->splitArg();
1058 if ( strval( $bits['index'] ) === '' ) {
1059 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1060 $value = trim( $frame->expand( $bits['value'] ) );
1061 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1062 $value = isset( $m[1] ) ? $m[1] : '';
1064 $attributes[$name] = $value;
1068 $stripList = $parser->getStripList();
1069 if ( !in_array( $tagName, $stripList ) ) {
1070 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1071 $attrText = '';
1072 foreach ( $attributes as $name => $value ) {
1073 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1075 if ( $inner === null ) {
1076 return "<$tagName$attrText/>";
1078 return "<$tagName$attrText>$inner</$tagName>";
1081 $params = [
1082 'name' => $tagName,
1083 'inner' => $inner,
1084 'attributes' => $attributes,
1085 'close' => "</$tagName>",
1087 return $parser->extensionSubstitution( $params, $frame );
1091 * Fetched the current revision of the given title and return this.
1092 * Will increment the expensive function count and
1093 * add a template link to get the value refreshed on changes.
1094 * For a given title, which is equal to the current parser title,
1095 * the revision object from the parser is used, when that is the current one
1097 * @param Parser $parser
1098 * @param Title $title
1099 * @return Revision
1100 * @since 1.23
1102 private static function getCachedRevisionObject( $parser, $title = null ) {
1103 if ( is_null( $title ) ) {
1104 return null;
1107 // Use the revision from the parser itself, when param is the current page
1108 // and the revision is the current one
1109 if ( $title->equals( $parser->getTitle() ) ) {
1110 $parserRev = $parser->getRevisionObject();
1111 if ( $parserRev && $parserRev->isCurrent() ) {
1112 // force reparse after edit with vary-revision flag
1113 $parser->getOutput()->setFlag( 'vary-revision' );
1114 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
1115 return $parserRev;
1119 // Normalize name for cache
1120 $page = $title->getPrefixedDBkey();
1122 if ( !( $parser->currentRevisionCache && $parser->currentRevisionCache->has( $page ) )
1123 && !$parser->incrementExpensiveFunctionCount() ) {
1124 return null;
1126 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1127 $pageID = $rev ? $rev->getPage() : 0;
1128 $revID = $rev ? $rev->getId() : 0;
1130 // Register dependency in templatelinks
1131 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1133 return $rev;
1137 * Get the pageid of a specified page
1138 * @param Parser $parser
1139 * @param string $title Title to get the pageid from
1140 * @return int|null|string
1141 * @since 1.23
1143 public static function pageid( $parser, $title = null ) {
1144 $t = Title::newFromText( $title );
1145 if ( is_null( $t ) ) {
1146 return '';
1148 // Use title from parser to have correct pageid after edit
1149 if ( $t->equals( $parser->getTitle() ) ) {
1150 $t = $parser->getTitle();
1151 return $t->getArticleID();
1154 // These can't have ids
1155 if ( !$t->canExist() || $t->isExternal() ) {
1156 return 0;
1159 // Check the link cache, maybe something already looked it up.
1160 $linkCache = LinkCache::singleton();
1161 $pdbk = $t->getPrefixedDBkey();
1162 $id = $linkCache->getGoodLinkID( $pdbk );
1163 if ( $id != 0 ) {
1164 $parser->mOutput->addLink( $t, $id );
1165 return $id;
1167 if ( $linkCache->isBadLink( $pdbk ) ) {
1168 $parser->mOutput->addLink( $t, 0 );
1169 return $id;
1172 // We need to load it from the DB, so mark expensive
1173 if ( $parser->incrementExpensiveFunctionCount() ) {
1174 $id = $t->getArticleID();
1175 $parser->mOutput->addLink( $t, $id );
1176 return $id;
1178 return null;
1182 * Get the id from the last revision of a specified page.
1183 * @param Parser $parser
1184 * @param string $title Title to get the id from
1185 * @return int|null|string
1186 * @since 1.23
1188 public static function revisionid( $parser, $title = null ) {
1189 $t = Title::newFromText( $title );
1190 if ( is_null( $t ) ) {
1191 return '';
1193 // fetch revision from cache/database and return the value
1194 $rev = self::getCachedRevisionObject( $parser, $t );
1195 return $rev ? $rev->getId() : '';
1199 * Get the day from the last revision of a specified page.
1200 * @param Parser $parser
1201 * @param string $title Title to get the day from
1202 * @return string
1203 * @since 1.23
1205 public static function revisionday( $parser, $title = null ) {
1206 $t = Title::newFromText( $title );
1207 if ( is_null( $t ) ) {
1208 return '';
1210 // fetch revision from cache/database and return the value
1211 $rev = self::getCachedRevisionObject( $parser, $t );
1212 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1216 * Get the day with leading zeros from the last revision of a specified page.
1217 * @param Parser $parser
1218 * @param string $title Title to get the day from
1219 * @return string
1220 * @since 1.23
1222 public static function revisionday2( $parser, $title = null ) {
1223 $t = Title::newFromText( $title );
1224 if ( is_null( $t ) ) {
1225 return '';
1227 // fetch revision from cache/database and return the value
1228 $rev = self::getCachedRevisionObject( $parser, $t );
1229 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1233 * Get the month with leading zeros from the last revision of a specified page.
1234 * @param Parser $parser
1235 * @param string $title Title to get the month from
1236 * @return string
1237 * @since 1.23
1239 public static function revisionmonth( $parser, $title = null ) {
1240 $t = Title::newFromText( $title );
1241 if ( is_null( $t ) ) {
1242 return '';
1244 // fetch revision from cache/database and return the value
1245 $rev = self::getCachedRevisionObject( $parser, $t );
1246 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1250 * Get the month from the last revision of a specified page.
1251 * @param Parser $parser
1252 * @param string $title Title to get the month from
1253 * @return string
1254 * @since 1.23
1256 public static function revisionmonth1( $parser, $title = null ) {
1257 $t = Title::newFromText( $title );
1258 if ( is_null( $t ) ) {
1259 return '';
1261 // fetch revision from cache/database and return the value
1262 $rev = self::getCachedRevisionObject( $parser, $t );
1263 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1267 * Get the year from the last revision of a specified page.
1268 * @param Parser $parser
1269 * @param string $title Title to get the year from
1270 * @return string
1271 * @since 1.23
1273 public static function revisionyear( $parser, $title = null ) {
1274 $t = Title::newFromText( $title );
1275 if ( is_null( $t ) ) {
1276 return '';
1278 // fetch revision from cache/database and return the value
1279 $rev = self::getCachedRevisionObject( $parser, $t );
1280 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1284 * Get the timestamp from the last revision of a specified page.
1285 * @param Parser $parser
1286 * @param string $title Title to get the timestamp from
1287 * @return string
1288 * @since 1.23
1290 public static function revisiontimestamp( $parser, $title = null ) {
1291 $t = Title::newFromText( $title );
1292 if ( is_null( $t ) ) {
1293 return '';
1295 // fetch revision from cache/database and return the value
1296 $rev = self::getCachedRevisionObject( $parser, $t );
1297 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1301 * Get the user from the last revision of a specified page.
1302 * @param Parser $parser
1303 * @param string $title Title to get the user from
1304 * @return string
1305 * @since 1.23
1307 public static function revisionuser( $parser, $title = null ) {
1308 $t = Title::newFromText( $title );
1309 if ( is_null( $t ) ) {
1310 return '';
1312 // fetch revision from cache/database and return the value
1313 $rev = self::getCachedRevisionObject( $parser, $t );
1314 return $rev ? $rev->getUserText() : '';
1318 * Returns the sources of any cascading protection acting on a specified page.
1319 * Pages will not return their own title unless they transclude themselves.
1320 * This is an expensive parser function and can't be called too many times per page,
1321 * unless cascading protection sources for the page have already been loaded.
1323 * @param Parser $parser
1324 * @param string $title
1326 * @return string
1327 * @since 1.23
1329 public static function cascadingsources( $parser, $title = '' ) {
1330 $titleObject = Title::newFromText( $title );
1331 if ( !( $titleObject instanceof Title ) ) {
1332 $titleObject = $parser->mTitle;
1334 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1335 || $parser->incrementExpensiveFunctionCount()
1337 $names = [];
1338 $sources = $titleObject->getCascadeProtectionSources();
1339 foreach ( $sources[0] as $sourceTitle ) {
1340 $names[] = $sourceTitle->getPrefixedText();
1342 return implode( $names, '|' );
1344 return '';