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' ) );
103 $parser->setFunctionHook( 'pageid', array( __CLASS__
, 'pageid' ), SFH_NO_HASH
);
104 $parser->setFunctionHook( 'revisionid', array( __CLASS__
, 'revisionid' ), SFH_NO_HASH
);
105 $parser->setFunctionHook( 'revisionday', array( __CLASS__
, 'revisionday' ), SFH_NO_HASH
);
106 $parser->setFunctionHook( 'revisionday2', array( __CLASS__
, 'revisionday2' ), SFH_NO_HASH
);
107 $parser->setFunctionHook( 'revisionmonth', array( __CLASS__
, 'revisionmonth' ), SFH_NO_HASH
);
108 $parser->setFunctionHook( 'revisionmonth1', array( __CLASS__
, 'revisionmonth1' ), SFH_NO_HASH
);
109 $parser->setFunctionHook( 'revisionyear', array( __CLASS__
, 'revisionyear' ), SFH_NO_HASH
);
110 $parser->setFunctionHook( 'revisiontimestamp', array( __CLASS__
, 'revisiontimestamp' ), SFH_NO_HASH
);
111 $parser->setFunctionHook( 'revisionuser', array( __CLASS__
, 'revisionuser' ), SFH_NO_HASH
);
113 if ( $wgAllowDisplayTitle ) {
114 $parser->setFunctionHook( 'displaytitle', array( __CLASS__
, 'displaytitle' ), SFH_NO_HASH
);
116 if ( $wgAllowSlowParserFunctions ) {
117 $parser->setFunctionHook( 'pagesinnamespace', array( __CLASS__
, 'pagesinnamespace' ), SFH_NO_HASH
);
122 * @param $parser Parser
123 * @param string $part1
126 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
127 if ( strval( $part1 ) !== '' ) {
128 $args = array_slice( func_get_args(), 2 );
129 $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
130 return array( $message, 'noparse' => false );
132 return array( 'found' => false );
137 * @param $parser Parser
139 * @param null $defaultPref
140 * @return mixed|string
142 static function formatDate( $parser, $date, $defaultPref = null ) {
143 $lang = $parser->getFunctionLang();
144 $df = DateFormatter
::getInstance( $lang );
146 $date = trim( $date );
148 $pref = $parser->getOptions()->getDateFormat();
150 // Specify a different default date format other than the the normal default
151 // if the user has 'default' for their setting
152 if ( $pref == 'default' && $defaultPref ) {
153 $pref = $defaultPref;
156 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
160 static function ns( $parser, $part1 = '' ) {
162 if ( intval( $part1 ) ||
$part1 == "0" ) {
163 $index = intval( $part1 );
165 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
167 if ( $index !== false ) {
168 return $wgContLang->getFormattedNsText( $index );
170 return array( 'found' => false );
174 static function nse( $parser, $part1 = '' ) {
175 $ret = self
::ns( $parser, $part1 );
176 if ( is_string( $ret ) ) {
177 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
183 * urlencodes a string according to one of three patterns: (bug 22474)
185 * By default (for HTTP "query" strings), spaces are encoded as '+'.
186 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
187 * For links to "wiki"s, or similar software, spaces are encoded as '_',
189 * @param $parser Parser object
190 * @param string $s The text to encode.
191 * @param string $arg (optional): The type of encoding.
194 static function urlencode( $parser, $s = '', $arg = null ) {
195 static $magicWords = null;
196 if ( is_null( $magicWords ) ) {
197 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
199 switch ( $magicWords->matchStartToEnd( $arg ) ) {
201 // Encode as though it's a wiki page, '_' for ' '.
203 $func = 'wfUrlencode';
204 $s = str_replace( ' ', '_', $s );
207 // Encode for an HTTP Path, '%20' for ' '.
209 $func = 'rawurlencode';
212 // Encode for HTTP query, '+' for ' '.
217 return $parser->markerSkipCallback( $s, $func );
220 static function lcfirst( $parser, $s = '' ) {
222 return $wgContLang->lcfirst( $s );
225 static function ucfirst( $parser, $s = '' ) {
227 return $wgContLang->ucfirst( $s );
231 * @param $parser Parser
235 static function lc( $parser, $s = '' ) {
237 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
241 * @param $parser Parser
245 static function uc( $parser, $s = '' ) {
247 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
250 static function localurl( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'getLocalURL', $s, $arg ); }
251 static function localurle( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'escapeLocalURL', $s, $arg ); }
252 static function fullurl( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'getFullURL', $s, $arg ); }
253 static function fullurle( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'escapeFullURL', $s, $arg ); }
254 static function canonicalurl( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'getCanonicalURL', $s, $arg ); }
255 static function canonicalurle( $parser, $s = '', $arg = null ) { return self
::urlFunction( 'escapeCanonicalURL', $s, $arg ); }
257 static function urlFunction( $func, $s = '', $arg = null ) {
258 $title = Title
::newFromText( $s );
259 # Due to order of execution of a lot of bits, the values might be encoded
260 # before arriving here; if that's true, then the title can't be created
261 # and the variable will fail. If we can't get a decent title from the first
262 # attempt, url-decode and try for a second.
263 if ( is_null( $title ) ) {
264 $title = Title
::newFromURL( urldecode( $s ) );
266 if ( !is_null( $title ) ) {
267 # Convert NS_MEDIA -> NS_FILE
268 if ( $title->getNamespace() == NS_MEDIA
) {
269 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
271 if ( !is_null( $arg ) ) {
272 $text = $title->$func( $arg );
274 $text = $title->$func();
278 return array( 'found' => false );
283 * @param $parser Parser
288 static function formatnum( $parser, $num = '', $arg = null ) {
289 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
290 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
291 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
292 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
294 $func = array( $parser->getFunctionLang(), 'formatNum' );
296 return $parser->markerSkipCallback( $num, $func );
300 * @param $parser Parser
301 * @param string $case
302 * @param string $word
305 static function grammar( $parser, $case = '', $word = '' ) {
306 $word = $parser->killMarkers( $word );
307 return $parser->getFunctionLang()->convertGrammar( $word, $case );
311 * @param $parser Parser
312 * @param $username string
315 static function gender( $parser, $username ) {
316 wfProfileIn( __METHOD__
);
317 $forms = array_slice( func_get_args(), 2 );
319 // Some shortcuts to avoid loading user data unnecessarily
320 if ( count( $forms ) === 0 ) {
321 wfProfileOut( __METHOD__
);
323 } elseif ( count( $forms ) === 1 ) {
324 wfProfileOut( __METHOD__
);
328 $username = trim( $username );
331 $gender = User
::getDefaultOption( 'gender' );
334 $title = Title
::newFromText( $username );
336 if ( $title && $title->getNamespace() == NS_USER
) {
337 $username = $title->getText();
340 // check parameter, or use the ParserOptions if in interface message
341 $user = User
::newFromName( $username );
343 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
344 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
345 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
347 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
348 wfProfileOut( __METHOD__
);
353 * @param $parser Parser
354 * @param string $text
357 static function plural( $parser, $text = '' ) {
358 $forms = array_slice( func_get_args(), 2 );
359 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
360 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
361 return $parser->getFunctionLang()->convertPlural( $text, $forms );
365 * Override the title of the page when viewed, provided we've been given a
366 * title which will normalise to the canonical title
368 * @param $parser Parser: parent parser
369 * @param string $text desired title text
372 static function displaytitle( $parser, $text = '' ) {
373 global $wgRestrictDisplayTitle;
375 // parse a limited subset of wiki markup (just the single quote items)
376 $text = $parser->doQuotes( $text );
378 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
379 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
380 . preg_quote( Parser
::MARKER_SUFFIX
, '/' ) . '/', '', $text );
382 // list of disallowed tags for DISPLAYTITLE
383 // these will be escaped even though they are allowed in normal wiki text
384 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
385 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
387 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
388 if ( $wgRestrictDisplayTitle ) {
389 $htmlTagsCallback = function ( &$params ) {
390 $decoded = Sanitizer
::decodeTagAttributes( $params );
392 if ( isset( $decoded['style'] ) ) {
393 // this is called later anyway, but we need it right now for the regexes below to be safe
394 // calling it twice doesn't hurt
395 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
397 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
398 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
402 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
405 $htmlTagsCallback = null;
408 // only requested titles that normalize to the actual title are allowed through
409 // if $wgRestrictDisplayTitle is true (it is by default)
410 // mimic the escaping process that occurs in OutputPage::setPageTitle
411 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $text, $htmlTagsCallback, array(), array(), $bad ) );
412 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
414 if ( !$wgRestrictDisplayTitle ) {
415 $parser->mOutput
->setDisplayTitle( $text );
416 } elseif ( $title instanceof Title
&& $title->getFragment() == '' && $title->equals( $parser->mTitle
) ) {
417 $parser->mOutput
->setDisplayTitle( $text );
424 * Matches the given value against the value of given magic word
426 * @param string $magicword magic word key
427 * @param mixed $value value to match
428 * @return boolean true on successful match
430 static private function matchAgainstMagicword( $magicword, $value ) {
431 if ( strval( $value ) === '' ) {
434 $mwObject = MagicWord
::get( $magicword );
435 return $mwObject->match( $value );
438 static function formatRaw( $num, $raw ) {
439 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
443 return $wgContLang->formatNum( $num );
446 static function numberofpages( $parser, $raw = null ) {
447 return self
::formatRaw( SiteStats
::pages(), $raw );
449 static function numberofusers( $parser, $raw = null ) {
450 return self
::formatRaw( SiteStats
::users(), $raw );
452 static function numberofactiveusers( $parser, $raw = null ) {
453 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
455 static function numberofarticles( $parser, $raw = null ) {
456 return self
::formatRaw( SiteStats
::articles(), $raw );
458 static function numberoffiles( $parser, $raw = null ) {
459 return self
::formatRaw( SiteStats
::images(), $raw );
461 static function numberofadmins( $parser, $raw = null ) {
462 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
464 static function numberofedits( $parser, $raw = null ) {
465 return self
::formatRaw( SiteStats
::edits(), $raw );
467 static function numberofviews( $parser, $raw = null ) {
468 global $wgDisableCounters;
469 return !$wgDisableCounters ? self
::formatRaw( SiteStats
::views(), $raw ) : '';
471 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
472 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
474 static function numberingroup( $parser, $name = '', $raw = null ) {
475 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
479 * Given a title, return the namespace name that would be given by the
480 * corresponding magic word
481 * Note: function name changed to "mwnamespace" rather than "namespace"
482 * to not break PHP 5.3
483 * @return mixed|string
485 static function mwnamespace( $parser, $title = null ) {
486 $t = Title
::newFromText( $title );
487 if ( is_null( $t ) ) {
490 return str_replace( '_', ' ', $t->getNsText() );
492 static function namespacee( $parser, $title = null ) {
493 $t = Title
::newFromText( $title );
494 if ( is_null( $t ) ) {
497 return wfUrlencode( $t->getNsText() );
499 static function namespacenumber( $parser, $title = null ) {
500 $t = Title
::newFromText( $title );
501 if ( is_null( $t ) ) {
504 return $t->getNamespace();
506 static function talkspace( $parser, $title = null ) {
507 $t = Title
::newFromText( $title );
508 if ( is_null( $t ) ||
!$t->canTalk() ) {
511 return str_replace( '_', ' ', $t->getTalkNsText() );
513 static function talkspacee( $parser, $title = null ) {
514 $t = Title
::newFromText( $title );
515 if ( is_null( $t ) ||
!$t->canTalk() ) {
518 return wfUrlencode( $t->getTalkNsText() );
520 static function subjectspace( $parser, $title = null ) {
521 $t = Title
::newFromText( $title );
522 if ( is_null( $t ) ) {
525 return str_replace( '_', ' ', $t->getSubjectNsText() );
527 static function subjectspacee( $parser, $title = null ) {
528 $t = Title
::newFromText( $title );
529 if ( is_null( $t ) ) {
532 return wfUrlencode( $t->getSubjectNsText() );
536 * Functions to get and normalize pagenames, corresponding to the magic words
540 static function pagename( $parser, $title = null ) {
541 $t = Title
::newFromText( $title );
542 if ( is_null( $t ) ) {
545 return wfEscapeWikiText( $t->getText() );
547 static function pagenamee( $parser, $title = null ) {
548 $t = Title
::newFromText( $title );
549 if ( is_null( $t ) ) {
552 return wfEscapeWikiText( $t->getPartialURL() );
554 static function fullpagename( $parser, $title = null ) {
555 $t = Title
::newFromText( $title );
556 if ( is_null( $t ) ||
!$t->canTalk() ) {
559 return wfEscapeWikiText( $t->getPrefixedText() );
561 static function fullpagenamee( $parser, $title = null ) {
562 $t = Title
::newFromText( $title );
563 if ( is_null( $t ) ||
!$t->canTalk() ) {
566 return wfEscapeWikiText( $t->getPrefixedURL() );
568 static function subpagename( $parser, $title = null ) {
569 $t = Title
::newFromText( $title );
570 if ( is_null( $t ) ) {
573 return wfEscapeWikiText( $t->getSubpageText() );
575 static function subpagenamee( $parser, $title = null ) {
576 $t = Title
::newFromText( $title );
577 if ( is_null( $t ) ) {
580 return wfEscapeWikiText( $t->getSubpageUrlForm() );
582 static function rootpagename( $parser, $title = null ) {
583 $t = Title
::newFromText( $title );
584 if ( is_null( $t ) ) {
587 return wfEscapeWikiText( $t->getRootText() );
589 static function rootpagenamee( $parser, $title = null ) {
590 $t = Title
::newFromText( $title );
591 if ( is_null( $t ) ) {
594 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
596 static function basepagename( $parser, $title = null ) {
597 $t = Title
::newFromText( $title );
598 if ( is_null( $t ) ) {
601 return wfEscapeWikiText( $t->getBaseText() );
603 static function basepagenamee( $parser, $title = null ) {
604 $t = Title
::newFromText( $title );
605 if ( is_null( $t ) ) {
608 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
610 static function talkpagename( $parser, $title = null ) {
611 $t = Title
::newFromText( $title );
612 if ( is_null( $t ) ||
!$t->canTalk() ) {
615 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
617 static function talkpagenamee( $parser, $title = null ) {
618 $t = Title
::newFromText( $title );
619 if ( is_null( $t ) ||
!$t->canTalk() ) {
622 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
624 static function subjectpagename( $parser, $title = null ) {
625 $t = Title
::newFromText( $title );
626 if ( is_null( $t ) ) {
629 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
631 static function subjectpagenamee( $parser, $title = null ) {
632 $t = Title
::newFromText( $title );
633 if ( is_null( $t ) ) {
636 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
640 * Return the number of pages, files or subcats in the given category,
641 * or 0 if it's nonexistent. This is an expensive parser function and
642 * can't be called too many times per page.
645 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
647 static $magicWords = null;
648 if ( is_null( $magicWords ) ) {
649 $magicWords = new MagicWordArray( array(
650 'pagesincategory_all',
651 'pagesincategory_pages',
652 'pagesincategory_subcats',
653 'pagesincategory_files'
656 static $cache = array();
658 // split the given option to its variable
659 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
660 //{{pagesincategory:|raw[|type]}}
662 $type = $magicWords->matchStartToEnd( $arg2 );
664 //{{pagesincategory:[|type[|raw]]}}
665 $type = $magicWords->matchStartToEnd( $arg1 );
668 if ( !$type ) { //backward compatibility
669 $type = 'pagesincategory_all';
672 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
673 if ( !$title ) { # invalid title
674 return self
::formatRaw( 0, $raw );
676 $wgContLang->findVariantLink( $name, $title, true );
678 // Normalize name for cache
679 $name = $title->getDBkey();
681 if ( !isset( $cache[$name] ) ) {
682 $category = Category
::newFromTitle( $title );
684 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
685 if ( $parser->incrementExpensiveFunctionCount() ) {
686 // $allCount is the total number of cat members,
687 // not the count of how many members are normal pages.
688 $allCount = (int)$category->getPageCount();
689 $subcatCount = (int)$category->getSubcatCount();
690 $fileCount = (int)$category->getFileCount();
691 $pagesCount = $allCount - $subcatCount - $fileCount;
693 $cache[$name]['pagesincategory_all'] = $allCount;
694 $cache[$name]['pagesincategory_pages'] = $pagesCount;
695 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
696 $cache[$name]['pagesincategory_files'] = $fileCount;
699 $count = $cache[$name][$type];
700 return self
::formatRaw( $count, $raw );
704 * Return the size of the given page, or 0 if it's nonexistent. This is an
705 * expensive parser function and can't be called too many times per page.
707 * @todo FIXME: Title::getLength() documentation claims that it adds things
708 * to the link cache, so the local cache here should be unnecessary, but
709 * in fact calling getLength() repeatedly for the same $page does seem to
710 * run one query for each call?
711 * @todo Document parameters
713 * @param $parser Parser
714 * @param $page String Name of page to check (Default: empty string)
715 * @param $raw String Should number be human readable with commas or just number
718 static function pagesize( $parser, $page = '', $raw = null ) {
719 $title = Title
::newFromText( $page );
721 if ( !is_object( $title ) ) {
722 return self
::formatRaw( 0, $raw );
725 // fetch revision from cache/database and return the value
726 $rev = self
::getCachedRevisionObject( $parser, $title );
727 $length = $rev ?
$rev->getSize() : 0;
728 return self
::formatRaw( $length, $raw );
732 * Returns the requested protection level for the current page
734 * @param Parser $parser
735 * @param string $type
736 * @param string $title
740 static function protectionlevel( $parser, $type = '', $title = '' ) {
741 $titleObject = Title
::newFromText( $title );
742 if ( !( $titleObject instanceof Title
) ) {
743 $titleObject = $parser->mTitle
;
745 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
746 # Title::getRestrictions returns an array, its possible it may have
747 # multiple values in the future
748 return implode( $restrictions, ',' );
752 * Gives language names.
753 * @param $parser Parser
754 * @param string $code Language code (of which to get name)
755 * @param string $inLanguage Language code (in which to get name)
758 static function language( $parser, $code = '', $inLanguage = '' ) {
759 $code = strtolower( $code );
760 $inLanguage = strtolower( $inLanguage );
761 $lang = Language
::fetchLanguageName( $code, $inLanguage );
762 return $lang !== '' ?
$lang : wfBCP47( $code );
766 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
769 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
770 $padding = $parser->killMarkers( $padding );
771 $lengthOfPadding = mb_strlen( $padding );
772 if ( $lengthOfPadding == 0 ) {
776 # The remaining length to add counts down to 0 as padding is added
777 $length = min( $length, 500 ) - mb_strlen( $string );
778 # $finalPadding is just $padding repeated enough times so that
779 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
781 while ( $length > 0 ) {
782 # If $length < $lengthofPadding, truncate $padding so we get the
783 # exact length desired.
784 $finalPadding .= mb_substr( $padding, 0, $length );
785 $length -= $lengthOfPadding;
788 if ( $direction == STR_PAD_LEFT
) {
789 return $finalPadding . $string;
791 return $string . $finalPadding;
795 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
796 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
799 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
800 return self
::pad( $parser, $string, $length, $padding );
804 * @param $parser Parser
808 static function anchorencode( $parser, $text ) {
809 $text = $parser->killMarkers( $text );
810 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
813 static function special( $parser, $text ) {
814 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
816 $title = SpecialPage
::getTitleFor( $page, $subpage );
817 return $title->getPrefixedText();
819 // unknown special page, just use the given text as its title, if at all possible
820 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
821 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
825 static function speciale( $parser, $text ) {
826 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
830 * @param $parser Parser
831 * @param string $text The sortkey to use
832 * @param string $uarg Either "noreplace" or "noerror" (in en)
833 * both suppress errors, and noreplace does nothing if
834 * a default sortkey already exists.
837 public static function defaultsort( $parser, $text, $uarg = '' ) {
838 static $magicWords = null;
839 if ( is_null( $magicWords ) ) {
840 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
842 $arg = $magicWords->matchStartToEnd( $uarg );
844 $text = trim( $text );
845 if ( strlen( $text ) == 0 ) {
848 $old = $parser->getCustomDefaultSort();
849 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
850 $parser->setDefaultSort( $text );
853 if ( $old === false ||
$old == $text ||
$arg ) {
856 $converter = $parser->getConverterLanguage()->getConverter();
857 return '<span class="error">' .
858 wfMessage( 'duplicate-defaultsort',
859 // Message should be parsed, but these params should only be escaped.
860 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
861 $converter->markNoConversion( wfEscapeWikiText( $text ) )
862 )->inContentLanguage()->text() .
867 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
868 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
869 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
870 $file = wfFindFile( $name );
872 if ( $argA == 'nowiki' ) {
873 // {{filepath: | option [| size] }}
875 $parsedWidthParam = $parser->parseWidthParam( $argB );
877 // {{filepath: [| size [|option]] }}
878 $parsedWidthParam = $parser->parseWidthParam( $argA );
879 $isNowiki = ( $argB == 'nowiki' );
883 $url = $file->getFullUrl();
885 // If a size is requested...
886 if ( count( $parsedWidthParam ) ) {
887 $mto = $file->transform( $parsedWidthParam );
889 if ( $mto && !$mto->isError() ) {
890 // ... change the URL to point to a thumbnail.
891 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
895 return array( $url, 'nowiki' => true );
904 * Parser function to extension tag adaptor
907 public static function tagObj( $parser, $frame, $args ) {
908 if ( !count( $args ) ) {
911 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
913 if ( count( $args ) ) {
914 $inner = $frame->expand( array_shift( $args ) );
919 $stripList = $parser->getStripList();
920 if ( !in_array( $tagName, $stripList ) ) {
921 return '<span class="error">' .
922 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
926 $attributes = array();
927 foreach ( $args as $arg ) {
928 $bits = $arg->splitArg();
929 if ( strval( $bits['index'] ) === '' ) {
930 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
931 $value = trim( $frame->expand( $bits['value'] ) );
932 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
933 $value = isset( $m[1] ) ?
$m[1] : '';
935 $attributes[$name] = $value;
942 'attributes' => $attributes,
943 'close' => "</$tagName>",
945 return $parser->extensionSubstitution( $params, $frame );
949 * Fetched the current revision of the given title and return this.
950 * Will increment the expensive function count and
951 * add a template link to get the value refreshed on changes.
952 * For a given title, which is equal to the current parser title,
953 * the revision object from the parser is used, when that is the current one
955 * @param $parser Parser
956 * @param $title Title
960 private static function getCachedRevisionObject( $parser, $title = null ) {
961 static $cache = array();
963 if ( is_null( $title ) ) {
967 // Use the revision from the parser itself, when param is the current page
968 // and the revision is the current one
969 if ( $title->equals( $parser->getTitle() ) ) {
970 $parserRev = $parser->getRevisionObject();
971 if ( $parserRev && $parserRev->isCurrent() ) {
972 // force reparse after edit with vary-revision flag
973 $parser->getOutput()->setFlag( 'vary-revision' );
974 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
979 // Normalize name for cache
980 $page = $title->getPrefixedDBkey();
982 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
983 return $cache[$page];
985 if ( $parser->incrementExpensiveFunctionCount() ) {
986 $rev = Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
987 $pageID = $rev ?
$rev->getPage() : 0;
988 $revID = $rev ?
$rev->getId() : 0;
989 $cache[$page] = $rev; // maybe null
991 // Register dependency in templatelinks
992 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
996 $cache[$page] = null;
1001 * Get the pageid of a specified page
1002 * @param $parser Parser
1003 * @param $title string Title to get the pageid from
1006 public static function pageid( $parser, $title = null ) {
1007 $t = Title
::newFromText( $title );
1008 if ( is_null( $t ) ) {
1011 // Use title from parser to have correct pageid after edit
1012 if ( $t->equals( $parser->getTitle() ) ) {
1013 $t = $parser->getTitle();
1015 // fetch pageid from cache/database and return the value
1016 $pageid = $t->getArticleID();
1017 return $pageid ?
$pageid : '';
1021 * Get the id from the last revision of a specified page.
1022 * @param $parser Parser
1023 * @param $title string Title to get the id from
1026 public static function revisionid( $parser, $title = null ) {
1027 $t = Title
::newFromText( $title );
1028 if ( is_null( $t ) ) {
1031 // fetch revision from cache/database and return the value
1032 $rev = self
::getCachedRevisionObject( $parser, $t );
1033 return $rev ?
$rev->getId() : '';
1037 * Get the day from the last revision of a specified page.
1038 * @param $parser Parser
1039 * @param $title string Title to get the day from
1042 public static function revisionday( $parser, $title = null ) {
1043 $t = Title
::newFromText( $title );
1044 if ( is_null( $t ) ) {
1047 // fetch revision from cache/database and return the value
1048 $rev = self
::getCachedRevisionObject( $parser, $t );
1049 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1053 * Get the day with leading zeros from the last revision of a specified page.
1054 * @param $parser Parser
1055 * @param $title string Title to get the day from
1058 public static function revisionday2( $parser, $title = null ) {
1059 $t = Title
::newFromText( $title );
1060 if ( is_null( $t ) ) {
1063 // fetch revision from cache/database and return the value
1064 $rev = self
::getCachedRevisionObject( $parser, $t );
1065 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1069 * Get the month with leading zeros from the last revision of a specified page.
1070 * @param $parser Parser
1071 * @param $title string Title to get the month from
1074 public static function revisionmonth( $parser, $title = null ) {
1075 $t = Title
::newFromText( $title );
1076 if ( is_null( $t ) ) {
1079 // fetch revision from cache/database and return the value
1080 $rev = self
::getCachedRevisionObject( $parser, $t );
1081 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1085 * Get the month from the last revision of a specified page.
1086 * @param $parser Parser
1087 * @param $title string Title to get the month from
1090 public static function revisionmonth1( $parser, $title = null ) {
1091 $t = Title
::newFromText( $title );
1092 if ( is_null( $t ) ) {
1095 // fetch revision from cache/database and return the value
1096 $rev = self
::getCachedRevisionObject( $parser, $t );
1097 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1101 * Get the year from the last revision of a specified page.
1102 * @param $parser Parser
1103 * @param $title string Title to get the year from
1106 public static function revisionyear( $parser, $title = null ) {
1107 $t = Title
::newFromText( $title );
1108 if ( is_null( $t ) ) {
1111 // fetch revision from cache/database and return the value
1112 $rev = self
::getCachedRevisionObject( $parser, $t );
1113 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1117 * Get the timestamp from the last revision of a specified page.
1118 * @param $parser Parser
1119 * @param $title string Title to get the timestamp from
1122 public static function revisiontimestamp( $parser, $title = null ) {
1123 $t = Title
::newFromText( $title );
1124 if ( is_null( $t ) ) {
1127 // fetch revision from cache/database and return the value
1128 $rev = self
::getCachedRevisionObject( $parser, $t );
1129 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1133 * Get the user from the last revision of a specified page.
1134 * @param $parser Parser
1135 * @param $title string Title to get the user from
1138 public static function revisionuser( $parser, $title = null ) {
1139 $t = Title
::newFromText( $title );
1140 if ( is_null( $t ) ) {
1143 // fetch revision from cache/database and return the value
1144 $rev = self
::getCachedRevisionObject( $parser, $t );
1145 return $rev ?
$rev->getUserText() : '';