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