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 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 ), SFH_NO_HASH
);
63 $parser->setFunctionHook( 'namespace', array( __CLASS__
, 'mwnamespace' ), SFH_NO_HASH
);
64 $parser->setFunctionHook( 'int', array( __CLASS__
, 'intFunction' ), SFH_NO_HASH
);
65 $parser->setFunctionHook( 'special', array( __CLASS__
, 'special' ) );
66 $parser->setFunctionHook( 'speciale', array( __CLASS__
, 'speciale' ) );
67 $parser->setFunctionHook( 'tag', array( __CLASS__
, 'tagObj' ), SFH_OBJECT_ARGS
);
68 $parser->setFunctionHook( 'formatdate', array( __CLASS__
, 'formatDate' ) );
70 if ( $wgAllowDisplayTitle ) {
71 $parser->setFunctionHook( 'displaytitle', array( __CLASS__
, 'displaytitle' ), SFH_NO_HASH
);
73 if ( $wgAllowSlowParserFunctions ) {
74 $parser->setFunctionHook(
76 array( __CLASS__
, 'pagesinnamespace' ),
83 * @param Parser $parser
84 * @param string $part1
87 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 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 wfProfileIn( __METHOD__
);
313 $forms = array_slice( func_get_args(), 2 );
315 // Some shortcuts to avoid loading user data unnecessarily
316 if ( count( $forms ) === 0 ) {
317 wfProfileOut( __METHOD__
);
319 } elseif ( count( $forms ) === 1 ) {
320 wfProfileOut( __METHOD__
);
324 $username = trim( $username );
327 $gender = User
::getDefaultOption( 'gender' );
330 $title = Title
::newFromText( $username );
332 if ( $title && $title->getNamespace() == NS_USER
) {
333 $username = $title->getText();
336 // check parameter, or use the ParserOptions if in interface message
337 $user = User
::newFromName( $username );
339 $gender = GenderCache
::singleton()->getGenderOf( $user, __METHOD__
);
340 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
341 $gender = GenderCache
::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__
);
343 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
344 wfProfileOut( __METHOD__
);
349 * @param Parser $parser
350 * @param string $text
353 public static function plural( $parser, $text = '' ) {
354 $forms = array_slice( func_get_args(), 2 );
355 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
356 settype( $text, ctype_digit( $text ) ?
'int' : 'float' );
357 return $parser->getFunctionLang()->convertPlural( $text, $forms );
361 * Override the title of the page when viewed, provided we've been given a
362 * title which will normalise to the canonical title
364 * @param Parser $parser Parent parser
365 * @param string $text Desired title text
366 * @param string $uarg
369 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
370 global $wgRestrictDisplayTitle;
372 static $magicWords = null;
373 if ( is_null( $magicWords ) ) {
374 $magicWords = new MagicWordArray( array( 'displaytitle_noerror', 'displaytitle_noreplace' ) );
376 $arg = $magicWords->matchStartToEnd( $uarg );
378 // parse a limited subset of wiki markup (just the single quote items)
379 $text = $parser->doQuotes( $text );
381 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
382 $text = $parser->killMarkers( $text );
384 // list of disallowed tags for DISPLAYTITLE
385 // these will be escaped even though they are allowed in normal wiki text
386 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
387 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' );
389 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
390 if ( $wgRestrictDisplayTitle ) {
391 $htmlTagsCallback = function ( &$params ) {
392 $decoded = Sanitizer
::decodeTagAttributes( $params );
394 if ( isset( $decoded['style'] ) ) {
395 // this is called later anyway, but we need it right now for the regexes below to be safe
396 // calling it twice doesn't hurt
397 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
399 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
400 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
404 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
407 $htmlTagsCallback = null;
410 // only requested titles that normalize to the actual title are allowed through
411 // if $wgRestrictDisplayTitle is true (it is by default)
412 // mimic the escaping process that occurs in OutputPage::setPageTitle
413 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
420 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
422 if ( !$wgRestrictDisplayTitle ||
423 ( $title instanceof Title
424 && !$title->hasFragment()
425 && $title->equals( $parser->mTitle
) )
427 $old = $parser->mOutput
->getProperty( 'displaytitle' );
428 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
429 $parser->mOutput
->setDisplayTitle( $text );
431 if ( $old !== false && $old !== $text && !$arg ) {
432 $converter = $parser->getConverterLanguage()->getConverter();
433 return '<span class="error">' .
434 wfMessage( 'duplicate-displaytitle',
435 // Message should be parsed, but these params should only be escaped.
436 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
437 $converter->markNoConversion( wfEscapeWikiText( $text ) )
438 )->inContentLanguage()->text() .
447 * Matches the given value against the value of given magic word
449 * @param string $magicword Magic word key
450 * @param string $value Value to match
451 * @return bool True on successful match
453 private static function matchAgainstMagicword( $magicword, $value ) {
454 $value = trim( strval( $value ) );
455 if ( $value === '' ) {
458 $mwObject = MagicWord
::get( $magicword );
459 return $mwObject->matchStartToEnd( $value );
462 public static function formatRaw( $num, $raw ) {
463 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
467 return $wgContLang->formatNum( $num );
470 public static function numberofpages( $parser, $raw = null ) {
471 return self
::formatRaw( SiteStats
::pages(), $raw );
473 public static function numberofusers( $parser, $raw = null ) {
474 return self
::formatRaw( SiteStats
::users(), $raw );
476 public static function numberofactiveusers( $parser, $raw = null ) {
477 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
479 public static function numberofarticles( $parser, $raw = null ) {
480 return self
::formatRaw( SiteStats
::articles(), $raw );
482 public static function numberoffiles( $parser, $raw = null ) {
483 return self
::formatRaw( SiteStats
::images(), $raw );
485 public static function numberofadmins( $parser, $raw = null ) {
486 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
488 public static function numberofedits( $parser, $raw = null ) {
489 return self
::formatRaw( SiteStats
::edits(), $raw );
491 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
492 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
494 public static function numberingroup( $parser, $name = '', $raw = null ) {
495 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
499 * Given a title, return the namespace name that would be given by the
500 * corresponding magic word
501 * Note: function name changed to "mwnamespace" rather than "namespace"
502 * to not break PHP 5.3
503 * @param Parser $parser
504 * @param string $title
505 * @return mixed|string
507 public static function mwnamespace( $parser, $title = null ) {
508 $t = Title
::newFromText( $title );
509 if ( is_null( $t ) ) {
512 return str_replace( '_', ' ', $t->getNsText() );
514 public static function namespacee( $parser, $title = null ) {
515 $t = Title
::newFromText( $title );
516 if ( is_null( $t ) ) {
519 return wfUrlencode( $t->getNsText() );
521 public static function namespacenumber( $parser, $title = null ) {
522 $t = Title
::newFromText( $title );
523 if ( is_null( $t ) ) {
526 return $t->getNamespace();
528 public static function talkspace( $parser, $title = null ) {
529 $t = Title
::newFromText( $title );
530 if ( is_null( $t ) ||
!$t->canTalk() ) {
533 return str_replace( '_', ' ', $t->getTalkNsText() );
535 public static function talkspacee( $parser, $title = null ) {
536 $t = Title
::newFromText( $title );
537 if ( is_null( $t ) ||
!$t->canTalk() ) {
540 return wfUrlencode( $t->getTalkNsText() );
542 public static function subjectspace( $parser, $title = null ) {
543 $t = Title
::newFromText( $title );
544 if ( is_null( $t ) ) {
547 return str_replace( '_', ' ', $t->getSubjectNsText() );
549 public static function subjectspacee( $parser, $title = null ) {
550 $t = Title
::newFromText( $title );
551 if ( is_null( $t ) ) {
554 return wfUrlencode( $t->getSubjectNsText() );
558 * Functions to get and normalize pagenames, corresponding to the magic words
560 * @param Parser $parser
561 * @param string $title
564 public static function pagename( $parser, $title = null ) {
565 $t = Title
::newFromText( $title );
566 if ( is_null( $t ) ) {
569 return wfEscapeWikiText( $t->getText() );
571 public static function pagenamee( $parser, $title = null ) {
572 $t = Title
::newFromText( $title );
573 if ( is_null( $t ) ) {
576 return wfEscapeWikiText( $t->getPartialURL() );
578 public static function fullpagename( $parser, $title = null ) {
579 $t = Title
::newFromText( $title );
580 if ( is_null( $t ) ||
!$t->canTalk() ) {
583 return wfEscapeWikiText( $t->getPrefixedText() );
585 public static function fullpagenamee( $parser, $title = null ) {
586 $t = Title
::newFromText( $title );
587 if ( is_null( $t ) ||
!$t->canTalk() ) {
590 return wfEscapeWikiText( $t->getPrefixedURL() );
592 public static function subpagename( $parser, $title = null ) {
593 $t = Title
::newFromText( $title );
594 if ( is_null( $t ) ) {
597 return wfEscapeWikiText( $t->getSubpageText() );
599 public static function subpagenamee( $parser, $title = null ) {
600 $t = Title
::newFromText( $title );
601 if ( is_null( $t ) ) {
604 return wfEscapeWikiText( $t->getSubpageUrlForm() );
606 public static function rootpagename( $parser, $title = null ) {
607 $t = Title
::newFromText( $title );
608 if ( is_null( $t ) ) {
611 return wfEscapeWikiText( $t->getRootText() );
613 public static function rootpagenamee( $parser, $title = null ) {
614 $t = Title
::newFromText( $title );
615 if ( is_null( $t ) ) {
618 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
620 public static function basepagename( $parser, $title = null ) {
621 $t = Title
::newFromText( $title );
622 if ( is_null( $t ) ) {
625 return wfEscapeWikiText( $t->getBaseText() );
627 public static function basepagenamee( $parser, $title = null ) {
628 $t = Title
::newFromText( $title );
629 if ( is_null( $t ) ) {
632 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
634 public static function talkpagename( $parser, $title = null ) {
635 $t = Title
::newFromText( $title );
636 if ( is_null( $t ) ||
!$t->canTalk() ) {
639 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
641 public static function talkpagenamee( $parser, $title = null ) {
642 $t = Title
::newFromText( $title );
643 if ( is_null( $t ) ||
!$t->canTalk() ) {
646 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
648 public static function subjectpagename( $parser, $title = null ) {
649 $t = Title
::newFromText( $title );
650 if ( is_null( $t ) ) {
653 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
655 public static function subjectpagenamee( $parser, $title = null ) {
656 $t = Title
::newFromText( $title );
657 if ( is_null( $t ) ) {
660 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
664 * Return the number of pages, files or subcats in the given category,
665 * or 0 if it's nonexistent. This is an expensive parser function and
666 * can't be called too many times per page.
667 * @param Parser $parser
668 * @param string $name
669 * @param string $arg1
670 * @param string $arg2
673 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
675 static $magicWords = null;
676 if ( is_null( $magicWords ) ) {
677 $magicWords = new MagicWordArray( array(
678 'pagesincategory_all',
679 'pagesincategory_pages',
680 'pagesincategory_subcats',
681 'pagesincategory_files'
684 static $cache = array();
686 // split the given option to its variable
687 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
688 //{{pagesincategory:|raw[|type]}}
690 $type = $magicWords->matchStartToEnd( $arg2 );
692 //{{pagesincategory:[|type[|raw]]}}
693 $type = $magicWords->matchStartToEnd( $arg1 );
696 if ( !$type ) { //backward compatibility
697 $type = 'pagesincategory_all';
700 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
701 if ( !$title ) { # invalid title
702 return self
::formatRaw( 0, $raw );
704 $wgContLang->findVariantLink( $name, $title, true );
706 // Normalize name for cache
707 $name = $title->getDBkey();
709 if ( !isset( $cache[$name] ) ) {
710 $category = Category
::newFromTitle( $title );
712 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
713 if ( $parser->incrementExpensiveFunctionCount() ) {
714 // $allCount is the total number of cat members,
715 // not the count of how many members are normal pages.
716 $allCount = (int)$category->getPageCount();
717 $subcatCount = (int)$category->getSubcatCount();
718 $fileCount = (int)$category->getFileCount();
719 $pagesCount = $allCount - $subcatCount - $fileCount;
721 $cache[$name]['pagesincategory_all'] = $allCount;
722 $cache[$name]['pagesincategory_pages'] = $pagesCount;
723 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
724 $cache[$name]['pagesincategory_files'] = $fileCount;
727 $count = $cache[$name][$type];
728 return self
::formatRaw( $count, $raw );
732 * Return the size of the given page, or 0 if it's nonexistent. This is an
733 * expensive parser function and can't be called too many times per page.
735 * @param Parser $parser
736 * @param string $page Name of page to check (Default: empty string)
737 * @param string $raw Should number be human readable with commas or just number
740 public static function pagesize( $parser, $page = '', $raw = null ) {
741 $title = Title
::newFromText( $page );
743 if ( !is_object( $title ) ) {
744 return self
::formatRaw( 0, $raw );
747 // fetch revision from cache/database and return the value
748 $rev = self
::getCachedRevisionObject( $parser, $title );
749 $length = $rev ?
$rev->getSize() : 0;
750 return self
::formatRaw( $length, $raw );
754 * Returns the requested protection level for the current page. This
755 * is an expensive parser function and can't be called too many times
756 * per page, unless the protection levels for the given title have
757 * already been retrieved
759 * @param Parser $parser
760 * @param string $type
761 * @param string $title
765 public static function protectionlevel( $parser, $type = '', $title = '' ) {
766 $titleObject = Title
::newFromText( $title );
767 if ( !( $titleObject instanceof Title
) ) {
768 $titleObject = $parser->mTitle
;
770 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
771 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
772 # Title::getRestrictions returns an array, its possible it may have
773 # multiple values in the future
774 return implode( $restrictions, ',' );
780 * Gives language names.
781 * @param Parser $parser
782 * @param string $code Language code (of which to get name)
783 * @param string $inLanguage Language code (in which to get name)
786 public static function language( $parser, $code = '', $inLanguage = '' ) {
787 $code = strtolower( $code );
788 $inLanguage = strtolower( $inLanguage );
789 $lang = Language
::fetchLanguageName( $code, $inLanguage );
790 return $lang !== '' ?
$lang : wfBCP47( $code );
794 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
795 * @param Parser $parser
796 * @param string $string
798 * @param string $padding
799 * @param int $direction
802 public static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
803 $padding = $parser->killMarkers( $padding );
804 $lengthOfPadding = mb_strlen( $padding );
805 if ( $lengthOfPadding == 0 ) {
809 # The remaining length to add counts down to 0 as padding is added
810 $length = min( $length, 500 ) - mb_strlen( $string );
811 # $finalPadding is just $padding repeated enough times so that
812 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
814 while ( $length > 0 ) {
815 # If $length < $lengthofPadding, truncate $padding so we get the
816 # exact length desired.
817 $finalPadding .= mb_substr( $padding, 0, $length );
818 $length -= $lengthOfPadding;
821 if ( $direction == STR_PAD_LEFT
) {
822 return $finalPadding . $string;
824 return $string . $finalPadding;
828 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
829 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
832 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
833 return self
::pad( $parser, $string, $length, $padding );
837 * @param Parser $parser
838 * @param string $text
841 public static function anchorencode( $parser, $text ) {
842 $text = $parser->killMarkers( $text );
843 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
846 public static function special( $parser, $text ) {
847 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
849 $title = SpecialPage
::getTitleFor( $page, $subpage );
850 return $title->getPrefixedText();
852 // unknown special page, just use the given text as its title, if at all possible
853 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
854 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
858 public static function speciale( $parser, $text ) {
859 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
863 * @param Parser $parser
864 * @param string $text The sortkey to use
865 * @param string $uarg Either "noreplace" or "noerror" (in en)
866 * both suppress errors, and noreplace does nothing if
867 * a default sortkey already exists.
870 public static function defaultsort( $parser, $text, $uarg = '' ) {
871 static $magicWords = null;
872 if ( is_null( $magicWords ) ) {
873 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
875 $arg = $magicWords->matchStartToEnd( $uarg );
877 $text = trim( $text );
878 if ( strlen( $text ) == 0 ) {
881 $old = $parser->getCustomDefaultSort();
882 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
883 $parser->setDefaultSort( $text );
886 if ( $old === false ||
$old == $text ||
$arg ) {
889 $converter = $parser->getConverterLanguage()->getConverter();
890 return '<span class="error">' .
891 wfMessage( 'duplicate-defaultsort',
892 // Message should be parsed, but these params should only be escaped.
893 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
894 $converter->markNoConversion( wfEscapeWikiText( $text ) )
895 )->inContentLanguage()->text() .
900 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
901 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
902 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
903 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
904 $file = wfFindFile( $name );
906 if ( $argA == 'nowiki' ) {
907 // {{filepath: | option [| size] }}
909 $parsedWidthParam = $parser->parseWidthParam( $argB );
911 // {{filepath: [| size [|option]] }}
912 $parsedWidthParam = $parser->parseWidthParam( $argA );
913 $isNowiki = ( $argB == 'nowiki' );
917 $url = $file->getFullUrl();
919 // If a size is requested...
920 if ( count( $parsedWidthParam ) ) {
921 $mto = $file->transform( $parsedWidthParam );
923 if ( $mto && !$mto->isError() ) {
924 // ... change the URL to point to a thumbnail.
925 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
929 return array( $url, 'nowiki' => true );
938 * Parser function to extension tag adaptor
939 * @param Parser $parser
940 * @param PPFrame $frame
944 public static function tagObj( $parser, $frame, $args ) {
945 if ( !count( $args ) ) {
948 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
950 if ( count( $args ) ) {
951 $inner = $frame->expand( array_shift( $args ) );
956 $stripList = $parser->getStripList();
957 if ( !in_array( $tagName, $stripList ) ) {
958 return '<span class="error">' .
959 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
963 $attributes = array();
964 foreach ( $args as $arg ) {
965 $bits = $arg->splitArg();
966 if ( strval( $bits['index'] ) === '' ) {
967 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
968 $value = trim( $frame->expand( $bits['value'] ) );
969 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
970 $value = isset( $m[1] ) ?
$m[1] : '';
972 $attributes[$name] = $value;
979 'attributes' => $attributes,
980 'close' => "</$tagName>",
982 return $parser->extensionSubstitution( $params, $frame );
986 * Fetched the current revision of the given title and return this.
987 * Will increment the expensive function count and
988 * add a template link to get the value refreshed on changes.
989 * For a given title, which is equal to the current parser title,
990 * the revision object from the parser is used, when that is the current one
992 * @param Parser $parser
993 * @param Title $title
997 private static function getCachedRevisionObject( $parser, $title = null ) {
998 if ( is_null( $title ) ) {
1002 // Use the revision from the parser itself, when param is the current page
1003 // and the revision is the current one
1004 if ( $title->equals( $parser->getTitle() ) ) {
1005 $parserRev = $parser->getRevisionObject();
1006 if ( $parserRev && $parserRev->isCurrent() ) {
1007 // force reparse after edit with vary-revision flag
1008 $parser->getOutput()->setFlag( 'vary-revision' );
1009 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1014 // Normalize name for cache
1015 $page = $title->getPrefixedDBkey();
1017 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1018 && !$parser->incrementExpensiveFunctionCount() ) {
1021 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1022 $pageID = $rev ?
$rev->getPage() : 0;
1023 $revID = $rev ?
$rev->getId() : 0;
1025 // Register dependency in templatelinks
1026 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1032 * Get the pageid of a specified page
1033 * @param Parser $parser
1034 * @param string $title Title to get the pageid from
1035 * @return int|null|string
1038 public static function pageid( $parser, $title = null ) {
1039 $t = Title
::newFromText( $title );
1040 if ( is_null( $t ) ) {
1043 // Use title from parser to have correct pageid after edit
1044 if ( $t->equals( $parser->getTitle() ) ) {
1045 $t = $parser->getTitle();
1046 return $t->getArticleID();
1049 // These can't have ids
1050 if ( !$t->canExist() ||
$t->isExternal() ) {
1054 // Check the link cache, maybe something already looked it up.
1055 $linkCache = LinkCache
::singleton();
1056 $pdbk = $t->getPrefixedDBkey();
1057 $id = $linkCache->getGoodLinkID( $pdbk );
1059 $parser->mOutput
->addLink( $t, $id );
1062 if ( $linkCache->isBadLink( $pdbk ) ) {
1063 $parser->mOutput
->addLink( $t, 0 );
1067 // We need to load it from the DB, so mark expensive
1068 if ( $parser->incrementExpensiveFunctionCount() ) {
1069 $id = $t->getArticleID();
1070 $parser->mOutput
->addLink( $t, $id );
1077 * Get the id from the last revision of a specified page.
1078 * @param Parser $parser
1079 * @param string $title Title to get the id from
1080 * @return int|null|string
1083 public static function revisionid( $parser, $title = null ) {
1084 $t = Title
::newFromText( $title );
1085 if ( is_null( $t ) ) {
1088 // fetch revision from cache/database and return the value
1089 $rev = self
::getCachedRevisionObject( $parser, $t );
1090 return $rev ?
$rev->getId() : '';
1094 * Get the day from the last revision of a specified page.
1095 * @param Parser $parser
1096 * @param string $title Title to get the day from
1100 public static function revisionday( $parser, $title = null ) {
1101 $t = Title
::newFromText( $title );
1102 if ( is_null( $t ) ) {
1105 // fetch revision from cache/database and return the value
1106 $rev = self
::getCachedRevisionObject( $parser, $t );
1107 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1111 * Get the day with leading zeros from the last revision of a specified page.
1112 * @param Parser $parser
1113 * @param string $title Title to get the day from
1117 public static function revisionday2( $parser, $title = null ) {
1118 $t = Title
::newFromText( $title );
1119 if ( is_null( $t ) ) {
1122 // fetch revision from cache/database and return the value
1123 $rev = self
::getCachedRevisionObject( $parser, $t );
1124 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1128 * Get the month with leading zeros from the last revision of a specified page.
1129 * @param Parser $parser
1130 * @param string $title Title to get the month from
1134 public static function revisionmonth( $parser, $title = null ) {
1135 $t = Title
::newFromText( $title );
1136 if ( is_null( $t ) ) {
1139 // fetch revision from cache/database and return the value
1140 $rev = self
::getCachedRevisionObject( $parser, $t );
1141 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1145 * Get the month from the last revision of a specified page.
1146 * @param Parser $parser
1147 * @param string $title Title to get the month from
1151 public static function revisionmonth1( $parser, $title = null ) {
1152 $t = Title
::newFromText( $title );
1153 if ( is_null( $t ) ) {
1156 // fetch revision from cache/database and return the value
1157 $rev = self
::getCachedRevisionObject( $parser, $t );
1158 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1162 * Get the year from the last revision of a specified page.
1163 * @param Parser $parser
1164 * @param string $title Title to get the year from
1168 public static function revisionyear( $parser, $title = null ) {
1169 $t = Title
::newFromText( $title );
1170 if ( is_null( $t ) ) {
1173 // fetch revision from cache/database and return the value
1174 $rev = self
::getCachedRevisionObject( $parser, $t );
1175 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1179 * Get the timestamp from the last revision of a specified page.
1180 * @param Parser $parser
1181 * @param string $title Title to get the timestamp from
1185 public static function revisiontimestamp( $parser, $title = null ) {
1186 $t = Title
::newFromText( $title );
1187 if ( is_null( $t ) ) {
1190 // fetch revision from cache/database and return the value
1191 $rev = self
::getCachedRevisionObject( $parser, $t );
1192 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1196 * Get the user from the last revision of a specified page.
1197 * @param Parser $parser
1198 * @param string $title Title to get the user from
1202 public static function revisionuser( $parser, $title = null ) {
1203 $t = Title
::newFromText( $title );
1204 if ( is_null( $t ) ) {
1207 // fetch revision from cache/database and return the value
1208 $rev = self
::getCachedRevisionObject( $parser, $t );
1209 return $rev ?
$rev->getUserText() : '';
1213 * Returns the sources of any cascading protection acting on a specified page.
1214 * Pages will not return their own title unless they transclude themselves.
1215 * This is an expensive parser function and can't be called too many times per page,
1216 * unless cascading protection sources for the page have already been loaded.
1218 * @param Parser $parser
1219 * @param string $title
1224 public static function cascadingsources( $parser, $title = '' ) {
1225 $titleObject = Title
::newFromText( $title );
1226 if ( !( $titleObject instanceof Title
) ) {
1227 $titleObject = $parser->mTitle
;
1229 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1230 ||
$parser->incrementExpensiveFunctionCount()
1233 $sources = $titleObject->getCascadeProtectionSources();
1234 foreach ( $sources[0] as $sourceTitle ) {
1235 $names[] = $sourceTitle->getPrefixedText();
1237 return implode( $names, '|' );