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