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