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
25 * Various core parser functions, registered in Parser::firstCallInit()
28 class CoreParserFunctions
{
30 * @param $parser Parser
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",
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( 'pagesinnamespace', array( __CLASS__
, 'pagesinnamespace' ), SFH_NO_HASH
);
79 * @param $parser Parser
80 * @param string $part1
83 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
84 if ( strval( $part1 ) !== '' ) {
85 $args = array_slice( func_get_args(), 2 );
86 $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
87 return array( $message, 'noparse' => false );
89 return array( 'found' => false );
94 * @param Parser $parser
96 * @param string $defaultPref
100 static function formatDate( $parser, $date, $defaultPref = null ) {
101 $lang = $parser->getFunctionLang();
102 $df = DateFormatter
::getInstance( $lang );
104 $date = trim( $date );
106 $pref = $parser->getOptions()->getDateFormat();
108 // Specify a different default date format other than the the normal default
109 // if the user has 'default' for their setting
110 if ( $pref == 'default' && $defaultPref ) {
111 $pref = $defaultPref;
114 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
118 static function ns( $parser, $part1 = '' ) {
120 if ( intval( $part1 ) ||
$part1 == "0" ) {
121 $index = intval( $part1 );
123 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
125 if ( $index !== false ) {
126 return $wgContLang->getFormattedNsText( $index );
128 return array( 'found' => false );
132 static function nse( $parser, $part1 = '' ) {
133 $ret = self
::ns( $parser, $part1 );
134 if ( is_string( $ret ) ) {
135 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
141 * urlencodes a string according to one of three patterns: (bug 22474)
143 * By default (for HTTP "query" strings), spaces are encoded as '+'.
144 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
145 * For links to "wiki"s, or similar software, spaces are encoded as '_',
147 * @param $parser Parser object
148 * @param string $s The text to encode.
149 * @param string $arg (optional): The type of encoding.
152 static function urlencode( $parser, $s = '', $arg = null ) {
153 static $magicWords = null;
154 if ( is_null( $magicWords ) ) {
155 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
157 switch ( $magicWords->matchStartToEnd( $arg ) ) {
159 // Encode as though it's a wiki page, '_' for ' '.
161 $func = 'wfUrlencode';
162 $s = str_replace( ' ', '_', $s );
165 // Encode for an HTTP Path, '%20' for ' '.
167 $func = 'rawurlencode';
170 // Encode for HTTP query, '+' for ' '.
175 return $parser->markerSkipCallback( $s, $func );
178 static function lcfirst( $parser, $s = '' ) {
180 return $wgContLang->lcfirst( $s );
183 static function ucfirst( $parser, $s = '' ) {
185 return $wgContLang->ucfirst( $s );
189 * @param $parser Parser
193 static function lc( $parser, $s = '' ) {
195 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
199 * @param $parser Parser
203 static function uc( $parser, $s = '' ) {
205 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
208 static function localurl( $parser, $s = '', $arg = null ) {
209 return self
::urlFunction( 'getLocalURL', $s, $arg );
212 static function localurle( $parser, $s = '', $arg = null ) {
213 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
214 if ( !is_string( $temp ) ) {
217 return htmlspecialchars( $temp );
221 static function fullurl( $parser, $s = '', $arg = null ) {
222 return self
::urlFunction( 'getFullURL', $s, $arg );
225 static function fullurle( $parser, $s = '', $arg = null ) {
226 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
227 if ( !is_string( $temp ) ) {
230 return htmlspecialchars( $temp );
234 static function canonicalurl( $parser, $s = '', $arg = null ) {
235 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
238 static function canonicalurle( $parser, $s = '', $arg = null ) {
239 return self
::urlFunction( 'escapeCanonicalURL', $s, $arg );
242 static function urlFunction( $func, $s = '', $arg = null ) {
243 $title = Title
::newFromText( $s );
244 # Due to order of execution of a lot of bits, the values might be encoded
245 # before arriving here; if that's true, then the title can't be created
246 # and the variable will fail. If we can't get a decent title from the first
247 # attempt, url-decode and try for a second.
248 if ( is_null( $title ) ) {
249 $title = Title
::newFromURL( urldecode( $s ) );
251 if ( !is_null( $title ) ) {
252 # Convert NS_MEDIA -> NS_FILE
253 if ( $title->getNamespace() == NS_MEDIA
) {
254 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
256 if ( !is_null( $arg ) ) {
257 $text = $title->$func( $arg );
259 $text = $title->$func();
263 return array( 'found' => false );
268 * @param $parser Parser
273 static function formatnum( $parser, $num = '', $arg = null ) {
274 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
275 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
276 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
277 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
279 $func = array( $parser->getFunctionLang(), 'formatNum' );
281 return $parser->markerSkipCallback( $num, $func );
285 * @param $parser Parser
286 * @param string $case
287 * @param string $word
290 static function grammar( $parser, $case = '', $word = '' ) {
291 $word = $parser->killMarkers( $word );
292 return $parser->getFunctionLang()->convertGrammar( $word, $case );
296 * @param $parser Parser
297 * @param $username string
300 static function gender( $parser, $username ) {
301 wfProfileIn( __METHOD__
);
302 $forms = array_slice( func_get_args(), 2 );
304 // Some shortcuts to avoid loading user data unnecessarily
305 if ( count( $forms ) === 0 ) {
306 wfProfileOut( __METHOD__
);
308 } elseif ( count( $forms ) === 1 ) {
309 wfProfileOut( __METHOD__
);
313 $username = trim( $username );
316 $gender = User
::getDefaultOption( 'gender' );
319 $title = Title
::newFromText( $username );
321 if ( $title && $title->getNamespace() == NS_USER
) {
322 $username = $title->getText();
325 // check parameter, or use the ParserOptions if in interface message
326 $user = User
::newFromName( $username );
328 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
329 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
330 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
332 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
333 wfProfileOut( __METHOD__
);
338 * @param $parser Parser
339 * @param string $text
342 static function plural( $parser, $text = '' ) {
343 $forms = array_slice( func_get_args(), 2 );
344 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
345 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
346 return $parser->getFunctionLang()->convertPlural( $text, $forms );
350 * Override the title of the page when viewed, provided we've been given a
351 * title which will normalise to the canonical title
353 * @param $parser Parser: parent parser
354 * @param string $text desired title text
357 static function displaytitle( $parser, $text = '' ) {
358 global $wgRestrictDisplayTitle;
360 // parse a limited subset of wiki markup (just the single quote items)
361 $text = $parser->doQuotes( $text );
363 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
364 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
365 . preg_quote( Parser
::MARKER_SUFFIX
, '/' ) . '/', '', $text );
367 // list of disallowed tags for DISPLAYTITLE
368 // these will be escaped even though they are allowed in normal wiki text
369 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
370 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
372 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
373 if ( $wgRestrictDisplayTitle ) {
374 $htmlTagsCallback = function ( &$params ) {
375 $decoded = Sanitizer
::decodeTagAttributes( $params );
377 if ( isset( $decoded['style'] ) ) {
378 // this is called later anyway, but we need it right now for the regexes below to be safe
379 // calling it twice doesn't hurt
380 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
382 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
383 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
387 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
390 $htmlTagsCallback = null;
393 // only requested titles that normalize to the actual title are allowed through
394 // if $wgRestrictDisplayTitle is true (it is by default)
395 // mimic the escaping process that occurs in OutputPage::setPageTitle
396 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $text, $htmlTagsCallback, array(), array(), $bad ) );
397 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
399 if ( !$wgRestrictDisplayTitle ) {
400 $parser->mOutput
->setDisplayTitle( $text );
401 } elseif ( $title instanceof Title
&& !$title->hasFragment() && $title->equals( $parser->mTitle
) ) {
402 $parser->mOutput
->setDisplayTitle( $text );
409 * Matches the given value against the value of given magic word
411 * @param string $magicword magic word key
412 * @param mixed $value value to match
413 * @return boolean true on successful match
415 private static function matchAgainstMagicword( $magicword, $value ) {
416 $value = trim( strval( $value ) );
417 if ( $value === '' ) {
420 $mwObject = MagicWord
::get( $magicword );
421 return $mwObject->matchStartToEnd( $value );
424 static function formatRaw( $num, $raw ) {
425 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
429 return $wgContLang->formatNum( $num );
432 static function numberofpages( $parser, $raw = null ) {
433 return self
::formatRaw( SiteStats
::pages(), $raw );
435 static function numberofusers( $parser, $raw = null ) {
436 return self
::formatRaw( SiteStats
::users(), $raw );
438 static function numberofactiveusers( $parser, $raw = null ) {
439 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
441 static function numberofarticles( $parser, $raw = null ) {
442 return self
::formatRaw( SiteStats
::articles(), $raw );
444 static function numberoffiles( $parser, $raw = null ) {
445 return self
::formatRaw( SiteStats
::images(), $raw );
447 static function numberofadmins( $parser, $raw = null ) {
448 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
450 static function numberofedits( $parser, $raw = null ) {
451 return self
::formatRaw( SiteStats
::edits(), $raw );
453 static function numberofviews( $parser, $raw = null ) {
454 global $wgDisableCounters;
455 return !$wgDisableCounters ? self
::formatRaw( SiteStats
::views(), $raw ) : '';
457 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
458 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
460 static function numberingroup( $parser, $name = '', $raw = null ) {
461 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
465 * Given a title, return the namespace name that would be given by the
466 * corresponding magic word
467 * Note: function name changed to "mwnamespace" rather than "namespace"
468 * to not break PHP 5.3
469 * @return mixed|string
471 static function mwnamespace( $parser, $title = null ) {
472 $t = Title
::newFromText( $title );
473 if ( is_null( $t ) ) {
476 return str_replace( '_', ' ', $t->getNsText() );
478 static function namespacee( $parser, $title = null ) {
479 $t = Title
::newFromText( $title );
480 if ( is_null( $t ) ) {
483 return wfUrlencode( $t->getNsText() );
485 static function namespacenumber( $parser, $title = null ) {
486 $t = Title
::newFromText( $title );
487 if ( is_null( $t ) ) {
490 return $t->getNamespace();
492 static function talkspace( $parser, $title = null ) {
493 $t = Title
::newFromText( $title );
494 if ( is_null( $t ) ||
!$t->canTalk() ) {
497 return str_replace( '_', ' ', $t->getTalkNsText() );
499 static function talkspacee( $parser, $title = null ) {
500 $t = Title
::newFromText( $title );
501 if ( is_null( $t ) ||
!$t->canTalk() ) {
504 return wfUrlencode( $t->getTalkNsText() );
506 static function subjectspace( $parser, $title = null ) {
507 $t = Title
::newFromText( $title );
508 if ( is_null( $t ) ) {
511 return str_replace( '_', ' ', $t->getSubjectNsText() );
513 static function subjectspacee( $parser, $title = null ) {
514 $t = Title
::newFromText( $title );
515 if ( is_null( $t ) ) {
518 return wfUrlencode( $t->getSubjectNsText() );
522 * Functions to get and normalize pagenames, corresponding to the magic words
526 static function pagename( $parser, $title = null ) {
527 $t = Title
::newFromText( $title );
528 if ( is_null( $t ) ) {
531 return wfEscapeWikiText( $t->getText() );
533 static function pagenamee( $parser, $title = null ) {
534 $t = Title
::newFromText( $title );
535 if ( is_null( $t ) ) {
538 return wfEscapeWikiText( $t->getPartialURL() );
540 static function fullpagename( $parser, $title = null ) {
541 $t = Title
::newFromText( $title );
542 if ( is_null( $t ) ||
!$t->canTalk() ) {
545 return wfEscapeWikiText( $t->getPrefixedText() );
547 static function fullpagenamee( $parser, $title = null ) {
548 $t = Title
::newFromText( $title );
549 if ( is_null( $t ) ||
!$t->canTalk() ) {
552 return wfEscapeWikiText( $t->getPrefixedURL() );
554 static function subpagename( $parser, $title = null ) {
555 $t = Title
::newFromText( $title );
556 if ( is_null( $t ) ) {
559 return wfEscapeWikiText( $t->getSubpageText() );
561 static function subpagenamee( $parser, $title = null ) {
562 $t = Title
::newFromText( $title );
563 if ( is_null( $t ) ) {
566 return wfEscapeWikiText( $t->getSubpageUrlForm() );
568 static function rootpagename( $parser, $title = null ) {
569 $t = Title
::newFromText( $title );
570 if ( is_null( $t ) ) {
573 return wfEscapeWikiText( $t->getRootText() );
575 static function rootpagenamee( $parser, $title = null ) {
576 $t = Title
::newFromText( $title );
577 if ( is_null( $t ) ) {
580 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
582 static function basepagename( $parser, $title = null ) {
583 $t = Title
::newFromText( $title );
584 if ( is_null( $t ) ) {
587 return wfEscapeWikiText( $t->getBaseText() );
589 static function basepagenamee( $parser, $title = null ) {
590 $t = Title
::newFromText( $title );
591 if ( is_null( $t ) ) {
594 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
596 static function talkpagename( $parser, $title = null ) {
597 $t = Title
::newFromText( $title );
598 if ( is_null( $t ) ||
!$t->canTalk() ) {
601 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
603 static function talkpagenamee( $parser, $title = null ) {
604 $t = Title
::newFromText( $title );
605 if ( is_null( $t ) ||
!$t->canTalk() ) {
608 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
610 static function subjectpagename( $parser, $title = null ) {
611 $t = Title
::newFromText( $title );
612 if ( is_null( $t ) ) {
615 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
617 static function subjectpagenamee( $parser, $title = null ) {
618 $t = Title
::newFromText( $title );
619 if ( is_null( $t ) ) {
622 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
626 * Return the number of pages, files or subcats in the given category,
627 * or 0 if it's nonexistent. This is an expensive parser function and
628 * can't be called too many times per page.
631 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
633 static $magicWords = null;
634 if ( is_null( $magicWords ) ) {
635 $magicWords = new MagicWordArray( array(
636 'pagesincategory_all',
637 'pagesincategory_pages',
638 'pagesincategory_subcats',
639 'pagesincategory_files'
642 static $cache = array();
644 // split the given option to its variable
645 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
646 //{{pagesincategory:|raw[|type]}}
648 $type = $magicWords->matchStartToEnd( $arg2 );
650 //{{pagesincategory:[|type[|raw]]}}
651 $type = $magicWords->matchStartToEnd( $arg1 );
654 if ( !$type ) { //backward compatibility
655 $type = 'pagesincategory_all';
658 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
659 if ( !$title ) { # invalid title
660 return self
::formatRaw( 0, $raw );
662 $wgContLang->findVariantLink( $name, $title, true );
664 // Normalize name for cache
665 $name = $title->getDBkey();
667 if ( !isset( $cache[$name] ) ) {
668 $category = Category
::newFromTitle( $title );
670 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
671 if ( $parser->incrementExpensiveFunctionCount() ) {
672 // $allCount is the total number of cat members,
673 // not the count of how many members are normal pages.
674 $allCount = (int)$category->getPageCount();
675 $subcatCount = (int)$category->getSubcatCount();
676 $fileCount = (int)$category->getFileCount();
677 $pagesCount = $allCount - $subcatCount - $fileCount;
679 $cache[$name]['pagesincategory_all'] = $allCount;
680 $cache[$name]['pagesincategory_pages'] = $pagesCount;
681 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
682 $cache[$name]['pagesincategory_files'] = $fileCount;
685 $count = $cache[$name][$type];
686 return self
::formatRaw( $count, $raw );
690 * Return the size of the given page, or 0 if it's nonexistent. This is an
691 * expensive parser function and can't be called too many times per page.
693 * @param $parser Parser
694 * @param $page String Name of page to check (Default: empty string)
695 * @param $raw String Should number be human readable with commas or just number
698 static function pagesize( $parser, $page = '', $raw = null ) {
699 $title = Title
::newFromText( $page );
701 if ( !is_object( $title ) ) {
702 return self
::formatRaw( 0, $raw );
705 // fetch revision from cache/database and return the value
706 $rev = self
::getCachedRevisionObject( $parser, $title );
707 $length = $rev ?
$rev->getSize() : 0;
708 return self
::formatRaw( $length, $raw );
712 * Returns the requested protection level for the current page. This
713 * is an expensive parser function and can't be called too many times
714 * per page, unless the protection levels for the given title have
715 * already been retrieved
717 * @param Parser $parser
718 * @param string $type
719 * @param string $title
723 static function protectionlevel( $parser, $type = '', $title = '' ) {
724 $titleObject = Title
::newFromText( $title );
725 if ( !( $titleObject instanceof Title
) ) {
726 $titleObject = $parser->mTitle
;
728 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
729 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
730 # Title::getRestrictions returns an array, its possible it may have
731 # multiple values in the future
732 return implode( $restrictions, ',' );
738 * Gives language names.
739 * @param $parser Parser
740 * @param string $code Language code (of which to get name)
741 * @param string $inLanguage Language code (in which to get name)
744 static function language( $parser, $code = '', $inLanguage = '' ) {
745 $code = strtolower( $code );
746 $inLanguage = strtolower( $inLanguage );
747 $lang = Language
::fetchLanguageName( $code, $inLanguage );
748 return $lang !== '' ?
$lang : wfBCP47( $code );
752 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
755 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
756 $padding = $parser->killMarkers( $padding );
757 $lengthOfPadding = mb_strlen( $padding );
758 if ( $lengthOfPadding == 0 ) {
762 # The remaining length to add counts down to 0 as padding is added
763 $length = min( $length, 500 ) - mb_strlen( $string );
764 # $finalPadding is just $padding repeated enough times so that
765 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
767 while ( $length > 0 ) {
768 # If $length < $lengthofPadding, truncate $padding so we get the
769 # exact length desired.
770 $finalPadding .= mb_substr( $padding, 0, $length );
771 $length -= $lengthOfPadding;
774 if ( $direction == STR_PAD_LEFT
) {
775 return $finalPadding . $string;
777 return $string . $finalPadding;
781 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
782 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
785 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
786 return self
::pad( $parser, $string, $length, $padding );
790 * @param $parser Parser
794 static function anchorencode( $parser, $text ) {
795 $text = $parser->killMarkers( $text );
796 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
799 static function special( $parser, $text ) {
800 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
802 $title = SpecialPage
::getTitleFor( $page, $subpage );
803 return $title->getPrefixedText();
805 // unknown special page, just use the given text as its title, if at all possible
806 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
807 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
811 static function speciale( $parser, $text ) {
812 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
816 * @param $parser Parser
817 * @param string $text The sortkey to use
818 * @param string $uarg Either "noreplace" or "noerror" (in en)
819 * both suppress errors, and noreplace does nothing if
820 * a default sortkey already exists.
823 public static function defaultsort( $parser, $text, $uarg = '' ) {
824 static $magicWords = null;
825 if ( is_null( $magicWords ) ) {
826 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
828 $arg = $magicWords->matchStartToEnd( $uarg );
830 $text = trim( $text );
831 if ( strlen( $text ) == 0 ) {
834 $old = $parser->getCustomDefaultSort();
835 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
836 $parser->setDefaultSort( $text );
839 if ( $old === false ||
$old == $text ||
$arg ) {
842 $converter = $parser->getConverterLanguage()->getConverter();
843 return '<span class="error">' .
844 wfMessage( 'duplicate-defaultsort',
845 // Message should be parsed, but these params should only be escaped.
846 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
847 $converter->markNoConversion( wfEscapeWikiText( $text ) )
848 )->inContentLanguage()->text() .
853 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
854 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
855 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
856 $file = wfFindFile( $name );
858 if ( $argA == 'nowiki' ) {
859 // {{filepath: | option [| size] }}
861 $parsedWidthParam = $parser->parseWidthParam( $argB );
863 // {{filepath: [| size [|option]] }}
864 $parsedWidthParam = $parser->parseWidthParam( $argA );
865 $isNowiki = ( $argB == 'nowiki' );
869 $url = $file->getFullUrl();
871 // If a size is requested...
872 if ( count( $parsedWidthParam ) ) {
873 $mto = $file->transform( $parsedWidthParam );
875 if ( $mto && !$mto->isError() ) {
876 // ... change the URL to point to a thumbnail.
877 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
881 return array( $url, 'nowiki' => true );
890 * Parser function to extension tag adaptor
893 public static function tagObj( $parser, $frame, $args ) {
894 if ( !count( $args ) ) {
897 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
899 if ( count( $args ) ) {
900 $inner = $frame->expand( array_shift( $args ) );
905 $stripList = $parser->getStripList();
906 if ( !in_array( $tagName, $stripList ) ) {
907 return '<span class="error">' .
908 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
912 $attributes = array();
913 foreach ( $args as $arg ) {
914 $bits = $arg->splitArg();
915 if ( strval( $bits['index'] ) === '' ) {
916 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
917 $value = trim( $frame->expand( $bits['value'] ) );
918 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
919 $value = isset( $m[1] ) ?
$m[1] : '';
921 $attributes[$name] = $value;
928 'attributes' => $attributes,
929 'close' => "</$tagName>",
931 return $parser->extensionSubstitution( $params, $frame );
935 * Fetched the current revision of the given title and return this.
936 * Will increment the expensive function count and
937 * add a template link to get the value refreshed on changes.
938 * For a given title, which is equal to the current parser title,
939 * the revision object from the parser is used, when that is the current one
941 * @param $parser Parser
942 * @param $title Title
946 private static function getCachedRevisionObject( $parser, $title = null ) {
947 static $cache = array();
949 if ( is_null( $title ) ) {
953 // Use the revision from the parser itself, when param is the current page
954 // and the revision is the current one
955 if ( $title->equals( $parser->getTitle() ) ) {
956 $parserRev = $parser->getRevisionObject();
957 if ( $parserRev && $parserRev->isCurrent() ) {
958 // force reparse after edit with vary-revision flag
959 $parser->getOutput()->setFlag( 'vary-revision' );
960 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
965 // Normalize name for cache
966 $page = $title->getPrefixedDBkey();
968 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
969 return $cache[$page];
971 if ( $parser->incrementExpensiveFunctionCount() ) {
972 $rev = Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
973 $pageID = $rev ?
$rev->getPage() : 0;
974 $revID = $rev ?
$rev->getId() : 0;
975 $cache[$page] = $rev; // maybe null
977 // Register dependency in templatelinks
978 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
982 $cache[$page] = null;
987 * Get the pageid of a specified page
988 * @param $parser Parser
989 * @param $title string Title to get the pageid from
992 public static function pageid( $parser, $title = null ) {
993 $t = Title
::newFromText( $title );
994 if ( is_null( $t ) ) {
997 // Use title from parser to have correct pageid after edit
998 if ( $t->equals( $parser->getTitle() ) ) {
999 $t = $parser->getTitle();
1000 return $t->getArticleID();
1003 // These can't have ids
1004 if ( !$t->canExist() ||
$t->isExternal() ) {
1008 // Check the link cache, maybe something already looked it up.
1009 $linkCache = LinkCache
::singleton();
1010 $pdbk = $t->getPrefixedDBkey();
1011 $id = $linkCache->getGoodLinkID( $pdbk );
1013 $parser->mOutput
->addLink( $t, $id );
1016 if ( $linkCache->isBadLink( $pdbk ) ) {
1017 $parser->mOutput
->addLink( $t, 0 );
1021 // We need to load it from the DB, so mark expensive
1022 if ( $parser->incrementExpensiveFunctionCount() ) {
1023 $id = $t->getArticleID();
1024 $parser->mOutput
->addLink( $t, $id );
1031 * Get the id from the last revision of a specified page.
1032 * @param $parser Parser
1033 * @param $title string Title to get the id from
1036 public static function revisionid( $parser, $title = null ) {
1037 $t = Title
::newFromText( $title );
1038 if ( is_null( $t ) ) {
1041 // fetch revision from cache/database and return the value
1042 $rev = self
::getCachedRevisionObject( $parser, $t );
1043 return $rev ?
$rev->getId() : '';
1047 * Get the day from the last revision of a specified page.
1048 * @param $parser Parser
1049 * @param $title string Title to get the day from
1052 public static function revisionday( $parser, $title = null ) {
1053 $t = Title
::newFromText( $title );
1054 if ( is_null( $t ) ) {
1057 // fetch revision from cache/database and return the value
1058 $rev = self
::getCachedRevisionObject( $parser, $t );
1059 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1063 * Get the day with leading zeros from the last revision of a specified page.
1064 * @param $parser Parser
1065 * @param $title string Title to get the day from
1068 public static function revisionday2( $parser, $title = null ) {
1069 $t = Title
::newFromText( $title );
1070 if ( is_null( $t ) ) {
1073 // fetch revision from cache/database and return the value
1074 $rev = self
::getCachedRevisionObject( $parser, $t );
1075 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1079 * Get the month with leading zeros from the last revision of a specified page.
1080 * @param $parser Parser
1081 * @param $title string Title to get the month from
1084 public static function revisionmonth( $parser, $title = null ) {
1085 $t = Title
::newFromText( $title );
1086 if ( is_null( $t ) ) {
1089 // fetch revision from cache/database and return the value
1090 $rev = self
::getCachedRevisionObject( $parser, $t );
1091 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1095 * Get the month from the last revision of a specified page.
1096 * @param $parser Parser
1097 * @param $title string Title to get the month from
1100 public static function revisionmonth1( $parser, $title = null ) {
1101 $t = Title
::newFromText( $title );
1102 if ( is_null( $t ) ) {
1105 // fetch revision from cache/database and return the value
1106 $rev = self
::getCachedRevisionObject( $parser, $t );
1107 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1111 * Get the year from the last revision of a specified page.
1112 * @param $parser Parser
1113 * @param $title string Title to get the year from
1116 public static function revisionyear( $parser, $title = null ) {
1117 $t = Title
::newFromText( $title );
1118 if ( is_null( $t ) ) {
1121 // fetch revision from cache/database and return the value
1122 $rev = self
::getCachedRevisionObject( $parser, $t );
1123 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1127 * Get the timestamp from the last revision of a specified page.
1128 * @param $parser Parser
1129 * @param $title string Title to get the timestamp from
1132 public static function revisiontimestamp( $parser, $title = null ) {
1133 $t = Title
::newFromText( $title );
1134 if ( is_null( $t ) ) {
1137 // fetch revision from cache/database and return the value
1138 $rev = self
::getCachedRevisionObject( $parser, $t );
1139 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1143 * Get the user from the last revision of a specified page.
1144 * @param $parser Parser
1145 * @param $title string Title to get the user from
1148 public static function revisionuser( $parser, $title = null ) {
1149 $t = Title
::newFromText( $title );
1150 if ( is_null( $t ) ) {
1153 // fetch revision from cache/database and return the value
1154 $rev = self
::getCachedRevisionObject( $parser, $t );
1155 return $rev ?
$rev->getUserText() : '';
1159 * Returns the sources of any cascading protection acting on a specified page.
1160 * Pages will not return their own title unless they transclude themselves.
1161 * This is an expensive parser function and can't be called too many times per page,
1162 * unless cascading protection sources for the page have already been loaded.
1164 * @param Parser $parser
1165 * @param string $title
1170 public static function cascadingsources( $parser, $title = '' ) {
1171 $titleObject = Title
::newFromText( $title );
1172 if ( !( $titleObject instanceof Title
) ) {
1173 $titleObject = $parser->mTitle
;
1175 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1176 ||
$parser->incrementExpensiveFunctionCount()
1179 $sources = $titleObject->getCascadeProtectionSources();
1180 foreach ( $sources[0] as $sourceTitle ) {
1181 $names[] = $sourceTitle->getPrefixedText();
1183 return implode( $names, '|' );