Debian Codegraph @

includes/parser/CoreParserFunctions.php

raw symbols SCIP
1 <?php
2 /**
3 * Parser functions provided by MediaWiki core
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 namespace MediaWiki\Parser;
25
26 use InvalidArgumentException;
27 use MediaWiki\Category\Category;
28 use MediaWiki\Config\ServiceOptions;
29 use MediaWiki\Language\Language;
30 use MediaWiki\Language\LanguageCode;
31 use MediaWiki\Languages\LanguageNameUtils;
32 use MediaWiki\MainConfigNames;
33 use MediaWiki\MediaWikiServices;
34 use MediaWiki\Message\Message;
35 use MediaWiki\Revision\RevisionAccessException;
36 use MediaWiki\Revision\RevisionRecord;
37 use MediaWiki\SiteStats\SiteStats;
38 use MediaWiki\SpecialPage\SpecialPage;
39 use MediaWiki\Title\Title;
40 use MediaWiki\User\User;
41 use Wikimedia\Bcp47Code\Bcp47CodeValue;
42 use Wikimedia\RemexHtml\Tokenizer\Attributes;
43 use Wikimedia\RemexHtml\Tokenizer\PlainAttributes;
44
45 /**
46 * Various core parser functions, registered in every Parser
47 * @ingroup Parser
48 */
49 class CoreParserFunctions {
50 /** @var int Assume that no output will later be saved this many seconds after parsing */
51 private const MAX_TTS = 900;
52
53 /**
54 * @internal
55 */
56 public const REGISTER_OPTIONS = [
57 // See documentation for the corresponding config options
58 MainConfigNames::AllowDisplayTitle,
59 MainConfigNames::AllowSlowParserFunctions,
60 ];
61
62 /**
63 * @param Parser $parser
64 * @param ServiceOptions $options
65 *
66 * @return void
67 * @internal
68 */
69 public static function register( Parser $parser, ServiceOptions $options ) {
70 $options->assertRequiredOptions( self::REGISTER_OPTIONS );
71 $allowDisplayTitle = $options->get( MainConfigNames::AllowDisplayTitle );
72 $allowSlowParserFunctions = $options->get( MainConfigNames::AllowSlowParserFunctions );
73
74 # Syntax for arguments (see Parser::setFunctionHook):
75 # "name for lookup in localized magic words array",
76 # function callback,
77 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
78 # instead of {{#int:...}})
79 $noHashFunctions = [
80 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
81 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
82 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural', 'formal',
83 'bidi', 'numberingroup', 'language',
84 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
85 'pagesincategory', 'pagesize', 'protectionlevel', 'protectionexpiry',
86 # The following are the "parser function" forms of magic
87 # variables defined in CoreMagicVariables. The no-args form will
88 # go through the magic variable code path (and be cached); the
89 # presence of arguments will cause the parser function form to
90 # be invoked. (Note that the actual implementation will pass
91 # a Parser object as first argument, in addition to the
92 # parser function parameters.)
93
94 # For this group, the first parameter to the parser function is
95 # "page title", and the no-args form (and the magic variable)
96 # defaults to "current page title".
97 'pagename', 'pagenamee',
98 'fullpagename', 'fullpagenamee',
99 'subpagename', 'subpagenamee',
100 'rootpagename', 'rootpagenamee',
101 'basepagename', 'basepagenamee',
102 'talkpagename', 'talkpagenamee',
103 'subjectpagename', 'subjectpagenamee',
104 'pageid', 'revisionid', 'revisionday',
105 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
106 'revisiontimestamp',
107 'revisionuser',
108 'cascadingsources',
109 'namespace', 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
110 'subjectspace', 'subjectspacee',
111
112 # More parser functions corresponding to CoreMagicVariables.
113 # For this group, the first parameter to the parser function is
114 # "raw" (uses the 'raw' format if present) and the no-args form
115 # (and the magic variable) defaults to 'not raw'.
116 'numberofarticles', 'numberoffiles',
117 'numberofusers',
118 'numberofactiveusers',
119 'numberofpages',
120 'numberofadmins',
121 'numberofedits',
122
123 # These magic words already contain the hash, and the no-args form
124 # is the same as passing an empty first argument
125 'bcp47',
126 'dir',
127 ];
128 foreach ( $noHashFunctions as $func ) {
129 $parser->setFunctionHook( $func, [ __CLASS__, $func ], Parser::SFH_NO_HASH );
130 }
131
132 $parser->setFunctionHook( 'int', [ __CLASS__, 'intFunction' ], Parser::SFH_NO_HASH );
133 $parser->setFunctionHook( 'special', [ __CLASS__, 'special' ] );
134 $parser->setFunctionHook( 'speciale', [ __CLASS__, 'speciale' ] );
135 $parser->setFunctionHook( 'tag', [ __CLASS__, 'tagObj' ], Parser::SFH_OBJECT_ARGS );
136 $parser->setFunctionHook( 'formatdate', [ __CLASS__, 'formatDate' ] );
137
138 if ( $allowDisplayTitle ) {
139 $parser->setFunctionHook(
140 'displaytitle',
141 [ __CLASS__, 'displaytitle' ],
142 Parser::SFH_NO_HASH
143 );
144 }
145 if ( $allowSlowParserFunctions ) {
146 $parser->setFunctionHook(
147 'pagesinnamespace',
148 [ __CLASS__, 'pagesinnamespace' ],
149 Parser::SFH_NO_HASH
150 );
151 }
152 }
153
154 /**
155 * @param Parser $parser
156 * @param string $part1 Message key
157 * @param mixed ...$params To pass to wfMessage()
158 * @return array
159 */
160 public static function intFunction( $parser, $part1 = '', ...$params ) {
161 if ( strval( $part1 ) !== '' ) {
162 $message = wfMessage( $part1, $params )
163 ->inLanguage( $parser->getOptions()->getUserLangObj() );
164 return [ $message->plain(), 'noparse' => false ];
165 } else {
166 return [ 'found' => false ];
167 }
168 }
169
170 /**
171 * @param Parser $parser
172 * @param string $date
173 * @param string|null $defaultPref
174 *
175 * @return string
176 */
177 public static function formatDate( $parser, $date, $defaultPref = null ) {
178 $lang = $parser->getTargetLanguage();
179 $df = MediaWikiServices::getInstance()->getDateFormatterFactory()->get( $lang );
180
181 $date = trim( $date );
182
183 $pref = $parser->getOptions()->getDateFormat();
184
185 // Specify a different default date format other than the normal default
186 // if the user has 'default' for their setting
187 if ( $pref == 'default' && $defaultPref ) {
188 $pref = $defaultPref;
189 }
190
191 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
192 return $date;
193 }
194
195 public static function ns( $parser, $part1 = '' ) {
196 if ( intval( $part1 ) || $part1 == "0" ) {
197 $index = intval( $part1 );
198 } else {
199 $index = $parser->getContentLanguage()->getNsIndex( str_replace( ' ', '_', $part1 ) );
200 }
201 if ( $index !== false ) {
202 return $parser->getContentLanguage()->getFormattedNsText( $index );
203 } else {
204 return [ 'found' => false ];
205 }
206 }
207
208 public static function nse( $parser, $part1 = '' ) {
209 $ret = self::ns( $parser, $part1 );
210 if ( is_string( $ret ) ) {
211 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
212 }
213 return $ret;
214 }
215
216 /**
217 * urlencodes a string according to one of three patterns: (T24474)
218 *
219 * By default (for HTTP "query" strings), spaces are encoded as '+'.
220 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
221 * For links to "wiki"s, or similar software, spaces are encoded as '_',
222 *
223 * @param Parser $parser
224 * @param string $s The text to encode.
225 * @param string|null $arg (optional): The type of encoding.
226 * @return string
227 */
228 public static function urlencode( $parser, $s = '', $arg = null ) {
229 static $magicWords = null;
230 if ( $magicWords === null ) {
231 $magicWords =
232 $parser->getMagicWordFactory()->newArray( [ 'url_path', 'url_query', 'url_wiki' ] );
233 }
234 switch ( $magicWords->matchStartToEnd( $arg ?? '' ) ) {
235 // Encode as though it's a wiki page, '_' for ' '.
236 case 'url_wiki':
237 $func = 'wfUrlencode';
238 $s = str_replace( ' ', '_', $s );
239 break;
240
241 // Encode for an HTTP Path, '%20' for ' '.
242 case 'url_path':
243 $func = 'rawurlencode';
244 break;
245
246 // Encode for HTTP query, '+' for ' '.
247 case 'url_query':
248 default:
249 $func = 'urlencode';
250 }
251 // See T105242, where the choice to kill markers and various
252 // other options were discussed.
253 return $func( $parser->killMarkers( $s ) );
254 }
255
256 public static function lcfirst( $parser, $s = '' ) {
257 return $parser->getContentLanguage()->lcfirst( $s );
258 }
259
260 public static function ucfirst( $parser, $s = '' ) {
261 return $parser->getContentLanguage()->ucfirst( $s );
262 }
263
264 /**
265 * @param Parser $parser
266 * @param string $s
267 * @return string
268 */
269 public static function lc( $parser, $s = '' ) {
270 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'lc' ] );
271 }
272
273 /**
274 * @param Parser $parser
275 * @param string $s
276 * @return string
277 */
278 public static function uc( $parser, $s = '' ) {
279 return $parser->markerSkipCallback( $s, [ $parser->getContentLanguage(), 'uc' ] );
280 }
281
282 public static function localurl( $parser, $s = '', $arg = null ) {
283 return self::urlFunction( 'getLocalURL', $s, $arg );
284 }
285
286 public static function localurle( $parser, $s = '', $arg = null ) {
287 $temp = self::urlFunction( 'getLocalURL', $s, $arg );
288 if ( !is_string( $temp ) ) {
289 return $temp;
290 } else {
291 return htmlspecialchars( $temp, ENT_COMPAT );
292 }
293 }
294
295 public static function fullurl( $parser, $s = '', $arg = null ) {
296 return self::urlFunction( 'getFullURL', $s, $arg );
297 }
298
299 public static function fullurle( $parser, $s = '', $arg = null ) {
300 $temp = self::urlFunction( 'getFullURL', $s, $arg );
301 if ( !is_string( $temp ) ) {
302 return $temp;
303 } else {
304 return htmlspecialchars( $temp, ENT_COMPAT );
305 }
306 }
307
308 public static function canonicalurl( $parser, $s = '', $arg = null ) {
309 return self::urlFunction( 'getCanonicalURL', $s, $arg );
310 }
311
312 public static function canonicalurle( $parser, $s = '', $arg = null ) {
313 $temp = self::urlFunction( 'getCanonicalURL', $s, $arg );
314 if ( !is_string( $temp ) ) {
315 return $temp;
316 } else {
317 return htmlspecialchars( $temp, ENT_COMPAT );
318 }
319 }
320
321 public static function urlFunction( $func, $s = '', $arg = null ) {
322 # Due to order of execution of a lot of bits, the values might be encoded
323 # before arriving here; if that's true, then the title can't be created
324 # and the variable will fail. If we can't get a decent title from the first
325 # attempt, url-decode and try for a second.
326 $title = Title::newFromText( $s ) ?? Title::newFromURL( urldecode( $s ) );
327 if ( $title !== null ) {
328 # Convert NS_MEDIA -> NS_FILE
329 if ( $title->inNamespace( NS_MEDIA ) ) {
330 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
331 }
332 if ( $arg !== null ) {
333 $text = $title->$func( $arg );
334 } else {
335 $text = $title->$func();
336 }
337 return $text;
338 } else {
339 return [ 'found' => false ];
340 }
341 }
342
343 /**
344 * @param Parser $parser
345 * @param string $num
346 * @param string|null $arg
347 * @return string
348 */
349 public static function formatnum( $parser, $num = '', $arg = null ) {
350 if ( self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg ) ) {
351 $func = [ $parser->getTargetLanguage(), 'parseFormattedNumber' ];
352 } elseif (
353 self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'nocommafysuffix', $arg )
354 ) {
355 $func = [ $parser->getTargetLanguage(), 'formatNumNoSeparators' ];
356 $func = self::getLegacyFormatNum( $parser, $func );
357 } else {
358 $func = [ $parser->getTargetLanguage(), 'formatNum' ];
359 $func = self::getLegacyFormatNum( $parser, $func );
360 }
361 return $parser->markerSkipCallback( $num, $func );
362 }
363
364 /**
365 * @param Parser $parser
366 * @param callable $callback
367 *
368 * @return callable
369 */
370 private static function getLegacyFormatNum( $parser, $callback ) {
371 // For historic reasons, the formatNum parser function will
372 // take arguments which are not actually formatted numbers,
373 // which then trigger deprecation warnings in Language::formatNum*.
374 // Instead emit a tracking category instead to allow linting.
375 return static function ( $number ) use ( $parser, $callback ) {
376 $validNumberRe = '(-(?=[\d\.]))?(\d+|(?=\.\d))(\.\d*)?([Ee][-+]?\d+)?';
377 if (
378 !is_numeric( $number ) &&
379 $number !== 'NAN' &&
380 $number !== 'INF' &&
381 $number !== '-INF'
382 ) {
383 $parser->addTrackingCategory( 'nonnumeric-formatnum' );
384 // Don't split on NAN/INF in the legacy case since they are
385 // likely to be found embedded inside non-numeric text.
386 return preg_replace_callback( "/{$validNumberRe}/", static function ( $m ) use ( $callback ) {
387 return call_user_func( $callback, $m[0] );
388 }, $number );
389 }
390 return call_user_func( $callback, $number );
391 };
392 }
393
394 /**
395 * @param Parser $parser
396 * @param string $case
397 * @param string $word
398 * @return string
399 */
400 public static function grammar( $parser, $case = '', $word = '' ) {
401 $word = $parser->killMarkers( $word );
402 return $parser->getTargetLanguage()->convertGrammar( $word, $case );
403 }
404
405 /**
406 * @param Parser $parser
407 * @param string $username
408 * @param string ...$forms What to output for each gender
409 * @return string
410 */
411 public static function gender( $parser, $username, ...$forms ) {
412 // Some shortcuts to avoid loading user data unnecessarily
413 if ( count( $forms ) === 0 ) {
414 return '';
415 } elseif ( count( $forms ) === 1 ) {
416 return $forms[0];
417 }
418
419 $username = trim( $username );
420
421 $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
422 $gender = $userOptionsLookup->getDefaultOption( 'gender' );
423
424 // allow prefix and normalize (e.g. "&#42;foo" -> "*foo" ).
425 $title = Title::newFromText( $username, NS_USER );
426
427 if ( $title && $title->inNamespace( NS_USER ) ) {
428 $username = $title->getText();
429 }
430
431 // check parameter, or use the ParserOptions if in interface message
432 $user = User::newFromName( $username );
433 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
434 if ( $user ) {
435 $gender = $genderCache->getGenderOf( $user, __METHOD__ );
436 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
437 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUserIdentity(), __METHOD__ );
438 }
439 $ret = $parser->getTargetLanguage()->gender( $gender, $forms );
440 return $ret;
441 }
442
443 /**
444 * @param Parser $parser
445 * @param string $text
446 * @param string ...$forms What to output for each number (singular, dual, plural, etc.)
447 * @return string
448 */
449 public static function plural( $parser, $text = '', ...$forms ) {
450 $text = $parser->getTargetLanguage()->parseFormattedNumber( $text );
451 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
452 // @phan-suppress-next-line PhanTypeMismatchArgument Phan does not handle settype
453 return $parser->getTargetLanguage()->convertPlural( $text, $forms );
454 }
455
456 public static function formal( Parser $parser, string ...$forms ): string {
457 $index = $parser->getTargetLanguage()->getFormalityIndex();
458 return $forms[$index] ?? $forms[0];
459 }
460
461 /**
462 * @param Parser $parser
463 * @param string $text
464 * @return string
465 */
466 public static function bidi( $parser, $text = '' ) {
467 return $parser->getTargetLanguage()->embedBidi( $text );
468 }
469
470 /**
471 * Override the title of the page when viewed, provided we've been given a
472 * title which will normalise to the canonical title
473 *
474 * @param Parser $parser Parent parser
475 * @param string $text Desired title text
476 * @param string $uarg
477 * @return string
478 */
479 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
480 $restrictDisplayTitle = MediaWikiServices::getInstance()->getMainConfig()
481 ->get( MainConfigNames::RestrictDisplayTitle );
482
483 static $magicWords = null;
484 if ( $magicWords === null ) {
485 $magicWords = $parser->getMagicWordFactory()->newArray(
486 [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
487 }
488 $arg = $magicWords->matchStartToEnd( $uarg );
489
490 // parse a limited subset of wiki markup (just the single quote items)
491 $text = $parser->doQuotes( $text );
492
493 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
494 $text = $parser->killMarkers( $text );
495
496 // See T28547 for rationale for this processing.
497 // list of disallowed tags for DISPLAYTITLE
498 // these will be escaped even though they are allowed in normal wiki text
499 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
500 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
501
502 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
503 if ( $restrictDisplayTitle ) {
504 // This code is tested with the cases marked T28547 in
505 // parserTests.txt
506 $htmlTagsCallback = static function ( Attributes $attr ): Attributes {
507 $decoded = $attr->getValues();
508
509 if ( isset( $decoded['style'] ) ) {
510 // this is called later anyway, but we need it right now for the regexes below to be safe
511 // calling it twice doesn't hurt
512 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
513
514 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
515 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
516 }
517 }
518
519 return new PlainAttributes( $decoded );
520 };
521 } else {
522 $htmlTagsCallback = null;
523 }
524
525 // only requested titles that normalize to the actual title are allowed through
526 // if $wgRestrictDisplayTitle is true (it is by default)
527 // mimic the escaping process that occurs in OutputPage::setPageTitle
528 $text = Sanitizer::removeSomeTags( $text, [
529 'attrCallback' => $htmlTagsCallback,
530 'removeTags' => $bad,
531 ] );
532 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
533 // Decode entities in $text the same way that Title::newFromText does
534 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
535
536 if ( !$restrictDisplayTitle ||
537 ( $title instanceof Title
538 && !$title->hasFragment()
539 && $title->equals( $parser->getTitle() ) )
540 ) {
541 $old = $parser->getOutput()->getPageProperty( 'displaytitle' );
542 if ( $old === null || $arg !== 'displaytitle_noreplace' ) {
543 $parser->getOutput()->setDisplayTitle( $text );
544 }
545 if ( $old !== null && $old !== $text && !$arg ) {
546
547 $converter = $parser->getTargetLanguageConverter();
548 return '<span class="error">' .
549 $parser->msg( 'duplicate-displaytitle',
550 // Message should be parsed, but these params should only be escaped.
551 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
552 $converter->markNoConversion( wfEscapeWikiText( $filteredText ) )
553 )->text() .
554 '</span>';
555 } else {
556 return '';
557 }
558 } else {
559 $parser->getOutput()->addWarningMsg(
560 'restricted-displaytitle',
561 // Message should be parsed, but this param should only be escaped.
562 Message::plaintextParam( $filteredText )
563 );
564 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
565 }
566 }
567
568 /**
569 * Matches the given value against the value of given magic word
570 *
571 * @param MagicWordFactory $magicWordFactory A factory to get the word from, e.g., from
572 * $parser->getMagicWordFactory()
573 * @param string $magicword Magic word key
574 * @param string $value Value to match
575 * @return bool True on successful match
576 */
577 private static function matchAgainstMagicword(
578 MagicWordFactory $magicWordFactory, $magicword, $value
579 ) {
580 $value = trim( strval( $value ) );
581 if ( $value === '' ) {
582 return false;
583 }
584 $mwObject = $magicWordFactory->get( $magicword );
585 return $mwObject->matchStartToEnd( $value );
586 }
587
588 /**
589 * Formats a number according to a language.
590 *
591 * @param int|float $num
592 * @param ?string $raw
593 * @param Language $language
594 * @param MagicWordFactory|null $magicWordFactory To evaluate $raw
595 * @return string
596 */
597 public static function formatRaw(
598 $num, $raw, $language, ?MagicWordFactory $magicWordFactory = null
599 ) {
600 if ( $raw !== null && $raw !== '' ) {
601 if ( !$magicWordFactory ) {
602 $magicWordFactory = MediaWikiServices::getInstance()->getMagicWordFactory();
603 }
604 if ( self::matchAgainstMagicword( $magicWordFactory, 'rawsuffix', $raw ) ) {
605 return (string)$num;
606 }
607 }
608 return $language->formatNum( $num );
609 }
610
611 public static function numberofpages( $parser, $raw = null ) {
612 return self::formatRaw( SiteStats::pages(), $raw, $parser->getTargetLanguage() );
613 }
614
615 public static function numberofusers( $parser, $raw = null ) {
616 return self::formatRaw( SiteStats::users(), $raw, $parser->getTargetLanguage() );
617 }
618
619 public static function numberofactiveusers( $parser, $raw = null ) {
620 return self::formatRaw( SiteStats::activeUsers(), $raw, $parser->getTargetLanguage() );
621 }
622
623 public static function numberofarticles( $parser, $raw = null ) {
624 return self::formatRaw( SiteStats::articles(), $raw, $parser->getTargetLanguage() );
625 }
626
627 public static function numberoffiles( $parser, $raw = null ) {
628 return self::formatRaw( SiteStats::images(), $raw, $parser->getTargetLanguage() );
629 }
630
631 public static function numberofadmins( $parser, $raw = null ) {
632 return self::formatRaw(
633 SiteStats::numberingroup( 'sysop' ),
634 $raw,
635 $parser->getTargetLanguage()
636 );
637 }
638
639 public static function numberofedits( $parser, $raw = null ) {
640 return self::formatRaw( SiteStats::edits(), $raw, $parser->getTargetLanguage() );
641 }
642
643 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
644 return self::formatRaw(
645 SiteStats::pagesInNs( intval( $namespace ) ),
646 $raw,
647 $parser->getTargetLanguage()
648 );
649 }
650
651 public static function numberingroup( $parser, $name = '', $raw = null ) {
652 return self::formatRaw(
653 SiteStats::numberingroup( strtolower( $name ) ),
654 $raw,
655 $parser->getTargetLanguage()
656 );
657 }
658
659 /**
660 * Helper function for preprocessing an optional argument which represents
661 * a title.
662 * @param Parser $parser
663 * @param string|null $t if null, returns the Parser's Title
664 * for consistency with magic variable forms
665 * @return ?Title
666 */
667 private static function makeTitle( Parser $parser, ?string $t ) {
668 if ( $t === null ) {
669 // For consistency with magic variable forms
670 $title = $parser->getTitle();
671 } else {
672 $title = Title::newFromText( $t );
673 }
674 return $title;
675 }
676
677 /**
678 * Given a title, return the namespace name that would be given by the
679 * corresponding magic word
680 * @param Parser $parser
681 * @param string|null $title
682 * @return mixed|string
683 * @since 1.39
684 */
685 public static function namespace( $parser, $title = null ) {
686 $t = self::makeTitle( $parser, $title );
687 if ( $t === null ) {
688 return '';
689 }
690 return str_replace( '_', ' ', $t->getNsText() );
691 }
692
693 public static function namespacee( $parser, $title = null ) {
694 $t = self::makeTitle( $parser, $title );
695 if ( $t === null ) {
696 return '';
697 }
698 return wfUrlencode( $t->getNsText() );
699 }
700
701 public static function namespacenumber( $parser, $title = null ) {
702 $t = self::makeTitle( $parser, $title );
703 if ( $t === null ) {
704 return '';
705 }
706 return (string)$t->getNamespace();
707 }
708
709 public static function talkspace( $parser, $title = null ) {
710 $t = self::makeTitle( $parser, $title );
711 if ( $t === null || !$t->canHaveTalkPage() ) {
712 return '';
713 }
714 return str_replace( '_', ' ', $t->getTalkNsText() );
715 }
716
717 public static function talkspacee( $parser, $title = null ) {
718 $t = self::makeTitle( $parser, $title );
719 if ( $t === null || !$t->canHaveTalkPage() ) {
720 return '';
721 }
722 return wfUrlencode( $t->getTalkNsText() );
723 }
724
725 public static function subjectspace( $parser, $title = null ) {
726 $t = self::makeTitle( $parser, $title );
727 if ( $t === null ) {
728 return '';
729 }
730 return str_replace( '_', ' ', $t->getSubjectNsText() );
731 }
732
733 public static function subjectspacee( $parser, $title = null ) {
734 $t = self::makeTitle( $parser, $title );
735 if ( $t === null ) {
736 return '';
737 }
738 return wfUrlencode( $t->getSubjectNsText() );
739 }
740
741 /**
742 * Functions to get and normalize pagenames, corresponding to the magic words
743 * of the same names
744 * @param Parser $parser
745 * @param string|null $title
746 * @return string
747 */
748 public static function pagename( $parser, $title = null ) {
749 $t = self::makeTitle( $parser, $title );
750 if ( $t === null ) {
751 return '';
752 }
753 return wfEscapeWikiText( $t->getText() );
754 }
755
756 public static function pagenamee( $parser, $title = null ) {
757 $t = self::makeTitle( $parser, $title );
758 if ( $t === null ) {
759 return '';
760 }
761 return wfEscapeWikiText( $t->getPartialURL() );
762 }
763
764 public static function fullpagename( $parser, $title = null ) {
765 $t = self::makeTitle( $parser, $title );
766 if ( $t === null ) {
767 return '';
768 }
769 return wfEscapeWikiText( $t->getPrefixedText() );
770 }
771
772 public static function fullpagenamee( $parser, $title = null ) {
773 $t = self::makeTitle( $parser, $title );
774 if ( $t === null ) {
775 return '';
776 }
777 return wfEscapeWikiText( $t->getPrefixedURL() );
778 }
779
780 public static function subpagename( $parser, $title = null ) {
781 $t = self::makeTitle( $parser, $title );
782 if ( $t === null ) {
783 return '';
784 }
785 return wfEscapeWikiText( $t->getSubpageText() );
786 }
787
788 public static function subpagenamee( $parser, $title = null ) {
789 $t = self::makeTitle( $parser, $title );
790 if ( $t === null ) {
791 return '';
792 }
793 return wfEscapeWikiText( $t->getSubpageUrlForm() );
794 }
795
796 public static function rootpagename( $parser, $title = null ) {
797 $t = self::makeTitle( $parser, $title );
798 if ( $t === null ) {
799 return '';
800 }
801 return wfEscapeWikiText( $t->getRootText() );
802 }
803
804 public static function rootpagenamee( $parser, $title = null ) {
805 $t = self::makeTitle( $parser, $title );
806 if ( $t === null ) {
807 return '';
808 }
809 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
810 }
811
812 public static function basepagename( $parser, $title = null ) {
813 $t = self::makeTitle( $parser, $title );
814 if ( $t === null ) {
815 return '';
816 }
817 return wfEscapeWikiText( $t->getBaseText() );
818 }
819
820 public static function basepagenamee( $parser, $title = null ) {
821 $t = self::makeTitle( $parser, $title );
822 if ( $t === null ) {
823 return '';
824 }
825 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
826 }
827
828 public static function talkpagename( $parser, $title = null ) {
829 $t = self::makeTitle( $parser, $title );
830 if ( $t === null || !$t->canHaveTalkPage() ) {
831 return '';
832 }
833 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
834 }
835
836 public static function talkpagenamee( $parser, $title = null ) {
837 $t = self::makeTitle( $parser, $title );
838 if ( $t === null || !$t->canHaveTalkPage() ) {
839 return '';
840 }
841 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
842 }
843
844 public static function subjectpagename( $parser, $title = null ) {
845 $t = self::makeTitle( $parser, $title );
846 if ( $t === null ) {
847 return '';
848 }
849 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
850 }
851
852 public static function subjectpagenamee( $parser, $title = null ) {
853 $t = self::makeTitle( $parser, $title );
854 if ( $t === null ) {
855 return '';
856 }
857 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
858 }
859
860 /**
861 * Return the number of pages, files or subcats in the given category,
862 * or 0 if it's nonexistent. This is an expensive parser function and
863 * can't be called too many times per page.
864 * @param Parser $parser
865 * @param string $name
866 * @param string $arg1
867 * @param string $arg2
868 * @return string
869 */
870 public static function pagesincategory( $parser, $name = '', $arg1 = '', $arg2 = '' ) {
871 static $magicWords = null;
872 if ( $magicWords === null ) {
873 $magicWords = $parser->getMagicWordFactory()->newArray( [
874 'pagesincategory_all',
875 'pagesincategory_pages',
876 'pagesincategory_subcats',
877 'pagesincategory_files'
878 ] );
879 }
880 static $cache = [];
881
882 // split the given option to its variable
883 if ( self::matchAgainstMagicword( $parser->getMagicWordFactory(), 'rawsuffix', $arg1 ) ) {
884 // {{pagesincategory:|raw[|type]}}
885 $raw = $arg1;
886 $type = $magicWords->matchStartToEnd( $arg2 );
887 } else {
888 // {{pagesincategory:[|type[|raw]]}}
889 $type = $magicWords->matchStartToEnd( $arg1 );
890 $raw = $arg2;
891 }
892 if ( !$type ) { // backward compatibility
893 $type = 'pagesincategory_all';
894 }
895
896 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
897 if ( !$title ) { # invalid title
898 return self::formatRaw( 0, $raw, $parser->getTargetLanguage() );
899 }
900 $languageConverter = MediaWikiServices::getInstance()
901 ->getLanguageConverterFactory()
902 ->getLanguageConverter( $parser->getContentLanguage() );
903 $languageConverter->findVariantLink( $name, $title, true );
904
905 // Normalize name for cache
906 $name = $title->getDBkey();
907
908 if ( !isset( $cache[$name] ) ) {
909 $category = Category::newFromTitle( $title );
910
911 $allCount = $subcatCount = $fileCount = $pageCount = 0;
912 if ( $parser->incrementExpensiveFunctionCount() ) {
913 $allCount = $category->getMemberCount();
914 $subcatCount = $category->getSubcatCount();
915 $fileCount = $category->getFileCount();
916 $pageCount = $category->getPageCount( Category::COUNT_CONTENT_PAGES );
917 }
918 $cache[$name]['pagesincategory_all'] = $allCount;
919 $cache[$name]['pagesincategory_pages'] = $pageCount;
920 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
921 $cache[$name]['pagesincategory_files'] = $fileCount;
922 }
923
924 $count = $cache[$name][$type];
925 return self::formatRaw( $count, $raw, $parser->getTargetLanguage() );
926 }
927
928 /**
929 * Return the size of the given page, or 0 if it's nonexistent. This is an
930 * expensive parser function and can't be called too many times per page.
931 *
932 * @param Parser $parser
933 * @param string $page Name of page to check (Default: empty string)
934 * @param string|null $raw Should number be human readable with commas or just number
935 * @return string
936 */
937 public static function pagesize( $parser, $page = '', $raw = null ) {
938 $title = Title::newFromText( $page );
939
940 if ( !is_object( $title ) || $title->isExternal() ) {
941 return self::formatRaw( 0, $raw, $parser->getTargetLanguage() );
942 }
943
944 // fetch revision from cache/database and return the value
945 $rev = self::getCachedRevisionObject( $parser, $title, ParserOutputFlags::VARY_REVISION_SHA1 );
946 $length = $rev ? $rev->getSize() : 0;
947 if ( $length === null ) {
948 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
949 $length = 0;
950 }
951 return self::formatRaw( $length, $raw, $parser->getTargetLanguage() );
952 }
953
954 /**
955 * Returns the requested protection level for the current page. This
956 * is an expensive parser function and can't be called too many times
957 * per page, unless the protection levels/expiries for the given title
958 * have already been retrieved
959 *
960 * @param Parser $parser
961 * @param string $type
962 * @param string $title
963 *
964 * @return string
965 */
966 public static function protectionlevel( $parser, $type = '', $title = '' ) {
967 $titleObject = Title::newFromText( $title ) ?? $parser->getTitle();
968 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
969 if ( $restrictionStore->areRestrictionsLoaded( $titleObject ) || $parser->incrementExpensiveFunctionCount() ) {
970 $restrictions = $restrictionStore->getRestrictions( $titleObject, strtolower( $type ) );
971 # RestrictionStore::getRestrictions returns an array, its possible it may have
972 # multiple values in the future
973 return implode( ',', $restrictions );
974 }
975 return '';
976 }
977
978 /**
979 * Returns the requested protection expiry for the current page. This
980 * is an expensive parser function and can't be called too many times
981 * per page, unless the protection levels/expiries for the given title
982 * have already been retrieved
983 *
984 * @param Parser $parser
985 * @param string $type
986 * @param string $title
987 *
988 * @return string
989 */
990 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
991 $titleObject = Title::newFromText( $title ) ?? $parser->getTitle();
992 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
993 if ( $restrictionStore->areRestrictionsLoaded( $titleObject ) || $parser->incrementExpensiveFunctionCount() ) {
994 // getRestrictionExpiry() returns null on invalid type; trying to
995 // match protectionlevel() function that returns empty string instead
996 return $restrictionStore->getRestrictionExpiry( $titleObject, strtolower( $type ) ) ?? '';
997 }
998 return '';
999 }
1000
1001 /**
1002 * Gives language names.
1003 * @param Parser $parser
1004 * @param string $code Language code (of which to get name)
1005 * @param string $inLanguage Language code (in which to get name);
1006 * if missing or empty, the language's autonym will be returned.
1007 * @return string
1008 */
1009 public static function language( $parser, $code = '', $inLanguage = '' ) {
1010 if ( $code === '' ) {
1011 $code = $parser->getTargetLanguage()->getCode();
1012 }
1013 if ( $inLanguage === '' ) {
1014 $inLanguage = LanguageNameUtils::AUTONYMS;
1015 }
1016 $lang = MediaWikiServices::getInstance()
1017 ->getLanguageNameUtils()
1018 ->getLanguageName( $code, $inLanguage );
1019 return $lang !== '' ? $lang : LanguageCode::bcp47( $code );
1020 }
1021
1022 /**
1023 * Gives direction of script of a language given a language code.
1024 * @param Parser $parser
1025 * @param string $code a language code. If missing, the parser target
1026 * language will be used.
1027 * @param string $arg If this optional argument matches the
1028 * `language_option_bcp47` magic word, the language code will be treated
1029 * as a BCP-47 code.
1030 * @return string 'rtl' if the language code is recognized as
1031 * right-to-left, otherwise returns 'ltr'
1032 */
1033 public static function dir( Parser $parser, string $code = '', string $arg = '' ): string {
1034 static $magicWords = null;
1035 $languageFactory = MediaWikiServices::getInstance()->getLanguageFactory();
1036
1037 if ( $code === '' ) {
1038 $lang = $parser->getTargetLanguage();
1039 } else {
1040 if ( $arg !== '' ) {
1041 if ( $magicWords === null ) {
1042 $magicWords = $parser->getMagicWordFactory()->newArray( [ 'language_option_bcp47' ] );
1043 }
1044 if ( $magicWords->matchStartToEnd( $arg ) === 'language_option_bcp47' ) {
1045 // Prefer the BCP-47 interpretation of this code.
1046 $code = new Bcp47CodeValue( $code );
1047 }
1048 }
1049 try {
1050 $lang = $languageFactory->getLanguage( $code );
1051 } catch ( InvalidArgumentException $ex ) {
1052 $parser->addTrackingCategory( 'bad-language-code-category' );
1053 return 'ltr';
1054 }
1055 }
1056 return $lang->getDir();
1057 }
1058
1059 /**
1060 * Gives the BCP-47 code for a language given the mediawiki internal
1061 * language code.
1062 * @param Parser $parser
1063 * @param string $code a language code. If missing, the parser target
1064 * language will be used.
1065 * @return string the corresponding BCP-47 code
1066 */
1067 public static function bcp47( Parser $parser, string $code = '' ): string {
1068 if ( $code === '' ) {
1069 return $parser->getTargetLanguage()->toBcp47Code();
1070 } else {
1071 return LanguageCode::bcp47( $code );
1072 }
1073 }
1074
1075 /**
1076 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
1077 * @param Parser $parser
1078 * @param string $string
1079 * @param string $length
1080 * @param string $padding
1081 * @param int $direction
1082 * @return string
1083 */
1084 public static function pad(
1085 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
1086 ) {
1087 $padding = $parser->killMarkers( $padding );
1088 $lengthOfPadding = mb_strlen( $padding );
1089 if ( $lengthOfPadding == 0 ) {
1090 return $string;
1091 }
1092
1093 # The remaining length to add counts down to 0 as padding is added
1094 $length = min( (int)$length, 500 ) - mb_strlen( $string );
1095 if ( $length <= 0 ) {
1096 // Nothing to add
1097 return $string;
1098 }
1099
1100 # $finalPadding is just $padding repeated enough times so that
1101 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
1102 $finalPadding = '';
1103 while ( $length > 0 ) {
1104 # If $length < $lengthofPadding, truncate $padding so we get the
1105 # exact length desired.
1106 $finalPadding .= mb_substr( $padding, 0, $length );
1107 $length -= $lengthOfPadding;
1108 }
1109
1110 if ( $direction == STR_PAD_LEFT ) {
1111 return $finalPadding . $string;
1112 } else {
1113 return $string . $finalPadding;
1114 }
1115 }
1116
1117 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
1118 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
1119 }
1120
1121 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
1122 return self::pad( $parser, $string, $length, $padding );
1123 }
1124
1125 /**
1126 * @param Parser $parser
1127 * @param string $text
1128 * @return string
1129 */
1130 public static function anchorencode( $parser, $text ) {
1131 $text = $parser->killMarkers( $text );
1132 $section = substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
1133 $encodedSection = Sanitizer::safeEncodeAttribute( $section );
1134 // decode underscores to avoid breaking templates (T407131)
1135 return str_replace( '&#95;', '_', $encodedSection );
1136 }
1137
1138 public static function special( $parser, $text ) {
1139 [ $page, $subpage ] = MediaWikiServices::getInstance()->getSpecialPageFactory()->
1140 resolveAlias( $text );
1141 if ( $page ) {
1142 $title = SpecialPage::getTitleFor( $page, $subpage );
1143 return $title->getPrefixedText();
1144 } else {
1145 // unknown special page, just use the given text as its title, if at all possible
1146 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
1147 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
1148 }
1149 }
1150
1151 public static function speciale( $parser, $text ) {
1152 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
1153 }
1154
1155 /**
1156 * @param Parser $parser
1157 * @param string $text The sortkey to use
1158 * @param string $uarg Either "noreplace" or "noerror" (in en)
1159 * both suppress errors, and noreplace does nothing if
1160 * a default sortkey already exists.
1161 * @return string
1162 */
1163 public static function defaultsort( $parser, $text, $uarg = '' ) {
1164 static $magicWords = null;
1165 if ( $magicWords === null ) {
1166 $magicWords = $parser->getMagicWordFactory()->newArray(
1167 [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
1168 }
1169 $arg = $magicWords->matchStartToEnd( $uarg );
1170
1171 $text = trim( $text );
1172 if ( strlen( $text ) == 0 ) {
1173 return '';
1174 }
1175 $old = $parser->getOutput()->getPageProperty( 'defaultsort' );
1176 if ( $old === null || $arg !== 'defaultsort_noreplace' ) {
1177 $parser->getOutput()->setPageProperty( 'defaultsort', $text );
1178 }
1179
1180 if ( $old === null || $old == $text || $arg ) {
1181 return '';
1182 } else {
1183 $converter = $parser->getTargetLanguageConverter();
1184 return '<span class="error">' .
1185 $parser->msg( 'duplicate-defaultsort',
1186 // Message should be parsed, but these params should only be escaped.
1187 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
1188 $converter->markNoConversion( wfEscapeWikiText( $text ) )
1189 )->text() .
1190 '</span>';
1191 }
1192 }
1193
1194 /**
1195 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
1196 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
1197 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
1198 *
1199 * @param Parser $parser
1200 * @param string $name
1201 * @param string $argA
1202 * @param string $argB
1203 * @return array|string
1204 */
1205 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1206 $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile( $name );
1207
1208 if ( $argA == 'nowiki' ) {
1209 // {{filepath: | option [| size] }}
1210 $isNowiki = true;
1211 $parsedWidthParam = $parser->parseWidthParam( $argB );
1212 } else {
1213 // {{filepath: [| size [|option]] }}
1214 $parsedWidthParam = $parser->parseWidthParam( $argA );
1215 $isNowiki = ( $argB == 'nowiki' );
1216 }
1217
1218 if ( $file ) {
1219 $url = $file->getFullUrl();
1220
1221 // If a size is requested...
1222 if ( count( $parsedWidthParam ) ) {
1223 $mto = $file->transform( $parsedWidthParam );
1224 // ... and we can
1225 if ( $mto && !$mto->isError() ) {
1226 // ... change the URL to point to a thumbnail.
1227 $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
1228 $url = $urlUtils->expand( $mto->getUrl(), PROTO_RELATIVE ) ?? false;
1229 }
1230 }
1231 if ( $isNowiki ) {
1232 return [ $url, 'nowiki' => true ];
1233 }
1234 return $url;
1235 } else {
1236 return '';
1237 }
1238 }
1239
1240 /**
1241 * Parser function to extension tag adaptor
1242 * @param Parser $parser
1243 * @param PPFrame $frame
1244 * @param PPNode[] $args
1245 * @return string
1246 */
1247 public static function tagObj( $parser, $frame, $args ) {
1248 if ( !count( $args ) ) {
1249 return '';
1250 }
1251 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1252 $processNowiki = $parser->tagNeedsNowikiStrippedInTagPF( $tagName ) ? PPFrame::PROCESS_NOWIKI : 0;
1253
1254 if ( count( $args ) ) {
1255 $inner = $frame->expand( array_shift( $args ), $processNowiki );
1256 } else {
1257 $inner = null;
1258 }
1259
1260 $attributes = [];
1261 foreach ( $args as $arg ) {
1262 $bits = $arg->splitArg();
1263 if ( strval( $bits['index'] ) === '' ) {
1264 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1265 $value = trim( $frame->expand( $bits['value'] ) );
1266 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1267 $value = $m[1] ?? '';
1268 }
1269 $attributes[$name] = $value;
1270 }
1271 }
1272
1273 $stripList = $parser->getStripList();
1274 if ( !in_array( $tagName, $stripList ) ) {
1275 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1276 $attrText = '';
1277 foreach ( $attributes as $name => $value ) {
1278 $attrText .= ' ' . htmlspecialchars( $name ) .
1279 '="' . htmlspecialchars( $value, ENT_COMPAT ) . '"';
1280 }
1281 if ( $inner === null ) {
1282 return "<$tagName$attrText/>";
1283 }
1284 return "<$tagName$attrText>$inner</$tagName>";
1285 }
1286
1287 $params = [
1288 'name' => $tagName,
1289 'inner' => $inner,
1290 'attributes' => $attributes,
1291 'close' => "</$tagName>",
1292 ];
1293 return $parser->extensionSubstitution( $params, $frame );
1294 }
1295
1296 /**
1297 * Fetched the current revision of the given title and return this.
1298 * Will increment the expensive function count and
1299 * add a template link to get the value refreshed on changes.
1300 * For a given title, which is equal to the current parser title,
1301 * the RevisionRecord object from the parser is used, when that is the current one
1302 *
1303 * @param Parser $parser
1304 * @param Title $title
1305 * @param string $vary ParserOutput vary-* flag
1306 * @return RevisionRecord|null
1307 * @since 1.23
1308 */
1309 private static function getCachedRevisionObject( $parser, $title, $vary ) {
1310 if ( !$title ) {
1311 return null;
1312 }
1313
1314 $revisionRecord = null;
1315
1316 $isSelfReferential = $title->equals( $parser->getTitle() );
1317 if ( $isSelfReferential ) {
1318 // Revision is for the same title that is currently being parsed. Only use the last
1319 // saved revision, regardless of Parser::getRevisionId() or fake revision injection
1320 // callbacks against the current title.
1321
1322 // FIXME (T318278): the above is the intention, but doesn't
1323 // describe the actual current behavior of this code, since
1324 // ->isCurrent() for the last saved revision will return
1325 // false so we're going to fall through and end up calling
1326 // ->getCurrentRevisionRecordOfTitle().
1327 $parserRevisionRecord = $parser->getRevisionRecordObject();
1328 if ( $parserRevisionRecord && $parserRevisionRecord->isCurrent() ) {
1329 $revisionRecord = $parserRevisionRecord;
1330 }
1331 }
1332
1333 $parserOutput = $parser->getOutput();
1334 if ( !$revisionRecord ) {
1335 if (
1336 !$parser->isCurrentRevisionOfTitleCached( $title ) &&
1337 !$parser->incrementExpensiveFunctionCount()
1338 ) {
1339 return null; // not allowed
1340 }
1341 // Get the current revision, ignoring Parser::getRevisionId() being null/old
1342 $revisionRecord = $parser->fetchCurrentRevisionRecordOfTitle( $title );
1343 if ( !$revisionRecord ) {
1344 // Convert `false` error return to `null`
1345 $revisionRecord = null;
1346 }
1347 // Register dependency in templatelinks
1348 $parserOutput->addTemplate(
1349 $title,
1350 $revisionRecord ? $revisionRecord->getPageId() : 0,
1351 $revisionRecord ? $revisionRecord->getId() : 0
1352 );
1353 }
1354
1355 if ( $isSelfReferential ) {
1356 wfDebug( __METHOD__ . ": used current revision, setting $vary" );
1357 // Upon page save, the result of the parser function using this might change
1358 $parserOutput->setOutputFlag( $vary );
1359 if ( $vary === ParserOutputFlags::VARY_REVISION_SHA1 && $revisionRecord ) {
1360 try {
1361 $sha1 = $revisionRecord->getSha1();
1362 } catch ( RevisionAccessException $e ) {
1363 $sha1 = null;
1364 }
1365 $parserOutput->setRevisionUsedSha1Base36( $sha1 );
1366 }
1367 }
1368
1369 return $revisionRecord;
1370 }
1371
1372 /**
1373 * Get the pageid of a specified page
1374 * @param Parser $parser
1375 * @param string|null $title Title to get the pageid from
1376 * @return int|null|string
1377 * @since 1.23
1378 */
1379 public static function pageid( $parser, $title = null ) {
1380 $t = self::makeTitle( $parser, $title );
1381 if ( !$t ) {
1382 return '';
1383 } elseif ( !$t->canExist() || $t->isExternal() ) {
1384 return 0; // e.g. special page or interwiki link
1385 }
1386
1387 $parserOutput = $parser->getOutput();
1388
1389 if ( $t->equals( $parser->getTitle() ) ) {
1390 // Revision is for the same title that is currently being parsed.
1391 // Use the title from Parser in case a new page ID was injected into it.
1392 $parserOutput->setOutputFlag( ParserOutputFlags::VARY_PAGE_ID );
1393 $id = $parser->getTitle()->getArticleID();
1394 if ( $id ) {
1395 $parserOutput->setSpeculativePageIdUsed( $id );
1396 }
1397
1398 return $id;
1399 }
1400
1401 // Check the link cache for the title
1402 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1403 $pdbk = $t->getPrefixedDBkey();
1404 $id = $linkCache->getGoodLinkID( $pdbk );
1405 if ( $id != 0 || $linkCache->isBadLink( $pdbk ) ) {
1406 $parserOutput->addLink( $t, $id );
1407
1408 return $id;
1409 }
1410
1411 // We need to load it from the DB, so mark expensive
1412 if ( $parser->incrementExpensiveFunctionCount() ) {
1413 $id = $t->getArticleID();
1414 $parserOutput->addLink( $t, $id );
1415
1416 return $id;
1417 }
1418
1419 return null;
1420 }
1421
1422 /**
1423 * Get the id from the last revision of a specified page.
1424 * @param Parser $parser
1425 * @param string|null $title Title to get the id from
1426 * @return int|null|string
1427 * @since 1.23
1428 */
1429 public static function revisionid( $parser, $title = null ) {
1430 $t = self::makeTitle( $parser, $title );
1431 if ( $t === null || $t->isExternal() ) {
1432 return '';
1433 }
1434
1435 $services = MediaWikiServices::getInstance();
1436 if (
1437 $t->equals( $parser->getTitle() ) &&
1438 $services->getMainConfig()->get( MainConfigNames::MiserMode ) &&
1439 !$parser->getOptions()->getInterfaceMessage() &&
1440 // @TODO: disallow this word on all namespaces (T235957)
1441 $services->getNamespaceInfo()->isSubject( $t->getNamespace() )
1442 ) {
1443 // Use a stub result instead of the actual revision ID in order to avoid
1444 // double parses on page save but still allow preview detection (T137900)
1445 if ( $parser->getRevisionId() || $parser->getOptions()->getSpeculativeRevId() ) {
1446 return '-';
1447 } else {
1448 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_REVISION_EXISTS );
1449 return '';
1450 }
1451 }
1452 // Fetch revision from cache/database and return the value.
1453 // Inform the edit saving system that getting the canonical output
1454 // after revision insertion requires a parse that used that exact
1455 // revision ID.
1456 if ( $t->equals( $parser->getTitle() ) && $title === null ) {
1457 // special handling for no-arg case: use speculative rev id
1458 // for current page.
1459 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_REVISION_ID );
1460 $id = $parser->getRevisionId();
1461 if ( $id === 0 ) {
1462 $rev = $parser->getRevisionRecordObject();
1463 if ( $rev ) {
1464 $id = $rev->getId();
1465 }
1466 }
1467 if ( !$id ) {
1468 $id = $parser->getOptions()->getSpeculativeRevId();
1469 if ( $id ) {
1470 $parser->getOutput()->setSpeculativeRevIdUsed( $id );
1471 }
1472 }
1473 return (string)$id;
1474 }
1475 $rev = self::getCachedRevisionObject( $parser, $t, ParserOutputFlags::VARY_REVISION_ID );
1476 return $rev ? $rev->getId() : '';
1477 }
1478
1479 private static function getRevisionTimestampSubstring(
1480 Parser $parser,
1481 Title $title,
1482 int $start,
1483 int $len,
1484 int $mtts
1485 ): string {
1486 // If fetching the revision timestamp of the current page, substitute the
1487 // speculative timestamp to be used when this revision is saved. This
1488 // avoids having to invalidate the cache immediately by assuming the "last
1489 // saved revision" will in fact be this one.
1490 // Don't do this for interface messages (eg, edit notices) however; in that
1491 // case fall through and use the actual timestamp of the last saved revision.
1492 if ( $title->equals( $parser->getTitle() ) && !$parser->getOptions()->getInterfaceMessage() ) {
1493 // Get the timezone-adjusted timestamp to be used for this revision
1494 $resNow = substr( $parser->getRevisionTimestamp(), $start, $len );
1495 // Possibly set vary-revision if there is not yet an associated revision
1496 if ( !$parser->getRevisionRecordObject() ) {
1497 // Get the timezone-adjusted timestamp $mtts seconds in the future.
1498 // This future is relative to the current time and not that of the
1499 // parser options. The rendered timestamp can be compared to that
1500 // of the timestamp specified by the parser options.
1501 $resThen = substr(
1502 $parser->getContentLanguage()->userAdjust( wfTimestamp( TS_MW, time() + $mtts ), '' ),
1503 $start,
1504 $len
1505 );
1506
1507 if ( $resNow !== $resThen ) {
1508 // Inform the edit saving system that getting the canonical output after
1509 // revision insertion requires a parse that used an actual revision timestamp
1510 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_REVISION_TIMESTAMP );
1511 }
1512 }
1513
1514 return $resNow;
1515 } else {
1516 $rev = self::getCachedRevisionObject( $parser, $title, ParserOutputFlags::VARY_REVISION_TIMESTAMP );
1517 if ( !$rev ) {
1518 return '';
1519 }
1520 $resNow = substr(
1521 $parser->getContentLanguage()->userAdjust( $rev->getTimestamp(), '' ), $start, $len
1522 );
1523 return $resNow;
1524 }
1525 }
1526
1527 /**
1528 * Get the day from the last revision of a specified page.
1529 * @param Parser $parser
1530 * @param string|null $title Title to get the day from
1531 * @return string
1532 * @since 1.23
1533 */
1534 public static function revisionday( $parser, $title = null ) {
1535 $t = self::makeTitle( $parser, $title );
1536 if ( $t === null || $t->isExternal() ) {
1537 return '';
1538 }
1539 return strval( (int)self::getRevisionTimestampSubstring(
1540 $parser, $t, 6, 2, self::MAX_TTS
1541 ) );
1542 }
1543
1544 /**
1545 * Get the day with leading zeros from the last revision of a specified page.
1546 * @param Parser $parser
1547 * @param string|null $title Title to get the day from
1548 * @return string
1549 * @since 1.23
1550 */
1551 public static function revisionday2( $parser, $title = null ) {
1552 $t = self::makeTitle( $parser, $title );
1553 if ( $t === null || $t->isExternal() ) {
1554 return '';
1555 }
1556 return self::getRevisionTimestampSubstring(
1557 $parser, $t, 6, 2, self::MAX_TTS
1558 );
1559 }
1560
1561 /**
1562 * Get the month with leading zeros from the last revision of a specified page.
1563 * @param Parser $parser
1564 * @param string|null $title Title to get the month from
1565 * @return string
1566 * @since 1.23
1567 */
1568 public static function revisionmonth( $parser, $title = null ) {
1569 $t = self::makeTitle( $parser, $title );
1570 if ( $t === null || $t->isExternal() ) {
1571 return '';
1572 }
1573 return self::getRevisionTimestampSubstring(
1574 $parser, $t, 4, 2, self::MAX_TTS
1575 );
1576 }
1577
1578 /**
1579 * Get the month from the last revision of a specified page.
1580 * @param Parser $parser
1581 * @param string|null $title Title to get the month from
1582 * @return string
1583 * @since 1.23
1584 */
1585 public static function revisionmonth1( $parser, $title = null ) {
1586 $t = self::makeTitle( $parser, $title );
1587 if ( $t === null || $t->isExternal() ) {
1588 return '';
1589 }
1590 return strval( (int)self::getRevisionTimestampSubstring(
1591 $parser, $t, 4, 2, self::MAX_TTS
1592 ) );
1593 }
1594
1595 /**
1596 * Get the year from the last revision of a specified page.
1597 * @param Parser $parser
1598 * @param string|null $title Title to get the year from
1599 * @return string
1600 * @since 1.23
1601 */
1602 public static function revisionyear( $parser, $title = null ) {
1603 $t = self::makeTitle( $parser, $title );
1604 if ( $t === null || $t->isExternal() ) {
1605 return '';
1606 }
1607 return self::getRevisionTimestampSubstring(
1608 $parser, $t, 0, 4, self::MAX_TTS
1609 );
1610 }
1611
1612 /**
1613 * Get the timestamp from the last revision of a specified page.
1614 * @param Parser $parser
1615 * @param string|null $title Title to get the timestamp from
1616 * @return string
1617 * @since 1.23
1618 */
1619 public static function revisiontimestamp( $parser, $title = null ) {
1620 $t = self::makeTitle( $parser, $title );
1621 if ( $t === null || $t->isExternal() ) {
1622 return '';
1623 }
1624 return self::getRevisionTimestampSubstring(
1625 $parser, $t, 0, 14, self::MAX_TTS
1626 );
1627 }
1628
1629 /**
1630 * Get the user from the last revision of a specified page.
1631 * @param Parser $parser
1632 * @param string|null $title Title to get the user from
1633 * @return string
1634 * @since 1.23
1635 */
1636 public static function revisionuser( $parser, $title = null ) {
1637 $t = self::makeTitle( $parser, $title );
1638 if ( $t === null || $t->isExternal() ) {
1639 return '';
1640 }
1641 // VARY_USER informs the edit saving system that getting the canonical
1642 // output after revision insertion requires a parse that used the
1643 // actual user ID.
1644 if ( $t->equals( $parser->getTitle() ) ) {
1645 // Fall back to Parser's "revision user" for the current title
1646 $parser->getOutput()->setOutputFlag( ParserOutputFlags::VARY_USER );
1647 // Note that getRevisionUser() can return null; we need to
1648 // be sure to cast this to (an empty) string, since returning
1649 // null means "magic variable not handled".
1650 return (string)$parser->getRevisionUser();
1651 }
1652 // Fetch revision from cache/database and return the value.
1653 $rev = self::getCachedRevisionObject( $parser, $t, ParserOutputFlags::VARY_USER );
1654 $user = ( $rev !== null ) ? $rev->getUser() : null;
1655 return $user ? $user->getName() : '';
1656 }
1657
1658 /**
1659 * Returns the sources of any cascading protection acting on a specified page.
1660 * Pages will not return their own title unless they transclude themselves.
1661 * This is an expensive parser function and can't be called too many times per page,
1662 * unless cascading protection sources for the page have already been loaded.
1663 *
1664 * @param Parser $parser
1665 * @param ?string $title
1666 *
1667 * @return string
1668 * @since 1.23
1669 */
1670 public static function cascadingsources( $parser, $title = '' ) {
1671 $titleObject = Title::newFromText( $title ) ?? $parser->getTitle();
1672 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
1673 if ( $restrictionStore->areCascadeProtectionSourcesLoaded( $titleObject )
1674 || $parser->incrementExpensiveFunctionCount()
1675 ) {
1676 $names = [];
1677 $sources = $restrictionStore->getCascadeProtectionSources( $titleObject );
1678 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
1679 foreach ( $sources[0] as $sourcePageIdentity ) {
1680 $names[] = $titleFormatter->getPrefixedText( $sourcePageIdentity );
1681 }
1682 return implode( '|', $names );
1683 }
1684 return '';
1685 }
1686 }
1687
1688 /** @deprecated class alias since 1.43 */
1689 class_alias( CoreParserFunctions::class, 'CoreParserFunctions' );