Fixed spacing
[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 #only requested titles that normalize to the actual title are allowed through
379 #if $wgRestrictDisplayTitle is true (it is by default)
380 #mimic the escaping process that occurs in OutputPage::setPageTitle
381 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $text, null, array(), array(), $bad ) );
382 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
383
384 if ( !$wgRestrictDisplayTitle ) {
385 $parser->mOutput->setDisplayTitle( $text );
386 } elseif ( $title instanceof Title && $title->getFragment() == '' && $title->equals( $parser->mTitle ) ) {
387 $parser->mOutput->setDisplayTitle( $text );
388 }
389
390 return '';
391 }
392
393 /**
394 * Matches the given value against the value of given magic word
395 *
396 * @param string $magicword magic word key
397 * @param mixed $value value to match
398 * @return boolean true on successful match
399 */
400 static private function matchAgainstMagicword( $magicword, $value ) {
401 if ( strval( $value ) === '' ) {
402 return false;
403 }
404 $mwObject = MagicWord::get( $magicword );
405 return $mwObject->match( $value );
406 }
407
408 static function formatRaw( $num, $raw ) {
409 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
410 return $num;
411 } else {
412 global $wgContLang;
413 return $wgContLang->formatNum( $num );
414 }
415 }
416 static function numberofpages( $parser, $raw = null ) {
417 return self::formatRaw( SiteStats::pages(), $raw );
418 }
419 static function numberofusers( $parser, $raw = null ) {
420 return self::formatRaw( SiteStats::users(), $raw );
421 }
422 static function numberofactiveusers( $parser, $raw = null ) {
423 return self::formatRaw( SiteStats::activeUsers(), $raw );
424 }
425 static function numberofarticles( $parser, $raw = null ) {
426 return self::formatRaw( SiteStats::articles(), $raw );
427 }
428 static function numberoffiles( $parser, $raw = null ) {
429 return self::formatRaw( SiteStats::images(), $raw );
430 }
431 static function numberofadmins( $parser, $raw = null ) {
432 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
433 }
434 static function numberofedits( $parser, $raw = null ) {
435 return self::formatRaw( SiteStats::edits(), $raw );
436 }
437 static function numberofviews( $parser, $raw = null ) {
438 return self::formatRaw( SiteStats::views(), $raw );
439 }
440 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
441 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
442 }
443 static function numberingroup( $parser, $name = '', $raw = null ) {
444 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
445 }
446
447 /**
448 * Given a title, return the namespace name that would be given by the
449 * corresponding magic word
450 * Note: function name changed to "mwnamespace" rather than "namespace"
451 * to not break PHP 5.3
452 * @return mixed|string
453 */
454 static function mwnamespace( $parser, $title = null ) {
455 $t = Title::newFromText( $title );
456 if ( is_null( $t ) ) {
457 return '';
458 }
459 return str_replace( '_', ' ', $t->getNsText() );
460 }
461 static function namespacee( $parser, $title = null ) {
462 $t = Title::newFromText( $title );
463 if ( is_null( $t ) ) {
464 return '';
465 }
466 return wfUrlencode( $t->getNsText() );
467 }
468 static function namespacenumber( $parser, $title = null ) {
469 $t = Title::newFromText( $title );
470 if ( is_null( $t ) ) {
471 return '';
472 }
473 return $t->getNamespace();
474 }
475 static function talkspace( $parser, $title = null ) {
476 $t = Title::newFromText( $title );
477 if ( is_null( $t ) || !$t->canTalk() ) {
478 return '';
479 }
480 return str_replace( '_', ' ', $t->getTalkNsText() );
481 }
482 static function talkspacee( $parser, $title = null ) {
483 $t = Title::newFromText( $title );
484 if ( is_null( $t ) || !$t->canTalk() ) {
485 return '';
486 }
487 return wfUrlencode( $t->getTalkNsText() );
488 }
489 static function subjectspace( $parser, $title = null ) {
490 $t = Title::newFromText( $title );
491 if ( is_null( $t ) ) {
492 return '';
493 }
494 return str_replace( '_', ' ', $t->getSubjectNsText() );
495 }
496 static function subjectspacee( $parser, $title = null ) {
497 $t = Title::newFromText( $title );
498 if ( is_null( $t ) ) {
499 return '';
500 }
501 return wfUrlencode( $t->getSubjectNsText() );
502 }
503
504 /**
505 * Functions to get and normalize pagenames, corresponding to the magic words
506 * of the same names
507 * @return String
508 */
509 static function pagename( $parser, $title = null ) {
510 $t = Title::newFromText( $title );
511 if ( is_null( $t ) ) {
512 return '';
513 }
514 return wfEscapeWikiText( $t->getText() );
515 }
516 static function pagenamee( $parser, $title = null ) {
517 $t = Title::newFromText( $title );
518 if ( is_null( $t ) ) {
519 return '';
520 }
521 return wfEscapeWikiText( $t->getPartialURL() );
522 }
523 static function fullpagename( $parser, $title = null ) {
524 $t = Title::newFromText( $title );
525 if ( is_null( $t ) || !$t->canTalk() ) {
526 return '';
527 }
528 return wfEscapeWikiText( $t->getPrefixedText() );
529 }
530 static function fullpagenamee( $parser, $title = null ) {
531 $t = Title::newFromText( $title );
532 if ( is_null( $t ) || !$t->canTalk() ) {
533 return '';
534 }
535 return wfEscapeWikiText( $t->getPrefixedURL() );
536 }
537 static function subpagename( $parser, $title = null ) {
538 $t = Title::newFromText( $title );
539 if ( is_null( $t ) ) {
540 return '';
541 }
542 return wfEscapeWikiText( $t->getSubpageText() );
543 }
544 static function subpagenamee( $parser, $title = null ) {
545 $t = Title::newFromText( $title );
546 if ( is_null( $t ) ) {
547 return '';
548 }
549 return wfEscapeWikiText( $t->getSubpageUrlForm() );
550 }
551 static function rootpagename( $parser, $title = null ) {
552 $t = Title::newFromText( $title );
553 if ( is_null( $t ) ) {
554 return '';
555 }
556 return wfEscapeWikiText( $t->getRootText() );
557 }
558 static function rootpagenamee( $parser, $title = null ) {
559 $t = Title::newFromText( $title );
560 if ( is_null( $t ) ) {
561 return '';
562 }
563 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
564 }
565 static function basepagename( $parser, $title = null ) {
566 $t = Title::newFromText( $title );
567 if ( is_null( $t ) ) {
568 return '';
569 }
570 return wfEscapeWikiText( $t->getBaseText() );
571 }
572 static function basepagenamee( $parser, $title = null ) {
573 $t = Title::newFromText( $title );
574 if ( is_null( $t ) ) {
575 return '';
576 }
577 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
578 }
579 static function talkpagename( $parser, $title = null ) {
580 $t = Title::newFromText( $title );
581 if ( is_null( $t ) || !$t->canTalk() ) {
582 return '';
583 }
584 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
585 }
586 static function talkpagenamee( $parser, $title = null ) {
587 $t = Title::newFromText( $title );
588 if ( is_null( $t ) || !$t->canTalk() ) {
589 return '';
590 }
591 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
592 }
593 static function subjectpagename( $parser, $title = null ) {
594 $t = Title::newFromText( $title );
595 if ( is_null( $t ) ) {
596 return '';
597 }
598 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
599 }
600 static function subjectpagenamee( $parser, $title = null ) {
601 $t = Title::newFromText( $title );
602 if ( is_null( $t ) ) {
603 return '';
604 }
605 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
606 }
607
608 /**
609 * Return the number of pages, files or subcats in the given category,
610 * or 0 if it's nonexistent. This is an expensive parser function and
611 * can't be called too many times per page.
612 * @return string
613 */
614 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
615 static $magicWords = null;
616 if ( is_null( $magicWords ) ) {
617 $magicWords = new MagicWordArray( array(
618 'pagesincategory_all',
619 'pagesincategory_pages',
620 'pagesincategory_subcats',
621 'pagesincategory_files'
622 ) );
623 }
624 static $cache = array();
625
626 // split the given option to its variable
627 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
628 //{{pagesincategory:|raw[|type]}}
629 $raw = $arg1;
630 $type = $magicWords->matchStartToEnd( $arg2 );
631 } else {
632 //{{pagesincategory:[|type[|raw]]}}
633 $type = $magicWords->matchStartToEnd( $arg1 );
634 $raw = $arg2;
635 }
636 if ( !$type ) { //backward compatibility
637 $type = 'pagesincategory_all';
638 }
639
640 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
641 if ( !$title ) { # invalid title
642 return self::formatRaw( 0, $raw );
643 }
644
645 // Normalize name for cache
646 $name = $title->getDBkey();
647
648 if ( !isset( $cache[$name] ) ) {
649 $category = Category::newFromTitle( $title );
650
651 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
652 if ( $parser->incrementExpensiveFunctionCount() ) {
653 // $allCount is the total number of cat members,
654 // not the count of how many members are normal pages.
655 $allCount = (int)$category->getPageCount();
656 $subcatCount = (int)$category->getSubcatCount();
657 $fileCount = (int)$category->getFileCount();
658 $pagesCount = $allCount - $subcatCount - $fileCount;
659 }
660 $cache[$name]['pagesincategory_all'] = $allCount;
661 $cache[$name]['pagesincategory_pages'] = $pagesCount;
662 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
663 $cache[$name]['pagesincategory_files'] = $fileCount;
664 }
665
666 $count = $cache[$name][$type];
667 return self::formatRaw( $count, $raw );
668 }
669
670 /**
671 * Return the size of the given page, or 0 if it's nonexistent. This is an
672 * expensive parser function and can't be called too many times per page.
673 *
674 * @todo FIXME: Title::getLength() documentation claims that it adds things
675 * to the link cache, so the local cache here should be unnecessary, but
676 * in fact calling getLength() repeatedly for the same $page does seem to
677 * run one query for each call?
678 * @todo Document parameters
679 *
680 * @param $parser Parser
681 * @param $page String Name of page to check (Default: empty string)
682 * @param $raw String Should number be human readable with commas or just number
683 * @return string
684 */
685 static function pagesize( $parser, $page = '', $raw = null ) {
686 static $cache = array();
687 $title = Title::newFromText( $page );
688
689 if ( !is_object( $title ) ) {
690 $cache[$page] = 0;
691 return self::formatRaw( 0, $raw );
692 }
693
694 # Normalize name for cache
695 $page = $title->getPrefixedText();
696
697 $length = 0;
698 if ( $title->equals( $parser->getTitle() )
699 && $parser->mInputSize !== false
700 ) {
701 # We are on current page (and not in PST), so
702 # take length of input to parser.
703 $length = $parser->mInputSize;
704 } elseif ( isset( $cache[$page] ) ) {
705 $length = $cache[$page];
706 } elseif ( $parser->incrementExpensiveFunctionCount() ) {
707 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
708 $pageID = $rev ? $rev->getPage() : 0;
709 $revID = $rev ? $rev->getId() : 0;
710 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
711
712 // Register dependency in templatelinks
713 $parser->mOutput->addTemplate( $title, $pageID, $revID );
714 }
715 return self::formatRaw( $length, $raw );
716 }
717
718 /**
719 * Returns the requested protection level for the current page
720 *
721 * @param Parser $parser
722 * @param string $type
723 * @param string $title
724 *
725 * @return string
726 */
727 static function protectionlevel( $parser, $type = '', $title = '' ) {
728 $titleObject = Title::newFromText( $title );
729 if ( !( $titleObject instanceof Title ) ) {
730 $titleObject = $parser->mTitle;
731 }
732 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
733 # Title::getRestrictions returns an array, its possible it may have
734 # multiple values in the future
735 return implode( $restrictions, ',' );
736 }
737
738 /**
739 * Gives language names.
740 * @param $parser Parser
741 * @param string $code Language code (of which to get name)
742 * @param string $inLanguage Language code (in which to get name)
743 * @return String
744 */
745 static function language( $parser, $code = '', $inLanguage = '' ) {
746 $code = strtolower( $code );
747 $inLanguage = strtolower( $inLanguage );
748 $lang = Language::fetchLanguageName( $code, $inLanguage );
749 return $lang !== '' ? $lang : wfBCP47( $code );
750 }
751
752 /**
753 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
754 * @return string
755 */
756 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
757 $padding = $parser->killMarkers( $padding );
758 $lengthOfPadding = mb_strlen( $padding );
759 if ( $lengthOfPadding == 0 ) {
760 return $string;
761 }
762
763 # The remaining length to add counts down to 0 as padding is added
764 $length = min( $length, 500 ) - mb_strlen( $string );
765 # $finalPadding is just $padding repeated enough times so that
766 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
767 $finalPadding = '';
768 while ( $length > 0 ) {
769 # If $length < $lengthofPadding, truncate $padding so we get the
770 # exact length desired.
771 $finalPadding .= mb_substr( $padding, 0, $length );
772 $length -= $lengthOfPadding;
773 }
774
775 if ( $direction == STR_PAD_LEFT ) {
776 return $finalPadding . $string;
777 } else {
778 return $string . $finalPadding;
779 }
780 }
781
782 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
783 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
784 }
785
786 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
787 return self::pad( $parser, $string, $length, $padding );
788 }
789
790 /**
791 * @param $parser Parser
792 * @param $text
793 * @return string
794 */
795 static function anchorencode( $parser, $text ) {
796 $text = $parser->killMarkers( $text );
797 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
798 }
799
800 static function special( $parser, $text ) {
801 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
802 if ( $page ) {
803 $title = SpecialPage::getTitleFor( $page, $subpage );
804 return $title->getPrefixedText();
805 } else {
806 return wfMessage( 'nosuchspecialpage' )->inContentLanguage()->text();
807 }
808 }
809
810 static function speciale( $parser, $text ) {
811 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
812 }
813
814 /**
815 * @param $parser Parser
816 * @param string $text The sortkey to use
817 * @param string $uarg Either "noreplace" or "noerror" (in en)
818 * both suppress errors, and noreplace does nothing if
819 * a default sortkey already exists.
820 * @return string
821 */
822 public static function defaultsort( $parser, $text, $uarg = '' ) {
823 static $magicWords = null;
824 if ( is_null( $magicWords ) ) {
825 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
826 }
827 $arg = $magicWords->matchStartToEnd( $uarg );
828
829 $text = trim( $text );
830 if ( strlen( $text ) == 0 ) {
831 return '';
832 }
833 $old = $parser->getCustomDefaultSort();
834 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
835 $parser->setDefaultSort( $text );
836 }
837
838 if ( $old === false || $old == $text || $arg ) {
839 return '';
840 } else {
841 return '<span class="error">' .
842 wfMessage( 'duplicate-defaultsort', $old, $text )->inContentLanguage()->escaped() .
843 '</span>';
844 }
845 }
846
847 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
848 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
849 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
850 $file = wfFindFile( $name );
851
852 if ( $argA == 'nowiki' ) {
853 // {{filepath: | option [| size] }}
854 $isNowiki = true;
855 $parsedWidthParam = $parser->parseWidthParam( $argB );
856 } else {
857 // {{filepath: [| size [|option]] }}
858 $parsedWidthParam = $parser->parseWidthParam( $argA );
859 $isNowiki = ( $argB == 'nowiki' );
860 }
861
862 if ( $file ) {
863 $url = $file->getFullUrl();
864
865 // If a size is requested...
866 if ( count( $parsedWidthParam ) ) {
867 $mto = $file->transform( $parsedWidthParam );
868 // ... and we can
869 if ( $mto && !$mto->isError() ) {
870 // ... change the URL to point to a thumbnail.
871 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
872 }
873 }
874 if ( $isNowiki ) {
875 return array( $url, 'nowiki' => true );
876 }
877 return $url;
878 } else {
879 return '';
880 }
881 }
882
883 /**
884 * Parser function to extension tag adaptor
885 * @return string
886 */
887 public static function tagObj( $parser, $frame, $args ) {
888 if ( !count( $args ) ) {
889 return '';
890 }
891 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
892
893 if ( count( $args ) ) {
894 $inner = $frame->expand( array_shift( $args ) );
895 } else {
896 $inner = null;
897 }
898
899 $stripList = $parser->getStripList();
900 if ( !in_array( $tagName, $stripList ) ) {
901 return '<span class="error">' .
902 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
903 '</span>';
904 }
905
906 $attributes = array();
907 foreach ( $args as $arg ) {
908 $bits = $arg->splitArg();
909 if ( strval( $bits['index'] ) === '' ) {
910 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
911 $value = trim( $frame->expand( $bits['value'] ) );
912 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
913 $value = isset( $m[1] ) ? $m[1] : '';
914 }
915 $attributes[$name] = $value;
916 }
917 }
918
919 $params = array(
920 'name' => $tagName,
921 'inner' => $inner,
922 'attributes' => $attributes,
923 'close' => "</$tagName>",
924 );
925 return $parser->extensionSubstitution( $params, $frame );
926 }
927 }