7639e2f83795de2aba172ded79432431812db993
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 public static function register( $parser ) {
34 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36 # Syntax for arguments (see Parser::setFunctionHook):
37 # "name for lookup in localized magic words array",
39 # optional Parser::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', 'bidi',
45 'numberofpages', 'numberofusers', 'numberofactiveusers',
46 'numberofarticles', 'numberoffiles', 'numberofadmins',
47 'numberingroup', 'numberofedits', '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 ), Parser
::SFH_NO_HASH
);
63 $parser->setFunctionHook( 'namespace', array( __CLASS__
, 'mwnamespace' ), Parser
::SFH_NO_HASH
);
64 $parser->setFunctionHook( 'int', array( __CLASS__
, 'intFunction' ), Parser
::SFH_NO_HASH
);
65 $parser->setFunctionHook( 'special', array( __CLASS__
, 'special' ) );
66 $parser->setFunctionHook( 'speciale', array( __CLASS__
, 'speciale' ) );
67 $parser->setFunctionHook( 'tag', array( __CLASS__
, 'tagObj' ), Parser
::SFH_OBJECT_ARGS
);
68 $parser->setFunctionHook( 'formatdate', array( __CLASS__
, 'formatDate' ) );
70 if ( $wgAllowDisplayTitle ) {
71 $parser->setFunctionHook( 'displaytitle', array( __CLASS__
, 'displaytitle' ), Parser
::SFH_NO_HASH
);
73 if ( $wgAllowSlowParserFunctions ) {
74 $parser->setFunctionHook(
76 array( __CLASS__
, 'pagesinnamespace' ),
83 * @param Parser $parser
84 * @param string $part1
87 public 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() );
92 if ( !$message->exists() ) {
93 // When message does not exists, the message name is surrounded by angle
94 // and can result in a tag, therefore escape the angles
95 return $message->escaped();
97 return array( $message->plain(), 'noparse' => false );
99 return array( 'found' => false );
104 * @param Parser $parser
105 * @param string $date
106 * @param string $defaultPref
110 public static function formatDate( $parser, $date, $defaultPref = null ) {
111 $lang = $parser->getFunctionLang();
112 $df = DateFormatter
::getInstance( $lang );
114 $date = trim( $date );
116 $pref = $parser->getOptions()->getDateFormat();
118 // Specify a different default date format other than the normal default
119 // if the user has 'default' for their setting
120 if ( $pref == 'default' && $defaultPref ) {
121 $pref = $defaultPref;
124 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
128 public static function ns( $parser, $part1 = '' ) {
130 if ( intval( $part1 ) ||
$part1 == "0" ) {
131 $index = intval( $part1 );
133 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
135 if ( $index !== false ) {
136 return $wgContLang->getFormattedNsText( $index );
138 return array( 'found' => false );
142 public static function nse( $parser, $part1 = '' ) {
143 $ret = self
::ns( $parser, $part1 );
144 if ( is_string( $ret ) ) {
145 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
151 * urlencodes a string according to one of three patterns: (bug 22474)
153 * By default (for HTTP "query" strings), spaces are encoded as '+'.
154 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
155 * For links to "wiki"s, or similar software, spaces are encoded as '_',
157 * @param Parser $parser
158 * @param string $s The text to encode.
159 * @param string $arg (optional): The type of encoding.
162 public static function urlencode( $parser, $s = '', $arg = null ) {
163 static $magicWords = null;
164 if ( is_null( $magicWords ) ) {
165 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
167 switch ( $magicWords->matchStartToEnd( $arg ) ) {
169 // Encode as though it's a wiki page, '_' for ' '.
171 $func = 'wfUrlencode';
172 $s = str_replace( ' ', '_', $s );
175 // Encode for an HTTP Path, '%20' for ' '.
177 $func = 'rawurlencode';
180 // Encode for HTTP query, '+' for ' '.
185 // See T105242, where the choice to kill markers and various
186 // other options were discussed.
187 return $func( $parser->killMarkers( $s ) );
190 public static function lcfirst( $parser, $s = '' ) {
192 return $wgContLang->lcfirst( $s );
195 public static function ucfirst( $parser, $s = '' ) {
197 return $wgContLang->ucfirst( $s );
201 * @param Parser $parser
205 public static function lc( $parser, $s = '' ) {
207 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
211 * @param Parser $parser
215 public static function uc( $parser, $s = '' ) {
217 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
220 public static function localurl( $parser, $s = '', $arg = null ) {
221 return self
::urlFunction( 'getLocalURL', $s, $arg );
224 public static function localurle( $parser, $s = '', $arg = null ) {
225 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
226 if ( !is_string( $temp ) ) {
229 return htmlspecialchars( $temp );
233 public static function fullurl( $parser, $s = '', $arg = null ) {
234 return self
::urlFunction( 'getFullURL', $s, $arg );
237 public static function fullurle( $parser, $s = '', $arg = null ) {
238 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
239 if ( !is_string( $temp ) ) {
242 return htmlspecialchars( $temp );
246 public static function canonicalurl( $parser, $s = '', $arg = null ) {
247 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
250 public static function canonicalurle( $parser, $s = '', $arg = null ) {
251 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
252 if ( !is_string( $temp ) ) {
255 return htmlspecialchars( $temp );
259 public static function urlFunction( $func, $s = '', $arg = null ) {
260 $title = Title
::newFromText( $s );
261 # Due to order of execution of a lot of bits, the values might be encoded
262 # before arriving here; if that's true, then the title can't be created
263 # and the variable will fail. If we can't get a decent title from the first
264 # attempt, url-decode and try for a second.
265 if ( is_null( $title ) ) {
266 $title = Title
::newFromURL( urldecode( $s ) );
268 if ( !is_null( $title ) ) {
269 # Convert NS_MEDIA -> NS_FILE
270 if ( $title->getNamespace() == NS_MEDIA
) {
271 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
273 if ( !is_null( $arg ) ) {
274 $text = $title->$func( $arg );
276 $text = $title->$func();
280 return array( 'found' => false );
285 * @param Parser $parser
290 public static function formatnum( $parser, $num = '', $arg = null ) {
291 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
292 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
293 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
294 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
296 $func = array( $parser->getFunctionLang(), 'formatNum' );
298 return $parser->markerSkipCallback( $num, $func );
302 * @param Parser $parser
303 * @param string $case
304 * @param string $word
307 public static function grammar( $parser, $case = '', $word = '' ) {
308 $word = $parser->killMarkers( $word );
309 return $parser->getFunctionLang()->convertGrammar( $word, $case );
313 * @param Parser $parser
314 * @param string $username
317 public static function gender( $parser, $username ) {
318 $forms = array_slice( func_get_args(), 2 );
320 // Some shortcuts to avoid loading user data unnecessarily
321 if ( count( $forms ) === 0 ) {
323 } elseif ( count( $forms ) === 1 ) {
327 $username = trim( $username );
330 $gender = User
::getDefaultOption( 'gender' );
333 $title = Title
::newFromText( $username );
335 if ( $title && $title->getNamespace() == NS_USER
) {
336 $username = $title->getText();
339 // check parameter, or use the ParserOptions if in interface message
340 $user = User
::newFromName( $username );
342 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
343 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
344 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
346 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
351 * @param Parser $parser
352 * @param string $text
355 public static function plural( $parser, $text = '' ) {
356 $forms = array_slice( func_get_args(), 2 );
357 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
358 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
359 return $parser->getFunctionLang()->convertPlural( $text, $forms );
363 * @param Parser $parser
364 * @param string $text
367 public static function bidi( $parser, $text = '' ) {
368 return $parser->getFunctionLang()->embedBidi( $text );
372 * Override the title of the page when viewed, provided we've been given a
373 * title which will normalise to the canonical title
375 * @param Parser $parser Parent parser
376 * @param string $text Desired title text
377 * @param string $uarg
380 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
381 global $wgRestrictDisplayTitle;
383 static $magicWords = null;
384 if ( is_null( $magicWords ) ) {
385 $magicWords = new MagicWordArray( array( 'displaytitle_noerror', 'displaytitle_noreplace' ) );
387 $arg = $magicWords->matchStartToEnd( $uarg );
389 // parse a limited subset of wiki markup (just the single quote items)
390 $text = $parser->doQuotes( $text );
392 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
393 $text = $parser->killMarkers( $text );
395 // list of disallowed tags for DISPLAYTITLE
396 // these will be escaped even though they are allowed in normal wiki text
397 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
398 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' );
400 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
401 if ( $wgRestrictDisplayTitle ) {
402 $htmlTagsCallback = function ( &$params ) {
403 $decoded = Sanitizer
::decodeTagAttributes( $params );
405 if ( isset( $decoded['style'] ) ) {
406 // this is called later anyway, but we need it right now for the regexes below to be safe
407 // calling it twice doesn't hurt
408 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
410 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
411 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
415 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
418 $htmlTagsCallback = null;
421 // only requested titles that normalize to the actual title are allowed through
422 // if $wgRestrictDisplayTitle is true (it is by default)
423 // mimic the escaping process that occurs in OutputPage::setPageTitle
424 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
431 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
433 if ( !$wgRestrictDisplayTitle ||
434 ( $title instanceof Title
435 && !$title->hasFragment()
436 && $title->equals( $parser->mTitle
) )
438 $old = $parser->mOutput
->getProperty( 'displaytitle' );
439 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
440 $parser->mOutput
->setDisplayTitle( $text );
442 if ( $old !== false && $old !== $text && !$arg ) {
443 $converter = $parser->getConverterLanguage()->getConverter();
444 return '<span class="error">' .
445 wfMessage( 'duplicate-displaytitle',
446 // Message should be parsed, but these params should only be escaped.
447 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
448 $converter->markNoConversion( wfEscapeWikiText( $text ) )
449 )->inContentLanguage()->text() .
458 * Matches the given value against the value of given magic word
460 * @param string $magicword Magic word key
461 * @param string $value Value to match
462 * @return bool True on successful match
464 private static function matchAgainstMagicword( $magicword, $value ) {
465 $value = trim( strval( $value ) );
466 if ( $value === '' ) {
469 $mwObject = MagicWord
::get( $magicword );
470 return $mwObject->matchStartToEnd( $value );
473 public static function formatRaw( $num, $raw ) {
474 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
478 return $wgContLang->formatNum( $num );
481 public static function numberofpages( $parser, $raw = null ) {
482 return self
::formatRaw( SiteStats
::pages(), $raw );
484 public static function numberofusers( $parser, $raw = null ) {
485 return self
::formatRaw( SiteStats
::users(), $raw );
487 public static function numberofactiveusers( $parser, $raw = null ) {
488 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
490 public static function numberofarticles( $parser, $raw = null ) {
491 return self
::formatRaw( SiteStats
::articles(), $raw );
493 public static function numberoffiles( $parser, $raw = null ) {
494 return self
::formatRaw( SiteStats
::images(), $raw );
496 public static function numberofadmins( $parser, $raw = null ) {
497 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
499 public static function numberofedits( $parser, $raw = null ) {
500 return self
::formatRaw( SiteStats
::edits(), $raw );
502 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
503 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
505 public static function numberingroup( $parser, $name = '', $raw = null ) {
506 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
510 * Given a title, return the namespace name that would be given by the
511 * corresponding magic word
512 * Note: function name changed to "mwnamespace" rather than "namespace"
513 * to not break PHP 5.3
514 * @param Parser $parser
515 * @param string $title
516 * @return mixed|string
518 public static function mwnamespace( $parser, $title = null ) {
519 $t = Title
::newFromText( $title );
520 if ( is_null( $t ) ) {
523 return str_replace( '_', ' ', $t->getNsText() );
525 public static function namespacee( $parser, $title = null ) {
526 $t = Title
::newFromText( $title );
527 if ( is_null( $t ) ) {
530 return wfUrlencode( $t->getNsText() );
532 public static function namespacenumber( $parser, $title = null ) {
533 $t = Title
::newFromText( $title );
534 if ( is_null( $t ) ) {
537 return $t->getNamespace();
539 public static function talkspace( $parser, $title = null ) {
540 $t = Title
::newFromText( $title );
541 if ( is_null( $t ) ||
!$t->canTalk() ) {
544 return str_replace( '_', ' ', $t->getTalkNsText() );
546 public static function talkspacee( $parser, $title = null ) {
547 $t = Title
::newFromText( $title );
548 if ( is_null( $t ) ||
!$t->canTalk() ) {
551 return wfUrlencode( $t->getTalkNsText() );
553 public static function subjectspace( $parser, $title = null ) {
554 $t = Title
::newFromText( $title );
555 if ( is_null( $t ) ) {
558 return str_replace( '_', ' ', $t->getSubjectNsText() );
560 public static function subjectspacee( $parser, $title = null ) {
561 $t = Title
::newFromText( $title );
562 if ( is_null( $t ) ) {
565 return wfUrlencode( $t->getSubjectNsText() );
569 * Functions to get and normalize pagenames, corresponding to the magic words
571 * @param Parser $parser
572 * @param string $title
575 public static function pagename( $parser, $title = null ) {
576 $t = Title
::newFromText( $title );
577 if ( is_null( $t ) ) {
580 return wfEscapeWikiText( $t->getText() );
582 public static function pagenamee( $parser, $title = null ) {
583 $t = Title
::newFromText( $title );
584 if ( is_null( $t ) ) {
587 return wfEscapeWikiText( $t->getPartialURL() );
589 public static function fullpagename( $parser, $title = null ) {
590 $t = Title
::newFromText( $title );
591 if ( is_null( $t ) ||
!$t->canTalk() ) {
594 return wfEscapeWikiText( $t->getPrefixedText() );
596 public static function fullpagenamee( $parser, $title = null ) {
597 $t = Title
::newFromText( $title );
598 if ( is_null( $t ) ||
!$t->canTalk() ) {
601 return wfEscapeWikiText( $t->getPrefixedURL() );
603 public static function subpagename( $parser, $title = null ) {
604 $t = Title
::newFromText( $title );
605 if ( is_null( $t ) ) {
608 return wfEscapeWikiText( $t->getSubpageText() );
610 public static function subpagenamee( $parser, $title = null ) {
611 $t = Title
::newFromText( $title );
612 if ( is_null( $t ) ) {
615 return wfEscapeWikiText( $t->getSubpageUrlForm() );
617 public static function rootpagename( $parser, $title = null ) {
618 $t = Title
::newFromText( $title );
619 if ( is_null( $t ) ) {
622 return wfEscapeWikiText( $t->getRootText() );
624 public static function rootpagenamee( $parser, $title = null ) {
625 $t = Title
::newFromText( $title );
626 if ( is_null( $t ) ) {
629 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
631 public static function basepagename( $parser, $title = null ) {
632 $t = Title
::newFromText( $title );
633 if ( is_null( $t ) ) {
636 return wfEscapeWikiText( $t->getBaseText() );
638 public static function basepagenamee( $parser, $title = null ) {
639 $t = Title
::newFromText( $title );
640 if ( is_null( $t ) ) {
643 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
645 public static function talkpagename( $parser, $title = null ) {
646 $t = Title
::newFromText( $title );
647 if ( is_null( $t ) ||
!$t->canTalk() ) {
650 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
652 public static function talkpagenamee( $parser, $title = null ) {
653 $t = Title
::newFromText( $title );
654 if ( is_null( $t ) ||
!$t->canTalk() ) {
657 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
659 public static function subjectpagename( $parser, $title = null ) {
660 $t = Title
::newFromText( $title );
661 if ( is_null( $t ) ) {
664 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
666 public static function subjectpagenamee( $parser, $title = null ) {
667 $t = Title
::newFromText( $title );
668 if ( is_null( $t ) ) {
671 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
675 * Return the number of pages, files or subcats in the given category,
676 * or 0 if it's nonexistent. This is an expensive parser function and
677 * can't be called too many times per page.
678 * @param Parser $parser
679 * @param string $name
680 * @param string $arg1
681 * @param string $arg2
684 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
686 static $magicWords = null;
687 if ( is_null( $magicWords ) ) {
688 $magicWords = new MagicWordArray( array(
689 'pagesincategory_all',
690 'pagesincategory_pages',
691 'pagesincategory_subcats',
692 'pagesincategory_files'
695 static $cache = array();
697 // split the given option to its variable
698 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
699 //{{pagesincategory:|raw[|type]}}
701 $type = $magicWords->matchStartToEnd( $arg2 );
703 //{{pagesincategory:[|type[|raw]]}}
704 $type = $magicWords->matchStartToEnd( $arg1 );
707 if ( !$type ) { //backward compatibility
708 $type = 'pagesincategory_all';
711 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
712 if ( !$title ) { # invalid title
713 return self
::formatRaw( 0, $raw );
715 $wgContLang->findVariantLink( $name, $title, true );
717 // Normalize name for cache
718 $name = $title->getDBkey();
720 if ( !isset( $cache[$name] ) ) {
721 $category = Category
::newFromTitle( $title );
723 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
724 if ( $parser->incrementExpensiveFunctionCount() ) {
725 // $allCount is the total number of cat members,
726 // not the count of how many members are normal pages.
727 $allCount = (int)$category->getPageCount();
728 $subcatCount = (int)$category->getSubcatCount();
729 $fileCount = (int)$category->getFileCount();
730 $pagesCount = $allCount - $subcatCount - $fileCount;
732 $cache[$name]['pagesincategory_all'] = $allCount;
733 $cache[$name]['pagesincategory_pages'] = $pagesCount;
734 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
735 $cache[$name]['pagesincategory_files'] = $fileCount;
738 $count = $cache[$name][$type];
739 return self
::formatRaw( $count, $raw );
743 * Return the size of the given page, or 0 if it's nonexistent. This is an
744 * expensive parser function and can't be called too many times per page.
746 * @param Parser $parser
747 * @param string $page Name of page to check (Default: empty string)
748 * @param string $raw Should number be human readable with commas or just number
751 public static function pagesize( $parser, $page = '', $raw = null ) {
752 $title = Title
::newFromText( $page );
754 if ( !is_object( $title ) ) {
755 return self
::formatRaw( 0, $raw );
758 // fetch revision from cache/database and return the value
759 $rev = self
::getCachedRevisionObject( $parser, $title );
760 $length = $rev ?
$rev->getSize() : 0;
761 return self
::formatRaw( $length, $raw );
765 * Returns the requested protection level for the current page. This
766 * is an expensive parser function and can't be called too many times
767 * per page, unless the protection levels for the given title have
768 * already been retrieved
770 * @param Parser $parser
771 * @param string $type
772 * @param string $title
776 public static function protectionlevel( $parser, $type = '', $title = '' ) {
777 $titleObject = Title
::newFromText( $title );
778 if ( !( $titleObject instanceof Title
) ) {
779 $titleObject = $parser->mTitle
;
781 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
782 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
783 # Title::getRestrictions returns an array, its possible it may have
784 # multiple values in the future
785 return implode( $restrictions, ',' );
791 * Gives language names.
792 * @param Parser $parser
793 * @param string $code Language code (of which to get name)
794 * @param string $inLanguage Language code (in which to get name)
797 public static function language( $parser, $code = '', $inLanguage = '' ) {
798 $code = strtolower( $code );
799 $inLanguage = strtolower( $inLanguage );
800 $lang = Language
::fetchLanguageName( $code, $inLanguage );
801 return $lang !== '' ?
$lang : wfBCP47( $code );
805 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
806 * @param Parser $parser
807 * @param string $string
809 * @param string $padding
810 * @param int $direction
813 public static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
814 $padding = $parser->killMarkers( $padding );
815 $lengthOfPadding = mb_strlen( $padding );
816 if ( $lengthOfPadding == 0 ) {
820 # The remaining length to add counts down to 0 as padding is added
821 $length = min( $length, 500 ) - mb_strlen( $string );
822 # $finalPadding is just $padding repeated enough times so that
823 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
825 while ( $length > 0 ) {
826 # If $length < $lengthofPadding, truncate $padding so we get the
827 # exact length desired.
828 $finalPadding .= mb_substr( $padding, 0, $length );
829 $length -= $lengthOfPadding;
832 if ( $direction == STR_PAD_LEFT
) {
833 return $finalPadding . $string;
835 return $string . $finalPadding;
839 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
840 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
843 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
844 return self
::pad( $parser, $string, $length, $padding );
848 * @param Parser $parser
849 * @param string $text
852 public static function anchorencode( $parser, $text ) {
853 $text = $parser->killMarkers( $text );
854 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
857 public static function special( $parser, $text ) {
858 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
860 $title = SpecialPage
::getTitleFor( $page, $subpage );
861 return $title->getPrefixedText();
863 // unknown special page, just use the given text as its title, if at all possible
864 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
865 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
869 public static function speciale( $parser, $text ) {
870 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
874 * @param Parser $parser
875 * @param string $text The sortkey to use
876 * @param string $uarg Either "noreplace" or "noerror" (in en)
877 * both suppress errors, and noreplace does nothing if
878 * a default sortkey already exists.
881 public static function defaultsort( $parser, $text, $uarg = '' ) {
882 static $magicWords = null;
883 if ( is_null( $magicWords ) ) {
884 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
886 $arg = $magicWords->matchStartToEnd( $uarg );
888 $text = trim( $text );
889 if ( strlen( $text ) == 0 ) {
892 $old = $parser->getCustomDefaultSort();
893 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
894 $parser->setDefaultSort( $text );
897 if ( $old === false ||
$old == $text ||
$arg ) {
900 $converter = $parser->getConverterLanguage()->getConverter();
901 return '<span class="error">' .
902 wfMessage( 'duplicate-defaultsort',
903 // Message should be parsed, but these params should only be escaped.
904 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
905 $converter->markNoConversion( wfEscapeWikiText( $text ) )
906 )->inContentLanguage()->text() .
912 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
913 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
914 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
916 * @param Parser $parser
917 * @param string $name
918 * @param string $argA
919 * @param string $argB
920 * @return array|string
922 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
923 $file = wfFindFile( $name );
925 if ( $argA == 'nowiki' ) {
926 // {{filepath: | option [| size] }}
928 $parsedWidthParam = $parser->parseWidthParam( $argB );
930 // {{filepath: [| size [|option]] }}
931 $parsedWidthParam = $parser->parseWidthParam( $argA );
932 $isNowiki = ( $argB == 'nowiki' );
936 $url = $file->getFullUrl();
938 // If a size is requested...
939 if ( count( $parsedWidthParam ) ) {
940 $mto = $file->transform( $parsedWidthParam );
942 if ( $mto && !$mto->isError() ) {
943 // ... change the URL to point to a thumbnail.
944 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
948 return array( $url, 'nowiki' => true );
957 * Parser function to extension tag adaptor
958 * @param Parser $parser
959 * @param PPFrame $frame
960 * @param PPNode[] $args
963 public static function tagObj( $parser, $frame, $args ) {
964 if ( !count( $args ) ) {
967 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
969 if ( count( $args ) ) {
970 $inner = $frame->expand( array_shift( $args ) );
975 $attributes = array();
976 foreach ( $args as $arg ) {
977 $bits = $arg->splitArg();
978 if ( strval( $bits['index'] ) === '' ) {
979 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
980 $value = trim( $frame->expand( $bits['value'] ) );
981 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
982 $value = isset( $m[1] ) ?
$m[1] : '';
984 $attributes[$name] = $value;
988 $stripList = $parser->getStripList();
989 if ( !in_array( $tagName, $stripList ) ) {
990 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
992 foreach ( $attributes as $name => $value ) {
993 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
995 if ( $inner === null ) {
996 return "<$tagName$attrText/>";
998 return "<$tagName$attrText>$inner</$tagName>";
1004 'attributes' => $attributes,
1005 'close' => "</$tagName>",
1007 return $parser->extensionSubstitution( $params, $frame );
1011 * Fetched the current revision of the given title and return this.
1012 * Will increment the expensive function count and
1013 * add a template link to get the value refreshed on changes.
1014 * For a given title, which is equal to the current parser title,
1015 * the revision object from the parser is used, when that is the current one
1017 * @param Parser $parser
1018 * @param Title $title
1022 private static function getCachedRevisionObject( $parser, $title = null ) {
1023 if ( is_null( $title ) ) {
1027 // Use the revision from the parser itself, when param is the current page
1028 // and the revision is the current one
1029 if ( $title->equals( $parser->getTitle() ) ) {
1030 $parserRev = $parser->getRevisionObject();
1031 if ( $parserRev && $parserRev->isCurrent() ) {
1032 // force reparse after edit with vary-revision flag
1033 $parser->getOutput()->setFlag( 'vary-revision' );
1034 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1039 // Normalize name for cache
1040 $page = $title->getPrefixedDBkey();
1042 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1043 && !$parser->incrementExpensiveFunctionCount() ) {
1046 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1047 $pageID = $rev ?
$rev->getPage() : 0;
1048 $revID = $rev ?
$rev->getId() : 0;
1050 // Register dependency in templatelinks
1051 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1057 * Get the pageid of a specified page
1058 * @param Parser $parser
1059 * @param string $title Title to get the pageid from
1060 * @return int|null|string
1063 public static function pageid( $parser, $title = null ) {
1064 $t = Title
::newFromText( $title );
1065 if ( is_null( $t ) ) {
1068 // Use title from parser to have correct pageid after edit
1069 if ( $t->equals( $parser->getTitle() ) ) {
1070 $t = $parser->getTitle();
1071 return $t->getArticleID();
1074 // These can't have ids
1075 if ( !$t->canExist() ||
$t->isExternal() ) {
1079 // Check the link cache, maybe something already looked it up.
1080 $linkCache = LinkCache
::singleton();
1081 $pdbk = $t->getPrefixedDBkey();
1082 $id = $linkCache->getGoodLinkID( $pdbk );
1084 $parser->mOutput
->addLink( $t, $id );
1087 if ( $linkCache->isBadLink( $pdbk ) ) {
1088 $parser->mOutput
->addLink( $t, 0 );
1092 // We need to load it from the DB, so mark expensive
1093 if ( $parser->incrementExpensiveFunctionCount() ) {
1094 $id = $t->getArticleID();
1095 $parser->mOutput
->addLink( $t, $id );
1102 * Get the id from the last revision of a specified page.
1103 * @param Parser $parser
1104 * @param string $title Title to get the id from
1105 * @return int|null|string
1108 public static function revisionid( $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 ?
$rev->getId() : '';
1119 * Get the day from the last revision of a specified page.
1120 * @param Parser $parser
1121 * @param string $title Title to get the day from
1125 public static function revisionday( $parser, $title = null ) {
1126 $t = Title
::newFromText( $title );
1127 if ( is_null( $t ) ) {
1130 // fetch revision from cache/database and return the value
1131 $rev = self
::getCachedRevisionObject( $parser, $t );
1132 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1136 * Get the day with leading zeros from the last revision of a specified page.
1137 * @param Parser $parser
1138 * @param string $title Title to get the day from
1142 public static function revisionday2( $parser, $title = null ) {
1143 $t = Title
::newFromText( $title );
1144 if ( is_null( $t ) ) {
1147 // fetch revision from cache/database and return the value
1148 $rev = self
::getCachedRevisionObject( $parser, $t );
1149 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1153 * Get the month with leading zeros from the last revision of a specified page.
1154 * @param Parser $parser
1155 * @param string $title Title to get the month from
1159 public static function revisionmonth( $parser, $title = null ) {
1160 $t = Title
::newFromText( $title );
1161 if ( is_null( $t ) ) {
1164 // fetch revision from cache/database and return the value
1165 $rev = self
::getCachedRevisionObject( $parser, $t );
1166 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1170 * Get the month from the last revision of a specified page.
1171 * @param Parser $parser
1172 * @param string $title Title to get the month from
1176 public static function revisionmonth1( $parser, $title = null ) {
1177 $t = Title
::newFromText( $title );
1178 if ( is_null( $t ) ) {
1181 // fetch revision from cache/database and return the value
1182 $rev = self
::getCachedRevisionObject( $parser, $t );
1183 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1187 * Get the year from the last revision of a specified page.
1188 * @param Parser $parser
1189 * @param string $title Title to get the year from
1193 public static function revisionyear( $parser, $title = null ) {
1194 $t = Title
::newFromText( $title );
1195 if ( is_null( $t ) ) {
1198 // fetch revision from cache/database and return the value
1199 $rev = self
::getCachedRevisionObject( $parser, $t );
1200 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1204 * Get the timestamp from the last revision of a specified page.
1205 * @param Parser $parser
1206 * @param string $title Title to get the timestamp from
1210 public static function revisiontimestamp( $parser, $title = null ) {
1211 $t = Title
::newFromText( $title );
1212 if ( is_null( $t ) ) {
1215 // fetch revision from cache/database and return the value
1216 $rev = self
::getCachedRevisionObject( $parser, $t );
1217 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1221 * Get the user from the last revision of a specified page.
1222 * @param Parser $parser
1223 * @param string $title Title to get the user from
1227 public static function revisionuser( $parser, $title = null ) {
1228 $t = Title
::newFromText( $title );
1229 if ( is_null( $t ) ) {
1232 // fetch revision from cache/database and return the value
1233 $rev = self
::getCachedRevisionObject( $parser, $t );
1234 return $rev ?
$rev->getUserText() : '';
1238 * Returns the sources of any cascading protection acting on a specified page.
1239 * Pages will not return their own title unless they transclude themselves.
1240 * This is an expensive parser function and can't be called too many times per page,
1241 * unless cascading protection sources for the page have already been loaded.
1243 * @param Parser $parser
1244 * @param string $title
1249 public static function cascadingsources( $parser, $title = '' ) {
1250 $titleObject = Title
::newFromText( $title );
1251 if ( !( $titleObject instanceof Title
) ) {
1252 $titleObject = $parser->mTitle
;
1254 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1255 ||
$parser->incrementExpensiveFunctionCount()
1258 $sources = $titleObject->getCascadeProtectionSources();
1259 foreach ( $sources[0] as $sourceTitle ) {
1260 $names[] = $sourceTitle->getPrefixedText();
1262 return implode( $names, '|' );