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