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 static function register( $parser ) {
34 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36 # Syntax for arguments (see self::setFunctionHook):
37 # "name for lookup in localized magic words array",
39 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
40 # instead of {{#int:...}})
42 $parser->setFunctionHook( 'int', array( __CLASS__
, 'intFunction' ), SFH_NO_HASH
);
43 $parser->setFunctionHook( 'ns', array( __CLASS__
, 'ns' ), SFH_NO_HASH
);
44 $parser->setFunctionHook( 'nse', array( __CLASS__
, 'nse' ), SFH_NO_HASH
);
45 $parser->setFunctionHook( 'urlencode', array( __CLASS__
, 'urlencode' ), SFH_NO_HASH
);
46 $parser->setFunctionHook( 'lcfirst', array( __CLASS__
, 'lcfirst' ), SFH_NO_HASH
);
47 $parser->setFunctionHook( 'ucfirst', array( __CLASS__
, 'ucfirst' ), SFH_NO_HASH
);
48 $parser->setFunctionHook( 'lc', array( __CLASS__
, 'lc' ), SFH_NO_HASH
);
49 $parser->setFunctionHook( 'uc', array( __CLASS__
, 'uc' ), SFH_NO_HASH
);
50 $parser->setFunctionHook( 'localurl', array( __CLASS__
, 'localurl' ), SFH_NO_HASH
);
51 $parser->setFunctionHook( 'localurle', array( __CLASS__
, 'localurle' ), SFH_NO_HASH
);
52 $parser->setFunctionHook( 'fullurl', array( __CLASS__
, 'fullurl' ), SFH_NO_HASH
);
53 $parser->setFunctionHook( 'fullurle', array( __CLASS__
, 'fullurle' ), SFH_NO_HASH
);
54 $parser->setFunctionHook( 'canonicalurl', array( __CLASS__
, 'canonicalurl' ), SFH_NO_HASH
);
55 $parser->setFunctionHook( 'canonicalurle', array( __CLASS__
, 'canonicalurle' ), SFH_NO_HASH
);
56 $parser->setFunctionHook( 'formatnum', array( __CLASS__
, 'formatnum' ), SFH_NO_HASH
);
57 $parser->setFunctionHook( 'grammar', array( __CLASS__
, 'grammar' ), SFH_NO_HASH
);
58 $parser->setFunctionHook( 'gender', array( __CLASS__
, 'gender' ), SFH_NO_HASH
);
59 $parser->setFunctionHook( 'plural', array( __CLASS__
, 'plural' ), SFH_NO_HASH
);
60 $parser->setFunctionHook( 'numberofpages', array( __CLASS__
, 'numberofpages' ), SFH_NO_HASH
);
61 $parser->setFunctionHook( 'numberofusers', array( __CLASS__
, 'numberofusers' ), SFH_NO_HASH
);
62 $parser->setFunctionHook( 'numberofactiveusers', array( __CLASS__
, 'numberofactiveusers' ), SFH_NO_HASH
);
63 $parser->setFunctionHook( 'numberofarticles', array( __CLASS__
, 'numberofarticles' ), SFH_NO_HASH
);
64 $parser->setFunctionHook( 'numberoffiles', array( __CLASS__
, 'numberoffiles' ), SFH_NO_HASH
);
65 $parser->setFunctionHook( 'numberofadmins', array( __CLASS__
, 'numberofadmins' ), SFH_NO_HASH
);
66 $parser->setFunctionHook( 'numberingroup', array( __CLASS__
, 'numberingroup' ), SFH_NO_HASH
);
67 $parser->setFunctionHook( 'numberofedits', array( __CLASS__
, 'numberofedits' ), SFH_NO_HASH
);
68 $parser->setFunctionHook( 'numberofviews', array( __CLASS__
, 'numberofviews' ), SFH_NO_HASH
);
69 $parser->setFunctionHook( 'language', array( __CLASS__
, 'language' ), SFH_NO_HASH
);
70 $parser->setFunctionHook( 'padleft', array( __CLASS__
, 'padleft' ), SFH_NO_HASH
);
71 $parser->setFunctionHook( 'padright', array( __CLASS__
, 'padright' ), SFH_NO_HASH
);
72 $parser->setFunctionHook( 'anchorencode', array( __CLASS__
, 'anchorencode' ), SFH_NO_HASH
);
73 $parser->setFunctionHook( 'special', array( __CLASS__
, 'special' ) );
74 $parser->setFunctionHook( 'speciale', array( __CLASS__
, 'speciale' ) );
75 $parser->setFunctionHook( 'defaultsort', array( __CLASS__
, 'defaultsort' ), SFH_NO_HASH
);
76 $parser->setFunctionHook( 'filepath', array( __CLASS__
, 'filepath' ), SFH_NO_HASH
);
77 $parser->setFunctionHook( 'pagesincategory', array( __CLASS__
, 'pagesincategory' ), SFH_NO_HASH
);
78 $parser->setFunctionHook( 'pagesize', array( __CLASS__
, 'pagesize' ), SFH_NO_HASH
);
79 $parser->setFunctionHook( 'protectionlevel', array( __CLASS__
, 'protectionlevel' ), SFH_NO_HASH
);
80 $parser->setFunctionHook( 'namespace', array( __CLASS__
, 'mwnamespace' ), SFH_NO_HASH
);
81 $parser->setFunctionHook( 'namespacee', array( __CLASS__
, 'namespacee' ), SFH_NO_HASH
);
82 $parser->setFunctionHook( 'namespacenumber', array( __CLASS__
, 'namespacenumber' ), SFH_NO_HASH
);
83 $parser->setFunctionHook( 'talkspace', array( __CLASS__
, 'talkspace' ), SFH_NO_HASH
);
84 $parser->setFunctionHook( 'talkspacee', array( __CLASS__
, 'talkspacee' ), SFH_NO_HASH
);
85 $parser->setFunctionHook( 'subjectspace', array( __CLASS__
, 'subjectspace' ), SFH_NO_HASH
);
86 $parser->setFunctionHook( 'subjectspacee', array( __CLASS__
, 'subjectspacee' ), SFH_NO_HASH
);
87 $parser->setFunctionHook( 'pagename', array( __CLASS__
, 'pagename' ), SFH_NO_HASH
);
88 $parser->setFunctionHook( 'pagenamee', array( __CLASS__
, 'pagenamee' ), SFH_NO_HASH
);
89 $parser->setFunctionHook( 'fullpagename', array( __CLASS__
, 'fullpagename' ), SFH_NO_HASH
);
90 $parser->setFunctionHook( 'fullpagenamee', array( __CLASS__
, 'fullpagenamee' ), SFH_NO_HASH
);
91 $parser->setFunctionHook( 'rootpagename', array( __CLASS__
, 'rootpagename' ), SFH_NO_HASH
);
92 $parser->setFunctionHook( 'rootpagenamee', array( __CLASS__
, 'rootpagenamee' ), SFH_NO_HASH
);
93 $parser->setFunctionHook( 'basepagename', array( __CLASS__
, 'basepagename' ), SFH_NO_HASH
);
94 $parser->setFunctionHook( 'basepagenamee', array( __CLASS__
, 'basepagenamee' ), SFH_NO_HASH
);
95 $parser->setFunctionHook( 'subpagename', array( __CLASS__
, 'subpagename' ), SFH_NO_HASH
);
96 $parser->setFunctionHook( 'subpagenamee', array( __CLASS__
, 'subpagenamee' ), SFH_NO_HASH
);
97 $parser->setFunctionHook( 'talkpagename', array( __CLASS__
, 'talkpagename' ), SFH_NO_HASH
);
98 $parser->setFunctionHook( 'talkpagenamee', array( __CLASS__
, 'talkpagenamee' ), SFH_NO_HASH
);
99 $parser->setFunctionHook( 'subjectpagename', array( __CLASS__
, 'subjectpagename' ), SFH_NO_HASH
);
100 $parser->setFunctionHook( 'subjectpagenamee', array( __CLASS__
, 'subjectpagenamee' ), SFH_NO_HASH
);
101 $parser->setFunctionHook( 'tag', array( __CLASS__
, 'tagObj' ), SFH_OBJECT_ARGS
);
102 $parser->setFunctionHook( 'formatdate', array( __CLASS__
, 'formatDate' ) );
104 if ( $wgAllowDisplayTitle ) {
105 $parser->setFunctionHook( 'displaytitle', array( __CLASS__
, 'displaytitle' ), SFH_NO_HASH
);
107 if ( $wgAllowSlowParserFunctions ) {
108 $parser->setFunctionHook( 'pagesinnamespace', array( __CLASS__
, 'pagesinnamespace' ), SFH_NO_HASH
);
113 * @param $parser Parser
114 * @param string $part1
117 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
118 if ( strval( $part1 ) !== '' ) {
119 $args = array_slice( func_get_args(), 2 );
120 $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
121 return array( $message, 'noparse' => false );
123 return array( 'found' => false );
128 * @param $parser Parser
130 * @param null $defaultPref
131 * @return mixed|string
133 static function formatDate( $parser, $date, $defaultPref = null ) {
134 $lang = $parser->getFunctionLang();
135 $df = DateFormatter
::getInstance( $lang );
137 $date = trim( $date );
139 $pref = $parser->getOptions()->getDateFormat();
141 // Specify a different default date format other than the the normal default
142 // iff the user has 'default' for their setting
143 if ( $pref == 'default' && $defaultPref ) {
144 $pref = $defaultPref;
147 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
151 static function ns( $parser, $part1 = '' ) {
153 if ( intval( $part1 ) ||
$part1 == "0" ) {
154 $index = intval( $part1 );
156 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
158 if ( $index !== false ) {
159 return $wgContLang->getFormattedNsText( $index );
161 return array( 'found' => false );
165 static function nse( $parser, $part1 = '' ) {
166 $ret = self
::ns( $parser, $part1 );
167 if ( is_string( $ret ) ) {
168 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
174 * urlencodes a string according to one of three patterns: (bug 22474)
176 * By default (for HTTP "query" strings), spaces are encoded as '+'.
177 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
178 * For links to "wiki"s, or similar software, spaces are encoded as '_',
180 * @param $parser Parser object
181 * @param string $s The text to encode.
182 * @param string $arg (optional): The type of encoding.
185 static function urlencode( $parser, $s = '', $arg = null ) {
186 static $magicWords = null;
187 if ( is_null( $magicWords ) ) {
188 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
190 switch ( $magicWords->matchStartToEnd( $arg ) ) {
192 // Encode as though it's a wiki page, '_' for ' '.
194 $func = 'wfUrlencode';
195 $s = str_replace( ' ', '_', $s );
198 // Encode for an HTTP Path, '%20' for ' '.
200 $func = 'rawurlencode';
203 // Encode for HTTP query, '+' for ' '.
208 return $parser->markerSkipCallback( $s, $func );
211 static function lcfirst( $parser, $s = '' ) {
213 return $wgContLang->lcfirst( $s );
216 static function ucfirst( $parser, $s = '' ) {
218 return $wgContLang->ucfirst( $s );
222 * @param $parser Parser
226 static function lc( $parser, $s = '' ) {
228 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
232 * @param $parser Parser
236 static function uc( $parser, $s = '' ) {
238 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
241 static function localurl( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'getLocalURL', $s, $arg ); }
242 static function localurle( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'escapeLocalURL', $s, $arg ); }
243 static function fullurl( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'getFullURL', $s, $arg ); }
244 static function fullurle( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'escapeFullURL', $s, $arg ); }
245 static function canonicalurl( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'getCanonicalURL', $s, $arg ); }
246 static function canonicalurle( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'escapeCanonicalURL', $s, $arg ); }
248 static function urlFunction( $func, $s = '', $arg = null ) {
249 $title = Title
::newFromText( $s );
250 # Due to order of execution of a lot of bits, the values might be encoded
251 # before arriving here; if that's true, then the title can't be created
252 # and the variable will fail. If we can't get a decent title from the first
253 # attempt, url-decode and try for a second.
254 if ( is_null( $title ) ) {
255 $title = Title
::newFromURL( urldecode( $s ) );
257 if ( !is_null( $title ) ) {
258 # Convert NS_MEDIA -> NS_FILE
259 if ( $title->getNamespace() == NS_MEDIA
) {
260 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
262 if ( !is_null( $arg ) ) {
263 $text = $title->$func( $arg );
265 $text = $title->$func();
269 return array( 'found' => false );
274 * @param $parser Parser
279 static function formatnum( $parser, $num = '', $arg = null ) {
280 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
281 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
282 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
283 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
285 $func = array( $parser->getFunctionLang(), 'formatNum' );
287 return $parser->markerSkipCallback( $num, $func );
291 * @param $parser Parser
292 * @param string $case
293 * @param string $word
296 static function grammar( $parser, $case = '', $word = '' ) {
297 $word = $parser->killMarkers( $word );
298 return $parser->getFunctionLang()->convertGrammar( $word, $case );
302 * @param $parser Parser
303 * @param $username string
306 static function gender( $parser, $username ) {
307 wfProfileIn( __METHOD__
);
308 $forms = array_slice( func_get_args(), 2 );
310 // Some shortcuts to avoid loading user data unnecessarily
311 if ( count( $forms ) === 0 ) {
312 wfProfileOut( __METHOD__
);
314 } elseif ( count( $forms ) === 1 ) {
315 wfProfileOut( __METHOD__
);
319 $username = trim( $username );
322 $gender = User
::getDefaultOption( 'gender' );
325 $title = Title
::newFromText( $username );
327 if ( $title && $title->getNamespace() == NS_USER
) {
328 $username = $title->getText();
331 // check parameter, or use the ParserOptions if in interface message
332 $user = User
::newFromName( $username );
334 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
335 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
336 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
338 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
339 wfProfileOut( __METHOD__
);
344 * @param $parser Parser
345 * @param string $text
348 static function plural( $parser, $text = '' ) {
349 $forms = array_slice( func_get_args(), 2 );
350 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
351 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
352 return $parser->getFunctionLang()->convertPlural( $text, $forms );
356 * Override the title of the page when viewed, provided we've been given a
357 * title which will normalise to the canonical title
359 * @param $parser Parser: parent parser
360 * @param string $text desired title text
363 static function displaytitle( $parser, $text = '' ) {
364 global $wgRestrictDisplayTitle;
366 // parse a limited subset of wiki markup (just the single quote items)
367 $text = $parser->doQuotes( $text );
369 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
370 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
371 . preg_quote( Parser
::MARKER_SUFFIX
, '/' ) . '/', '', $text );
373 // list of disallowed tags for DISPLAYTITLE
374 // these will be escaped even though they are allowed in normal wiki text
375 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
376 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
378 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
379 if ( $wgRestrictDisplayTitle ) {
380 $htmlTagsCallback = function ( &$params ) {
381 $decoded = Sanitizer
::decodeTagAttributes( $params );
383 if ( isset( $decoded['style'] ) ) {
384 // this is called later anyway, but we need it right now for the regexes below to be safe
385 // calling it twice doesn't hurt
386 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
388 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
389 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
393 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
396 $htmlTagsCallback = null;
399 // only requested titles that normalize to the actual title are allowed through
400 // if $wgRestrictDisplayTitle is true (it is by default)
401 // mimic the escaping process that occurs in OutputPage::setPageTitle
402 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $text, $htmlTagsCallback, array(), array(), $bad ) );
403 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
405 if ( !$wgRestrictDisplayTitle ) {
406 $parser->mOutput
->setDisplayTitle( $text );
407 } elseif ( $title instanceof Title
&& $title->getFragment() == '' && $title->equals( $parser->mTitle
) ) {
408 $parser->mOutput
->setDisplayTitle( $text );
415 * Matches the given value against the value of given magic word
417 * @param string $magicword magic word key
418 * @param mixed $value value to match
419 * @return boolean true on successful match
421 static private function matchAgainstMagicword( $magicword, $value ) {
422 if ( strval( $value ) === '' ) {
425 $mwObject = MagicWord
::get( $magicword );
426 return $mwObject->match( $value );
429 static function formatRaw( $num, $raw ) {
430 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
434 return $wgContLang->formatNum( $num );
437 static function numberofpages( $parser, $raw = null ) {
438 return self
::formatRaw( SiteStats
::pages(), $raw );
440 static function numberofusers( $parser, $raw = null ) {
441 return self
::formatRaw( SiteStats
::users(), $raw );
443 static function numberofactiveusers( $parser, $raw = null ) {
444 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
446 static function numberofarticles( $parser, $raw = null ) {
447 return self
::formatRaw( SiteStats
::articles(), $raw );
449 static function numberoffiles( $parser, $raw = null ) {
450 return self
::formatRaw( SiteStats
::images(), $raw );
452 static function numberofadmins( $parser, $raw = null ) {
453 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
455 static function numberofedits( $parser, $raw = null ) {
456 return self
::formatRaw( SiteStats
::edits(), $raw );
458 static function numberofviews( $parser, $raw = null ) {
459 global $wgDisableCounters;
460 return !$wgDisableCounters ? self
::formatRaw( SiteStats
::views(), $raw ) : '';
462 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
463 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
465 static function numberingroup( $parser, $name = '', $raw = null ) {
466 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
470 * Given a title, return the namespace name that would be given by the
471 * corresponding magic word
472 * Note: function name changed to "mwnamespace" rather than "namespace"
473 * to not break PHP 5.3
474 * @return mixed|string
476 static function mwnamespace( $parser, $title = null ) {
477 $t = Title
::newFromText( $title );
478 if ( is_null( $t ) ) {
481 return str_replace( '_', ' ', $t->getNsText() );
483 static function namespacee( $parser, $title = null ) {
484 $t = Title
::newFromText( $title );
485 if ( is_null( $t ) ) {
488 return wfUrlencode( $t->getNsText() );
490 static function namespacenumber( $parser, $title = null ) {
491 $t = Title
::newFromText( $title );
492 if ( is_null( $t ) ) {
495 return $t->getNamespace();
497 static function talkspace( $parser, $title = null ) {
498 $t = Title
::newFromText( $title );
499 if ( is_null( $t ) ||
!$t->canTalk() ) {
502 return str_replace( '_', ' ', $t->getTalkNsText() );
504 static function talkspacee( $parser, $title = null ) {
505 $t = Title
::newFromText( $title );
506 if ( is_null( $t ) ||
!$t->canTalk() ) {
509 return wfUrlencode( $t->getTalkNsText() );
511 static function subjectspace( $parser, $title = null ) {
512 $t = Title
::newFromText( $title );
513 if ( is_null( $t ) ) {
516 return str_replace( '_', ' ', $t->getSubjectNsText() );
518 static function subjectspacee( $parser, $title = null ) {
519 $t = Title
::newFromText( $title );
520 if ( is_null( $t ) ) {
523 return wfUrlencode( $t->getSubjectNsText() );
527 * Functions to get and normalize pagenames, corresponding to the magic words
531 static function pagename( $parser, $title = null ) {
532 $t = Title
::newFromText( $title );
533 if ( is_null( $t ) ) {
536 return wfEscapeWikiText( $t->getText() );
538 static function pagenamee( $parser, $title = null ) {
539 $t = Title
::newFromText( $title );
540 if ( is_null( $t ) ) {
543 return wfEscapeWikiText( $t->getPartialURL() );
545 static function fullpagename( $parser, $title = null ) {
546 $t = Title
::newFromText( $title );
547 if ( is_null( $t ) ||
!$t->canTalk() ) {
550 return wfEscapeWikiText( $t->getPrefixedText() );
552 static function fullpagenamee( $parser, $title = null ) {
553 $t = Title
::newFromText( $title );
554 if ( is_null( $t ) ||
!$t->canTalk() ) {
557 return wfEscapeWikiText( $t->getPrefixedURL() );
559 static function subpagename( $parser, $title = null ) {
560 $t = Title
::newFromText( $title );
561 if ( is_null( $t ) ) {
564 return wfEscapeWikiText( $t->getSubpageText() );
566 static function subpagenamee( $parser, $title = null ) {
567 $t = Title
::newFromText( $title );
568 if ( is_null( $t ) ) {
571 return wfEscapeWikiText( $t->getSubpageUrlForm() );
573 static function rootpagename( $parser, $title = null ) {
574 $t = Title
::newFromText( $title );
575 if ( is_null( $t ) ) {
578 return wfEscapeWikiText( $t->getRootText() );
580 static function rootpagenamee( $parser, $title = null ) {
581 $t = Title
::newFromText( $title );
582 if ( is_null( $t ) ) {
585 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
587 static function basepagename( $parser, $title = null ) {
588 $t = Title
::newFromText( $title );
589 if ( is_null( $t ) ) {
592 return wfEscapeWikiText( $t->getBaseText() );
594 static function basepagenamee( $parser, $title = null ) {
595 $t = Title
::newFromText( $title );
596 if ( is_null( $t ) ) {
599 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
601 static function talkpagename( $parser, $title = null ) {
602 $t = Title
::newFromText( $title );
603 if ( is_null( $t ) ||
!$t->canTalk() ) {
606 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
608 static function talkpagenamee( $parser, $title = null ) {
609 $t = Title
::newFromText( $title );
610 if ( is_null( $t ) ||
!$t->canTalk() ) {
613 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
615 static function subjectpagename( $parser, $title = null ) {
616 $t = Title
::newFromText( $title );
617 if ( is_null( $t ) ) {
620 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
622 static function subjectpagenamee( $parser, $title = null ) {
623 $t = Title
::newFromText( $title );
624 if ( is_null( $t ) ) {
627 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
631 * Return the number of pages, files or subcats in the given category,
632 * or 0 if it's nonexistent. This is an expensive parser function and
633 * can't be called too many times per page.
636 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
637 static $magicWords = null;
638 if ( is_null( $magicWords ) ) {
639 $magicWords = new MagicWordArray( array(
640 'pagesincategory_all',
641 'pagesincategory_pages',
642 'pagesincategory_subcats',
643 'pagesincategory_files'
646 static $cache = array();
648 // split the given option to its variable
649 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
650 //{{pagesincategory:|raw[|type]}}
652 $type = $magicWords->matchStartToEnd( $arg2 );
654 //{{pagesincategory:[|type[|raw]]}}
655 $type = $magicWords->matchStartToEnd( $arg1 );
658 if ( !$type ) { //backward compatibility
659 $type = 'pagesincategory_all';
662 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
663 if ( !$title ) { # invalid title
664 return self
::formatRaw( 0, $raw );
667 // Normalize name for cache
668 $name = $title->getDBkey();
670 if ( !isset( $cache[$name] ) ) {
671 $category = Category
::newFromTitle( $title );
673 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
674 if ( $parser->incrementExpensiveFunctionCount() ) {
675 // $allCount is the total number of cat members,
676 // not the count of how many members are normal pages.
677 $allCount = (int)$category->getPageCount();
678 $subcatCount = (int)$category->getSubcatCount();
679 $fileCount = (int)$category->getFileCount();
680 $pagesCount = $allCount - $subcatCount - $fileCount;
682 $cache[$name]['pagesincategory_all'] = $allCount;
683 $cache[$name]['pagesincategory_pages'] = $pagesCount;
684 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
685 $cache[$name]['pagesincategory_files'] = $fileCount;
688 $count = $cache[$name][$type];
689 return self
::formatRaw( $count, $raw );
693 * Return the size of the given page, or 0 if it's nonexistent. This is an
694 * expensive parser function and can't be called too many times per page.
696 * @todo FIXME: Title::getLength() documentation claims that it adds things
697 * to the link cache, so the local cache here should be unnecessary, but
698 * in fact calling getLength() repeatedly for the same $page does seem to
699 * run one query for each call?
700 * @todo Document parameters
702 * @param $parser Parser
703 * @param $page String Name of page to check (Default: empty string)
704 * @param $raw String Should number be human readable with commas or just number
707 static function pagesize( $parser, $page = '', $raw = null ) {
708 static $cache = array();
709 $title = Title
::newFromText( $page );
711 if ( !is_object( $title ) ) {
713 return self
::formatRaw( 0, $raw );
716 # Normalize name for cache
717 $page = $title->getPrefixedText();
720 if ( $title->equals( $parser->getTitle() )
721 && $parser->mInputSize
!== false
723 # We are on current page (and not in PST), so
724 # take length of input to parser.
725 $length = $parser->mInputSize
;
726 } elseif ( isset( $cache[$page] ) ) {
727 $length = $cache[$page];
728 } elseif ( $parser->incrementExpensiveFunctionCount() ) {
729 $rev = Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
730 $pageID = $rev ?
$rev->getPage() : 0;
731 $revID = $rev ?
$rev->getId() : 0;
732 $length = $cache[$page] = $rev ?
$rev->getSize() : 0;
734 // Register dependency in templatelinks
735 $parser->mOutput
->addTemplate( $title, $pageID, $revID );
737 return self
::formatRaw( $length, $raw );
741 * Returns the requested protection level for the current page
743 * @param Parser $parser
744 * @param string $type
745 * @param string $title
749 static function protectionlevel( $parser, $type = '', $title = '' ) {
750 $titleObject = Title
::newFromText( $title );
751 if ( !( $titleObject instanceof Title
) ) {
752 $titleObject = $parser->mTitle
;
754 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
755 # Title::getRestrictions returns an array, its possible it may have
756 # multiple values in the future
757 return implode( $restrictions, ',' );
761 * Gives language names.
762 * @param $parser Parser
763 * @param string $code Language code (of which to get name)
764 * @param string $inLanguage Language code (in which to get name)
767 static function language( $parser, $code = '', $inLanguage = '' ) {
768 $code = strtolower( $code );
769 $inLanguage = strtolower( $inLanguage );
770 $lang = Language
::fetchLanguageName( $code, $inLanguage );
771 return $lang !== '' ?
$lang : wfBCP47( $code );
775 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
778 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
779 $padding = $parser->killMarkers( $padding );
780 $lengthOfPadding = mb_strlen( $padding );
781 if ( $lengthOfPadding == 0 ) {
785 # The remaining length to add counts down to 0 as padding is added
786 $length = min( $length, 500 ) - mb_strlen( $string );
787 # $finalPadding is just $padding repeated enough times so that
788 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
790 while ( $length > 0 ) {
791 # If $length < $lengthofPadding, truncate $padding so we get the
792 # exact length desired.
793 $finalPadding .= mb_substr( $padding, 0, $length );
794 $length -= $lengthOfPadding;
797 if ( $direction == STR_PAD_LEFT
) {
798 return $finalPadding . $string;
800 return $string . $finalPadding;
804 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
805 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
808 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
809 return self
::pad( $parser, $string, $length, $padding );
813 * @param $parser Parser
817 static function anchorencode( $parser, $text ) {
818 $text = $parser->killMarkers( $text );
819 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
822 static function special( $parser, $text ) {
823 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
825 $title = SpecialPage
::getTitleFor( $page, $subpage );
826 return $title->getPrefixedText();
828 // unknown special page, just use the given text as its title, if at all possible
829 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
830 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
834 static function speciale( $parser, $text ) {
835 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
839 * @param $parser Parser
840 * @param string $text The sortkey to use
841 * @param string $uarg Either "noreplace" or "noerror" (in en)
842 * both suppress errors, and noreplace does nothing if
843 * a default sortkey already exists.
846 public static function defaultsort( $parser, $text, $uarg = '' ) {
847 static $magicWords = null;
848 if ( is_null( $magicWords ) ) {
849 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
851 $arg = $magicWords->matchStartToEnd( $uarg );
853 $text = trim( $text );
854 if ( strlen( $text ) == 0 ) {
857 $old = $parser->getCustomDefaultSort();
858 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
859 $parser->setDefaultSort( $text );
862 if ( $old === false ||
$old == $text ||
$arg ) {
865 $converter = $parser->getConverterLanguage()->getConverter();
866 return '<span class="error">' .
867 wfMessage( 'duplicate-defaultsort',
868 // Message should be parsed, but these params should only be escaped.
869 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
870 $converter->markNoConversion( wfEscapeWikiText( $text ) )
871 )->inContentLanguage()->text() .
876 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
877 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
878 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
879 $file = wfFindFile( $name );
881 if ( $argA == 'nowiki' ) {
882 // {{filepath: | option [| size] }}
884 $parsedWidthParam = $parser->parseWidthParam( $argB );
886 // {{filepath: [| size [|option]] }}
887 $parsedWidthParam = $parser->parseWidthParam( $argA );
888 $isNowiki = ( $argB == 'nowiki' );
892 $url = $file->getFullUrl();
894 // If a size is requested...
895 if ( count( $parsedWidthParam ) ) {
896 $mto = $file->transform( $parsedWidthParam );
898 if ( $mto && !$mto->isError() ) {
899 // ... change the URL to point to a thumbnail.
900 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
904 return array( $url, 'nowiki' => true );
913 * Parser function to extension tag adaptor
916 public static function tagObj( $parser, $frame, $args ) {
917 if ( !count( $args ) ) {
920 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
922 if ( count( $args ) ) {
923 $inner = $frame->expand( array_shift( $args ) );
928 $stripList = $parser->getStripList();
929 if ( !in_array( $tagName, $stripList ) ) {
930 return '<span class="error">' .
931 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
935 $attributes = array();
936 foreach ( $args as $arg ) {
937 $bits = $arg->splitArg();
938 if ( strval( $bits['index'] ) === '' ) {
939 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
940 $value = trim( $frame->expand( $bits['value'] ) );
941 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
942 $value = isset( $m[1] ) ?
$m[1] : '';
944 $attributes[$name] = $value;
951 'attributes' => $attributes,
952 'close' => "</$tagName>",
954 return $parser->extensionSubstitution( $params, $frame );