Merge "Don't fallback from uk to ru"
[lhc/web/wiklou.git] / includes / parser / CoreParserFunctions.php
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 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Various core parser functions, registered in Parser::firstCallInit()
27 * @ingroup Parser
28 */
29 class CoreParserFunctions {
30 /**
31 * @param Parser $parser
32 * @return void
33 */
34 public static function register( $parser ) {
35 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
36
37 # Syntax for arguments (see Parser::setFunctionHook):
38 # "name for lookup in localized magic words array",
39 # function callback,
40 # optional Parser::SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}}
41 # instead of {{#int:...}})
42 $noHashFunctions = [
43 'ns', 'nse', 'urlencode', 'lcfirst', 'ucfirst', 'lc', 'uc',
44 'localurl', 'localurle', 'fullurl', 'fullurle', 'canonicalurl',
45 'canonicalurle', 'formatnum', 'grammar', 'gender', 'plural', 'bidi',
46 'numberofpages', 'numberofusers', 'numberofactiveusers',
47 'numberofarticles', 'numberoffiles', 'numberofadmins',
48 'numberingroup', 'numberofedits', 'language',
49 'padleft', 'padright', 'anchorencode', 'defaultsort', 'filepath',
50 'pagesincategory', 'pagesize', 'protectionlevel', 'protectionexpiry',
51 'namespacee', 'namespacenumber', 'talkspace', 'talkspacee',
52 'subjectspace', 'subjectspacee', 'pagename', 'pagenamee',
53 'fullpagename', 'fullpagenamee', 'rootpagename', 'rootpagenamee',
54 'basepagename', 'basepagenamee', 'subpagename', 'subpagenamee',
55 'talkpagename', 'talkpagenamee', 'subjectpagename',
56 'subjectpagenamee', 'pageid', 'revisionid', 'revisionday',
57 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear',
58 'revisiontimestamp', 'revisionuser', 'cascadingsources',
59 ];
60 foreach ( $noHashFunctions as $func ) {
61 $parser->setFunctionHook( $func, [ __CLASS__, $func ], Parser::SFH_NO_HASH );
62 }
63
64 $parser->setFunctionHook(
65 'namespace',
66 [ __CLASS__, 'mwnamespace' ],
67 Parser::SFH_NO_HASH
68 );
69 $parser->setFunctionHook( 'int', [ __CLASS__, 'intFunction' ], Parser::SFH_NO_HASH );
70 $parser->setFunctionHook( 'special', [ __CLASS__, 'special' ] );
71 $parser->setFunctionHook( 'speciale', [ __CLASS__, 'speciale' ] );
72 $parser->setFunctionHook( 'tag', [ __CLASS__, 'tagObj' ], Parser::SFH_OBJECT_ARGS );
73 $parser->setFunctionHook( 'formatdate', [ __CLASS__, 'formatDate' ] );
74
75 if ( $wgAllowDisplayTitle ) {
76 $parser->setFunctionHook(
77 'displaytitle',
78 [ __CLASS__, 'displaytitle' ],
79 Parser::SFH_NO_HASH
80 );
81 }
82 if ( $wgAllowSlowParserFunctions ) {
83 $parser->setFunctionHook(
84 'pagesinnamespace',
85 [ __CLASS__, 'pagesinnamespace' ],
86 Parser::SFH_NO_HASH
87 );
88 }
89 }
90
91 /**
92 * @param Parser $parser
93 * @param string $part1
94 * @return array
95 */
96 public static function intFunction( $parser, $part1 = '' /*, ... */ ) {
97 if ( strval( $part1 ) !== '' ) {
98 $args = array_slice( func_get_args(), 2 );
99 $message = wfMessage( $part1, $args )
100 ->inLanguage( $parser->getOptions()->getUserLangObj() );
101 if ( !$message->exists() ) {
102 // When message does not exists, the message name is surrounded by angle
103 // and can result in a tag, therefore escape the angles
104 return $message->escaped();
105 }
106 return [ $message->plain(), 'noparse' => false ];
107 } else {
108 return [ 'found' => false ];
109 }
110 }
111
112 /**
113 * @param Parser $parser
114 * @param string $date
115 * @param string $defaultPref
116 *
117 * @return string
118 */
119 public static function formatDate( $parser, $date, $defaultPref = null ) {
120 $lang = $parser->getFunctionLang();
121 $df = DateFormatter::getInstance( $lang );
122
123 $date = trim( $date );
124
125 $pref = $parser->getOptions()->getDateFormat();
126
127 // Specify a different default date format other than the normal default
128 // if the user has 'default' for their setting
129 if ( $pref == 'default' && $defaultPref ) {
130 $pref = $defaultPref;
131 }
132
133 $date = $df->reformat( $pref, $date, [ 'match-whole' ] );
134 return $date;
135 }
136
137 public static function ns( $parser, $part1 = '' ) {
138 global $wgContLang;
139 if ( intval( $part1 ) || $part1 == "0" ) {
140 $index = intval( $part1 );
141 } else {
142 $index = $wgContLang->getNsIndex( str_replace( ' ', '_', $part1 ) );
143 }
144 if ( $index !== false ) {
145 return $wgContLang->getFormattedNsText( $index );
146 } else {
147 return [ 'found' => false ];
148 }
149 }
150
151 public static function nse( $parser, $part1 = '' ) {
152 $ret = self::ns( $parser, $part1 );
153 if ( is_string( $ret ) ) {
154 $ret = wfUrlencode( str_replace( ' ', '_', $ret ) );
155 }
156 return $ret;
157 }
158
159 /**
160 * urlencodes a string according to one of three patterns: (bug 22474)
161 *
162 * By default (for HTTP "query" strings), spaces are encoded as '+'.
163 * Or to encode a value for the HTTP "path", spaces are encoded as '%20'.
164 * For links to "wiki"s, or similar software, spaces are encoded as '_',
165 *
166 * @param Parser $parser
167 * @param string $s The text to encode.
168 * @param string $arg (optional): The type of encoding.
169 * @return string
170 */
171 public static function urlencode( $parser, $s = '', $arg = null ) {
172 static $magicWords = null;
173 if ( is_null( $magicWords ) ) {
174 $magicWords = new MagicWordArray( [ 'url_path', 'url_query', 'url_wiki' ] );
175 }
176 switch ( $magicWords->matchStartToEnd( $arg ) ) {
177
178 // Encode as though it's a wiki page, '_' for ' '.
179 case 'url_wiki':
180 $func = 'wfUrlencode';
181 $s = str_replace( ' ', '_', $s );
182 break;
183
184 // Encode for an HTTP Path, '%20' for ' '.
185 case 'url_path':
186 $func = 'rawurlencode';
187 break;
188
189 // Encode for HTTP query, '+' for ' '.
190 case 'url_query':
191 default:
192 $func = 'urlencode';
193 }
194 // See T105242, where the choice to kill markers and various
195 // other options were discussed.
196 return $func( $parser->killMarkers( $s ) );
197 }
198
199 public static function lcfirst( $parser, $s = '' ) {
200 global $wgContLang;
201 return $wgContLang->lcfirst( $s );
202 }
203
204 public static function ucfirst( $parser, $s = '' ) {
205 global $wgContLang;
206 return $wgContLang->ucfirst( $s );
207 }
208
209 /**
210 * @param Parser $parser
211 * @param string $s
212 * @return string
213 */
214 public static function lc( $parser, $s = '' ) {
215 global $wgContLang;
216 return $parser->markerSkipCallback( $s, [ $wgContLang, 'lc' ] );
217 }
218
219 /**
220 * @param Parser $parser
221 * @param string $s
222 * @return string
223 */
224 public static function uc( $parser, $s = '' ) {
225 global $wgContLang;
226 return $parser->markerSkipCallback( $s, [ $wgContLang, 'uc' ] );
227 }
228
229 public static function localurl( $parser, $s = '', $arg = null ) {
230 return self::urlFunction( 'getLocalURL', $s, $arg );
231 }
232
233 public static function localurle( $parser, $s = '', $arg = null ) {
234 $temp = self::urlFunction( 'getLocalURL', $s, $arg );
235 if ( !is_string( $temp ) ) {
236 return $temp;
237 } else {
238 return htmlspecialchars( $temp );
239 }
240 }
241
242 public static function fullurl( $parser, $s = '', $arg = null ) {
243 return self::urlFunction( 'getFullURL', $s, $arg );
244 }
245
246 public static function fullurle( $parser, $s = '', $arg = null ) {
247 $temp = self::urlFunction( 'getFullURL', $s, $arg );
248 if ( !is_string( $temp ) ) {
249 return $temp;
250 } else {
251 return htmlspecialchars( $temp );
252 }
253 }
254
255 public static function canonicalurl( $parser, $s = '', $arg = null ) {
256 return self::urlFunction( 'getCanonicalURL', $s, $arg );
257 }
258
259 public static function canonicalurle( $parser, $s = '', $arg = null ) {
260 $temp = self::urlFunction( 'getCanonicalURL', $s, $arg );
261 if ( !is_string( $temp ) ) {
262 return $temp;
263 } else {
264 return htmlspecialchars( $temp );
265 }
266 }
267
268 public static function urlFunction( $func, $s = '', $arg = null ) {
269 $title = Title::newFromText( $s );
270 # Due to order of execution of a lot of bits, the values might be encoded
271 # before arriving here; if that's true, then the title can't be created
272 # and the variable will fail. If we can't get a decent title from the first
273 # attempt, url-decode and try for a second.
274 if ( is_null( $title ) ) {
275 $title = Title::newFromURL( urldecode( $s ) );
276 }
277 if ( !is_null( $title ) ) {
278 # Convert NS_MEDIA -> NS_FILE
279 if ( $title->getNamespace() == NS_MEDIA ) {
280 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
281 }
282 if ( !is_null( $arg ) ) {
283 $text = $title->$func( $arg );
284 } else {
285 $text = $title->$func();
286 }
287 return $text;
288 } else {
289 return [ 'found' => false ];
290 }
291 }
292
293 /**
294 * @param Parser $parser
295 * @param string $num
296 * @param string $arg
297 * @return string
298 */
299 public static function formatnum( $parser, $num = '', $arg = null ) {
300 if ( self::matchAgainstMagicword( 'rawsuffix', $arg ) ) {
301 $func = [ $parser->getFunctionLang(), 'parseFormattedNumber' ];
302 } elseif ( self::matchAgainstMagicword( 'nocommafysuffix', $arg ) ) {
303 $func = [ $parser->getFunctionLang(), 'formatNumNoSeparators' ];
304 } else {
305 $func = [ $parser->getFunctionLang(), 'formatNum' ];
306 }
307 return $parser->markerSkipCallback( $num, $func );
308 }
309
310 /**
311 * @param Parser $parser
312 * @param string $case
313 * @param string $word
314 * @return string
315 */
316 public static function grammar( $parser, $case = '', $word = '' ) {
317 $word = $parser->killMarkers( $word );
318 return $parser->getFunctionLang()->convertGrammar( $word, $case );
319 }
320
321 /**
322 * @param Parser $parser
323 * @param string $username
324 * @return string
325 */
326 public static function gender( $parser, $username ) {
327 $forms = array_slice( func_get_args(), 2 );
328
329 // Some shortcuts to avoid loading user data unnecessarily
330 if ( count( $forms ) === 0 ) {
331 return '';
332 } elseif ( count( $forms ) === 1 ) {
333 return $forms[0];
334 }
335
336 $username = trim( $username );
337
338 // default
339 $gender = User::getDefaultOption( 'gender' );
340
341 // allow prefix.
342 $title = Title::newFromText( $username );
343
344 if ( $title && $title->getNamespace() == NS_USER ) {
345 $username = $title->getText();
346 }
347
348 // check parameter, or use the ParserOptions if in interface message
349 $user = User::newFromName( $username );
350 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
351 if ( $user ) {
352 $gender = $genderCache->getGenderOf( $user, __METHOD__ );
353 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
354 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
355 }
356 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
357 return $ret;
358 }
359
360 /**
361 * @param Parser $parser
362 * @param string $text
363 * @return string
364 */
365 public static function plural( $parser, $text = '' ) {
366 $forms = array_slice( func_get_args(), 2 );
367 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
368 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
369 return $parser->getFunctionLang()->convertPlural( $text, $forms );
370 }
371
372 /**
373 * @param Parser $parser
374 * @param string $text
375 * @return string
376 */
377 public static function bidi( $parser, $text = '' ) {
378 return $parser->getFunctionLang()->embedBidi( $text );
379 }
380
381 /**
382 * Override the title of the page when viewed, provided we've been given a
383 * title which will normalise to the canonical title
384 *
385 * @param Parser $parser Parent parser
386 * @param string $text Desired title text
387 * @param string $uarg
388 * @return string
389 */
390 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
391 global $wgRestrictDisplayTitle;
392
393 static $magicWords = null;
394 if ( is_null( $magicWords ) ) {
395 $magicWords = new MagicWordArray( [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
396 }
397 $arg = $magicWords->matchStartToEnd( $uarg );
398
399 // parse a limited subset of wiki markup (just the single quote items)
400 $text = $parser->doQuotes( $text );
401
402 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
403 $text = $parser->killMarkers( $text );
404
405 // list of disallowed tags for DISPLAYTITLE
406 // these will be escaped even though they are allowed in normal wiki text
407 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
408 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
409
410 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
411 if ( $wgRestrictDisplayTitle ) {
412 $htmlTagsCallback = function ( &$params ) {
413 $decoded = Sanitizer::decodeTagAttributes( $params );
414
415 if ( isset( $decoded['style'] ) ) {
416 // this is called later anyway, but we need it right now for the regexes below to be safe
417 // calling it twice doesn't hurt
418 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
419
420 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
421 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
422 }
423 }
424
425 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
426 };
427 } else {
428 $htmlTagsCallback = null;
429 }
430
431 // only requested titles that normalize to the actual title are allowed through
432 // if $wgRestrictDisplayTitle is true (it is by default)
433 // mimic the escaping process that occurs in OutputPage::setPageTitle
434 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
435 $text,
436 $htmlTagsCallback,
437 [],
438 [],
439 $bad
440 ) );
441 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
442
443 if ( !$wgRestrictDisplayTitle ||
444 ( $title instanceof Title
445 && !$title->hasFragment()
446 && $title->equals( $parser->mTitle ) )
447 ) {
448 $old = $parser->mOutput->getProperty( 'displaytitle' );
449 if ( $old === false || $arg !== 'displaytitle_noreplace' ) {
450 $parser->mOutput->setDisplayTitle( $text );
451 }
452 if ( $old !== false && $old !== $text && !$arg ) {
453 $converter = $parser->getConverterLanguage()->getConverter();
454 return '<span class="error">' .
455 wfMessage( 'duplicate-displaytitle',
456 // Message should be parsed, but these params should only be escaped.
457 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
458 $converter->markNoConversion( wfEscapeWikiText( $text ) )
459 )->inContentLanguage()->text() .
460 '</span>';
461 } else {
462 return '';
463 }
464 } else {
465 $converter = $parser->getConverterLanguage()->getConverter();
466 $parser->getOutput()->addWarning(
467 wfMessage( 'restricted-displaytitle',
468 // Message should be parsed, but this param should only be escaped.
469 $converter->markNoConversion( wfEscapeWikiText( $text ) )
470 )->text()
471 );
472 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
473 }
474 }
475
476 /**
477 * Matches the given value against the value of given magic word
478 *
479 * @param string $magicword Magic word key
480 * @param string $value Value to match
481 * @return bool True on successful match
482 */
483 private static function matchAgainstMagicword( $magicword, $value ) {
484 $value = trim( strval( $value ) );
485 if ( $value === '' ) {
486 return false;
487 }
488 $mwObject = MagicWord::get( $magicword );
489 return $mwObject->matchStartToEnd( $value );
490 }
491
492 public static function formatRaw( $num, $raw ) {
493 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
494 return $num;
495 } else {
496 global $wgContLang;
497 return $wgContLang->formatNum( $num );
498 }
499 }
500 public static function numberofpages( $parser, $raw = null ) {
501 return self::formatRaw( SiteStats::pages(), $raw );
502 }
503 public static function numberofusers( $parser, $raw = null ) {
504 return self::formatRaw( SiteStats::users(), $raw );
505 }
506 public static function numberofactiveusers( $parser, $raw = null ) {
507 return self::formatRaw( SiteStats::activeUsers(), $raw );
508 }
509 public static function numberofarticles( $parser, $raw = null ) {
510 return self::formatRaw( SiteStats::articles(), $raw );
511 }
512 public static function numberoffiles( $parser, $raw = null ) {
513 return self::formatRaw( SiteStats::images(), $raw );
514 }
515 public static function numberofadmins( $parser, $raw = null ) {
516 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
517 }
518 public static function numberofedits( $parser, $raw = null ) {
519 return self::formatRaw( SiteStats::edits(), $raw );
520 }
521 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
522 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
523 }
524 public static function numberingroup( $parser, $name = '', $raw = null ) {
525 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
526 }
527
528 /**
529 * Given a title, return the namespace name that would be given by the
530 * corresponding magic word
531 * Note: function name changed to "mwnamespace" rather than "namespace"
532 * to not break PHP 5.3
533 * @param Parser $parser
534 * @param string $title
535 * @return mixed|string
536 */
537 public static function mwnamespace( $parser, $title = null ) {
538 $t = Title::newFromText( $title );
539 if ( is_null( $t ) ) {
540 return '';
541 }
542 return str_replace( '_', ' ', $t->getNsText() );
543 }
544 public static function namespacee( $parser, $title = null ) {
545 $t = Title::newFromText( $title );
546 if ( is_null( $t ) ) {
547 return '';
548 }
549 return wfUrlencode( $t->getNsText() );
550 }
551 public static function namespacenumber( $parser, $title = null ) {
552 $t = Title::newFromText( $title );
553 if ( is_null( $t ) ) {
554 return '';
555 }
556 return $t->getNamespace();
557 }
558 public static function talkspace( $parser, $title = null ) {
559 $t = Title::newFromText( $title );
560 if ( is_null( $t ) || !$t->canTalk() ) {
561 return '';
562 }
563 return str_replace( '_', ' ', $t->getTalkNsText() );
564 }
565 public static function talkspacee( $parser, $title = null ) {
566 $t = Title::newFromText( $title );
567 if ( is_null( $t ) || !$t->canTalk() ) {
568 return '';
569 }
570 return wfUrlencode( $t->getTalkNsText() );
571 }
572 public static function subjectspace( $parser, $title = null ) {
573 $t = Title::newFromText( $title );
574 if ( is_null( $t ) ) {
575 return '';
576 }
577 return str_replace( '_', ' ', $t->getSubjectNsText() );
578 }
579 public static function subjectspacee( $parser, $title = null ) {
580 $t = Title::newFromText( $title );
581 if ( is_null( $t ) ) {
582 return '';
583 }
584 return wfUrlencode( $t->getSubjectNsText() );
585 }
586
587 /**
588 * Functions to get and normalize pagenames, corresponding to the magic words
589 * of the same names
590 * @param Parser $parser
591 * @param string $title
592 * @return string
593 */
594 public static function pagename( $parser, $title = null ) {
595 $t = Title::newFromText( $title );
596 if ( is_null( $t ) ) {
597 return '';
598 }
599 return wfEscapeWikiText( $t->getText() );
600 }
601 public static function pagenamee( $parser, $title = null ) {
602 $t = Title::newFromText( $title );
603 if ( is_null( $t ) ) {
604 return '';
605 }
606 return wfEscapeWikiText( $t->getPartialURL() );
607 }
608 public static function fullpagename( $parser, $title = null ) {
609 $t = Title::newFromText( $title );
610 if ( is_null( $t ) || !$t->canTalk() ) {
611 return '';
612 }
613 return wfEscapeWikiText( $t->getPrefixedText() );
614 }
615 public static function fullpagenamee( $parser, $title = null ) {
616 $t = Title::newFromText( $title );
617 if ( is_null( $t ) || !$t->canTalk() ) {
618 return '';
619 }
620 return wfEscapeWikiText( $t->getPrefixedURL() );
621 }
622 public static function subpagename( $parser, $title = null ) {
623 $t = Title::newFromText( $title );
624 if ( is_null( $t ) ) {
625 return '';
626 }
627 return wfEscapeWikiText( $t->getSubpageText() );
628 }
629 public static function subpagenamee( $parser, $title = null ) {
630 $t = Title::newFromText( $title );
631 if ( is_null( $t ) ) {
632 return '';
633 }
634 return wfEscapeWikiText( $t->getSubpageUrlForm() );
635 }
636 public static function rootpagename( $parser, $title = null ) {
637 $t = Title::newFromText( $title );
638 if ( is_null( $t ) ) {
639 return '';
640 }
641 return wfEscapeWikiText( $t->getRootText() );
642 }
643 public static function rootpagenamee( $parser, $title = null ) {
644 $t = Title::newFromText( $title );
645 if ( is_null( $t ) ) {
646 return '';
647 }
648 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
649 }
650 public static function basepagename( $parser, $title = null ) {
651 $t = Title::newFromText( $title );
652 if ( is_null( $t ) ) {
653 return '';
654 }
655 return wfEscapeWikiText( $t->getBaseText() );
656 }
657 public static function basepagenamee( $parser, $title = null ) {
658 $t = Title::newFromText( $title );
659 if ( is_null( $t ) ) {
660 return '';
661 }
662 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
663 }
664 public static function talkpagename( $parser, $title = null ) {
665 $t = Title::newFromText( $title );
666 if ( is_null( $t ) || !$t->canTalk() ) {
667 return '';
668 }
669 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
670 }
671 public static function talkpagenamee( $parser, $title = null ) {
672 $t = Title::newFromText( $title );
673 if ( is_null( $t ) || !$t->canTalk() ) {
674 return '';
675 }
676 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
677 }
678 public static function subjectpagename( $parser, $title = null ) {
679 $t = Title::newFromText( $title );
680 if ( is_null( $t ) ) {
681 return '';
682 }
683 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
684 }
685 public static function subjectpagenamee( $parser, $title = null ) {
686 $t = Title::newFromText( $title );
687 if ( is_null( $t ) ) {
688 return '';
689 }
690 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
691 }
692
693 /**
694 * Return the number of pages, files or subcats in the given category,
695 * or 0 if it's nonexistent. This is an expensive parser function and
696 * can't be called too many times per page.
697 * @param Parser $parser
698 * @param string $name
699 * @param string $arg1
700 * @param string $arg2
701 * @return string
702 */
703 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
704 global $wgContLang;
705 static $magicWords = null;
706 if ( is_null( $magicWords ) ) {
707 $magicWords = new MagicWordArray( [
708 'pagesincategory_all',
709 'pagesincategory_pages',
710 'pagesincategory_subcats',
711 'pagesincategory_files'
712 ] );
713 }
714 static $cache = [];
715
716 // split the given option to its variable
717 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
718 // {{pagesincategory:|raw[|type]}}
719 $raw = $arg1;
720 $type = $magicWords->matchStartToEnd( $arg2 );
721 } else {
722 // {{pagesincategory:[|type[|raw]]}}
723 $type = $magicWords->matchStartToEnd( $arg1 );
724 $raw = $arg2;
725 }
726 if ( !$type ) { // backward compatibility
727 $type = 'pagesincategory_all';
728 }
729
730 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
731 if ( !$title ) { # invalid title
732 return self::formatRaw( 0, $raw );
733 }
734 $wgContLang->findVariantLink( $name, $title, true );
735
736 // Normalize name for cache
737 $name = $title->getDBkey();
738
739 if ( !isset( $cache[$name] ) ) {
740 $category = Category::newFromTitle( $title );
741
742 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
743 if ( $parser->incrementExpensiveFunctionCount() ) {
744 // $allCount is the total number of cat members,
745 // not the count of how many members are normal pages.
746 $allCount = (int)$category->getPageCount();
747 $subcatCount = (int)$category->getSubcatCount();
748 $fileCount = (int)$category->getFileCount();
749 $pagesCount = $allCount - $subcatCount - $fileCount;
750 }
751 $cache[$name]['pagesincategory_all'] = $allCount;
752 $cache[$name]['pagesincategory_pages'] = $pagesCount;
753 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
754 $cache[$name]['pagesincategory_files'] = $fileCount;
755 }
756
757 $count = $cache[$name][$type];
758 return self::formatRaw( $count, $raw );
759 }
760
761 /**
762 * Return the size of the given page, or 0 if it's nonexistent. This is an
763 * expensive parser function and can't be called too many times per page.
764 *
765 * @param Parser $parser
766 * @param string $page Name of page to check (Default: empty string)
767 * @param string $raw Should number be human readable with commas or just number
768 * @return string
769 */
770 public static function pagesize( $parser, $page = '', $raw = null ) {
771 $title = Title::newFromText( $page );
772
773 if ( !is_object( $title ) ) {
774 return self::formatRaw( 0, $raw );
775 }
776
777 // fetch revision from cache/database and return the value
778 $rev = self::getCachedRevisionObject( $parser, $title );
779 $length = $rev ? $rev->getSize() : 0;
780 if ( $length === null ) {
781 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
782 $length = 0;
783 }
784 return self::formatRaw( $length, $raw );
785 }
786
787 /**
788 * Returns the requested protection level for the current page. This
789 * is an expensive parser function and can't be called too many times
790 * per page, unless the protection levels/expiries for the given title
791 * have already been retrieved
792 *
793 * @param Parser $parser
794 * @param string $type
795 * @param string $title
796 *
797 * @return string
798 */
799 public static function protectionlevel( $parser, $type = '', $title = '' ) {
800 $titleObject = Title::newFromText( $title );
801 if ( !( $titleObject instanceof Title ) ) {
802 $titleObject = $parser->mTitle;
803 }
804 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
805 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
806 # Title::getRestrictions returns an array, its possible it may have
807 # multiple values in the future
808 return implode( $restrictions, ',' );
809 }
810 return '';
811 }
812
813 /**
814 * Returns the requested protection expiry for the current page. This
815 * is an expensive parser function and can't be called too many times
816 * per page, unless the protection levels/expiries for the given title
817 * have already been retrieved
818 *
819 * @param Parser $parser
820 * @param string $type
821 * @param string $title
822 *
823 * @return string
824 */
825 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
826 $titleObject = Title::newFromText( $title );
827 if ( !( $titleObject instanceof Title ) ) {
828 $titleObject = $parser->mTitle;
829 }
830 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
831 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
832 // getRestrictionExpiry() returns false on invalid type; trying to
833 // match protectionlevel() function that returns empty string instead
834 if ( $expiry === false ) {
835 $expiry = '';
836 }
837 return $expiry;
838 }
839 return '';
840 }
841
842 /**
843 * Gives language names.
844 * @param Parser $parser
845 * @param string $code Language code (of which to get name)
846 * @param string $inLanguage Language code (in which to get name)
847 * @return string
848 */
849 public static function language( $parser, $code = '', $inLanguage = '' ) {
850 $code = strtolower( $code );
851 $inLanguage = strtolower( $inLanguage );
852 $lang = Language::fetchLanguageName( $code, $inLanguage );
853 return $lang !== '' ? $lang : wfBCP47( $code );
854 }
855
856 /**
857 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
858 * @param Parser $parser
859 * @param string $string
860 * @param int $length
861 * @param string $padding
862 * @param int $direction
863 * @return string
864 */
865 public static function pad(
866 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
867 ) {
868 $padding = $parser->killMarkers( $padding );
869 $lengthOfPadding = mb_strlen( $padding );
870 if ( $lengthOfPadding == 0 ) {
871 return $string;
872 }
873
874 # The remaining length to add counts down to 0 as padding is added
875 $length = min( $length, 500 ) - mb_strlen( $string );
876 # $finalPadding is just $padding repeated enough times so that
877 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
878 $finalPadding = '';
879 while ( $length > 0 ) {
880 # If $length < $lengthofPadding, truncate $padding so we get the
881 # exact length desired.
882 $finalPadding .= mb_substr( $padding, 0, $length );
883 $length -= $lengthOfPadding;
884 }
885
886 if ( $direction == STR_PAD_LEFT ) {
887 return $finalPadding . $string;
888 } else {
889 return $string . $finalPadding;
890 }
891 }
892
893 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
894 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
895 }
896
897 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
898 return self::pad( $parser, $string, $length, $padding );
899 }
900
901 /**
902 * @param Parser $parser
903 * @param string $text
904 * @return string
905 */
906 public static function anchorencode( $parser, $text ) {
907 $text = $parser->killMarkers( $text );
908 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
909 }
910
911 public static function special( $parser, $text ) {
912 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
913 if ( $page ) {
914 $title = SpecialPage::getTitleFor( $page, $subpage );
915 return $title->getPrefixedText();
916 } else {
917 // unknown special page, just use the given text as its title, if at all possible
918 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
919 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
920 }
921 }
922
923 public static function speciale( $parser, $text ) {
924 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
925 }
926
927 /**
928 * @param Parser $parser
929 * @param string $text The sortkey to use
930 * @param string $uarg Either "noreplace" or "noerror" (in en)
931 * both suppress errors, and noreplace does nothing if
932 * a default sortkey already exists.
933 * @return string
934 */
935 public static function defaultsort( $parser, $text, $uarg = '' ) {
936 static $magicWords = null;
937 if ( is_null( $magicWords ) ) {
938 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
939 }
940 $arg = $magicWords->matchStartToEnd( $uarg );
941
942 $text = trim( $text );
943 if ( strlen( $text ) == 0 ) {
944 return '';
945 }
946 $old = $parser->getCustomDefaultSort();
947 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
948 $parser->setDefaultSort( $text );
949 }
950
951 if ( $old === false || $old == $text || $arg ) {
952 return '';
953 } else {
954 $converter = $parser->getConverterLanguage()->getConverter();
955 return '<span class="error">' .
956 wfMessage( 'duplicate-defaultsort',
957 // Message should be parsed, but these params should only be escaped.
958 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
959 $converter->markNoConversion( wfEscapeWikiText( $text ) )
960 )->inContentLanguage()->text() .
961 '</span>';
962 }
963 }
964
965 /**
966 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
967 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
968 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
969 *
970 * @param Parser $parser
971 * @param string $name
972 * @param string $argA
973 * @param string $argB
974 * @return array|string
975 */
976 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
977 $file = wfFindFile( $name );
978
979 if ( $argA == 'nowiki' ) {
980 // {{filepath: | option [| size] }}
981 $isNowiki = true;
982 $parsedWidthParam = $parser->parseWidthParam( $argB );
983 } else {
984 // {{filepath: [| size [|option]] }}
985 $parsedWidthParam = $parser->parseWidthParam( $argA );
986 $isNowiki = ( $argB == 'nowiki' );
987 }
988
989 if ( $file ) {
990 $url = $file->getFullUrl();
991
992 // If a size is requested...
993 if ( count( $parsedWidthParam ) ) {
994 $mto = $file->transform( $parsedWidthParam );
995 // ... and we can
996 if ( $mto && !$mto->isError() ) {
997 // ... change the URL to point to a thumbnail.
998 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
999 }
1000 }
1001 if ( $isNowiki ) {
1002 return [ $url, 'nowiki' => true ];
1003 }
1004 return $url;
1005 } else {
1006 return '';
1007 }
1008 }
1009
1010 /**
1011 * Parser function to extension tag adaptor
1012 * @param Parser $parser
1013 * @param PPFrame $frame
1014 * @param PPNode[] $args
1015 * @return string
1016 */
1017 public static function tagObj( $parser, $frame, $args ) {
1018 if ( !count( $args ) ) {
1019 return '';
1020 }
1021 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1022
1023 if ( count( $args ) ) {
1024 $inner = $frame->expand( array_shift( $args ) );
1025 } else {
1026 $inner = null;
1027 }
1028
1029 $attributes = [];
1030 foreach ( $args as $arg ) {
1031 $bits = $arg->splitArg();
1032 if ( strval( $bits['index'] ) === '' ) {
1033 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1034 $value = trim( $frame->expand( $bits['value'] ) );
1035 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1036 $value = isset( $m[1] ) ? $m[1] : '';
1037 }
1038 $attributes[$name] = $value;
1039 }
1040 }
1041
1042 $stripList = $parser->getStripList();
1043 if ( !in_array( $tagName, $stripList ) ) {
1044 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1045 $attrText = '';
1046 foreach ( $attributes as $name => $value ) {
1047 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1048 }
1049 if ( $inner === null ) {
1050 return "<$tagName$attrText/>";
1051 }
1052 return "<$tagName$attrText>$inner</$tagName>";
1053 }
1054
1055 $params = [
1056 'name' => $tagName,
1057 'inner' => $inner,
1058 'attributes' => $attributes,
1059 'close' => "</$tagName>",
1060 ];
1061 return $parser->extensionSubstitution( $params, $frame );
1062 }
1063
1064 /**
1065 * Fetched the current revision of the given title and return this.
1066 * Will increment the expensive function count and
1067 * add a template link to get the value refreshed on changes.
1068 * For a given title, which is equal to the current parser title,
1069 * the revision object from the parser is used, when that is the current one
1070 *
1071 * @param Parser $parser
1072 * @param Title $title
1073 * @return Revision
1074 * @since 1.23
1075 */
1076 private static function getCachedRevisionObject( $parser, $title = null ) {
1077 if ( is_null( $title ) ) {
1078 return null;
1079 }
1080
1081 // Use the revision from the parser itself, when param is the current page
1082 // and the revision is the current one
1083 if ( $title->equals( $parser->getTitle() ) ) {
1084 $parserRev = $parser->getRevisionObject();
1085 if ( $parserRev && $parserRev->isCurrent() ) {
1086 // force reparse after edit with vary-revision flag
1087 $parser->getOutput()->setFlag( 'vary-revision' );
1088 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
1089 return $parserRev;
1090 }
1091 }
1092
1093 // Normalize name for cache
1094 $page = $title->getPrefixedDBkey();
1095
1096 if ( !( $parser->currentRevisionCache && $parser->currentRevisionCache->has( $page ) )
1097 && !$parser->incrementExpensiveFunctionCount() ) {
1098 return null;
1099 }
1100 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1101 $pageID = $rev ? $rev->getPage() : 0;
1102 $revID = $rev ? $rev->getId() : 0;
1103
1104 // Register dependency in templatelinks
1105 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1106
1107 return $rev;
1108 }
1109
1110 /**
1111 * Get the pageid of a specified page
1112 * @param Parser $parser
1113 * @param string $title Title to get the pageid from
1114 * @return int|null|string
1115 * @since 1.23
1116 */
1117 public static function pageid( $parser, $title = null ) {
1118 $t = Title::newFromText( $title );
1119 if ( is_null( $t ) ) {
1120 return '';
1121 }
1122 // Use title from parser to have correct pageid after edit
1123 if ( $t->equals( $parser->getTitle() ) ) {
1124 $t = $parser->getTitle();
1125 return $t->getArticleID();
1126 }
1127
1128 // These can't have ids
1129 if ( !$t->canExist() || $t->isExternal() ) {
1130 return 0;
1131 }
1132
1133 // Check the link cache, maybe something already looked it up.
1134 $linkCache = LinkCache::singleton();
1135 $pdbk = $t->getPrefixedDBkey();
1136 $id = $linkCache->getGoodLinkID( $pdbk );
1137 if ( $id != 0 ) {
1138 $parser->mOutput->addLink( $t, $id );
1139 return $id;
1140 }
1141 if ( $linkCache->isBadLink( $pdbk ) ) {
1142 $parser->mOutput->addLink( $t, 0 );
1143 return $id;
1144 }
1145
1146 // We need to load it from the DB, so mark expensive
1147 if ( $parser->incrementExpensiveFunctionCount() ) {
1148 $id = $t->getArticleID();
1149 $parser->mOutput->addLink( $t, $id );
1150 return $id;
1151 }
1152 return null;
1153 }
1154
1155 /**
1156 * Get the id from the last revision of a specified page.
1157 * @param Parser $parser
1158 * @param string $title Title to get the id from
1159 * @return int|null|string
1160 * @since 1.23
1161 */
1162 public static function revisionid( $parser, $title = null ) {
1163 $t = Title::newFromText( $title );
1164 if ( is_null( $t ) ) {
1165 return '';
1166 }
1167 // fetch revision from cache/database and return the value
1168 $rev = self::getCachedRevisionObject( $parser, $t );
1169 return $rev ? $rev->getId() : '';
1170 }
1171
1172 /**
1173 * Get the day from the last revision of a specified page.
1174 * @param Parser $parser
1175 * @param string $title Title to get the day from
1176 * @return string
1177 * @since 1.23
1178 */
1179 public static function revisionday( $parser, $title = null ) {
1180 $t = Title::newFromText( $title );
1181 if ( is_null( $t ) ) {
1182 return '';
1183 }
1184 // fetch revision from cache/database and return the value
1185 $rev = self::getCachedRevisionObject( $parser, $t );
1186 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1187 }
1188
1189 /**
1190 * Get the day with leading zeros from the last revision of a specified page.
1191 * @param Parser $parser
1192 * @param string $title Title to get the day from
1193 * @return string
1194 * @since 1.23
1195 */
1196 public static function revisionday2( $parser, $title = null ) {
1197 $t = Title::newFromText( $title );
1198 if ( is_null( $t ) ) {
1199 return '';
1200 }
1201 // fetch revision from cache/database and return the value
1202 $rev = self::getCachedRevisionObject( $parser, $t );
1203 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1204 }
1205
1206 /**
1207 * Get the month with leading zeros from the last revision of a specified page.
1208 * @param Parser $parser
1209 * @param string $title Title to get the month from
1210 * @return string
1211 * @since 1.23
1212 */
1213 public static function revisionmonth( $parser, $title = null ) {
1214 $t = Title::newFromText( $title );
1215 if ( is_null( $t ) ) {
1216 return '';
1217 }
1218 // fetch revision from cache/database and return the value
1219 $rev = self::getCachedRevisionObject( $parser, $t );
1220 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1221 }
1222
1223 /**
1224 * Get the month from the last revision of a specified page.
1225 * @param Parser $parser
1226 * @param string $title Title to get the month from
1227 * @return string
1228 * @since 1.23
1229 */
1230 public static function revisionmonth1( $parser, $title = null ) {
1231 $t = Title::newFromText( $title );
1232 if ( is_null( $t ) ) {
1233 return '';
1234 }
1235 // fetch revision from cache/database and return the value
1236 $rev = self::getCachedRevisionObject( $parser, $t );
1237 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1238 }
1239
1240 /**
1241 * Get the year from the last revision of a specified page.
1242 * @param Parser $parser
1243 * @param string $title Title to get the year from
1244 * @return string
1245 * @since 1.23
1246 */
1247 public static function revisionyear( $parser, $title = null ) {
1248 $t = Title::newFromText( $title );
1249 if ( is_null( $t ) ) {
1250 return '';
1251 }
1252 // fetch revision from cache/database and return the value
1253 $rev = self::getCachedRevisionObject( $parser, $t );
1254 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1255 }
1256
1257 /**
1258 * Get the timestamp from the last revision of a specified page.
1259 * @param Parser $parser
1260 * @param string $title Title to get the timestamp from
1261 * @return string
1262 * @since 1.23
1263 */
1264 public static function revisiontimestamp( $parser, $title = null ) {
1265 $t = Title::newFromText( $title );
1266 if ( is_null( $t ) ) {
1267 return '';
1268 }
1269 // fetch revision from cache/database and return the value
1270 $rev = self::getCachedRevisionObject( $parser, $t );
1271 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1272 }
1273
1274 /**
1275 * Get the user from the last revision of a specified page.
1276 * @param Parser $parser
1277 * @param string $title Title to get the user from
1278 * @return string
1279 * @since 1.23
1280 */
1281 public static function revisionuser( $parser, $title = null ) {
1282 $t = Title::newFromText( $title );
1283 if ( is_null( $t ) ) {
1284 return '';
1285 }
1286 // fetch revision from cache/database and return the value
1287 $rev = self::getCachedRevisionObject( $parser, $t );
1288 return $rev ? $rev->getUserText() : '';
1289 }
1290
1291 /**
1292 * Returns the sources of any cascading protection acting on a specified page.
1293 * Pages will not return their own title unless they transclude themselves.
1294 * This is an expensive parser function and can't be called too many times per page,
1295 * unless cascading protection sources for the page have already been loaded.
1296 *
1297 * @param Parser $parser
1298 * @param string $title
1299 *
1300 * @return string
1301 * @since 1.23
1302 */
1303 public static function cascadingsources( $parser, $title = '' ) {
1304 $titleObject = Title::newFromText( $title );
1305 if ( !( $titleObject instanceof Title ) ) {
1306 $titleObject = $parser->mTitle;
1307 }
1308 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1309 || $parser->incrementExpensiveFunctionCount()
1310 ) {
1311 $names = [];
1312 $sources = $titleObject->getCascadeProtectionSources();
1313 foreach ( $sources[0] as $sourceTitle ) {
1314 $names[] = $sourceTitle->getPrefixedText();
1315 }
1316 return implode( $names, '|' );
1317 }
1318 return '';
1319 }
1320
1321 }