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