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',
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() )->plain();
93 return array( $message, 'noparse' => false );
95 return array( 'found' => false );
100 * @param Parser $parser
101 * @param string $date
102 * @param string $defaultPref
106 public static function formatDate( $parser, $date, $defaultPref = null ) {
107 $lang = $parser->getFunctionLang();
108 $df = DateFormatter
::getInstance( $lang );
110 $date = trim( $date );
112 $pref = $parser->getOptions()->getDateFormat();
114 // Specify a different default date format other than the normal default
115 // if the user has 'default' for their setting
116 if ( $pref == 'default' && $defaultPref ) {
117 $pref = $defaultPref;
120 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
124 public static function ns( $parser, $part1 = '' ) {
126 if ( intval( $part1 ) ||
$part1 == "0" ) {
127 $index = intval( $part1 );
129 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
131 if ( $index !== false ) {
132 return $wgContLang->getFormattedNsText( $index );
134 return array( 'found' => false );
138 public static function nse( $parser, $part1 = '' ) {
139 $ret = self
::ns( $parser, $part1 );
140 if ( is_string( $ret ) ) {
141 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
147 * urlencodes a string according to one of three patterns: (bug 22474)
149 * By default (for HTTP "query" strings), spaces are encoded as '+'.
150 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
151 * For links to "wiki"s, or similar software, spaces are encoded as '_',
153 * @param Parser $parser
154 * @param string $s The text to encode.
155 * @param string $arg (optional): The type of encoding.
158 public static function urlencode( $parser, $s = '', $arg = null ) {
159 static $magicWords = null;
160 if ( is_null( $magicWords ) ) {
161 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
163 switch ( $magicWords->matchStartToEnd( $arg ) ) {
165 // Encode as though it's a wiki page, '_' for ' '.
167 $func = 'wfUrlencode';
168 $s = str_replace( ' ', '_', $s );
171 // Encode for an HTTP Path, '%20' for ' '.
173 $func = 'rawurlencode';
176 // Encode for HTTP query, '+' for ' '.
181 return $parser->markerSkipCallback( $s, $func );
184 public static function lcfirst( $parser, $s = '' ) {
186 return $wgContLang->lcfirst( $s );
189 public static function ucfirst( $parser, $s = '' ) {
191 return $wgContLang->ucfirst( $s );
195 * @param Parser $parser
199 public static function lc( $parser, $s = '' ) {
201 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
205 * @param Parser $parser
209 public static function uc( $parser, $s = '' ) {
211 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
214 public static function localurl( $parser, $s = '', $arg = null ) {
215 return self
::urlFunction( 'getLocalURL', $s, $arg );
218 public static function localurle( $parser, $s = '', $arg = null ) {
219 $temp = self
::urlFunction( 'getLocalURL', $s, $arg );
220 if ( !is_string( $temp ) ) {
223 return htmlspecialchars( $temp );
227 public static function fullurl( $parser, $s = '', $arg = null ) {
228 return self
::urlFunction( 'getFullURL', $s, $arg );
231 public static function fullurle( $parser, $s = '', $arg = null ) {
232 $temp = self
::urlFunction( 'getFullURL', $s, $arg );
233 if ( !is_string( $temp ) ) {
236 return htmlspecialchars( $temp );
240 public static function canonicalurl( $parser, $s = '', $arg = null ) {
241 return self
::urlFunction( 'getCanonicalURL', $s, $arg );
244 public static function canonicalurle( $parser, $s = '', $arg = null ) {
245 $temp = self
::urlFunction( 'getCanonicalURL', $s, $arg );
246 if ( !is_string( $temp ) ) {
249 return htmlspecialchars( $temp );
253 public static function urlFunction( $func, $s = '', $arg = null ) {
254 $title = Title
::newFromText( $s );
255 # Due to order of execution of a lot of bits, the values might be encoded
256 # before arriving here; if that's true, then the title can't be created
257 # and the variable will fail. If we can't get a decent title from the first
258 # attempt, url-decode and try for a second.
259 if ( is_null( $title ) ) {
260 $title = Title
::newFromURL( urldecode( $s ) );
262 if ( !is_null( $title ) ) {
263 # Convert NS_MEDIA -> NS_FILE
264 if ( $title->getNamespace() == NS_MEDIA
) {
265 $title = Title
::makeTitle( NS_FILE
, $title->getDBkey() );
267 if ( !is_null( $arg ) ) {
268 $text = $title->$func( $arg );
270 $text = $title->$func();
274 return array( 'found' => false );
279 * @param Parser $parser
284 public static function formatnum( $parser, $num = '', $arg = null ) {
285 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
286 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
287 } elseif ( self
::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
288 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
290 $func = array( $parser->getFunctionLang(), 'formatNum' );
292 return $parser->markerSkipCallback( $num, $func );
296 * @param Parser $parser
297 * @param string $case
298 * @param string $word
301 public static function grammar( $parser, $case = '', $word = '' ) {
302 $word = $parser->killMarkers( $word );
303 return $parser->getFunctionLang()->convertGrammar( $word, $case );
307 * @param Parser $parser
308 * @param string $username
311 public static function gender( $parser, $username ) {
312 $forms = array_slice( func_get_args(), 2 );
314 // Some shortcuts to avoid loading user data unnecessarily
315 if ( count( $forms ) === 0 ) {
317 } elseif ( count( $forms ) === 1 ) {
321 $username = trim( $username );
324 $gender = User
::getDefaultOption( 'gender' );
327 $title = Title
::newFromText( $username );
329 if ( $title && $title->getNamespace() == NS_USER
) {
330 $username = $title->getText();
333 // check parameter, or use the ParserOptions if in interface message
334 $user = User
::newFromName( $username );
336 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
337 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
338 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
340 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
345 * @param Parser $parser
346 * @param string $text
349 public static function plural( $parser, $text = '' ) {
350 $forms = array_slice( func_get_args(), 2 );
351 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
352 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
353 return $parser->getFunctionLang()->convertPlural( $text, $forms );
357 * Override the title of the page when viewed, provided we've been given a
358 * title which will normalise to the canonical title
360 * @param Parser $parser Parent parser
361 * @param string $text Desired title text
362 * @param string $uarg
365 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
366 global $wgRestrictDisplayTitle;
368 static $magicWords = null;
369 if ( is_null( $magicWords ) ) {
370 $magicWords = new MagicWordArray( array( 'displaytitle_noerror', 'displaytitle_noreplace' ) );
372 $arg = $magicWords->matchStartToEnd( $uarg );
374 // parse a limited subset of wiki markup (just the single quote items)
375 $text = $parser->doQuotes( $text );
377 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
378 $text = $parser->killMarkers( $text );
380 // list of disallowed tags for DISPLAYTITLE
381 // these will be escaped even though they are allowed in normal wiki text
382 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
383 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' );
385 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
386 if ( $wgRestrictDisplayTitle ) {
387 $htmlTagsCallback = function ( &$params ) {
388 $decoded = Sanitizer
::decodeTagAttributes( $params );
390 if ( isset( $decoded['style'] ) ) {
391 // this is called later anyway, but we need it right now for the regexes below to be safe
392 // calling it twice doesn't hurt
393 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
395 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
396 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
400 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
403 $htmlTagsCallback = null;
406 // only requested titles that normalize to the actual title are allowed through
407 // if $wgRestrictDisplayTitle is true (it is by default)
408 // mimic the escaping process that occurs in OutputPage::setPageTitle
409 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
416 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
418 if ( !$wgRestrictDisplayTitle ||
419 ( $title instanceof Title
420 && !$title->hasFragment()
421 && $title->equals( $parser->mTitle
) )
423 $old = $parser->mOutput
->getProperty( 'displaytitle' );
424 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
425 $parser->mOutput
->setDisplayTitle( $text );
427 if ( $old !== false && $old !== $text && !$arg ) {
428 $converter = $parser->getConverterLanguage()->getConverter();
429 return '<span class="error">' .
430 wfMessage( 'duplicate-displaytitle',
431 // Message should be parsed, but these params should only be escaped.
432 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
433 $converter->markNoConversion( wfEscapeWikiText( $text ) )
434 )->inContentLanguage()->text() .
443 * Matches the given value against the value of given magic word
445 * @param string $magicword Magic word key
446 * @param string $value Value to match
447 * @return bool True on successful match
449 private static function matchAgainstMagicword( $magicword, $value ) {
450 $value = trim( strval( $value ) );
451 if ( $value === '' ) {
454 $mwObject = MagicWord
::get( $magicword );
455 return $mwObject->matchStartToEnd( $value );
458 public static function formatRaw( $num, $raw ) {
459 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
463 return $wgContLang->formatNum( $num );
466 public static function numberofpages( $parser, $raw = null ) {
467 return self
::formatRaw( SiteStats
::pages(), $raw );
469 public static function numberofusers( $parser, $raw = null ) {
470 return self
::formatRaw( SiteStats
::users(), $raw );
472 public static function numberofactiveusers( $parser, $raw = null ) {
473 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
475 public static function numberofarticles( $parser, $raw = null ) {
476 return self
::formatRaw( SiteStats
::articles(), $raw );
478 public static function numberoffiles( $parser, $raw = null ) {
479 return self
::formatRaw( SiteStats
::images(), $raw );
481 public static function numberofadmins( $parser, $raw = null ) {
482 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
484 public static function numberofedits( $parser, $raw = null ) {
485 return self
::formatRaw( SiteStats
::edits(), $raw );
487 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
488 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
490 public static function numberingroup( $parser, $name = '', $raw = null ) {
491 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
495 * Given a title, return the namespace name that would be given by the
496 * corresponding magic word
497 * Note: function name changed to "mwnamespace" rather than "namespace"
498 * to not break PHP 5.3
499 * @param Parser $parser
500 * @param string $title
501 * @return mixed|string
503 public static function mwnamespace( $parser, $title = null ) {
504 $t = Title
::newFromText( $title );
505 if ( is_null( $t ) ) {
508 return str_replace( '_', ' ', $t->getNsText() );
510 public static function namespacee( $parser, $title = null ) {
511 $t = Title
::newFromText( $title );
512 if ( is_null( $t ) ) {
515 return wfUrlencode( $t->getNsText() );
517 public static function namespacenumber( $parser, $title = null ) {
518 $t = Title
::newFromText( $title );
519 if ( is_null( $t ) ) {
522 return $t->getNamespace();
524 public static function talkspace( $parser, $title = null ) {
525 $t = Title
::newFromText( $title );
526 if ( is_null( $t ) ||
!$t->canTalk() ) {
529 return str_replace( '_', ' ', $t->getTalkNsText() );
531 public static function talkspacee( $parser, $title = null ) {
532 $t = Title
::newFromText( $title );
533 if ( is_null( $t ) ||
!$t->canTalk() ) {
536 return wfUrlencode( $t->getTalkNsText() );
538 public static function subjectspace( $parser, $title = null ) {
539 $t = Title
::newFromText( $title );
540 if ( is_null( $t ) ) {
543 return str_replace( '_', ' ', $t->getSubjectNsText() );
545 public static function subjectspacee( $parser, $title = null ) {
546 $t = Title
::newFromText( $title );
547 if ( is_null( $t ) ) {
550 return wfUrlencode( $t->getSubjectNsText() );
554 * Functions to get and normalize pagenames, corresponding to the magic words
556 * @param Parser $parser
557 * @param string $title
560 public static function pagename( $parser, $title = null ) {
561 $t = Title
::newFromText( $title );
562 if ( is_null( $t ) ) {
565 return wfEscapeWikiText( $t->getText() );
567 public static function pagenamee( $parser, $title = null ) {
568 $t = Title
::newFromText( $title );
569 if ( is_null( $t ) ) {
572 return wfEscapeWikiText( $t->getPartialURL() );
574 public static function fullpagename( $parser, $title = null ) {
575 $t = Title
::newFromText( $title );
576 if ( is_null( $t ) ||
!$t->canTalk() ) {
579 return wfEscapeWikiText( $t->getPrefixedText() );
581 public static function fullpagenamee( $parser, $title = null ) {
582 $t = Title
::newFromText( $title );
583 if ( is_null( $t ) ||
!$t->canTalk() ) {
586 return wfEscapeWikiText( $t->getPrefixedURL() );
588 public static function subpagename( $parser, $title = null ) {
589 $t = Title
::newFromText( $title );
590 if ( is_null( $t ) ) {
593 return wfEscapeWikiText( $t->getSubpageText() );
595 public static function subpagenamee( $parser, $title = null ) {
596 $t = Title
::newFromText( $title );
597 if ( is_null( $t ) ) {
600 return wfEscapeWikiText( $t->getSubpageUrlForm() );
602 public static function rootpagename( $parser, $title = null ) {
603 $t = Title
::newFromText( $title );
604 if ( is_null( $t ) ) {
607 return wfEscapeWikiText( $t->getRootText() );
609 public static function rootpagenamee( $parser, $title = null ) {
610 $t = Title
::newFromText( $title );
611 if ( is_null( $t ) ) {
614 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
616 public static function basepagename( $parser, $title = null ) {
617 $t = Title
::newFromText( $title );
618 if ( is_null( $t ) ) {
621 return wfEscapeWikiText( $t->getBaseText() );
623 public static function basepagenamee( $parser, $title = null ) {
624 $t = Title
::newFromText( $title );
625 if ( is_null( $t ) ) {
628 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
630 public static function talkpagename( $parser, $title = null ) {
631 $t = Title
::newFromText( $title );
632 if ( is_null( $t ) ||
!$t->canTalk() ) {
635 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
637 public static function talkpagenamee( $parser, $title = null ) {
638 $t = Title
::newFromText( $title );
639 if ( is_null( $t ) ||
!$t->canTalk() ) {
642 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
644 public static function subjectpagename( $parser, $title = null ) {
645 $t = Title
::newFromText( $title );
646 if ( is_null( $t ) ) {
649 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
651 public static function subjectpagenamee( $parser, $title = null ) {
652 $t = Title
::newFromText( $title );
653 if ( is_null( $t ) ) {
656 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
660 * Return the number of pages, files or subcats in the given category,
661 * or 0 if it's nonexistent. This is an expensive parser function and
662 * can't be called too many times per page.
663 * @param Parser $parser
664 * @param string $name
665 * @param string $arg1
666 * @param string $arg2
669 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
671 static $magicWords = null;
672 if ( is_null( $magicWords ) ) {
673 $magicWords = new MagicWordArray( array(
674 'pagesincategory_all',
675 'pagesincategory_pages',
676 'pagesincategory_subcats',
677 'pagesincategory_files'
680 static $cache = array();
682 // split the given option to its variable
683 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
684 //{{pagesincategory:|raw[|type]}}
686 $type = $magicWords->matchStartToEnd( $arg2 );
688 //{{pagesincategory:[|type[|raw]]}}
689 $type = $magicWords->matchStartToEnd( $arg1 );
692 if ( !$type ) { //backward compatibility
693 $type = 'pagesincategory_all';
696 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
697 if ( !$title ) { # invalid title
698 return self
::formatRaw( 0, $raw );
700 $wgContLang->findVariantLink( $name, $title, true );
702 // Normalize name for cache
703 $name = $title->getDBkey();
705 if ( !isset( $cache[$name] ) ) {
706 $category = Category
::newFromTitle( $title );
708 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
709 if ( $parser->incrementExpensiveFunctionCount() ) {
710 // $allCount is the total number of cat members,
711 // not the count of how many members are normal pages.
712 $allCount = (int)$category->getPageCount();
713 $subcatCount = (int)$category->getSubcatCount();
714 $fileCount = (int)$category->getFileCount();
715 $pagesCount = $allCount - $subcatCount - $fileCount;
717 $cache[$name]['pagesincategory_all'] = $allCount;
718 $cache[$name]['pagesincategory_pages'] = $pagesCount;
719 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
720 $cache[$name]['pagesincategory_files'] = $fileCount;
723 $count = $cache[$name][$type];
724 return self
::formatRaw( $count, $raw );
728 * Return the size of the given page, or 0 if it's nonexistent. This is an
729 * expensive parser function and can't be called too many times per page.
731 * @param Parser $parser
732 * @param string $page Name of page to check (Default: empty string)
733 * @param string $raw Should number be human readable with commas or just number
736 public static function pagesize( $parser, $page = '', $raw = null ) {
737 $title = Title
::newFromText( $page );
739 if ( !is_object( $title ) ) {
740 return self
::formatRaw( 0, $raw );
743 // fetch revision from cache/database and return the value
744 $rev = self
::getCachedRevisionObject( $parser, $title );
745 $length = $rev ?
$rev->getSize() : 0;
746 return self
::formatRaw( $length, $raw );
750 * Returns the requested protection level for the current page. This
751 * is an expensive parser function and can't be called too many times
752 * per page, unless the protection levels for the given title have
753 * already been retrieved
755 * @param Parser $parser
756 * @param string $type
757 * @param string $title
761 public static function protectionlevel( $parser, $type = '', $title = '' ) {
762 $titleObject = Title
::newFromText( $title );
763 if ( !( $titleObject instanceof Title
) ) {
764 $titleObject = $parser->mTitle
;
766 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
767 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
768 # Title::getRestrictions returns an array, its possible it may have
769 # multiple values in the future
770 return implode( $restrictions, ',' );
776 * Gives language names.
777 * @param Parser $parser
778 * @param string $code Language code (of which to get name)
779 * @param string $inLanguage Language code (in which to get name)
782 public static function language( $parser, $code = '', $inLanguage = '' ) {
783 $code = strtolower( $code );
784 $inLanguage = strtolower( $inLanguage );
785 $lang = Language
::fetchLanguageName( $code, $inLanguage );
786 return $lang !== '' ?
$lang : wfBCP47( $code );
790 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
791 * @param Parser $parser
792 * @param string $string
794 * @param string $padding
795 * @param int $direction
798 public static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
799 $padding = $parser->killMarkers( $padding );
800 $lengthOfPadding = mb_strlen( $padding );
801 if ( $lengthOfPadding == 0 ) {
805 # The remaining length to add counts down to 0 as padding is added
806 $length = min( $length, 500 ) - mb_strlen( $string );
807 # $finalPadding is just $padding repeated enough times so that
808 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
810 while ( $length > 0 ) {
811 # If $length < $lengthofPadding, truncate $padding so we get the
812 # exact length desired.
813 $finalPadding .= mb_substr( $padding, 0, $length );
814 $length -= $lengthOfPadding;
817 if ( $direction == STR_PAD_LEFT
) {
818 return $finalPadding . $string;
820 return $string . $finalPadding;
824 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
825 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
828 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
829 return self
::pad( $parser, $string, $length, $padding );
833 * @param Parser $parser
834 * @param string $text
837 public static function anchorencode( $parser, $text ) {
838 $text = $parser->killMarkers( $text );
839 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
842 public static function special( $parser, $text ) {
843 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
845 $title = SpecialPage
::getTitleFor( $page, $subpage );
846 return $title->getPrefixedText();
848 // unknown special page, just use the given text as its title, if at all possible
849 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
850 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
854 public static function speciale( $parser, $text ) {
855 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
859 * @param Parser $parser
860 * @param string $text The sortkey to use
861 * @param string $uarg Either "noreplace" or "noerror" (in en)
862 * both suppress errors, and noreplace does nothing if
863 * a default sortkey already exists.
866 public static function defaultsort( $parser, $text, $uarg = '' ) {
867 static $magicWords = null;
868 if ( is_null( $magicWords ) ) {
869 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
871 $arg = $magicWords->matchStartToEnd( $uarg );
873 $text = trim( $text );
874 if ( strlen( $text ) == 0 ) {
877 $old = $parser->getCustomDefaultSort();
878 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
879 $parser->setDefaultSort( $text );
882 if ( $old === false ||
$old == $text ||
$arg ) {
885 $converter = $parser->getConverterLanguage()->getConverter();
886 return '<span class="error">' .
887 wfMessage( 'duplicate-defaultsort',
888 // Message should be parsed, but these params should only be escaped.
889 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
890 $converter->markNoConversion( wfEscapeWikiText( $text ) )
891 )->inContentLanguage()->text() .
896 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
897 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
898 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
899 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
900 $file = wfFindFile( $name );
902 if ( $argA == 'nowiki' ) {
903 // {{filepath: | option [| size] }}
905 $parsedWidthParam = $parser->parseWidthParam( $argB );
907 // {{filepath: [| size [|option]] }}
908 $parsedWidthParam = $parser->parseWidthParam( $argA );
909 $isNowiki = ( $argB == 'nowiki' );
913 $url = $file->getFullUrl();
915 // If a size is requested...
916 if ( count( $parsedWidthParam ) ) {
917 $mto = $file->transform( $parsedWidthParam );
919 if ( $mto && !$mto->isError() ) {
920 // ... change the URL to point to a thumbnail.
921 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
925 return array( $url, 'nowiki' => true );
934 * Parser function to extension tag adaptor
935 * @param Parser $parser
936 * @param PPFrame $frame
940 public static function tagObj( $parser, $frame, $args ) {
941 if ( !count( $args ) ) {
944 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
946 if ( count( $args ) ) {
947 $inner = $frame->expand( array_shift( $args ) );
952 $attributes = array();
953 foreach ( $args as $arg ) {
954 $bits = $arg->splitArg();
955 if ( strval( $bits['index'] ) === '' ) {
956 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
957 $value = trim( $frame->expand( $bits['value'] ) );
958 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
959 $value = isset( $m[1] ) ?
$m[1] : '';
961 $attributes[$name] = $value;
965 $stripList = $parser->getStripList();
966 if ( !in_array( $tagName, $stripList ) ) {
967 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
969 foreach ( $attributes as $name => $value ) {
970 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
972 if ( $inner === null ) {
973 return "<$tagName$attrText/>";
975 return "<$tagName$attrText>$inner</$tagName>";
981 'attributes' => $attributes,
982 'close' => "</$tagName>",
984 return $parser->extensionSubstitution( $params, $frame );
988 * Fetched the current revision of the given title and return this.
989 * Will increment the expensive function count and
990 * add a template link to get the value refreshed on changes.
991 * For a given title, which is equal to the current parser title,
992 * the revision object from the parser is used, when that is the current one
994 * @param Parser $parser
995 * @param Title $title
999 private static function getCachedRevisionObject( $parser, $title = null ) {
1000 if ( is_null( $title ) ) {
1004 // Use the revision from the parser itself, when param is the current page
1005 // and the revision is the current one
1006 if ( $title->equals( $parser->getTitle() ) ) {
1007 $parserRev = $parser->getRevisionObject();
1008 if ( $parserRev && $parserRev->isCurrent() ) {
1009 // force reparse after edit with vary-revision flag
1010 $parser->getOutput()->setFlag( 'vary-revision' );
1011 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1016 // Normalize name for cache
1017 $page = $title->getPrefixedDBkey();
1019 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1020 && !$parser->incrementExpensiveFunctionCount() ) {
1023 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1024 $pageID = $rev ?
$rev->getPage() : 0;
1025 $revID = $rev ?
$rev->getId() : 0;
1027 // Register dependency in templatelinks
1028 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1034 * Get the pageid of a specified page
1035 * @param Parser $parser
1036 * @param string $title Title to get the pageid from
1037 * @return int|null|string
1040 public static function pageid( $parser, $title = null ) {
1041 $t = Title
::newFromText( $title );
1042 if ( is_null( $t ) ) {
1045 // Use title from parser to have correct pageid after edit
1046 if ( $t->equals( $parser->getTitle() ) ) {
1047 $t = $parser->getTitle();
1048 return $t->getArticleID();
1051 // These can't have ids
1052 if ( !$t->canExist() ||
$t->isExternal() ) {
1056 // Check the link cache, maybe something already looked it up.
1057 $linkCache = LinkCache
::singleton();
1058 $pdbk = $t->getPrefixedDBkey();
1059 $id = $linkCache->getGoodLinkID( $pdbk );
1061 $parser->mOutput
->addLink( $t, $id );
1064 if ( $linkCache->isBadLink( $pdbk ) ) {
1065 $parser->mOutput
->addLink( $t, 0 );
1069 // We need to load it from the DB, so mark expensive
1070 if ( $parser->incrementExpensiveFunctionCount() ) {
1071 $id = $t->getArticleID();
1072 $parser->mOutput
->addLink( $t, $id );
1079 * Get the id from the last revision of a specified page.
1080 * @param Parser $parser
1081 * @param string $title Title to get the id from
1082 * @return int|null|string
1085 public static function revisionid( $parser, $title = null ) {
1086 $t = Title
::newFromText( $title );
1087 if ( is_null( $t ) ) {
1090 // fetch revision from cache/database and return the value
1091 $rev = self
::getCachedRevisionObject( $parser, $t );
1092 return $rev ?
$rev->getId() : '';
1096 * Get the day from the last revision of a specified page.
1097 * @param Parser $parser
1098 * @param string $title Title to get the day from
1102 public static function revisionday( $parser, $title = null ) {
1103 $t = Title
::newFromText( $title );
1104 if ( is_null( $t ) ) {
1107 // fetch revision from cache/database and return the value
1108 $rev = self
::getCachedRevisionObject( $parser, $t );
1109 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1113 * Get the day with leading zeros from the last revision of a specified page.
1114 * @param Parser $parser
1115 * @param string $title Title to get the day from
1119 public static function revisionday2( $parser, $title = null ) {
1120 $t = Title
::newFromText( $title );
1121 if ( is_null( $t ) ) {
1124 // fetch revision from cache/database and return the value
1125 $rev = self
::getCachedRevisionObject( $parser, $t );
1126 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1130 * Get the month with leading zeros from the last revision of a specified page.
1131 * @param Parser $parser
1132 * @param string $title Title to get the month from
1136 public static function revisionmonth( $parser, $title = null ) {
1137 $t = Title
::newFromText( $title );
1138 if ( is_null( $t ) ) {
1141 // fetch revision from cache/database and return the value
1142 $rev = self
::getCachedRevisionObject( $parser, $t );
1143 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1147 * Get the month from the last revision of a specified page.
1148 * @param Parser $parser
1149 * @param string $title Title to get the month from
1153 public static function revisionmonth1( $parser, $title = null ) {
1154 $t = Title
::newFromText( $title );
1155 if ( is_null( $t ) ) {
1158 // fetch revision from cache/database and return the value
1159 $rev = self
::getCachedRevisionObject( $parser, $t );
1160 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1164 * Get the year from the last revision of a specified page.
1165 * @param Parser $parser
1166 * @param string $title Title to get the year from
1170 public static function revisionyear( $parser, $title = null ) {
1171 $t = Title
::newFromText( $title );
1172 if ( is_null( $t ) ) {
1175 // fetch revision from cache/database and return the value
1176 $rev = self
::getCachedRevisionObject( $parser, $t );
1177 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1181 * Get the timestamp from the last revision of a specified page.
1182 * @param Parser $parser
1183 * @param string $title Title to get the timestamp from
1187 public static function revisiontimestamp( $parser, $title = null ) {
1188 $t = Title
::newFromText( $title );
1189 if ( is_null( $t ) ) {
1192 // fetch revision from cache/database and return the value
1193 $rev = self
::getCachedRevisionObject( $parser, $t );
1194 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1198 * Get the user from the last revision of a specified page.
1199 * @param Parser $parser
1200 * @param string $title Title to get the user from
1204 public static function revisionuser( $parser, $title = null ) {
1205 $t = Title
::newFromText( $title );
1206 if ( is_null( $t ) ) {
1209 // fetch revision from cache/database and return the value
1210 $rev = self
::getCachedRevisionObject( $parser, $t );
1211 return $rev ?
$rev->getUserText() : '';
1215 * Returns the sources of any cascading protection acting on a specified page.
1216 * Pages will not return their own title unless they transclude themselves.
1217 * This is an expensive parser function and can't be called too many times per page,
1218 * unless cascading protection sources for the page have already been loaded.
1220 * @param Parser $parser
1221 * @param string $title
1226 public static function cascadingsources( $parser, $title = '' ) {
1227 $titleObject = Title
::newFromText( $title );
1228 if ( !( $titleObject instanceof Title
) ) {
1229 $titleObject = $parser->mTitle
;
1231 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1232 ||
$parser->incrementExpensiveFunctionCount()
1235 $sources = $titleObject->getCascadeProtectionSources();
1236 foreach ( $sources[0] as $sourceTitle ) {
1237 $names[] = $sourceTitle->getPrefixedText();
1239 return implode( $names, '|' );