(bug 12998) Weaken DISPLAYTITLE restictions (patch by 'rememberthedot@gmail.com')
[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 if ( !is_null( $arg ) ) {
131 $text = $title->$func( $arg );
132 } else {
133 $text = $title->$func();
134 }
135 return $text;
136 } else {
137 return array( 'found' => false );
138 }
139 }
140
141 static function formatNum( $parser, $num = '', $raw = null) {
142 if ( self::israw( $raw ) ) {
143 return $parser->getFunctionLang()->parseFormattedNumber( $num );
144 } else {
145 return $parser->getFunctionLang()->formatNum( $num );
146 }
147 }
148
149 static function grammar( $parser, $case = '', $word = '' ) {
150 return $parser->getFunctionLang()->convertGrammar( $word, $case );
151 }
152
153 static function plural( $parser, $text = '') {
154 $forms = array_slice( func_get_args(), 2);
155 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
156 return $parser->getFunctionLang()->convertPlural( $text, $forms );
157 }
158
159 /**
160 * Override the title of the page when viewed, provided we've been given a
161 * title which will normalise to the canonical title
162 *
163 * @param Parser $parser Parent parser
164 * @param string $text Desired title text
165 * @return string
166 */
167 static function displaytitle( $parser, $displayTitleH1 = '', $displayTitleTitle = '' ) {
168 global $wgRestrictDisplayTitle;
169
170 $titleHTML = Sanitizer::removeHTMLtags( $displayTitleH1 ); #escape the bad tags
171 $titleText = trim( Sanitizer::stripAllTags( $titleHTML ) ); #remove the good tags, leaving the bad tags escaped, and trim it to make sure it comes out pretty
172
173 #the user can put any sanitized text into the page title used in the <title> attribute, since it is not copy-pasteable like the <h1> tag
174 if ($displayTitleTitle == '') {
175 $parser->mOutput->setDisplayTitle( $titleText ); #use the stripped contents of <h1>
176 } else {
177 $parser->mOutput->setDisplayTitle( $displayTitleTitle ); #use what the user explicitly requested, MediaWiki escapes this automatically before it is served out
178 }
179
180 if ( !$wgRestrictDisplayTitle ) {
181 $parser->mOutput->setDisplayTitleH1( $titleHTML );
182 } else {
183 #only titles that normalize to the same title are allowed in the <h1> tag
184 $title = Title::newFromText( $titleText );
185
186 if ( $title instanceof Title && $title->getFragment() == '' && $title->equals( $parser->mTitle ) ) {
187 $parser->mOutput->setDisplayTitleH1( $titleHTML );
188 } else {
189 $parser->mOutput->setDisplayTitleH1( $parser->mTitle );
190 }
191 }
192
193 return '';
194 }
195
196 static function isRaw( $param ) {
197 static $mwRaw;
198 if ( !$mwRaw ) {
199 $mwRaw =& MagicWord::get( 'rawsuffix' );
200 }
201 if ( is_null( $param ) ) {
202 return false;
203 } else {
204 return $mwRaw->match( $param );
205 }
206 }
207
208 static function formatRaw( $num, $raw ) {
209 if( self::isRaw( $raw ) ) {
210 return $num;
211 } else {
212 global $wgContLang;
213 return $wgContLang->formatNum( $num );
214 }
215 }
216 static function numberofpages( $parser, $raw = null ) {
217 return self::formatRaw( SiteStats::pages(), $raw );
218 }
219 static function numberofusers( $parser, $raw = null ) {
220 return self::formatRaw( SiteStats::users(), $raw );
221 }
222 static function numberofarticles( $parser, $raw = null ) {
223 return self::formatRaw( SiteStats::articles(), $raw );
224 }
225 static function numberoffiles( $parser, $raw = null ) {
226 return self::formatRaw( SiteStats::images(), $raw );
227 }
228 static function numberofadmins( $parser, $raw = null ) {
229 return self::formatRaw( SiteStats::numberingroup('sysop'), $raw );
230 }
231 static function numberofedits( $parser, $raw = null ) {
232 return self::formatRaw( SiteStats::edits(), $raw );
233 }
234 static function numberofviews( $parser, $raw = null ) {
235 return self::formatRaw( SiteStats::views(), $raw );
236 }
237 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
238 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
239 }
240 static function numberingroup( $parser, $name = '', $raw = null) {
241 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
242 }
243
244 /**
245 * Return the number of pages in the given category, or 0 if it's nonexis-
246 * tent. This is an expensive parser function and can't be called too many
247 * times per page.
248 */
249 static function pagesincategory( $parser, $name = '', $raw = null ) {
250 static $cache = array();
251 $category = Category::newFromName( $name );
252
253 if( !is_object( $category ) ) {
254 $cache[$name] = 0;
255 return self::formatRaw( 0, $raw );
256 }
257
258 # Normalize name for cache
259 $name = $category->getName();
260
261 $count = 0;
262 if( isset( $cache[$name] ) ) {
263 $count = $cache[$name];
264 } elseif( $parser->incrementExpensiveFunctionCount() ) {
265 $count = $cache[$name] = (int)$category->getPageCount();
266 }
267 return self::formatRaw( $count, $raw );
268 }
269
270 /**
271 * Return the size of the given page, or 0 if it's nonexistent. This is an
272 * expensive parser function and can't be called too many times per page.
273 *
274 * @FIXME This doesn't work correctly on preview for getting the size of
275 * the current page.
276 * @FIXME Title::getLength() documentation claims that it adds things to
277 * the link cache, so the local cache here should be unnecessary, but in
278 * fact calling getLength() repeatedly for the same $page does seem to
279 * run one query for each call?
280 */
281 static function pagesize( $parser, $page = '', $raw = null ) {
282 static $cache = array();
283 $title = Title::newFromText($page);
284
285 if( !is_object( $title ) ) {
286 $cache[$page] = 0;
287 return self::formatRaw( 0, $raw );
288 }
289
290 # Normalize name for cache
291 $page = $title->getPrefixedText();
292
293 $length = 0;
294 if( isset( $cache[$page] ) ) {
295 $length = $cache[$page];
296 } elseif( $parser->incrementExpensiveFunctionCount() ) {
297 $length = $cache[$page] = $title->getLength();
298
299 // Register dependency in templatelinks
300 $id = $title->getArticleId();
301 $revid = Revision::newFromTitle($title);
302 $parser->mOutput->addTemplate($title, $id, $revid);
303 }
304 return self::formatRaw( $length, $raw );
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 static function pad( $string = '', $length = 0, $char = 0, $direction = STR_PAD_RIGHT ) {
314 $length = min( max( $length, 0 ), 500 );
315 $char = substr( $char, 0, 1 );
316 return ( $string !== '' && (int)$length > 0 && strlen( trim( (string)$char ) ) > 0 )
317 ? str_pad( $string, $length, (string)$char, $direction )
318 : $string;
319 }
320
321 static function padleft( $parser, $string = '', $length = 0, $char = 0 ) {
322 return self::pad( $string, $length, $char, STR_PAD_LEFT );
323 }
324
325 static function padright( $parser, $string = '', $length = 0, $char = 0 ) {
326 return self::pad( $string, $length, $char );
327 }
328
329 static function anchorencode( $parser, $text ) {
330 $a = urlencode( $text );
331 $a = strtr( $a, array( '%' => '.', '+' => '_' ) );
332 # leave colons alone, however
333 $a = str_replace( '.3A', ':', $a );
334 return $a;
335 }
336
337 static function special( $parser, $text ) {
338 $title = SpecialPage::getTitleForAlias( $text );
339 if ( $title ) {
340 return $title->getPrefixedText();
341 } else {
342 return wfMsgForContent( 'nosuchspecialpage' );
343 }
344 }
345
346 public static function defaultsort( $parser, $text ) {
347 $text = trim( $text );
348 if( strlen( $text ) == 0 )
349 return '';
350 $old = $parser->getCustomDefaultSort();
351 $parser->setDefaultSort( $text );
352 if( $old === false || $old == $text )
353 return '';
354 else
355 return( '<span class="error">' .
356 wfMsg( 'duplicate-defaultsort',
357 htmlspecialchars( $old ),
358 htmlspecialchars( $text ) ) .
359 '</span>' );
360 }
361
362 public static function filepath( $parser, $name='', $option='' ) {
363 $file = wfFindFile( $name );
364 if( $file ) {
365 $url = $file->getFullUrl();
366 if( $option == 'nowiki' ) {
367 return "<nowiki>$url</nowiki>";
368 }
369 return $url;
370 } else {
371 return '';
372 }
373 }
374
375 /**
376 * Parser function to extension tag adaptor
377 */
378 public static function tagObj( $parser, $frame, $args ) {
379 $xpath = false;
380 if ( !count( $args ) ) {
381 return '';
382 }
383 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
384
385 if ( count( $args ) ) {
386 $inner = $frame->expand( array_shift( $args ) );
387 } else {
388 $inner = null;
389 }
390
391 $stripList = $parser->getStripList();
392 if ( !in_array( $tagName, $stripList ) ) {
393 return '<span class="error">' .
394 wfMsg( 'unknown_extension_tag', $tagName ) .
395 '</span>';
396 }
397
398 $attributes = array();
399 foreach ( $args as $arg ) {
400 $bits = $arg->splitArg();
401 if ( strval( $bits['index'] ) === '' ) {
402 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
403 $value = trim( $frame->expand( $bits['value'] ) );
404 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
405 $value = isset( $m[1] ) ? $m[1] : '';
406 }
407 $attributes[$name] = $value;
408 }
409 }
410
411 $params = array(
412 'name' => $tagName,
413 'inner' => $inner,
414 'attributes' => $attributes,
415 'close' => "</$tagName>",
416 );
417 return $parser->extensionSubstitution( $params, $frame );
418 }
419 }