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