Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / parser / CoreParserFunctions.php
blob5b02e1947d6d2dd64568aa796237ca61b1fdaa26
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( 'basepagename', array( __CLASS__, 'basepagename' ), SFH_NO_HASH );
92 $parser->setFunctionHook( 'basepagenamee', array( __CLASS__, 'basepagenamee' ), SFH_NO_HASH );
93 $parser->setFunctionHook( 'subpagename', array( __CLASS__, 'subpagename' ), SFH_NO_HASH );
94 $parser->setFunctionHook( 'subpagenamee', array( __CLASS__, 'subpagenamee' ), SFH_NO_HASH );
95 $parser->setFunctionHook( 'talkpagename', array( __CLASS__, 'talkpagename' ), SFH_NO_HASH );
96 $parser->setFunctionHook( 'talkpagenamee', array( __CLASS__, 'talkpagenamee' ), SFH_NO_HASH );
97 $parser->setFunctionHook( 'subjectpagename', array( __CLASS__, 'subjectpagename' ), SFH_NO_HASH );
98 $parser->setFunctionHook( 'subjectpagenamee', array( __CLASS__, 'subjectpagenamee' ), SFH_NO_HASH );
99 $parser->setFunctionHook( 'tag', array( __CLASS__, 'tagObj' ), SFH_OBJECT_ARGS );
100 $parser->setFunctionHook( 'formatdate', array( __CLASS__, 'formatDate' ) );
102 if ( $wgAllowDisplayTitle ) {
103 $parser->setFunctionHook( 'displaytitle', array( __CLASS__, 'displaytitle' ), SFH_NO_HASH );
105 if ( $wgAllowSlowParserFunctions ) {
106 $parser->setFunctionHook( 'pagesinnamespace', array( __CLASS__, 'pagesinnamespace' ), SFH_NO_HASH );
111 * @param $parser Parser
112 * @param string $part1
113 * @return array
115 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
116 if ( strval( $part1 ) !== '' ) {
117 $args = array_slice( func_get_args(), 2 );
118 $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
119 return array( $message, 'noparse' => false );
120 } else {
121 return array( 'found' => false );
126 * @param $parser Parser
127 * @param $date
128 * @param null $defaultPref
129 * @return mixed|string
131 static function formatDate( $parser, $date, $defaultPref = null ) {
132 $lang = $parser->getFunctionLang();
133 $df = DateFormatter::getInstance( $lang );
135 $date = trim( $date );
137 $pref = $parser->getOptions()->getDateFormat();
139 // Specify a different default date format other than the the normal default
140 // iff the user has 'default' for their setting
141 if ( $pref == 'default' && $defaultPref ) {
142 $pref = $defaultPref;
145 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
146 return $date;
149 static function ns( $parser, $part1 = '' ) {
150 global $wgContLang;
151 if ( intval( $part1 ) || $part1 == "0" ) {
152 $index = intval( $part1 );
153 } else {
154 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
156 if ( $index !== false ) {
157 return $wgContLang->getFormattedNsText( $index );
158 } else {
159 return array( 'found' => false );
163 static function nse( $parser, $part1 = '' ) {
164 $ret = self::ns( $parser, $part1 );
165 if ( is_string( $ret ) ) {
166 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
168 return $ret;
172 * urlencodes a string according to one of three patterns: (bug 22474)
174 * By default (for HTTP "query" strings), spaces are encoded as '+'.
175 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
176 * For links to "wiki"s, or similar software, spaces are encoded as '_',
178 * @param $parser Parser object
179 * @param string $s The text to encode.
180 * @param string $arg (optional): The type of encoding.
181 * @return string
183 static function urlencode( $parser, $s = '', $arg = null ) {
184 static $magicWords = null;
185 if ( is_null( $magicWords ) ) {
186 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
188 switch( $magicWords->matchStartToEnd( $arg ) ) {
190 // Encode as though it's a wiki page, '_' for ' '.
191 case 'url_wiki':
192 $func = 'wfUrlencode';
193 $s = str_replace( ' ', '_', $s );
194 break;
196 // Encode for an HTTP Path, '%20' for ' '.
197 case 'url_path':
198 $func = 'rawurlencode';
199 break;
201 // Encode for HTTP query, '+' for ' '.
202 case 'url_query':
203 default:
204 $func = 'urlencode';
206 return $parser->markerSkipCallback( $s, $func );
209 static function lcfirst( $parser, $s = '' ) {
210 global $wgContLang;
211 return $wgContLang->lcfirst( $s );
214 static function ucfirst( $parser, $s = '' ) {
215 global $wgContLang;
216 return $wgContLang->ucfirst( $s );
220 * @param $parser Parser
221 * @param string $s
222 * @return
224 static function lc( $parser, $s = '' ) {
225 global $wgContLang;
226 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
230 * @param $parser Parser
231 * @param string $s
232 * @return
234 static function uc( $parser, $s = '' ) {
235 global $wgContLang;
236 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
239 static function localurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getLocalURL', $s, $arg ); }
240 static function localurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeLocalURL', $s, $arg ); }
241 static function fullurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getFullURL', $s, $arg ); }
242 static function fullurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeFullURL', $s, $arg ); }
243 static function canonicalurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getCanonicalURL', $s, $arg ); }
244 static function canonicalurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeCanonicalURL', $s, $arg ); }
246 static function urlFunction( $func, $s = '', $arg = null ) {
247 $title = Title::newFromText( $s );
248 # Due to order of execution of a lot of bits, the values might be encoded
249 # before arriving here; if that's true, then the title can't be created
250 # and the variable will fail. If we can't get a decent title from the first
251 # attempt, url-decode and try for a second.
252 if ( is_null( $title ) ) {
253 $title = Title::newFromURL( urldecode( $s ) );
255 if ( !is_null( $title ) ) {
256 # Convert NS_MEDIA -> NS_FILE
257 if ( $title->getNamespace() == NS_MEDIA ) {
258 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
260 if ( !is_null( $arg ) ) {
261 $text = $title->$func( $arg );
262 } else {
263 $text = $title->$func();
265 return $text;
266 } else {
267 return array( 'found' => false );
272 * @param $parser Parser
273 * @param string $num
274 * @param string $arg
275 * @return string
277 static function formatnum( $parser, $num = '', $arg = null ) {
278 if ( self::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
279 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
280 } elseif ( self::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
281 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
282 } else {
283 $func = array( $parser->getFunctionLang(), 'formatNum' );
285 return $parser->markerSkipCallback( $num, $func );
289 * @param $parser Parser
290 * @param string $case
291 * @param string $word
292 * @return
294 static function grammar( $parser, $case = '', $word = '' ) {
295 $word = $parser->killMarkers( $word );
296 return $parser->getFunctionLang()->convertGrammar( $word, $case );
300 * @param $parser Parser
301 * @param $username string
302 * @return
304 static function gender( $parser, $username ) {
305 wfProfileIn( __METHOD__ );
306 $forms = array_slice( func_get_args(), 2 );
308 // Some shortcuts to avoid loading user data unnecessarily
309 if ( count( $forms ) === 0 ) {
310 wfProfileOut( __METHOD__ );
311 return '';
312 } elseif ( count( $forms ) === 1 ) {
313 wfProfileOut( __METHOD__ );
314 return $forms[0];
317 $username = trim( $username );
319 // default
320 $gender = User::getDefaultOption( 'gender' );
322 // allow prefix.
323 $title = Title::newFromText( $username );
325 if ( $title && $title->getNamespace() == NS_USER ) {
326 $username = $title->getText();
329 // check parameter, or use the ParserOptions if in interface message
330 $user = User::newFromName( $username );
331 if ( $user ) {
332 $gender = GenderCache::singleton()->getGenderOf( $user, __METHOD__ );
333 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
334 $gender = GenderCache::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
336 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
337 wfProfileOut( __METHOD__ );
338 return $ret;
342 * @param $parser Parser
343 * @param string $text
344 * @return
346 static function plural( $parser, $text = '' ) {
347 $forms = array_slice( func_get_args(), 2 );
348 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
349 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
350 return $parser->getFunctionLang()->convertPlural( $text, $forms );
354 * Override the title of the page when viewed, provided we've been given a
355 * title which will normalise to the canonical title
357 * @param $parser Parser: parent parser
358 * @param string $text desired title text
359 * @return String
361 static function displaytitle( $parser, $text = '' ) {
362 global $wgRestrictDisplayTitle;
364 #parse a limited subset of wiki markup (just the single quote items)
365 $text = $parser->doQuotes( $text );
367 #remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
368 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
369 . preg_quote( Parser::MARKER_SUFFIX, '/' ) . '/', '', $text );
371 #list of disallowed tags for DISPLAYTITLE
372 #these will be escaped even though they are allowed in normal wiki text
373 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
374 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
376 #only requested titles that normalize to the actual title are allowed through
377 #if $wgRestrictDisplayTitle is true (it is by default)
378 #mimic the escaping process that occurs in OutputPage::setPageTitle
379 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $text, null, array(), array(), $bad ) );
380 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
382 if ( !$wgRestrictDisplayTitle ) {
383 $parser->mOutput->setDisplayTitle( $text );
384 } elseif ( $title instanceof Title && $title->getFragment() == '' && $title->equals( $parser->mTitle ) ) {
385 $parser->mOutput->setDisplayTitle( $text );
388 return '';
392 * Matches the given value against the value of given magic word
394 * @param string $magicword magic word key
395 * @param mixed $value value to match
396 * @return boolean true on successful match
398 static private function matchAgainstMagicword( $magicword, $value ) {
399 if ( strval( $value ) === '' ) {
400 return false;
402 $mwObject = MagicWord::get( $magicword );
403 return $mwObject->match( $value );
406 static function formatRaw( $num, $raw ) {
407 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
408 return $num;
409 } else {
410 global $wgContLang;
411 return $wgContLang->formatNum( $num );
414 static function numberofpages( $parser, $raw = null ) {
415 return self::formatRaw( SiteStats::pages(), $raw );
417 static function numberofusers( $parser, $raw = null ) {
418 return self::formatRaw( SiteStats::users(), $raw );
420 static function numberofactiveusers( $parser, $raw = null ) {
421 return self::formatRaw( SiteStats::activeUsers(), $raw );
423 static function numberofarticles( $parser, $raw = null ) {
424 return self::formatRaw( SiteStats::articles(), $raw );
426 static function numberoffiles( $parser, $raw = null ) {
427 return self::formatRaw( SiteStats::images(), $raw );
429 static function numberofadmins( $parser, $raw = null ) {
430 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
432 static function numberofedits( $parser, $raw = null ) {
433 return self::formatRaw( SiteStats::edits(), $raw );
435 static function numberofviews( $parser, $raw = null ) {
436 return self::formatRaw( SiteStats::views(), $raw );
438 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
439 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
441 static function numberingroup( $parser, $name = '', $raw = null) {
442 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
446 * Given a title, return the namespace name that would be given by the
447 * corresponding magic word
448 * Note: function name changed to "mwnamespace" rather than "namespace"
449 * to not break PHP 5.3
450 * @return mixed|string
452 static function mwnamespace( $parser, $title = null ) {
453 $t = Title::newFromText( $title );
454 if ( is_null( $t ) ) {
455 return '';
457 return str_replace( '_', ' ', $t->getNsText() );
459 static function namespacee( $parser, $title = null ) {
460 $t = Title::newFromText( $title );
461 if ( is_null( $t ) ) {
462 return '';
464 return wfUrlencode( $t->getNsText() );
466 static function namespacenumber( $parser, $title = null ) {
467 $t = Title::newFromText( $title );
468 if ( is_null( $t ) ) {
469 return '';
471 return $t->getNamespace();
473 static function talkspace( $parser, $title = null ) {
474 $t = Title::newFromText( $title );
475 if ( is_null( $t ) || !$t->canTalk() ) {
476 return '';
478 return str_replace( '_', ' ', $t->getTalkNsText() );
480 static function talkspacee( $parser, $title = null ) {
481 $t = Title::newFromText( $title );
482 if ( is_null( $t ) || !$t->canTalk() ) {
483 return '';
485 return wfUrlencode( $t->getTalkNsText() );
487 static function subjectspace( $parser, $title = null ) {
488 $t = Title::newFromText( $title );
489 if ( is_null( $t ) ) {
490 return '';
492 return str_replace( '_', ' ', $t->getSubjectNsText() );
494 static function subjectspacee( $parser, $title = null ) {
495 $t = Title::newFromText( $title );
496 if ( is_null( $t ) ) {
497 return '';
499 return wfUrlencode( $t->getSubjectNsText() );
503 * Functions to get and normalize pagenames, corresponding to the magic words
504 * of the same names
505 * @return String
507 static function pagename( $parser, $title = null ) {
508 $t = Title::newFromText( $title );
509 if ( is_null( $t ) ) {
510 return '';
512 return wfEscapeWikiText( $t->getText() );
514 static function pagenamee( $parser, $title = null ) {
515 $t = Title::newFromText( $title );
516 if ( is_null( $t ) ) {
517 return '';
519 return wfEscapeWikiText( $t->getPartialURL() );
521 static function fullpagename( $parser, $title = null ) {
522 $t = Title::newFromText( $title );
523 if ( is_null( $t ) || !$t->canTalk() ) {
524 return '';
526 return wfEscapeWikiText( $t->getPrefixedText() );
528 static function fullpagenamee( $parser, $title = null ) {
529 $t = Title::newFromText( $title );
530 if ( is_null( $t ) || !$t->canTalk() ) {
531 return '';
533 return wfEscapeWikiText( $t->getPrefixedURL() );
535 static function subpagename( $parser, $title = null ) {
536 $t = Title::newFromText( $title );
537 if ( is_null( $t ) ) {
538 return '';
540 return wfEscapeWikiText( $t->getSubpageText() );
542 static function subpagenamee( $parser, $title = null ) {
543 $t = Title::newFromText( $title );
544 if ( is_null( $t ) ) {
545 return '';
547 return wfEscapeWikiText( $t->getSubpageUrlForm() );
549 static function basepagename( $parser, $title = null ) {
550 $t = Title::newFromText( $title );
551 if ( is_null( $t ) ) {
552 return '';
554 return wfEscapeWikiText( $t->getBaseText() );
556 static function basepagenamee( $parser, $title = null ) {
557 $t = Title::newFromText( $title );
558 if ( is_null( $t ) ) {
559 return '';
561 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
563 static function talkpagename( $parser, $title = null ) {
564 $t = Title::newFromText( $title );
565 if ( is_null( $t ) || !$t->canTalk() ) {
566 return '';
568 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
570 static function talkpagenamee( $parser, $title = null ) {
571 $t = Title::newFromText( $title );
572 if ( is_null( $t ) || !$t->canTalk() ) {
573 return '';
575 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
577 static function subjectpagename( $parser, $title = null ) {
578 $t = Title::newFromText( $title );
579 if ( is_null( $t ) ) {
580 return '';
582 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
584 static function subjectpagenamee( $parser, $title = null ) {
585 $t = Title::newFromText( $title );
586 if ( is_null( $t ) ) {
587 return '';
589 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
593 * Return the number of pages, files or subcats in the given category,
594 * or 0 if it's nonexistent. This is an expensive parser function and
595 * can't be called too many times per page.
596 * @return string
598 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
599 static $magicWords = null;
600 if ( is_null( $magicWords ) ) {
601 $magicWords = new MagicWordArray( array(
602 'pagesincategory_all',
603 'pagesincategory_pages',
604 'pagesincategory_subcats',
605 'pagesincategory_files'
606 ) );
608 static $cache = array();
610 // split the given option to its variable
611 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
612 //{{pagesincategory:|raw[|type]}}
613 $raw = $arg1;
614 $type = $magicWords->matchStartToEnd( $arg2 );
615 } else {
616 //{{pagesincategory:[|type[|raw]]}}
617 $type = $magicWords->matchStartToEnd( $arg1 );
618 $raw = $arg2;
620 if ( !$type ) { //backward compatibility
621 $type = 'pagesincategory_all';
624 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
625 if ( !$title ) { # invalid title
626 return self::formatRaw( 0, $raw );
629 // Normalize name for cache
630 $name = $title->getDBkey();
632 if ( !isset( $cache[$name] ) ) {
633 $category = Category::newFromTitle( $title );
635 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
636 if ( $parser->incrementExpensiveFunctionCount() ) {
637 // $allCount is the total number of cat members,
638 // not the count of how many members are normal pages.
639 $allCount = (int)$category->getPageCount();
640 $subcatCount = (int)$category->getSubcatCount();
641 $fileCount = (int)$category->getFileCount();
642 $pagesCount = $allCount - $subcatCount - $fileCount;
644 $cache[$name]['pagesincategory_all'] = $allCount;
645 $cache[$name]['pagesincategory_pages'] = $pagesCount;
646 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
647 $cache[$name]['pagesincategory_files'] = $fileCount;
650 $count = $cache[$name][$type];
651 return self::formatRaw( $count, $raw );
655 * Return the size of the given page, or 0 if it's nonexistent. This is an
656 * expensive parser function and can't be called too many times per page.
658 * @todo FIXME: This doesn't work correctly on preview for getting the size
659 * of the current page.
660 * @todo FIXME: Title::getLength() documentation claims that it adds things
661 * to the link cache, so the local cache here should be unnecessary, but
662 * in fact calling getLength() repeatedly for the same $page does seem to
663 * run one query for each call?
664 * @todo Document parameters
666 * @param $parser Parser
667 * @param string $page TODO DOCUMENT (Default: empty string)
668 * @param $raw TODO DOCUMENT (Default: null)
669 * @return string
671 static function pagesize( $parser, $page = '', $raw = null ) {
672 static $cache = array();
673 $title = Title::newFromText( $page );
675 if ( !is_object( $title ) ) {
676 $cache[$page] = 0;
677 return self::formatRaw( 0, $raw );
680 # Normalize name for cache
681 $page = $title->getPrefixedText();
683 $length = 0;
684 if ( isset( $cache[$page] ) ) {
685 $length = $cache[$page];
686 } elseif ( $parser->incrementExpensiveFunctionCount() ) {
687 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
688 $pageID = $rev ? $rev->getPage() : 0;
689 $revID = $rev ? $rev->getId() : 0;
690 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
692 // Register dependency in templatelinks
693 $parser->mOutput->addTemplate( $title, $pageID, $revID );
695 return self::formatRaw( $length, $raw );
699 * Returns the requested protection level for the current page
701 * @param Parser $parser
702 * @param string $type
703 * @param string $title
705 * @return string
707 static function protectionlevel( $parser, $type = '', $title = '' ) {
708 $titleObject = Title::newFromText( $title );
709 if ( !( $titleObject instanceof Title ) ) {
710 $titleObject = $parser->mTitle;
712 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
713 # Title::getRestrictions returns an array, its possible it may have
714 # multiple values in the future
715 return implode( $restrictions, ',' );
719 * Gives language names.
720 * @param $parser Parser
721 * @param string $code Language code (of which to get name)
722 * @param string $inLanguage Language code (in which to get name)
723 * @return String
725 static function language( $parser, $code = '', $inLanguage = '' ) {
726 $code = strtolower( $code );
727 $inLanguage = strtolower( $inLanguage );
728 $lang = Language::fetchLanguageName( $code, $inLanguage );
729 return $lang !== '' ? $lang : wfBCP47( $code );
733 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
734 * @return string
736 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
737 $padding = $parser->killMarkers( $padding );
738 $lengthOfPadding = mb_strlen( $padding );
739 if ( $lengthOfPadding == 0 ) {
740 return $string;
743 # The remaining length to add counts down to 0 as padding is added
744 $length = min( $length, 500 ) - mb_strlen( $string );
745 # $finalPadding is just $padding repeated enough times so that
746 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
747 $finalPadding = '';
748 while ( $length > 0 ) {
749 # If $length < $lengthofPadding, truncate $padding so we get the
750 # exact length desired.
751 $finalPadding .= mb_substr( $padding, 0, $length );
752 $length -= $lengthOfPadding;
755 if ( $direction == STR_PAD_LEFT ) {
756 return $finalPadding . $string;
757 } else {
758 return $string . $finalPadding;
762 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
763 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
766 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
767 return self::pad( $parser, $string, $length, $padding );
771 * @param $parser Parser
772 * @param $text
773 * @return string
775 static function anchorencode( $parser, $text ) {
776 $text = $parser->killMarkers( $text );
777 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
780 static function special( $parser, $text ) {
781 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
782 if ( $page ) {
783 $title = SpecialPage::getTitleFor( $page, $subpage );
784 return $title->getPrefixedText();
785 } else {
786 return wfMessage( 'nosuchspecialpage' )->inContentLanguage()->text();
790 static function speciale( $parser, $text ) {
791 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
795 * @param $parser Parser
796 * @param string $text The sortkey to use
797 * @param string $uarg Either "noreplace" or "noerror" (in en)
798 * both suppress errors, and noreplace does nothing if
799 * a default sortkey already exists.
800 * @return string
802 public static function defaultsort( $parser, $text, $uarg = '' ) {
803 static $magicWords = null;
804 if ( is_null( $magicWords ) ) {
805 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
807 $arg = $magicWords->matchStartToEnd( $uarg );
809 $text = trim( $text );
810 if ( strlen( $text ) == 0 ) {
811 return '';
813 $old = $parser->getCustomDefaultSort();
814 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
815 $parser->setDefaultSort( $text );
818 if ( $old === false || $old == $text || $arg ) {
819 return '';
820 } else {
821 return( '<span class="error">' .
822 wfMessage( 'duplicate-defaultsort', $old, $text )->inContentLanguage()->escaped() .
823 '</span>' );
827 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
828 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
829 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
830 $file = wfFindFile( $name );
832 if ( $argA == 'nowiki' ) {
833 // {{filepath: | option [| size] }}
834 $isNowiki = true;
835 $parsedWidthParam = $parser->parseWidthParam( $argB );
836 } else {
837 // {{filepath: [| size [|option]] }}
838 $parsedWidthParam = $parser->parseWidthParam( $argA );
839 $isNowiki = ( $argB == 'nowiki' );
842 if ( $file ) {
843 $url = $file->getFullUrl();
845 // If a size is requested...
846 if ( count( $parsedWidthParam ) ) {
847 $mto = $file->transform( $parsedWidthParam );
848 // ... and we can
849 if ( $mto && !$mto->isError() ) {
850 // ... change the URL to point to a thumbnail.
851 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
854 if ( $isNowiki ) {
855 return array( $url, 'nowiki' => true );
857 return $url;
858 } else {
859 return '';
864 * Parser function to extension tag adaptor
865 * @return string
867 public static function tagObj( $parser, $frame, $args ) {
868 if ( !count( $args ) ) {
869 return '';
871 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
873 if ( count( $args ) ) {
874 $inner = $frame->expand( array_shift( $args ) );
875 } else {
876 $inner = null;
879 $stripList = $parser->getStripList();
880 if ( !in_array( $tagName, $stripList ) ) {
881 return '<span class="error">' .
882 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
883 '</span>';
886 $attributes = array();
887 foreach ( $args as $arg ) {
888 $bits = $arg->splitArg();
889 if ( strval( $bits['index'] ) === '' ) {
890 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
891 $value = trim( $frame->expand( $bits['value'] ) );
892 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
893 $value = isset( $m[1] ) ? $m[1] : '';
895 $attributes[$name] = $value;
899 $params = array(
900 'name' => $tagName,
901 'inner' => $inner,
902 'attributes' => $attributes,
903 'close' => "</$tagName>",
905 return $parser->extensionSubstitution( $params, $frame );