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