88288269513cc12a9cec336fef80853ab2d26a1d
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 = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
383 . preg_quote( Parser
::MARKER_SUFFIX
, '/' ) . '/', '', $text );
385 // list of disallowed tags for DISPLAYTITLE
386 // these will be escaped even though they are allowed in normal wiki text
387 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
388 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' );
390 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
391 if ( $wgRestrictDisplayTitle ) {
392 $htmlTagsCallback = function ( &$params ) {
393 $decoded = Sanitizer
::decodeTagAttributes( $params );
395 if ( isset( $decoded['style'] ) ) {
396 // this is called later anyway, but we need it right now for the regexes below to be safe
397 // calling it twice doesn't hurt
398 $decoded['style'] = Sanitizer
::checkCss( $decoded['style'] );
400 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
401 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
405 $params = Sanitizer
::safeEncodeTagAttributes( $decoded );
408 $htmlTagsCallback = null;
411 // only requested titles that normalize to the actual title are allowed through
412 // if $wgRestrictDisplayTitle is true (it is by default)
413 // mimic the escaping process that occurs in OutputPage::setPageTitle
414 $text = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags(
421 $title = Title
::newFromText( Sanitizer
::stripAllTags( $text ) );
423 if ( !$wgRestrictDisplayTitle ||
424 ( $title instanceof Title
425 && !$title->hasFragment()
426 && $title->equals( $parser->mTitle
) )
428 $old = $parser->mOutput
->getProperty( 'displaytitle' );
429 if ( $old === false ||
$arg !== 'displaytitle_noreplace' ) {
430 $parser->mOutput
->setDisplayTitle( $text );
432 if ( $old !== false && $old !== $text && !$arg ) {
433 $converter = $parser->getConverterLanguage()->getConverter();
434 return '<span class="error">' .
435 wfMessage( 'duplicate-displaytitle',
436 // Message should be parsed, but these params should only be escaped.
437 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
438 $converter->markNoConversion( wfEscapeWikiText( $text ) )
439 )->inContentLanguage()->text() .
448 * Matches the given value against the value of given magic word
450 * @param string $magicword Magic word key
451 * @param string $value Value to match
452 * @return bool True on successful match
454 private static function matchAgainstMagicword( $magicword, $value ) {
455 $value = trim( strval( $value ) );
456 if ( $value === '' ) {
459 $mwObject = MagicWord
::get( $magicword );
460 return $mwObject->matchStartToEnd( $value );
463 public static function formatRaw( $num, $raw ) {
464 if ( self
::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
468 return $wgContLang->formatNum( $num );
471 public static function numberofpages( $parser, $raw = null ) {
472 return self
::formatRaw( SiteStats
::pages(), $raw );
474 public static function numberofusers( $parser, $raw = null ) {
475 return self
::formatRaw( SiteStats
::users(), $raw );
477 public static function numberofactiveusers( $parser, $raw = null ) {
478 return self
::formatRaw( SiteStats
::activeUsers(), $raw );
480 public static function numberofarticles( $parser, $raw = null ) {
481 return self
::formatRaw( SiteStats
::articles(), $raw );
483 public static function numberoffiles( $parser, $raw = null ) {
484 return self
::formatRaw( SiteStats
::images(), $raw );
486 public static function numberofadmins( $parser, $raw = null ) {
487 return self
::formatRaw( SiteStats
::numberingroup( 'sysop' ), $raw );
489 public static function numberofedits( $parser, $raw = null ) {
490 return self
::formatRaw( SiteStats
::edits(), $raw );
492 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
493 return self
::formatRaw( SiteStats
::pagesInNs( intval( $namespace ) ), $raw );
495 public static function numberingroup( $parser, $name = '', $raw = null ) {
496 return self
::formatRaw( SiteStats
::numberingroup( strtolower( $name ) ), $raw );
500 * Given a title, return the namespace name that would be given by the
501 * corresponding magic word
502 * Note: function name changed to "mwnamespace" rather than "namespace"
503 * to not break PHP 5.3
504 * @param Parser $parser
505 * @param string $title
506 * @return mixed|string
508 public static function mwnamespace( $parser, $title = null ) {
509 $t = Title
::newFromText( $title );
510 if ( is_null( $t ) ) {
513 return str_replace( '_', ' ', $t->getNsText() );
515 public static function namespacee( $parser, $title = null ) {
516 $t = Title
::newFromText( $title );
517 if ( is_null( $t ) ) {
520 return wfUrlencode( $t->getNsText() );
522 public static function namespacenumber( $parser, $title = null ) {
523 $t = Title
::newFromText( $title );
524 if ( is_null( $t ) ) {
527 return $t->getNamespace();
529 public static function talkspace( $parser, $title = null ) {
530 $t = Title
::newFromText( $title );
531 if ( is_null( $t ) ||
!$t->canTalk() ) {
534 return str_replace( '_', ' ', $t->getTalkNsText() );
536 public static function talkspacee( $parser, $title = null ) {
537 $t = Title
::newFromText( $title );
538 if ( is_null( $t ) ||
!$t->canTalk() ) {
541 return wfUrlencode( $t->getTalkNsText() );
543 public static function subjectspace( $parser, $title = null ) {
544 $t = Title
::newFromText( $title );
545 if ( is_null( $t ) ) {
548 return str_replace( '_', ' ', $t->getSubjectNsText() );
550 public static function subjectspacee( $parser, $title = null ) {
551 $t = Title
::newFromText( $title );
552 if ( is_null( $t ) ) {
555 return wfUrlencode( $t->getSubjectNsText() );
559 * Functions to get and normalize pagenames, corresponding to the magic words
561 * @param Parser $parser
562 * @param string $title
565 public static function pagename( $parser, $title = null ) {
566 $t = Title
::newFromText( $title );
567 if ( is_null( $t ) ) {
570 return wfEscapeWikiText( $t->getText() );
572 public static function pagenamee( $parser, $title = null ) {
573 $t = Title
::newFromText( $title );
574 if ( is_null( $t ) ) {
577 return wfEscapeWikiText( $t->getPartialURL() );
579 public static function fullpagename( $parser, $title = null ) {
580 $t = Title
::newFromText( $title );
581 if ( is_null( $t ) ||
!$t->canTalk() ) {
584 return wfEscapeWikiText( $t->getPrefixedText() );
586 public static function fullpagenamee( $parser, $title = null ) {
587 $t = Title
::newFromText( $title );
588 if ( is_null( $t ) ||
!$t->canTalk() ) {
591 return wfEscapeWikiText( $t->getPrefixedURL() );
593 public static function subpagename( $parser, $title = null ) {
594 $t = Title
::newFromText( $title );
595 if ( is_null( $t ) ) {
598 return wfEscapeWikiText( $t->getSubpageText() );
600 public static function subpagenamee( $parser, $title = null ) {
601 $t = Title
::newFromText( $title );
602 if ( is_null( $t ) ) {
605 return wfEscapeWikiText( $t->getSubpageUrlForm() );
607 public static function rootpagename( $parser, $title = null ) {
608 $t = Title
::newFromText( $title );
609 if ( is_null( $t ) ) {
612 return wfEscapeWikiText( $t->getRootText() );
614 public static function rootpagenamee( $parser, $title = null ) {
615 $t = Title
::newFromText( $title );
616 if ( is_null( $t ) ) {
619 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
621 public static function basepagename( $parser, $title = null ) {
622 $t = Title
::newFromText( $title );
623 if ( is_null( $t ) ) {
626 return wfEscapeWikiText( $t->getBaseText() );
628 public static function basepagenamee( $parser, $title = null ) {
629 $t = Title
::newFromText( $title );
630 if ( is_null( $t ) ) {
633 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
635 public static function talkpagename( $parser, $title = null ) {
636 $t = Title
::newFromText( $title );
637 if ( is_null( $t ) ||
!$t->canTalk() ) {
640 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
642 public static function talkpagenamee( $parser, $title = null ) {
643 $t = Title
::newFromText( $title );
644 if ( is_null( $t ) ||
!$t->canTalk() ) {
647 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
649 public static function subjectpagename( $parser, $title = null ) {
650 $t = Title
::newFromText( $title );
651 if ( is_null( $t ) ) {
654 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
656 public static function subjectpagenamee( $parser, $title = null ) {
657 $t = Title
::newFromText( $title );
658 if ( is_null( $t ) ) {
661 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
665 * Return the number of pages, files or subcats in the given category,
666 * or 0 if it's nonexistent. This is an expensive parser function and
667 * can't be called too many times per page.
668 * @param Parser $parser
669 * @param string $name
670 * @param string $arg1
671 * @param string $arg2
674 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
676 static $magicWords = null;
677 if ( is_null( $magicWords ) ) {
678 $magicWords = new MagicWordArray( array(
679 'pagesincategory_all',
680 'pagesincategory_pages',
681 'pagesincategory_subcats',
682 'pagesincategory_files'
685 static $cache = array();
687 // split the given option to its variable
688 if ( self
::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
689 //{{pagesincategory:|raw[|type]}}
691 $type = $magicWords->matchStartToEnd( $arg2 );
693 //{{pagesincategory:[|type[|raw]]}}
694 $type = $magicWords->matchStartToEnd( $arg1 );
697 if ( !$type ) { //backward compatibility
698 $type = 'pagesincategory_all';
701 $title = Title
::makeTitleSafe( NS_CATEGORY
, $name );
702 if ( !$title ) { # invalid title
703 return self
::formatRaw( 0, $raw );
705 $wgContLang->findVariantLink( $name, $title, true );
707 // Normalize name for cache
708 $name = $title->getDBkey();
710 if ( !isset( $cache[$name] ) ) {
711 $category = Category
::newFromTitle( $title );
713 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
714 if ( $parser->incrementExpensiveFunctionCount() ) {
715 // $allCount is the total number of cat members,
716 // not the count of how many members are normal pages.
717 $allCount = (int)$category->getPageCount();
718 $subcatCount = (int)$category->getSubcatCount();
719 $fileCount = (int)$category->getFileCount();
720 $pagesCount = $allCount - $subcatCount - $fileCount;
722 $cache[$name]['pagesincategory_all'] = $allCount;
723 $cache[$name]['pagesincategory_pages'] = $pagesCount;
724 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
725 $cache[$name]['pagesincategory_files'] = $fileCount;
728 $count = $cache[$name][$type];
729 return self
::formatRaw( $count, $raw );
733 * Return the size of the given page, or 0 if it's nonexistent. This is an
734 * expensive parser function and can't be called too many times per page.
736 * @param Parser $parser
737 * @param string $page Name of page to check (Default: empty string)
738 * @param string $raw Should number be human readable with commas or just number
741 public static function pagesize( $parser, $page = '', $raw = null ) {
742 $title = Title
::newFromText( $page );
744 if ( !is_object( $title ) ) {
745 return self
::formatRaw( 0, $raw );
748 // fetch revision from cache/database and return the value
749 $rev = self
::getCachedRevisionObject( $parser, $title );
750 $length = $rev ?
$rev->getSize() : 0;
751 return self
::formatRaw( $length, $raw );
755 * Returns the requested protection level for the current page. This
756 * is an expensive parser function and can't be called too many times
757 * per page, unless the protection levels for the given title have
758 * already been retrieved
760 * @param Parser $parser
761 * @param string $type
762 * @param string $title
766 public static function protectionlevel( $parser, $type = '', $title = '' ) {
767 $titleObject = Title
::newFromText( $title );
768 if ( !( $titleObject instanceof Title
) ) {
769 $titleObject = $parser->mTitle
;
771 if ( $titleObject->areRestrictionsLoaded() ||
$parser->incrementExpensiveFunctionCount() ) {
772 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
773 # Title::getRestrictions returns an array, its possible it may have
774 # multiple values in the future
775 return implode( $restrictions, ',' );
781 * Gives language names.
782 * @param Parser $parser
783 * @param string $code Language code (of which to get name)
784 * @param string $inLanguage Language code (in which to get name)
787 public static function language( $parser, $code = '', $inLanguage = '' ) {
788 $code = strtolower( $code );
789 $inLanguage = strtolower( $inLanguage );
790 $lang = Language
::fetchLanguageName( $code, $inLanguage );
791 return $lang !== '' ?
$lang : wfBCP47( $code );
795 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
796 * @param Parser $parser
797 * @param string $string
799 * @param string $padding
800 * @param int $direction
803 public static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
) {
804 $padding = $parser->killMarkers( $padding );
805 $lengthOfPadding = mb_strlen( $padding );
806 if ( $lengthOfPadding == 0 ) {
810 # The remaining length to add counts down to 0 as padding is added
811 $length = min( $length, 500 ) - mb_strlen( $string );
812 # $finalPadding is just $padding repeated enough times so that
813 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
815 while ( $length > 0 ) {
816 # If $length < $lengthofPadding, truncate $padding so we get the
817 # exact length desired.
818 $finalPadding .= mb_substr( $padding, 0, $length );
819 $length -= $lengthOfPadding;
822 if ( $direction == STR_PAD_LEFT
) {
823 return $finalPadding . $string;
825 return $string . $finalPadding;
829 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
830 return self
::pad( $parser, $string, $length, $padding, STR_PAD_LEFT
);
833 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
834 return self
::pad( $parser, $string, $length, $padding );
838 * @param Parser $parser
839 * @param string $text
842 public static function anchorencode( $parser, $text ) {
843 $text = $parser->killMarkers( $text );
844 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
847 public static function special( $parser, $text ) {
848 list( $page, $subpage ) = SpecialPageFactory
::resolveAlias( $text );
850 $title = SpecialPage
::getTitleFor( $page, $subpage );
851 return $title->getPrefixedText();
853 // unknown special page, just use the given text as its title, if at all possible
854 $title = Title
::makeTitleSafe( NS_SPECIAL
, $text );
855 return $title ?
$title->getPrefixedText() : self
::special( $parser, 'Badtitle' );
859 public static function speciale( $parser, $text ) {
860 return wfUrlencode( str_replace( ' ', '_', self
::special( $parser, $text ) ) );
864 * @param Parser $parser
865 * @param string $text The sortkey to use
866 * @param string $uarg Either "noreplace" or "noerror" (in en)
867 * both suppress errors, and noreplace does nothing if
868 * a default sortkey already exists.
871 public static function defaultsort( $parser, $text, $uarg = '' ) {
872 static $magicWords = null;
873 if ( is_null( $magicWords ) ) {
874 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
876 $arg = $magicWords->matchStartToEnd( $uarg );
878 $text = trim( $text );
879 if ( strlen( $text ) == 0 ) {
882 $old = $parser->getCustomDefaultSort();
883 if ( $old === false ||
$arg !== 'defaultsort_noreplace' ) {
884 $parser->setDefaultSort( $text );
887 if ( $old === false ||
$old == $text ||
$arg ) {
890 $converter = $parser->getConverterLanguage()->getConverter();
891 return '<span class="error">' .
892 wfMessage( 'duplicate-defaultsort',
893 // Message should be parsed, but these params should only be escaped.
894 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
895 $converter->markNoConversion( wfEscapeWikiText( $text ) )
896 )->inContentLanguage()->text() .
901 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
902 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
903 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
904 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
905 $file = wfFindFile( $name );
907 if ( $argA == 'nowiki' ) {
908 // {{filepath: | option [| size] }}
910 $parsedWidthParam = $parser->parseWidthParam( $argB );
912 // {{filepath: [| size [|option]] }}
913 $parsedWidthParam = $parser->parseWidthParam( $argA );
914 $isNowiki = ( $argB == 'nowiki' );
918 $url = $file->getFullUrl();
920 // If a size is requested...
921 if ( count( $parsedWidthParam ) ) {
922 $mto = $file->transform( $parsedWidthParam );
924 if ( $mto && !$mto->isError() ) {
925 // ... change the URL to point to a thumbnail.
926 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE
);
930 return array( $url, 'nowiki' => true );
939 * Parser function to extension tag adaptor
940 * @param Parser $parser
941 * @param PPFrame $frame
945 public static function tagObj( $parser, $frame, $args ) {
946 if ( !count( $args ) ) {
949 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
951 if ( count( $args ) ) {
952 $inner = $frame->expand( array_shift( $args ) );
957 $stripList = $parser->getStripList();
958 if ( !in_array( $tagName, $stripList ) ) {
959 return '<span class="error">' .
960 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
964 $attributes = array();
965 foreach ( $args as $arg ) {
966 $bits = $arg->splitArg();
967 if ( strval( $bits['index'] ) === '' ) {
968 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
969 $value = trim( $frame->expand( $bits['value'] ) );
970 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
971 $value = isset( $m[1] ) ?
$m[1] : '';
973 $attributes[$name] = $value;
980 'attributes' => $attributes,
981 'close' => "</$tagName>",
983 return $parser->extensionSubstitution( $params, $frame );
987 * Fetched the current revision of the given title and return this.
988 * Will increment the expensive function count and
989 * add a template link to get the value refreshed on changes.
990 * For a given title, which is equal to the current parser title,
991 * the revision object from the parser is used, when that is the current one
993 * @param Parser $parser
994 * @param Title $title
998 private static function getCachedRevisionObject( $parser, $title = null ) {
999 if ( is_null( $title ) ) {
1003 // Use the revision from the parser itself, when param is the current page
1004 // and the revision is the current one
1005 if ( $title->equals( $parser->getTitle() ) ) {
1006 $parserRev = $parser->getRevisionObject();
1007 if ( $parserRev && $parserRev->isCurrent() ) {
1008 // force reparse after edit with vary-revision flag
1009 $parser->getOutput()->setFlag( 'vary-revision' );
1010 wfDebug( __METHOD__
. ": use current revision from parser, setting vary-revision...\n" );
1015 // Normalize name for cache
1016 $page = $title->getPrefixedDBkey();
1018 if ( !( $parser->currentRevisionCache
&& $parser->currentRevisionCache
->has( $page ) )
1019 && !$parser->incrementExpensiveFunctionCount() ) {
1022 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1023 $pageID = $rev ?
$rev->getPage() : 0;
1024 $revID = $rev ?
$rev->getId() : 0;
1026 // Register dependency in templatelinks
1027 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1033 * Get the pageid of a specified page
1034 * @param Parser $parser
1035 * @param string $title Title to get the pageid from
1036 * @return int|null|string
1039 public static function pageid( $parser, $title = null ) {
1040 $t = Title
::newFromText( $title );
1041 if ( is_null( $t ) ) {
1044 // Use title from parser to have correct pageid after edit
1045 if ( $t->equals( $parser->getTitle() ) ) {
1046 $t = $parser->getTitle();
1047 return $t->getArticleID();
1050 // These can't have ids
1051 if ( !$t->canExist() ||
$t->isExternal() ) {
1055 // Check the link cache, maybe something already looked it up.
1056 $linkCache = LinkCache
::singleton();
1057 $pdbk = $t->getPrefixedDBkey();
1058 $id = $linkCache->getGoodLinkID( $pdbk );
1060 $parser->mOutput
->addLink( $t, $id );
1063 if ( $linkCache->isBadLink( $pdbk ) ) {
1064 $parser->mOutput
->addLink( $t, 0 );
1068 // We need to load it from the DB, so mark expensive
1069 if ( $parser->incrementExpensiveFunctionCount() ) {
1070 $id = $t->getArticleID();
1071 $parser->mOutput
->addLink( $t, $id );
1078 * Get the id from the last revision of a specified page.
1079 * @param Parser $parser
1080 * @param string $title Title to get the id from
1081 * @return int|null|string
1084 public static function revisionid( $parser, $title = null ) {
1085 $t = Title
::newFromText( $title );
1086 if ( is_null( $t ) ) {
1089 // fetch revision from cache/database and return the value
1090 $rev = self
::getCachedRevisionObject( $parser, $t );
1091 return $rev ?
$rev->getId() : '';
1095 * Get the day from the last revision of a specified page.
1096 * @param Parser $parser
1097 * @param string $title Title to get the day from
1101 public static function revisionday( $parser, $title = null ) {
1102 $t = Title
::newFromText( $title );
1103 if ( is_null( $t ) ) {
1106 // fetch revision from cache/database and return the value
1107 $rev = self
::getCachedRevisionObject( $parser, $t );
1108 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1112 * Get the day with leading zeros from the last revision of a specified page.
1113 * @param Parser $parser
1114 * @param string $title Title to get the day from
1118 public static function revisionday2( $parser, $title = null ) {
1119 $t = Title
::newFromText( $title );
1120 if ( is_null( $t ) ) {
1123 // fetch revision from cache/database and return the value
1124 $rev = self
::getCachedRevisionObject( $parser, $t );
1125 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1129 * Get the month with leading zeros from the last revision of a specified page.
1130 * @param Parser $parser
1131 * @param string $title Title to get the month from
1135 public static function revisionmonth( $parser, $title = null ) {
1136 $t = Title
::newFromText( $title );
1137 if ( is_null( $t ) ) {
1140 // fetch revision from cache/database and return the value
1141 $rev = self
::getCachedRevisionObject( $parser, $t );
1142 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1146 * Get the month from the last revision of a specified page.
1147 * @param Parser $parser
1148 * @param string $title Title to get the month from
1152 public static function revisionmonth1( $parser, $title = null ) {
1153 $t = Title
::newFromText( $title );
1154 if ( is_null( $t ) ) {
1157 // fetch revision from cache/database and return the value
1158 $rev = self
::getCachedRevisionObject( $parser, $t );
1159 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1163 * Get the year from the last revision of a specified page.
1164 * @param Parser $parser
1165 * @param string $title Title to get the year from
1169 public static function revisionyear( $parser, $title = null ) {
1170 $t = Title
::newFromText( $title );
1171 if ( is_null( $t ) ) {
1174 // fetch revision from cache/database and return the value
1175 $rev = self
::getCachedRevisionObject( $parser, $t );
1176 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1180 * Get the timestamp from the last revision of a specified page.
1181 * @param Parser $parser
1182 * @param string $title Title to get the timestamp from
1186 public static function revisiontimestamp( $parser, $title = null ) {
1187 $t = Title
::newFromText( $title );
1188 if ( is_null( $t ) ) {
1191 // fetch revision from cache/database and return the value
1192 $rev = self
::getCachedRevisionObject( $parser, $t );
1193 return $rev ? MWTimestamp
::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1197 * Get the user from the last revision of a specified page.
1198 * @param Parser $parser
1199 * @param string $title Title to get the user from
1203 public static function revisionuser( $parser, $title = null ) {
1204 $t = Title
::newFromText( $title );
1205 if ( is_null( $t ) ) {
1208 // fetch revision from cache/database and return the value
1209 $rev = self
::getCachedRevisionObject( $parser, $t );
1210 return $rev ?
$rev->getUserText() : '';
1214 * Returns the sources of any cascading protection acting on a specified page.
1215 * Pages will not return their own title unless they transclude themselves.
1216 * This is an expensive parser function and can't be called too many times per page,
1217 * unless cascading protection sources for the page have already been loaded.
1219 * @param Parser $parser
1220 * @param string $title
1225 public static function cascadingsources( $parser, $title = '' ) {
1226 $titleObject = Title
::newFromText( $title );
1227 if ( !( $titleObject instanceof Title
) ) {
1228 $titleObject = $parser->mTitle
;
1230 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1231 ||
$parser->incrementExpensiveFunctionCount()
1234 $sources = $titleObject->getCascadeProtectionSources();
1235 foreach ( $sources[0] as $sourceTitle ) {
1236 $names[] = $sourceTitle->getPrefixedText();
1238 return implode( $names, '|' );