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