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',
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 self
::urlFunction( 'escapeLocalURL', $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->getFragment() == '' && $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 if ( strval( $value ) === '' ) {
408 $mwObject = MagicWord
::get( $magicword );
409 return $mwObject->match( $value );
412 static function formatRaw( $num, $raw ) {
413 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
417 return $wgContLang->formatNum( $num );
420 static function numberofpages( $parser, $raw = null ) {
421 return self
::formatRaw( SiteStats
::pages(), $raw );
423 static function numberofusers( $parser, $raw = null ) {
424 return self
::formatRaw( SiteStats
::users(), $raw );
426 static function numberofactiveusers( $parser, $raw = null ) {
427 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
429 static function numberofarticles( $parser, $raw = null ) {
430 return self
::formatRaw( SiteStats
::articles(), $raw );
432 static function numberoffiles( $parser, $raw = null ) {
433 return self
::formatRaw( SiteStats
::images(), $raw );
435 static function numberofadmins( $parser, $raw = null ) {
436 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
438 static function numberofedits( $parser, $raw = null ) {
439 return self
::formatRaw( SiteStats
::edits(), $raw );
441 static function numberofviews( $parser, $raw = null ) {
442 global $wgDisableCounters;
443 return !$wgDisableCounters ? self
::formatRaw( SiteStats
::views(), $raw ) : '';
445 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
446 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
448 static function numberingroup( $parser, $name = '', $raw = null ) {
449 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
453 * Given a title, return the namespace name that would be given by the
454 * corresponding magic word
455 * Note: function name changed to "mwnamespace" rather than "namespace"
456 * to not break PHP 5.3
457 * @return mixed|string
459 static function mwnamespace( $parser, $title = null ) {
460 $t = Title
::newFromText( $title );
461 if ( is_null( $t ) ) {
464 return str_replace( '_', ' ', $t->getNsText() );
466 static function namespacee( $parser, $title = null ) {
467 $t = Title
::newFromText( $title );
468 if ( is_null( $t ) ) {
471 return wfUrlencode( $t->getNsText() );
473 static function namespacenumber( $parser, $title = null ) {
474 $t = Title
::newFromText( $title );
475 if ( is_null( $t ) ) {
478 return $t->getNamespace();
480 static function talkspace( $parser, $title = null ) {
481 $t = Title
::newFromText( $title );
482 if ( is_null( $t ) ||
!$t->canTalk() ) {
485 return str_replace( '_', ' ', $t->getTalkNsText() );
487 static function talkspacee( $parser, $title = null ) {
488 $t = Title
::newFromText( $title );
489 if ( is_null( $t ) ||
!$t->canTalk() ) {
492 return wfUrlencode( $t->getTalkNsText() );
494 static function subjectspace( $parser, $title = null ) {
495 $t = Title
::newFromText( $title );
496 if ( is_null( $t ) ) {
499 return str_replace( '_', ' ', $t->getSubjectNsText() );
501 static function subjectspacee( $parser, $title = null ) {
502 $t = Title
::newFromText( $title );
503 if ( is_null( $t ) ) {
506 return wfUrlencode( $t->getSubjectNsText() );
510 * Functions to get and normalize pagenames, corresponding to the magic words
514 static function pagename( $parser, $title = null ) {
515 $t = Title
::newFromText( $title );
516 if ( is_null( $t ) ) {
519 return wfEscapeWikiText( $t->getText() );
521 static function pagenamee( $parser, $title = null ) {
522 $t = Title
::newFromText( $title );
523 if ( is_null( $t ) ) {
526 return wfEscapeWikiText( $t->getPartialURL() );
528 static function fullpagename( $parser, $title = null ) {
529 $t = Title
::newFromText( $title );
530 if ( is_null( $t ) ||
!$t->canTalk() ) {
533 return wfEscapeWikiText( $t->getPrefixedText() );
535 static function fullpagenamee( $parser, $title = null ) {
536 $t = Title
::newFromText( $title );
537 if ( is_null( $t ) ||
!$t->canTalk() ) {
540 return wfEscapeWikiText( $t->getPrefixedURL() );
542 static function subpagename( $parser, $title = null ) {
543 $t = Title
::newFromText( $title );
544 if ( is_null( $t ) ) {
547 return wfEscapeWikiText( $t->getSubpageText() );
549 static function subpagenamee( $parser, $title = null ) {
550 $t = Title
::newFromText( $title );
551 if ( is_null( $t ) ) {
554 return wfEscapeWikiText( $t->getSubpageUrlForm() );
556 static function rootpagename( $parser, $title = null ) {
557 $t = Title
::newFromText( $title );
558 if ( is_null( $t ) ) {
561 return wfEscapeWikiText( $t->getRootText() );
563 static function rootpagenamee( $parser, $title = null ) {
564 $t = Title
::newFromText( $title );
565 if ( is_null( $t ) ) {
568 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
570 static function basepagename( $parser, $title = null ) {
571 $t = Title
::newFromText( $title );
572 if ( is_null( $t ) ) {
575 return wfEscapeWikiText( $t->getBaseText() );
577 static function basepagenamee( $parser, $title = null ) {
578 $t = Title
::newFromText( $title );
579 if ( is_null( $t ) ) {
582 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
584 static function talkpagename( $parser, $title = null ) {
585 $t = Title
::newFromText( $title );
586 if ( is_null( $t ) ||
!$t->canTalk() ) {
589 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
591 static function talkpagenamee( $parser, $title = null ) {
592 $t = Title
::newFromText( $title );
593 if ( is_null( $t ) ||
!$t->canTalk() ) {
596 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
598 static function subjectpagename( $parser, $title = null ) {
599 $t = Title
::newFromText( $title );
600 if ( is_null( $t ) ) {
603 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
605 static function subjectpagenamee( $parser, $title = null ) {
606 $t = Title
::newFromText( $title );
607 if ( is_null( $t ) ) {
610 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
614 * Return the number of pages, files or subcats in the given category,
615 * or 0 if it's nonexistent. This is an expensive parser function and
616 * can't be called too many times per page.
619 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
621 static $magicWords = null;
622 if ( is_null( $magicWords ) ) {
623 $magicWords = new MagicWordArray( array(
624 'pagesincategory_all',
625 'pagesincategory_pages',
626 'pagesincategory_subcats',
627 'pagesincategory_files'
630 static $cache = array();
632 // split the given option to its variable
633 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
634 //{{pagesincategory:|raw[|type]}}
636 $type = $magicWords->matchStartToEnd( $arg2 );
638 //{{pagesincategory:[|type[|raw]]}}
639 $type = $magicWords->matchStartToEnd( $arg1 );
642 if ( !$type ) { //backward compatibility
643 $type = 'pagesincategory_all';
646 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
647 if ( !$title ) { # invalid title
648 return self
::formatRaw( 0, $raw );
650 $wgContLang->findVariantLink( $name, $title, true );
652 // Normalize name for cache
653 $name = $title->getDBkey();
655 if ( !isset( $cache[$name] ) ) {
656 $category = Category
::newFromTitle( $title );
658 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
659 if ( $parser->incrementExpensiveFunctionCount() ) {
660 // $allCount is the total number of cat members,
661 // not the count of how many members are normal pages.
662 $allCount = (int)$category->getPageCount();
663 $subcatCount = (int)$category->getSubcatCount();
664 $fileCount = (int)$category->getFileCount();
665 $pagesCount = $allCount - $subcatCount - $fileCount;
667 $cache[$name]['pagesincategory_all'] = $allCount;
668 $cache[$name]['pagesincategory_pages'] = $pagesCount;
669 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
670 $cache[$name]['pagesincategory_files'] = $fileCount;
673 $count = $cache[$name][$type];
674 return self
::formatRaw( $count, $raw );
678 * Return the size of the given page, or 0 if it's nonexistent. This is an
679 * expensive parser function and can't be called too many times per page.
681 * @todo FIXME: Title::getLength() documentation claims that it adds things
682 * to the link cache, so the local cache here should be unnecessary, but
683 * in fact calling getLength() repeatedly for the same $page does seem to
684 * run one query for each call?
685 * @todo Document parameters
687 * @param $parser Parser
688 * @param $page String Name of page to check (Default: empty string)
689 * @param $raw String Should number be human readable with commas or just number
692 static function pagesize( $parser, $page = '', $raw = null ) {
693 $title = Title
::newFromText( $page );
695 if ( !is_object( $title ) ) {
696 return self
::formatRaw( 0, $raw );
699 // fetch revision from cache/database and return the value
700 $rev = self
::getCachedRevisionObject( $parser, $title );
701 $length = $rev ?
$rev->getSize() : 0;
702 return self
::formatRaw( $length, $raw );
706 * Returns the requested protection level for the current page
708 * @param Parser $parser
709 * @param string $type
710 * @param string $title
714 static function protectionlevel( $parser, $type = '', $title = '' ) {
715 $titleObject = Title
::newFromText( $title );
716 if ( !( $titleObject instanceof Title
) ) {
717 $titleObject = $parser->mTitle
;
719 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
720 # Title::getRestrictions returns an array, its possible it may have
721 # multiple values in the future
722 return implode( $restrictions, ',' );
726 * Gives language names.
727 * @param $parser Parser
728 * @param string $code Language code (of which to get name)
729 * @param string $inLanguage Language code (in which to get name)
732 static function language( $parser, $code = '', $inLanguage = '' ) {
733 $code = strtolower( $code );
734 $inLanguage = strtolower( $inLanguage );
735 $lang = Language
::fetchLanguageName( $code, $inLanguage );
736 return $lang !== '' ?
$lang : wfBCP47( $code );
740 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
743 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
744 $padding = $parser->killMarkers( $padding );
745 $lengthOfPadding = mb_strlen( $padding );
746 if ( $lengthOfPadding == 0 ) {
750 # The remaining length to add counts down to 0 as padding is added
751 $length = min( $length, 500 ) - mb_strlen( $string );
752 # $finalPadding is just $padding repeated enough times so that
753 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
755 while ( $length > 0 ) {
756 # If $length < $lengthofPadding, truncate $padding so we get the
757 # exact length desired.
758 $finalPadding .= mb_substr( $padding, 0, $length );
759 $length -= $lengthOfPadding;
762 if ( $direction == STR_PAD_LEFT
) {
763 return $finalPadding . $string;
765 return $string . $finalPadding;
769 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
770 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
773 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
774 return self
::pad( $parser, $string, $length, $padding );
778 * @param $parser Parser
782 static function anchorencode( $parser, $text ) {
783 $text = $parser->killMarkers( $text );
784 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
787 static function special( $parser, $text ) {
788 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
790 $title = SpecialPage
::getTitleFor( $page, $subpage );
791 return $title->getPrefixedText();
793 // unknown special page, just use the given text as its title, if at all possible
794 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
795 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
799 static function speciale( $parser, $text ) {
800 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
804 * @param $parser Parser
805 * @param string $text The sortkey to use
806 * @param string $uarg Either "noreplace" or "noerror" (in en)
807 * both suppress errors, and noreplace does nothing if
808 * a default sortkey already exists.
811 public static function defaultsort( $parser, $text, $uarg = '' ) {
812 static $magicWords = null;
813 if ( is_null( $magicWords ) ) {
814 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
816 $arg = $magicWords->matchStartToEnd( $uarg );
818 $text = trim( $text );
819 if ( strlen( $text ) == 0 ) {
822 $old = $parser->getCustomDefaultSort();
823 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
824 $parser->setDefaultSort( $text );
827 if ( $old === false ||
$old == $text ||
$arg ) {
830 $converter = $parser->getConverterLanguage()->getConverter();
831 return '<span class="error">' .
832 wfMessage( 'duplicate-defaultsort',
833 // Message should be parsed, but these params should only be escaped.
834 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
835 $converter->markNoConversion( wfEscapeWikiText( $text ) )
836 )->inContentLanguage()->text() .
841 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
842 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
843 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
844 $file = wfFindFile( $name );
846 if ( $argA == 'nowiki' ) {
847 // {{filepath: | option [| size] }}
849 $parsedWidthParam = $parser->parseWidthParam( $argB );
851 // {{filepath: [| size [|option]] }}
852 $parsedWidthParam = $parser->parseWidthParam( $argA );
853 $isNowiki = ( $argB == 'nowiki' );
857 $url = $file->getFullUrl();
859 // If a size is requested...
860 if ( count( $parsedWidthParam ) ) {
861 $mto = $file->transform( $parsedWidthParam );
863 if ( $mto && !$mto->isError() ) {
864 // ... change the URL to point to a thumbnail.
865 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
869 return array( $url, 'nowiki' => true );
878 * Parser function to extension tag adaptor
881 public static function tagObj( $parser, $frame, $args ) {
882 if ( !count( $args ) ) {
885 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
887 if ( count( $args ) ) {
888 $inner = $frame->expand( array_shift( $args ) );
893 $stripList = $parser->getStripList();
894 if ( !in_array( $tagName, $stripList ) ) {
895 return '<span class="error">' .
896 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
900 $attributes = array();
901 foreach ( $args as $arg ) {
902 $bits = $arg->splitArg();
903 if ( strval( $bits['index'] ) === '' ) {
904 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
905 $value = trim( $frame->expand( $bits['value'] ) );
906 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
907 $value = isset( $m[1] ) ?
$m[1] : '';
909 $attributes[$name] = $value;
916 'attributes' => $attributes,
917 'close' => "</$tagName>",
919 return $parser->extensionSubstitution( $params, $frame );
923 * Fetched the current revision of the given title and return this.
924 * Will increment the expensive function count and
925 * add a template link to get the value refreshed on changes.
926 * For a given title, which is equal to the current parser title,
927 * the revision object from the parser is used, when that is the current one
929 * @param $parser Parser
930 * @param $title Title
934 private static function getCachedRevisionObject( $parser, $title = null ) {
935 static $cache = array();
937 if ( is_null( $title ) ) {
941 // Use the revision from the parser itself, when param is the current page
942 // and the revision is the current one
943 if ( $title->equals( $parser->getTitle() ) ) {
944 $parserRev = $parser->getRevisionObject();
945 if ( $parserRev && $parserRev->isCurrent() ) {
946 // force reparse after edit with vary-revision flag
947 $parser->getOutput()->setFlag( 'vary-revision' );
948 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
953 // Normalize name for cache
954 $page = $title->getPrefixedDBkey();
956 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
957 return $cache[$page];
959 if ( $parser->incrementExpensiveFunctionCount() ) {
960 $rev = Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
961 $pageID = $rev ?
$rev->getPage() : 0;
962 $revID = $rev ?
$rev->getId() : 0;
963 $cache[$page] = $rev; // maybe null
965 // Register dependency in templatelinks
966 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
970 $cache[$page] = null;
975 * Get the pageid of a specified page
976 * @param $parser Parser
977 * @param $title string Title to get the pageid from
980 public static function pageid( $parser, $title = null ) {
981 $t = Title
::newFromText( $title );
982 if ( is_null( $t ) ) {
985 // Use title from parser to have correct pageid after edit
986 if ( $t->equals( $parser->getTitle() ) ) {
987 $t = $parser->getTitle();
989 // fetch pageid from cache/database and return the value
990 $pageid = $t->getArticleID();
991 return $pageid ?
$pageid : '';
995 * Get the id from the last revision of a specified page.
996 * @param $parser Parser
997 * @param $title string Title to get the id from
1000 public static function revisionid( $parser, $title = null ) {
1001 $t = Title
::newFromText( $title );
1002 if ( is_null( $t ) ) {
1005 // fetch revision from cache/database and return the value
1006 $rev = self
::getCachedRevisionObject( $parser, $t );
1007 return $rev ?
$rev->getId() : '';
1011 * Get the day from the last revision of a specified page.
1012 * @param $parser Parser
1013 * @param $title string Title to get the day from
1016 public static function revisionday( $parser, $title = null ) {
1017 $t = Title
::newFromText( $title );
1018 if ( is_null( $t ) ) {
1021 // fetch revision from cache/database and return the value
1022 $rev = self
::getCachedRevisionObject( $parser, $t );
1023 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1027 * Get the day with leading zeros from the last revision of a specified page.
1028 * @param $parser Parser
1029 * @param $title string Title to get the day from
1032 public static function revisionday2( $parser, $title = null ) {
1033 $t = Title
::newFromText( $title );
1034 if ( is_null( $t ) ) {
1037 // fetch revision from cache/database and return the value
1038 $rev = self
::getCachedRevisionObject( $parser, $t );
1039 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1043 * Get the month with leading zeros from the last revision of a specified page.
1044 * @param $parser Parser
1045 * @param $title string Title to get the month from
1048 public static function revisionmonth( $parser, $title = null ) {
1049 $t = Title
::newFromText( $title );
1050 if ( is_null( $t ) ) {
1053 // fetch revision from cache/database and return the value
1054 $rev = self
::getCachedRevisionObject( $parser, $t );
1055 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1059 * Get the month from the last revision of a specified page.
1060 * @param $parser Parser
1061 * @param $title string Title to get the month from
1064 public static function revisionmonth1( $parser, $title = null ) {
1065 $t = Title
::newFromText( $title );
1066 if ( is_null( $t ) ) {
1069 // fetch revision from cache/database and return the value
1070 $rev = self
::getCachedRevisionObject( $parser, $t );
1071 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1075 * Get the year from the last revision of a specified page.
1076 * @param $parser Parser
1077 * @param $title string Title to get the year from
1080 public static function revisionyear( $parser, $title = null ) {
1081 $t = Title
::newFromText( $title );
1082 if ( is_null( $t ) ) {
1085 // fetch revision from cache/database and return the value
1086 $rev = self
::getCachedRevisionObject( $parser, $t );
1087 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1091 * Get the timestamp from the last revision of a specified page.
1092 * @param $parser Parser
1093 * @param $title string Title to get the timestamp from
1096 public static function revisiontimestamp( $parser, $title = null ) {
1097 $t = Title
::newFromText( $title );
1098 if ( is_null( $t ) ) {
1101 // fetch revision from cache/database and return the value
1102 $rev = self
::getCachedRevisionObject( $parser, $t );
1103 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1107 * Get the user from the last revision of a specified page.
1108 * @param $parser Parser
1109 * @param $title string Title to get the user from
1112 public static function revisionuser( $parser, $title = null ) {
1113 $t = Title
::newFromText( $title );
1114 if ( is_null( $t ) ) {
1117 // fetch revision from cache/database and return the value
1118 $rev = self
::getCachedRevisionObject( $parser, $t );
1119 return $rev ?
$rev->getUserText() : '';