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