Fix r46628 -- I'd misunderstood the nature of the hack. People wanted to append the...
[lhc/web/wiklou.git] / includes / parser / CoreParserFunctions.php
1 <?php
2
3 /**
4 * Various core parser functions, registered in Parser::firstCallInit()
5 * @ingroup Parser
6 */
7 class CoreParserFunctions {
8 static function register( $parser ) {
9 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
10
11 # Syntax for arguments (see self::setFunctionHook):
12 # "name for lookup in localized magic words array",
13 # function callback,
14 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
15 # instead of {{#int:...}})
16
17 $parser->setFunctionHook( 'int', array( __CLASS__, 'intFunction' ), SFH_NO_HASH );
18 $parser->setFunctionHook( 'ns', array( __CLASS__, 'ns' ), SFH_NO_HASH );
19 $parser->setFunctionHook( 'urlencode', array( __CLASS__, 'urlencode' ), SFH_NO_HASH );
20 $parser->setFunctionHook( 'lcfirst', array( __CLASS__, 'lcfirst' ), SFH_NO_HASH );
21 $parser->setFunctionHook( 'ucfirst', array( __CLASS__, 'ucfirst' ), SFH_NO_HASH );
22 $parser->setFunctionHook( 'lc', array( __CLASS__, 'lc' ), SFH_NO_HASH );
23 $parser->setFunctionHook( 'uc', array( __CLASS__, 'uc' ), SFH_NO_HASH );
24 $parser->setFunctionHook( 'localurl', array( __CLASS__, 'localurl' ), SFH_NO_HASH );
25 $parser->setFunctionHook( 'localurle', array( __CLASS__, 'localurle' ), SFH_NO_HASH );
26 $parser->setFunctionHook( 'fullurl', array( __CLASS__, 'fullurl' ), SFH_NO_HASH );
27 $parser->setFunctionHook( 'fullurle', array( __CLASS__, 'fullurle' ), SFH_NO_HASH );
28 $parser->setFunctionHook( 'formatnum', array( __CLASS__, 'formatnum' ), SFH_NO_HASH );
29 $parser->setFunctionHook( 'grammar', array( __CLASS__, 'grammar' ), SFH_NO_HASH );
30 $parser->setFunctionHook( 'gender', array( __CLASS__, 'gender' ), SFH_NO_HASH );
31 $parser->setFunctionHook( 'plural', array( __CLASS__, 'plural' ), SFH_NO_HASH );
32 $parser->setFunctionHook( 'numberofpages', array( __CLASS__, 'numberofpages' ), SFH_NO_HASH );
33 $parser->setFunctionHook( 'numberofusers', array( __CLASS__, 'numberofusers' ), SFH_NO_HASH );
34 $parser->setFunctionHook( 'numberofarticles', array( __CLASS__, 'numberofarticles' ), SFH_NO_HASH );
35 $parser->setFunctionHook( 'numberoffiles', array( __CLASS__, 'numberoffiles' ), SFH_NO_HASH );
36 $parser->setFunctionHook( 'numberofadmins', array( __CLASS__, 'numberofadmins' ), SFH_NO_HASH );
37 $parser->setFunctionHook( 'numberingroup', array( __CLASS__, 'numberingroup' ), SFH_NO_HASH );
38 $parser->setFunctionHook( 'numberofedits', array( __CLASS__, 'numberofedits' ), SFH_NO_HASH );
39 $parser->setFunctionHook( 'numberofviews', array( __CLASS__, 'numberofviews' ), SFH_NO_HASH );
40 $parser->setFunctionHook( 'language', array( __CLASS__, 'language' ), SFH_NO_HASH );
41 $parser->setFunctionHook( 'padleft', array( __CLASS__, 'padleft' ), SFH_NO_HASH );
42 $parser->setFunctionHook( 'padright', array( __CLASS__, 'padright' ), SFH_NO_HASH );
43 $parser->setFunctionHook( 'anchorencode', array( __CLASS__, 'anchorencode' ), SFH_NO_HASH );
44 $parser->setFunctionHook( 'special', array( __CLASS__, 'special' ) );
45 $parser->setFunctionHook( 'defaultsort', array( __CLASS__, 'defaultsort' ), SFH_NO_HASH );
46 $parser->setFunctionHook( 'filepath', array( __CLASS__, 'filepath' ), SFH_NO_HASH );
47 $parser->setFunctionHook( 'pagesincategory', array( __CLASS__, 'pagesincategory' ), SFH_NO_HASH );
48 $parser->setFunctionHook( 'pagesize', array( __CLASS__, 'pagesize' ), SFH_NO_HASH );
49 $parser->setFunctionHook( 'protectionlevel', array( __CLASS__, 'protectionlevel' ), SFH_NO_HASH );
50 $parser->setFunctionHook( 'namespace', array( __CLASS__, 'namespace' ), SFH_NO_HASH );
51 $parser->setFunctionHook( 'namespacee', array( __CLASS__, 'namespacee' ), SFH_NO_HASH );
52 $parser->setFunctionHook( 'talkspace', array( __CLASS__, 'talkspace' ), SFH_NO_HASH );
53 $parser->setFunctionHook( 'talkspacee', array( __CLASS__, 'talkspacee' ), SFH_NO_HASH );
54 $parser->setFunctionHook( 'subjectspace', array( __CLASS__, 'subjectspace' ), SFH_NO_HASH );
55 $parser->setFunctionHook( 'subjectspacee', array( __CLASS__, 'subjectspacee' ), SFH_NO_HASH );
56 $parser->setFunctionHook( 'tag', array( __CLASS__, 'tagObj' ), SFH_OBJECT_ARGS );
57
58 if ( $wgAllowDisplayTitle ) {
59 $parser->setFunctionHook( 'displaytitle', array( __CLASS__, 'displaytitle' ), SFH_NO_HASH );
60 }
61 if ( $wgAllowSlowParserFunctions ) {
62 $parser->setFunctionHook( 'pagesinnamespace', array( __CLASS__, 'pagesinnamespace' ), SFH_NO_HASH );
63 }
64 }
65
66 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
67 if ( strval( $part1 ) !== '' ) {
68 $args = array_slice( func_get_args(), 2 );
69 $message = wfMsgGetKey( $part1, true, false, false );
70 $message = wfMsgReplaceArgs( $message, $args );
71 $message = $parser->replaceVariables( $message ); // like $wgMessageCache->transform()
72 return $message;
73 } else {
74 return array( 'found' => false );
75 }
76 }
77
78 static function ns( $parser, $part1 = '' ) {
79 global $wgContLang;
80 if ( intval( $part1 ) || $part1 == "0" ) {
81 $index = intval( $part1 );
82 } else {
83 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
84 }
85 if ( $index !== false ) {
86 return $wgContLang->getFormattedNsText( $index );
87 } else {
88 return array( 'found' => false );
89 }
90 }
91
92 static function urlencode( $parser, $s = '' ) {
93 return urlencode( $s );
94 }
95
96 static function lcfirst( $parser, $s = '' ) {
97 global $wgContLang;
98 return $wgContLang->lcfirst( $s );
99 }
100
101 static function ucfirst( $parser, $s = '' ) {
102 global $wgContLang;
103 return $wgContLang->ucfirst( $s );
104 }
105
106 static function lc( $parser, $s = '' ) {
107 global $wgContLang;
108 if ( is_callable( array( $parser, 'markerSkipCallback' ) ) ) {
109 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
110 } else {
111 return $wgContLang->lc( $s );
112 }
113 }
114
115 static function uc( $parser, $s = '' ) {
116 global $wgContLang;
117 if ( is_callable( array( $parser, 'markerSkipCallback' ) ) ) {
118 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
119 } else {
120 return $wgContLang->uc( $s );
121 }
122 }
123
124 static function localurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getLocalURL', $s, $arg ); }
125 static function localurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeLocalURL', $s, $arg ); }
126 static function fullurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getFullURL', $s, $arg ); }
127 static function fullurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeFullURL', $s, $arg ); }
128
129 static function urlFunction( $func, $s = '', $arg = null ) {
130 $title = Title::newFromText( $s );
131 # Due to order of execution of a lot of bits, the values might be encoded
132 # before arriving here; if that's true, then the title can't be created
133 # and the variable will fail. If we can't get a decent title from the first
134 # attempt, url-decode and try for a second.
135 if( is_null( $title ) )
136 $title = Title::newFromUrl( urldecode( $s ) );
137 if( !is_null( $title ) ) {
138 # Convert NS_MEDIA -> NS_FILE
139 if( $title->getNamespace() == NS_MEDIA ) {
140 $title = Title::makeTitle( NS_FILE, $title->getDBKey() );
141 }
142 if( !is_null( $arg ) ) {
143 $text = $title->$func( $arg );
144 } else {
145 $text = $title->$func();
146 }
147 return $text;
148 } else {
149 return array( 'found' => false );
150 }
151 }
152
153 static function formatNum( $parser, $num = '', $raw = null) {
154 if ( self::israw( $raw ) ) {
155 return $parser->getFunctionLang()->parseFormattedNumber( $num );
156 } else {
157 return $parser->getFunctionLang()->formatNum( $num );
158 }
159 }
160
161 static function grammar( $parser, $case = '', $word = '' ) {
162 return $parser->getFunctionLang()->convertGrammar( $word, $case );
163 }
164
165 static function gender( $parser, $user ) {
166 $forms = array_slice( func_get_args(), 2);
167
168 // default
169 $gender = User::getDefaultOption( 'gender' );
170
171 // check parameter, or use $wgUser if in interface message
172 $user = User::newFromName( $user );
173 if ( $user ) {
174 $gender = $user->getOption( 'gender' );
175 } elseif ( $parser->mOptions->getInterfaceMessage() ) {
176 global $wgUser;
177 $gender = $wgUser->getOption( 'gender' );
178 }
179 return $parser->getFunctionLang()->gender( $gender, $forms );
180 }
181 static function plural( $parser, $text = '') {
182 $forms = array_slice( func_get_args(), 2);
183 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
184 return $parser->getFunctionLang()->convertPlural( $text, $forms );
185 }
186
187 /**
188 * Override the title of the page when viewed, provided we've been given a
189 * title which will normalise to the canonical title
190 *
191 * @param Parser $parser Parent parser
192 * @param string $text Desired title text
193 * @return string
194 */
195 static function displaytitle( $parser, $text = '' ) {
196 global $wgRestrictDisplayTitle;
197 $text = trim( Sanitizer::decodeCharReferences( $text ) );
198
199 if ( !$wgRestrictDisplayTitle ) {
200 $parser->mOutput->setDisplayTitle( $text );
201 } else {
202 $title = Title::newFromText( $text );
203 if( $title instanceof Title && $title->getFragment() == '' && $title->equals( $parser->mTitle ) )
204 $parser->mOutput->setDisplayTitle( $text );
205 }
206 return '';
207 }
208
209 static function isRaw( $param ) {
210 static $mwRaw;
211 if ( !$mwRaw ) {
212 $mwRaw =& MagicWord::get( 'rawsuffix' );
213 }
214 if ( is_null( $param ) ) {
215 return false;
216 } else {
217 return $mwRaw->match( $param );
218 }
219 }
220
221 static function formatRaw( $num, $raw ) {
222 if( self::isRaw( $raw ) ) {
223 return $num;
224 } else {
225 global $wgContLang;
226 return $wgContLang->formatNum( $num );
227 }
228 }
229 static function numberofpages( $parser, $raw = null ) {
230 return self::formatRaw( SiteStats::pages(), $raw );
231 }
232 static function numberofusers( $parser, $raw = null ) {
233 return self::formatRaw( SiteStats::users(), $raw );
234 }
235 static function numberofarticles( $parser, $raw = null ) {
236 return self::formatRaw( SiteStats::articles(), $raw );
237 }
238 static function numberoffiles( $parser, $raw = null ) {
239 return self::formatRaw( SiteStats::images(), $raw );
240 }
241 static function numberofadmins( $parser, $raw = null ) {
242 return self::formatRaw( SiteStats::numberingroup('sysop'), $raw );
243 }
244 static function numberofedits( $parser, $raw = null ) {
245 return self::formatRaw( SiteStats::edits(), $raw );
246 }
247 static function numberofviews( $parser, $raw = null ) {
248 return self::formatRaw( SiteStats::views(), $raw );
249 }
250 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
251 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
252 }
253 static function numberingroup( $parser, $name = '', $raw = null) {
254 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
255 }
256
257
258 /*
259 * Given a title, return the namespace name that would be given by the
260 * corresponding magic word
261 */
262 static function namespace( $parser, $title = null ) {
263 $t = Title::newFromText( $title );
264 if ( is_null($t) )
265 return '';
266 return str_replace( '_', ' ', $t->getNsText() );
267 }
268 static function namespacee( $parser, $title = null ) {
269 $t = Title::newFromText( $title );
270 if ( is_null($t) )
271 return '';
272 return wfUrlencode( $t->getNsText() );
273 }
274 static function talkspace( $parser, $title = null ) {
275 $t = Title::newFromText( $title );
276 if ( is_null($t) || !$t->canTalk() )
277 return '';
278 return str_replace( '_', ' ', $t->getTalkNsText() );
279 }
280 static function talkspacee( $parser, $title = null ) {
281 $t = Title::newFromText( $title );
282 if ( is_null($t) || !$t->canTalk() )
283 return '';
284 return wfUrlencode( $t->getTalkNsText() );
285 }
286 static function subjectspace( $parser, $title = null ) {
287 $t = Title::newFromText( $title );
288 if ( is_null($t) )
289 return '';
290 return str_replace( '_', ' ', $t->getSubjectNsText() );
291 }
292 static function subjectspacee( $parser, $title = null ) {
293 $t = Title::newFromText( $title );
294 if ( is_null($t) )
295 return '';
296 return wfUrlencode( $t->getSubjectNsText() );
297 }
298
299 /**
300 * Return the number of pages in the given category, or 0 if it's nonexis-
301 * tent. This is an expensive parser function and can't be called too many
302 * times per page.
303 */
304 static function pagesincategory( $parser, $name = '', $raw = null ) {
305 static $cache = array();
306 $category = Category::newFromName( $name );
307
308 if( !is_object( $category ) ) {
309 $cache[$name] = 0;
310 return self::formatRaw( 0, $raw );
311 }
312
313 # Normalize name for cache
314 $name = $category->getName();
315
316 $count = 0;
317 if( isset( $cache[$name] ) ) {
318 $count = $cache[$name];
319 } elseif( $parser->incrementExpensiveFunctionCount() ) {
320 $count = $cache[$name] = (int)$category->getPageCount();
321 }
322 return self::formatRaw( $count, $raw );
323 }
324
325 /**
326 * Return the size of the given page, or 0 if it's nonexistent. This is an
327 * expensive parser function and can't be called too many times per page.
328 *
329 * @FIXME This doesn't work correctly on preview for getting the size of
330 * the current page.
331 * @FIXME Title::getLength() documentation claims that it adds things to
332 * the link cache, so the local cache here should be unnecessary, but in
333 * fact calling getLength() repeatedly for the same $page does seem to
334 * run one query for each call?
335 */
336 static function pagesize( $parser, $page = '', $raw = null ) {
337 static $cache = array();
338 $title = Title::newFromText($page);
339
340 if( !is_object( $title ) ) {
341 $cache[$page] = 0;
342 return self::formatRaw( 0, $raw );
343 }
344
345 # Normalize name for cache
346 $page = $title->getPrefixedText();
347
348 $length = 0;
349 if( isset( $cache[$page] ) ) {
350 $length = $cache[$page];
351 } elseif( $parser->incrementExpensiveFunctionCount() ) {
352 $rev = Revision::newFromTitle($title);
353 $id = $rev ? $rev->getPage() : 0;
354 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
355
356 // Register dependency in templatelinks
357 $parser->mOutput->addTemplate( $title, $id, $rev ? $rev->getId() : 0 );
358 }
359 return self::formatRaw( $length, $raw );
360 }
361
362 /**
363 * Returns the requested protection level for the current page
364 */
365 static function protectionlevel( $parser, $type = '' ) {
366 $restrictions = $parser->mTitle->getRestrictions( strtolower( $type ) );
367 # Title::getRestrictions returns an array, its possible it may have
368 # multiple values in the future
369 return implode( $restrictions, ',' );
370 }
371
372 static function language( $parser, $arg = '' ) {
373 global $wgContLang;
374 $lang = $wgContLang->getLanguageName( strtolower( $arg ) );
375 return $lang != '' ? $lang : $arg;
376 }
377
378 /**
379 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
380 */
381 static function pad( $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
382 $lengthOfPadding = mb_strlen( $padding );
383 if ( $lengthOfPadding == 0 ) return $string;
384
385 // Thwart attempts to use this function to truncate strings.
386 // We don't want people implementing ParserFunctions in template,
387 // for performance and usability reasons.
388 if ($lengthOfPadding > $length && $string == '') return $string;
389
390 # The remaining length to add counts down to 0 as padding is added
391 $length = min( $length, 500 ) - mb_strlen( $string );
392 # $finalPadding is just $padding repeated enough times so that
393 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
394 $finalPadding = '';
395 while ( $length > 0 ) {
396 # If $length < $lengthofPadding, truncate $padding so we get the
397 # exact length desired.
398 $finalPadding .= mb_substr( $padding, 0, $length );
399 $length -= $lengthOfPadding;
400 }
401
402 if ( $direction == STR_PAD_LEFT ) {
403 return $finalPadding . $string;
404 } else {
405 return $string . $finalPadding;
406 }
407 }
408
409 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
410 return self::pad( $string, $length, $padding, STR_PAD_LEFT );
411 }
412
413 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
414 return self::pad( $string, $length, $padding );
415 }
416
417 static function anchorencode( $parser, $text ) {
418 $a = urlencode( $text );
419 $a = strtr( $a, array( '%' => '.', '+' => '_' ) );
420 # leave colons alone, however
421 $a = str_replace( '.3A', ':', $a );
422 return $a;
423 }
424
425 static function special( $parser, $text ) {
426 $title = SpecialPage::getTitleForAlias( $text );
427 if ( $title ) {
428 return $title->getPrefixedText();
429 } else {
430 return wfMsgForContent( 'nosuchspecialpage' );
431 }
432 }
433
434 public static function defaultsort( $parser, $text ) {
435 $text = trim( $text );
436 if( strlen( $text ) == 0 )
437 return '';
438 $old = $parser->getCustomDefaultSort();
439 $parser->setDefaultSort( $text );
440 if( $old === false || $old == $text )
441 return '';
442 else
443 return( '<span class="error">' .
444 wfMsg( 'duplicate-defaultsort',
445 htmlspecialchars( $old ),
446 htmlspecialchars( $text ) ) .
447 '</span>' );
448 }
449
450 public static function filepath( $parser, $name='', $option='' ) {
451 $file = wfFindFile( $name );
452 if( $file ) {
453 $url = $file->getFullUrl();
454 if( $option == 'nowiki' ) {
455 return array( $url, 'nowiki' => true );
456 }
457 return $url;
458 } else {
459 return '';
460 }
461 }
462
463 /**
464 * Parser function to extension tag adaptor
465 */
466 public static function tagObj( $parser, $frame, $args ) {
467 $xpath = false;
468 if ( !count( $args ) ) {
469 return '';
470 }
471 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
472
473 if ( count( $args ) ) {
474 $inner = $frame->expand( array_shift( $args ) );
475 } else {
476 $inner = null;
477 }
478
479 $stripList = $parser->getStripList();
480 if ( !in_array( $tagName, $stripList ) ) {
481 return '<span class="error">' .
482 wfMsg( 'unknown_extension_tag', $tagName ) .
483 '</span>';
484 }
485
486 $attributes = array();
487 foreach ( $args as $arg ) {
488 $bits = $arg->splitArg();
489 if ( strval( $bits['index'] ) === '' ) {
490 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
491 $value = trim( $frame->expand( $bits['value'] ) );
492 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
493 $value = isset( $m[1] ) ? $m[1] : '';
494 }
495 $attributes[$name] = $value;
496 }
497 }
498
499 $params = array(
500 'name' => $tagName,
501 'inner' => $inner,
502 'attributes' => $attributes,
503 'close' => "</$tagName>",
504 );
505 return $parser->extensionSubstitution( $params, $frame );
506 }
507 }