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