EditPage::newSectionSummary should return a value in all code paths
[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 Parser::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 = '', $uarg = '' ) {
369 global $wgRestrictDisplayTitle;
370
371 static $magicWords = null;
372 if ( is_null( $magicWords ) ) {
373 $magicWords = new MagicWordArray( array( 'displaytitle_noerror', 'displaytitle_noreplace' ) );
374 }
375 $arg = $magicWords->matchStartToEnd( $uarg );
376
377 // parse a limited subset of wiki markup (just the single quote items)
378 $text = $parser->doQuotes( $text );
379
380 // remove stripped text (e.g. the UNIQ-QINU stuff) that was generated by tag extensions/whatever
381 $text = preg_replace( '/' . preg_quote( $parser->uniqPrefix(), '/' ) . '.*?'
382 . preg_quote( Parser::MARKER_SUFFIX, '/' ) . '/', '', $text );
383
384 // list of disallowed tags for DISPLAYTITLE
385 // these will be escaped even though they are allowed in normal wiki text
386 $bad = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'blockquote', 'ol', 'ul', 'li', 'hr',
387 'table', 'tr', 'th', 'td', 'dl', 'dd', 'caption', 'p', 'ruby', 'rb', 'rt', 'rtc', 'rp', 'br' );
388
389 // disallow some styles that could be used to bypass $wgRestrictDisplayTitle
390 if ( $wgRestrictDisplayTitle ) {
391 $htmlTagsCallback = function ( &$params ) {
392 $decoded = Sanitizer::decodeTagAttributes( $params );
393
394 if ( isset( $decoded['style'] ) ) {
395 // this is called later anyway, but we need it right now for the regexes below to be safe
396 // calling it twice doesn't hurt
397 $decoded['style'] = Sanitizer::checkCss( $decoded['style'] );
398
399 if ( preg_match( '/(display|user-select|visibility)\s*:/i', $decoded['style'] ) ) {
400 $decoded['style'] = '/* attempt to bypass $wgRestrictDisplayTitle */';
401 }
402 }
403
404 $params = Sanitizer::safeEncodeTagAttributes( $decoded );
405 };
406 } else {
407 $htmlTagsCallback = null;
408 }
409
410 // only requested titles that normalize to the actual title are allowed through
411 // if $wgRestrictDisplayTitle is true (it is by default)
412 // mimic the escaping process that occurs in OutputPage::setPageTitle
413 $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
414 $text,
415 $htmlTagsCallback,
416 array(),
417 array(),
418 $bad
419 ) );
420 $title = Title::newFromText( Sanitizer::stripAllTags( $text ) );
421
422 if ( !$wgRestrictDisplayTitle ||
423 ( $title instanceof Title
424 && !$title->hasFragment()
425 && $title->equals( $parser->mTitle ) )
426 ) {
427 $old = $parser->mOutput->getProperty( 'displaytitle' );
428 if ( $old === false || $arg !== 'displaytitle_noreplace' ) {
429 $parser->mOutput->setDisplayTitle( $text );
430 }
431 if ( $old !== false && $old !== $text && !$arg ) {
432 $converter = $parser->getConverterLanguage()->getConverter();
433 return '<span class="error">' .
434 wfMessage( 'duplicate-displaytitle',
435 // Message should be parsed, but these params should only be escaped.
436 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
437 $converter->markNoConversion( wfEscapeWikiText( $text ) )
438 )->inContentLanguage()->text() .
439 '</span>';
440 }
441 }
442
443 return '';
444 }
445
446 /**
447 * Matches the given value against the value of given magic word
448 *
449 * @param string $magicword Magic word key
450 * @param string $value Value to match
451 * @return bool True on successful match
452 */
453 private static function matchAgainstMagicword( $magicword, $value ) {
454 $value = trim( strval( $value ) );
455 if ( $value === '' ) {
456 return false;
457 }
458 $mwObject = MagicWord::get( $magicword );
459 return $mwObject->matchStartToEnd( $value );
460 }
461
462 static function formatRaw( $num, $raw ) {
463 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
464 return $num;
465 } else {
466 global $wgContLang;
467 return $wgContLang->formatNum( $num );
468 }
469 }
470 static function numberofpages( $parser, $raw = null ) {
471 return self::formatRaw( SiteStats::pages(), $raw );
472 }
473 static function numberofusers( $parser, $raw = null ) {
474 return self::formatRaw( SiteStats::users(), $raw );
475 }
476 static function numberofactiveusers( $parser, $raw = null ) {
477 return self::formatRaw( SiteStats::activeUsers(), $raw );
478 }
479 static function numberofarticles( $parser, $raw = null ) {
480 return self::formatRaw( SiteStats::articles(), $raw );
481 }
482 static function numberoffiles( $parser, $raw = null ) {
483 return self::formatRaw( SiteStats::images(), $raw );
484 }
485 static function numberofadmins( $parser, $raw = null ) {
486 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
487 }
488 static function numberofedits( $parser, $raw = null ) {
489 return self::formatRaw( SiteStats::edits(), $raw );
490 }
491 static function numberofviews( $parser, $raw = null ) {
492 global $wgDisableCounters;
493 return !$wgDisableCounters ? self::formatRaw( SiteStats::views(), $raw ) : '';
494 }
495 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
496 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
497 }
498 static function numberingroup( $parser, $name = '', $raw = null ) {
499 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
500 }
501
502 /**
503 * Given a title, return the namespace name that would be given by the
504 * corresponding magic word
505 * Note: function name changed to "mwnamespace" rather than "namespace"
506 * to not break PHP 5.3
507 * @param Parser $parser
508 * @param string $title
509 * @return mixed|string
510 */
511 static function mwnamespace( $parser, $title = null ) {
512 $t = Title::newFromText( $title );
513 if ( is_null( $t ) ) {
514 return '';
515 }
516 return str_replace( '_', ' ', $t->getNsText() );
517 }
518 static function namespacee( $parser, $title = null ) {
519 $t = Title::newFromText( $title );
520 if ( is_null( $t ) ) {
521 return '';
522 }
523 return wfUrlencode( $t->getNsText() );
524 }
525 static function namespacenumber( $parser, $title = null ) {
526 $t = Title::newFromText( $title );
527 if ( is_null( $t ) ) {
528 return '';
529 }
530 return $t->getNamespace();
531 }
532 static function talkspace( $parser, $title = null ) {
533 $t = Title::newFromText( $title );
534 if ( is_null( $t ) || !$t->canTalk() ) {
535 return '';
536 }
537 return str_replace( '_', ' ', $t->getTalkNsText() );
538 }
539 static function talkspacee( $parser, $title = null ) {
540 $t = Title::newFromText( $title );
541 if ( is_null( $t ) || !$t->canTalk() ) {
542 return '';
543 }
544 return wfUrlencode( $t->getTalkNsText() );
545 }
546 static function subjectspace( $parser, $title = null ) {
547 $t = Title::newFromText( $title );
548 if ( is_null( $t ) ) {
549 return '';
550 }
551 return str_replace( '_', ' ', $t->getSubjectNsText() );
552 }
553 static function subjectspacee( $parser, $title = null ) {
554 $t = Title::newFromText( $title );
555 if ( is_null( $t ) ) {
556 return '';
557 }
558 return wfUrlencode( $t->getSubjectNsText() );
559 }
560
561 /**
562 * Functions to get and normalize pagenames, corresponding to the magic words
563 * of the same names
564 * @param Parser $parser
565 * @param string $title
566 * @return string
567 */
568 static function pagename( $parser, $title = null ) {
569 $t = Title::newFromText( $title );
570 if ( is_null( $t ) ) {
571 return '';
572 }
573 return wfEscapeWikiText( $t->getText() );
574 }
575 static function pagenamee( $parser, $title = null ) {
576 $t = Title::newFromText( $title );
577 if ( is_null( $t ) ) {
578 return '';
579 }
580 return wfEscapeWikiText( $t->getPartialURL() );
581 }
582 static function fullpagename( $parser, $title = null ) {
583 $t = Title::newFromText( $title );
584 if ( is_null( $t ) || !$t->canTalk() ) {
585 return '';
586 }
587 return wfEscapeWikiText( $t->getPrefixedText() );
588 }
589 static function fullpagenamee( $parser, $title = null ) {
590 $t = Title::newFromText( $title );
591 if ( is_null( $t ) || !$t->canTalk() ) {
592 return '';
593 }
594 return wfEscapeWikiText( $t->getPrefixedURL() );
595 }
596 static function subpagename( $parser, $title = null ) {
597 $t = Title::newFromText( $title );
598 if ( is_null( $t ) ) {
599 return '';
600 }
601 return wfEscapeWikiText( $t->getSubpageText() );
602 }
603 static function subpagenamee( $parser, $title = null ) {
604 $t = Title::newFromText( $title );
605 if ( is_null( $t ) ) {
606 return '';
607 }
608 return wfEscapeWikiText( $t->getSubpageUrlForm() );
609 }
610 static function rootpagename( $parser, $title = null ) {
611 $t = Title::newFromText( $title );
612 if ( is_null( $t ) ) {
613 return '';
614 }
615 return wfEscapeWikiText( $t->getRootText() );
616 }
617 static function rootpagenamee( $parser, $title = null ) {
618 $t = Title::newFromText( $title );
619 if ( is_null( $t ) ) {
620 return '';
621 }
622 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
623 }
624 static function basepagename( $parser, $title = null ) {
625 $t = Title::newFromText( $title );
626 if ( is_null( $t ) ) {
627 return '';
628 }
629 return wfEscapeWikiText( $t->getBaseText() );
630 }
631 static function basepagenamee( $parser, $title = null ) {
632 $t = Title::newFromText( $title );
633 if ( is_null( $t ) ) {
634 return '';
635 }
636 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
637 }
638 static function talkpagename( $parser, $title = null ) {
639 $t = Title::newFromText( $title );
640 if ( is_null( $t ) || !$t->canTalk() ) {
641 return '';
642 }
643 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
644 }
645 static function talkpagenamee( $parser, $title = null ) {
646 $t = Title::newFromText( $title );
647 if ( is_null( $t ) || !$t->canTalk() ) {
648 return '';
649 }
650 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
651 }
652 static function subjectpagename( $parser, $title = null ) {
653 $t = Title::newFromText( $title );
654 if ( is_null( $t ) ) {
655 return '';
656 }
657 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
658 }
659 static function subjectpagenamee( $parser, $title = null ) {
660 $t = Title::newFromText( $title );
661 if ( is_null( $t ) ) {
662 return '';
663 }
664 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
665 }
666
667 /**
668 * Return the number of pages, files or subcats in the given category,
669 * or 0 if it's nonexistent. This is an expensive parser function and
670 * can't be called too many times per page.
671 * @param Parser $parser
672 * @param string $name
673 * @param string $arg1
674 * @param string $arg2
675 * @return string
676 */
677 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
678 global $wgContLang;
679 static $magicWords = null;
680 if ( is_null( $magicWords ) ) {
681 $magicWords = new MagicWordArray( array(
682 'pagesincategory_all',
683 'pagesincategory_pages',
684 'pagesincategory_subcats',
685 'pagesincategory_files'
686 ) );
687 }
688 static $cache = array();
689
690 // split the given option to its variable
691 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
692 //{{pagesincategory:|raw[|type]}}
693 $raw = $arg1;
694 $type = $magicWords->matchStartToEnd( $arg2 );
695 } else {
696 //{{pagesincategory:[|type[|raw]]}}
697 $type = $magicWords->matchStartToEnd( $arg1 );
698 $raw = $arg2;
699 }
700 if ( !$type ) { //backward compatibility
701 $type = 'pagesincategory_all';
702 }
703
704 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
705 if ( !$title ) { # invalid title
706 return self::formatRaw( 0, $raw );
707 }
708 $wgContLang->findVariantLink( $name, $title, true );
709
710 // Normalize name for cache
711 $name = $title->getDBkey();
712
713 if ( !isset( $cache[$name] ) ) {
714 $category = Category::newFromTitle( $title );
715
716 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
717 if ( $parser->incrementExpensiveFunctionCount() ) {
718 // $allCount is the total number of cat members,
719 // not the count of how many members are normal pages.
720 $allCount = (int)$category->getPageCount();
721 $subcatCount = (int)$category->getSubcatCount();
722 $fileCount = (int)$category->getFileCount();
723 $pagesCount = $allCount - $subcatCount - $fileCount;
724 }
725 $cache[$name]['pagesincategory_all'] = $allCount;
726 $cache[$name]['pagesincategory_pages'] = $pagesCount;
727 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
728 $cache[$name]['pagesincategory_files'] = $fileCount;
729 }
730
731 $count = $cache[$name][$type];
732 return self::formatRaw( $count, $raw );
733 }
734
735 /**
736 * Return the size of the given page, or 0 if it's nonexistent. This is an
737 * expensive parser function and can't be called too many times per page.
738 *
739 * @param Parser $parser
740 * @param string $page Name of page to check (Default: empty string)
741 * @param string $raw Should number be human readable with commas or just number
742 * @return string
743 */
744 static function pagesize( $parser, $page = '', $raw = null ) {
745 $title = Title::newFromText( $page );
746
747 if ( !is_object( $title ) ) {
748 return self::formatRaw( 0, $raw );
749 }
750
751 // fetch revision from cache/database and return the value
752 $rev = self::getCachedRevisionObject( $parser, $title );
753 $length = $rev ? $rev->getSize() : 0;
754 return self::formatRaw( $length, $raw );
755 }
756
757 /**
758 * Returns the requested protection level for the current page. This
759 * is an expensive parser function and can't be called too many times
760 * per page, unless the protection levels for the given title have
761 * already been retrieved
762 *
763 * @param Parser $parser
764 * @param string $type
765 * @param string $title
766 *
767 * @return string
768 */
769 static function protectionlevel( $parser, $type = '', $title = '' ) {
770 $titleObject = Title::newFromText( $title );
771 if ( !( $titleObject instanceof Title ) ) {
772 $titleObject = $parser->mTitle;
773 }
774 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
775 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
776 # Title::getRestrictions returns an array, its possible it may have
777 # multiple values in the future
778 return implode( $restrictions, ',' );
779 }
780 return '';
781 }
782
783 /**
784 * Gives language names.
785 * @param Parser $parser
786 * @param string $code Language code (of which to get name)
787 * @param string $inLanguage Language code (in which to get name)
788 * @return string
789 */
790 static function language( $parser, $code = '', $inLanguage = '' ) {
791 $code = strtolower( $code );
792 $inLanguage = strtolower( $inLanguage );
793 $lang = Language::fetchLanguageName( $code, $inLanguage );
794 return $lang !== '' ? $lang : wfBCP47( $code );
795 }
796
797 /**
798 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
799 * @param Parser $parser
800 * @param string $string
801 * @param int $length
802 * @param string $padding
803 * @param int $direction
804 * @return string
805 */
806 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
807 $padding = $parser->killMarkers( $padding );
808 $lengthOfPadding = mb_strlen( $padding );
809 if ( $lengthOfPadding == 0 ) {
810 return $string;
811 }
812
813 # The remaining length to add counts down to 0 as padding is added
814 $length = min( $length, 500 ) - mb_strlen( $string );
815 # $finalPadding is just $padding repeated enough times so that
816 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
817 $finalPadding = '';
818 while ( $length > 0 ) {
819 # If $length < $lengthofPadding, truncate $padding so we get the
820 # exact length desired.
821 $finalPadding .= mb_substr( $padding, 0, $length );
822 $length -= $lengthOfPadding;
823 }
824
825 if ( $direction == STR_PAD_LEFT ) {
826 return $finalPadding . $string;
827 } else {
828 return $string . $finalPadding;
829 }
830 }
831
832 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
833 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
834 }
835
836 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
837 return self::pad( $parser, $string, $length, $padding );
838 }
839
840 /**
841 * @param Parser $parser
842 * @param string $text
843 * @return string
844 */
845 static function anchorencode( $parser, $text ) {
846 $text = $parser->killMarkers( $text );
847 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
848 }
849
850 static function special( $parser, $text ) {
851 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
852 if ( $page ) {
853 $title = SpecialPage::getTitleFor( $page, $subpage );
854 return $title->getPrefixedText();
855 } else {
856 // unknown special page, just use the given text as its title, if at all possible
857 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
858 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
859 }
860 }
861
862 static function speciale( $parser, $text ) {
863 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
864 }
865
866 /**
867 * @param Parser $parser
868 * @param string $text The sortkey to use
869 * @param string $uarg Either "noreplace" or "noerror" (in en)
870 * both suppress errors, and noreplace does nothing if
871 * a default sortkey already exists.
872 * @return string
873 */
874 public static function defaultsort( $parser, $text, $uarg = '' ) {
875 static $magicWords = null;
876 if ( is_null( $magicWords ) ) {
877 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
878 }
879 $arg = $magicWords->matchStartToEnd( $uarg );
880
881 $text = trim( $text );
882 if ( strlen( $text ) == 0 ) {
883 return '';
884 }
885 $old = $parser->getCustomDefaultSort();
886 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
887 $parser->setDefaultSort( $text );
888 }
889
890 if ( $old === false || $old == $text || $arg ) {
891 return '';
892 } else {
893 $converter = $parser->getConverterLanguage()->getConverter();
894 return '<span class="error">' .
895 wfMessage( 'duplicate-defaultsort',
896 // Message should be parsed, but these params should only be escaped.
897 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
898 $converter->markNoConversion( wfEscapeWikiText( $text ) )
899 )->inContentLanguage()->text() .
900 '</span>';
901 }
902 }
903
904 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
905 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
906 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
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 array $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 $stripList = $parser->getStripList();
961 if ( !in_array( $tagName, $stripList ) ) {
962 return '<span class="error">' .
963 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
964 '</span>';
965 }
966
967 $attributes = array();
968 foreach ( $args as $arg ) {
969 $bits = $arg->splitArg();
970 if ( strval( $bits['index'] ) === '' ) {
971 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
972 $value = trim( $frame->expand( $bits['value'] ) );
973 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
974 $value = isset( $m[1] ) ? $m[1] : '';
975 }
976 $attributes[$name] = $value;
977 }
978 }
979
980 $params = array(
981 'name' => $tagName,
982 'inner' => $inner,
983 'attributes' => $attributes,
984 'close' => "</$tagName>",
985 );
986 return $parser->extensionSubstitution( $params, $frame );
987 }
988
989 /**
990 * Fetched the current revision of the given title and return this.
991 * Will increment the expensive function count and
992 * add a template link to get the value refreshed on changes.
993 * For a given title, which is equal to the current parser title,
994 * the revision object from the parser is used, when that is the current one
995 *
996 * @param Parser $parser
997 * @param Title $title
998 * @return Revision
999 * @since 1.23
1000 */
1001 private static function getCachedRevisionObject( $parser, $title = null ) {
1002 static $cache = array();
1003
1004 if ( is_null( $title ) ) {
1005 return null;
1006 }
1007
1008 // Use the revision from the parser itself, when param is the current page
1009 // and the revision is the current one
1010 if ( $title->equals( $parser->getTitle() ) ) {
1011 $parserRev = $parser->getRevisionObject();
1012 if ( $parserRev && $parserRev->isCurrent() ) {
1013 // force reparse after edit with vary-revision flag
1014 $parser->getOutput()->setFlag( 'vary-revision' );
1015 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
1016 return $parserRev;
1017 }
1018 }
1019
1020 // Normalize name for cache
1021 $page = $title->getPrefixedDBkey();
1022
1023 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
1024 return $cache[$page];
1025 }
1026 if ( $parser->incrementExpensiveFunctionCount() ) {
1027 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
1028 $pageID = $rev ? $rev->getPage() : 0;
1029 $revID = $rev ? $rev->getId() : 0;
1030 $cache[$page] = $rev; // maybe null
1031
1032 // Register dependency in templatelinks
1033 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1034
1035 return $rev;
1036 }
1037 $cache[$page] = null;
1038 return null;
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 }