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