MediaWiki master
CoreParserFunctions.php
Go to the documentation of this file.
1<?php
10namespace MediaWiki\Parser;
11
12use InvalidArgumentException;
18use MediaWiki\Languages\LanguageNameUtils;
29use Wikimedia\Bcp47Code\Bcp47CodeValue;
30use Wikimedia\RemexHtml\Tokenizer\Attributes;
31use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
32use Wikimedia\Timestamp\TimestampFormat as TS;
33
40 private const MAX_TTS = 900;
41
45 public const REGISTER_OPTIONS = [
46 // See documentation for the corresponding config options
49 ];
50
58 public static function register( Parser $parser, ServiceOptions $options ) {
59 $options->assertRequiredOptions( self::REGISTER_OPTIONS );
60 $allowDisplayTitle = $options->get( MainConfigNames::AllowDisplayTitle );
61 $allowSlowParserFunctions = $options->get( MainConfigNames::AllowSlowParserFunctions );
62
63 # Syntax for arguments (see Parser::setFunctionHook):
64 # "name for lookup in localized magic words array",
65 # function callback,
66 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
67 # instead of {{#int:...}})
68 $noHashFunctions = [
69 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
70 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
71 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural', 'formal',
72 'bidi', 'numberingroup', 'language',
73 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
74 'pagesincategory', 'pagesize', 'protectionlevel', 'protectionexpiry',
75 # The following are the "parser function" forms of magic
76 # variables defined in CoreMagicVariables. The no-args form will
77 # go through the magic variable code path (and be cached); the
78 # presence of arguments will cause the parser function form to
79 # be invoked. (Note that the actual implementation will pass
80 # a Parser object as first argument, in addition to the
81 # parser function parameters.)
82
83 # For this group, the first parameter to the parser function is
84 # "page title", and the no-args form (and the magic variable)
85 # defaults to "current page title".
86 'pagename', 'pagenamee',
87 'fullpagename', 'fullpagenamee',
88 'subpagename', 'subpagenamee',
89 'rootpagename', 'rootpagenamee',
90 'basepagename', 'basepagenamee',
91 'talkpagename', 'talkpagenamee',
92 'subjectpagename', 'subjectpagenamee',
93 'pageid', 'revisionid', 'revisionday',
94 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
95 'revisiontimestamp',
96 'revisionuser',
97 'cascadingsources',
98 'namespace', 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
99 'subjectspace', 'subjectspacee',
100
101 # More parser functions corresponding to CoreMagicVariables.
102 # For this group, the first parameter to the parser function is
103 # "raw" (uses the 'raw' format if present) and the no-args form
104 # (and the magic variable) defaults to 'not raw'.
105 'numberofarticles', 'numberoffiles',
106 'numberofusers',
107 'numberofactiveusers',
108 'numberofpages',
109 'numberofadmins',
110 'numberofedits',
111
112 # These magic words already contain the hash, and the no-args form
113 # is the same as passing an empty first argument
114 'bcp47',
115 'dir',
116 'interwikilink',
117 'interlanguagelink',
118 'contentmodel',
119 'isbn',
120 ];
121 foreach ( $noHashFunctions as $func ) {
122 $parser->setFunctionHook( $func, self::$func( ... ), Parser::SFH_NO_HASH );
123 }
124
125 $parser->setFunctionHook( 'int', self::intFunction( ... ), Parser::SFH_NO_HASH );
126 $parser->setFunctionHook( 'special', self::special( ... ) );
127 $parser->setFunctionHook( 'speciale', self::speciale( ... ) );
128 $parser->setFunctionHook( 'tag', self::tagObj( ... ), Parser::SFH_OBJECT_ARGS );
129 $parser->setFunctionHook( 'formatdate', self::formatDate( ... ) );
130
131 if ( $allowDisplayTitle ) {
132 $parser->setFunctionHook(
133 'displaytitle',
134 self::displaytitle( ... ),
136 );
137 }
138 if ( $allowSlowParserFunctions ) {
139 $parser->setFunctionHook(
140 'pagesinnamespace',
141 self::pagesinnamespace( ... ),
143 );
144 }
145 }
146
153 public static function intFunction( $parser, $part1 = '', ...$params ) {
154 if ( strval( $part1 ) !== '' ) {
155 $message = wfMessage( $part1, $params )
156 ->inLanguage( $parser->getOptions()->getUserLangObj() );
157 return [ $message->plain(), 'noparse' => false ];
158 } else {
159 return [ 'found' => false ];
160 }
161 }
162
170 public static function formatDate( $parser, $date, $defaultPref = null ) {
171 $lang = $parser->getTargetLanguage();
172 $df = MediaWikiServices::getInstance()->getDateFormatterFactory()->get( $lang );
173
174 $date = trim( $date );
175
176 $pref = $parser->getOptions()->getDateFormat();
177
178 // Specify a different default date format other than the normal default
179 // if the user has 'default' for their setting
180 if ( $pref == 'default' && $defaultPref ) {
181 $pref = $defaultPref;
182 }
183
184 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
185 return $date;
186 }
187
193 public static function ns( $parser, $part1 = '' ) {
194 if ( intval( $part1 ) || $part1 == "0" ) {
195 $index = intval( $part1 );
196 } else {
197 $index = $parser->getContentLanguage()->getNsIndex( str_replace( ' ', '_', $part1 ) );
198 }
199 if ( $index !== false ) {
200 return $parser->getContentLanguage()->getFormattedNsText( $index );
201 } else {
202 return [ 'found' => false ];
203 }
204 }
205
211 public static function nse( $parser, $part1 = '' ) {
212 $ret = self::ns( $parser, $part1 );
213 if ( is_string( $ret ) ) {
214 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
215 }
216 return $ret;
217 }
218
231 public static function urlencode( $parser, $s = '', $arg = null ) {
232 static $magicWords = null;
233 if ( $magicWords === null ) {
235 $parser->getMagicWordFactory()->newArray( [ 'url_path', 'url_query', 'url_wiki' ] );
236 }
237 switch ( $magicWords->matchStartToEnd( $arg ?? '' ) ) {
238 // Encode as though it's a wiki page, '_' for ' '.
239 case 'url_wiki':
240 $func = 'wfUrlencode';
241 $s = str_replace( ' ', '_', $s );
242 break;
243
244 // Encode for an HTTP Path, '%20' for ' '.
245 case 'url_path':
246 $func = 'rawurlencode';
247 break;
248
249 // Encode for HTTP query, '+' for ' '.
250 case 'url_query':
251 default:
252 $func = 'urlencode';
253 }
254 // See T105242, where the choice to kill markers and various
255 // other options were discussed.
256 return $func( $parser->killMarkers( $s ) );
257 }
258
264 public static function lcfirst( $parser, $s = '' ) {
265 return $parser->getContentLanguage()->lcfirst( $s );
266 }
267
273 public static function ucfirst( $parser, $s = '' ) {
274 return $parser->getContentLanguage()->ucfirst( $s );
275 }
276
282 public static function lc( $parser, $s = '' ) {
283 return $parser->markerSkipCallback( $s, $parser->getContentLanguage()->lc( ... ) );
284 }
285
291 public static function uc( $parser, $s = '' ) {
292 return $parser->markerSkipCallback( $s, $parser->getContentLanguage()->uc( ... ) );
293 }
294
301 public static function localurl( $parser, $s = '', $arg = null ) {
302 return self::urlFunction( 'getLocalURL', $s, $arg );
303 }
304
311 public static function localurle( $parser, $s = '', $arg = null ) {
312 $temp = self::urlFunction( 'getLocalURL', $s, $arg );
313 if ( !is_string( $temp ) ) {
314 return $temp;
315 } else {
316 return htmlspecialchars( $temp, ENT_COMPAT );
317 }
318 }
319
326 public static function fullurl( $parser, $s = '', $arg = null ) {
327 return self::urlFunction( 'getFullURL', $s, $arg );
328 }
329
336 public static function fullurle( $parser, $s = '', $arg = null ) {
337 $temp = self::urlFunction( 'getFullURL', $s, $arg );
338 if ( !is_string( $temp ) ) {
339 return $temp;
340 } else {
341 return htmlspecialchars( $temp, ENT_COMPAT );
342 }
343 }
344
351 public static function canonicalurl( $parser, $s = '', $arg = null ) {
352 return self::urlFunction( 'getCanonicalURL', $s, $arg );
353 }
354
361 public static function canonicalurle( $parser, $s = '', $arg = null ) {
362 $temp = self::urlFunction( 'getCanonicalURL', $s, $arg );
363 if ( !is_string( $temp ) ) {
364 return $temp;
365 } else {
366 return htmlspecialchars( $temp, ENT_COMPAT );
367 }
368 }
369
376 public static function urlFunction( $func, $s = '', $arg = null ) {
377 # Due to order of execution of a lot of bits, the values might be encoded
378 # before arriving here; if that's true, then the title can't be created
379 # and the variable will fail. If we can't get a decent title from the first
380 # attempt, url-decode and try for a second.
381 $title = Title::newFromText( $s ) ?? Title::newFromURL( urldecode( $s ) );
382 if ( $title !== null ) {
383 # Convert NS_MEDIA -> NS_FILE
384 if ( $title->inNamespace( NS_MEDIA ) ) {
385 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
386 }
387 if ( $arg !== null ) {
388 $text = $title->$func( $arg );
389 } else {
390 $text = $title->$func();
391 }
392 return $text;
393 } else {
394 return [ 'found' => false ];
395 }
396 }
397
405 public static function formatnum( $parser, $num = '', $arg1 = '', $arg2 = '' ) {
406 static $magicWords = null;
407 if ( $magicWords === null ) {
408 $magicWords = $parser->getMagicWordFactory()->newArray( [
409 'rawsuffix',
410 'nocommafysuffix',
411 'lossless',
412 ] );
413 }
414
415 $modifiers = [ $magicWords->matchStartToEnd( $arg1 ), $magicWords->matchStartToEnd( $arg2 ) ];
416 $targetLanguage = $parser->getTargetLanguage();
417 if ( in_array( 'rawsuffix', $modifiers, true ) ) {
418 $func = [ $targetLanguage, 'parseFormattedNumber' ];
419 } else {
420 if ( in_array( 'nocommafysuffix', $modifiers, true ) ) {
421 $func = [ $targetLanguage, 'formatNumNoSeparators' ];
422 } else {
423 $func = [ $targetLanguage, 'formatNum' ];
424 $func = self::getLegacyFormatNum( $parser, $func );
425 }
426 if ( in_array( 'lossless', $modifiers, true ) ) {
427 $potentiallyLossyFunc = $func;
428 $func = static function ( $num ) use ( $targetLanguage, $potentiallyLossyFunc ) {
429 $formatted = $potentiallyLossyFunc( $num );
430 $parsed = $targetLanguage->parseFormattedNumber( $formatted );
431 if ( $num === $parsed ) {
432 return $formatted;
433 } else {
434 return (string)$num;
435 }
436 };
437 }
438 }
439 return $parser->markerSkipCallback( $num, $func );
440 }
441
448 private static function getLegacyFormatNum( $parser, $callback ) {
449 // For historic reasons, the formatNum parser function will
450 // take arguments which are not actually formatted numbers,
451 // which then trigger deprecation warnings in Language::formatNum*.
452 // Instead emit a tracking category instead to allow linting.
453 return static function ( $number ) use ( $parser, $callback ) {
454 $validNumberRe = '(-(?=[\d\.]))?(\d+|(?=\.\d))(\.\d*)?([Ee][-+]?\d+)?';
455 if (
456 !is_numeric( $number ) &&
457 $number !== 'NAN' &&
458 $number !== 'INF' &&
459 $number !== '-INF'
460 ) {
461 $parser->addTrackingCategory( 'nonnumeric-formatnum' );
462 // Don't split on NAN/INF in the legacy case since they are
463 // likely to be found embedded inside non-numeric text.
464 return preg_replace_callback( "/{$validNumberRe}/", static function ( $m ) use ( $callback ) {
465 return $callback( $m[0] );
466 }, $number );
467 }
468 return $callback( $number );
469 };
470 }
471
478 public static function grammar( $parser, $case = '', $word = '' ) {
479 $word = $parser->killMarkers( $word );
480 return $parser->getTargetLanguage()->convertGrammar( $word, $case );
481 }
482
489 public static function gender( $parser, $username, ...$forms ) {
490 // Some shortcuts to avoid loading user data unnecessarily
491 if ( count( $forms ) === 0 ) {
492 return '';
493 } elseif ( count( $forms ) === 1 ) {
494 return $forms[0];
495 }
496
497 $username = trim( $username );
498
499 $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
500 $gender = $userOptionsLookup->getDefaultOption( 'gender' );
501
502 // allow prefix and normalize (e.g. "&#42;foo" -> "*foo" ).
503 $title = Title::newFromText( $username, NS_USER );
504
505 if ( $title && $title->inNamespace( NS_USER ) ) {
506 $username = $title->getText();
507 }
508
509 // check parameter, or use the ParserOptions if in interface message
510 $user = User::newFromName( $username );
511 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
512 if ( $user ) {
513 $gender = $genderCache->getGenderOf( $user, __METHOD__ );
514 } elseif ( $username === '' && $parser->getOptions()->isMessage() ) {
515 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUserIdentity(), __METHOD__ );
516 }
517 $ret = $parser->getTargetLanguage()->gender( $gender, $forms );
518 return $ret;
519 }
520
527 public static function plural( $parser, $text = '', ...$forms ) {
528 $text = $parser->getTargetLanguage()->parseFormattedNumber( $text );
529 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
530 // @phan-suppress-next-line PhanTypeMismatchArgument Phan does not handle settype
531 return $parser->getTargetLanguage()->convertPlural( $text, $forms );
532 }
533
534 public static function formal( Parser $parser, string ...$forms ): string {
535 $index = $parser->getTargetLanguage()->getFormalityIndex();
536 return $forms[$index] ?? $forms[0];
537 }
538
544 public static function bidi( $parser, $text = '' ) {
545 return $parser->getTargetLanguage()->embedBidi( $text );
546 }
547
557 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
558 $restrictDisplayTitle = MediaWikiServices::getInstance()->getMainConfig()
560
561 static $magicWords = null;
562 if ( $magicWords === null ) {
563 $magicWords = $parser->getMagicWordFactory()->newArray(
564 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
565 }
566 $arg = $magicWords->matchStartToEnd( $uarg );
567
568 // parse a limited subset of wiki markup (just the single quote items)
569 $text = $parser->doQuotes( $text );
570
571 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
572 $text = $parser->killMarkers( $text );
573
574 // See T28547 for rationale for this processing.
575 // list of disallowed tags for DISPLAYTITLE
576 // these will be escaped even though they are allowed in normal wiki text
577 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
578 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
579
580 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
581 if ( $restrictDisplayTitle ) {
582 // This code is tested with the cases marked T28547 in
583 // parserTests.txt
584 $htmlTagsCallback = static function ( Attributes $attr ): Attributes {
585 $decoded = $attr->getValues();
586
587 if ( isset( $decoded['style'] ) ) {
588 // this is called later anyway, but we need it right now for the regexes below to be safe
589 // calling it twice doesn't hurt
590 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
591
592 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
593 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
594 }
595 }
596
597 return new PlainAttributes( $decoded );
598 };
599 } else {
600 $htmlTagsCallback = null;
601 }
602
603 // only requested titles that normalize to the actual title are allowed through
604 // if $wgRestrictDisplayTitle is true (it is by default)
605 // mimic the escaping process that occurs in OutputPage::setPageTitle
606 $text = Sanitizer::removeSomeTags( $text, [
607 'attrCallback' => $htmlTagsCallback,
608 'removeTags' => $bad,
609 ] );
610 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
611 // Decode entities in $text the same way that Title::newFromText does
612 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
613
614 if ( !$restrictDisplayTitle ||
615 ( $title instanceof Title
616 && !$title->hasFragment()
617 && $title->equals( $parser->getTitle() ) )
618 ) {
619 $old = $parser->getOutput()->getPageProperty( 'displaytitle' );
620 if ( $old === null || $arg !== 'displaytitle_noreplace' ) {
621 $parser->getOutput()->setDisplayTitle( $text );
622 }
623 if ( $old !== null && $old !== $text && !$arg ) {
624
625 $converter = $parser->getTargetLanguageConverter();
626 return '<span class="error">' .
627 $parser->msg( 'duplicate-displaytitle',
628 // Message should be parsed, but these params should only be escaped.
629 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
630 $converter->markNoConversion( wfEscapeWikiText( $filteredText ) )
631 )->text() .
632 '</span>';
633 } else {
634 return '';
635 }
636 } else {
637 $parser->getOutput()->addWarningMsg(
638 'restricted-displaytitle',
639 // Message should be parsed, but this param should only be escaped.
640 wfEscapeWikiText( $filteredText )
641 );
642 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
643 }
644 }
645
655 private static function matchAgainstMagicword(
656 MagicWordFactory $magicWordFactory, $magicword, $value
657 ) {
658 $value = trim( strval( $value ) );
659 if ( $value === '' ) {
660 return false;
661 }
662 $mwObject = $magicWordFactory->get( $magicword );
663 return $mwObject->matchStartToEnd( $value );
664 }
665
675 public static function formatRaw(
676 $num, $raw, $language, ?MagicWordFactory $magicWordFactory = null
677 ) {
678 if ( $raw !== null && $raw !== '' ) {
679 if ( !$magicWordFactory ) {
680 $magicWordFactory = MediaWikiServices::getInstance()->getMagicWordFactory();
681 }
682 if ( self::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw ) ) {
683 return (string)$num;
684 }
685 }
686 return $language->formatNum( $num );
687 }
688
694 public static function numberofpages( $parser, $raw = null ) {
695 return self::formatRaw( SiteStats::pages(), $raw, $parser->getTargetLanguage() );
696 }
697
703 public static function numberofusers( $parser, $raw = null ) {
704 return self::formatRaw( SiteStats::users(), $raw, $parser->getTargetLanguage() );
705 }
706
712 public static function numberofactiveusers( $parser, $raw = null ) {
713 return self::formatRaw( SiteStats::activeUsers(), $raw, $parser->getTargetLanguage() );
714 }
715
721 public static function numberofarticles( $parser, $raw = null ) {
722 return self::formatRaw( SiteStats::articles(), $raw, $parser->getTargetLanguage() );
723 }
724
730 public static function numberoffiles( $parser, $raw = null ) {
731 return self::formatRaw( SiteStats::images(), $raw, $parser->getTargetLanguage() );
732 }
733
739 public static function numberofadmins( $parser, $raw = null ) {
740 return self::formatRaw(
741 SiteStats::numberingroup( 'sysop' ),
742 $raw,
743 $parser->getTargetLanguage()
744 );
745 }
746
752 public static function numberofedits( $parser, $raw = null ) {
753 return self::formatRaw( SiteStats::edits(), $raw, $parser->getTargetLanguage() );
754 }
755
762 public static function pagesinnamespace( $parser, $namespace = '0', $raw = null ) {
763 return self::formatRaw(
764 SiteStats::pagesInNs( intval( $namespace ) ),
765 $raw,
766 $parser->getTargetLanguage()
767 );
768 }
769
776 public static function numberingroup( $parser, $name = '', $raw = null ) {
777 return self::formatRaw(
778 SiteStats::numberingroup( strtolower( $name ) ),
779 $raw,
780 $parser->getTargetLanguage()
781 );
782 }
783
792 private static function makeTitle( Parser $parser, ?string $t ) {
793 if ( $t === null ) {
794 // For consistency with magic variable forms
795 $title = $parser->getTitle();
796 } else {
797 $title = Title::newFromText( $t );
798 }
799 return $title;
800 }
801
810 public static function namespace( $parser, $title = null ) {
811 $t = self::makeTitle( $parser, $title );
812 if ( $t === null ) {
813 return '';
814 }
815 return str_replace( '_', ' ', $t->getNsText() );
816 }
817
823 public static function namespacee( $parser, $title = null ) {
824 $t = self::makeTitle( $parser, $title );
825 if ( $t === null ) {
826 return '';
827 }
828 return wfUrlencode( $t->getNsText() );
829 }
830
836 public static function namespacenumber( $parser, $title = null ) {
837 $t = self::makeTitle( $parser, $title );
838 if ( $t === null ) {
839 return '';
840 }
841 return (string)$t->getNamespace();
842 }
843
849 public static function talkspace( $parser, $title = null ) {
850 $t = self::makeTitle( $parser, $title );
851 if ( $t === null || !$t->canHaveTalkPage() ) {
852 return '';
853 }
854 return str_replace( '_', ' ', $t->getTalkNsText() );
855 }
856
862 public static function talkspacee( $parser, $title = null ) {
863 $t = self::makeTitle( $parser, $title );
864 if ( $t === null || !$t->canHaveTalkPage() ) {
865 return '';
866 }
867 return wfUrlencode( $t->getTalkNsText() );
868 }
869
875 public static function subjectspace( $parser, $title = null ) {
876 $t = self::makeTitle( $parser, $title );
877 if ( $t === null ) {
878 return '';
879 }
880 return str_replace( '_', ' ', $t->getSubjectNsText() );
881 }
882
888 public static function subjectspacee( $parser, $title = null ) {
889 $t = self::makeTitle( $parser, $title );
890 if ( $t === null ) {
891 return '';
892 }
893 return wfUrlencode( $t->getSubjectNsText() );
894 }
895
903 public static function pagename( $parser, $title = null ) {
904 $t = self::makeTitle( $parser, $title );
905 if ( $t === null ) {
906 return '';
907 }
908 return wfEscapeWikiText( $t->getText() );
909 }
910
916 public static function pagenamee( $parser, $title = null ) {
917 $t = self::makeTitle( $parser, $title );
918 if ( $t === null ) {
919 return '';
920 }
921 return wfEscapeWikiText( $t->getPartialURL() );
922 }
923
929 public static function fullpagename( $parser, $title = null ) {
930 $t = self::makeTitle( $parser, $title );
931 if ( $t === null ) {
932 return '';
933 }
934 return wfEscapeWikiText( $t->getPrefixedText() );
935 }
936
942 public static function fullpagenamee( $parser, $title = null ) {
943 $t = self::makeTitle( $parser, $title );
944 if ( $t === null ) {
945 return '';
946 }
947 return wfEscapeWikiText( $t->getPrefixedURL() );
948 }
949
955 public static function subpagename( $parser, $title = null ) {
956 $t = self::makeTitle( $parser, $title );
957 if ( $t === null ) {
958 return '';
959 }
960 return wfEscapeWikiText( $t->getSubpageText() );
961 }
962
968 public static function subpagenamee( $parser, $title = null ) {
969 $t = self::makeTitle( $parser, $title );
970 if ( $t === null ) {
971 return '';
972 }
973 return wfEscapeWikiText( $t->getSubpageUrlForm() );
974 }
975
981 public static function rootpagename( $parser, $title = null ) {
982 $t = self::makeTitle( $parser, $title );
983 if ( $t === null ) {
984 return '';
985 }
986 return wfEscapeWikiText( $t->getRootText() );
987 }
988
994 public static function rootpagenamee( $parser, $title = null ) {
995 $t = self::makeTitle( $parser, $title );
996 if ( $t === null ) {
997 return '';
998 }
999 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
1000 }
1001
1007 public static function basepagename( $parser, $title = null ) {
1008 $t = self::makeTitle( $parser, $title );
1009 if ( $t === null ) {
1010 return '';
1011 }
1012 return wfEscapeWikiText( $t->getBaseText() );
1013 }
1014
1020 public static function basepagenamee( $parser, $title = null ) {
1021 $t = self::makeTitle( $parser, $title );
1022 if ( $t === null ) {
1023 return '';
1024 }
1025 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
1026 }
1027
1033 public static function talkpagename( $parser, $title = null ) {
1034 $t = self::makeTitle( $parser, $title );
1035 if ( $t === null || !$t->canHaveTalkPage() ) {
1036 return '';
1037 }
1038 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
1039 }
1040
1046 public static function talkpagenamee( $parser, $title = null ) {
1047 $t = self::makeTitle( $parser, $title );
1048 if ( $t === null || !$t->canHaveTalkPage() ) {
1049 return '';
1050 }
1051 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
1052 }
1053
1059 public static function subjectpagename( $parser, $title = null ) {
1060 $t = self::makeTitle( $parser, $title );
1061 if ( $t === null ) {
1062 return '';
1063 }
1064 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
1065 }
1066
1072 public static function subjectpagenamee( $parser, $title = null ) {
1073 $t = self::makeTitle( $parser, $title );
1074 if ( $t === null ) {
1075 return '';
1076 }
1077 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
1078 }
1079
1090 public static function pagesincategory( $parser, $name = '', $arg1 = '', $arg2 = '' ) {
1091 static $magicWords = null;
1092 if ( $magicWords === null ) {
1093 $magicWords = $parser->getMagicWordFactory()->newArray( [
1094 'pagesincategory_all',
1095 'pagesincategory_pages',
1096 'pagesincategory_subcats',
1097 'pagesincategory_files'
1098 ] );
1099 }
1100 static $cache = [];
1101
1102 // split the given option to its variable
1103 if ( self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
1104 // {{pagesincategory:|raw[|type]}}
1105 $raw = $arg1;
1106 $type = $magicWords->matchStartToEnd( $arg2 );
1107 } else {
1108 // {{pagesincategory:[|type[|raw]]}}
1109 $type = $magicWords->matchStartToEnd( $arg1 );
1110 $raw = $arg2;
1111 }
1112 if ( !$type ) { // backward compatibility
1113 $type = 'pagesincategory_all';
1114 }
1115
1116 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
1117 if ( !$title ) { # invalid title
1118 return self::formatRaw( 0, $raw, $parser->getTargetLanguage() );
1119 }
1120 $languageConverter = MediaWikiServices::getInstance()
1121 ->getLanguageConverterFactory()
1122 ->getLanguageConverter( $parser->getContentLanguage() );
1123 $languageConverter->findVariantLink( $name, $title, true );
1124
1125 // Normalize name for cache
1126 $name = $title->getDBkey();
1127
1128 if ( !isset( $cache[$name] ) ) {
1129 $category = Category::newFromTitle( $title );
1130
1131 $allCount = $subcatCount = $fileCount = $pageCount = 0;
1132 if ( $parser->incrementExpensiveFunctionCount() ) {
1133 $allCount = $category->getMemberCount();
1134 $subcatCount = $category->getSubcatCount();
1135 $fileCount = $category->getFileCount();
1136 $pageCount = $category->getPageCount( Category::COUNT_CONTENT_PAGES );
1137 }
1138 $cache[$name]['pagesincategory_all'] = $allCount;
1139 $cache[$name]['pagesincategory_pages'] = $pageCount;
1140 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
1141 $cache[$name]['pagesincategory_files'] = $fileCount;
1142 }
1143
1144 $count = $cache[$name][$type];
1145 return self::formatRaw( $count, $raw, $parser->getTargetLanguage() );
1146 }
1147
1157 public static function pagesize( $parser, $page = '', $raw = null ) {
1158 $title = Title::newFromText( $page );
1159
1160 if ( !is_object( $title ) || $title->isExternal() ) {
1161 return self::formatRaw( 0, $raw, $parser->getTargetLanguage() );
1162 }
1163
1164 // fetch revision from cache/database and return the value
1165 $rev = self::getCachedRevisionObject( $parser, $title, ParserOutputFlags::VARY_REVISION_SHA1 );
1166 $length = $rev ? $rev->getSize() : 0;
1167 if ( $length === null ) {
1168 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
1169 $length = 0;
1170 }
1171 return self::formatRaw( $length, $raw, $parser->getTargetLanguage() );
1172 }
1173
1186 public static function protectionlevel( $parser, $type = '', $title = '' ) {
1187 $titleObject = Title::newFromText( $title ) ?? $parser->getTitle();
1188 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
1189 if ( $restrictionStore->areRestrictionsLoaded( $titleObject ) || $parser->incrementExpensiveFunctionCount() ) {
1190 $restrictions = $restrictionStore->getRestrictions( $titleObject, strtolower( $type ) );
1191 # RestrictionStore::getRestrictions returns an array, its possible it may have
1192 # multiple values in the future
1193 return implode( ',', $restrictions );
1194 }
1195 return '';
1196 }
1197
1210 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
1211 $titleObject = Title::newFromText( $title ) ?? $parser->getTitle();
1212 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
1213 if ( $restrictionStore->areRestrictionsLoaded( $titleObject ) || $parser->incrementExpensiveFunctionCount() ) {
1214 // getRestrictionExpiry() returns null on invalid type; trying to
1215 // match protectionlevel() function that returns empty string instead
1216 return $restrictionStore->getRestrictionExpiry( $titleObject, strtolower( $type ) ) ?? '';
1217 }
1218 return '';
1219 }
1220
1229 public static function language( $parser, $code = '', $inLanguage = '' ) {
1230 if ( $code === '' ) {
1231 $code = $parser->getTargetLanguage()->getCode();
1232 }
1233 if ( $inLanguage === '' ) {
1234 $inLanguage = LanguageNameUtils::AUTONYMS;
1235 }
1237 ->getLanguageNameUtils()
1238 ->getLanguageName( $code, $inLanguage );
1239 return $lang !== '' ? $lang : LanguageCode::bcp47( $code );
1240 }
1241
1253 public static function dir( Parser $parser, string $code = '', string $arg = '' ): string {
1254 static $magicWords = null;
1255 $languageFactory = MediaWikiServices::getInstance()->getLanguageFactory();
1256
1257 if ( $code === '' ) {
1258 $lang = $parser->getTargetLanguage();
1259 } else {
1260 if ( $arg !== '' ) {
1261 if ( $magicWords === null ) {
1262 $magicWords = $parser->getMagicWordFactory()->newArray( [ 'language_option_bcp47' ] );
1263 }
1264 if ( $magicWords->matchStartToEnd( $arg ) === 'language_option_bcp47' ) {
1265 // Prefer the BCP-47 interpretation of this code.
1266 $code = new Bcp47CodeValue( $code );
1267 }
1268 }
1269 try {
1270 $lang = $languageFactory->getLanguage( $code );
1271 } catch ( InvalidArgumentException ) {
1272 $parser->addTrackingCategory( 'bad-language-code-category' );
1273 return 'ltr';
1274 }
1275 }
1276 return $lang->getDir();
1277 }
1278
1287 public static function bcp47( Parser $parser, string $code = '' ): string {
1288 if ( $code === '' ) {
1289 return $parser->getTargetLanguage()->toBcp47Code();
1290 } else {
1291 return LanguageCode::bcp47( $code );
1292 }
1293 }
1294
1304 public static function pad(
1305 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
1306 ) {
1307 $padding = $parser->killMarkers( $padding );
1308 $lengthOfPadding = mb_strlen( $padding );
1309 if ( $lengthOfPadding == 0 ) {
1310 return $string;
1311 }
1312
1313 # The remaining length to add counts down to 0 as padding is added
1314 $length = min( (int)$length, 500 ) - mb_strlen( $string );
1315 if ( $length <= 0 ) {
1316 // Nothing to add
1317 return $string;
1318 }
1319
1320 # $finalPadding is just $padding repeated enough times so that
1321 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
1322 $finalPadding = '';
1323 while ( $length > 0 ) {
1324 # If $length < $lengthofPadding, truncate $padding so we get the
1325 # exact length desired.
1326 $finalPadding .= mb_substr( $padding, 0, $length );
1327 $length -= $lengthOfPadding;
1328 }
1329
1330 if ( $direction == STR_PAD_LEFT ) {
1331 return $finalPadding . $string;
1332 } else {
1333 return $string . $finalPadding;
1334 }
1335 }
1336
1344 public static function padleft( $parser, $string = '', $length = '0', $padding = '0' ) {
1345 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
1346 }
1347
1355 public static function padright( $parser, $string = '', $length = '0', $padding = '0' ) {
1356 return self::pad( $parser, $string, $length, $padding );
1357 }
1358
1364 public static function anchorencode( $parser, $text ) {
1365 $text = $parser->killMarkers( $text );
1366 $section = substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
1367 $encodedSection = Sanitizer::safeEncodeAttribute( $section );
1368 // decode underscores to avoid breaking templates (T407131)
1369 return str_replace( '&#95;', '_', $encodedSection );
1370 }
1371
1377 public static function special( $parser, $text ) {
1378 [ $page, $subpage ] = MediaWikiServices::getInstance()->getSpecialPageFactory()->
1379 resolveAlias( $text );
1380 if ( $page ) {
1381 $title = SpecialPage::getTitleFor( $page, $subpage );
1382 return $title->getPrefixedText();
1383 } else {
1384 // unknown special page, just use the given text as its title, if at all possible
1385 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
1386 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
1387 }
1388 }
1389
1395 public static function speciale( $parser, $text ) {
1396 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
1397 }
1398
1407 public static function defaultsort( $parser, $text, $uarg = '' ) {
1408 static $magicWords = null;
1409 if ( $magicWords === null ) {
1410 $magicWords = $parser->getMagicWordFactory()->newArray(
1411 [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
1412 }
1413 $arg = $magicWords->matchStartToEnd( $uarg );
1414
1415 $text = trim( $text );
1416 if ( $text === '' ) {
1417 return '';
1418 }
1419 $old = $parser->getOutput()->getPageProperty( 'defaultsort' );
1420 if ( $old === null || $arg !== 'defaultsort_noreplace' ) {
1421 $parser->getOutput()->setPageProperty( 'defaultsort', $text );
1422 }
1423
1424 if ( $old === null || $old == $text || $arg ) {
1425 return '';
1426 } else {
1427 $converter = $parser->getTargetLanguageConverter();
1428 return '<span class="error">' .
1429 $parser->msg( 'duplicate-defaultsort',
1430 // Message should be parsed, but these params should only be escaped.
1431 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
1432 $converter->markNoConversion( wfEscapeWikiText( $text ) )
1433 )->text() .
1434 '</span>';
1435 }
1436 }
1437
1449 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1450 $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile( $name );
1451
1452 if ( $argA == 'nowiki' ) {
1453 // {{filepath: | option [| size] }}
1454 $isNowiki = true;
1455 $parsedWidthParam = $parser->parseWidthParam( $argB );
1456 } else {
1457 // {{filepath: [| size [|option]] }}
1458 $parsedWidthParam = $parser->parseWidthParam( $argA );
1459 $isNowiki = ( $argB == 'nowiki' );
1460 }
1461
1462 if ( $file ) {
1463 $url = $file->getFullUrl();
1464
1465 // If a size is requested...
1466 if ( count( $parsedWidthParam ) ) {
1467 $mto = $file->transform( $parsedWidthParam );
1468 // ... and we can
1469 if ( $mto && !$mto->isError() ) {
1470 // ... change the URL to point to a thumbnail.
1471 $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
1472 $url = $urlUtils->expand( $mto->getUrl(), PROTO_RELATIVE ) ?? false;
1473 }
1474 }
1475 if ( $isNowiki ) {
1476 return [ $url, 'nowiki' => true ];
1477 }
1478 return $url;
1479 } else {
1480 return '';
1481 }
1482 }
1483
1491 public static function tagObj( $parser, $frame, $args ) {
1492 if ( !count( $args ) ) {
1493 return '';
1494 }
1495 $tagName = strtolower( trim( $parser->killMarkers(
1496 $frame->expand( array_shift( $args ) )
1497 ) ) );
1498 $processNowiki = $parser->tagNeedsNowikiStrippedInTagPF( $tagName ) ? PPFrame::PROCESS_NOWIKI : 0;
1499
1500 if ( count( $args ) ) {
1501 // With Parsoid Fragment support, $processNoWiki flag
1502 // isn't actually required as a ::expand() flag, but it
1503 // doesn't do any harm.
1504 $inner = $frame->expand( array_shift( $args ), $processNowiki );
1505 if ( $processNowiki ) {
1506 // This is the T299103 workaround for <syntaxhighlight>,
1507 // and reproduces the code in SyntaxHighlight::parserHook.
1508 // The Parsoid extension API (SyntaxHighlight::sourceToDom)
1509 // doesn't (yet) know about strip state, and so can't do
1510 // this itself.
1511 $inner = $parser->getStripState()->unstripNoWiki( $inner );
1512 }
1513 } else {
1514 $inner = null;
1515 }
1516
1517 $attributes = [];
1518 foreach ( $args as $arg ) {
1519 $bits = $arg->splitArg();
1520 if ( strval( $bits['index'] ) === '' ) {
1521 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1522 $value = trim( $frame->expand( $bits['value'] ) );
1523 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1524 $value = $m[1] ?? '';
1525 }
1526 $attributes[$name] = $value;
1527 }
1528 }
1529
1530 $stripList = $parser->getStripList();
1531 if ( !in_array( $tagName, $stripList ) ) {
1532 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1533 $attrText = '';
1534 foreach ( $attributes as $name => $value ) {
1535 $attrText .= ' ' . htmlspecialchars( $name ) .
1536 '="' . htmlspecialchars( $parser->killMarkers( $value ), ENT_COMPAT ) . '"';
1537 }
1538 if ( $inner === null ) {
1539 return "<$tagName$attrText/>";
1540 }
1541 return "<$tagName$attrText>$inner</$tagName>";
1542 }
1543
1544 $params = [
1545 'name' => $tagName,
1546 'inner' => $inner,
1547 'attributes' => $attributes,
1548 'close' => "</$tagName>",
1549 ];
1550 return $parser->extensionSubstitution( $params, $frame );
1551 }
1552
1566 private static function getCachedRevisionObject( $parser, $title, $vary ) {
1567 if ( !$title ) {
1568 return null;
1569 }
1570
1571 $revisionRecord = null;
1572
1573 $isSelfReferential = $title->equals( $parser->getTitle() );
1574 if ( $isSelfReferential ) {
1575 // Revision is for the same title that is currently being parsed. Only use the last
1576 // saved revision, regardless of Parser::getRevisionId() or fake revision injection
1577 // callbacks against the current title.
1578
1579 // FIXME (T318278): the above is the intention, but doesn't
1580 // describe the actual current behavior of this code, since
1581 // ->isCurrent() for the last saved revision will return
1582 // false so we're going to fall through and end up calling
1583 // ->getCurrentRevisionRecordOfTitle().
1584 $parserRevisionRecord = $parser->getRevisionRecordObject();
1585 if ( $parserRevisionRecord && $parserRevisionRecord->isCurrent() ) {
1586 $revisionRecord = $parserRevisionRecord;
1587 }
1588 }
1589
1590 $parserOutput = $parser->getOutput();
1591 if ( !$revisionRecord ) {
1592 if (
1593 !$parser->isCurrentRevisionOfTitleCached( $title ) &&
1595 ) {
1596 return null; // not allowed
1597 }
1598 // Get the current revision, ignoring Parser::getRevisionId() being null/old
1599 $revisionRecord = $parser->fetchCurrentRevisionRecordOfTitle( $title );
1600 if ( !$revisionRecord ) {
1601 // Convert `false` error return to `null`
1602 $revisionRecord = null;
1603 }
1604 // Register dependency in templatelinks
1605 $parserOutput->addTemplate(
1606 $title,
1607 $revisionRecord ? $revisionRecord->getPageId() : 0,
1608 $revisionRecord ? $revisionRecord->getId() : 0
1609 );
1610 }
1611
1612 if ( $isSelfReferential ) {
1613 wfDebug( __METHOD__ . ": used current revision, setting {$vary->value}" );
1614 // Upon page save, the result of the parser function using this might change
1615 $parserOutput->setOutputFlag( $vary );
1616 if ( $vary === ParserOutputFlags::VARY_REVISION_SHA1 && $revisionRecord ) {
1617 try {
1618 $sha1 = $revisionRecord->getSha1();
1619 } catch ( RevisionAccessException ) {
1620 $sha1 = null;
1621 }
1622 $parserOutput->setRevisionUsedSha1Base36( $sha1 );
1623 }
1624 }
1625
1626 return $revisionRecord;
1627 }
1628
1636 public static function pageid( $parser, $title = null ) {
1637 $t = self::makeTitle( $parser, $title );
1638 if ( !$t ) {
1639 return '';
1640 } elseif ( !$t->canExist() || $t->isExternal() ) {
1641 return 0; // e.g. special page or interwiki link
1642 }
1643
1644 $parserOutput = $parser->getOutput();
1645
1646 if ( $t->equals( $parser->getTitle() ) ) {
1647 // Revision is for the same title that is currently being parsed.
1648 // Use the title from Parser in case a new page ID was injected into it.
1649 $parserOutput->setOutputFlag( ParserOutputFlags::VARY_PAGE_ID );
1650 $id = $parser->getTitle()->getArticleID();
1651 if ( $id ) {
1652 $parserOutput->setSpeculativePageIdUsed( $id );
1653 }
1654
1655 return $id;
1656 }
1657
1658 // Check the link cache for the title
1659 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1660 $pdbk = $t->getPrefixedDBkey();
1661 $id = $linkCache->getGoodLinkID( $pdbk );
1662 if ( $id != 0 || $linkCache->isBadLink( $pdbk ) ) {
1663 $parserOutput->addLink( $t, $id );
1664
1665 return $id;
1666 }
1667
1668 // We need to load it from the DB, so mark expensive
1669 if ( $parser->incrementExpensiveFunctionCount() ) {
1670 $id = $t->getArticleID();
1671 $parserOutput->addLink( $t, $id );
1672
1673 return $id;
1674 }
1675
1676 return null;
1677 }
1678
1686 public static function revisionid( $parser, $title = null ) {
1687 $t = self::makeTitle( $parser, $title );
1688 if ( $t === null || $t->isExternal() ) {
1689 return '';
1690 }
1691
1692 $services = MediaWikiServices::getInstance();
1693 if (
1694 $t->equals( $parser->getTitle() ) &&
1695 $services->getMainConfig()->get( MainConfigNames::MiserMode ) &&
1696 !$parser->getOptions()->getInterfaceMessage() &&
1697 // @TODO: disallow this word on all namespaces (T235957)
1698 $services->getNamespaceInfo()->isSubject( $t->getNamespace() )
1699 ) {
1700 // Use a stub result instead of the actual revision ID in order to avoid
1701 // double parses on page save but still allow preview detection (T137900)
1702 if ( $parser->getRevisionId() || $parser->getOptions()->getSpeculativeRevId() ) {
1703 return '-';
1704 } else {
1705 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_REVISION_EXISTS );
1706 return '';
1707 }
1708 }
1709 // Fetch revision from cache/database and return the value.
1710 // Inform the edit saving system that getting the canonical output
1711 // after revision insertion requires a parse that used that exact
1712 // revision ID.
1713 if ( $t->equals( $parser->getTitle() ) && $title === null ) {
1714 // special handling for no-arg case: use speculative rev id
1715 // for current page.
1716 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_REVISION_ID );
1717 $id = $parser->getRevisionId();
1718 if ( $id === 0 ) {
1719 $rev = $parser->getRevisionRecordObject();
1720 if ( $rev ) {
1721 $id = $rev->getId();
1722 }
1723 }
1724 if ( !$id ) {
1725 $id = $parser->getOptions()->getSpeculativeRevId();
1726 if ( $id ) {
1727 $parser->getOutput()->setSpeculativeRevIdUsed( $id );
1728 }
1729 }
1730 return (string)$id;
1731 }
1732 $rev = self::getCachedRevisionObject( $parser, $t, ParserOutputFlags::VARY_REVISION_ID );
1733 return $rev ? $rev->getId() : '';
1734 }
1735
1736 private static function getRevisionTimestampSubstring(
1737 Parser $parser,
1738 Title $title,
1739 int $start,
1740 int $len,
1741 int $mtts
1742 ): string {
1743 // If fetching the revision timestamp of the current page, substitute the
1744 // speculative timestamp to be used when this revision is saved. This
1745 // avoids having to invalidate the cache immediately by assuming the "last
1746 // saved revision" will in fact be this one.
1747 // Don't do this for interface messages (eg, edit notices) however; in that
1748 // case fall through and use the actual timestamp of the last saved revision.
1749 if ( $title->equals( $parser->getTitle() ) && !$parser->getOptions()->getInterfaceMessage() ) {
1750 // Get the timezone-adjusted timestamp to be used for this revision
1751 $resNow = substr( $parser->getRevisionTimestamp(), $start, $len );
1752 // Possibly set vary-revision if there is not yet an associated revision
1753 if ( !$parser->getRevisionRecordObject() ) {
1754 // Get the timezone-adjusted timestamp $mtts seconds in the future.
1755 // This future is relative to the current time and not that of the
1756 // parser options. The rendered timestamp can be compared to that
1757 // of the timestamp specified by the parser options.
1758 $resThen = substr(
1759 $parser->getContentLanguage()->userAdjust( wfTimestamp( TS::MW, time() + $mtts ), '' ),
1760 $start,
1761 $len
1762 );
1763
1764 if ( $resNow !== $resThen ) {
1765 // Inform the edit saving system that getting the canonical output after
1766 // revision insertion requires a parse that used an actual revision timestamp
1767 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_REVISION_TIMESTAMP );
1768 }
1769 }
1770
1771 return $resNow;
1772 } else {
1773 $rev = self::getCachedRevisionObject( $parser, $title, ParserOutputFlags::VARY_REVISION_TIMESTAMP );
1774 if ( !$rev ) {
1775 return '';
1776 }
1777 $resNow = substr(
1778 $parser->getContentLanguage()->userAdjust( $rev->getTimestamp(), '' ), $start, $len
1779 );
1780 return $resNow;
1781 }
1782 }
1783
1791 public static function revisionday( $parser, $title = null ) {
1792 $t = self::makeTitle( $parser, $title );
1793 if ( $t === null || $t->isExternal() ) {
1794 return '';
1795 }
1796 return strval( (int)self::getRevisionTimestampSubstring(
1797 $parser, $t, 6, 2, self::MAX_TTS
1798 ) );
1799 }
1800
1808 public static function revisionday2( $parser, $title = null ) {
1809 $t = self::makeTitle( $parser, $title );
1810 if ( $t === null || $t->isExternal() ) {
1811 return '';
1812 }
1813 return self::getRevisionTimestampSubstring(
1814 $parser, $t, 6, 2, self::MAX_TTS
1815 );
1816 }
1817
1825 public static function revisionmonth( $parser, $title = null ) {
1826 $t = self::makeTitle( $parser, $title );
1827 if ( $t === null || $t->isExternal() ) {
1828 return '';
1829 }
1830 return self::getRevisionTimestampSubstring(
1831 $parser, $t, 4, 2, self::MAX_TTS
1832 );
1833 }
1834
1842 public static function revisionmonth1( $parser, $title = null ) {
1843 $t = self::makeTitle( $parser, $title );
1844 if ( $t === null || $t->isExternal() ) {
1845 return '';
1846 }
1847 return strval( (int)self::getRevisionTimestampSubstring(
1848 $parser, $t, 4, 2, self::MAX_TTS
1849 ) );
1850 }
1851
1859 public static function revisionyear( $parser, $title = null ) {
1860 $t = self::makeTitle( $parser, $title );
1861 if ( $t === null || $t->isExternal() ) {
1862 return '';
1863 }
1864 return self::getRevisionTimestampSubstring(
1865 $parser, $t, 0, 4, self::MAX_TTS
1866 );
1867 }
1868
1876 public static function revisiontimestamp( $parser, $title = null ) {
1877 $t = self::makeTitle( $parser, $title );
1878 if ( $t === null || $t->isExternal() ) {
1879 return '';
1880 }
1881 return self::getRevisionTimestampSubstring(
1882 $parser, $t, 0, 14, self::MAX_TTS
1883 );
1884 }
1885
1893 public static function revisionuser( $parser, $title = null ) {
1894 $t = self::makeTitle( $parser, $title );
1895 if ( $t === null || $t->isExternal() ) {
1896 return '';
1897 }
1898 // VARY_USER informs the edit saving system that getting the canonical
1899 // output after revision insertion requires a parse that used the
1900 // actual user ID.
1901 if ( $t->equals( $parser->getTitle() ) ) {
1902 // Fall back to Parser's "revision user" for the current title
1903 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_USER );
1904 // Note that getRevisionUser() can return null; we need to
1905 // be sure to cast this to (an empty) string, since returning
1906 // null means "magic variable not handled".
1907 return (string)$parser->getRevisionUser();
1908 }
1909 // Fetch revision from cache/database and return the value.
1910 $rev = self::getCachedRevisionObject( $parser, $t, ParserOutputFlags::VARY_USER );
1911 $user = ( $rev !== null ) ? $rev->getUser() : null;
1912 return $user ? $user->getName() : '';
1913 }
1914
1927 public static function cascadingsources( $parser, $title = '' ) {
1928 $titleObject = Title::newFromText( $title ) ?? $parser->getTitle();
1929 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
1930 if ( $restrictionStore->areCascadeProtectionSourcesLoaded( $titleObject )
1932 ) {
1933 $names = [];
1934 $sources = $restrictionStore->getCascadeProtectionSources( $titleObject );
1935 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
1936 foreach ( $sources[0] as $sourcePageIdentity ) {
1937 $names[] = $titleFormatter->getPrefixedText( $sourcePageIdentity );
1938 }
1939 return implode( '|', $names );
1940 }
1941 return '';
1942 }
1943
1951 public static function contentmodel( Parser $parser, ?string $format = null, ?string $title = null ) {
1952 static $magicWords = null;
1953 if ( $magicWords === null ) {
1954 $magicWords = $parser->getMagicWordFactory()->newArray( [
1955 'contentmodel_canonical',
1956 'contentmodel_local',
1957 ] );
1958 }
1959
1960 $formatType = $format === null ? 'contentmodel_local' :
1961 $magicWords->matchStartToEnd( $format );
1962
1963 $t = self::makeTitle( $parser, $title );
1964 if ( $t === null ) {
1965 return '';
1966 }
1967
1968 if ( !$parser->incrementExpensiveFunctionCount() ) {
1969 return '';
1970 }
1971
1972 $contentModel = $t->getContentModel();
1973 if ( $formatType === 'contentmodel_canonical' ) {
1974 return wfEscapeWikiText( $contentModel );
1975 } elseif ( $formatType === 'contentmodel_local' ) {
1976 $localizedContentModel = ContentHandler::getLocalizedName( $contentModel, $parser->getTargetLanguage() );
1977 return wfEscapeWikiText( $localizedContentModel );
1978 } else {
1979 // Unknown format option
1980 return '';
1981 }
1982 }
1983
1989 public static function isbn( $parser, $isbn = '' ) {
1990 $space = '(?:\t|&nbsp;|&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
1991 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1992 $regex = "!
1993 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1994 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1995 [0-9Xx] # check digit
1996 !xu";
1997 if ( !preg_match( $regex, $isbn ) ) {
1998 return [ 'found' => false ];
1999 }
2000 $isbn = preg_replace( "/$space/", ' ', $isbn );
2001 $num = strtr( $isbn, [
2002 '-' => '',
2003 ' ' => '',
2004 'x' => 'X',
2005 ] );
2006 $target = SpecialPage::getTitleFor( 'Booksources', $num );
2007 $parser->getOutput()->addLink( $target );
2008 return [
2009 'text' => $parser->getLinkRenderer()->makeKnownLink(
2010 $target,
2011 "ISBN $isbn",
2012 [
2013 'class' => 'internal mw-magiclink-isbn',
2014 'title' => false, // suppress title attribute
2015 ]
2016 ),
2017 'isHTML' => true,
2018 ];
2019 }
2020
2028 public static function interwikilink( $parser, $prefix = '', $title = '', $linkText = null ) {
2029 $services = MediaWikiServices::getInstance();
2030 if (
2031 $prefix !== '' &&
2032 $services->getInterwikiLookup()->isValidInterwiki( $prefix )
2033 ) {
2034
2035 $target = self::getTitleValueSafe( $title, $prefix );
2036
2037 if ( $target !== null ) {
2038 if ( $linkText !== null ) {
2039 $linkText = Parser::stripOuterParagraph(
2040 # FIXME T382287: when using Parsoid this may leave
2041 # strip markers behind for embedded extension tags.
2042 $parser->recursiveTagParseFully( $linkText )
2043 );
2044 }
2045 $parser->getOutput()->addInterwikiLink( $target );
2046 return [
2047 'text' => Linker::link( $target, $linkText ),
2048 'isHTML' => true,
2049 ];
2050 }
2051 }
2052 // Invalid interwiki link, render as plain text
2053 return [ 'found' => false ];
2054 }
2055
2063 public static function interlanguagelink( $parser, $prefix = '', $title = '', $linkText = null ) {
2064 $services = MediaWikiServices::getInstance();
2065 $extraInterlanguageLinkPrefixes = $services->getMainConfig()->get(
2066 MainConfigNames::ExtraInterlanguageLinkPrefixes
2067 );
2068 if (
2069 $prefix !== '' &&
2070 $services->getInterwikiLookup()->isValidInterwiki( $prefix ) &&
2071 (
2072 $services->getLanguageNameUtils()->getLanguageName(
2073 $prefix, LanguageNameUtils::AUTONYMS, LanguageNameUtils::DEFINED
2074 ) || in_array( $prefix, $extraInterlanguageLinkPrefixes, true )
2075 )
2076 ) {
2077 // $linkText is ignored for language links, but fragment is kept
2078 $target = self::getTitleValueSafe( $title, $prefix );
2079
2080 if ( $target !== null ) {
2081 $parser->getOutput()->addLanguageLink( $target );
2082 return '';
2083 }
2084 }
2085 // Invalid language link, render as plain text
2086 return [ 'found' => false ];
2087 }
2088
2104 private static function getTitleValueSafe( $title, $prefix ): ?TitleValue {
2105 [ $title, $frag ] = array_pad( explode( '#', $title, 2 ), 2, '' );
2106
2107 try {
2108 return new TitleValue( NS_MAIN, $title, $frag, $prefix );
2109 } catch ( InvalidArgumentException ) {
2110 return null;
2111 }
2112 }
2113}
2114
2116class_alias( CoreParserFunctions::class, 'CoreParserFunctions' );
const NS_USER
Definition Defines.php:53
const NS_FILE
Definition Defines.php:57
const NS_MAIN
Definition Defines.php:51
const NS_SPECIAL
Definition Defines.php:40
const NS_MEDIA
Definition Defines.php:39
const PROTO_RELATIVE
Definition Defines.php:219
const NS_CATEGORY
Definition Defines.php:65
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
$magicWords
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
Category objects are immutable, strictly speaking.
Definition Category.php:29
A class for passing options to services.
Base class for content handling.
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
Methods for dealing with language codes.
Base class for language-specific code.
Definition Language.php:68
Some internal bits split of from Skin.php.
Definition Linker.php:47
A class containing constants representing the names of configuration variables.
const AllowSlowParserFunctions
Name constant for the AllowSlowParserFunctions setting, for use with Config::get()
const AllowDisplayTitle
Name constant for the AllowDisplayTitle setting, for use with Config::get()
const RestrictDisplayTitle
Name constant for the RestrictDisplayTitle setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Various core parser functions, registered in every Parser.
static pagesize( $parser, $page='', $raw=null)
Return the size of the given page, or 0 if it's nonexistent.
static pagesincategory( $parser, $name='', $arg1='', $arg2='')
Return the number of pages, files or subcats in the given category, or 0 if it's nonexistent.
static language( $parser, $code='', $inLanguage='')
Gives language names.
static bcp47(Parser $parser, string $code='')
Gives the BCP-47 code for a language given the mediawiki internal language code.
static numberofedits( $parser, $raw=null)
static namespacenumber( $parser, $title=null)
static revisiontimestamp( $parser, $title=null)
Get the timestamp from the last revision of a specified page.
static defaultsort( $parser, $text, $uarg='')
static basepagename( $parser, $title=null)
static formal(Parser $parser, string ... $forms)
static namespacee( $parser, $title=null)
static numberofpages( $parser, $raw=null)
static dir(Parser $parser, string $code='', string $arg='')
Gives direction of script of a language given a language code.
static numberingroup( $parser, $name='', $raw=null)
static interlanguagelink( $parser, $prefix='', $title='', $linkText=null)
static fullurle( $parser, $s='', $arg=null)
static pageid( $parser, $title=null)
Get the pageid of a specified page.
static intFunction( $parser, $part1='',... $params)
static pagesinnamespace( $parser, $namespace='0', $raw=null)
static tagObj( $parser, $frame, $args)
Parser function to extension tag adaptor.
static numberofusers( $parser, $raw=null)
static formatDate( $parser, $date, $defaultPref=null)
static talkspacee( $parser, $title=null)
static subjectpagenamee( $parser, $title=null)
static rootpagename( $parser, $title=null)
static cascadingsources( $parser, $title='')
Returns the sources of any cascading protection acting on a specified page.
static padright( $parser, $string='', $length='0', $padding='0')
static fullpagename( $parser, $title=null)
static formatRaw( $num, $raw, $language, ?MagicWordFactory $magicWordFactory=null)
Formats a number according to a language.
static plural( $parser, $text='',... $forms)
static subpagenamee( $parser, $title=null)
static fullpagenamee( $parser, $title=null)
static urlFunction( $func, $s='', $arg=null)
static talkpagenamee( $parser, $title=null)
static canonicalurl( $parser, $s='', $arg=null)
static pad( $parser, $string, $length, $padding='0', $direction=STR_PAD_RIGHT)
Unicode-safe str_pad with the restriction that $length is forced to be <= 500.
static revisionday2( $parser, $title=null)
Get the day with leading zeros from the last revision of a specified page.
static protectionexpiry( $parser, $type='', $title='')
Returns the requested protection expiry for the current page.
static padleft( $parser, $string='', $length='0', $padding='0')
static talkspace( $parser, $title=null)
static numberofactiveusers( $parser, $raw=null)
static subjectspacee( $parser, $title=null)
static pagenamee( $parser, $title=null)
static grammar( $parser, $case='', $word='')
static revisionuser( $parser, $title=null)
Get the user from the last revision of a specified page.
static localurl( $parser, $s='', $arg=null)
static urlencode( $parser, $s='', $arg=null)
urlencodes a string according to one of three patterns: (T24474)
static localurle( $parser, $s='', $arg=null)
static formatnum( $parser, $num='', $arg1='', $arg2='')
static rootpagenamee( $parser, $title=null)
static contentmodel(Parser $parser, ?string $format=null, ?string $title=null)
static protectionlevel( $parser, $type='', $title='')
Returns the requested protection level for the current page.
static subpagename( $parser, $title=null)
static subjectpagename( $parser, $title=null)
static interwikilink( $parser, $prefix='', $title='', $linkText=null)
static numberofadmins( $parser, $raw=null)
static revisionday( $parser, $title=null)
Get the day from the last revision of a specified page.
static canonicalurle( $parser, $s='', $arg=null)
static subjectspace( $parser, $title=null)
static revisionmonth( $parser, $title=null)
Get the month with leading zeros from the last revision of a specified page.
static basepagenamee( $parser, $title=null)
static gender( $parser, $username,... $forms)
static revisionyear( $parser, $title=null)
Get the year from the last revision of a specified page.
static pagename( $parser, $title=null)
Functions to get and normalize pagenames, corresponding to the magic words of the same names.
static fullurl( $parser, $s='', $arg=null)
static numberofarticles( $parser, $raw=null)
static revisionmonth1( $parser, $title=null)
Get the month from the last revision of a specified page.
static displaytitle( $parser, $text='', $uarg='')
Override the title of the page when viewed, provided we've been given a title which will normalise to...
static talkpagename( $parser, $title=null)
static revisionid( $parser, $title=null)
Get the id from the last revision of a specified page.
static numberoffiles( $parser, $raw=null)
static filepath( $parser, $name='', $argA='', $argB='')
Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}} or {{...
Store information about magic words, and create/cache MagicWord objects.
get( $id)
Get a MagicWord object for a given internal ID.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:135
getTargetLanguageConverter()
Shorthand for getting a Language Converter for Target language.
Definition Parser.php:1585
markerSkipCallback( $s, callable $callback)
Call a callback function on all regions of the given text that are not inside strip markers,...
Definition Parser.php:6322
getLinkRenderer()
Get a LinkRenderer instance to make links with.
Definition Parser.php:1151
tagNeedsNowikiStrippedInTagPF(string $lowerTagName)
Definition Parser.php:3941
getMagicWordFactory()
Get the MagicWordFactory that this Parser is using.
Definition Parser.php:1166
setFunctionHook( $id, callable $callback, $flags=0)
Create a function, e.g.
Definition Parser.php:5063
guessSectionNameFromWikiText( $text)
Try to guess the section anchor name based on a wikitext fragment presumably extracted from a heading...
Definition Parser.php:6215
isCurrentRevisionOfTitleCached(LinkTarget $link)
Definition Parser.php:3551
getRevisionId()
Get the ID of the revision we are parsing.
Definition Parser.php:6052
getContentLanguage()
Get the content language that this Parser is using.
Definition Parser.php:1176
parseWidthParam( $value, $parseHeight=true, bool $localized=false)
Parsed a width param of imagelink like 300px or 200x300px.
Definition Parser.php:6370
killMarkers( $text)
Remove any strip markers found in the given text.
Definition Parser.php:6353
getRevisionUser()
Get the name of the user that edited the last revision.
Definition Parser.php:6147
getTargetLanguage()
Get the target language for the content being parsed.
Definition Parser.php:1112
msg(string $msg,... $params)
Helper function to correctly set the target language and title of a message based on the parser conte...
Definition Parser.php:4182
getStripList()
Get a list of strippable XML-like elements.
Definition Parser.php:1272
extensionSubstitution(array $params, PPFrame $frame, bool $processNowiki=false)
Return the text to be used for a given extension tag.
Definition Parser.php:3965
getRevisionRecordObject()
Get the revision record object for $this->mRevisionId.
Definition Parser.php:6062
getRevisionTimestamp()
Get the timestamp associated with the current revision, adjusted for the default server-local timesta...
Definition Parser.php:6119
doQuotes( $text)
Helper function for handleAllQuotes()
Definition Parser.php:1923
recursiveTagParseFully( $text, $frame=false)
Fully parse wikitext to fully parsed HTML.
Definition Parser.php:818
fetchCurrentRevisionRecordOfTitle(LinkTarget $link)
Fetch the current revision of a given title as a RevisionRecord.
Definition Parser.php:3522
static stripAllTags(string $html)
Take a fragment of (potentially invalid) HTML and return a version with any tags removed,...
static checkCss( $value)
Pick apart some CSS and check it for forbidden or unsafe structures.
static decodeCharReferencesAndNormalize(string $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
static removeSomeTags(string $text, array $options=[])
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments; the result will alw...
Exception representing a failure to look up a revision.
Page revision base class.
Static accessor class for site_stats and related things.
Definition SiteStats.php:22
Parent class for all special pages.
Represents the target of a wiki link.
Represents a title within MediaWiki.
Definition Title.php:69
inNamespace(int $ns)
Returns true if the title is inside the specified namespace.
Definition Title.php:1295
equals(object $other)
Compares with another Title.
Definition Title.php:3086
getDBkey()
Get the main part with underscores.
Definition Title.php:1028
getText()
Get the text form (spaces not underscores) of the main part.
Definition Title.php:1010
getDefaultOption(string $opt, ?UserIdentity $userIdentity=null)
Get a given default option value.
User class for the MediaWiki software.
Definition User.php:130
hasFragment()
Whether the link target has a fragment.