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