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