Merge "Localisation updates from https://translatewiki.net."
[mediawiki.git] / includes / parser / CoreParserFunctions.php
blob65c3e1dbac4f658d74e3dcbcd94d0d481afa9552
1 <?php
2 /**
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
20 * @file
21 * @ingroup Parser
24 /**
25 * Various core parser functions, registered in Parser::firstCallInit()
26 * @ingroup Parser
28 class CoreParserFunctions {
29 /**
30 * @param Parser $parser
31 * @return void
33 static function register( $parser ) {
34 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36 # Syntax for arguments (see self::setFunctionHook):
37 # "name for lookup in localized magic words array",
38 # function callback,
39 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
40 # instead of {{#int:...}})
41 $noHashFunctions = array(
42 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
43 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
44 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural',
45 'numberofpages', 'numberofusers', 'numberofactiveusers',
46 'numberofarticles', 'numberoffiles', 'numberofadmins',
47 'numberingroup', 'numberofedits', 'numberofviews', 'language',
48 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
49 'pagesincategory', 'pagesize', 'protectionlevel',
50 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
51 'subjectspace', 'subjectspacee', 'pagename', 'pagenamee',
52 'fullpagename', 'fullpagenamee', 'rootpagename', 'rootpagenamee',
53 'basepagename', 'basepagenamee', 'subpagename', 'subpagenamee',
54 'talkpagename', 'talkpagenamee', 'subjectpagename',
55 'subjectpagenamee', 'pageid', 'revisionid', 'revisionday',
56 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
57 'revisiontimestamp', 'revisionuser', '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( 'pagesinnamespace', array( __CLASS__, 'pagesinnamespace' ), SFH_NO_HASH );
78 /**
79 * @param Parser $parser
80 * @param string $part1
81 * @return array
83 static function intFunction( $parser, $part1 = '' /*, ... */ ) {
84 if ( strval( $part1 ) !== '' ) {
85 $args = array_slice( func_get_args(), 2 );
86 $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain();
87 return array( $message, 'noparse' => false );
88 } else {
89 return array( 'found' => false );
93 /**
94 * @param Parser $parser
95 * @param string $date
96 * @param string $defaultPref
98 * @return string
100 static function formatDate( $parser, $date, $defaultPref = null ) {
101 $lang = $parser->getFunctionLang();
102 $df = DateFormatter::getInstance( $lang );
104 $date = trim( $date );
106 $pref = $parser->getOptions()->getDateFormat();
108 // Specify a different default date format other than the the normal default
109 // if the user has 'default' for their setting
110 if ( $pref == 'default' && $defaultPref ) {
111 $pref = $defaultPref;
114 $date = $df->reformat( $pref, $date, array( 'match-whole' ) );
115 return $date;
118 static function ns( $parser, $part1 = '' ) {
119 global $wgContLang;
120 if ( intval( $part1 ) || $part1 == "0" ) {
121 $index = intval( $part1 );
122 } else {
123 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
125 if ( $index !== false ) {
126 return $wgContLang->getFormattedNsText( $index );
127 } else {
128 return array( 'found' => false );
132 static function nse( $parser, $part1 = '' ) {
133 $ret = self::ns( $parser, $part1 );
134 if ( is_string( $ret ) ) {
135 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
137 return $ret;
141 * urlencodes a string according to one of three patterns: (bug 22474)
143 * By default (for HTTP "query" strings), spaces are encoded as '+'.
144 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
145 * For links to "wiki"s, or similar software, spaces are encoded as '_',
147 * @param Parser $parser
148 * @param string $s The text to encode.
149 * @param string $arg (optional): The type of encoding.
150 * @return string
152 static function urlencode( $parser, $s = '', $arg = null ) {
153 static $magicWords = null;
154 if ( is_null( $magicWords ) ) {
155 $magicWords = new MagicWordArray( array( 'url_path', 'url_query', 'url_wiki' ) );
157 switch ( $magicWords->matchStartToEnd( $arg ) ) {
159 // Encode as though it's a wiki page, '_' for ' '.
160 case 'url_wiki':
161 $func = 'wfUrlencode';
162 $s = str_replace( ' ', '_', $s );
163 break;
165 // Encode for an HTTP Path, '%20' for ' '.
166 case 'url_path':
167 $func = 'rawurlencode';
168 break;
170 // Encode for HTTP query, '+' for ' '.
171 case 'url_query':
172 default:
173 $func = 'urlencode';
175 return $parser->markerSkipCallback( $s, $func );
178 static function lcfirst( $parser, $s = '' ) {
179 global $wgContLang;
180 return $wgContLang->lcfirst( $s );
183 static function ucfirst( $parser, $s = '' ) {
184 global $wgContLang;
185 return $wgContLang->ucfirst( $s );
189 * @param Parser $parser
190 * @param string $s
191 * @return
193 static function lc( $parser, $s = '' ) {
194 global $wgContLang;
195 return $parser->markerSkipCallback( $s, array( $wgContLang, 'lc' ) );
199 * @param Parser $parser
200 * @param string $s
201 * @return
203 static function uc( $parser, $s = '' ) {
204 global $wgContLang;
205 return $parser->markerSkipCallback( $s, array( $wgContLang, 'uc' ) );
208 static function localurl( $parser, $s = '', $arg = null ) {
209 return self::urlFunction( 'getLocalURL', $s, $arg );
212 static function localurle( $parser, $s = '', $arg = null ) {
213 $temp = self::urlFunction( 'getLocalURL', $s, $arg );
214 if ( !is_string( $temp ) ) {
215 return $temp;
216 } else {
217 return htmlspecialchars( $temp );
221 static function fullurl( $parser, $s = '', $arg = null ) {
222 return self::urlFunction( 'getFullURL', $s, $arg );
225 static function fullurle( $parser, $s = '', $arg = null ) {
226 $temp = self::urlFunction( 'getFullURL', $s, $arg );
227 if ( !is_string( $temp ) ) {
228 return $temp;
229 } else {
230 return htmlspecialchars( $temp );
234 static function canonicalurl( $parser, $s = '', $arg = null ) {
235 return self::urlFunction( 'getCanonicalURL', $s, $arg );
238 static function canonicalurle( $parser, $s = '', $arg = null ) {
239 return self::urlFunction( 'escapeCanonicalURL', $s, $arg );
242 static function urlFunction( $func, $s = '', $arg = null ) {
243 $title = Title::newFromText( $s );
244 # Due to order of execution of a lot of bits, the values might be encoded
245 # before arriving here; if that's true, then the title can't be created
246 # and the variable will fail. If we can't get a decent title from the first
247 # attempt, url-decode and try for a second.
248 if ( is_null( $title ) ) {
249 $title = Title::newFromURL( urldecode( $s ) );
251 if ( !is_null( $title ) ) {
252 # Convert NS_MEDIA -> NS_FILE
253 if ( $title->getNamespace() == NS_MEDIA ) {
254 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
256 if ( !is_null( $arg ) ) {
257 $text = $title->$func( $arg );
258 } else {
259 $text = $title->$func();
261 return $text;
262 } else {
263 return array( 'found' => false );
268 * @param Parser $parser
269 * @param string $num
270 * @param string $arg
271 * @return string
273 static function formatnum( $parser, $num = '', $arg = null ) {
274 if ( self::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
275 $func = array( $parser->getFunctionLang(), 'parseFormattedNumber' );
276 } elseif ( self::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
277 $func = array( $parser->getFunctionLang(), 'formatNumNoSeparators' );
278 } else {
279 $func = array( $parser->getFunctionLang(), 'formatNum' );
281 return $parser->markerSkipCallback( $num, $func );
285 * @param Parser $parser
286 * @param string $case
287 * @param string $word
288 * @return
290 static function grammar( $parser, $case = '', $word = '' ) {
291 $word = $parser->killMarkers( $word );
292 return $parser->getFunctionLang()->convertGrammar( $word, $case );
296 * @param Parser $parser
297 * @param string $username
298 * @return
300 static function gender( $parser, $username ) {
301 wfProfileIn( __METHOD__ );
302 $forms = array_slice( func_get_args(), 2 );
304 // Some shortcuts to avoid loading user data unnecessarily
305 if ( count( $forms ) === 0 ) {
306 wfProfileOut( __METHOD__ );
307 return '';
308 } elseif ( count( $forms ) === 1 ) {
309 wfProfileOut( __METHOD__ );
310 return $forms[0];
313 $username = trim( $username );
315 // default
316 $gender = User::getDefaultOption( 'gender' );
318 // allow prefix.
319 $title = Title::newFromText( $username );
321 if ( $title && $title->getNamespace() == NS_USER ) {
322 $username = $title->getText();
325 // check parameter, or use the ParserOptions if in interface message
326 $user = User::newFromName( $username );
327 if ( $user ) {
328 $gender = GenderCache::singleton()->getGenderOf( $user, __METHOD__ );
329 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
330 $gender = GenderCache::singleton()->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
332 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
333 wfProfileOut( __METHOD__ );
334 return $ret;
338 * @param Parser $parser
339 * @param string $text
340 * @return
342 static function plural( $parser, $text = '' ) {
343 $forms = array_slice( func_get_args(), 2 );
344 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
345 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
346 return $parser->getFunctionLang()->convertPlural( $text, $forms );
350 * Override the title of the page when viewed, provided we've been given a
351 * title which will normalise to the canonical title
353 * @param Parser $parser Parent parser
354 * @param string $text Desired title text
355 * @return string
357 static function displaytitle( $parser, $text = '' ) {
358 global $wgRestrictDisplayTitle;
360 // parse a limited subset of wiki markup (just the single quote items)
361 $text = $parser->doQuotes( $text );
363 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
364 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
365 . preg_quote( Parser::MARKER_SUFFIX, '/' ) . '/', '', $text );
367 // list of disallowed tags for DISPLAYTITLE
368 // these will be escaped even though they are allowed in normal wiki text
369 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
370 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rp', 'br' );
372 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
373 if ( $wgRestrictDisplayTitle ) {
374 $htmlTagsCallback = function ( &$params ) {
375 $decoded = Sanitizer::decodeTagAttributes( $params );
377 if ( isset( $decoded['style'] ) ) {
378 // this is called later anyway, but we need it right now for the regexes below to be safe
379 // calling it twice doesn't hurt
380 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
382 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
383 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
387 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
389 } else {
390 $htmlTagsCallback = null;
393 // only requested titles that normalize to the actual title are allowed through
394 // if $wgRestrictDisplayTitle is true (it is by default)
395 // mimic the escaping process that occurs in OutputPage::setPageTitle
396 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $text, $htmlTagsCallback, array(), array(), $bad ) );
397 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
399 if ( !$wgRestrictDisplayTitle ) {
400 $parser->mOutput->setDisplayTitle( $text );
401 } elseif ( $title instanceof Title && !$title->hasFragment() && $title->equals( $parser->mTitle ) ) {
402 $parser->mOutput->setDisplayTitle( $text );
405 return '';
409 * Matches the given value against the value of given magic word
411 * @param string $magicword Magic word key
412 * @param string $value Value to match
413 * @return bool True on successful match
415 private static function matchAgainstMagicword( $magicword, $value ) {
416 $value = trim( strval( $value ) );
417 if ( $value === '' ) {
418 return false;
420 $mwObject = MagicWord::get( $magicword );
421 return $mwObject->matchStartToEnd( $value );
424 static function formatRaw( $num, $raw ) {
425 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
426 return $num;
427 } else {
428 global $wgContLang;
429 return $wgContLang->formatNum( $num );
432 static function numberofpages( $parser, $raw = null ) {
433 return self::formatRaw( SiteStats::pages(), $raw );
435 static function numberofusers( $parser, $raw = null ) {
436 return self::formatRaw( SiteStats::users(), $raw );
438 static function numberofactiveusers( $parser, $raw = null ) {
439 return self::formatRaw( SiteStats::activeUsers(), $raw );
441 static function numberofarticles( $parser, $raw = null ) {
442 return self::formatRaw( SiteStats::articles(), $raw );
444 static function numberoffiles( $parser, $raw = null ) {
445 return self::formatRaw( SiteStats::images(), $raw );
447 static function numberofadmins( $parser, $raw = null ) {
448 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
450 static function numberofedits( $parser, $raw = null ) {
451 return self::formatRaw( SiteStats::edits(), $raw );
453 static function numberofviews( $parser, $raw = null ) {
454 global $wgDisableCounters;
455 return !$wgDisableCounters ? self::formatRaw( SiteStats::views(), $raw ) : '';
457 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
458 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
460 static function numberingroup( $parser, $name = '', $raw = null ) {
461 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
465 * Given a title, return the namespace name that would be given by the
466 * corresponding magic word
467 * Note: function name changed to "mwnamespace" rather than "namespace"
468 * to not break PHP 5.3
469 * @return mixed|string
471 static function mwnamespace( $parser, $title = null ) {
472 $t = Title::newFromText( $title );
473 if ( is_null( $t ) ) {
474 return '';
476 return str_replace( '_', ' ', $t->getNsText() );
478 static function namespacee( $parser, $title = null ) {
479 $t = Title::newFromText( $title );
480 if ( is_null( $t ) ) {
481 return '';
483 return wfUrlencode( $t->getNsText() );
485 static function namespacenumber( $parser, $title = null ) {
486 $t = Title::newFromText( $title );
487 if ( is_null( $t ) ) {
488 return '';
490 return $t->getNamespace();
492 static function talkspace( $parser, $title = null ) {
493 $t = Title::newFromText( $title );
494 if ( is_null( $t ) || !$t->canTalk() ) {
495 return '';
497 return str_replace( '_', ' ', $t->getTalkNsText() );
499 static function talkspacee( $parser, $title = null ) {
500 $t = Title::newFromText( $title );
501 if ( is_null( $t ) || !$t->canTalk() ) {
502 return '';
504 return wfUrlencode( $t->getTalkNsText() );
506 static function subjectspace( $parser, $title = null ) {
507 $t = Title::newFromText( $title );
508 if ( is_null( $t ) ) {
509 return '';
511 return str_replace( '_', ' ', $t->getSubjectNsText() );
513 static function subjectspacee( $parser, $title = null ) {
514 $t = Title::newFromText( $title );
515 if ( is_null( $t ) ) {
516 return '';
518 return wfUrlencode( $t->getSubjectNsText() );
522 * Functions to get and normalize pagenames, corresponding to the magic words
523 * of the same names
524 * @return string
526 static function pagename( $parser, $title = null ) {
527 $t = Title::newFromText( $title );
528 if ( is_null( $t ) ) {
529 return '';
531 return wfEscapeWikiText( $t->getText() );
533 static function pagenamee( $parser, $title = null ) {
534 $t = Title::newFromText( $title );
535 if ( is_null( $t ) ) {
536 return '';
538 return wfEscapeWikiText( $t->getPartialURL() );
540 static function fullpagename( $parser, $title = null ) {
541 $t = Title::newFromText( $title );
542 if ( is_null( $t ) || !$t->canTalk() ) {
543 return '';
545 return wfEscapeWikiText( $t->getPrefixedText() );
547 static function fullpagenamee( $parser, $title = null ) {
548 $t = Title::newFromText( $title );
549 if ( is_null( $t ) || !$t->canTalk() ) {
550 return '';
552 return wfEscapeWikiText( $t->getPrefixedURL() );
554 static function subpagename( $parser, $title = null ) {
555 $t = Title::newFromText( $title );
556 if ( is_null( $t ) ) {
557 return '';
559 return wfEscapeWikiText( $t->getSubpageText() );
561 static function subpagenamee( $parser, $title = null ) {
562 $t = Title::newFromText( $title );
563 if ( is_null( $t ) ) {
564 return '';
566 return wfEscapeWikiText( $t->getSubpageUrlForm() );
568 static function rootpagename( $parser, $title = null ) {
569 $t = Title::newFromText( $title );
570 if ( is_null( $t ) ) {
571 return '';
573 return wfEscapeWikiText( $t->getRootText() );
575 static function rootpagenamee( $parser, $title = null ) {
576 $t = Title::newFromText( $title );
577 if ( is_null( $t ) ) {
578 return '';
580 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
582 static function basepagename( $parser, $title = null ) {
583 $t = Title::newFromText( $title );
584 if ( is_null( $t ) ) {
585 return '';
587 return wfEscapeWikiText( $t->getBaseText() );
589 static function basepagenamee( $parser, $title = null ) {
590 $t = Title::newFromText( $title );
591 if ( is_null( $t ) ) {
592 return '';
594 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
596 static function talkpagename( $parser, $title = null ) {
597 $t = Title::newFromText( $title );
598 if ( is_null( $t ) || !$t->canTalk() ) {
599 return '';
601 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
603 static function talkpagenamee( $parser, $title = null ) {
604 $t = Title::newFromText( $title );
605 if ( is_null( $t ) || !$t->canTalk() ) {
606 return '';
608 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
610 static function subjectpagename( $parser, $title = null ) {
611 $t = Title::newFromText( $title );
612 if ( is_null( $t ) ) {
613 return '';
615 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
617 static function subjectpagenamee( $parser, $title = null ) {
618 $t = Title::newFromText( $title );
619 if ( is_null( $t ) ) {
620 return '';
622 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
626 * Return the number of pages, files or subcats in the given category,
627 * or 0 if it's nonexistent. This is an expensive parser function and
628 * can't be called too many times per page.
629 * @return string
631 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
632 global $wgContLang;
633 static $magicWords = null;
634 if ( is_null( $magicWords ) ) {
635 $magicWords = new MagicWordArray( array(
636 'pagesincategory_all',
637 'pagesincategory_pages',
638 'pagesincategory_subcats',
639 'pagesincategory_files'
640 ) );
642 static $cache = array();
644 // split the given option to its variable
645 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
646 //{{pagesincategory:|raw[|type]}}
647 $raw = $arg1;
648 $type = $magicWords->matchStartToEnd( $arg2 );
649 } else {
650 //{{pagesincategory:[|type[|raw]]}}
651 $type = $magicWords->matchStartToEnd( $arg1 );
652 $raw = $arg2;
654 if ( !$type ) { //backward compatibility
655 $type = 'pagesincategory_all';
658 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
659 if ( !$title ) { # invalid title
660 return self::formatRaw( 0, $raw );
662 $wgContLang->findVariantLink( $name, $title, true );
664 // Normalize name for cache
665 $name = $title->getDBkey();
667 if ( !isset( $cache[$name] ) ) {
668 $category = Category::newFromTitle( $title );
670 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
671 if ( $parser->incrementExpensiveFunctionCount() ) {
672 // $allCount is the total number of cat members,
673 // not the count of how many members are normal pages.
674 $allCount = (int)$category->getPageCount();
675 $subcatCount = (int)$category->getSubcatCount();
676 $fileCount = (int)$category->getFileCount();
677 $pagesCount = $allCount - $subcatCount - $fileCount;
679 $cache[$name]['pagesincategory_all'] = $allCount;
680 $cache[$name]['pagesincategory_pages'] = $pagesCount;
681 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
682 $cache[$name]['pagesincategory_files'] = $fileCount;
685 $count = $cache[$name][$type];
686 return self::formatRaw( $count, $raw );
690 * Return the size of the given page, or 0 if it's nonexistent. This is an
691 * expensive parser function and can't be called too many times per page.
693 * @param Parser $parser
694 * @param string $page Name of page to check (Default: empty string)
695 * @param string $raw Should number be human readable with commas or just number
696 * @return string
698 static function pagesize( $parser, $page = '', $raw = null ) {
699 $title = Title::newFromText( $page );
701 if ( !is_object( $title ) ) {
702 return self::formatRaw( 0, $raw );
705 // fetch revision from cache/database and return the value
706 $rev = self::getCachedRevisionObject( $parser, $title );
707 $length = $rev ? $rev->getSize() : 0;
708 return self::formatRaw( $length, $raw );
712 * Returns the requested protection level for the current page. This
713 * is an expensive parser function and can't be called too many times
714 * per page, unless the protection levels for the given title have
715 * already been retrieved
717 * @param Parser $parser
718 * @param string $type
719 * @param string $title
721 * @return string
723 static function protectionlevel( $parser, $type = '', $title = '' ) {
724 $titleObject = Title::newFromText( $title );
725 if ( !( $titleObject instanceof Title ) ) {
726 $titleObject = $parser->mTitle;
728 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
729 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
730 # Title::getRestrictions returns an array, its possible it may have
731 # multiple values in the future
732 return implode( $restrictions, ',' );
734 return '';
738 * Gives language names.
739 * @param Parser $parser
740 * @param string $code Language code (of which to get name)
741 * @param string $inLanguage Language code (in which to get name)
742 * @return string
744 static function language( $parser, $code = '', $inLanguage = '' ) {
745 $code = strtolower( $code );
746 $inLanguage = strtolower( $inLanguage );
747 $lang = Language::fetchLanguageName( $code, $inLanguage );
748 return $lang !== '' ? $lang : wfBCP47( $code );
752 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
753 * @param Parser $parser
754 * @param string $string
755 * @param int $length
756 * @param string $padding
757 * @param int $direction
758 * @return string
760 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
761 $padding = $parser->killMarkers( $padding );
762 $lengthOfPadding = mb_strlen( $padding );
763 if ( $lengthOfPadding == 0 ) {
764 return $string;
767 # The remaining length to add counts down to 0 as padding is added
768 $length = min( $length, 500 ) - mb_strlen( $string );
769 # $finalPadding is just $padding repeated enough times so that
770 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
771 $finalPadding = '';
772 while ( $length > 0 ) {
773 # If $length < $lengthofPadding, truncate $padding so we get the
774 # exact length desired.
775 $finalPadding .= mb_substr( $padding, 0, $length );
776 $length -= $lengthOfPadding;
779 if ( $direction == STR_PAD_LEFT ) {
780 return $finalPadding . $string;
781 } else {
782 return $string . $finalPadding;
786 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
787 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
790 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
791 return self::pad( $parser, $string, $length, $padding );
795 * @param Parser $parser
796 * @param string $text
797 * @return string
799 static function anchorencode( $parser, $text ) {
800 $text = $parser->killMarkers( $text );
801 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
804 static function special( $parser, $text ) {
805 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
806 if ( $page ) {
807 $title = SpecialPage::getTitleFor( $page, $subpage );
808 return $title->getPrefixedText();
809 } else {
810 // unknown special page, just use the given text as its title, if at all possible
811 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
812 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
816 static function speciale( $parser, $text ) {
817 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
821 * @param Parser $parser
822 * @param string $text The sortkey to use
823 * @param string $uarg Either "noreplace" or "noerror" (in en)
824 * both suppress errors, and noreplace does nothing if
825 * a default sortkey already exists.
826 * @return string
828 public static function defaultsort( $parser, $text, $uarg = '' ) {
829 static $magicWords = null;
830 if ( is_null( $magicWords ) ) {
831 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
833 $arg = $magicWords->matchStartToEnd( $uarg );
835 $text = trim( $text );
836 if ( strlen( $text ) == 0 ) {
837 return '';
839 $old = $parser->getCustomDefaultSort();
840 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
841 $parser->setDefaultSort( $text );
844 if ( $old === false || $old == $text || $arg ) {
845 return '';
846 } else {
847 $converter = $parser->getConverterLanguage()->getConverter();
848 return '<span class="error">' .
849 wfMessage( 'duplicate-defaultsort',
850 // Message should be parsed, but these params should only be escaped.
851 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
852 $converter->markNoConversion( wfEscapeWikiText( $text ) )
853 )->inContentLanguage()->text() .
854 '</span>';
858 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
859 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
860 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
861 $file = wfFindFile( $name );
863 if ( $argA == 'nowiki' ) {
864 // {{filepath: | option [| size] }}
865 $isNowiki = true;
866 $parsedWidthParam = $parser->parseWidthParam( $argB );
867 } else {
868 // {{filepath: [| size [|option]] }}
869 $parsedWidthParam = $parser->parseWidthParam( $argA );
870 $isNowiki = ( $argB == 'nowiki' );
873 if ( $file ) {
874 $url = $file->getFullUrl();
876 // If a size is requested...
877 if ( count( $parsedWidthParam ) ) {
878 $mto = $file->transform( $parsedWidthParam );
879 // ... and we can
880 if ( $mto && !$mto->isError() ) {
881 // ... change the URL to point to a thumbnail.
882 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
885 if ( $isNowiki ) {
886 return array( $url, 'nowiki' => true );
888 return $url;
889 } else {
890 return '';
895 * Parser function to extension tag adaptor
896 * @param Parser $parser
897 * @param PPFrame $frame
898 * @param array $args
899 * @return string
901 public static function tagObj( $parser, $frame, $args ) {
902 if ( !count( $args ) ) {
903 return '';
905 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
907 if ( count( $args ) ) {
908 $inner = $frame->expand( array_shift( $args ) );
909 } else {
910 $inner = null;
913 $stripList = $parser->getStripList();
914 if ( !in_array( $tagName, $stripList ) ) {
915 return '<span class="error">' .
916 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
917 '</span>';
920 $attributes = array();
921 foreach ( $args as $arg ) {
922 $bits = $arg->splitArg();
923 if ( strval( $bits['index'] ) === '' ) {
924 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
925 $value = trim( $frame->expand( $bits['value'] ) );
926 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
927 $value = isset( $m[1] ) ? $m[1] : '';
929 $attributes[$name] = $value;
933 $params = array(
934 'name' => $tagName,
935 'inner' => $inner,
936 'attributes' => $attributes,
937 'close' => "</$tagName>",
939 return $parser->extensionSubstitution( $params, $frame );
943 * Fetched the current revision of the given title and return this.
944 * Will increment the expensive function count and
945 * add a template link to get the value refreshed on changes.
946 * For a given title, which is equal to the current parser title,
947 * the revision object from the parser is used, when that is the current one
949 * @param Parser $parser
950 * @param Title $title
951 * @return Revision
952 * @since 1.23
954 private static function getCachedRevisionObject( $parser, $title = null ) {
955 static $cache = array();
957 if ( is_null( $title ) ) {
958 return null;
961 // Use the revision from the parser itself, when param is the current page
962 // and the revision is the current one
963 if ( $title->equals( $parser->getTitle() ) ) {
964 $parserRev = $parser->getRevisionObject();
965 if ( $parserRev && $parserRev->isCurrent() ) {
966 // force reparse after edit with vary-revision flag
967 $parser->getOutput()->setFlag( 'vary-revision' );
968 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
969 return $parserRev;
973 // Normalize name for cache
974 $page = $title->getPrefixedDBkey();
976 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
977 return $cache[$page];
979 if ( $parser->incrementExpensiveFunctionCount() ) {
980 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
981 $pageID = $rev ? $rev->getPage() : 0;
982 $revID = $rev ? $rev->getId() : 0;
983 $cache[$page] = $rev; // maybe null
985 // Register dependency in templatelinks
986 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
988 return $rev;
990 $cache[$page] = null;
991 return null;
995 * Get the pageid of a specified page
996 * @param Parser $parser
997 * @param string $title Title to get the pageid from
998 * @since 1.23
1000 public static function pageid( $parser, $title = null ) {
1001 $t = Title::newFromText( $title );
1002 if ( is_null( $t ) ) {
1003 return '';
1005 // Use title from parser to have correct pageid after edit
1006 if ( $t->equals( $parser->getTitle() ) ) {
1007 $t = $parser->getTitle();
1008 return $t->getArticleID();
1011 // These can't have ids
1012 if ( !$t->canExist() || $t->isExternal() ) {
1013 return 0;
1016 // Check the link cache, maybe something already looked it up.
1017 $linkCache = LinkCache::singleton();
1018 $pdbk = $t->getPrefixedDBkey();
1019 $id = $linkCache->getGoodLinkID( $pdbk );
1020 if ( $id != 0 ) {
1021 $parser->mOutput->addLink( $t, $id );
1022 return $id;
1024 if ( $linkCache->isBadLink( $pdbk ) ) {
1025 $parser->mOutput->addLink( $t, 0 );
1026 return $id;
1029 // We need to load it from the DB, so mark expensive
1030 if ( $parser->incrementExpensiveFunctionCount() ) {
1031 $id = $t->getArticleID();
1032 $parser->mOutput->addLink( $t, $id );
1033 return $id;
1035 return null;
1039 * Get the id from the last revision of a specified page.
1040 * @param Parser $parser
1041 * @param string $title Title to get the id from
1042 * @since 1.23
1044 public static function revisionid( $parser, $title = null ) {
1045 $t = Title::newFromText( $title );
1046 if ( is_null( $t ) ) {
1047 return '';
1049 // fetch revision from cache/database and return the value
1050 $rev = self::getCachedRevisionObject( $parser, $t );
1051 return $rev ? $rev->getId() : '';
1055 * Get the day from the last revision of a specified page.
1056 * @param Parser $parser
1057 * @param string $title Title to get the day from
1058 * @since 1.23
1060 public static function revisionday( $parser, $title = null ) {
1061 $t = Title::newFromText( $title );
1062 if ( is_null( $t ) ) {
1063 return '';
1065 // fetch revision from cache/database and return the value
1066 $rev = self::getCachedRevisionObject( $parser, $t );
1067 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1071 * Get the day with leading zeros from the last revision of a specified page.
1072 * @param Parser $parser
1073 * @param string $title Title to get the day from
1074 * @since 1.23
1076 public static function revisionday2( $parser, $title = null ) {
1077 $t = Title::newFromText( $title );
1078 if ( is_null( $t ) ) {
1079 return '';
1081 // fetch revision from cache/database and return the value
1082 $rev = self::getCachedRevisionObject( $parser, $t );
1083 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1087 * Get the month with leading zeros from the last revision of a specified page.
1088 * @param Parser $parser
1089 * @param string $title Title to get the month from
1090 * @since 1.23
1092 public static function revisionmonth( $parser, $title = null ) {
1093 $t = Title::newFromText( $title );
1094 if ( is_null( $t ) ) {
1095 return '';
1097 // fetch revision from cache/database and return the value
1098 $rev = self::getCachedRevisionObject( $parser, $t );
1099 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1103 * Get the month from the last revision of a specified page.
1104 * @param Parser $parser
1105 * @param string $title Title to get the month from
1106 * @since 1.23
1108 public static function revisionmonth1( $parser, $title = null ) {
1109 $t = Title::newFromText( $title );
1110 if ( is_null( $t ) ) {
1111 return '';
1113 // fetch revision from cache/database and return the value
1114 $rev = self::getCachedRevisionObject( $parser, $t );
1115 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1119 * Get the year from the last revision of a specified page.
1120 * @param Parser $parser
1121 * @param string $title Title to get the year from
1122 * @since 1.23
1124 public static function revisionyear( $parser, $title = null ) {
1125 $t = Title::newFromText( $title );
1126 if ( is_null( $t ) ) {
1127 return '';
1129 // fetch revision from cache/database and return the value
1130 $rev = self::getCachedRevisionObject( $parser, $t );
1131 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1135 * Get the timestamp from the last revision of a specified page.
1136 * @param Parser $parser
1137 * @param string $title Title to get the timestamp from
1138 * @since 1.23
1140 public static function revisiontimestamp( $parser, $title = null ) {
1141 $t = Title::newFromText( $title );
1142 if ( is_null( $t ) ) {
1143 return '';
1145 // fetch revision from cache/database and return the value
1146 $rev = self::getCachedRevisionObject( $parser, $t );
1147 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1151 * Get the user from the last revision of a specified page.
1152 * @param Parser $parser
1153 * @param string $title Title to get the user from
1154 * @since 1.23
1156 public static function revisionuser( $parser, $title = null ) {
1157 $t = Title::newFromText( $title );
1158 if ( is_null( $t ) ) {
1159 return '';
1161 // fetch revision from cache/database and return the value
1162 $rev = self::getCachedRevisionObject( $parser, $t );
1163 return $rev ? $rev->getUserText() : '';
1167 * Returns the sources of any cascading protection acting on a specified page.
1168 * Pages will not return their own title unless they transclude themselves.
1169 * This is an expensive parser function and can't be called too many times per page,
1170 * unless cascading protection sources for the page have already been loaded.
1172 * @param Parser $parser
1173 * @param string $title
1175 * @return string
1176 * @since 1.23
1178 public static function cascadingsources( $parser, $title = '' ) {
1179 $titleObject = Title::newFromText( $title );
1180 if ( !( $titleObject instanceof Title ) ) {
1181 $titleObject = $parser->mTitle;
1183 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1184 || $parser->incrementExpensiveFunctionCount()
1186 $names = array();
1187 $sources = $titleObject->getCascadeProtectionSources();
1188 foreach ( $sources[0] as $sourceTitle ) {
1189 $names[] = $sourceTitle->getPrefixedText();
1191 return implode( $names, '|' );
1193 return '';