Fixed a few "strip tag exposed" bugs.
[lhc/web/wiklou.git] / includes / parser / CoreParserFunctions.php
1 <?php
2 /**
3 * Parser functions provided by MediaWiki core
4 *
5 * @file
6 */
7
8 /**
9 * Various core parser functions, registered in Parser::firstCallInit()
10 * @ingroup Parser
11 */
12 class CoreParserFunctions {
13 /**
14 * @param $parser Parser
15 * @return void
16 */
17 static function register( $parser ) {
18 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
19
20 # Syntax for arguments (see self::setFunctionHook):
21 # "name for lookup in localized magic words array",
22 # function callback,
23 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
24 # instead of {{#int:...}})
25
26 $parser->setFunctionHook( 'int', array( __CLASS__, 'intFunction' ), SFH_NO_HASH );
27 $parser->setFunctionHook( 'ns', array( __CLASS__, 'ns' ), SFH_NO_HASH );
28 $parser->setFunctionHook( 'nse', array( __CLASS__, 'nse' ), SFH_NO_HASH );
29 $parser->setFunctionHook( 'urlencode', array( __CLASS__, 'urlencode' ), SFH_NO_HASH );
30 $parser->setFunctionHook( 'lcfirst', array( __CLASS__, 'lcfirst' ), SFH_NO_HASH );
31 $parser->setFunctionHook( 'ucfirst', array( __CLASS__, 'ucfirst' ), SFH_NO_HASH );
32 $parser->setFunctionHook( 'lc', array( __CLASS__, 'lc' ), SFH_NO_HASH );
33 $parser->setFunctionHook( 'uc', array( __CLASS__, 'uc' ), SFH_NO_HASH );
34 $parser->setFunctionHook( 'localurl', array( __CLASS__, 'localurl' ), SFH_NO_HASH );
35 $parser->setFunctionHook( 'localurle', array( __CLASS__, 'localurle' ), SFH_NO_HASH );
36 $parser->setFunctionHook( 'fullurl', array( __CLASS__, 'fullurl' ), SFH_NO_HASH );
37 $parser->setFunctionHook( 'fullurle', array( __CLASS__, 'fullurle' ), SFH_NO_HASH );
38 $parser->setFunctionHook( 'canonicalurl', array( __CLASS__, 'canonicalurl' ), SFH_NO_HASH );
39 $parser->setFunctionHook( 'canonicalurle', array( __CLASS__, 'canonicalurle' ), SFH_NO_HASH );
40 $parser->setFunctionHook( 'formatnum', array( __CLASS__, 'formatnum' ), SFH_NO_HASH );
41 $parser->setFunctionHook( 'grammar', array( __CLASS__, 'grammar' ), SFH_NO_HASH );
42 $parser->setFunctionHook( 'gender', array( __CLASS__, 'gender' ), SFH_NO_HASH );
43 $parser->setFunctionHook( 'plural', array( __CLASS__, 'plural' ), SFH_NO_HASH );
44 $parser->setFunctionHook( 'numberofpages', array( __CLASS__, 'numberofpages' ), SFH_NO_HASH );
45 $parser->setFunctionHook( 'numberofusers', array( __CLASS__, 'numberofusers' ), SFH_NO_HASH );
46 $parser->setFunctionHook( 'numberofactiveusers', array( __CLASS__, 'numberofactiveusers' ), SFH_NO_HASH );
47 $parser->setFunctionHook( 'numberofarticles', array( __CLASS__, 'numberofarticles' ), SFH_NO_HASH );
48 $parser->setFunctionHook( 'numberoffiles', array( __CLASS__, 'numberoffiles' ), SFH_NO_HASH );
49 $parser->setFunctionHook( 'numberofadmins', array( __CLASS__, 'numberofadmins' ), SFH_NO_HASH );
50 $parser->setFunctionHook( 'numberingroup', array( __CLASS__, 'numberingroup' ), SFH_NO_HASH );
51 $parser->setFunctionHook( 'numberofedits', array( __CLASS__, 'numberofedits' ), SFH_NO_HASH );
52 $parser->setFunctionHook( 'numberofviews', array( __CLASS__, 'numberofviews' ), SFH_NO_HASH );
53 $parser->setFunctionHook( 'language', array( __CLASS__, 'language' ), SFH_NO_HASH );
54 $parser->setFunctionHook( 'padleft', array( __CLASS__, 'padleft' ), SFH_NO_HASH );
55 $parser->setFunctionHook( 'padright', array( __CLASS__, 'padright' ), SFH_NO_HASH );
56 $parser->setFunctionHook( 'anchorencode', array( __CLASS__, 'anchorencode' ), SFH_NO_HASH );
57 $parser->setFunctionHook( 'special', array( __CLASS__, 'special' ) );
58 $parser->setFunctionHook( 'defaultsort', array( __CLASS__, 'defaultsort' ), SFH_NO_HASH );
59 $parser->setFunctionHook( 'filepath', array( __CLASS__, 'filepath' ), SFH_NO_HASH );
60 $parser->setFunctionHook( 'pagesincategory', array( __CLASS__, 'pagesincategory' ), SFH_NO_HASH );
61 $parser->setFunctionHook( 'pagesize', array( __CLASS__, 'pagesize' ), SFH_NO_HASH );
62 $parser->setFunctionHook( 'protectionlevel', array( __CLASS__, 'protectionlevel' ), SFH_NO_HASH );
63 $parser->setFunctionHook( 'namespace', array( __CLASS__, 'mwnamespace' ), SFH_NO_HASH );
64 $parser->setFunctionHook( 'namespacee', array( __CLASS__, 'namespacee' ), SFH_NO_HASH );
65 $parser->setFunctionHook( 'talkspace', array( __CLASS__, 'talkspace' ), SFH_NO_HASH );
66 $parser->setFunctionHook( 'talkspacee', array( __CLASS__, 'talkspacee' ), SFH_NO_HASH );
67 $parser->setFunctionHook( 'subjectspace', array( __CLASS__, 'subjectspace' ), SFH_NO_HASH );
68 $parser->setFunctionHook( 'subjectspacee', array( __CLASS__, 'subjectspacee' ), SFH_NO_HASH );
69 $parser->setFunctionHook( 'pagename', array( __CLASS__, 'pagename' ), SFH_NO_HASH );
70 $parser->setFunctionHook( 'pagenamee', array( __CLASS__, 'pagenamee' ), SFH_NO_HASH );
71 $parser->setFunctionHook( 'fullpagename', array( __CLASS__, 'fullpagename' ), SFH_NO_HASH );
72 $parser->setFunctionHook( 'fullpagenamee', array( __CLASS__, 'fullpagenamee' ), SFH_NO_HASH );
73 $parser->setFunctionHook( 'basepagename', array( __CLASS__, 'basepagename' ), SFH_NO_HASH );
74 $parser->setFunctionHook( 'basepagenamee', array( __CLASS__, 'basepagenamee' ), SFH_NO_HASH );
75 $parser->setFunctionHook( 'subpagename', array( __CLASS__, 'subpagename' ), SFH_NO_HASH );
76 $parser->setFunctionHook( 'subpagenamee', array( __CLASS__, 'subpagenamee' ), SFH_NO_HASH );
77 $parser->setFunctionHook( 'talkpagename', array( __CLASS__, 'talkpagename' ), SFH_NO_HASH );
78 $parser->setFunctionHook( 'talkpagenamee', array( __CLASS__, 'talkpagenamee' ), SFH_NO_HASH );
79 $parser->setFunctionHook( 'subjectpagename', array( __CLASS__, 'subjectpagename' ), SFH_NO_HASH );
80 $parser->setFunctionHook( 'subjectpagenamee', array( __CLASS__, 'subjectpagenamee' ), SFH_NO_HASH );
81 $parser->setFunctionHook( 'tag', array( __CLASS__, 'tagObj' ), SFH_OBJECT_ARGS );
82 $parser->setFunctionHook( 'formatdate', array( __CLASS__, 'formatDate' ) );
83
84 if ( $wgAllowDisplayTitle ) {
85 $parser->setFunctionHook( 'displaytitle', array( __CLASS__, 'displaytitle' ), SFH_NO_HASH );
86 }
87 if ( $wgAllowSlowParserFunctions ) {
88 $parser->setFunctionHook( 'pagesinnamespace', array( __CLASS__, 'pagesinnamespace' ), SFH_NO_HASH );
89 }
90 }
91
92 /**
93 * @param $parser Parser
94 * @param string $part1
95 * @return array
96 */
97 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
98 if ( strval( $part1 ) !== '' ) {
99 $args = array_slice( func_get_args(), 2 );
100 $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
101 return array( $message, 'noparse' => false );
102 } else {
103 return array( 'found' => false );
104 }
105 }
106
107 /**
108 * @param $parser Parser
109 * @param $date
110 * @param null $defaultPref
111 * @return mixed|string
112 */
113 static function formatDate( $parser, $date, $defaultPref = null ) {
114 $df = DateFormatter::getInstance();
115
116 $date = trim( $date );
117
118 $pref = $parser->getOptions()->getDateFormat();
119
120 // Specify a different default date format other than the the normal default
121 // iff the user has 'default' for their setting
122 if ( $pref == 'default' && $defaultPref )
123 $pref = $defaultPref;
124
125 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
126 return $date;
127 }
128
129 static function ns( $parser, $part1 = '' ) {
130 global $wgContLang;
131 if ( intval( $part1 ) || $part1 == "0" ) {
132 $index = intval( $part1 );
133 } else {
134 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
135 }
136 if ( $index !== false ) {
137 return $wgContLang->getFormattedNsText( $index );
138 } else {
139 return array( 'found' => false );
140 }
141 }
142
143 static function nse( $parser, $part1 = '' ) {
144 return wfUrlencode( str_replace( ' ', '_', self::ns( $parser, $part1 ) ) );
145 }
146
147 /**
148 * urlencodes a string according to one of three patterns: (bug 22474)
149 *
150 * By default (for HTTP "query" strings), spaces are encoded as '+'.
151 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
152 * For links to "wiki"s, or similar software, spaces are encoded as '_',
153 *
154 * @param $parser Parser object
155 * @param $s String: The text to encode.
156 * @param $arg String (optional): The type of encoding.
157 * @return string
158 */
159 static function urlencode( $parser, $s = '', $arg = null ) {
160 static $magicWords = null;
161 if ( is_null( $magicWords ) ) {
162 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
163 }
164 switch( $magicWords->matchStartToEnd( $arg ) ) {
165
166 // Encode as though it's a wiki page, '_' for ' '.
167 case 'url_wiki':
168 $func = 'wfUrlencode';
169 $s = str_replace( ' ', '_', $s );
170 break;
171
172 // Encode for an HTTP Path, '%20' for ' '.
173 case 'url_path':
174 $func = 'rawurlencode';
175 break;
176
177 // Encode for HTTP query, '+' for ' '.
178 case 'url_query':
179 default:
180 $func = 'urlencode';
181 }
182 return $parser->markerSkipCallback( $s, $func );
183 }
184
185 static function lcfirst( $parser, $s = '' ) {
186 global $wgContLang;
187 return $wgContLang->lcfirst( $s );
188 }
189
190 static function ucfirst( $parser, $s = '' ) {
191 global $wgContLang;
192 return $wgContLang->ucfirst( $s );
193 }
194
195 /**
196 * @param $parser Parser
197 * @param string $s
198 * @return
199 */
200 static function lc( $parser, $s = '' ) {
201 global $wgContLang;
202 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
203 }
204
205 /**
206 * @param $parser Parser
207 * @param string $s
208 * @return
209 */
210 static function uc( $parser, $s = '' ) {
211 global $wgContLang;
212 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
213 }
214
215 static function localurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getLocalURL', $s, $arg ); }
216 static function localurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeLocalURL', $s, $arg ); }
217 static function fullurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getFullURL', $s, $arg ); }
218 static function fullurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeFullURL', $s, $arg ); }
219 static function canonicalurl( $parser, $s = '', $arg = null ) { return self::urlFunction( 'getCanonicalURL', $s, $arg ); }
220 static function canonicalurle( $parser, $s = '', $arg = null ) { return self::urlFunction( 'escapeCanonicalURL', $s, $arg ); }
221
222 static function urlFunction( $func, $s = '', $arg = null ) {
223 $title = Title::newFromText( $s );
224 # Due to order of execution of a lot of bits, the values might be encoded
225 # before arriving here; if that's true, then the title can't be created
226 # and the variable will fail. If we can't get a decent title from the first
227 # attempt, url-decode and try for a second.
228 if( is_null( $title ) )
229 $title = Title::newFromURL( urldecode( $s ) );
230 if( !is_null( $title ) ) {
231 # Convert NS_MEDIA -> NS_FILE
232 if( $title->getNamespace() == NS_MEDIA ) {
233 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
234 }
235 if( !is_null( $arg ) ) {
236 $text = $title->$func( $arg );
237 } else {
238 $text = $title->$func();
239 }
240 return $text;
241 } else {
242 return array( 'found' => false );
243 }
244 }
245
246 /**
247 * @param $parser Parser
248 * @param string $num
249 * @param null $raw
250 * @return
251 */
252 static function formatnum( $parser, $num = '', $raw = null) {
253 if ( self::isRaw( $raw ) ) {
254 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
255 } else {
256 $func = array( $parser->getFunctionLang(), 'formatNum' );
257 }
258 return $parser->markerSkipCallback( $num, $func );
259 }
260
261 /**
262 * @param $parser Parser
263 * @param string $case
264 * @param string $word
265 * @return
266 */
267 static function grammar( $parser, $case = '', $word = '' ) {
268 $word = $parser->killMarkers( $word );
269 return $parser->getFunctionLang()->convertGrammar( $word, $case );
270 }
271
272 /**
273 * @param $parser Parser
274 * @param $username string
275 * @return
276 */
277 static function gender( $parser, $username ) {
278 wfProfileIn( __METHOD__ );
279 $forms = array_slice( func_get_args(), 2 );
280
281 // Some shortcuts to avoid loading user data unnecessarily
282 if ( count( $forms ) === 0 ) {
283 wfProfileOut( __METHOD__ );
284 return '';
285 } elseif ( count( $forms ) === 1 ) {
286 wfProfileOut( __METHOD__ );
287 return $forms[0];
288 }
289
290 $username = trim( $username );
291
292 // default
293 $gender = User::getDefaultOption( 'gender' );
294
295 // allow prefix.
296 $title = Title::newFromText( $username );
297
298 if ( $title && $title->getNamespace() == NS_USER ) {
299 $username = $title->getText();
300 }
301
302 // check parameter, or use the ParserOptions if in interface message
303 $user = User::newFromName( $username );
304 if ( $user ) {
305 $gender = $user->getOption( 'gender' );
306 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
307 $gender = $parser->getOptions()->getUser()->getOption( 'gender' );
308 }
309 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
310 wfProfileOut( __METHOD__ );
311 return $ret;
312 }
313
314 /**
315 * @param $parser Parser
316 * @param string $text
317 * @return
318 */
319 static function plural( $parser, $text = '' ) {
320 $forms = array_slice( func_get_args(), 2 );
321 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
322 return $parser->getFunctionLang()->convertPlural( $text, $forms );
323 }
324
325 /**
326 * Override the title of the page when viewed, provided we've been given a
327 * title which will normalise to the canonical title
328 *
329 * @param $parser Parser: parent parser
330 * @param $text String: desired title text
331 * @return String
332 */
333 static function displaytitle( $parser, $text = '' ) {
334 global $wgRestrictDisplayTitle;
335
336 #parse a limited subset of wiki markup (just the single quote items)
337 $text = $parser->doQuotes( $text );
338
339 #remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
340 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
341 . preg_quote( Parser::MARKER_SUFFIX, '/' ) . '/', '', $text );
342
343 #list of disallowed tags for DISPLAYTITLE
344 #these will be escaped even though they are allowed in normal wiki text
345 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
346 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
347
348 #only requested titles that normalize to the actual title are allowed through
349 #if $wgRestrictDisplayTitle is true (it is by default)
350 #mimic the escaping process that occurs in OutputPage::setPageTitle
351 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $text, null, array(), array(), $bad ) );
352 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
353
354 if( !$wgRestrictDisplayTitle ) {
355 $parser->mOutput->setDisplayTitle( $text );
356 } else {
357 if ( $title instanceof Title && $title->getFragment() == '' && $title->equals( $parser->mTitle ) ) {
358 $parser->mOutput->setDisplayTitle( $text );
359 }
360 }
361
362 return '';
363 }
364
365 static function isRaw( $param ) {
366 static $mwRaw;
367 if ( !$mwRaw ) {
368 $mwRaw =& MagicWord::get( 'rawsuffix' );
369 }
370 if ( is_null( $param ) ) {
371 return false;
372 } else {
373 return $mwRaw->match( $param );
374 }
375 }
376
377 static function formatRaw( $num, $raw ) {
378 if( self::isRaw( $raw ) ) {
379 return $num;
380 } else {
381 global $wgContLang;
382 return $wgContLang->formatNum( $num );
383 }
384 }
385 static function numberofpages( $parser, $raw = null ) {
386 return self::formatRaw( SiteStats::pages(), $raw );
387 }
388 static function numberofusers( $parser, $raw = null ) {
389 return self::formatRaw( SiteStats::users(), $raw );
390 }
391 static function numberofactiveusers( $parser, $raw = null ) {
392 return self::formatRaw( SiteStats::activeUsers(), $raw );
393 }
394 static function numberofarticles( $parser, $raw = null ) {
395 return self::formatRaw( SiteStats::articles(), $raw );
396 }
397 static function numberoffiles( $parser, $raw = null ) {
398 return self::formatRaw( SiteStats::images(), $raw );
399 }
400 static function numberofadmins( $parser, $raw = null ) {
401 return self::formatRaw( SiteStats::numberingroup('sysop'), $raw );
402 }
403 static function numberofedits( $parser, $raw = null ) {
404 return self::formatRaw( SiteStats::edits(), $raw );
405 }
406 static function numberofviews( $parser, $raw = null ) {
407 return self::formatRaw( SiteStats::views(), $raw );
408 }
409 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
410 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
411 }
412 static function numberingroup( $parser, $name = '', $raw = null) {
413 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
414 }
415
416
417 /**
418 * Given a title, return the namespace name that would be given by the
419 * corresponding magic word
420 * Note: function name changed to "mwnamespace" rather than "namespace"
421 * to not break PHP 5.3
422 * @return mixed|string
423 */
424 static function mwnamespace( $parser, $title = null ) {
425 $t = Title::newFromText( $title );
426 if ( is_null( $t ) )
427 return '';
428 return str_replace( '_', ' ', $t->getNsText() );
429 }
430 static function namespacee( $parser, $title = null ) {
431 $t = Title::newFromText( $title );
432 if ( is_null( $t ) )
433 return '';
434 return wfUrlencode( $t->getNsText() );
435 }
436 static function talkspace( $parser, $title = null ) {
437 $t = Title::newFromText( $title );
438 if ( is_null( $t ) || !$t->canTalk() )
439 return '';
440 return str_replace( '_', ' ', $t->getTalkNsText() );
441 }
442 static function talkspacee( $parser, $title = null ) {
443 $t = Title::newFromText( $title );
444 if ( is_null( $t ) || !$t->canTalk() )
445 return '';
446 return wfUrlencode( $t->getTalkNsText() );
447 }
448 static function subjectspace( $parser, $title = null ) {
449 $t = Title::newFromText( $title );
450 if ( is_null( $t ) )
451 return '';
452 return str_replace( '_', ' ', $t->getSubjectNsText() );
453 }
454 static function subjectspacee( $parser, $title = null ) {
455 $t = Title::newFromText( $title );
456 if ( is_null( $t ) )
457 return '';
458 return wfUrlencode( $t->getSubjectNsText() );
459 }
460
461 /**
462 * Functions to get and normalize pagenames, corresponding to the magic words
463 * of the same names
464 * @return String
465 */
466 static function pagename( $parser, $title = null ) {
467 $t = Title::newFromText( $title );
468 if ( is_null( $t ) )
469 return '';
470 return wfEscapeWikiText( $t->getText() );
471 }
472 static function pagenamee( $parser, $title = null ) {
473 $t = Title::newFromText( $title );
474 if ( is_null( $t ) )
475 return '';
476 return wfEscapeWikiText( $t->getPartialURL() );
477 }
478 static function fullpagename( $parser, $title = null ) {
479 $t = Title::newFromText( $title );
480 if ( is_null( $t ) || !$t->canTalk() )
481 return '';
482 return wfEscapeWikiText( $t->getPrefixedText() );
483 }
484 static function fullpagenamee( $parser, $title = null ) {
485 $t = Title::newFromText( $title );
486 if ( is_null( $t ) || !$t->canTalk() )
487 return '';
488 return wfEscapeWikiText( $t->getPrefixedURL() );
489 }
490 static function subpagename( $parser, $title = null ) {
491 $t = Title::newFromText( $title );
492 if ( is_null( $t ) )
493 return '';
494 return wfEscapeWikiText( $t->getSubpageText() );
495 }
496 static function subpagenamee( $parser, $title = null ) {
497 $t = Title::newFromText( $title );
498 if ( is_null( $t ) )
499 return '';
500 return wfEscapeWikiText( $t->getSubpageUrlForm() );
501 }
502 static function basepagename( $parser, $title = null ) {
503 $t = Title::newFromText( $title );
504 if ( is_null( $t ) )
505 return '';
506 return wfEscapeWikiText( $t->getBaseText() );
507 }
508 static function basepagenamee( $parser, $title = null ) {
509 $t = Title::newFromText( $title );
510 if ( is_null( $t ) )
511 return '';
512 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
513 }
514 static function talkpagename( $parser, $title = null ) {
515 $t = Title::newFromText( $title );
516 if ( is_null( $t ) || !$t->canTalk() )
517 return '';
518 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
519 }
520 static function talkpagenamee( $parser, $title = null ) {
521 $t = Title::newFromText( $title );
522 if ( is_null( $t ) || !$t->canTalk() )
523 return '';
524 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedUrl() );
525 }
526 static function subjectpagename( $parser, $title = null ) {
527 $t = Title::newFromText( $title );
528 if ( is_null( $t ) )
529 return '';
530 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
531 }
532 static function subjectpagenamee( $parser, $title = null ) {
533 $t = Title::newFromText( $title );
534 if ( is_null( $t ) )
535 return '';
536 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedUrl() );
537 }
538
539 /**
540 * Return the number of pages in the given category, or 0 if it's nonexis-
541 * tent. This is an expensive parser function and can't be called too many
542 * times per page.
543 * @return string
544 */
545 static function pagesincategory( $parser, $name = '', $raw = null ) {
546 static $cache = array();
547 $category = Category::newFromName( $name );
548
549 if( !is_object( $category ) ) {
550 $cache[$name] = 0;
551 return self::formatRaw( 0, $raw );
552 }
553
554 # Normalize name for cache
555 $name = $category->getName();
556
557 $count = 0;
558 if( isset( $cache[$name] ) ) {
559 $count = $cache[$name];
560 } elseif( $parser->incrementExpensiveFunctionCount() ) {
561 $count = $cache[$name] = (int)$category->getPageCount();
562 }
563 return self::formatRaw( $count, $raw );
564 }
565
566 /**
567 * Return the size of the given page, or 0 if it's nonexistent. This is an
568 * expensive parser function and can't be called too many times per page.
569 *
570 * @todo FIXME: This doesn't work correctly on preview for getting the size
571 * of the current page.
572 * @todo FIXME: Title::getLength() documentation claims that it adds things
573 * to the link cache, so the local cache here should be unnecessary, but
574 * in fact calling getLength() repeatedly for the same $page does seem to
575 * run one query for each call?
576 * @todo Document parameters
577 *
578 * @param $parser Parser
579 * @param $page String TODO DOCUMENT (Default: empty string)
580 * @param $raw TODO DOCUMENT (Default: null)
581 * @return string
582 */
583 static function pagesize( $parser, $page = '', $raw = null ) {
584 static $cache = array();
585 $title = Title::newFromText( $page );
586
587 if( !is_object( $title ) ) {
588 $cache[$page] = 0;
589 return self::formatRaw( 0, $raw );
590 }
591
592 # Normalize name for cache
593 $page = $title->getPrefixedText();
594
595 $length = 0;
596 if( isset( $cache[$page] ) ) {
597 $length = $cache[$page];
598 } elseif( $parser->incrementExpensiveFunctionCount() ) {
599 $rev = Revision::newFromTitle( $title );
600 $id = $rev ? $rev->getPage() : 0;
601 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
602
603 // Register dependency in templatelinks
604 $parser->mOutput->addTemplate( $title, $id, $rev ? $rev->getId() : 0 );
605 }
606 return self::formatRaw( $length, $raw );
607 }
608
609 /**
610 * Returns the requested protection level for the current page
611 * @return string
612 */
613 static function protectionlevel( $parser, $type = '' ) {
614 $restrictions = $parser->mTitle->getRestrictions( strtolower( $type ) );
615 # Title::getRestrictions returns an array, its possible it may have
616 # multiple values in the future
617 return implode( $restrictions, ',' );
618 }
619
620 /**
621 * Gives language names.
622 * @param $parser Parser
623 * @param $code String Language code (of which to get name)
624 * @param $inLanguage String Language code (in which to get name)
625 * @return String
626 */
627 static function language( $parser, $code = '', $inLanguage = '' ) {
628 $code = strtolower( $code );
629 $inLanguage = strtolower( $inLanguage );
630 $lang = Language::fetchLanguageName( $code, $inLanguage );
631 return $lang !== '' ? $lang : wfBCP47( $code );
632 }
633
634 /**
635 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
636 * @return string
637 */
638 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
639 $padding = $parser->killMarkers( $padding );
640 $lengthOfPadding = mb_strlen( $padding );
641 if ( $lengthOfPadding == 0 ) return $string;
642
643 # The remaining length to add counts down to 0 as padding is added
644 $length = min( $length, 500 ) - mb_strlen( $string );
645 # $finalPadding is just $padding repeated enough times so that
646 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
647 $finalPadding = '';
648 while ( $length > 0 ) {
649 # If $length < $lengthofPadding, truncate $padding so we get the
650 # exact length desired.
651 $finalPadding .= mb_substr( $padding, 0, $length );
652 $length -= $lengthOfPadding;
653 }
654
655 if ( $direction == STR_PAD_LEFT ) {
656 return $finalPadding . $string;
657 } else {
658 return $string . $finalPadding;
659 }
660 }
661
662 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
663 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
664 }
665
666 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
667 return self::pad( $parser, $string, $length, $padding );
668 }
669
670 /**
671 * @param $parser Parser
672 * @param $text
673 * @return string
674 */
675 static function anchorencode( $parser, $text ) {
676 $text = $parser->killMarkers( $text );
677 return substr( $parser->guessSectionNameFromWikiText( $text ), 1);
678 }
679
680 static function special( $parser, $text ) {
681 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
682 if ( $page ) {
683 $title = SpecialPage::getTitleFor( $page, $subpage );
684 return $title;
685 } else {
686 return wfMsgForContent( 'nosuchspecialpage' );
687 }
688 }
689
690 /**
691 * @param $parser Parser
692 * @param $text String The sortkey to use
693 * @param $uarg String Either "noreplace" or "noerror" (in en)
694 * both suppress errors, and noreplace does nothing if
695 * a default sortkey already exists.
696 * @return string
697 */
698 public static function defaultsort( $parser, $text, $uarg = '' ) {
699 static $magicWords = null;
700 if ( is_null( $magicWords ) ) {
701 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
702 }
703 $arg = $magicWords->matchStartToEnd( $uarg );
704
705 $text = trim( $text );
706 if( strlen( $text ) == 0 )
707 return '';
708 $old = $parser->getCustomDefaultSort();
709 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
710 $parser->setDefaultSort( $text );
711 }
712
713 if( $old === false || $old == $text || $arg ) {
714 return '';
715 } else {
716 return( '<span class="error">' .
717 wfMsgForContent( 'duplicate-defaultsort',
718 htmlspecialchars( $old ),
719 htmlspecialchars( $text ) ) .
720 '</span>' );
721 }
722 }
723
724 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
725 public static function filepath( $parser, $name='', $argA='', $argB='' ) {
726 $file = wfFindFile( $name );
727 $size = '';
728 $argA_int = intval( $argA );
729 $argB_int = intval( $argB );
730
731 if ( $argB_int > 0 ) {
732 // {{filepath: | option | size }}
733 $size = $argB_int;
734 $option = $argA;
735
736 } elseif ( $argA_int > 0 ) {
737 // {{filepath: | size [|option] }}
738 $size = $argA_int;
739 $option = $argB;
740
741 } else {
742 // {{filepath: [|option] }}
743 $option = $argA;
744 }
745
746 if ( $file ) {
747 $url = $file->getFullUrl();
748
749 // If a size is requested...
750 if ( is_integer( $size ) ) {
751 $mto = $file->transform( array( 'width' => $size ) );
752 // ... and we can
753 if ( $mto && !$mto->isError() ) {
754 // ... change the URL to point to a thumbnail.
755 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
756 }
757 }
758 if ( $option == 'nowiki' ) {
759 return array( $url, 'nowiki' => true );
760 }
761 return $url;
762 } else {
763 return '';
764 }
765 }
766
767 /**
768 * Parser function to extension tag adaptor
769 * @return string
770 */
771 public static function tagObj( $parser, $frame, $args ) {
772 if ( !count( $args ) ) {
773 return '';
774 }
775 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
776
777 if ( count( $args ) ) {
778 $inner = $frame->expand( array_shift( $args ) );
779 } else {
780 $inner = null;
781 }
782
783 $stripList = $parser->getStripList();
784 if ( !in_array( $tagName, $stripList ) ) {
785 return '<span class="error">' .
786 wfMsgForContent( 'unknown_extension_tag', $tagName ) .
787 '</span>';
788 }
789
790 $attributes = array();
791 foreach ( $args as $arg ) {
792 $bits = $arg->splitArg();
793 if ( strval( $bits['index'] ) === '' ) {
794 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
795 $value = trim( $frame->expand( $bits['value'] ) );
796 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
797 $value = isset( $m[1] ) ? $m[1] : '';
798 }
799 $attributes[$name] = $value;
800 }
801 }
802
803 $params = array(
804 'name' => $tagName,
805 'inner' => $inner,
806 'attributes' => $attributes,
807 'close' => "</$tagName>",
808 );
809 return $parser->extensionSubstitution( $params, $frame );
810 }
811 }