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