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