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