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