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