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