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