Merge "Added a separate error message for mkdir failures"
[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: (T24474)
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 // 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->inNamespace( 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->inNamespace( 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 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
350 if ( $user ) {
351 $gender = $genderCache->getGenderOf( $user, __METHOD__ );
352 } elseif ( $username === '' && $parser->getOptions()->getInterfaceMessage() ) {
353 $gender = $genderCache->getGenderOf( $parser->getOptions()->getUser(), __METHOD__ );
354 }
355 $ret = $parser->getFunctionLang()->gender( $gender, $forms );
356 return $ret;
357 }
358
359 /**
360 * @param Parser $parser
361 * @param string $text
362 * @return string
363 */
364 public static function plural( $parser, $text = '' ) {
365 $forms = array_slice( func_get_args(), 2 );
366 $text = $parser->getFunctionLang()->parseFormattedNumber( $text );
367 settype( $text, ctype_digit( $text ) ? 'int' : 'float' );
368 return $parser->getFunctionLang()->convertPlural( $text, $forms );
369 }
370
371 /**
372 * @param Parser $parser
373 * @param string $text
374 * @return string
375 */
376 public static function bidi( $parser, $text = '' ) {
377 return $parser->getFunctionLang()->embedBidi( $text );
378 }
379
380 /**
381 * Override the title of the page when viewed, provided we've been given a
382 * title which will normalise to the canonical title
383 *
384 * @param Parser $parser Parent parser
385 * @param string $text Desired title text
386 * @param string $uarg
387 * @return string
388 */
389 public static function displaytitle( $parser, $text = '', $uarg = '' ) {
390 global $wgRestrictDisplayTitle;
391
392 static $magicWords = null;
393 if ( is_null( $magicWords ) ) {
394 $magicWords = new MagicWordArray( [ 'displaytitle_noerror', 'displaytitle_noreplace' ] );
395 }
396 $arg = $magicWords->matchStartToEnd( $uarg );
397
398 // parse a limited subset of wiki markup (just the single quote items)
399 $text = $parser->doQuotes( $text );
400
401 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
402 $text = $parser->killMarkers( $text );
403
404 // list of disallowed tags for DISPLAYTITLE
405 // these will be escaped even though they are allowed in normal wiki text
406 $bad = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
407 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' ];
408
409 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
410 if ( $wgRestrictDisplayTitle ) {
411 $htmlTagsCallback = function ( &$params ) {
412 $decoded = Sanitizer::decodeTagAttributes( $params );
413
414 if ( isset( $decoded['style'] ) ) {
415 // this is called later anyway, but we need it right now for the regexes below to be safe
416 // calling it twice doesn't hurt
417 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
418
419 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
420 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
421 }
422 }
423
424 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
425 };
426 } else {
427 $htmlTagsCallback = null;
428 }
429
430 // only requested titles that normalize to the actual title are allowed through
431 // if $wgRestrictDisplayTitle is true (it is by default)
432 // mimic the escaping process that occurs in OutputPage::setPageTitle
433 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
434 $text,
435 $htmlTagsCallback,
436 [],
437 [],
438 $bad
439 ) );
440 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
441
442 if ( !$wgRestrictDisplayTitle ||
443 ( $title instanceof Title
444 && !$title->hasFragment()
445 && $title->equals( $parser->mTitle ) )
446 ) {
447 $old = $parser->mOutput->getProperty( 'displaytitle' );
448 if ( $old === false || $arg !== 'displaytitle_noreplace' ) {
449 $parser->mOutput->setDisplayTitle( $text );
450 }
451 if ( $old !== false && $old !== $text && !$arg ) {
452 $converter = $parser->getConverterLanguage()->getConverter();
453 return '<span class="error">' .
454 wfMessage( 'duplicate-displaytitle',
455 // Message should be parsed, but these params should only be escaped.
456 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
457 $converter->markNoConversion( wfEscapeWikiText( $text ) )
458 )->inContentLanguage()->text() .
459 '</span>';
460 } else {
461 return '';
462 }
463 } else {
464 $converter = $parser->getConverterLanguage()->getConverter();
465 $parser->getOutput()->addWarning(
466 wfMessage( 'restricted-displaytitle',
467 // Message should be parsed, but this param should only be escaped.
468 $converter->markNoConversion( wfEscapeWikiText( $text ) )
469 )->text()
470 );
471 $parser->addTrackingCategory( 'restricted-displaytitle-ignored' );
472 }
473 }
474
475 /**
476 * Matches the given value against the value of given magic word
477 *
478 * @param string $magicword Magic word key
479 * @param string $value Value to match
480 * @return bool True on successful match
481 */
482 private static function matchAgainstMagicword( $magicword, $value ) {
483 $value = trim( strval( $value ) );
484 if ( $value === '' ) {
485 return false;
486 }
487 $mwObject = MagicWord::get( $magicword );
488 return $mwObject->matchStartToEnd( $value );
489 }
490
491 /**
492 * Formats a number according to a language.
493 *
494 * @param int|float $num
495 * @param string $raw
496 * @param Language|StubUserLang $language
497 * @return string
498 */
499 public static function formatRaw( $num, $raw, $language ) {
500 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
501 return $num;
502 } else {
503 return $language->formatNum( $num );
504 }
505 }
506
507 public static function numberofpages( $parser, $raw = null ) {
508 return self::formatRaw( SiteStats::pages(), $raw, $parser->getFunctionLang() );
509 }
510
511 public static function numberofusers( $parser, $raw = null ) {
512 return self::formatRaw( SiteStats::users(), $raw, $parser->getFunctionLang() );
513 }
514 public static function numberofactiveusers( $parser, $raw = null ) {
515 return self::formatRaw( SiteStats::activeUsers(), $raw, $parser->getFunctionLang() );
516 }
517
518 public static function numberofarticles( $parser, $raw = null ) {
519 return self::formatRaw( SiteStats::articles(), $raw, $parser->getFunctionLang() );
520 }
521
522 public static function numberoffiles( $parser, $raw = null ) {
523 return self::formatRaw( SiteStats::images(), $raw, $parser->getFunctionLang() );
524 }
525
526 public static function numberofadmins( $parser, $raw = null ) {
527 return self::formatRaw(
528 SiteStats::numberingroup( 'sysop' ),
529 $raw,
530 $parser->getFunctionLang()
531 );
532 }
533
534 public static function numberofedits( $parser, $raw = null ) {
535 return self::formatRaw( SiteStats::edits(), $raw, $parser->getFunctionLang() );
536 }
537
538 public static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
539 return self::formatRaw(
540 SiteStats::pagesInNs( intval( $namespace ) ),
541 $raw,
542 $parser->getFunctionLang()
543 );
544 }
545 public static function numberingroup( $parser, $name = '', $raw = null ) {
546 return self::formatRaw(
547 SiteStats::numberingroup( strtolower( $name ) ),
548 $raw,
549 $parser->getFunctionLang()
550 );
551 }
552
553 /**
554 * Given a title, return the namespace name that would be given by the
555 * corresponding magic word
556 * Note: function name changed to "mwnamespace" rather than "namespace"
557 * to not break PHP 5.3
558 * @param Parser $parser
559 * @param string $title
560 * @return mixed|string
561 */
562 public static function mwnamespace( $parser, $title = null ) {
563 $t = Title::newFromText( $title );
564 if ( is_null( $t ) ) {
565 return '';
566 }
567 return str_replace( '_', ' ', $t->getNsText() );
568 }
569 public static function namespacee( $parser, $title = null ) {
570 $t = Title::newFromText( $title );
571 if ( is_null( $t ) ) {
572 return '';
573 }
574 return wfUrlencode( $t->getNsText() );
575 }
576 public static function namespacenumber( $parser, $title = null ) {
577 $t = Title::newFromText( $title );
578 if ( is_null( $t ) ) {
579 return '';
580 }
581 return $t->getNamespace();
582 }
583 public static function talkspace( $parser, $title = null ) {
584 $t = Title::newFromText( $title );
585 if ( is_null( $t ) || !$t->canTalk() ) {
586 return '';
587 }
588 return str_replace( '_', ' ', $t->getTalkNsText() );
589 }
590 public static function talkspacee( $parser, $title = null ) {
591 $t = Title::newFromText( $title );
592 if ( is_null( $t ) || !$t->canTalk() ) {
593 return '';
594 }
595 return wfUrlencode( $t->getTalkNsText() );
596 }
597 public static function subjectspace( $parser, $title = null ) {
598 $t = Title::newFromText( $title );
599 if ( is_null( $t ) ) {
600 return '';
601 }
602 return str_replace( '_', ' ', $t->getSubjectNsText() );
603 }
604 public static function subjectspacee( $parser, $title = null ) {
605 $t = Title::newFromText( $title );
606 if ( is_null( $t ) ) {
607 return '';
608 }
609 return wfUrlencode( $t->getSubjectNsText() );
610 }
611
612 /**
613 * Functions to get and normalize pagenames, corresponding to the magic words
614 * of the same names
615 * @param Parser $parser
616 * @param string $title
617 * @return string
618 */
619 public static function pagename( $parser, $title = null ) {
620 $t = Title::newFromText( $title );
621 if ( is_null( $t ) ) {
622 return '';
623 }
624 return wfEscapeWikiText( $t->getText() );
625 }
626 public static function pagenamee( $parser, $title = null ) {
627 $t = Title::newFromText( $title );
628 if ( is_null( $t ) ) {
629 return '';
630 }
631 return wfEscapeWikiText( $t->getPartialURL() );
632 }
633 public static function fullpagename( $parser, $title = null ) {
634 $t = Title::newFromText( $title );
635 if ( is_null( $t ) || !$t->canTalk() ) {
636 return '';
637 }
638 return wfEscapeWikiText( $t->getPrefixedText() );
639 }
640 public static function fullpagenamee( $parser, $title = null ) {
641 $t = Title::newFromText( $title );
642 if ( is_null( $t ) || !$t->canTalk() ) {
643 return '';
644 }
645 return wfEscapeWikiText( $t->getPrefixedURL() );
646 }
647 public static function subpagename( $parser, $title = null ) {
648 $t = Title::newFromText( $title );
649 if ( is_null( $t ) ) {
650 return '';
651 }
652 return wfEscapeWikiText( $t->getSubpageText() );
653 }
654 public static function subpagenamee( $parser, $title = null ) {
655 $t = Title::newFromText( $title );
656 if ( is_null( $t ) ) {
657 return '';
658 }
659 return wfEscapeWikiText( $t->getSubpageUrlForm() );
660 }
661 public static function rootpagename( $parser, $title = null ) {
662 $t = Title::newFromText( $title );
663 if ( is_null( $t ) ) {
664 return '';
665 }
666 return wfEscapeWikiText( $t->getRootText() );
667 }
668 public static function rootpagenamee( $parser, $title = null ) {
669 $t = Title::newFromText( $title );
670 if ( is_null( $t ) ) {
671 return '';
672 }
673 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getRootText() ) ) );
674 }
675 public static function basepagename( $parser, $title = null ) {
676 $t = Title::newFromText( $title );
677 if ( is_null( $t ) ) {
678 return '';
679 }
680 return wfEscapeWikiText( $t->getBaseText() );
681 }
682 public static function basepagenamee( $parser, $title = null ) {
683 $t = Title::newFromText( $title );
684 if ( is_null( $t ) ) {
685 return '';
686 }
687 return wfEscapeWikiText( wfUrlencode( str_replace( ' ', '_', $t->getBaseText() ) ) );
688 }
689 public static function talkpagename( $parser, $title = null ) {
690 $t = Title::newFromText( $title );
691 if ( is_null( $t ) || !$t->canTalk() ) {
692 return '';
693 }
694 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
695 }
696 public static function talkpagenamee( $parser, $title = null ) {
697 $t = Title::newFromText( $title );
698 if ( is_null( $t ) || !$t->canTalk() ) {
699 return '';
700 }
701 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
702 }
703 public static function subjectpagename( $parser, $title = null ) {
704 $t = Title::newFromText( $title );
705 if ( is_null( $t ) ) {
706 return '';
707 }
708 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
709 }
710 public static function subjectpagenamee( $parser, $title = null ) {
711 $t = Title::newFromText( $title );
712 if ( is_null( $t ) ) {
713 return '';
714 }
715 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
716 }
717
718 /**
719 * Return the number of pages, files or subcats in the given category,
720 * or 0 if it's nonexistent. This is an expensive parser function and
721 * can't be called too many times per page.
722 * @param Parser $parser
723 * @param string $name
724 * @param string $arg1
725 * @param string $arg2
726 * @return string
727 */
728 public static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
729 global $wgContLang;
730 static $magicWords = null;
731 if ( is_null( $magicWords ) ) {
732 $magicWords = new MagicWordArray( [
733 'pagesincategory_all',
734 'pagesincategory_pages',
735 'pagesincategory_subcats',
736 'pagesincategory_files'
737 ] );
738 }
739 static $cache = [];
740
741 // split the given option to its variable
742 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
743 // {{pagesincategory:|raw[|type]}}
744 $raw = $arg1;
745 $type = $magicWords->matchStartToEnd( $arg2 );
746 } else {
747 // {{pagesincategory:[|type[|raw]]}}
748 $type = $magicWords->matchStartToEnd( $arg1 );
749 $raw = $arg2;
750 }
751 if ( !$type ) { // backward compatibility
752 $type = 'pagesincategory_all';
753 }
754
755 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
756 if ( !$title ) { # invalid title
757 return self::formatRaw( 0, $raw, $parser->getFunctionLang() );
758 }
759 $wgContLang->findVariantLink( $name, $title, true );
760
761 // Normalize name for cache
762 $name = $title->getDBkey();
763
764 if ( !isset( $cache[$name] ) ) {
765 $category = Category::newFromTitle( $title );
766
767 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
768 if ( $parser->incrementExpensiveFunctionCount() ) {
769 // $allCount is the total number of cat members,
770 // not the count of how many members are normal pages.
771 $allCount = (int)$category->getPageCount();
772 $subcatCount = (int)$category->getSubcatCount();
773 $fileCount = (int)$category->getFileCount();
774 $pagesCount = $allCount - $subcatCount - $fileCount;
775 }
776 $cache[$name]['pagesincategory_all'] = $allCount;
777 $cache[$name]['pagesincategory_pages'] = $pagesCount;
778 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
779 $cache[$name]['pagesincategory_files'] = $fileCount;
780 }
781
782 $count = $cache[$name][$type];
783 return self::formatRaw( $count, $raw, $parser->getFunctionLang() );
784 }
785
786 /**
787 * Return the size of the given page, or 0 if it's nonexistent. This is an
788 * expensive parser function and can't be called too many times per page.
789 *
790 * @param Parser $parser
791 * @param string $page Name of page to check (Default: empty string)
792 * @param string $raw Should number be human readable with commas or just number
793 * @return string
794 */
795 public static function pagesize( $parser, $page = '', $raw = null ) {
796 $title = Title::newFromText( $page );
797
798 if ( !is_object( $title ) ) {
799 return self::formatRaw( 0, $raw, $parser->getFunctionLang() );
800 }
801
802 // fetch revision from cache/database and return the value
803 $rev = self::getCachedRevisionObject( $parser, $title );
804 $length = $rev ? $rev->getSize() : 0;
805 if ( $length === null ) {
806 // We've had bugs where rev_len was not being recorded for empty pages, see T135414
807 $length = 0;
808 }
809 return self::formatRaw( $length, $raw, $parser->getFunctionLang() );
810 }
811
812 /**
813 * Returns the requested protection level for the current page. This
814 * is an expensive parser function and can't be called too many times
815 * per page, unless the protection levels/expiries for the given title
816 * have already been retrieved
817 *
818 * @param Parser $parser
819 * @param string $type
820 * @param string $title
821 *
822 * @return string
823 */
824 public static function protectionlevel( $parser, $type = '', $title = '' ) {
825 $titleObject = Title::newFromText( $title );
826 if ( !( $titleObject instanceof Title ) ) {
827 $titleObject = $parser->mTitle;
828 }
829 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
830 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
831 # Title::getRestrictions returns an array, its possible it may have
832 # multiple values in the future
833 return implode( $restrictions, ',' );
834 }
835 return '';
836 }
837
838 /**
839 * Returns the requested protection expiry for the current page. This
840 * is an expensive parser function and can't be called too many times
841 * per page, unless the protection levels/expiries for the given title
842 * have already been retrieved
843 *
844 * @param Parser $parser
845 * @param string $type
846 * @param string $title
847 *
848 * @return string
849 */
850 public static function protectionexpiry( $parser, $type = '', $title = '' ) {
851 $titleObject = Title::newFromText( $title );
852 if ( !( $titleObject instanceof Title ) ) {
853 $titleObject = $parser->mTitle;
854 }
855 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
856 $expiry = $titleObject->getRestrictionExpiry( strtolower( $type ) );
857 // getRestrictionExpiry() returns false on invalid type; trying to
858 // match protectionlevel() function that returns empty string instead
859 if ( $expiry === false ) {
860 $expiry = '';
861 }
862 return $expiry;
863 }
864 return '';
865 }
866
867 /**
868 * Gives language names.
869 * @param Parser $parser
870 * @param string $code Language code (of which to get name)
871 * @param string $inLanguage Language code (in which to get name)
872 * @return string
873 */
874 public static function language( $parser, $code = '', $inLanguage = '' ) {
875 $code = strtolower( $code );
876 $inLanguage = strtolower( $inLanguage );
877 $lang = Language::fetchLanguageName( $code, $inLanguage );
878 return $lang !== '' ? $lang : wfBCP47( $code );
879 }
880
881 /**
882 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
883 * @param Parser $parser
884 * @param string $string
885 * @param int $length
886 * @param string $padding
887 * @param int $direction
888 * @return string
889 */
890 public static function pad(
891 $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT
892 ) {
893 $padding = $parser->killMarkers( $padding );
894 $lengthOfPadding = mb_strlen( $padding );
895 if ( $lengthOfPadding == 0 ) {
896 return $string;
897 }
898
899 # The remaining length to add counts down to 0 as padding is added
900 $length = min( $length, 500 ) - mb_strlen( $string );
901 # $finalPadding is just $padding repeated enough times so that
902 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
903 $finalPadding = '';
904 while ( $length > 0 ) {
905 # If $length < $lengthofPadding, truncate $padding so we get the
906 # exact length desired.
907 $finalPadding .= mb_substr( $padding, 0, $length );
908 $length -= $lengthOfPadding;
909 }
910
911 if ( $direction == STR_PAD_LEFT ) {
912 return $finalPadding . $string;
913 } else {
914 return $string . $finalPadding;
915 }
916 }
917
918 public static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
919 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
920 }
921
922 public static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
923 return self::pad( $parser, $string, $length, $padding );
924 }
925
926 /**
927 * @param Parser $parser
928 * @param string $text
929 * @return string
930 */
931 public static function anchorencode( $parser, $text ) {
932 $text = $parser->killMarkers( $text );
933 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
934 }
935
936 public static function special( $parser, $text ) {
937 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
938 if ( $page ) {
939 $title = SpecialPage::getTitleFor( $page, $subpage );
940 return $title->getPrefixedText();
941 } else {
942 // unknown special page, just use the given text as its title, if at all possible
943 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
944 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
945 }
946 }
947
948 public static function speciale( $parser, $text ) {
949 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
950 }
951
952 /**
953 * @param Parser $parser
954 * @param string $text The sortkey to use
955 * @param string $uarg Either "noreplace" or "noerror" (in en)
956 * both suppress errors, and noreplace does nothing if
957 * a default sortkey already exists.
958 * @return string
959 */
960 public static function defaultsort( $parser, $text, $uarg = '' ) {
961 static $magicWords = null;
962 if ( is_null( $magicWords ) ) {
963 $magicWords = new MagicWordArray( [ 'defaultsort_noerror', 'defaultsort_noreplace' ] );
964 }
965 $arg = $magicWords->matchStartToEnd( $uarg );
966
967 $text = trim( $text );
968 if ( strlen( $text ) == 0 ) {
969 return '';
970 }
971 $old = $parser->getCustomDefaultSort();
972 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
973 $parser->setDefaultSort( $text );
974 }
975
976 if ( $old === false || $old == $text || $arg ) {
977 return '';
978 } else {
979 $converter = $parser->getConverterLanguage()->getConverter();
980 return '<span class="error">' .
981 wfMessage( 'duplicate-defaultsort',
982 // Message should be parsed, but these params should only be escaped.
983 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
984 $converter->markNoConversion( wfEscapeWikiText( $text ) )
985 )->inContentLanguage()->text() .
986 '</span>';
987 }
988 }
989
990 /**
991 * Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
992 * or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
993 * {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
994 *
995 * @param Parser $parser
996 * @param string $name
997 * @param string $argA
998 * @param string $argB
999 * @return array|string
1000 */
1001 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
1002 $file = wfFindFile( $name );
1003
1004 if ( $argA == 'nowiki' ) {
1005 // {{filepath: | option [| size] }}
1006 $isNowiki = true;
1007 $parsedWidthParam = $parser->parseWidthParam( $argB );
1008 } else {
1009 // {{filepath: [| size [|option]] }}
1010 $parsedWidthParam = $parser->parseWidthParam( $argA );
1011 $isNowiki = ( $argB == 'nowiki' );
1012 }
1013
1014 if ( $file ) {
1015 $url = $file->getFullUrl();
1016
1017 // If a size is requested...
1018 if ( count( $parsedWidthParam ) ) {
1019 $mto = $file->transform( $parsedWidthParam );
1020 // ... and we can
1021 if ( $mto && !$mto->isError() ) {
1022 // ... change the URL to point to a thumbnail.
1023 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
1024 }
1025 }
1026 if ( $isNowiki ) {
1027 return [ $url, 'nowiki' => true ];
1028 }
1029 return $url;
1030 } else {
1031 return '';
1032 }
1033 }
1034
1035 /**
1036 * Parser function to extension tag adaptor
1037 * @param Parser $parser
1038 * @param PPFrame $frame
1039 * @param PPNode[] $args
1040 * @return string
1041 */
1042 public static function tagObj( $parser, $frame, $args ) {
1043 if ( !count( $args ) ) {
1044 return '';
1045 }
1046 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
1047
1048 if ( count( $args ) ) {
1049 $inner = $frame->expand( array_shift( $args ) );
1050 } else {
1051 $inner = null;
1052 }
1053
1054 $attributes = [];
1055 foreach ( $args as $arg ) {
1056 $bits = $arg->splitArg();
1057 if ( strval( $bits['index'] ) === '' ) {
1058 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
1059 $value = trim( $frame->expand( $bits['value'] ) );
1060 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
1061 $value = isset( $m[1] ) ? $m[1] : '';
1062 }
1063 $attributes[$name] = $value;
1064 }
1065 }
1066
1067 $stripList = $parser->getStripList();
1068 if ( !in_array( $tagName, $stripList ) ) {
1069 // we can't handle this tag (at least not now), so just re-emit it as an ordinary tag
1070 $attrText = '';
1071 foreach ( $attributes as $name => $value ) {
1072 $attrText .= ' ' . htmlspecialchars( $name ) . '="' . htmlspecialchars( $value ) . '"';
1073 }
1074 if ( $inner === null ) {
1075 return "<$tagName$attrText/>";
1076 }
1077 return "<$tagName$attrText>$inner</$tagName>";
1078 }
1079
1080 $params = [
1081 'name' => $tagName,
1082 'inner' => $inner,
1083 'attributes' => $attributes,
1084 'close' => "</$tagName>",
1085 ];
1086 return $parser->extensionSubstitution( $params, $frame );
1087 }
1088
1089 /**
1090 * Fetched the current revision of the given title and return this.
1091 * Will increment the expensive function count and
1092 * add a template link to get the value refreshed on changes.
1093 * For a given title, which is equal to the current parser title,
1094 * the revision object from the parser is used, when that is the current one
1095 *
1096 * @param Parser $parser
1097 * @param Title $title
1098 * @return Revision
1099 * @since 1.23
1100 */
1101 private static function getCachedRevisionObject( $parser, $title = null ) {
1102 if ( is_null( $title ) ) {
1103 return null;
1104 }
1105
1106 // Use the revision from the parser itself, when param is the current page
1107 // and the revision is the current one
1108 if ( $title->equals( $parser->getTitle() ) ) {
1109 $parserRev = $parser->getRevisionObject();
1110 if ( $parserRev && $parserRev->isCurrent() ) {
1111 // force reparse after edit with vary-revision flag
1112 $parser->getOutput()->setFlag( 'vary-revision' );
1113 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
1114 return $parserRev;
1115 }
1116 }
1117
1118 // Normalize name for cache
1119 $page = $title->getPrefixedDBkey();
1120
1121 if ( !( $parser->currentRevisionCache && $parser->currentRevisionCache->has( $page ) )
1122 && !$parser->incrementExpensiveFunctionCount() ) {
1123 return null;
1124 }
1125 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
1126 $pageID = $rev ? $rev->getPage() : 0;
1127 $revID = $rev ? $rev->getId() : 0;
1128
1129 // Register dependency in templatelinks
1130 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1131
1132 return $rev;
1133 }
1134
1135 /**
1136 * Get the pageid of a specified page
1137 * @param Parser $parser
1138 * @param string $title Title to get the pageid from
1139 * @return int|null|string
1140 * @since 1.23
1141 */
1142 public static function pageid( $parser, $title = null ) {
1143 $t = Title::newFromText( $title );
1144 if ( is_null( $t ) ) {
1145 return '';
1146 }
1147 // Use title from parser to have correct pageid after edit
1148 if ( $t->equals( $parser->getTitle() ) ) {
1149 $t = $parser->getTitle();
1150 return $t->getArticleID();
1151 }
1152
1153 // These can't have ids
1154 if ( !$t->canExist() || $t->isExternal() ) {
1155 return 0;
1156 }
1157
1158 // Check the link cache, maybe something already looked it up.
1159 $linkCache = LinkCache::singleton();
1160 $pdbk = $t->getPrefixedDBkey();
1161 $id = $linkCache->getGoodLinkID( $pdbk );
1162 if ( $id != 0 ) {
1163 $parser->mOutput->addLink( $t, $id );
1164 return $id;
1165 }
1166 if ( $linkCache->isBadLink( $pdbk ) ) {
1167 $parser->mOutput->addLink( $t, 0 );
1168 return $id;
1169 }
1170
1171 // We need to load it from the DB, so mark expensive
1172 if ( $parser->incrementExpensiveFunctionCount() ) {
1173 $id = $t->getArticleID();
1174 $parser->mOutput->addLink( $t, $id );
1175 return $id;
1176 }
1177 return null;
1178 }
1179
1180 /**
1181 * Get the id from the last revision of a specified page.
1182 * @param Parser $parser
1183 * @param string $title Title to get the id from
1184 * @return int|null|string
1185 * @since 1.23
1186 */
1187 public static function revisionid( $parser, $title = null ) {
1188 $t = Title::newFromText( $title );
1189 if ( is_null( $t ) ) {
1190 return '';
1191 }
1192 // fetch revision from cache/database and return the value
1193 $rev = self::getCachedRevisionObject( $parser, $t );
1194 return $rev ? $rev->getId() : '';
1195 }
1196
1197 /**
1198 * Get the day from the last revision of a specified page.
1199 * @param Parser $parser
1200 * @param string $title Title to get the day from
1201 * @return string
1202 * @since 1.23
1203 */
1204 public static function revisionday( $parser, $title = null ) {
1205 $t = Title::newFromText( $title );
1206 if ( is_null( $t ) ) {
1207 return '';
1208 }
1209 // fetch revision from cache/database and return the value
1210 $rev = self::getCachedRevisionObject( $parser, $t );
1211 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1212 }
1213
1214 /**
1215 * Get the day with leading zeros from the last revision of a specified page.
1216 * @param Parser $parser
1217 * @param string $title Title to get the day from
1218 * @return string
1219 * @since 1.23
1220 */
1221 public static function revisionday2( $parser, $title = null ) {
1222 $t = Title::newFromText( $title );
1223 if ( is_null( $t ) ) {
1224 return '';
1225 }
1226 // fetch revision from cache/database and return the value
1227 $rev = self::getCachedRevisionObject( $parser, $t );
1228 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1229 }
1230
1231 /**
1232 * Get the month with leading zeros from the last revision of a specified page.
1233 * @param Parser $parser
1234 * @param string $title Title to get the month from
1235 * @return string
1236 * @since 1.23
1237 */
1238 public static function revisionmonth( $parser, $title = null ) {
1239 $t = Title::newFromText( $title );
1240 if ( is_null( $t ) ) {
1241 return '';
1242 }
1243 // fetch revision from cache/database and return the value
1244 $rev = self::getCachedRevisionObject( $parser, $t );
1245 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1246 }
1247
1248 /**
1249 * Get the month from the last revision of a specified page.
1250 * @param Parser $parser
1251 * @param string $title Title to get the month from
1252 * @return string
1253 * @since 1.23
1254 */
1255 public static function revisionmonth1( $parser, $title = null ) {
1256 $t = Title::newFromText( $title );
1257 if ( is_null( $t ) ) {
1258 return '';
1259 }
1260 // fetch revision from cache/database and return the value
1261 $rev = self::getCachedRevisionObject( $parser, $t );
1262 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1263 }
1264
1265 /**
1266 * Get the year from the last revision of a specified page.
1267 * @param Parser $parser
1268 * @param string $title Title to get the year from
1269 * @return string
1270 * @since 1.23
1271 */
1272 public static function revisionyear( $parser, $title = null ) {
1273 $t = Title::newFromText( $title );
1274 if ( is_null( $t ) ) {
1275 return '';
1276 }
1277 // fetch revision from cache/database and return the value
1278 $rev = self::getCachedRevisionObject( $parser, $t );
1279 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1280 }
1281
1282 /**
1283 * Get the timestamp from the last revision of a specified page.
1284 * @param Parser $parser
1285 * @param string $title Title to get the timestamp from
1286 * @return string
1287 * @since 1.23
1288 */
1289 public static function revisiontimestamp( $parser, $title = null ) {
1290 $t = Title::newFromText( $title );
1291 if ( is_null( $t ) ) {
1292 return '';
1293 }
1294 // fetch revision from cache/database and return the value
1295 $rev = self::getCachedRevisionObject( $parser, $t );
1296 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1297 }
1298
1299 /**
1300 * Get the user from the last revision of a specified page.
1301 * @param Parser $parser
1302 * @param string $title Title to get the user from
1303 * @return string
1304 * @since 1.23
1305 */
1306 public static function revisionuser( $parser, $title = null ) {
1307 $t = Title::newFromText( $title );
1308 if ( is_null( $t ) ) {
1309 return '';
1310 }
1311 // fetch revision from cache/database and return the value
1312 $rev = self::getCachedRevisionObject( $parser, $t );
1313 return $rev ? $rev->getUserText() : '';
1314 }
1315
1316 /**
1317 * Returns the sources of any cascading protection acting on a specified page.
1318 * Pages will not return their own title unless they transclude themselves.
1319 * This is an expensive parser function and can't be called too many times per page,
1320 * unless cascading protection sources for the page have already been loaded.
1321 *
1322 * @param Parser $parser
1323 * @param string $title
1324 *
1325 * @return string
1326 * @since 1.23
1327 */
1328 public static function cascadingsources( $parser, $title = '' ) {
1329 $titleObject = Title::newFromText( $title );
1330 if ( !( $titleObject instanceof Title ) ) {
1331 $titleObject = $parser->mTitle;
1332 }
1333 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1334 || $parser->incrementExpensiveFunctionCount()
1335 ) {
1336 $names = [];
1337 $sources = $titleObject->getCascadeProtectionSources();
1338 foreach ( $sources[0] as $sourceTitle ) {
1339 $names[] = $sourceTitle->getPrefixedText();
1340 }
1341 return implode( $names, '|' );
1342 }
1343 return '';
1344 }
1345
1346 }