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