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