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