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