thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / parser / CoreParserFunctions.php
bloba7820d4b6aa0c48469a0cd86273d04fefd408229
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
24 /**
25 * Various core parser functions, registered in Parser::firstCallInit()
26 * @ingroup Parser
28 class CoreParserFunctions {
29 /**
30 * @param $parser Parser
31 * @return void
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",
38 # function callback,
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
115 * @return array
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 );
122 } else {
123 return array( 'found' => false );
128 * @param $parser Parser
129 * @param $date
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' ) );
148 return $date;
151 static function ns( $parser, $part1 = '' ) {
152 global $wgContLang;
153 if ( intval( $part1 ) || $part1 == "0" ) {
154 $index = intval( $part1 );
155 } else {
156 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
158 if ( $index !== false ) {
159 return $wgContLang->getFormattedNsText( $index );
160 } else {
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 ) );
170 return $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.
183 * @return string
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 ' '.
193 case 'url_wiki':
194 $func = 'wfUrlencode';
195 $s = str_replace( ' ', '_', $s );
196 break;
198 // Encode for an HTTP Path, '%20' for ' '.
199 case 'url_path':
200 $func = 'rawurlencode';
201 break;
203 // Encode for HTTP query, '+' for ' '.
204 case 'url_query':
205 default:
206 $func = 'urlencode';
208 return $parser->markerSkipCallback( $s, $func );
211 static function lcfirst( $parser, $s = '' ) {
212 global $wgContLang;
213 return $wgContLang->lcfirst( $s );
216 static function ucfirst( $parser, $s = '' ) {
217 global $wgContLang;
218 return $wgContLang->ucfirst( $s );
222 * @param $parser Parser
223 * @param string $s
224 * @return
226 static function lc( $parser, $s = '' ) {
227 global $wgContLang;
228 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
232 * @param $parser Parser
233 * @param string $s
234 * @return
236 static function uc( $parser, $s = '' ) {
237 global $wgContLang;
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 );
264 } else {
265 $text = $title->$func();
267 return $text;
268 } else {
269 return array( 'found' => false );
274 * @param $parser Parser
275 * @param string $num
276 * @param string $arg
277 * @return string
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' );
284 } else {
285 $func = array( $parser->getFunctionLang(), 'formatNum' );
287 return $parser->markerSkipCallback( $num, $func );
291 * @param $parser Parser
292 * @param string $case
293 * @param string $word
294 * @return
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
304 * @return
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__ );
313 return '';
314 } elseif ( count( $forms ) === 1 ) {
315 wfProfileOut( __METHOD__ );
316 return $forms[0];
319 $username = trim( $username );
321 // default
322 $gender = User::getDefaultOption( 'gender' );
324 // allow prefix.
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 );
333 if ( $user ) {
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__ );
340 return $ret;
344 * @param $parser Parser
345 * @param string $text
346 * @return
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
361 * @return String
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 );
395 } else {
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 );
411 return '';
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 ) === '' ) {
423 return false;
425 $mwObject = MagicWord::get( $magicword );
426 return $mwObject->match( $value );
429 static function formatRaw( $num, $raw ) {
430 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
431 return $num;
432 } else {
433 global $wgContLang;
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 return self::formatRaw( SiteStats::views(), $raw );
461 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
462 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
464 static function numberingroup( $parser, $name = '', $raw = null ) {
465 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
469 * Given a title, return the namespace name that would be given by the
470 * corresponding magic word
471 * Note: function name changed to "mwnamespace" rather than "namespace"
472 * to not break PHP 5.3
473 * @return mixed|string
475 static function mwnamespace( $parser, $title = null ) {
476 $t = Title::newFromText( $title );
477 if ( is_null( $t ) ) {
478 return '';
480 return str_replace( '_', ' ', $t->getNsText() );
482 static function namespacee( $parser, $title = null ) {
483 $t = Title::newFromText( $title );
484 if ( is_null( $t ) ) {
485 return '';
487 return wfUrlencode( $t->getNsText() );
489 static function namespacenumber( $parser, $title = null ) {
490 $t = Title::newFromText( $title );
491 if ( is_null( $t ) ) {
492 return '';
494 return $t->getNamespace();
496 static function talkspace( $parser, $title = null ) {
497 $t = Title::newFromText( $title );
498 if ( is_null( $t ) || !$t->canTalk() ) {
499 return '';
501 return str_replace( '_', ' ', $t->getTalkNsText() );
503 static function talkspacee( $parser, $title = null ) {
504 $t = Title::newFromText( $title );
505 if ( is_null( $t ) || !$t->canTalk() ) {
506 return '';
508 return wfUrlencode( $t->getTalkNsText() );
510 static function subjectspace( $parser, $title = null ) {
511 $t = Title::newFromText( $title );
512 if ( is_null( $t ) ) {
513 return '';
515 return str_replace( '_', ' ', $t->getSubjectNsText() );
517 static function subjectspacee( $parser, $title = null ) {
518 $t = Title::newFromText( $title );
519 if ( is_null( $t ) ) {
520 return '';
522 return wfUrlencode( $t->getSubjectNsText() );
526 * Functions to get and normalize pagenames, corresponding to the magic words
527 * of the same names
528 * @return String
530 static function pagename( $parser, $title = null ) {
531 $t = Title::newFromText( $title );
532 if ( is_null( $t ) ) {
533 return '';
535 return wfEscapeWikiText( $t->getText() );
537 static function pagenamee( $parser, $title = null ) {
538 $t = Title::newFromText( $title );
539 if ( is_null( $t ) ) {
540 return '';
542 return wfEscapeWikiText( $t->getPartialURL() );
544 static function fullpagename( $parser, $title = null ) {
545 $t = Title::newFromText( $title );
546 if ( is_null( $t ) || !$t->canTalk() ) {
547 return '';
549 return wfEscapeWikiText( $t->getPrefixedText() );
551 static function fullpagenamee( $parser, $title = null ) {
552 $t = Title::newFromText( $title );
553 if ( is_null( $t ) || !$t->canTalk() ) {
554 return '';
556 return wfEscapeWikiText( $t->getPrefixedURL() );
558 static function subpagename( $parser, $title = null ) {
559 $t = Title::newFromText( $title );
560 if ( is_null( $t ) ) {
561 return '';
563 return wfEscapeWikiText( $t->getSubpageText() );
565 static function subpagenamee( $parser, $title = null ) {
566 $t = Title::newFromText( $title );
567 if ( is_null( $t ) ) {
568 return '';
570 return wfEscapeWikiText( $t->getSubpageUrlForm() );
572 static function rootpagename( $parser, $title = null ) {
573 $t = Title::newFromText( $title );
574 if ( is_null( $t ) ) {
575 return '';
577 return wfEscapeWikiText( $t->getRootText() );
579 static function rootpagenamee( $parser, $title = null ) {
580 $t = Title::newFromText( $title );
581 if ( is_null( $t ) ) {
582 return '';
584 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
586 static function basepagename( $parser, $title = null ) {
587 $t = Title::newFromText( $title );
588 if ( is_null( $t ) ) {
589 return '';
591 return wfEscapeWikiText( $t->getBaseText() );
593 static function basepagenamee( $parser, $title = null ) {
594 $t = Title::newFromText( $title );
595 if ( is_null( $t ) ) {
596 return '';
598 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
600 static function talkpagename( $parser, $title = null ) {
601 $t = Title::newFromText( $title );
602 if ( is_null( $t ) || !$t->canTalk() ) {
603 return '';
605 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
607 static function talkpagenamee( $parser, $title = null ) {
608 $t = Title::newFromText( $title );
609 if ( is_null( $t ) || !$t->canTalk() ) {
610 return '';
612 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
614 static function subjectpagename( $parser, $title = null ) {
615 $t = Title::newFromText( $title );
616 if ( is_null( $t ) ) {
617 return '';
619 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
621 static function subjectpagenamee( $parser, $title = null ) {
622 $t = Title::newFromText( $title );
623 if ( is_null( $t ) ) {
624 return '';
626 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
630 * Return the number of pages, files or subcats in the given category,
631 * or 0 if it's nonexistent. This is an expensive parser function and
632 * can't be called too many times per page.
633 * @return string
635 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
636 static $magicWords = null;
637 if ( is_null( $magicWords ) ) {
638 $magicWords = new MagicWordArray( array(
639 'pagesincategory_all',
640 'pagesincategory_pages',
641 'pagesincategory_subcats',
642 'pagesincategory_files'
643 ) );
645 static $cache = array();
647 // split the given option to its variable
648 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
649 //{{pagesincategory:|raw[|type]}}
650 $raw = $arg1;
651 $type = $magicWords->matchStartToEnd( $arg2 );
652 } else {
653 //{{pagesincategory:[|type[|raw]]}}
654 $type = $magicWords->matchStartToEnd( $arg1 );
655 $raw = $arg2;
657 if ( !$type ) { //backward compatibility
658 $type = 'pagesincategory_all';
661 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
662 if ( !$title ) { # invalid title
663 return self::formatRaw( 0, $raw );
666 // Normalize name for cache
667 $name = $title->getDBkey();
669 if ( !isset( $cache[$name] ) ) {
670 $category = Category::newFromTitle( $title );
672 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
673 if ( $parser->incrementExpensiveFunctionCount() ) {
674 // $allCount is the total number of cat members,
675 // not the count of how many members are normal pages.
676 $allCount = (int)$category->getPageCount();
677 $subcatCount = (int)$category->getSubcatCount();
678 $fileCount = (int)$category->getFileCount();
679 $pagesCount = $allCount - $subcatCount - $fileCount;
681 $cache[$name]['pagesincategory_all'] = $allCount;
682 $cache[$name]['pagesincategory_pages'] = $pagesCount;
683 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
684 $cache[$name]['pagesincategory_files'] = $fileCount;
687 $count = $cache[$name][$type];
688 return self::formatRaw( $count, $raw );
692 * Return the size of the given page, or 0 if it's nonexistent. This is an
693 * expensive parser function and can't be called too many times per page.
695 * @todo FIXME: Title::getLength() documentation claims that it adds things
696 * to the link cache, so the local cache here should be unnecessary, but
697 * in fact calling getLength() repeatedly for the same $page does seem to
698 * run one query for each call?
699 * @todo Document parameters
701 * @param $parser Parser
702 * @param $page String Name of page to check (Default: empty string)
703 * @param $raw String Should number be human readable with commas or just number
704 * @return string
706 static function pagesize( $parser, $page = '', $raw = null ) {
707 static $cache = array();
708 $title = Title::newFromText( $page );
710 if ( !is_object( $title ) ) {
711 $cache[$page] = 0;
712 return self::formatRaw( 0, $raw );
715 # Normalize name for cache
716 $page = $title->getPrefixedText();
718 $length = 0;
719 if ( $title->equals( $parser->getTitle() )
720 && $parser->mInputSize !== false
722 # We are on current page (and not in PST), so
723 # take length of input to parser.
724 $length = $parser->mInputSize;
725 } elseif ( isset( $cache[$page] ) ) {
726 $length = $cache[$page];
727 } elseif ( $parser->incrementExpensiveFunctionCount() ) {
728 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
729 $pageID = $rev ? $rev->getPage() : 0;
730 $revID = $rev ? $rev->getId() : 0;
731 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
733 // Register dependency in templatelinks
734 $parser->mOutput->addTemplate( $title, $pageID, $revID );
736 return self::formatRaw( $length, $raw );
740 * Returns the requested protection level for the current page
742 * @param Parser $parser
743 * @param string $type
744 * @param string $title
746 * @return string
748 static function protectionlevel( $parser, $type = '', $title = '' ) {
749 $titleObject = Title::newFromText( $title );
750 if ( !( $titleObject instanceof Title ) ) {
751 $titleObject = $parser->mTitle;
753 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
754 # Title::getRestrictions returns an array, its possible it may have
755 # multiple values in the future
756 return implode( $restrictions, ',' );
760 * Gives language names.
761 * @param $parser Parser
762 * @param string $code Language code (of which to get name)
763 * @param string $inLanguage Language code (in which to get name)
764 * @return String
766 static function language( $parser, $code = '', $inLanguage = '' ) {
767 $code = strtolower( $code );
768 $inLanguage = strtolower( $inLanguage );
769 $lang = Language::fetchLanguageName( $code, $inLanguage );
770 return $lang !== '' ? $lang : wfBCP47( $code );
774 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
775 * @return string
777 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
778 $padding = $parser->killMarkers( $padding );
779 $lengthOfPadding = mb_strlen( $padding );
780 if ( $lengthOfPadding == 0 ) {
781 return $string;
784 # The remaining length to add counts down to 0 as padding is added
785 $length = min( $length, 500 ) - mb_strlen( $string );
786 # $finalPadding is just $padding repeated enough times so that
787 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
788 $finalPadding = '';
789 while ( $length > 0 ) {
790 # If $length < $lengthofPadding, truncate $padding so we get the
791 # exact length desired.
792 $finalPadding .= mb_substr( $padding, 0, $length );
793 $length -= $lengthOfPadding;
796 if ( $direction == STR_PAD_LEFT ) {
797 return $finalPadding . $string;
798 } else {
799 return $string . $finalPadding;
803 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
804 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
807 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
808 return self::pad( $parser, $string, $length, $padding );
812 * @param $parser Parser
813 * @param $text
814 * @return string
816 static function anchorencode( $parser, $text ) {
817 $text = $parser->killMarkers( $text );
818 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
821 static function special( $parser, $text ) {
822 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
823 if ( $page ) {
824 $title = SpecialPage::getTitleFor( $page, $subpage );
825 return $title->getPrefixedText();
826 } else {
827 // unknown special page, just use the given text as its title, if at all possible
828 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
829 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
833 static function speciale( $parser, $text ) {
834 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
838 * @param $parser Parser
839 * @param string $text The sortkey to use
840 * @param string $uarg Either "noreplace" or "noerror" (in en)
841 * both suppress errors, and noreplace does nothing if
842 * a default sortkey already exists.
843 * @return string
845 public static function defaultsort( $parser, $text, $uarg = '' ) {
846 static $magicWords = null;
847 if ( is_null( $magicWords ) ) {
848 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
850 $arg = $magicWords->matchStartToEnd( $uarg );
852 $text = trim( $text );
853 if ( strlen( $text ) == 0 ) {
854 return '';
856 $old = $parser->getCustomDefaultSort();
857 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
858 $parser->setDefaultSort( $text );
861 if ( $old === false || $old == $text || $arg ) {
862 return '';
863 } else {
864 return '<span class="error">' .
865 wfMessage( 'duplicate-defaultsort', $old, $text )->inContentLanguage()->escaped() .
866 '</span>';
870 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
871 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
872 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
873 $file = wfFindFile( $name );
875 if ( $argA == 'nowiki' ) {
876 // {{filepath: | option [| size] }}
877 $isNowiki = true;
878 $parsedWidthParam = $parser->parseWidthParam( $argB );
879 } else {
880 // {{filepath: [| size [|option]] }}
881 $parsedWidthParam = $parser->parseWidthParam( $argA );
882 $isNowiki = ( $argB == 'nowiki' );
885 if ( $file ) {
886 $url = $file->getFullUrl();
888 // If a size is requested...
889 if ( count( $parsedWidthParam ) ) {
890 $mto = $file->transform( $parsedWidthParam );
891 // ... and we can
892 if ( $mto && !$mto->isError() ) {
893 // ... change the URL to point to a thumbnail.
894 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
897 if ( $isNowiki ) {
898 return array( $url, 'nowiki' => true );
900 return $url;
901 } else {
902 return '';
907 * Parser function to extension tag adaptor
908 * @return string
910 public static function tagObj( $parser, $frame, $args ) {
911 if ( !count( $args ) ) {
912 return '';
914 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
916 if ( count( $args ) ) {
917 $inner = $frame->expand( array_shift( $args ) );
918 } else {
919 $inner = null;
922 $stripList = $parser->getStripList();
923 if ( !in_array( $tagName, $stripList ) ) {
924 return '<span class="error">' .
925 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
926 '</span>';
929 $attributes = array();
930 foreach ( $args as $arg ) {
931 $bits = $arg->splitArg();
932 if ( strval( $bits['index'] ) === '' ) {
933 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
934 $value = trim( $frame->expand( $bits['value'] ) );
935 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
936 $value = isset( $m[1] ) ? $m[1] : '';
938 $attributes[$name] = $value;
942 $params = array(
943 'name' => $tagName,
944 'inner' => $inner,
945 'attributes' => $attributes,
946 'close' => "</$tagName>",
948 return $parser->extensionSubstitution( $params, $frame );