Merge "Add Burmese to list of languages with wider headings"
[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, files or subcats in the given category,
569 * or 0 if it's nonexistent. This is an expensive parser function and
570 * can't be called too many times per page.
571 * @return string
572 */
573 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
574 static $magicWords = null;
575 if ( is_null( $magicWords ) ) {
576 $magicWords = new MagicWordArray( array(
577 'pagesincategory_all',
578 'pagesincategory_pages',
579 'pagesincategory_subcats',
580 'pagesincategory_files'
581 ) );
582 }
583 static $cache = array();
584
585 // split the given option to its variable
586 if( self::isRaw( $arg1 ) ) {
587 //{{pagesincategory:|raw[|type]}}
588 $raw = $arg1;
589 $type = $magicWords->matchStartToEnd( $arg2 );
590 } else {
591 //{{pagesincategory:[|type[|raw]]}}
592 $type = $magicWords->matchStartToEnd( $arg1 );
593 $raw = $arg2;
594 }
595 if( !$type ) { //backward compatibility
596 $type = 'pagesincategory_all';
597 }
598
599 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
600 if( !$title ) { # invalid title
601 return self::formatRaw( 0, $raw );
602 }
603
604 // Normalize name for cache
605 $name = $title->getDBkey();
606
607 if( !isset( $cache[$name] ) ) {
608 $category = Category::newFromTitle( $title );
609
610 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
611 if( $parser->incrementExpensiveFunctionCount() ) {
612 // $allCount is the total number of cat members,
613 // not the count of how many members are normal pages.
614 $allCount = (int)$category->getPageCount();
615 $subcatCount = (int)$category->getSubcatCount();
616 $fileCount = (int)$category->getFileCount();
617 $pagesCount = $allCount - $subcatCount - $fileCount;
618 }
619 $cache[$name]['pagesincategory_all'] = $allCount;
620 $cache[$name]['pagesincategory_pages'] = $pagesCount;
621 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
622 $cache[$name]['pagesincategory_files'] = $fileCount;
623 }
624
625 $count = $cache[$name][$type];
626 return self::formatRaw( $count, $raw );
627 }
628
629 /**
630 * Return the size of the given page, or 0 if it's nonexistent. This is an
631 * expensive parser function and can't be called too many times per page.
632 *
633 * @todo FIXME: This doesn't work correctly on preview for getting the size
634 * of the current page.
635 * @todo FIXME: Title::getLength() documentation claims that it adds things
636 * to the link cache, so the local cache here should be unnecessary, but
637 * in fact calling getLength() repeatedly for the same $page does seem to
638 * run one query for each call?
639 * @todo Document parameters
640 *
641 * @param $parser Parser
642 * @param $page String TODO DOCUMENT (Default: empty string)
643 * @param $raw TODO DOCUMENT (Default: null)
644 * @return string
645 */
646 static function pagesize( $parser, $page = '', $raw = null ) {
647 static $cache = array();
648 $title = Title::newFromText( $page );
649
650 if( !is_object( $title ) ) {
651 $cache[$page] = 0;
652 return self::formatRaw( 0, $raw );
653 }
654
655 # Normalize name for cache
656 $page = $title->getPrefixedText();
657
658 $length = 0;
659 if( isset( $cache[$page] ) ) {
660 $length = $cache[$page];
661 } elseif( $parser->incrementExpensiveFunctionCount() ) {
662 $rev = Revision::newFromTitle( $title );
663 $id = $rev ? $rev->getPage() : 0;
664 $length = $cache[$page] = $rev ? $rev->getSize() : 0;
665
666 // Register dependency in templatelinks
667 $parser->mOutput->addTemplate( $title, $id, $rev ? $rev->getId() : 0 );
668 }
669 return self::formatRaw( $length, $raw );
670 }
671
672 /**
673 * Returns the requested protection level for the current page
674 * @return string
675 */
676 static function protectionlevel( $parser, $type = '' ) {
677 $restrictions = $parser->mTitle->getRestrictions( strtolower( $type ) );
678 # Title::getRestrictions returns an array, its possible it may have
679 # multiple values in the future
680 return implode( $restrictions, ',' );
681 }
682
683 /**
684 * Gives language names.
685 * @param $parser Parser
686 * @param $code String Language code (of which to get name)
687 * @param $inLanguage String Language code (in which to get name)
688 * @return String
689 */
690 static function language( $parser, $code = '', $inLanguage = '' ) {
691 $code = strtolower( $code );
692 $inLanguage = strtolower( $inLanguage );
693 $lang = Language::fetchLanguageName( $code, $inLanguage );
694 return $lang !== '' ? $lang : wfBCP47( $code );
695 }
696
697 /**
698 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
699 * @return string
700 */
701 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
702 $padding = $parser->killMarkers( $padding );
703 $lengthOfPadding = mb_strlen( $padding );
704 if ( $lengthOfPadding == 0 ) return $string;
705
706 # The remaining length to add counts down to 0 as padding is added
707 $length = min( $length, 500 ) - mb_strlen( $string );
708 # $finalPadding is just $padding repeated enough times so that
709 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
710 $finalPadding = '';
711 while ( $length > 0 ) {
712 # If $length < $lengthofPadding, truncate $padding so we get the
713 # exact length desired.
714 $finalPadding .= mb_substr( $padding, 0, $length );
715 $length -= $lengthOfPadding;
716 }
717
718 if ( $direction == STR_PAD_LEFT ) {
719 return $finalPadding . $string;
720 } else {
721 return $string . $finalPadding;
722 }
723 }
724
725 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
726 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
727 }
728
729 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
730 return self::pad( $parser, $string, $length, $padding );
731 }
732
733 /**
734 * @param $parser Parser
735 * @param $text
736 * @return string
737 */
738 static function anchorencode( $parser, $text ) {
739 $text = $parser->killMarkers( $text );
740 return substr( $parser->guessSectionNameFromWikiText( $text ), 1);
741 }
742
743 static function special( $parser, $text ) {
744 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
745 if ( $page ) {
746 $title = SpecialPage::getTitleFor( $page, $subpage );
747 return $title->getPrefixedText();
748 } else {
749 return wfMsgForContent( 'nosuchspecialpage' );
750 }
751 }
752
753 static function speciale( $parser, $text ) {
754 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
755 }
756
757 /**
758 * @param $parser Parser
759 * @param $text String The sortkey to use
760 * @param $uarg String Either "noreplace" or "noerror" (in en)
761 * both suppress errors, and noreplace does nothing if
762 * a default sortkey already exists.
763 * @return string
764 */
765 public static function defaultsort( $parser, $text, $uarg = '' ) {
766 static $magicWords = null;
767 if ( is_null( $magicWords ) ) {
768 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
769 }
770 $arg = $magicWords->matchStartToEnd( $uarg );
771
772 $text = trim( $text );
773 if( strlen( $text ) == 0 )
774 return '';
775 $old = $parser->getCustomDefaultSort();
776 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
777 $parser->setDefaultSort( $text );
778 }
779
780 if( $old === false || $old == $text || $arg ) {
781 return '';
782 } else {
783 return( '<span class="error">' .
784 wfMsgForContent( 'duplicate-defaultsort',
785 htmlspecialchars( $old ),
786 htmlspecialchars( $text ) ) .
787 '</span>' );
788 }
789 }
790
791 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
792 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
793 public static function filepath( $parser, $name='', $argA='', $argB='' ) {
794 $file = wfFindFile( $name );
795 $isNowiki = false;
796
797 if( $argA == 'nowiki' ) {
798 // {{filepath: | option [| size] }}
799 $isNowiki = true;
800 $parsedWidthParam = $parser->parseWidthParam( $argB );
801 } else {
802 // {{filepath: [| size [|option]] }}
803 $parsedWidthParam = $parser->parseWidthParam( $argA );
804 $isNowiki = ($argB == 'nowiki');
805 }
806
807 if ( $file ) {
808 $url = $file->getFullUrl();
809
810 // If a size is requested...
811 if ( count( $parsedWidthParam ) ) {
812 $mto = $file->transform( $parsedWidthParam );
813 // ... and we can
814 if ( $mto && !$mto->isError() ) {
815 // ... change the URL to point to a thumbnail.
816 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
817 }
818 }
819 if ( $isNowiki ) {
820 return array( $url, 'nowiki' => true );
821 }
822 return $url;
823 } else {
824 return '';
825 }
826 }
827
828 /**
829 * Parser function to extension tag adaptor
830 * @return string
831 */
832 public static function tagObj( $parser, $frame, $args ) {
833 if ( !count( $args ) ) {
834 return '';
835 }
836 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
837
838 if ( count( $args ) ) {
839 $inner = $frame->expand( array_shift( $args ) );
840 } else {
841 $inner = null;
842 }
843
844 $stripList = $parser->getStripList();
845 if ( !in_array( $tagName, $stripList ) ) {
846 return '<span class="error">' .
847 wfMsgForContent( 'unknown_extension_tag', $tagName ) .
848 '</span>';
849 }
850
851 $attributes = array();
852 foreach ( $args as $arg ) {
853 $bits = $arg->splitArg();
854 if ( strval( $bits['index'] ) === '' ) {
855 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
856 $value = trim( $frame->expand( $bits['value'] ) );
857 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
858 $value = isset( $m[1] ) ? $m[1] : '';
859 }
860 $attributes[$name] = $value;
861 }
862 }
863
864 $params = array(
865 'name' => $tagName,
866 'inner' => $inner,
867 'attributes' => $attributes,
868 'close' => "</$tagName>",
869 );
870 return $parser->extensionSubstitution( $params, $frame );
871 }
872 }