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