Use consistent notation for "@todo FIXME". Should update http://svn.wikimedia.org...
[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 User
273 * @return
274 */
275 static function gender( $parser, $user ) {
276 wfProfileIn( __METHOD__ );
277 $forms = array_slice( func_get_args(), 2);
278
279 // default
280 $gender = User::getDefaultOption( 'gender' );
281
282 // allow prefix.
283 $title = Title::newFromText( $user );
284
285 if ( is_object( $title ) && $title->getNamespace() == NS_USER )
286 $user = $title->getText();
287
288 // check parameter, or use the ParserOptions if in interface message
289 $user = User::newFromName( $user );
290 if ( $user ) {
291 $gender = $user->getOption( 'gender' );
292 } elseif ( $parser->getOptions()->getInterfaceMessage() ) {
293 $gender = $parser->getOptions()->getUser()->getOption( 'gender' );
294 }
295 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
296 wfProfileOut( __METHOD__ );
297 return $ret;
298 }
299
300 /**
301 * @param $parser Parser
302 * @param string $text
303 * @return
304 */
305 static function plural( $parser, $text = '' ) {
306 $forms = array_slice( func_get_args(), 2 );
307 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
308 return $parser->getFunctionLang()->convertPlural( $text, $forms );
309 }
310
311 /**
312 * Override the title of the page when viewed, provided we've been given a
313 * title which will normalise to the canonical title
314 *
315 * @param $parser Parser: parent parser
316 * @param $text String: desired title text
317 * @return String
318 */
319 static function displaytitle( $parser, $text = '' ) {
320 global $wgRestrictDisplayTitle;
321
322 #parse a limited subset of wiki markup (just the single quote items)
323 $text = $parser->doQuotes( $text );
324
325 #remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
326 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
327 . preg_quote( Parser::MARKER_SUFFIX, '/' ) . '/', '', $text );
328
329 #list of disallowed tags for DISPLAYTITLE
330 #these will be escaped even though they are allowed in normal wiki text
331 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
332 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
333
334 #only requested titles that normalize to the actual title are allowed through
335 #if $wgRestrictDisplayTitle is true (it is by default)
336 #mimic the escaping process that occurs in OutputPage::setPageTitle
337 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $text, null, array(), array(), $bad ) );
338 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
339
340 if( !$wgRestrictDisplayTitle ) {
341 $parser->mOutput->setDisplayTitle( $text );
342 } else {
343 if ( $title instanceof Title && $title->getFragment() == '' && $title->equals( $parser->mTitle ) ) {
344 $parser->mOutput->setDisplayTitle( $text );
345 }
346 }
347
348 return '';
349 }
350
351 static function isRaw( $param ) {
352 static $mwRaw;
353 if ( !$mwRaw ) {
354 $mwRaw =& MagicWord::get( 'rawsuffix' );
355 }
356 if ( is_null( $param ) ) {
357 return false;
358 } else {
359 return $mwRaw->match( $param );
360 }
361 }
362
363 static function formatRaw( $num, $raw ) {
364 if( self::isRaw( $raw ) ) {
365 return $num;
366 } else {
367 global $wgContLang;
368 return $wgContLang->formatNum( $num );
369 }
370 }
371 static function numberofpages( $parser, $raw = null ) {
372 return self::formatRaw( SiteStats::pages(), $raw );
373 }
374 static function numberofusers( $parser, $raw = null ) {
375 return self::formatRaw( SiteStats::users(), $raw );
376 }
377 static function numberofactiveusers( $parser, $raw = null ) {
378 return self::formatRaw( SiteStats::activeUsers(), $raw );
379 }
380 static function numberofarticles( $parser, $raw = null ) {
381 return self::formatRaw( SiteStats::articles(), $raw );
382 }
383 static function numberoffiles( $parser, $raw = null ) {
384 return self::formatRaw( SiteStats::images(), $raw );
385 }
386 static function numberofadmins( $parser, $raw = null ) {
387 return self::formatRaw( SiteStats::numberingroup('sysop'), $raw );
388 }
389 static function numberofedits( $parser, $raw = null ) {
390 return self::formatRaw( SiteStats::edits(), $raw );
391 }
392 static function numberofviews( $parser, $raw = null ) {
393 return self::formatRaw( SiteStats::views(), $raw );
394 }
395 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
396 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
397 }
398 static function numberingroup( $parser, $name = '', $raw = null) {
399 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
400 }
401
402
403 /**
404 * Given a title, return the namespace name that would be given by the
405 * corresponding magic word
406 * Note: function name changed to "mwnamespace" rather than "namespace"
407 * to not break PHP 5.3
408 */
409 static function mwnamespace( $parser, $title = null ) {
410 $t = Title::newFromText( $title );
411 if ( is_null( $t ) )
412 return '';
413 return str_replace( '_', ' ', $t->getNsText() );
414 }
415 static function namespacee( $parser, $title = null ) {
416 $t = Title::newFromText( $title );
417 if ( is_null( $t ) )
418 return '';
419 return wfUrlencode( $t->getNsText() );
420 }
421 static function talkspace( $parser, $title = null ) {
422 $t = Title::newFromText( $title );
423 if ( is_null( $t ) || !$t->canTalk() )
424 return '';
425 return str_replace( '_', ' ', $t->getTalkNsText() );
426 }
427 static function talkspacee( $parser, $title = null ) {
428 $t = Title::newFromText( $title );
429 if ( is_null( $t ) || !$t->canTalk() )
430 return '';
431 return wfUrlencode( $t->getTalkNsText() );
432 }
433 static function subjectspace( $parser, $title = null ) {
434 $t = Title::newFromText( $title );
435 if ( is_null( $t ) )
436 return '';
437 return str_replace( '_', ' ', $t->getSubjectNsText() );
438 }
439 static function subjectspacee( $parser, $title = null ) {
440 $t = Title::newFromText( $title );
441 if ( is_null( $t ) )
442 return '';
443 return wfUrlencode( $t->getSubjectNsText() );
444 }
445 /*
446 * Functions to get and normalize pagenames, corresponding to the magic words
447 * of the same names
448 */
449 static function pagename( $parser, $title = null ) {
450 $t = Title::newFromText( $title );
451 if ( is_null( $t ) )
452 return '';
453 return wfEscapeWikiText( $t->getText() );
454 }
455 static function pagenamee( $parser, $title = null ) {
456 $t = Title::newFromText( $title );
457 if ( is_null( $t ) )
458 return '';
459 return wfEscapeWikiText( $t->getPartialURL() );
460 }
461 static function fullpagename( $parser, $title = null ) {
462 $t = Title::newFromText( $title );
463 if ( is_null( $t ) || !$t->canTalk() )
464 return '';
465 return wfEscapeWikiText( $t->getPrefixedText() );
466 }
467 static function fullpagenamee( $parser, $title = null ) {
468 $t = Title::newFromText( $title );
469 if ( is_null( $t ) || !$t->canTalk() )
470 return '';
471 return wfEscapeWikiText( $t->getPrefixedURL() );
472 }
473 static function subpagename( $parser, $title = null ) {
474 $t = Title::newFromText( $title );
475 if ( is_null( $t ) )
476 return '';
477 return wfEscapeWikiText( $t->getSubpageText() );
478 }
479 static function subpagenamee( $parser, $title = null ) {
480 $t = Title::newFromText( $title );
481 if ( is_null( $t ) )
482 return '';
483 return wfEscapeWikiText( $t->getSubpageUrlForm() );
484 }
485 static function basepagename( $parser, $title = null ) {
486 $t = Title::newFromText( $title );
487 if ( is_null( $t ) )
488 return '';
489 return wfEscapeWikiText( $t->getBaseText() );
490 }
491 static function basepagenamee( $parser, $title = null ) {
492 $t = Title::newFromText( $title );
493 if ( is_null( $t ) )
494 return '';
495 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
496 }
497 static function talkpagename( $parser, $title = null ) {
498 $t = Title::newFromText( $title );
499 if ( is_null( $t ) || !$t->canTalk() )
500 return '';
501 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
502 }
503 static function talkpagenamee( $parser, $title = null ) {
504 $t = Title::newFromText( $title );
505 if ( is_null( $t ) || !$t->canTalk() )
506 return '';
507 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedUrl() );
508 }
509 static function subjectpagename( $parser, $title = null ) {
510 $t = Title::newFromText( $title );
511 if ( is_null( $t ) )
512 return '';
513 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
514 }
515 static function subjectpagenamee( $parser, $title = null ) {
516 $t = Title::newFromText( $title );
517 if ( is_null( $t ) )
518 return '';
519 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedUrl() );
520 }
521
522 /**
523 * Return the number of pages in the given category, or 0 if it's nonexis-
524 * tent. This is an expensive parser function and can't be called too many
525 * times per page.
526 */
527 static function pagesincategory( $parser, $name = '', $raw = null ) {
528 static $cache = array();
529 $category = Category::newFromName( $name );
530
531 if( !is_object( $category ) ) {
532 $cache[$name] = 0;
533 return self::formatRaw( 0, $raw );
534 }
535
536 # Normalize name for cache
537 $name = $category->getName();
538
539 $count = 0;
540 if( isset( $cache[$name] ) ) {
541 $count = $cache[$name];
542 } elseif( $parser->incrementExpensiveFunctionCount() ) {
543 $count = $cache[$name] = (int)$category->getPageCount();
544 }
545 return self::formatRaw( $count, $raw );
546 }
547
548 /**
549 * Return the size of the given page, or 0 if it's nonexistent. This is an
550 * expensive parser function and can't be called too many times per page.
551 *
552 * @todo FIXME: This doesn't work correctly on preview for getting the size
553 * of the current page.
554 * @todo FIXME: Title::getLength() documentation claims that it adds things
555 * to the link cache, so the local cache here should be unnecessary, but
556 * in fact calling getLength() repeatedly for the same $page does seem to
557 * run one query for each call?
558 * @param $parser Parser
559 */
560 static function pagesize( $parser, $page = '', $raw = null ) {
561 static $cache = array();
562 $title = Title::newFromText( $page );
563
564 if( !is_object( $title ) ) {
565 $cache[$page] = 0;
566 return self::formatRaw( 0, $raw );
567 }
568
569 # Normalize name for cache
570 $page = $title->getPrefixedText();
571
572 $length = 0;
573 if( isset( $cache[$page] ) ) {
574 $length = $cache[$page];
575 } elseif( $parser->incrementExpensiveFunctionCount() ) {
576 $rev = Revision::newFromTitle( $title );
577 $id = $rev ? $rev->getPage() : 0;
578 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
579
580 // Register dependency in templatelinks
581 $parser->mOutput->addTemplate( $title, $id, $rev ? $rev->getId() : 0 );
582 }
583 return self::formatRaw( $length, $raw );
584 }
585
586 /**
587 * Returns the requested protection level for the current page
588 */
589 static function protectionlevel( $parser, $type = '' ) {
590 $restrictions = $parser->mTitle->getRestrictions( strtolower( $type ) );
591 # Title::getRestrictions returns an array, its possible it may have
592 # multiple values in the future
593 return implode( $restrictions, ',' );
594 }
595
596 static function language( $parser, $arg = '' ) {
597 global $wgContLang;
598 $lang = $wgContLang->getLanguageName( strtolower( $arg ) );
599 return $lang != '' ? $lang : $arg;
600 }
601
602 /**
603 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
604 */
605 static function pad( $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
606 $lengthOfPadding = mb_strlen( $padding );
607 if ( $lengthOfPadding == 0 ) return $string;
608
609 # The remaining length to add counts down to 0 as padding is added
610 $length = min( $length, 500 ) - mb_strlen( $string );
611 # $finalPadding is just $padding repeated enough times so that
612 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
613 $finalPadding = '';
614 while ( $length > 0 ) {
615 # If $length < $lengthofPadding, truncate $padding so we get the
616 # exact length desired.
617 $finalPadding .= mb_substr( $padding, 0, $length );
618 $length -= $lengthOfPadding;
619 }
620
621 if ( $direction == STR_PAD_LEFT ) {
622 return $finalPadding . $string;
623 } else {
624 return $string . $finalPadding;
625 }
626 }
627
628 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
629 return self::pad( $string, $length, $padding, STR_PAD_LEFT );
630 }
631
632 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
633 return self::pad( $string, $length, $padding );
634 }
635
636 /**
637 * @param $parser Parser
638 * @param $text
639 * @return string
640 */
641 static function anchorencode( $parser, $text ) {
642 return substr( $parser->guessSectionNameFromWikiText( $text ), 1);
643 }
644
645 static function special( $parser, $text ) {
646 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
647 if ( $page ) {
648 $title = SpecialPage::getTitleFor( $page, $subpage );
649 return $title;
650 } else {
651 return wfMsgForContent( 'nosuchspecialpage' );
652 }
653 }
654
655 /**
656 * @param $parser Parser
657 * @param $text
658 * @return string
659 */
660 public static function defaultsort( $parser, $text ) {
661 $text = trim( $text );
662 if( strlen( $text ) == 0 )
663 return '';
664 $old = $parser->getCustomDefaultSort();
665 $parser->setDefaultSort( $text );
666 if( $old === false || $old == $text )
667 return '';
668 else
669 return( '<span class="error">' .
670 wfMsgForContent( 'duplicate-defaultsort',
671 htmlspecialchars( $old ),
672 htmlspecialchars( $text ) ) .
673 '</span>' );
674 }
675
676 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
677 public static function filepath( $parser, $name='', $argA='', $argB='' ) {
678 $file = wfFindFile( $name );
679 $size = '';
680 $argA_int = intval( $argA );
681 $argB_int = intval( $argB );
682
683 if ( $argB_int > 0 ) {
684 // {{filepath: | option | size }}
685 $size = $argB_int;
686 $option = $argA;
687
688 } elseif ( $argA_int > 0 ) {
689 // {{filepath: | size [|option] }}
690 $size = $argA_int;
691 $option = $argB;
692
693 } else {
694 // {{filepath: [|option] }}
695 $option = $argA;
696 }
697
698 if ( $file ) {
699 $url = $file->getFullUrl();
700
701 // If a size is requested...
702 if ( is_integer( $size ) ) {
703 $mto = $file->transform( array( 'width' => $size ) );
704 // ... and we can
705 if ( $mto && !$mto->isError() ) {
706 // ... change the URL to point to a thumbnail.
707 $url = wfExpandUrl( $mto->getUrl() );
708 }
709 }
710 if ( $option == 'nowiki' ) {
711 return array( $url, 'nowiki' => true );
712 }
713 return $url;
714 } else {
715 return '';
716 }
717 }
718
719 /**
720 * Parser function to extension tag adaptor
721 */
722 public static function tagObj( $parser, $frame, $args ) {
723 if ( !count( $args ) ) {
724 return '';
725 }
726 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
727
728 if ( count( $args ) ) {
729 $inner = $frame->expand( array_shift( $args ) );
730 } else {
731 $inner = null;
732 }
733
734 $stripList = $parser->getStripList();
735 if ( !in_array( $tagName, $stripList ) ) {
736 return '<span class="error">' .
737 wfMsgForContent( 'unknown_extension_tag', $tagName ) .
738 '</span>';
739 }
740
741 $attributes = array();
742 foreach ( $args as $arg ) {
743 $bits = $arg->splitArg();
744 if ( strval( $bits['index'] ) === '' ) {
745 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
746 $value = trim( $frame->expand( $bits['value'] ) );
747 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
748 $value = isset( $m[1] ) ? $m[1] : '';
749 }
750 $attributes[$name] = $value;
751 }
752 }
753
754 $params = array(
755 'name' => $tagName,
756 'inner' => $inner,
757 'attributes' => $attributes,
758 'close' => "</$tagName>",
759 );
760 return $parser->extensionSubstitution( $params, $frame );
761 }
762 }