Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / parser / CoreParserFunctions.php
blob2b495b1411487247df3b57890c3e9c39080975a7
1 <?php
2 /**
3 * Parser functions provided by MediaWiki core
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.
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.
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
20 * @file
21 * @ingroup Parser
24 /**
25 * Various core parser functions, registered in Parser::firstCallInit()
26 * @ingroup Parser
28 class CoreParserFunctions {
29 /**
30 * @param Parser $parser
31 * @return void
33 public static function register( $parser ) {
34 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36 # Syntax for arguments (see Parser::setFunctionHook):
37 # "name for lookup in localized magic words array",
38 # function callback,
39 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
40 # instead of {{#int:...}})
41 $noHashFunctions = array(
42 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
43 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
44 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural',
45 'numberofpages', 'numberofusers', 'numberofactiveusers',
46 'numberofarticles', 'numberoffiles', 'numberofadmins',
47 'numberingroup', 'numberofedits', 'language',
48 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
49 'pagesincategory', 'pagesize', 'protectionlevel',
50 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
51 'subjectspace', 'subjectspacee', 'pagename', 'pagenamee',
52 'fullpagename', 'fullpagenamee', 'rootpagename', 'rootpagenamee',
53 'basepagename', 'basepagenamee', 'subpagename', 'subpagenamee',
54 'talkpagename', 'talkpagenamee', 'subjectpagename',
55 'subjectpagenamee', 'pageid', 'revisionid', 'revisionday',
56 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
57 'revisiontimestamp', 'revisionuser', 'cascadingsources',
59 foreach ( $noHashFunctions as $func ) {
60 $parser->setFunctionHook( $func, array( __CLASS__, $func ), Parser::SFH_NO_HASH );
63 $parser->setFunctionHook( 'namespace', array( __CLASS__, 'mwnamespace' ), Parser::SFH_NO_HASH );
64 $parser->setFunctionHook( 'int', array( __CLASS__, 'intFunction' ), Parser::SFH_NO_HASH );
65 $parser->setFunctionHook( 'special', array( __CLASS__, 'special' ) );
66 $parser->setFunctionHook( 'speciale', array( __CLASS__, 'speciale' ) );
67 $parser->setFunctionHook( 'tag', array( __CLASS__, 'tagObj' ), Parser::SFH_OBJECT_ARGS );
68 $parser->setFunctionHook( 'formatdate', array( __CLASS__, 'formatDate' ) );
70 if ( $wgAllowDisplayTitle ) {
71 $parser->setFunctionHook( 'displaytitle', array( __CLASS__, 'displaytitle' ), Parser::SFH_NO_HASH );
73 if ( $wgAllowSlowParserFunctions ) {
74 $parser->setFunctionHook(
75 'pagesinnamespace',
76 array( __CLASS__, 'pagesinnamespace' ),
77 Parser::SFH_NO_HASH
82 /**
83 * @param Parser $parser
84 * @param string $part1
85 * @return array
87 public static function intFunction( $parser, $part1 = '' /*, ... */ ) {
88 if ( strval( $part1 ) !== '' ) {
89 $args = array_slice( func_get_args(), 2 );
90 $message = wfMessage( $part1, $args )
91 ->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
93 return array( $message, 'noparse' => false );
94 } else {
95 return array( 'found' => false );
99 /**
100 * @param Parser $parser
101 * @param string $date
102 * @param string $defaultPref
104 * @return string
106 public static function formatDate( $parser, $date, $defaultPref = null ) {
107 $lang = $parser->getFunctionLang();
108 $df = DateFormatter::getInstance( $lang );
110 $date = trim( $date );
112 $pref = $parser->getOptions()->getDateFormat();
114 // Specify a different default date format other than the normal default
115 // if the user has 'default' for their setting
116 if ( $pref == 'default' && $defaultPref ) {
117 $pref = $defaultPref;
120 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
121 return $date;
124 public static function ns( $parser, $part1 = '' ) {
125 global $wgContLang;
126 if ( intval( $part1 ) || $part1 == "0" ) {
127 $index = intval( $part1 );
128 } else {
129 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
131 if ( $index !== false ) {
132 return $wgContLang->getFormattedNsText( $index );
133 } else {
134 return array( 'found' => false );
138 public static function nse( $parser, $part1 = '' ) {
139 $ret = self::ns( $parser, $part1 );
140 if ( is_string( $ret ) ) {
141 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
143 return $ret;
147 * urlencodes a string according to one of three patterns: (bug 22474)
149 * By default (for HTTP "query" strings), spaces are encoded as '+'.
150 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
151 * For links to "wiki"s, or similar software, spaces are encoded as '_',
153 * @param Parser $parser
154 * @param string $s The text to encode.
155 * @param string $arg (optional): The type of encoding.
156 * @return string
158 public static function urlencode( $parser, $s = '', $arg = null ) {
159 static $magicWords = null;
160 if ( is_null( $magicWords ) ) {
161 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
163 switch ( $magicWords->matchStartToEnd( $arg ) ) {
165 // Encode as though it's a wiki page, '_' for ' '.
166 case 'url_wiki':
167 $func = 'wfUrlencode';
168 $s = str_replace( ' ', '_', $s );
169 break;
171 // Encode for an HTTP Path, '%20' for ' '.
172 case 'url_path':
173 $func = 'rawurlencode';
174 break;
176 // Encode for HTTP query, '+' for ' '.
177 case 'url_query':
178 default:
179 $func = 'urlencode';
181 return $parser->markerSkipCallback( $s, $func );
184 public static function lcfirst( $parser, $s = '' ) {
185 global $wgContLang;
186 return $wgContLang->lcfirst( $s );
189 public static function ucfirst( $parser, $s = '' ) {
190 global $wgContLang;
191 return $wgContLang->ucfirst( $s );
195 * @param Parser $parser
196 * @param string $s
197 * @return string
199 public static function lc( $parser, $s = '' ) {
200 global $wgContLang;
201 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
205 * @param Parser $parser
206 * @param string $s
207 * @return string
209 public static function uc( $parser, $s = '' ) {
210 global $wgContLang;
211 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
214 public static function localurl( $parser, $s = '', $arg = null ) {
215 return self::urlFunction( 'getLocalURL', $s, $arg );
218 public static function localurle( $parser, $s = '', $arg = null ) {
219 $temp = self::urlFunction( 'getLocalURL', $s, $arg );
220 if ( !is_string( $temp ) ) {
221 return $temp;
222 } else {
223 return htmlspecialchars( $temp );
227 public static function fullurl( $parser, $s = '', $arg = null ) {
228 return self::urlFunction( 'getFullURL', $s, $arg );
231 public static function fullurle( $parser, $s = '', $arg = null ) {
232 $temp = self::urlFunction( 'getFullURL', $s, $arg );
233 if ( !is_string( $temp ) ) {
234 return $temp;
235 } else {
236 return htmlspecialchars( $temp );
240 public static function canonicalurl( $parser, $s = '', $arg = null ) {
241 return self::urlFunction( 'getCanonicalURL', $s, $arg );
244 public static function canonicalurle( $parser, $s = '', $arg = null ) {
245 $temp = self::urlFunction( 'getCanonicalURL', $s, $arg );
246 if ( !is_string( $temp ) ) {
247 return $temp;
248 } else {
249 return htmlspecialchars( $temp );
253 public static function urlFunction( $func, $s = '', $arg = null ) {
254 $title = Title::newFromText( $s );
255 # Due to order of execution of a lot of bits, the values might be encoded
256 # before arriving here; if that's true, then the title can't be created
257 # and the variable will fail. If we can't get a decent title from the first
258 # attempt, url-decode and try for a second.
259 if ( is_null( $title ) ) {
260 $title = Title::newFromURL( urldecode( $s ) );
262 if ( !is_null( $title ) ) {
263 # Convert NS_MEDIA -> NS_FILE
264 if ( $title->getNamespace() == NS_MEDIA ) {
265 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
267 if ( !is_null( $arg ) ) {
268 $text = $title->$func( $arg );
269 } else {
270 $text = $title->$func();
272 return $text;
273 } else {
274 return array( 'found' => false );
279 * @param Parser $parser
280 * @param string $num
281 * @param string $arg
282 * @return string
284 public static function formatnum( $parser, $num = '', $arg = null ) {
285 if ( self::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
286 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
287 } elseif ( self::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
288 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
289 } else {
290 $func = array( $parser->getFunctionLang(), 'formatNum' );
292 return $parser->markerSkipCallback( $num, $func );
296 * @param Parser $parser
297 * @param string $case
298 * @param string $word
299 * @return string
301 public static function grammar( $parser, $case = '', $word = '' ) {
302 $word = $parser->killMarkers( $word );
303 return $parser->getFunctionLang()->convertGrammar( $word, $case );
307 * @param Parser $parser
308 * @param string $username
309 * @return string
311 public static function gender( $parser, $username ) {
312 $forms = array_slice( func_get_args(), 2 );
314 // Some shortcuts to avoid loading user data unnecessarily
315 if ( count( $forms ) === 0 ) {
316 return '';
317 } elseif ( count( $forms ) === 1 ) {
318 return $forms[0];
321 $username = trim( $username );
323 // default
324 $gender = User::getDefaultOption( 'gender' );
326 // allow prefix.
327 $title = Title::newFromText( $username );
329 if ( $title && $title->getNamespace() == NS_USER ) {
330 $username = $title->getText();
333 // check parameter, or use the ParserOptions if in interface message
334 $user = User::newFromName( $username );
335 if ( $user ) {
336 $gender = GenderCache::singleton()->getGenderOf( $user, __METHOD__ );
337 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
338 $gender = GenderCache::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
340 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
341 return $ret;
345 * @param Parser $parser
346 * @param string $text
347 * @return string
349 public static function plural( $parser, $text = '' ) {
350 $forms = array_slice( func_get_args(), 2 );
351 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
352 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
353 return $parser->getFunctionLang()->convertPlural( $text, $forms );
357 * Override the title of the page when viewed, provided we've been given a
358 * title which will normalise to the canonical title
360 * @param Parser $parser Parent parser
361 * @param string $text Desired title text
362 * @param string $uarg
363 * @return string
365 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
366 global $wgRestrictDisplayTitle;
368 static $magicWords = null;
369 if ( is_null( $magicWords ) ) {
370 $magicWords = new MagicWordArray( array( 'displaytitle_noerror', 'displaytitle_noreplace' ) );
372 $arg = $magicWords->matchStartToEnd( $uarg );
374 // parse a limited subset of wiki markup (just the single quote items)
375 $text = $parser->doQuotes( $text );
377 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
378 $text = $parser->killMarkers( $text );
380 // list of disallowed tags for DISPLAYTITLE
381 // these will be escaped even though they are allowed in normal wiki text
382 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
383 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' );
385 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
386 if ( $wgRestrictDisplayTitle ) {
387 $htmlTagsCallback = function ( &$params ) {
388 $decoded = Sanitizer::decodeTagAttributes( $params );
390 if ( isset( $decoded['style'] ) ) {
391 // this is called later anyway, but we need it right now for the regexes below to be safe
392 // calling it twice doesn't hurt
393 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
395 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
396 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
400 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
402 } else {
403 $htmlTagsCallback = null;
406 // only requested titles that normalize to the actual title are allowed through
407 // if $wgRestrictDisplayTitle is true (it is by default)
408 // mimic the escaping process that occurs in OutputPage::setPageTitle
409 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
410 $text,
411 $htmlTagsCallback,
412 array(),
413 array(),
414 $bad
415 ) );
416 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
418 if ( !$wgRestrictDisplayTitle ||
419 ( $title instanceof Title
420 && !$title->hasFragment()
421 && $title->equals( $parser->mTitle ) )
423 $old = $parser->mOutput->getProperty( 'displaytitle' );
424 if ( $old === false || $arg !== 'displaytitle_noreplace' ) {
425 $parser->mOutput->setDisplayTitle( $text );
427 if ( $old !== false && $old !== $text && !$arg ) {
428 $converter = $parser->getConverterLanguage()->getConverter();
429 return '<span class="error">' .
430 wfMessage( 'duplicate-displaytitle',
431 // Message should be parsed, but these params should only be escaped.
432 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
433 $converter->markNoConversion( wfEscapeWikiText( $text ) )
434 )->inContentLanguage()->text() .
435 '</span>';
439 return '';
443 * Matches the given value against the value of given magic word
445 * @param string $magicword Magic word key
446 * @param string $value Value to match
447 * @return bool True on successful match
449 private static function matchAgainstMagicword( $magicword, $value ) {
450 $value = trim( strval( $value ) );
451 if ( $value === '' ) {
452 return false;
454 $mwObject = MagicWord::get( $magicword );
455 return $mwObject->matchStartToEnd( $value );
458 public static function formatRaw( $num, $raw ) {
459 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
460 return $num;
461 } else {
462 global $wgContLang;
463 return $wgContLang->formatNum( $num );
466 public static function numberofpages( $parser, $raw = null ) {
467 return self::formatRaw( SiteStats::pages(), $raw );
469 public static function numberofusers( $parser, $raw = null ) {
470 return self::formatRaw( SiteStats::users(), $raw );
472 public static function numberofactiveusers( $parser, $raw = null ) {
473 return self::formatRaw( SiteStats::activeUsers(), $raw );
475 public static function numberofarticles( $parser, $raw = null ) {
476 return self::formatRaw( SiteStats::articles(), $raw );
478 public static function numberoffiles( $parser, $raw = null ) {
479 return self::formatRaw( SiteStats::images(), $raw );
481 public static function numberofadmins( $parser, $raw = null ) {
482 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
484 public static function numberofedits( $parser, $raw = null ) {
485 return self::formatRaw( SiteStats::edits(), $raw );
487 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
488 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
490 public static function numberingroup( $parser, $name = '', $raw = null ) {
491 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
495 * Given a title, return the namespace name that would be given by the
496 * corresponding magic word
497 * Note: function name changed to "mwnamespace" rather than "namespace"
498 * to not break PHP 5.3
499 * @param Parser $parser
500 * @param string $title
501 * @return mixed|string
503 public static function mwnamespace( $parser, $title = null ) {
504 $t = Title::newFromText( $title );
505 if ( is_null( $t ) ) {
506 return '';
508 return str_replace( '_', ' ', $t->getNsText() );
510 public static function namespacee( $parser, $title = null ) {
511 $t = Title::newFromText( $title );
512 if ( is_null( $t ) ) {
513 return '';
515 return wfUrlencode( $t->getNsText() );
517 public static function namespacenumber( $parser, $title = null ) {
518 $t = Title::newFromText( $title );
519 if ( is_null( $t ) ) {
520 return '';
522 return $t->getNamespace();
524 public static function talkspace( $parser, $title = null ) {
525 $t = Title::newFromText( $title );
526 if ( is_null( $t ) || !$t->canTalk() ) {
527 return '';
529 return str_replace( '_', ' ', $t->getTalkNsText() );
531 public static function talkspacee( $parser, $title = null ) {
532 $t = Title::newFromText( $title );
533 if ( is_null( $t ) || !$t->canTalk() ) {
534 return '';
536 return wfUrlencode( $t->getTalkNsText() );
538 public static function subjectspace( $parser, $title = null ) {
539 $t = Title::newFromText( $title );
540 if ( is_null( $t ) ) {
541 return '';
543 return str_replace( '_', ' ', $t->getSubjectNsText() );
545 public static function subjectspacee( $parser, $title = null ) {
546 $t = Title::newFromText( $title );
547 if ( is_null( $t ) ) {
548 return '';
550 return wfUrlencode( $t->getSubjectNsText() );
554 * Functions to get and normalize pagenames, corresponding to the magic words
555 * of the same names
556 * @param Parser $parser
557 * @param string $title
558 * @return string
560 public static function pagename( $parser, $title = null ) {
561 $t = Title::newFromText( $title );
562 if ( is_null( $t ) ) {
563 return '';
565 return wfEscapeWikiText( $t->getText() );
567 public static function pagenamee( $parser, $title = null ) {
568 $t = Title::newFromText( $title );
569 if ( is_null( $t ) ) {
570 return '';
572 return wfEscapeWikiText( $t->getPartialURL() );
574 public static function fullpagename( $parser, $title = null ) {
575 $t = Title::newFromText( $title );
576 if ( is_null( $t ) || !$t->canTalk() ) {
577 return '';
579 return wfEscapeWikiText( $t->getPrefixedText() );
581 public static function fullpagenamee( $parser, $title = null ) {
582 $t = Title::newFromText( $title );
583 if ( is_null( $t ) || !$t->canTalk() ) {
584 return '';
586 return wfEscapeWikiText( $t->getPrefixedURL() );
588 public static function subpagename( $parser, $title = null ) {
589 $t = Title::newFromText( $title );
590 if ( is_null( $t ) ) {
591 return '';
593 return wfEscapeWikiText( $t->getSubpageText() );
595 public static function subpagenamee( $parser, $title = null ) {
596 $t = Title::newFromText( $title );
597 if ( is_null( $t ) ) {
598 return '';
600 return wfEscapeWikiText( $t->getSubpageUrlForm() );
602 public static function rootpagename( $parser, $title = null ) {
603 $t = Title::newFromText( $title );
604 if ( is_null( $t ) ) {
605 return '';
607 return wfEscapeWikiText( $t->getRootText() );
609 public static function rootpagenamee( $parser, $title = null ) {
610 $t = Title::newFromText( $title );
611 if ( is_null( $t ) ) {
612 return '';
614 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
616 public static function basepagename( $parser, $title = null ) {
617 $t = Title::newFromText( $title );
618 if ( is_null( $t ) ) {
619 return '';
621 return wfEscapeWikiText( $t->getBaseText() );
623 public static function basepagenamee( $parser, $title = null ) {
624 $t = Title::newFromText( $title );
625 if ( is_null( $t ) ) {
626 return '';
628 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
630 public static function talkpagename( $parser, $title = null ) {
631 $t = Title::newFromText( $title );
632 if ( is_null( $t ) || !$t->canTalk() ) {
633 return '';
635 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
637 public static function talkpagenamee( $parser, $title = null ) {
638 $t = Title::newFromText( $title );
639 if ( is_null( $t ) || !$t->canTalk() ) {
640 return '';
642 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
644 public static function subjectpagename( $parser, $title = null ) {
645 $t = Title::newFromText( $title );
646 if ( is_null( $t ) ) {
647 return '';
649 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
651 public static function subjectpagenamee( $parser, $title = null ) {
652 $t = Title::newFromText( $title );
653 if ( is_null( $t ) ) {
654 return '';
656 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
660 * Return the number of pages, files or subcats in the given category,
661 * or 0 if it's nonexistent. This is an expensive parser function and
662 * can't be called too many times per page.
663 * @param Parser $parser
664 * @param string $name
665 * @param string $arg1
666 * @param string $arg2
667 * @return string
669 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
670 global $wgContLang;
671 static $magicWords = null;
672 if ( is_null( $magicWords ) ) {
673 $magicWords = new MagicWordArray( array(
674 'pagesincategory_all',
675 'pagesincategory_pages',
676 'pagesincategory_subcats',
677 'pagesincategory_files'
678 ) );
680 static $cache = array();
682 // split the given option to its variable
683 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
684 //{{pagesincategory:|raw[|type]}}
685 $raw = $arg1;
686 $type = $magicWords->matchStartToEnd( $arg2 );
687 } else {
688 //{{pagesincategory:[|type[|raw]]}}
689 $type = $magicWords->matchStartToEnd( $arg1 );
690 $raw = $arg2;
692 if ( !$type ) { //backward compatibility
693 $type = 'pagesincategory_all';
696 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
697 if ( !$title ) { # invalid title
698 return self::formatRaw( 0, $raw );
700 $wgContLang->findVariantLink( $name, $title, true );
702 // Normalize name for cache
703 $name = $title->getDBkey();
705 if ( !isset( $cache[$name] ) ) {
706 $category = Category::newFromTitle( $title );
708 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
709 if ( $parser->incrementExpensiveFunctionCount() ) {
710 // $allCount is the total number of cat members,
711 // not the count of how many members are normal pages.
712 $allCount = (int)$category->getPageCount();
713 $subcatCount = (int)$category->getSubcatCount();
714 $fileCount = (int)$category->getFileCount();
715 $pagesCount = $allCount - $subcatCount - $fileCount;
717 $cache[$name]['pagesincategory_all'] = $allCount;
718 $cache[$name]['pagesincategory_pages'] = $pagesCount;
719 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
720 $cache[$name]['pagesincategory_files'] = $fileCount;
723 $count = $cache[$name][$type];
724 return self::formatRaw( $count, $raw );
728 * Return the size of the given page, or 0 if it's nonexistent. This is an
729 * expensive parser function and can't be called too many times per page.
731 * @param Parser $parser
732 * @param string $page Name of page to check (Default: empty string)
733 * @param string $raw Should number be human readable with commas or just number
734 * @return string
736 public static function pagesize( $parser, $page = '', $raw = null ) {
737 $title = Title::newFromText( $page );
739 if ( !is_object( $title ) ) {
740 return self::formatRaw( 0, $raw );
743 // fetch revision from cache/database and return the value
744 $rev = self::getCachedRevisionObject( $parser, $title );
745 $length = $rev ? $rev->getSize() : 0;
746 return self::formatRaw( $length, $raw );
750 * Returns the requested protection level for the current page. This
751 * is an expensive parser function and can't be called too many times
752 * per page, unless the protection levels for the given title have
753 * already been retrieved
755 * @param Parser $parser
756 * @param string $type
757 * @param string $title
759 * @return string
761 public static function protectionlevel( $parser, $type = '', $title = '' ) {
762 $titleObject = Title::newFromText( $title );
763 if ( !( $titleObject instanceof Title ) ) {
764 $titleObject = $parser->mTitle;
766 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
767 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
768 # Title::getRestrictions returns an array, its possible it may have
769 # multiple values in the future
770 return implode( $restrictions, ',' );
772 return '';
776 * Gives language names.
777 * @param Parser $parser
778 * @param string $code Language code (of which to get name)
779 * @param string $inLanguage Language code (in which to get name)
780 * @return string
782 public static function language( $parser, $code = '', $inLanguage = '' ) {
783 $code = strtolower( $code );
784 $inLanguage = strtolower( $inLanguage );
785 $lang = Language::fetchLanguageName( $code, $inLanguage );
786 return $lang !== '' ? $lang : wfBCP47( $code );
790 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
791 * @param Parser $parser
792 * @param string $string
793 * @param int $length
794 * @param string $padding
795 * @param int $direction
796 * @return string
798 public static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
799 $padding = $parser->killMarkers( $padding );
800 $lengthOfPadding = mb_strlen( $padding );
801 if ( $lengthOfPadding == 0 ) {
802 return $string;
805 # The remaining length to add counts down to 0 as padding is added
806 $length = min( $length, 500 ) - mb_strlen( $string );
807 # $finalPadding is just $padding repeated enough times so that
808 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
809 $finalPadding = '';
810 while ( $length > 0 ) {
811 # If $length < $lengthofPadding, truncate $padding so we get the
812 # exact length desired.
813 $finalPadding .= mb_substr( $padding, 0, $length );
814 $length -= $lengthOfPadding;
817 if ( $direction == STR_PAD_LEFT ) {
818 return $finalPadding . $string;
819 } else {
820 return $string . $finalPadding;
824 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
825 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
828 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
829 return self::pad( $parser, $string, $length, $padding );
833 * @param Parser $parser
834 * @param string $text
835 * @return string
837 public static function anchorencode( $parser, $text ) {
838 $text = $parser->killMarkers( $text );
839 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
842 public static function special( $parser, $text ) {
843 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
844 if ( $page ) {
845 $title = SpecialPage::getTitleFor( $page, $subpage );
846 return $title->getPrefixedText();
847 } else {
848 // unknown special page, just use the given text as its title, if at all possible
849 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
850 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
854 public static function speciale( $parser, $text ) {
855 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
859 * @param Parser $parser
860 * @param string $text The sortkey to use
861 * @param string $uarg Either "noreplace" or "noerror" (in en)
862 * both suppress errors, and noreplace does nothing if
863 * a default sortkey already exists.
864 * @return string
866 public static function defaultsort( $parser, $text, $uarg = '' ) {
867 static $magicWords = null;
868 if ( is_null( $magicWords ) ) {
869 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
871 $arg = $magicWords->matchStartToEnd( $uarg );
873 $text = trim( $text );
874 if ( strlen( $text ) == 0 ) {
875 return '';
877 $old = $parser->getCustomDefaultSort();
878 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
879 $parser->setDefaultSort( $text );
882 if ( $old === false || $old == $text || $arg ) {
883 return '';
884 } else {
885 $converter = $parser->getConverterLanguage()->getConverter();
886 return '<span class="error">' .
887 wfMessage( 'duplicate-defaultsort',
888 // Message should be parsed, but these params should only be escaped.
889 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
890 $converter->markNoConversion( wfEscapeWikiText( $text ) )
891 )->inContentLanguage()->text() .
892 '</span>';
896 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
897 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
898 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
899 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
900 $file = wfFindFile( $name );
902 if ( $argA == 'nowiki' ) {
903 // {{filepath: | option [| size] }}
904 $isNowiki = true;
905 $parsedWidthParam = $parser->parseWidthParam( $argB );
906 } else {
907 // {{filepath: [| size [|option]] }}
908 $parsedWidthParam = $parser->parseWidthParam( $argA );
909 $isNowiki = ( $argB == 'nowiki' );
912 if ( $file ) {
913 $url = $file->getFullUrl();
915 // If a size is requested...
916 if ( count( $parsedWidthParam ) ) {
917 $mto = $file->transform( $parsedWidthParam );
918 // ... and we can
919 if ( $mto && !$mto->isError() ) {
920 // ... change the URL to point to a thumbnail.
921 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
924 if ( $isNowiki ) {
925 return array( $url, 'nowiki' => true );
927 return $url;
928 } else {
929 return '';
934 * Parser function to extension tag adaptor
935 * @param Parser $parser
936 * @param PPFrame $frame
937 * @param array $args
938 * @return string
940 public static function tagObj( $parser, $frame, $args ) {
941 if ( !count( $args ) ) {
942 return '';
944 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
946 if ( count( $args ) ) {
947 $inner = $frame->expand( array_shift( $args ) );
948 } else {
949 $inner = null;
952 $attributes = array();
953 foreach ( $args as $arg ) {
954 $bits = $arg->splitArg();
955 if ( strval( $bits['index'] ) === '' ) {
956 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
957 $value = trim( $frame->expand( $bits['value'] ) );
958 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
959 $value = isset( $m[1] ) ? $m[1] : '';
961 $attributes[$name] = $value;
965 $stripList = $parser->getStripList();
966 if ( !in_array( $tagName, $stripList ) ) {
967 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
968 $attrText = '';
969 foreach ( $attributes as $name => $value ) {
970 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
972 if ( $inner === null ) {
973 return "<$tagName$attrText/>";
975 return "<$tagName$attrText>$inner</$tagName>";
978 $params = array(
979 'name' => $tagName,
980 'inner' => $inner,
981 'attributes' => $attributes,
982 'close' => "</$tagName>",
984 return $parser->extensionSubstitution( $params, $frame );
988 * Fetched the current revision of the given title and return this.
989 * Will increment the expensive function count and
990 * add a template link to get the value refreshed on changes.
991 * For a given title, which is equal to the current parser title,
992 * the revision object from the parser is used, when that is the current one
994 * @param Parser $parser
995 * @param Title $title
996 * @return Revision
997 * @since 1.23
999 private static function getCachedRevisionObject( $parser, $title = null ) {
1000 if ( is_null( $title ) ) {
1001 return null;
1004 // Use the revision from the parser itself, when param is the current page
1005 // and the revision is the current one
1006 if ( $title->equals( $parser->getTitle() ) ) {
1007 $parserRev = $parser->getRevisionObject();
1008 if ( $parserRev && $parserRev->isCurrent() ) {
1009 // force reparse after edit with vary-revision flag
1010 $parser->getOutput()->setFlag( 'vary-revision' );
1011 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
1012 return $parserRev;
1016 // Normalize name for cache
1017 $page = $title->getPrefixedDBkey();
1019 if ( !( $parser->currentRevisionCache && $parser->currentRevisionCache->has( $page ) )
1020 && !$parser->incrementExpensiveFunctionCount() ) {
1021 return null;
1023 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1024 $pageID = $rev ? $rev->getPage() : 0;
1025 $revID = $rev ? $rev->getId() : 0;
1027 // Register dependency in templatelinks
1028 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1030 return $rev;
1034 * Get the pageid of a specified page
1035 * @param Parser $parser
1036 * @param string $title Title to get the pageid from
1037 * @return int|null|string
1038 * @since 1.23
1040 public static function pageid( $parser, $title = null ) {
1041 $t = Title::newFromText( $title );
1042 if ( is_null( $t ) ) {
1043 return '';
1045 // Use title from parser to have correct pageid after edit
1046 if ( $t->equals( $parser->getTitle() ) ) {
1047 $t = $parser->getTitle();
1048 return $t->getArticleID();
1051 // These can't have ids
1052 if ( !$t->canExist() || $t->isExternal() ) {
1053 return 0;
1056 // Check the link cache, maybe something already looked it up.
1057 $linkCache = LinkCache::singleton();
1058 $pdbk = $t->getPrefixedDBkey();
1059 $id = $linkCache->getGoodLinkID( $pdbk );
1060 if ( $id != 0 ) {
1061 $parser->mOutput->addLink( $t, $id );
1062 return $id;
1064 if ( $linkCache->isBadLink( $pdbk ) ) {
1065 $parser->mOutput->addLink( $t, 0 );
1066 return $id;
1069 // We need to load it from the DB, so mark expensive
1070 if ( $parser->incrementExpensiveFunctionCount() ) {
1071 $id = $t->getArticleID();
1072 $parser->mOutput->addLink( $t, $id );
1073 return $id;
1075 return null;
1079 * Get the id from the last revision of a specified page.
1080 * @param Parser $parser
1081 * @param string $title Title to get the id from
1082 * @return int|null|string
1083 * @since 1.23
1085 public static function revisionid( $parser, $title = null ) {
1086 $t = Title::newFromText( $title );
1087 if ( is_null( $t ) ) {
1088 return '';
1090 // fetch revision from cache/database and return the value
1091 $rev = self::getCachedRevisionObject( $parser, $t );
1092 return $rev ? $rev->getId() : '';
1096 * Get the day from the last revision of a specified page.
1097 * @param Parser $parser
1098 * @param string $title Title to get the day from
1099 * @return string
1100 * @since 1.23
1102 public static function revisionday( $parser, $title = null ) {
1103 $t = Title::newFromText( $title );
1104 if ( is_null( $t ) ) {
1105 return '';
1107 // fetch revision from cache/database and return the value
1108 $rev = self::getCachedRevisionObject( $parser, $t );
1109 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1113 * Get the day with leading zeros from the last revision of a specified page.
1114 * @param Parser $parser
1115 * @param string $title Title to get the day from
1116 * @return string
1117 * @since 1.23
1119 public static function revisionday2( $parser, $title = null ) {
1120 $t = Title::newFromText( $title );
1121 if ( is_null( $t ) ) {
1122 return '';
1124 // fetch revision from cache/database and return the value
1125 $rev = self::getCachedRevisionObject( $parser, $t );
1126 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1130 * Get the month with leading zeros from the last revision of a specified page.
1131 * @param Parser $parser
1132 * @param string $title Title to get the month from
1133 * @return string
1134 * @since 1.23
1136 public static function revisionmonth( $parser, $title = null ) {
1137 $t = Title::newFromText( $title );
1138 if ( is_null( $t ) ) {
1139 return '';
1141 // fetch revision from cache/database and return the value
1142 $rev = self::getCachedRevisionObject( $parser, $t );
1143 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1147 * Get the month from the last revision of a specified page.
1148 * @param Parser $parser
1149 * @param string $title Title to get the month from
1150 * @return string
1151 * @since 1.23
1153 public static function revisionmonth1( $parser, $title = null ) {
1154 $t = Title::newFromText( $title );
1155 if ( is_null( $t ) ) {
1156 return '';
1158 // fetch revision from cache/database and return the value
1159 $rev = self::getCachedRevisionObject( $parser, $t );
1160 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1164 * Get the year from the last revision of a specified page.
1165 * @param Parser $parser
1166 * @param string $title Title to get the year from
1167 * @return string
1168 * @since 1.23
1170 public static function revisionyear( $parser, $title = null ) {
1171 $t = Title::newFromText( $title );
1172 if ( is_null( $t ) ) {
1173 return '';
1175 // fetch revision from cache/database and return the value
1176 $rev = self::getCachedRevisionObject( $parser, $t );
1177 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1181 * Get the timestamp from the last revision of a specified page.
1182 * @param Parser $parser
1183 * @param string $title Title to get the timestamp from
1184 * @return string
1185 * @since 1.23
1187 public static function revisiontimestamp( $parser, $title = null ) {
1188 $t = Title::newFromText( $title );
1189 if ( is_null( $t ) ) {
1190 return '';
1192 // fetch revision from cache/database and return the value
1193 $rev = self::getCachedRevisionObject( $parser, $t );
1194 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1198 * Get the user from the last revision of a specified page.
1199 * @param Parser $parser
1200 * @param string $title Title to get the user from
1201 * @return string
1202 * @since 1.23
1204 public static function revisionuser( $parser, $title = null ) {
1205 $t = Title::newFromText( $title );
1206 if ( is_null( $t ) ) {
1207 return '';
1209 // fetch revision from cache/database and return the value
1210 $rev = self::getCachedRevisionObject( $parser, $t );
1211 return $rev ? $rev->getUserText() : '';
1215 * Returns the sources of any cascading protection acting on a specified page.
1216 * Pages will not return their own title unless they transclude themselves.
1217 * This is an expensive parser function and can't be called too many times per page,
1218 * unless cascading protection sources for the page have already been loaded.
1220 * @param Parser $parser
1221 * @param string $title
1223 * @return string
1224 * @since 1.23
1226 public static function cascadingsources( $parser, $title = '' ) {
1227 $titleObject = Title::newFromText( $title );
1228 if ( !( $titleObject instanceof Title ) ) {
1229 $titleObject = $parser->mTitle;
1231 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1232 || $parser->incrementExpensiveFunctionCount()
1234 $names = array();
1235 $sources = $titleObject->getCascadeProtectionSources();
1236 foreach ( $sources[0] as $sourceTitle ) {
1237 $names[] = $sourceTitle->getPrefixedText();
1239 return implode( $names, '|' );
1241 return '';