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 null $defaultPref
97 * @return mixed|string
99 static function formatDate( $parser, $date, $defaultPref = null ) {
100 $lang = $parser->getFunctionLang();
101 $df = DateFormatter
::getInstance( $lang );
103 $date = trim( $date );
105 $pref = $parser->getOptions()->getDateFormat();
107 // Specify a different default date format other than the the normal default
108 // if the user has 'default' for their setting
109 if ( $pref == 'default' && $defaultPref ) {
110 $pref = $defaultPref;
113 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
117 static function ns( $parser, $part1 = '' ) {
119 if ( intval( $part1 ) ||
$part1 == "0" ) {
120 $index = intval( $part1 );
122 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
124 if ( $index !== false ) {
125 return $wgContLang->getFormattedNsText( $index );
127 return array( 'found' => false );
131 static function nse( $parser, $part1 = '' ) {
132 $ret = self
::ns( $parser, $part1 );
133 if ( is_string( $ret ) ) {
134 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
140 * urlencodes a string according to one of three patterns: (bug 22474)
142 * By default (for HTTP "query" strings), spaces are encoded as '+'.
143 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
144 * For links to "wiki"s, or similar software, spaces are encoded as '_',
146 * @param $parser Parser object
147 * @param string $s The text to encode.
148 * @param string $arg (optional): The type of encoding.
151 static function urlencode( $parser, $s = '', $arg = null ) {
152 static $magicWords = null;
153 if ( is_null( $magicWords ) ) {
154 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
156 switch ( $magicWords->matchStartToEnd( $arg ) ) {
158 // Encode as though it's a wiki page, '_' for ' '.
160 $func = 'wfUrlencode';
161 $s = str_replace( ' ', '_', $s );
164 // Encode for an HTTP Path, '%20' for ' '.
166 $func = 'rawurlencode';
169 // Encode for HTTP query, '+' for ' '.
174 return $parser->markerSkipCallback( $s, $func );
177 static function lcfirst( $parser, $s = '' ) {
179 return $wgContLang->lcfirst( $s );
182 static function ucfirst( $parser, $s = '' ) {
184 return $wgContLang->ucfirst( $s );
188 * @param $parser Parser
192 static function lc( $parser, $s = '' ) {
194 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
198 * @param $parser Parser
202 static function uc( $parser, $s = '' ) {
204 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
207 static function localurl( $parser, $s = '', $arg = null ) {
208 return self
::urlFunction( 'getLocalURL', $s, $arg );
211 static function localurle( $parser, $s = '', $arg = null ) {
212 return htmlspecialchars( self
::urlFunction( 'getLocalURL', $s, $arg ) );
215 static function fullurl( $parser, $s = '', $arg = null ) {
216 return self
::urlFunction( 'getFullURL', $s, $arg );
219 static function fullurle( $parser, $s = '', $arg = null ) {
220 return htmlspecialchars( self
::urlFunction( 'getFullURL', $s, $arg ) );
223 static function canonicalurl( $parser, $s = '', $arg = null ) {
224 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
227 static function canonicalurle( $parser, $s = '', $arg = null ) {
228 return self
::urlFunction( 'escapeCanonicalURL', $s, $arg );
231 static function urlFunction( $func, $s = '', $arg = null ) {
232 $title = Title
::newFromText( $s );
233 # Due to order of execution of a lot of bits, the values might be encoded
234 # before arriving here; if that's true, then the title can't be created
235 # and the variable will fail. If we can't get a decent title from the first
236 # attempt, url-decode and try for a second.
237 if ( is_null( $title ) ) {
238 $title = Title
::newFromURL( urldecode( $s ) );
240 if ( !is_null( $title ) ) {
241 # Convert NS_MEDIA -> NS_FILE
242 if ( $title->getNamespace() == NS_MEDIA
) {
243 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
245 if ( !is_null( $arg ) ) {
246 $text = $title->$func( $arg );
248 $text = $title->$func();
252 return array( 'found' => false );
257 * @param $parser Parser
262 static function formatnum( $parser, $num = '', $arg = null ) {
263 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
264 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
265 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
266 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
268 $func = array( $parser->getFunctionLang(), 'formatNum' );
270 return $parser->markerSkipCallback( $num, $func );
274 * @param $parser Parser
275 * @param string $case
276 * @param string $word
279 static function grammar( $parser, $case = '', $word = '' ) {
280 $word = $parser->killMarkers( $word );
281 return $parser->getFunctionLang()->convertGrammar( $word, $case );
285 * @param $parser Parser
286 * @param $username string
289 static function gender( $parser, $username ) {
290 wfProfileIn( __METHOD__
);
291 $forms = array_slice( func_get_args(), 2 );
293 // Some shortcuts to avoid loading user data unnecessarily
294 if ( count( $forms ) === 0 ) {
295 wfProfileOut( __METHOD__
);
297 } elseif ( count( $forms ) === 1 ) {
298 wfProfileOut( __METHOD__
);
302 $username = trim( $username );
305 $gender = User
::getDefaultOption( 'gender' );
308 $title = Title
::newFromText( $username );
310 if ( $title && $title->getNamespace() == NS_USER
) {
311 $username = $title->getText();
314 // check parameter, or use the ParserOptions if in interface message
315 $user = User
::newFromName( $username );
317 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
318 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
319 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
321 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
322 wfProfileOut( __METHOD__
);
327 * @param $parser Parser
328 * @param string $text
331 static function plural( $parser, $text = '' ) {
332 $forms = array_slice( func_get_args(), 2 );
333 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
334 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
335 return $parser->getFunctionLang()->convertPlural( $text, $forms );
339 * Override the title of the page when viewed, provided we've been given a
340 * title which will normalise to the canonical title
342 * @param $parser Parser: parent parser
343 * @param string $text desired title text
346 static function displaytitle( $parser, $text = '' ) {
347 global $wgRestrictDisplayTitle;
349 // parse a limited subset of wiki markup (just the single quote items)
350 $text = $parser->doQuotes( $text );
352 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
353 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
354 . preg_quote( Parser
::MARKER_SUFFIX
, '/' ) . '/', '', $text );
356 // list of disallowed tags for DISPLAYTITLE
357 // these will be escaped even though they are allowed in normal wiki text
358 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
359 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
361 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
362 if ( $wgRestrictDisplayTitle ) {
363 $htmlTagsCallback = function ( &$params ) {
364 $decoded = Sanitizer
::decodeTagAttributes( $params );
366 if ( isset( $decoded['style'] ) ) {
367 // this is called later anyway, but we need it right now for the regexes below to be safe
368 // calling it twice doesn't hurt
369 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
371 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
372 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
376 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
379 $htmlTagsCallback = null;
382 // only requested titles that normalize to the actual title are allowed through
383 // if $wgRestrictDisplayTitle is true (it is by default)
384 // mimic the escaping process that occurs in OutputPage::setPageTitle
385 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $text, $htmlTagsCallback, array(), array(), $bad ) );
386 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
388 if ( !$wgRestrictDisplayTitle ) {
389 $parser->mOutput
->setDisplayTitle( $text );
390 } elseif ( $title instanceof Title
&& !$title->hasFragment() && $title->equals( $parser->mTitle
) ) {
391 $parser->mOutput
->setDisplayTitle( $text );
398 * Matches the given value against the value of given magic word
400 * @param string $magicword magic word key
401 * @param mixed $value value to match
402 * @return boolean true on successful match
404 private static function matchAgainstMagicword( $magicword, $value ) {
405 $value = trim( strval( $value ) );
406 if ( $value === '' ) {
409 $mwObject = MagicWord
::get( $magicword );
410 return $mwObject->matchStartToEnd( $value );
413 static function formatRaw( $num, $raw ) {
414 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
418 return $wgContLang->formatNum( $num );
421 static function numberofpages( $parser, $raw = null ) {
422 return self
::formatRaw( SiteStats
::pages(), $raw );
424 static function numberofusers( $parser, $raw = null ) {
425 return self
::formatRaw( SiteStats
::users(), $raw );
427 static function numberofactiveusers( $parser, $raw = null ) {
428 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
430 static function numberofarticles( $parser, $raw = null ) {
431 return self
::formatRaw( SiteStats
::articles(), $raw );
433 static function numberoffiles( $parser, $raw = null ) {
434 return self
::formatRaw( SiteStats
::images(), $raw );
436 static function numberofadmins( $parser, $raw = null ) {
437 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
439 static function numberofedits( $parser, $raw = null ) {
440 return self
::formatRaw( SiteStats
::edits(), $raw );
442 static function numberofviews( $parser, $raw = null ) {
443 global $wgDisableCounters;
444 return !$wgDisableCounters ? self
::formatRaw( SiteStats
::views(), $raw ) : '';
446 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
447 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
449 static function numberingroup( $parser, $name = '', $raw = null ) {
450 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
454 * Given a title, return the namespace name that would be given by the
455 * corresponding magic word
456 * Note: function name changed to "mwnamespace" rather than "namespace"
457 * to not break PHP 5.3
458 * @return mixed|string
460 static function mwnamespace( $parser, $title = null ) {
461 $t = Title
::newFromText( $title );
462 if ( is_null( $t ) ) {
465 return str_replace( '_', ' ', $t->getNsText() );
467 static function namespacee( $parser, $title = null ) {
468 $t = Title
::newFromText( $title );
469 if ( is_null( $t ) ) {
472 return wfUrlencode( $t->getNsText() );
474 static function namespacenumber( $parser, $title = null ) {
475 $t = Title
::newFromText( $title );
476 if ( is_null( $t ) ) {
479 return $t->getNamespace();
481 static function talkspace( $parser, $title = null ) {
482 $t = Title
::newFromText( $title );
483 if ( is_null( $t ) ||
!$t->canTalk() ) {
486 return str_replace( '_', ' ', $t->getTalkNsText() );
488 static function talkspacee( $parser, $title = null ) {
489 $t = Title
::newFromText( $title );
490 if ( is_null( $t ) ||
!$t->canTalk() ) {
493 return wfUrlencode( $t->getTalkNsText() );
495 static function subjectspace( $parser, $title = null ) {
496 $t = Title
::newFromText( $title );
497 if ( is_null( $t ) ) {
500 return str_replace( '_', ' ', $t->getSubjectNsText() );
502 static function subjectspacee( $parser, $title = null ) {
503 $t = Title
::newFromText( $title );
504 if ( is_null( $t ) ) {
507 return wfUrlencode( $t->getSubjectNsText() );
511 * Functions to get and normalize pagenames, corresponding to the magic words
515 static function pagename( $parser, $title = null ) {
516 $t = Title
::newFromText( $title );
517 if ( is_null( $t ) ) {
520 return wfEscapeWikiText( $t->getText() );
522 static function pagenamee( $parser, $title = null ) {
523 $t = Title
::newFromText( $title );
524 if ( is_null( $t ) ) {
527 return wfEscapeWikiText( $t->getPartialURL() );
529 static function fullpagename( $parser, $title = null ) {
530 $t = Title
::newFromText( $title );
531 if ( is_null( $t ) ||
!$t->canTalk() ) {
534 return wfEscapeWikiText( $t->getPrefixedText() );
536 static function fullpagenamee( $parser, $title = null ) {
537 $t = Title
::newFromText( $title );
538 if ( is_null( $t ) ||
!$t->canTalk() ) {
541 return wfEscapeWikiText( $t->getPrefixedURL() );
543 static function subpagename( $parser, $title = null ) {
544 $t = Title
::newFromText( $title );
545 if ( is_null( $t ) ) {
548 return wfEscapeWikiText( $t->getSubpageText() );
550 static function subpagenamee( $parser, $title = null ) {
551 $t = Title
::newFromText( $title );
552 if ( is_null( $t ) ) {
555 return wfEscapeWikiText( $t->getSubpageUrlForm() );
557 static function rootpagename( $parser, $title = null ) {
558 $t = Title
::newFromText( $title );
559 if ( is_null( $t ) ) {
562 return wfEscapeWikiText( $t->getRootText() );
564 static function rootpagenamee( $parser, $title = null ) {
565 $t = Title
::newFromText( $title );
566 if ( is_null( $t ) ) {
569 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
571 static function basepagename( $parser, $title = null ) {
572 $t = Title
::newFromText( $title );
573 if ( is_null( $t ) ) {
576 return wfEscapeWikiText( $t->getBaseText() );
578 static function basepagenamee( $parser, $title = null ) {
579 $t = Title
::newFromText( $title );
580 if ( is_null( $t ) ) {
583 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
585 static function talkpagename( $parser, $title = null ) {
586 $t = Title
::newFromText( $title );
587 if ( is_null( $t ) ||
!$t->canTalk() ) {
590 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
592 static function talkpagenamee( $parser, $title = null ) {
593 $t = Title
::newFromText( $title );
594 if ( is_null( $t ) ||
!$t->canTalk() ) {
597 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
599 static function subjectpagename( $parser, $title = null ) {
600 $t = Title
::newFromText( $title );
601 if ( is_null( $t ) ) {
604 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
606 static function subjectpagenamee( $parser, $title = null ) {
607 $t = Title
::newFromText( $title );
608 if ( is_null( $t ) ) {
611 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
615 * Return the number of pages, files or subcats in the given category,
616 * or 0 if it's nonexistent. This is an expensive parser function and
617 * can't be called too many times per page.
620 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
622 static $magicWords = null;
623 if ( is_null( $magicWords ) ) {
624 $magicWords = new MagicWordArray( array(
625 'pagesincategory_all',
626 'pagesincategory_pages',
627 'pagesincategory_subcats',
628 'pagesincategory_files'
631 static $cache = array();
633 // split the given option to its variable
634 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
635 //{{pagesincategory:|raw[|type]}}
637 $type = $magicWords->matchStartToEnd( $arg2 );
639 //{{pagesincategory:[|type[|raw]]}}
640 $type = $magicWords->matchStartToEnd( $arg1 );
643 if ( !$type ) { //backward compatibility
644 $type = 'pagesincategory_all';
647 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
648 if ( !$title ) { # invalid title
649 return self
::formatRaw( 0, $raw );
651 $wgContLang->findVariantLink( $name, $title, true );
653 // Normalize name for cache
654 $name = $title->getDBkey();
656 if ( !isset( $cache[$name] ) ) {
657 $category = Category
::newFromTitle( $title );
659 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
660 if ( $parser->incrementExpensiveFunctionCount() ) {
661 // $allCount is the total number of cat members,
662 // not the count of how many members are normal pages.
663 $allCount = (int)$category->getPageCount();
664 $subcatCount = (int)$category->getSubcatCount();
665 $fileCount = (int)$category->getFileCount();
666 $pagesCount = $allCount - $subcatCount - $fileCount;
668 $cache[$name]['pagesincategory_all'] = $allCount;
669 $cache[$name]['pagesincategory_pages'] = $pagesCount;
670 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
671 $cache[$name]['pagesincategory_files'] = $fileCount;
674 $count = $cache[$name][$type];
675 return self
::formatRaw( $count, $raw );
679 * Return the size of the given page, or 0 if it's nonexistent. This is an
680 * expensive parser function and can't be called too many times per page.
682 * @param $parser Parser
683 * @param $page String Name of page to check (Default: empty string)
684 * @param $raw String Should number be human readable with commas or just number
687 static function pagesize( $parser, $page = '', $raw = null ) {
688 $title = Title
::newFromText( $page );
690 if ( !is_object( $title ) ) {
691 return self
::formatRaw( 0, $raw );
694 // fetch revision from cache/database and return the value
695 $rev = self
::getCachedRevisionObject( $parser, $title );
696 $length = $rev ?
$rev->getSize() : 0;
697 return self
::formatRaw( $length, $raw );
701 * Returns the requested protection level for the current page. This
702 * is an expensive parser function and can't be called too many times
703 * per page, unless the protection levels for the given title have
704 * already been retrieved
706 * @param Parser $parser
707 * @param string $type
708 * @param string $title
712 static function protectionlevel( $parser, $type = '', $title = '' ) {
713 $titleObject = Title
::newFromText( $title );
714 if ( !( $titleObject instanceof Title
) ) {
715 $titleObject = $parser->mTitle
;
717 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
718 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
719 # Title::getRestrictions returns an array, its possible it may have
720 # multiple values in the future
721 return implode( $restrictions, ',' );
727 * Gives language names.
728 * @param $parser Parser
729 * @param string $code Language code (of which to get name)
730 * @param string $inLanguage Language code (in which to get name)
733 static function language( $parser, $code = '', $inLanguage = '' ) {
734 $code = strtolower( $code );
735 $inLanguage = strtolower( $inLanguage );
736 $lang = Language
::fetchLanguageName( $code, $inLanguage );
737 return $lang !== '' ?
$lang : wfBCP47( $code );
741 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
744 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
745 $padding = $parser->killMarkers( $padding );
746 $lengthOfPadding = mb_strlen( $padding );
747 if ( $lengthOfPadding == 0 ) {
751 # The remaining length to add counts down to 0 as padding is added
752 $length = min( $length, 500 ) - mb_strlen( $string );
753 # $finalPadding is just $padding repeated enough times so that
754 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
756 while ( $length > 0 ) {
757 # If $length < $lengthofPadding, truncate $padding so we get the
758 # exact length desired.
759 $finalPadding .= mb_substr( $padding, 0, $length );
760 $length -= $lengthOfPadding;
763 if ( $direction == STR_PAD_LEFT
) {
764 return $finalPadding . $string;
766 return $string . $finalPadding;
770 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
771 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
774 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
775 return self
::pad( $parser, $string, $length, $padding );
779 * @param $parser Parser
783 static function anchorencode( $parser, $text ) {
784 $text = $parser->killMarkers( $text );
785 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
788 static function special( $parser, $text ) {
789 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
791 $title = SpecialPage
::getTitleFor( $page, $subpage );
792 return $title->getPrefixedText();
794 // unknown special page, just use the given text as its title, if at all possible
795 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
796 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
800 static function speciale( $parser, $text ) {
801 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
805 * @param $parser Parser
806 * @param string $text The sortkey to use
807 * @param string $uarg Either "noreplace" or "noerror" (in en)
808 * both suppress errors, and noreplace does nothing if
809 * a default sortkey already exists.
812 public static function defaultsort( $parser, $text, $uarg = '' ) {
813 static $magicWords = null;
814 if ( is_null( $magicWords ) ) {
815 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
817 $arg = $magicWords->matchStartToEnd( $uarg );
819 $text = trim( $text );
820 if ( strlen( $text ) == 0 ) {
823 $old = $parser->getCustomDefaultSort();
824 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
825 $parser->setDefaultSort( $text );
828 if ( $old === false ||
$old == $text ||
$arg ) {
831 $converter = $parser->getConverterLanguage()->getConverter();
832 return '<span class="error">' .
833 wfMessage( 'duplicate-defaultsort',
834 // Message should be parsed, but these params should only be escaped.
835 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
836 $converter->markNoConversion( wfEscapeWikiText( $text ) )
837 )->inContentLanguage()->text() .
842 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
843 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
844 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
845 $file = wfFindFile( $name );
847 if ( $argA == 'nowiki' ) {
848 // {{filepath: | option [| size] }}
850 $parsedWidthParam = $parser->parseWidthParam( $argB );
852 // {{filepath: [| size [|option]] }}
853 $parsedWidthParam = $parser->parseWidthParam( $argA );
854 $isNowiki = ( $argB == 'nowiki' );
858 $url = $file->getFullUrl();
860 // If a size is requested...
861 if ( count( $parsedWidthParam ) ) {
862 $mto = $file->transform( $parsedWidthParam );
864 if ( $mto && !$mto->isError() ) {
865 // ... change the URL to point to a thumbnail.
866 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
870 return array( $url, 'nowiki' => true );
879 * Parser function to extension tag adaptor
882 public static function tagObj( $parser, $frame, $args ) {
883 if ( !count( $args ) ) {
886 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
888 if ( count( $args ) ) {
889 $inner = $frame->expand( array_shift( $args ) );
894 $stripList = $parser->getStripList();
895 if ( !in_array( $tagName, $stripList ) ) {
896 return '<span class="error">' .
897 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
901 $attributes = array();
902 foreach ( $args as $arg ) {
903 $bits = $arg->splitArg();
904 if ( strval( $bits['index'] ) === '' ) {
905 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
906 $value = trim( $frame->expand( $bits['value'] ) );
907 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
908 $value = isset( $m[1] ) ?
$m[1] : '';
910 $attributes[$name] = $value;
917 'attributes' => $attributes,
918 'close' => "</$tagName>",
920 return $parser->extensionSubstitution( $params, $frame );
924 * Fetched the current revision of the given title and return this.
925 * Will increment the expensive function count and
926 * add a template link to get the value refreshed on changes.
927 * For a given title, which is equal to the current parser title,
928 * the revision object from the parser is used, when that is the current one
930 * @param $parser Parser
931 * @param $title Title
935 private static function getCachedRevisionObject( $parser, $title = null ) {
936 static $cache = array();
938 if ( is_null( $title ) ) {
942 // Use the revision from the parser itself, when param is the current page
943 // and the revision is the current one
944 if ( $title->equals( $parser->getTitle() ) ) {
945 $parserRev = $parser->getRevisionObject();
946 if ( $parserRev && $parserRev->isCurrent() ) {
947 // force reparse after edit with vary-revision flag
948 $parser->getOutput()->setFlag( 'vary-revision' );
949 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
954 // Normalize name for cache
955 $page = $title->getPrefixedDBkey();
957 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
958 return $cache[$page];
960 if ( $parser->incrementExpensiveFunctionCount() ) {
961 $rev = Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
962 $pageID = $rev ?
$rev->getPage() : 0;
963 $revID = $rev ?
$rev->getId() : 0;
964 $cache[$page] = $rev; // maybe null
966 // Register dependency in templatelinks
967 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
971 $cache[$page] = null;
976 * Get the pageid of a specified page
977 * @param $parser Parser
978 * @param $title string Title to get the pageid from
981 public static function pageid( $parser, $title = null ) {
982 $t = Title
::newFromText( $title );
983 if ( is_null( $t ) ) {
986 // Use title from parser to have correct pageid after edit
987 if ( $t->equals( $parser->getTitle() ) ) {
988 $t = $parser->getTitle();
989 return $t->getArticleID();
992 // These can't have ids
993 if ( !$t->canExist() ||
$t->isExternal() ) {
997 // Check the link cache, maybe something already looked it up.
998 $linkCache = LinkCache
::singleton();
999 $pdbk = $t->getPrefixedDBkey();
1000 $id = $linkCache->getGoodLinkID( $pdbk );
1002 $parser->mOutput
->addLink( $t, $id );
1005 if ( $linkCache->isBadLink( $pdbk ) ) {
1006 $parser->mOutput
->addLink( $t, 0 );
1010 // We need to load it from the DB, so mark expensive
1011 if ( $parser->incrementExpensiveFunctionCount() ) {
1012 $id = $t->getArticleID();
1013 $parser->mOutput
->addLink( $t, $id );
1020 * Get the id from the last revision of a specified page.
1021 * @param $parser Parser
1022 * @param $title string Title to get the id from
1025 public static function revisionid( $parser, $title = null ) {
1026 $t = Title
::newFromText( $title );
1027 if ( is_null( $t ) ) {
1030 // fetch revision from cache/database and return the value
1031 $rev = self
::getCachedRevisionObject( $parser, $t );
1032 return $rev ?
$rev->getId() : '';
1036 * Get the day from the last revision of a specified page.
1037 * @param $parser Parser
1038 * @param $title string Title to get the day from
1041 public static function revisionday( $parser, $title = null ) {
1042 $t = Title
::newFromText( $title );
1043 if ( is_null( $t ) ) {
1046 // fetch revision from cache/database and return the value
1047 $rev = self
::getCachedRevisionObject( $parser, $t );
1048 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1052 * Get the day with leading zeros from the last revision of a specified page.
1053 * @param $parser Parser
1054 * @param $title string Title to get the day from
1057 public static function revisionday2( $parser, $title = null ) {
1058 $t = Title
::newFromText( $title );
1059 if ( is_null( $t ) ) {
1062 // fetch revision from cache/database and return the value
1063 $rev = self
::getCachedRevisionObject( $parser, $t );
1064 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1068 * Get the month with leading zeros from the last revision of a specified page.
1069 * @param $parser Parser
1070 * @param $title string Title to get the month from
1073 public static function revisionmonth( $parser, $title = null ) {
1074 $t = Title
::newFromText( $title );
1075 if ( is_null( $t ) ) {
1078 // fetch revision from cache/database and return the value
1079 $rev = self
::getCachedRevisionObject( $parser, $t );
1080 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1084 * Get the month from the last revision of a specified page.
1085 * @param $parser Parser
1086 * @param $title string Title to get the month from
1089 public static function revisionmonth1( $parser, $title = null ) {
1090 $t = Title
::newFromText( $title );
1091 if ( is_null( $t ) ) {
1094 // fetch revision from cache/database and return the value
1095 $rev = self
::getCachedRevisionObject( $parser, $t );
1096 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1100 * Get the year from the last revision of a specified page.
1101 * @param $parser Parser
1102 * @param $title string Title to get the year from
1105 public static function revisionyear( $parser, $title = null ) {
1106 $t = Title
::newFromText( $title );
1107 if ( is_null( $t ) ) {
1110 // fetch revision from cache/database and return the value
1111 $rev = self
::getCachedRevisionObject( $parser, $t );
1112 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1116 * Get the timestamp from the last revision of a specified page.
1117 * @param $parser Parser
1118 * @param $title string Title to get the timestamp from
1121 public static function revisiontimestamp( $parser, $title = null ) {
1122 $t = Title
::newFromText( $title );
1123 if ( is_null( $t ) ) {
1126 // fetch revision from cache/database and return the value
1127 $rev = self
::getCachedRevisionObject( $parser, $t );
1128 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1132 * Get the user from the last revision of a specified page.
1133 * @param $parser Parser
1134 * @param $title string Title to get the user from
1137 public static function revisionuser( $parser, $title = null ) {
1138 $t = Title
::newFromText( $title );
1139 if ( is_null( $t ) ) {
1142 // fetch revision from cache/database and return the value
1143 $rev = self
::getCachedRevisionObject( $parser, $t );
1144 return $rev ?
$rev->getUserText() : '';
1148 * Returns the sources of any cascading protection acting on a specified page.
1149 * Pages will not return their own title unless they transclude themselves.
1150 * This is an expensive parser function and can't be called too many times per page,
1151 * unless cascading protection sources for the page have already been loaded.
1153 * @param Parser $parser
1154 * @param string $title
1159 public static function cascadingsources( $parser, $title = '' ) {
1160 $titleObject = Title
::newFromText( $title );
1161 if ( !( $titleObject instanceof Title
) ) {
1162 $titleObject = $parser->mTitle
;
1164 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1165 ||
$parser->incrementExpensiveFunctionCount()
1168 $sources = $titleObject->getCascadeProtectionSources();
1169 foreach ( $sources[0] as $sourceTitle ) {
1170 $names[] = $sourceTitle->getPrefixedText();
1172 return implode( $names, '|' );