Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / parser / CoreParserFunctions.php
blob3425b6bb7c3a083fcb56d7395caceb4aca4f6a6c
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 static function register( $parser ) {
34 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
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 $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', 'numberofviews', '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 ), SFH_NO_HASH );
63 $parser->setFunctionHook( 'namespace', array( __CLASS__, 'mwnamespace' ), SFH_NO_HASH );
64 $parser->setFunctionHook( 'int', array( __CLASS__, 'intFunction' ), SFH_NO_HASH );
65 $parser->setFunctionHook( 'special', array( __CLASS__, 'special' ) );
66 $parser->setFunctionHook( 'speciale', array( __CLASS__, 'speciale' ) );
67 $parser->setFunctionHook( 'tag', array( __CLASS__, 'tagObj' ), SFH_OBJECT_ARGS );
68 $parser->setFunctionHook( 'formatdate', array( __CLASS__, 'formatDate' ) );
70 if ( $wgAllowDisplayTitle ) {
71 $parser->setFunctionHook( 'displaytitle', array( __CLASS__, 'displaytitle' ), SFH_NO_HASH );
73 if ( $wgAllowSlowParserFunctions ) {
74 $parser->setFunctionHook(
75 'pagesinnamespace',
76 array( __CLASS__, 'pagesinnamespace' ),
77 SFH_NO_HASH
82 /**
83 * @param Parser $parser
84 * @param string $part1
85 * @return array
87 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 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 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 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 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 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 static function lcfirst( $parser, $s = '' ) {
185 global $wgContLang;
186 return $wgContLang->lcfirst( $s );
189 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 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 static function uc( $parser, $s = '' ) {
210 global $wgContLang;
211 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
214 static function localurl( $parser, $s = '', $arg = null ) {
215 return self::urlFunction( 'getLocalURL', $s, $arg );
218 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 static function fullurl( $parser, $s = '', $arg = null ) {
228 return self::urlFunction( 'getFullURL', $s, $arg );
231 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 static function canonicalurl( $parser, $s = '', $arg = null ) {
241 return self::urlFunction( 'getCanonicalURL', $s, $arg );
244 static function canonicalurle( $parser, $s = '', $arg = null ) {
245 return self::urlFunction( 'escapeCanonicalURL', $s, $arg );
248 static function urlFunction( $func, $s = '', $arg = null ) {
249 $title = Title::newFromText( $s );
250 # Due to order of execution of a lot of bits, the values might be encoded
251 # before arriving here; if that's true, then the title can't be created
252 # and the variable will fail. If we can't get a decent title from the first
253 # attempt, url-decode and try for a second.
254 if ( is_null( $title ) ) {
255 $title = Title::newFromURL( urldecode( $s ) );
257 if ( !is_null( $title ) ) {
258 # Convert NS_MEDIA -> NS_FILE
259 if ( $title->getNamespace() == NS_MEDIA ) {
260 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
262 if ( !is_null( $arg ) ) {
263 $text = $title->$func( $arg );
264 } else {
265 $text = $title->$func();
267 return $text;
268 } else {
269 return array( 'found' => false );
274 * @param Parser $parser
275 * @param string $num
276 * @param string $arg
277 * @return string
279 static function formatnum( $parser, $num = '', $arg = null ) {
280 if ( self::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
281 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
282 } elseif ( self::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
283 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
284 } else {
285 $func = array( $parser->getFunctionLang(), 'formatNum' );
287 return $parser->markerSkipCallback( $num, $func );
291 * @param Parser $parser
292 * @param string $case
293 * @param string $word
294 * @return string
296 static function grammar( $parser, $case = '', $word = '' ) {
297 $word = $parser->killMarkers( $word );
298 return $parser->getFunctionLang()->convertGrammar( $word, $case );
302 * @param Parser $parser
303 * @param string $username
304 * @return string
306 static function gender( $parser, $username ) {
307 wfProfileIn( __METHOD__ );
308 $forms = array_slice( func_get_args(), 2 );
310 // Some shortcuts to avoid loading user data unnecessarily
311 if ( count( $forms ) === 0 ) {
312 wfProfileOut( __METHOD__ );
313 return '';
314 } elseif ( count( $forms ) === 1 ) {
315 wfProfileOut( __METHOD__ );
316 return $forms[0];
319 $username = trim( $username );
321 // default
322 $gender = User::getDefaultOption( 'gender' );
324 // allow prefix.
325 $title = Title::newFromText( $username );
327 if ( $title && $title->getNamespace() == NS_USER ) {
328 $username = $title->getText();
331 // check parameter, or use the ParserOptions if in interface message
332 $user = User::newFromName( $username );
333 if ( $user ) {
334 $gender = GenderCache::singleton()->getGenderOf( $user, __METHOD__ );
335 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
336 $gender = GenderCache::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
338 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
339 wfProfileOut( __METHOD__ );
340 return $ret;
344 * @param Parser $parser
345 * @param string $text
346 * @return string
348 static function plural( $parser, $text = '' ) {
349 $forms = array_slice( func_get_args(), 2 );
350 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
351 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
352 return $parser->getFunctionLang()->convertPlural( $text, $forms );
356 * Override the title of the page when viewed, provided we've been given a
357 * title which will normalise to the canonical title
359 * @param Parser $parser Parent parser
360 * @param string $text Desired title text
361 * @return string
363 static function displaytitle( $parser, $text = '' ) {
364 global $wgRestrictDisplayTitle;
366 // parse a limited subset of wiki markup (just the single quote items)
367 $text = $parser->doQuotes( $text );
369 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
370 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
371 . preg_quote( Parser::MARKER_SUFFIX, '/' ) . '/', '', $text );
373 // list of disallowed tags for DISPLAYTITLE
374 // these will be escaped even though they are allowed in normal wiki text
375 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
376 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
378 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
379 if ( $wgRestrictDisplayTitle ) {
380 $htmlTagsCallback = function ( &$params ) {
381 $decoded = Sanitizer::decodeTagAttributes( $params );
383 if ( isset( $decoded['style'] ) ) {
384 // this is called later anyway, but we need it right now for the regexes below to be safe
385 // calling it twice doesn't hurt
386 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
388 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
389 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
393 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
395 } else {
396 $htmlTagsCallback = null;
399 // only requested titles that normalize to the actual title are allowed through
400 // if $wgRestrictDisplayTitle is true (it is by default)
401 // mimic the escaping process that occurs in OutputPage::setPageTitle
402 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
403 $text,
404 $htmlTagsCallback,
405 array(),
406 array(),
407 $bad
408 ) );
409 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
411 if ( !$wgRestrictDisplayTitle ) {
412 $parser->mOutput->setDisplayTitle( $text );
413 } elseif ( $title instanceof Title
414 && !$title->hasFragment()
415 && $title->equals( $parser->mTitle )
417 $parser->mOutput->setDisplayTitle( $text );
420 return '';
424 * Matches the given value against the value of given magic word
426 * @param string $magicword Magic word key
427 * @param string $value Value to match
428 * @return bool True on successful match
430 private static function matchAgainstMagicword( $magicword, $value ) {
431 $value = trim( strval( $value ) );
432 if ( $value === '' ) {
433 return false;
435 $mwObject = MagicWord::get( $magicword );
436 return $mwObject->matchStartToEnd( $value );
439 static function formatRaw( $num, $raw ) {
440 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
441 return $num;
442 } else {
443 global $wgContLang;
444 return $wgContLang->formatNum( $num );
447 static function numberofpages( $parser, $raw = null ) {
448 return self::formatRaw( SiteStats::pages(), $raw );
450 static function numberofusers( $parser, $raw = null ) {
451 return self::formatRaw( SiteStats::users(), $raw );
453 static function numberofactiveusers( $parser, $raw = null ) {
454 return self::formatRaw( SiteStats::activeUsers(), $raw );
456 static function numberofarticles( $parser, $raw = null ) {
457 return self::formatRaw( SiteStats::articles(), $raw );
459 static function numberoffiles( $parser, $raw = null ) {
460 return self::formatRaw( SiteStats::images(), $raw );
462 static function numberofadmins( $parser, $raw = null ) {
463 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
465 static function numberofedits( $parser, $raw = null ) {
466 return self::formatRaw( SiteStats::edits(), $raw );
468 static function numberofviews( $parser, $raw = null ) {
469 global $wgDisableCounters;
470 return !$wgDisableCounters ? self::formatRaw( SiteStats::views(), $raw ) : '';
472 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
473 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
475 static function numberingroup( $parser, $name = '', $raw = null ) {
476 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
480 * Given a title, return the namespace name that would be given by the
481 * corresponding magic word
482 * Note: function name changed to "mwnamespace" rather than "namespace"
483 * to not break PHP 5.3
484 * @param Parser $parser
485 * @param string $title
486 * @return mixed|string
488 static function mwnamespace( $parser, $title = null ) {
489 $t = Title::newFromText( $title );
490 if ( is_null( $t ) ) {
491 return '';
493 return str_replace( '_', ' ', $t->getNsText() );
495 static function namespacee( $parser, $title = null ) {
496 $t = Title::newFromText( $title );
497 if ( is_null( $t ) ) {
498 return '';
500 return wfUrlencode( $t->getNsText() );
502 static function namespacenumber( $parser, $title = null ) {
503 $t = Title::newFromText( $title );
504 if ( is_null( $t ) ) {
505 return '';
507 return $t->getNamespace();
509 static function talkspace( $parser, $title = null ) {
510 $t = Title::newFromText( $title );
511 if ( is_null( $t ) || !$t->canTalk() ) {
512 return '';
514 return str_replace( '_', ' ', $t->getTalkNsText() );
516 static function talkspacee( $parser, $title = null ) {
517 $t = Title::newFromText( $title );
518 if ( is_null( $t ) || !$t->canTalk() ) {
519 return '';
521 return wfUrlencode( $t->getTalkNsText() );
523 static function subjectspace( $parser, $title = null ) {
524 $t = Title::newFromText( $title );
525 if ( is_null( $t ) ) {
526 return '';
528 return str_replace( '_', ' ', $t->getSubjectNsText() );
530 static function subjectspacee( $parser, $title = null ) {
531 $t = Title::newFromText( $title );
532 if ( is_null( $t ) ) {
533 return '';
535 return wfUrlencode( $t->getSubjectNsText() );
539 * Functions to get and normalize pagenames, corresponding to the magic words
540 * of the same names
541 * @param Parser $parser
542 * @param string $title
543 * @return string
545 static function pagename( $parser, $title = null ) {
546 $t = Title::newFromText( $title );
547 if ( is_null( $t ) ) {
548 return '';
550 return wfEscapeWikiText( $t->getText() );
552 static function pagenamee( $parser, $title = null ) {
553 $t = Title::newFromText( $title );
554 if ( is_null( $t ) ) {
555 return '';
557 return wfEscapeWikiText( $t->getPartialURL() );
559 static function fullpagename( $parser, $title = null ) {
560 $t = Title::newFromText( $title );
561 if ( is_null( $t ) || !$t->canTalk() ) {
562 return '';
564 return wfEscapeWikiText( $t->getPrefixedText() );
566 static function fullpagenamee( $parser, $title = null ) {
567 $t = Title::newFromText( $title );
568 if ( is_null( $t ) || !$t->canTalk() ) {
569 return '';
571 return wfEscapeWikiText( $t->getPrefixedURL() );
573 static function subpagename( $parser, $title = null ) {
574 $t = Title::newFromText( $title );
575 if ( is_null( $t ) ) {
576 return '';
578 return wfEscapeWikiText( $t->getSubpageText() );
580 static function subpagenamee( $parser, $title = null ) {
581 $t = Title::newFromText( $title );
582 if ( is_null( $t ) ) {
583 return '';
585 return wfEscapeWikiText( $t->getSubpageUrlForm() );
587 static function rootpagename( $parser, $title = null ) {
588 $t = Title::newFromText( $title );
589 if ( is_null( $t ) ) {
590 return '';
592 return wfEscapeWikiText( $t->getRootText() );
594 static function rootpagenamee( $parser, $title = null ) {
595 $t = Title::newFromText( $title );
596 if ( is_null( $t ) ) {
597 return '';
599 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
601 static function basepagename( $parser, $title = null ) {
602 $t = Title::newFromText( $title );
603 if ( is_null( $t ) ) {
604 return '';
606 return wfEscapeWikiText( $t->getBaseText() );
608 static function basepagenamee( $parser, $title = null ) {
609 $t = Title::newFromText( $title );
610 if ( is_null( $t ) ) {
611 return '';
613 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
615 static function talkpagename( $parser, $title = null ) {
616 $t = Title::newFromText( $title );
617 if ( is_null( $t ) || !$t->canTalk() ) {
618 return '';
620 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
622 static function talkpagenamee( $parser, $title = null ) {
623 $t = Title::newFromText( $title );
624 if ( is_null( $t ) || !$t->canTalk() ) {
625 return '';
627 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
629 static function subjectpagename( $parser, $title = null ) {
630 $t = Title::newFromText( $title );
631 if ( is_null( $t ) ) {
632 return '';
634 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
636 static function subjectpagenamee( $parser, $title = null ) {
637 $t = Title::newFromText( $title );
638 if ( is_null( $t ) ) {
639 return '';
641 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
645 * Return the number of pages, files or subcats in the given category,
646 * or 0 if it's nonexistent. This is an expensive parser function and
647 * can't be called too many times per page.
648 * @param Parser $parser
649 * @param string $name
650 * @param string $arg1
651 * @param string $arg2
652 * @return string
654 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
655 global $wgContLang;
656 static $magicWords = null;
657 if ( is_null( $magicWords ) ) {
658 $magicWords = new MagicWordArray( array(
659 'pagesincategory_all',
660 'pagesincategory_pages',
661 'pagesincategory_subcats',
662 'pagesincategory_files'
663 ) );
665 static $cache = array();
667 // split the given option to its variable
668 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
669 //{{pagesincategory:|raw[|type]}}
670 $raw = $arg1;
671 $type = $magicWords->matchStartToEnd( $arg2 );
672 } else {
673 //{{pagesincategory:[|type[|raw]]}}
674 $type = $magicWords->matchStartToEnd( $arg1 );
675 $raw = $arg2;
677 if ( !$type ) { //backward compatibility
678 $type = 'pagesincategory_all';
681 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
682 if ( !$title ) { # invalid title
683 return self::formatRaw( 0, $raw );
685 $wgContLang->findVariantLink( $name, $title, true );
687 // Normalize name for cache
688 $name = $title->getDBkey();
690 if ( !isset( $cache[$name] ) ) {
691 $category = Category::newFromTitle( $title );
693 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
694 if ( $parser->incrementExpensiveFunctionCount() ) {
695 // $allCount is the total number of cat members,
696 // not the count of how many members are normal pages.
697 $allCount = (int)$category->getPageCount();
698 $subcatCount = (int)$category->getSubcatCount();
699 $fileCount = (int)$category->getFileCount();
700 $pagesCount = $allCount - $subcatCount - $fileCount;
702 $cache[$name]['pagesincategory_all'] = $allCount;
703 $cache[$name]['pagesincategory_pages'] = $pagesCount;
704 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
705 $cache[$name]['pagesincategory_files'] = $fileCount;
708 $count = $cache[$name][$type];
709 return self::formatRaw( $count, $raw );
713 * Return the size of the given page, or 0 if it's nonexistent. This is an
714 * expensive parser function and can't be called too many times per page.
716 * @param Parser $parser
717 * @param string $page Name of page to check (Default: empty string)
718 * @param string $raw Should number be human readable with commas or just number
719 * @return string
721 static function pagesize( $parser, $page = '', $raw = null ) {
722 $title = Title::newFromText( $page );
724 if ( !is_object( $title ) ) {
725 return self::formatRaw( 0, $raw );
728 // fetch revision from cache/database and return the value
729 $rev = self::getCachedRevisionObject( $parser, $title );
730 $length = $rev ? $rev->getSize() : 0;
731 return self::formatRaw( $length, $raw );
735 * Returns the requested protection level for the current page. This
736 * is an expensive parser function and can't be called too many times
737 * per page, unless the protection levels for the given title have
738 * already been retrieved
740 * @param Parser $parser
741 * @param string $type
742 * @param string $title
744 * @return string
746 static function protectionlevel( $parser, $type = '', $title = '' ) {
747 $titleObject = Title::newFromText( $title );
748 if ( !( $titleObject instanceof Title ) ) {
749 $titleObject = $parser->mTitle;
751 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
752 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
753 # Title::getRestrictions returns an array, its possible it may have
754 # multiple values in the future
755 return implode( $restrictions, ',' );
757 return '';
761 * Gives language names.
762 * @param Parser $parser
763 * @param string $code Language code (of which to get name)
764 * @param string $inLanguage Language code (in which to get name)
765 * @return string
767 static function language( $parser, $code = '', $inLanguage = '' ) {
768 $code = strtolower( $code );
769 $inLanguage = strtolower( $inLanguage );
770 $lang = Language::fetchLanguageName( $code, $inLanguage );
771 return $lang !== '' ? $lang : wfBCP47( $code );
775 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
776 * @param Parser $parser
777 * @param string $string
778 * @param int $length
779 * @param string $padding
780 * @param int $direction
781 * @return string
783 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
784 $padding = $parser->killMarkers( $padding );
785 $lengthOfPadding = mb_strlen( $padding );
786 if ( $lengthOfPadding == 0 ) {
787 return $string;
790 # The remaining length to add counts down to 0 as padding is added
791 $length = min( $length, 500 ) - mb_strlen( $string );
792 # $finalPadding is just $padding repeated enough times so that
793 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
794 $finalPadding = '';
795 while ( $length > 0 ) {
796 # If $length < $lengthofPadding, truncate $padding so we get the
797 # exact length desired.
798 $finalPadding .= mb_substr( $padding, 0, $length );
799 $length -= $lengthOfPadding;
802 if ( $direction == STR_PAD_LEFT ) {
803 return $finalPadding . $string;
804 } else {
805 return $string . $finalPadding;
809 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
810 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
813 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
814 return self::pad( $parser, $string, $length, $padding );
818 * @param Parser $parser
819 * @param string $text
820 * @return string
822 static function anchorencode( $parser, $text ) {
823 $text = $parser->killMarkers( $text );
824 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
827 static function special( $parser, $text ) {
828 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
829 if ( $page ) {
830 $title = SpecialPage::getTitleFor( $page, $subpage );
831 return $title->getPrefixedText();
832 } else {
833 // unknown special page, just use the given text as its title, if at all possible
834 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
835 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
839 static function speciale( $parser, $text ) {
840 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
844 * @param Parser $parser
845 * @param string $text The sortkey to use
846 * @param string $uarg Either "noreplace" or "noerror" (in en)
847 * both suppress errors, and noreplace does nothing if
848 * a default sortkey already exists.
849 * @return string
851 public static function defaultsort( $parser, $text, $uarg = '' ) {
852 static $magicWords = null;
853 if ( is_null( $magicWords ) ) {
854 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
856 $arg = $magicWords->matchStartToEnd( $uarg );
858 $text = trim( $text );
859 if ( strlen( $text ) == 0 ) {
860 return '';
862 $old = $parser->getCustomDefaultSort();
863 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
864 $parser->setDefaultSort( $text );
867 if ( $old === false || $old == $text || $arg ) {
868 return '';
869 } else {
870 $converter = $parser->getConverterLanguage()->getConverter();
871 return '<span class="error">' .
872 wfMessage( 'duplicate-defaultsort',
873 // Message should be parsed, but these params should only be escaped.
874 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
875 $converter->markNoConversion( wfEscapeWikiText( $text ) )
876 )->inContentLanguage()->text() .
877 '</span>';
881 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
882 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
883 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
884 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
885 $file = wfFindFile( $name );
887 if ( $argA == 'nowiki' ) {
888 // {{filepath: | option [| size] }}
889 $isNowiki = true;
890 $parsedWidthParam = $parser->parseWidthParam( $argB );
891 } else {
892 // {{filepath: [| size [|option]] }}
893 $parsedWidthParam = $parser->parseWidthParam( $argA );
894 $isNowiki = ( $argB == 'nowiki' );
897 if ( $file ) {
898 $url = $file->getFullUrl();
900 // If a size is requested...
901 if ( count( $parsedWidthParam ) ) {
902 $mto = $file->transform( $parsedWidthParam );
903 // ... and we can
904 if ( $mto && !$mto->isError() ) {
905 // ... change the URL to point to a thumbnail.
906 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
909 if ( $isNowiki ) {
910 return array( $url, 'nowiki' => true );
912 return $url;
913 } else {
914 return '';
919 * Parser function to extension tag adaptor
920 * @param Parser $parser
921 * @param PPFrame $frame
922 * @param array $args
923 * @return string
925 public static function tagObj( $parser, $frame, $args ) {
926 if ( !count( $args ) ) {
927 return '';
929 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
931 if ( count( $args ) ) {
932 $inner = $frame->expand( array_shift( $args ) );
933 } else {
934 $inner = null;
937 $stripList = $parser->getStripList();
938 if ( !in_array( $tagName, $stripList ) ) {
939 return '<span class="error">' .
940 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
941 '</span>';
944 $attributes = array();
945 foreach ( $args as $arg ) {
946 $bits = $arg->splitArg();
947 if ( strval( $bits['index'] ) === '' ) {
948 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
949 $value = trim( $frame->expand( $bits['value'] ) );
950 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
951 $value = isset( $m[1] ) ? $m[1] : '';
953 $attributes[$name] = $value;
957 $params = array(
958 'name' => $tagName,
959 'inner' => $inner,
960 'attributes' => $attributes,
961 'close' => "</$tagName>",
963 return $parser->extensionSubstitution( $params, $frame );
967 * Fetched the current revision of the given title and return this.
968 * Will increment the expensive function count and
969 * add a template link to get the value refreshed on changes.
970 * For a given title, which is equal to the current parser title,
971 * the revision object from the parser is used, when that is the current one
973 * @param Parser $parser
974 * @param Title $title
975 * @return Revision
976 * @since 1.23
978 private static function getCachedRevisionObject( $parser, $title = null ) {
979 static $cache = array();
981 if ( is_null( $title ) ) {
982 return null;
985 // Use the revision from the parser itself, when param is the current page
986 // and the revision is the current one
987 if ( $title->equals( $parser->getTitle() ) ) {
988 $parserRev = $parser->getRevisionObject();
989 if ( $parserRev && $parserRev->isCurrent() ) {
990 // force reparse after edit with vary-revision flag
991 $parser->getOutput()->setFlag( 'vary-revision' );
992 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
993 return $parserRev;
997 // Normalize name for cache
998 $page = $title->getPrefixedDBkey();
1000 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
1001 return $cache[$page];
1003 if ( $parser->incrementExpensiveFunctionCount() ) {
1004 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
1005 $pageID = $rev ? $rev->getPage() : 0;
1006 $revID = $rev ? $rev->getId() : 0;
1007 $cache[$page] = $rev; // maybe null
1009 // Register dependency in templatelinks
1010 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1012 return $rev;
1014 $cache[$page] = null;
1015 return null;
1019 * Get the pageid of a specified page
1020 * @param Parser $parser
1021 * @param string $title Title to get the pageid from
1022 * @return int|null|string
1023 * @since 1.23
1025 public static function pageid( $parser, $title = null ) {
1026 $t = Title::newFromText( $title );
1027 if ( is_null( $t ) ) {
1028 return '';
1030 // Use title from parser to have correct pageid after edit
1031 if ( $t->equals( $parser->getTitle() ) ) {
1032 $t = $parser->getTitle();
1033 return $t->getArticleID();
1036 // These can't have ids
1037 if ( !$t->canExist() || $t->isExternal() ) {
1038 return 0;
1041 // Check the link cache, maybe something already looked it up.
1042 $linkCache = LinkCache::singleton();
1043 $pdbk = $t->getPrefixedDBkey();
1044 $id = $linkCache->getGoodLinkID( $pdbk );
1045 if ( $id != 0 ) {
1046 $parser->mOutput->addLink( $t, $id );
1047 return $id;
1049 if ( $linkCache->isBadLink( $pdbk ) ) {
1050 $parser->mOutput->addLink( $t, 0 );
1051 return $id;
1054 // We need to load it from the DB, so mark expensive
1055 if ( $parser->incrementExpensiveFunctionCount() ) {
1056 $id = $t->getArticleID();
1057 $parser->mOutput->addLink( $t, $id );
1058 return $id;
1060 return null;
1064 * Get the id from the last revision of a specified page.
1065 * @param Parser $parser
1066 * @param string $title Title to get the id from
1067 * @return int|null|string
1068 * @since 1.23
1070 public static function revisionid( $parser, $title = null ) {
1071 $t = Title::newFromText( $title );
1072 if ( is_null( $t ) ) {
1073 return '';
1075 // fetch revision from cache/database and return the value
1076 $rev = self::getCachedRevisionObject( $parser, $t );
1077 return $rev ? $rev->getId() : '';
1081 * Get the day from the last revision of a specified page.
1082 * @param Parser $parser
1083 * @param string $title Title to get the day from
1084 * @return string
1085 * @since 1.23
1087 public static function revisionday( $parser, $title = null ) {
1088 $t = Title::newFromText( $title );
1089 if ( is_null( $t ) ) {
1090 return '';
1092 // fetch revision from cache/database and return the value
1093 $rev = self::getCachedRevisionObject( $parser, $t );
1094 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1098 * Get the day with leading zeros from the last revision of a specified page.
1099 * @param Parser $parser
1100 * @param string $title Title to get the day from
1101 * @return string
1102 * @since 1.23
1104 public static function revisionday2( $parser, $title = null ) {
1105 $t = Title::newFromText( $title );
1106 if ( is_null( $t ) ) {
1107 return '';
1109 // fetch revision from cache/database and return the value
1110 $rev = self::getCachedRevisionObject( $parser, $t );
1111 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1115 * Get the month with leading zeros from the last revision of a specified page.
1116 * @param Parser $parser
1117 * @param string $title Title to get the month from
1118 * @return string
1119 * @since 1.23
1121 public static function revisionmonth( $parser, $title = null ) {
1122 $t = Title::newFromText( $title );
1123 if ( is_null( $t ) ) {
1124 return '';
1126 // fetch revision from cache/database and return the value
1127 $rev = self::getCachedRevisionObject( $parser, $t );
1128 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1132 * Get the month from the last revision of a specified page.
1133 * @param Parser $parser
1134 * @param string $title Title to get the month from
1135 * @return string
1136 * @since 1.23
1138 public static function revisionmonth1( $parser, $title = null ) {
1139 $t = Title::newFromText( $title );
1140 if ( is_null( $t ) ) {
1141 return '';
1143 // fetch revision from cache/database and return the value
1144 $rev = self::getCachedRevisionObject( $parser, $t );
1145 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1149 * Get the year from the last revision of a specified page.
1150 * @param Parser $parser
1151 * @param string $title Title to get the year from
1152 * @return string
1153 * @since 1.23
1155 public static function revisionyear( $parser, $title = null ) {
1156 $t = Title::newFromText( $title );
1157 if ( is_null( $t ) ) {
1158 return '';
1160 // fetch revision from cache/database and return the value
1161 $rev = self::getCachedRevisionObject( $parser, $t );
1162 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1166 * Get the timestamp from the last revision of a specified page.
1167 * @param Parser $parser
1168 * @param string $title Title to get the timestamp from
1169 * @return string
1170 * @since 1.23
1172 public static function revisiontimestamp( $parser, $title = null ) {
1173 $t = Title::newFromText( $title );
1174 if ( is_null( $t ) ) {
1175 return '';
1177 // fetch revision from cache/database and return the value
1178 $rev = self::getCachedRevisionObject( $parser, $t );
1179 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1183 * Get the user from the last revision of a specified page.
1184 * @param Parser $parser
1185 * @param string $title Title to get the user from
1186 * @return string
1187 * @since 1.23
1189 public static function revisionuser( $parser, $title = null ) {
1190 $t = Title::newFromText( $title );
1191 if ( is_null( $t ) ) {
1192 return '';
1194 // fetch revision from cache/database and return the value
1195 $rev = self::getCachedRevisionObject( $parser, $t );
1196 return $rev ? $rev->getUserText() : '';
1200 * Returns the sources of any cascading protection acting on a specified page.
1201 * Pages will not return their own title unless they transclude themselves.
1202 * This is an expensive parser function and can't be called too many times per page,
1203 * unless cascading protection sources for the page have already been loaded.
1205 * @param Parser $parser
1206 * @param string $title
1208 * @return string
1209 * @since 1.23
1211 public static function cascadingsources( $parser, $title = '' ) {
1212 $titleObject = Title::newFromText( $title );
1213 if ( !( $titleObject instanceof Title ) ) {
1214 $titleObject = $parser->mTitle;
1216 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1217 || $parser->incrementExpensiveFunctionCount()
1219 $names = array();
1220 $sources = $titleObject->getCascadeProtectionSources();
1221 foreach ( $sources[0] as $sourceTitle ) {
1222 $names[] = $sourceTitle->getPrefixedText();
1224 return implode( $names, '|' );
1226 return '';