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