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