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