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