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(
76 array( __CLASS__
, 'pagesinnamespace' ),
83 * @param Parser $parser
84 * @param string $part1
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 );
95 return array( 'found' => false );
100 * @param Parser $parser
101 * @param string $date
102 * @param string $defaultPref
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' ) );
124 static function ns( $parser, $part1 = '' ) {
126 if ( intval( $part1 ) ||
$part1 == "0" ) {
127 $index = intval( $part1 );
129 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
131 if ( $index !== false ) {
132 return $wgContLang->getFormattedNsText( $index );
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 ) );
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.
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 ' '.
167 $func = 'wfUrlencode';
168 $s = str_replace( ' ', '_', $s );
171 // Encode for an HTTP Path, '%20' for ' '.
173 $func = 'rawurlencode';
176 // Encode for HTTP query, '+' for ' '.
181 return $parser->markerSkipCallback( $s, $func );
184 static function lcfirst( $parser, $s = '' ) {
186 return $wgContLang->lcfirst( $s );
189 static function ucfirst( $parser, $s = '' ) {
191 return $wgContLang->ucfirst( $s );
195 * @param Parser $parser
199 static function lc( $parser, $s = '' ) {
201 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
205 * @param Parser $parser
209 static function uc( $parser, $s = '' ) {
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 ) ) {
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 ) ) {
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 );
265 $text = $title->$func();
269 return array( 'found' => false );
274 * @param Parser $parser
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' );
285 $func = array( $parser->getFunctionLang(), 'formatNum' );
287 return $parser->markerSkipCallback( $num, $func );
291 * @param Parser $parser
292 * @param string $case
293 * @param string $word
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
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__
);
314 } elseif ( count( $forms ) === 1 ) {
315 wfProfileOut( __METHOD__
);
319 $username = trim( $username );
322 $gender = User
::getDefaultOption( 'gender' );
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 );
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__
);
344 * @param Parser $parser
345 * @param string $text
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
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 );
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(
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 );
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 === '' ) {
435 $mwObject = MagicWord
::get( $magicword );
436 return $mwObject->matchStartToEnd( $value );
439 static function formatRaw( $num, $raw ) {
440 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
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 * @return mixed|string
486 static function mwnamespace( $parser, $title = null ) {
487 $t = Title
::newFromText( $title );
488 if ( is_null( $t ) ) {
491 return str_replace( '_', ' ', $t->getNsText() );
493 static function namespacee( $parser, $title = null ) {
494 $t = Title
::newFromText( $title );
495 if ( is_null( $t ) ) {
498 return wfUrlencode( $t->getNsText() );
500 static function namespacenumber( $parser, $title = null ) {
501 $t = Title
::newFromText( $title );
502 if ( is_null( $t ) ) {
505 return $t->getNamespace();
507 static function talkspace( $parser, $title = null ) {
508 $t = Title
::newFromText( $title );
509 if ( is_null( $t ) ||
!$t->canTalk() ) {
512 return str_replace( '_', ' ', $t->getTalkNsText() );
514 static function talkspacee( $parser, $title = null ) {
515 $t = Title
::newFromText( $title );
516 if ( is_null( $t ) ||
!$t->canTalk() ) {
519 return wfUrlencode( $t->getTalkNsText() );
521 static function subjectspace( $parser, $title = null ) {
522 $t = Title
::newFromText( $title );
523 if ( is_null( $t ) ) {
526 return str_replace( '_', ' ', $t->getSubjectNsText() );
528 static function subjectspacee( $parser, $title = null ) {
529 $t = Title
::newFromText( $title );
530 if ( is_null( $t ) ) {
533 return wfUrlencode( $t->getSubjectNsText() );
537 * Functions to get and normalize pagenames, corresponding to the magic words
541 static function pagename( $parser, $title = null ) {
542 $t = Title
::newFromText( $title );
543 if ( is_null( $t ) ) {
546 return wfEscapeWikiText( $t->getText() );
548 static function pagenamee( $parser, $title = null ) {
549 $t = Title
::newFromText( $title );
550 if ( is_null( $t ) ) {
553 return wfEscapeWikiText( $t->getPartialURL() );
555 static function fullpagename( $parser, $title = null ) {
556 $t = Title
::newFromText( $title );
557 if ( is_null( $t ) ||
!$t->canTalk() ) {
560 return wfEscapeWikiText( $t->getPrefixedText() );
562 static function fullpagenamee( $parser, $title = null ) {
563 $t = Title
::newFromText( $title );
564 if ( is_null( $t ) ||
!$t->canTalk() ) {
567 return wfEscapeWikiText( $t->getPrefixedURL() );
569 static function subpagename( $parser, $title = null ) {
570 $t = Title
::newFromText( $title );
571 if ( is_null( $t ) ) {
574 return wfEscapeWikiText( $t->getSubpageText() );
576 static function subpagenamee( $parser, $title = null ) {
577 $t = Title
::newFromText( $title );
578 if ( is_null( $t ) ) {
581 return wfEscapeWikiText( $t->getSubpageUrlForm() );
583 static function rootpagename( $parser, $title = null ) {
584 $t = Title
::newFromText( $title );
585 if ( is_null( $t ) ) {
588 return wfEscapeWikiText( $t->getRootText() );
590 static function rootpagenamee( $parser, $title = null ) {
591 $t = Title
::newFromText( $title );
592 if ( is_null( $t ) ) {
595 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
597 static function basepagename( $parser, $title = null ) {
598 $t = Title
::newFromText( $title );
599 if ( is_null( $t ) ) {
602 return wfEscapeWikiText( $t->getBaseText() );
604 static function basepagenamee( $parser, $title = null ) {
605 $t = Title
::newFromText( $title );
606 if ( is_null( $t ) ) {
609 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
611 static function talkpagename( $parser, $title = null ) {
612 $t = Title
::newFromText( $title );
613 if ( is_null( $t ) ||
!$t->canTalk() ) {
616 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
618 static function talkpagenamee( $parser, $title = null ) {
619 $t = Title
::newFromText( $title );
620 if ( is_null( $t ) ||
!$t->canTalk() ) {
623 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
625 static function subjectpagename( $parser, $title = null ) {
626 $t = Title
::newFromText( $title );
627 if ( is_null( $t ) ) {
630 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
632 static function subjectpagenamee( $parser, $title = null ) {
633 $t = Title
::newFromText( $title );
634 if ( is_null( $t ) ) {
637 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
641 * Return the number of pages, files or subcats in the given category,
642 * or 0 if it's nonexistent. This is an expensive parser function and
643 * can't be called too many times per page.
646 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
648 static $magicWords = null;
649 if ( is_null( $magicWords ) ) {
650 $magicWords = new MagicWordArray( array(
651 'pagesincategory_all',
652 'pagesincategory_pages',
653 'pagesincategory_subcats',
654 'pagesincategory_files'
657 static $cache = array();
659 // split the given option to its variable
660 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
661 //{{pagesincategory:|raw[|type]}}
663 $type = $magicWords->matchStartToEnd( $arg2 );
665 //{{pagesincategory:[|type[|raw]]}}
666 $type = $magicWords->matchStartToEnd( $arg1 );
669 if ( !$type ) { //backward compatibility
670 $type = 'pagesincategory_all';
673 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
674 if ( !$title ) { # invalid title
675 return self
::formatRaw( 0, $raw );
677 $wgContLang->findVariantLink( $name, $title, true );
679 // Normalize name for cache
680 $name = $title->getDBkey();
682 if ( !isset( $cache[$name] ) ) {
683 $category = Category
::newFromTitle( $title );
685 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
686 if ( $parser->incrementExpensiveFunctionCount() ) {
687 // $allCount is the total number of cat members,
688 // not the count of how many members are normal pages.
689 $allCount = (int)$category->getPageCount();
690 $subcatCount = (int)$category->getSubcatCount();
691 $fileCount = (int)$category->getFileCount();
692 $pagesCount = $allCount - $subcatCount - $fileCount;
694 $cache[$name]['pagesincategory_all'] = $allCount;
695 $cache[$name]['pagesincategory_pages'] = $pagesCount;
696 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
697 $cache[$name]['pagesincategory_files'] = $fileCount;
700 $count = $cache[$name][$type];
701 return self
::formatRaw( $count, $raw );
705 * Return the size of the given page, or 0 if it's nonexistent. This is an
706 * expensive parser function and can't be called too many times per page.
708 * @param Parser $parser
709 * @param string $page Name of page to check (Default: empty string)
710 * @param string $raw Should number be human readable with commas or just number
713 static function pagesize( $parser, $page = '', $raw = null ) {
714 $title = Title
::newFromText( $page );
716 if ( !is_object( $title ) ) {
717 return self
::formatRaw( 0, $raw );
720 // fetch revision from cache/database and return the value
721 $rev = self
::getCachedRevisionObject( $parser, $title );
722 $length = $rev ?
$rev->getSize() : 0;
723 return self
::formatRaw( $length, $raw );
727 * Returns the requested protection level for the current page. This
728 * is an expensive parser function and can't be called too many times
729 * per page, unless the protection levels for the given title have
730 * already been retrieved
732 * @param Parser $parser
733 * @param string $type
734 * @param string $title
738 static function protectionlevel( $parser, $type = '', $title = '' ) {
739 $titleObject = Title
::newFromText( $title );
740 if ( !( $titleObject instanceof Title
) ) {
741 $titleObject = $parser->mTitle
;
743 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
744 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
745 # Title::getRestrictions returns an array, its possible it may have
746 # multiple values in the future
747 return implode( $restrictions, ',' );
753 * Gives language names.
754 * @param Parser $parser
755 * @param string $code Language code (of which to get name)
756 * @param string $inLanguage Language code (in which to get name)
759 static function language( $parser, $code = '', $inLanguage = '' ) {
760 $code = strtolower( $code );
761 $inLanguage = strtolower( $inLanguage );
762 $lang = Language
::fetchLanguageName( $code, $inLanguage );
763 return $lang !== '' ?
$lang : wfBCP47( $code );
767 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
768 * @param Parser $parser
769 * @param string $string
771 * @param string $padding
772 * @param int $direction
775 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
776 $padding = $parser->killMarkers( $padding );
777 $lengthOfPadding = mb_strlen( $padding );
778 if ( $lengthOfPadding == 0 ) {
782 # The remaining length to add counts down to 0 as padding is added
783 $length = min( $length, 500 ) - mb_strlen( $string );
784 # $finalPadding is just $padding repeated enough times so that
785 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
787 while ( $length > 0 ) {
788 # If $length < $lengthofPadding, truncate $padding so we get the
789 # exact length desired.
790 $finalPadding .= mb_substr( $padding, 0, $length );
791 $length -= $lengthOfPadding;
794 if ( $direction == STR_PAD_LEFT
) {
795 return $finalPadding . $string;
797 return $string . $finalPadding;
801 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
802 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
805 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
806 return self
::pad( $parser, $string, $length, $padding );
810 * @param Parser $parser
811 * @param string $text
814 static function anchorencode( $parser, $text ) {
815 $text = $parser->killMarkers( $text );
816 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
819 static function special( $parser, $text ) {
820 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
822 $title = SpecialPage
::getTitleFor( $page, $subpage );
823 return $title->getPrefixedText();
825 // unknown special page, just use the given text as its title, if at all possible
826 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
827 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
831 static function speciale( $parser, $text ) {
832 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
836 * @param Parser $parser
837 * @param string $text The sortkey to use
838 * @param string $uarg Either "noreplace" or "noerror" (in en)
839 * both suppress errors, and noreplace does nothing if
840 * a default sortkey already exists.
843 public static function defaultsort( $parser, $text, $uarg = '' ) {
844 static $magicWords = null;
845 if ( is_null( $magicWords ) ) {
846 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
848 $arg = $magicWords->matchStartToEnd( $uarg );
850 $text = trim( $text );
851 if ( strlen( $text ) == 0 ) {
854 $old = $parser->getCustomDefaultSort();
855 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
856 $parser->setDefaultSort( $text );
859 if ( $old === false ||
$old == $text ||
$arg ) {
862 $converter = $parser->getConverterLanguage()->getConverter();
863 return '<span class="error">' .
864 wfMessage( 'duplicate-defaultsort',
865 // Message should be parsed, but these params should only be escaped.
866 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
867 $converter->markNoConversion( wfEscapeWikiText( $text ) )
868 )->inContentLanguage()->text() .
873 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
874 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
875 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
876 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
877 $file = wfFindFile( $name );
879 if ( $argA == 'nowiki' ) {
880 // {{filepath: | option [| size] }}
882 $parsedWidthParam = $parser->parseWidthParam( $argB );
884 // {{filepath: [| size [|option]] }}
885 $parsedWidthParam = $parser->parseWidthParam( $argA );
886 $isNowiki = ( $argB == 'nowiki' );
890 $url = $file->getFullUrl();
892 // If a size is requested...
893 if ( count( $parsedWidthParam ) ) {
894 $mto = $file->transform( $parsedWidthParam );
896 if ( $mto && !$mto->isError() ) {
897 // ... change the URL to point to a thumbnail.
898 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
902 return array( $url, 'nowiki' => true );
911 * Parser function to extension tag adaptor
912 * @param Parser $parser
913 * @param PPFrame $frame
917 public static function tagObj( $parser, $frame, $args ) {
918 if ( !count( $args ) ) {
921 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
923 if ( count( $args ) ) {
924 $inner = $frame->expand( array_shift( $args ) );
929 $stripList = $parser->getStripList();
930 if ( !in_array( $tagName, $stripList ) ) {
931 return '<span class="error">' .
932 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
936 $attributes = array();
937 foreach ( $args as $arg ) {
938 $bits = $arg->splitArg();
939 if ( strval( $bits['index'] ) === '' ) {
940 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
941 $value = trim( $frame->expand( $bits['value'] ) );
942 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
943 $value = isset( $m[1] ) ?
$m[1] : '';
945 $attributes[$name] = $value;
952 'attributes' => $attributes,
953 'close' => "</$tagName>",
955 return $parser->extensionSubstitution( $params, $frame );
959 * Fetched the current revision of the given title and return this.
960 * Will increment the expensive function count and
961 * add a template link to get the value refreshed on changes.
962 * For a given title, which is equal to the current parser title,
963 * the revision object from the parser is used, when that is the current one
965 * @param Parser $parser
966 * @param Title $title
970 private static function getCachedRevisionObject( $parser, $title = null ) {
971 static $cache = array();
973 if ( is_null( $title ) ) {
977 // Use the revision from the parser itself, when param is the current page
978 // and the revision is the current one
979 if ( $title->equals( $parser->getTitle() ) ) {
980 $parserRev = $parser->getRevisionObject();
981 if ( $parserRev && $parserRev->isCurrent() ) {
982 // force reparse after edit with vary-revision flag
983 $parser->getOutput()->setFlag( 'vary-revision' );
984 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
989 // Normalize name for cache
990 $page = $title->getPrefixedDBkey();
992 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
993 return $cache[$page];
995 if ( $parser->incrementExpensiveFunctionCount() ) {
996 $rev = Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
997 $pageID = $rev ?
$rev->getPage() : 0;
998 $revID = $rev ?
$rev->getId() : 0;
999 $cache[$page] = $rev; // maybe null
1001 // Register dependency in templatelinks
1002 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1006 $cache[$page] = null;
1011 * Get the pageid of a specified page
1012 * @param Parser $parser
1013 * @param string $title Title to get the pageid from
1016 public static function pageid( $parser, $title = null ) {
1017 $t = Title
::newFromText( $title );
1018 if ( is_null( $t ) ) {
1021 // Use title from parser to have correct pageid after edit
1022 if ( $t->equals( $parser->getTitle() ) ) {
1023 $t = $parser->getTitle();
1024 return $t->getArticleID();
1027 // These can't have ids
1028 if ( !$t->canExist() ||
$t->isExternal() ) {
1032 // Check the link cache, maybe something already looked it up.
1033 $linkCache = LinkCache
::singleton();
1034 $pdbk = $t->getPrefixedDBkey();
1035 $id = $linkCache->getGoodLinkID( $pdbk );
1037 $parser->mOutput
->addLink( $t, $id );
1040 if ( $linkCache->isBadLink( $pdbk ) ) {
1041 $parser->mOutput
->addLink( $t, 0 );
1045 // We need to load it from the DB, so mark expensive
1046 if ( $parser->incrementExpensiveFunctionCount() ) {
1047 $id = $t->getArticleID();
1048 $parser->mOutput
->addLink( $t, $id );
1055 * Get the id from the last revision of a specified page.
1056 * @param Parser $parser
1057 * @param string $title Title to get the id from
1060 public static function revisionid( $parser, $title = null ) {
1061 $t = Title
::newFromText( $title );
1062 if ( is_null( $t ) ) {
1065 // fetch revision from cache/database and return the value
1066 $rev = self
::getCachedRevisionObject( $parser, $t );
1067 return $rev ?
$rev->getId() : '';
1071 * Get the day from the last revision of a specified page.
1072 * @param Parser $parser
1073 * @param string $title Title to get the day from
1076 public static function revisionday( $parser, $title = null ) {
1077 $t = Title
::newFromText( $title );
1078 if ( is_null( $t ) ) {
1081 // fetch revision from cache/database and return the value
1082 $rev = self
::getCachedRevisionObject( $parser, $t );
1083 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1087 * Get the day with leading zeros from the last revision of a specified page.
1088 * @param Parser $parser
1089 * @param string $title Title to get the day from
1092 public static function revisionday2( $parser, $title = null ) {
1093 $t = Title
::newFromText( $title );
1094 if ( is_null( $t ) ) {
1097 // fetch revision from cache/database and return the value
1098 $rev = self
::getCachedRevisionObject( $parser, $t );
1099 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1103 * Get the month with leading zeros from the last revision of a specified page.
1104 * @param Parser $parser
1105 * @param string $title Title to get the month from
1108 public static function revisionmonth( $parser, $title = null ) {
1109 $t = Title
::newFromText( $title );
1110 if ( is_null( $t ) ) {
1113 // fetch revision from cache/database and return the value
1114 $rev = self
::getCachedRevisionObject( $parser, $t );
1115 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1119 * Get the month from the last revision of a specified page.
1120 * @param Parser $parser
1121 * @param string $title Title to get the month from
1124 public static function revisionmonth1( $parser, $title = null ) {
1125 $t = Title
::newFromText( $title );
1126 if ( is_null( $t ) ) {
1129 // fetch revision from cache/database and return the value
1130 $rev = self
::getCachedRevisionObject( $parser, $t );
1131 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1135 * Get the year from the last revision of a specified page.
1136 * @param Parser $parser
1137 * @param string $title Title to get the year from
1140 public static function revisionyear( $parser, $title = null ) {
1141 $t = Title
::newFromText( $title );
1142 if ( is_null( $t ) ) {
1145 // fetch revision from cache/database and return the value
1146 $rev = self
::getCachedRevisionObject( $parser, $t );
1147 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1151 * Get the timestamp from the last revision of a specified page.
1152 * @param Parser $parser
1153 * @param string $title Title to get the timestamp from
1156 public static function revisiontimestamp( $parser, $title = null ) {
1157 $t = Title
::newFromText( $title );
1158 if ( is_null( $t ) ) {
1161 // fetch revision from cache/database and return the value
1162 $rev = self
::getCachedRevisionObject( $parser, $t );
1163 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1167 * Get the user from the last revision of a specified page.
1168 * @param Parser $parser
1169 * @param string $title Title to get the user from
1172 public static function revisionuser( $parser, $title = null ) {
1173 $t = Title
::newFromText( $title );
1174 if ( is_null( $t ) ) {
1177 // fetch revision from cache/database and return the value
1178 $rev = self
::getCachedRevisionObject( $parser, $t );
1179 return $rev ?
$rev->getUserText() : '';
1183 * Returns the sources of any cascading protection acting on a specified page.
1184 * Pages will not return their own title unless they transclude themselves.
1185 * This is an expensive parser function and can't be called too many times per page,
1186 * unless cascading protection sources for the page have already been loaded.
1188 * @param Parser $parser
1189 * @param string $title
1194 public static function cascadingsources( $parser, $title = '' ) {
1195 $titleObject = Title
::newFromText( $title );
1196 if ( !( $titleObject instanceof Title
) ) {
1197 $titleObject = $parser->mTitle
;
1199 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1200 ||
$parser->incrementExpensiveFunctionCount()
1203 $sources = $titleObject->getCascadeProtectionSources();
1204 foreach ( $sources[0] as $sourceTitle ) {
1205 $names[] = $sourceTitle->getPrefixedText();
1207 return implode( $names, '|' );