Fixed some @params documentation (includes/parser)
[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
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 string $username
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 string $value Value to match
413 * @return bool 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 string $page Name of page to check (Default: empty string)
695 * @param string $raw 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 * @param Parser $parser
754 * @param string $string
755 * @param int $length
756 * @param string $padding
757 * @param int $direction
758 * @return string
759 */
760 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
761 $padding = $parser->killMarkers( $padding );
762 $lengthOfPadding = mb_strlen( $padding );
763 if ( $lengthOfPadding == 0 ) {
764 return $string;
765 }
766
767 # The remaining length to add counts down to 0 as padding is added
768 $length = min( $length, 500 ) - mb_strlen( $string );
769 # $finalPadding is just $padding repeated enough times so that
770 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
771 $finalPadding = '';
772 while ( $length > 0 ) {
773 # If $length < $lengthofPadding, truncate $padding so we get the
774 # exact length desired.
775 $finalPadding .= mb_substr( $padding, 0, $length );
776 $length -= $lengthOfPadding;
777 }
778
779 if ( $direction == STR_PAD_LEFT ) {
780 return $finalPadding . $string;
781 } else {
782 return $string . $finalPadding;
783 }
784 }
785
786 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
787 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
788 }
789
790 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
791 return self::pad( $parser, $string, $length, $padding );
792 }
793
794 /**
795 * @param Parser $parser
796 * @param string $text
797 * @return string
798 */
799 static function anchorencode( $parser, $text ) {
800 $text = $parser->killMarkers( $text );
801 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
802 }
803
804 static function special( $parser, $text ) {
805 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
806 if ( $page ) {
807 $title = SpecialPage::getTitleFor( $page, $subpage );
808 return $title->getPrefixedText();
809 } else {
810 // unknown special page, just use the given text as its title, if at all possible
811 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
812 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
813 }
814 }
815
816 static function speciale( $parser, $text ) {
817 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
818 }
819
820 /**
821 * @param Parser $parser
822 * @param string $text The sortkey to use
823 * @param string $uarg Either "noreplace" or "noerror" (in en)
824 * both suppress errors, and noreplace does nothing if
825 * a default sortkey already exists.
826 * @return string
827 */
828 public static function defaultsort( $parser, $text, $uarg = '' ) {
829 static $magicWords = null;
830 if ( is_null( $magicWords ) ) {
831 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
832 }
833 $arg = $magicWords->matchStartToEnd( $uarg );
834
835 $text = trim( $text );
836 if ( strlen( $text ) == 0 ) {
837 return '';
838 }
839 $old = $parser->getCustomDefaultSort();
840 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
841 $parser->setDefaultSort( $text );
842 }
843
844 if ( $old === false || $old == $text || $arg ) {
845 return '';
846 } else {
847 $converter = $parser->getConverterLanguage()->getConverter();
848 return '<span class="error">' .
849 wfMessage( 'duplicate-defaultsort',
850 // Message should be parsed, but these params should only be escaped.
851 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
852 $converter->markNoConversion( wfEscapeWikiText( $text ) )
853 )->inContentLanguage()->text() .
854 '</span>';
855 }
856 }
857
858 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
859 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
860 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
861 $file = wfFindFile( $name );
862
863 if ( $argA == 'nowiki' ) {
864 // {{filepath: | option [| size] }}
865 $isNowiki = true;
866 $parsedWidthParam = $parser->parseWidthParam( $argB );
867 } else {
868 // {{filepath: [| size [|option]] }}
869 $parsedWidthParam = $parser->parseWidthParam( $argA );
870 $isNowiki = ( $argB == 'nowiki' );
871 }
872
873 if ( $file ) {
874 $url = $file->getFullUrl();
875
876 // If a size is requested...
877 if ( count( $parsedWidthParam ) ) {
878 $mto = $file->transform( $parsedWidthParam );
879 // ... and we can
880 if ( $mto && !$mto->isError() ) {
881 // ... change the URL to point to a thumbnail.
882 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
883 }
884 }
885 if ( $isNowiki ) {
886 return array( $url, 'nowiki' => true );
887 }
888 return $url;
889 } else {
890 return '';
891 }
892 }
893
894 /**
895 * Parser function to extension tag adaptor
896 * @param Parser $parser
897 * @param PPFrame $frame
898 * @param array $args
899 * @return string
900 */
901 public static function tagObj( $parser, $frame, $args ) {
902 if ( !count( $args ) ) {
903 return '';
904 }
905 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
906
907 if ( count( $args ) ) {
908 $inner = $frame->expand( array_shift( $args ) );
909 } else {
910 $inner = null;
911 }
912
913 $stripList = $parser->getStripList();
914 if ( !in_array( $tagName, $stripList ) ) {
915 return '<span class="error">' .
916 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
917 '</span>';
918 }
919
920 $attributes = array();
921 foreach ( $args as $arg ) {
922 $bits = $arg->splitArg();
923 if ( strval( $bits['index'] ) === '' ) {
924 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
925 $value = trim( $frame->expand( $bits['value'] ) );
926 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
927 $value = isset( $m[1] ) ? $m[1] : '';
928 }
929 $attributes[$name] = $value;
930 }
931 }
932
933 $params = array(
934 'name' => $tagName,
935 'inner' => $inner,
936 'attributes' => $attributes,
937 'close' => "</$tagName>",
938 );
939 return $parser->extensionSubstitution( $params, $frame );
940 }
941
942 /**
943 * Fetched the current revision of the given title and return this.
944 * Will increment the expensive function count and
945 * add a template link to get the value refreshed on changes.
946 * For a given title, which is equal to the current parser title,
947 * the revision object from the parser is used, when that is the current one
948 *
949 * @param Parser $parser
950 * @param Title $title
951 * @return Revision
952 * @since 1.23
953 */
954 private static function getCachedRevisionObject( $parser, $title = null ) {
955 static $cache = array();
956
957 if ( is_null( $title ) ) {
958 return null;
959 }
960
961 // Use the revision from the parser itself, when param is the current page
962 // and the revision is the current one
963 if ( $title->equals( $parser->getTitle() ) ) {
964 $parserRev = $parser->getRevisionObject();
965 if ( $parserRev && $parserRev->isCurrent() ) {
966 // force reparse after edit with vary-revision flag
967 $parser->getOutput()->setFlag( 'vary-revision' );
968 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
969 return $parserRev;
970 }
971 }
972
973 // Normalize name for cache
974 $page = $title->getPrefixedDBkey();
975
976 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
977 return $cache[$page];
978 }
979 if ( $parser->incrementExpensiveFunctionCount() ) {
980 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
981 $pageID = $rev ? $rev->getPage() : 0;
982 $revID = $rev ? $rev->getId() : 0;
983 $cache[$page] = $rev; // maybe null
984
985 // Register dependency in templatelinks
986 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
987
988 return $rev;
989 }
990 $cache[$page] = null;
991 return null;
992 }
993
994 /**
995 * Get the pageid of a specified page
996 * @param Parser $parser
997 * @param string $title Title to get the pageid from
998 * @since 1.23
999 */
1000 public static function pageid( $parser, $title = null ) {
1001 $t = Title::newFromText( $title );
1002 if ( is_null( $t ) ) {
1003 return '';
1004 }
1005 // Use title from parser to have correct pageid after edit
1006 if ( $t->equals( $parser->getTitle() ) ) {
1007 $t = $parser->getTitle();
1008 return $t->getArticleID();
1009 }
1010
1011 // These can't have ids
1012 if ( !$t->canExist() || $t->isExternal() ) {
1013 return 0;
1014 }
1015
1016 // Check the link cache, maybe something already looked it up.
1017 $linkCache = LinkCache::singleton();
1018 $pdbk = $t->getPrefixedDBkey();
1019 $id = $linkCache->getGoodLinkID( $pdbk );
1020 if ( $id != 0 ) {
1021 $parser->mOutput->addLink( $t, $id );
1022 return $id;
1023 }
1024 if ( $linkCache->isBadLink( $pdbk ) ) {
1025 $parser->mOutput->addLink( $t, 0 );
1026 return $id;
1027 }
1028
1029 // We need to load it from the DB, so mark expensive
1030 if ( $parser->incrementExpensiveFunctionCount() ) {
1031 $id = $t->getArticleID();
1032 $parser->mOutput->addLink( $t, $id );
1033 return $id;
1034 }
1035 return null;
1036 }
1037
1038 /**
1039 * Get the id from the last revision of a specified page.
1040 * @param Parser $parser
1041 * @param string $title Title to get the id from
1042 * @since 1.23
1043 */
1044 public static function revisionid( $parser, $title = null ) {
1045 $t = Title::newFromText( $title );
1046 if ( is_null( $t ) ) {
1047 return '';
1048 }
1049 // fetch revision from cache/database and return the value
1050 $rev = self::getCachedRevisionObject( $parser, $t );
1051 return $rev ? $rev->getId() : '';
1052 }
1053
1054 /**
1055 * Get the day from the last revision of a specified page.
1056 * @param Parser $parser
1057 * @param string $title Title to get the day from
1058 * @since 1.23
1059 */
1060 public static function revisionday( $parser, $title = null ) {
1061 $t = Title::newFromText( $title );
1062 if ( is_null( $t ) ) {
1063 return '';
1064 }
1065 // fetch revision from cache/database and return the value
1066 $rev = self::getCachedRevisionObject( $parser, $t );
1067 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1068 }
1069
1070 /**
1071 * Get the day with leading zeros from the last revision of a specified page.
1072 * @param Parser $parser
1073 * @param string $title Title to get the day from
1074 * @since 1.23
1075 */
1076 public static function revisionday2( $parser, $title = null ) {
1077 $t = Title::newFromText( $title );
1078 if ( is_null( $t ) ) {
1079 return '';
1080 }
1081 // fetch revision from cache/database and return the value
1082 $rev = self::getCachedRevisionObject( $parser, $t );
1083 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1084 }
1085
1086 /**
1087 * Get the month with leading zeros from the last revision of a specified page.
1088 * @param Parser $parser
1089 * @param string $title Title to get the month from
1090 * @since 1.23
1091 */
1092 public static function revisionmonth( $parser, $title = null ) {
1093 $t = Title::newFromText( $title );
1094 if ( is_null( $t ) ) {
1095 return '';
1096 }
1097 // fetch revision from cache/database and return the value
1098 $rev = self::getCachedRevisionObject( $parser, $t );
1099 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1100 }
1101
1102 /**
1103 * Get the month from the last revision of a specified page.
1104 * @param Parser $parser
1105 * @param string $title Title to get the month from
1106 * @since 1.23
1107 */
1108 public static function revisionmonth1( $parser, $title = null ) {
1109 $t = Title::newFromText( $title );
1110 if ( is_null( $t ) ) {
1111 return '';
1112 }
1113 // fetch revision from cache/database and return the value
1114 $rev = self::getCachedRevisionObject( $parser, $t );
1115 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1116 }
1117
1118 /**
1119 * Get the year from the last revision of a specified page.
1120 * @param Parser $parser
1121 * @param string $title Title to get the year from
1122 * @since 1.23
1123 */
1124 public static function revisionyear( $parser, $title = null ) {
1125 $t = Title::newFromText( $title );
1126 if ( is_null( $t ) ) {
1127 return '';
1128 }
1129 // fetch revision from cache/database and return the value
1130 $rev = self::getCachedRevisionObject( $parser, $t );
1131 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1132 }
1133
1134 /**
1135 * Get the timestamp from the last revision of a specified page.
1136 * @param Parser $parser
1137 * @param string $title Title to get the timestamp from
1138 * @since 1.23
1139 */
1140 public static function revisiontimestamp( $parser, $title = null ) {
1141 $t = Title::newFromText( $title );
1142 if ( is_null( $t ) ) {
1143 return '';
1144 }
1145 // fetch revision from cache/database and return the value
1146 $rev = self::getCachedRevisionObject( $parser, $t );
1147 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1148 }
1149
1150 /**
1151 * Get the user from the last revision of a specified page.
1152 * @param Parser $parser
1153 * @param string $title Title to get the user from
1154 * @since 1.23
1155 */
1156 public static function revisionuser( $parser, $title = null ) {
1157 $t = Title::newFromText( $title );
1158 if ( is_null( $t ) ) {
1159 return '';
1160 }
1161 // fetch revision from cache/database and return the value
1162 $rev = self::getCachedRevisionObject( $parser, $t );
1163 return $rev ? $rev->getUserText() : '';
1164 }
1165
1166 /**
1167 * Returns the sources of any cascading protection acting on a specified page.
1168 * Pages will not return their own title unless they transclude themselves.
1169 * This is an expensive parser function and can't be called too many times per page,
1170 * unless cascading protection sources for the page have already been loaded.
1171 *
1172 * @param Parser $parser
1173 * @param string $title
1174 *
1175 * @return string
1176 * @since 1.23
1177 */
1178 public static function cascadingsources( $parser, $title = '' ) {
1179 $titleObject = Title::newFromText( $title );
1180 if ( !( $titleObject instanceof Title ) ) {
1181 $titleObject = $parser->mTitle;
1182 }
1183 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1184 || $parser->incrementExpensiveFunctionCount()
1185 ) {
1186 $names = array();
1187 $sources = $titleObject->getCascadeProtectionSources();
1188 foreach ( $sources[0] as $sourceTitle ) {
1189 $names[] = $sourceTitle->getPrefixedText();
1190 }
1191 return implode( $names, '|' );
1192 }
1193 return '';
1194 }
1195
1196 }