Merge "Several tweaks to the install.php script"
[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
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
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
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
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
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 * @return mixed|string
485 */
486 static function mwnamespace( $parser, $title = null ) {
487 $t = Title::newFromText( $title );
488 if ( is_null( $t ) ) {
489 return '';
490 }
491 return str_replace( '_', ' ', $t->getNsText() );
492 }
493 static function namespacee( $parser, $title = null ) {
494 $t = Title::newFromText( $title );
495 if ( is_null( $t ) ) {
496 return '';
497 }
498 return wfUrlencode( $t->getNsText() );
499 }
500 static function namespacenumber( $parser, $title = null ) {
501 $t = Title::newFromText( $title );
502 if ( is_null( $t ) ) {
503 return '';
504 }
505 return $t->getNamespace();
506 }
507 static function talkspace( $parser, $title = null ) {
508 $t = Title::newFromText( $title );
509 if ( is_null( $t ) || !$t->canTalk() ) {
510 return '';
511 }
512 return str_replace( '_', ' ', $t->getTalkNsText() );
513 }
514 static function talkspacee( $parser, $title = null ) {
515 $t = Title::newFromText( $title );
516 if ( is_null( $t ) || !$t->canTalk() ) {
517 return '';
518 }
519 return wfUrlencode( $t->getTalkNsText() );
520 }
521 static function subjectspace( $parser, $title = null ) {
522 $t = Title::newFromText( $title );
523 if ( is_null( $t ) ) {
524 return '';
525 }
526 return str_replace( '_', ' ', $t->getSubjectNsText() );
527 }
528 static function subjectspacee( $parser, $title = null ) {
529 $t = Title::newFromText( $title );
530 if ( is_null( $t ) ) {
531 return '';
532 }
533 return wfUrlencode( $t->getSubjectNsText() );
534 }
535
536 /**
537 * Functions to get and normalize pagenames, corresponding to the magic words
538 * of the same names
539 * @return string
540 */
541 static function pagename( $parser, $title = null ) {
542 $t = Title::newFromText( $title );
543 if ( is_null( $t ) ) {
544 return '';
545 }
546 return wfEscapeWikiText( $t->getText() );
547 }
548 static function pagenamee( $parser, $title = null ) {
549 $t = Title::newFromText( $title );
550 if ( is_null( $t ) ) {
551 return '';
552 }
553 return wfEscapeWikiText( $t->getPartialURL() );
554 }
555 static function fullpagename( $parser, $title = null ) {
556 $t = Title::newFromText( $title );
557 if ( is_null( $t ) || !$t->canTalk() ) {
558 return '';
559 }
560 return wfEscapeWikiText( $t->getPrefixedText() );
561 }
562 static function fullpagenamee( $parser, $title = null ) {
563 $t = Title::newFromText( $title );
564 if ( is_null( $t ) || !$t->canTalk() ) {
565 return '';
566 }
567 return wfEscapeWikiText( $t->getPrefixedURL() );
568 }
569 static function subpagename( $parser, $title = null ) {
570 $t = Title::newFromText( $title );
571 if ( is_null( $t ) ) {
572 return '';
573 }
574 return wfEscapeWikiText( $t->getSubpageText() );
575 }
576 static function subpagenamee( $parser, $title = null ) {
577 $t = Title::newFromText( $title );
578 if ( is_null( $t ) ) {
579 return '';
580 }
581 return wfEscapeWikiText( $t->getSubpageUrlForm() );
582 }
583 static function rootpagename( $parser, $title = null ) {
584 $t = Title::newFromText( $title );
585 if ( is_null( $t ) ) {
586 return '';
587 }
588 return wfEscapeWikiText( $t->getRootText() );
589 }
590 static function rootpagenamee( $parser, $title = null ) {
591 $t = Title::newFromText( $title );
592 if ( is_null( $t ) ) {
593 return '';
594 }
595 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
596 }
597 static function basepagename( $parser, $title = null ) {
598 $t = Title::newFromText( $title );
599 if ( is_null( $t ) ) {
600 return '';
601 }
602 return wfEscapeWikiText( $t->getBaseText() );
603 }
604 static function basepagenamee( $parser, $title = null ) {
605 $t = Title::newFromText( $title );
606 if ( is_null( $t ) ) {
607 return '';
608 }
609 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
610 }
611 static function talkpagename( $parser, $title = null ) {
612 $t = Title::newFromText( $title );
613 if ( is_null( $t ) || !$t->canTalk() ) {
614 return '';
615 }
616 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
617 }
618 static function talkpagenamee( $parser, $title = null ) {
619 $t = Title::newFromText( $title );
620 if ( is_null( $t ) || !$t->canTalk() ) {
621 return '';
622 }
623 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
624 }
625 static function subjectpagename( $parser, $title = null ) {
626 $t = Title::newFromText( $title );
627 if ( is_null( $t ) ) {
628 return '';
629 }
630 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
631 }
632 static function subjectpagenamee( $parser, $title = null ) {
633 $t = Title::newFromText( $title );
634 if ( is_null( $t ) ) {
635 return '';
636 }
637 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
638 }
639
640 /**
641 * Return the number of pages, files or subcats in the given category,
642 * or 0 if it's nonexistent. This is an expensive parser function and
643 * can't be called too many times per page.
644 * @return string
645 */
646 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
647 global $wgContLang;
648 static $magicWords = null;
649 if ( is_null( $magicWords ) ) {
650 $magicWords = new MagicWordArray( array(
651 'pagesincategory_all',
652 'pagesincategory_pages',
653 'pagesincategory_subcats',
654 'pagesincategory_files'
655 ) );
656 }
657 static $cache = array();
658
659 // split the given option to its variable
660 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
661 //{{pagesincategory:|raw[|type]}}
662 $raw = $arg1;
663 $type = $magicWords->matchStartToEnd( $arg2 );
664 } else {
665 //{{pagesincategory:[|type[|raw]]}}
666 $type = $magicWords->matchStartToEnd( $arg1 );
667 $raw = $arg2;
668 }
669 if ( !$type ) { //backward compatibility
670 $type = 'pagesincategory_all';
671 }
672
673 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
674 if ( !$title ) { # invalid title
675 return self::formatRaw( 0, $raw );
676 }
677 $wgContLang->findVariantLink( $name, $title, true );
678
679 // Normalize name for cache
680 $name = $title->getDBkey();
681
682 if ( !isset( $cache[$name] ) ) {
683 $category = Category::newFromTitle( $title );
684
685 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
686 if ( $parser->incrementExpensiveFunctionCount() ) {
687 // $allCount is the total number of cat members,
688 // not the count of how many members are normal pages.
689 $allCount = (int)$category->getPageCount();
690 $subcatCount = (int)$category->getSubcatCount();
691 $fileCount = (int)$category->getFileCount();
692 $pagesCount = $allCount - $subcatCount - $fileCount;
693 }
694 $cache[$name]['pagesincategory_all'] = $allCount;
695 $cache[$name]['pagesincategory_pages'] = $pagesCount;
696 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
697 $cache[$name]['pagesincategory_files'] = $fileCount;
698 }
699
700 $count = $cache[$name][$type];
701 return self::formatRaw( $count, $raw );
702 }
703
704 /**
705 * Return the size of the given page, or 0 if it's nonexistent. This is an
706 * expensive parser function and can't be called too many times per page.
707 *
708 * @param Parser $parser
709 * @param string $page Name of page to check (Default: empty string)
710 * @param string $raw Should number be human readable with commas or just number
711 * @return string
712 */
713 static function pagesize( $parser, $page = '', $raw = null ) {
714 $title = Title::newFromText( $page );
715
716 if ( !is_object( $title ) ) {
717 return self::formatRaw( 0, $raw );
718 }
719
720 // fetch revision from cache/database and return the value
721 $rev = self::getCachedRevisionObject( $parser, $title );
722 $length = $rev ? $rev->getSize() : 0;
723 return self::formatRaw( $length, $raw );
724 }
725
726 /**
727 * Returns the requested protection level for the current page. This
728 * is an expensive parser function and can't be called too many times
729 * per page, unless the protection levels for the given title have
730 * already been retrieved
731 *
732 * @param Parser $parser
733 * @param string $type
734 * @param string $title
735 *
736 * @return string
737 */
738 static function protectionlevel( $parser, $type = '', $title = '' ) {
739 $titleObject = Title::newFromText( $title );
740 if ( !( $titleObject instanceof Title ) ) {
741 $titleObject = $parser->mTitle;
742 }
743 if ( $titleObject->areRestrictionsLoaded() || $parser->incrementExpensiveFunctionCount() ) {
744 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
745 # Title::getRestrictions returns an array, its possible it may have
746 # multiple values in the future
747 return implode( $restrictions, ',' );
748 }
749 return '';
750 }
751
752 /**
753 * Gives language names.
754 * @param Parser $parser
755 * @param string $code Language code (of which to get name)
756 * @param string $inLanguage Language code (in which to get name)
757 * @return string
758 */
759 static function language( $parser, $code = '', $inLanguage = '' ) {
760 $code = strtolower( $code );
761 $inLanguage = strtolower( $inLanguage );
762 $lang = Language::fetchLanguageName( $code, $inLanguage );
763 return $lang !== '' ? $lang : wfBCP47( $code );
764 }
765
766 /**
767 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
768 * @param Parser $parser
769 * @param string $string
770 * @param int $length
771 * @param string $padding
772 * @param int $direction
773 * @return string
774 */
775 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
776 $padding = $parser->killMarkers( $padding );
777 $lengthOfPadding = mb_strlen( $padding );
778 if ( $lengthOfPadding == 0 ) {
779 return $string;
780 }
781
782 # The remaining length to add counts down to 0 as padding is added
783 $length = min( $length, 500 ) - mb_strlen( $string );
784 # $finalPadding is just $padding repeated enough times so that
785 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
786 $finalPadding = '';
787 while ( $length > 0 ) {
788 # If $length < $lengthofPadding, truncate $padding so we get the
789 # exact length desired.
790 $finalPadding .= mb_substr( $padding, 0, $length );
791 $length -= $lengthOfPadding;
792 }
793
794 if ( $direction == STR_PAD_LEFT ) {
795 return $finalPadding . $string;
796 } else {
797 return $string . $finalPadding;
798 }
799 }
800
801 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
802 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
803 }
804
805 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
806 return self::pad( $parser, $string, $length, $padding );
807 }
808
809 /**
810 * @param Parser $parser
811 * @param string $text
812 * @return string
813 */
814 static function anchorencode( $parser, $text ) {
815 $text = $parser->killMarkers( $text );
816 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
817 }
818
819 static function special( $parser, $text ) {
820 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
821 if ( $page ) {
822 $title = SpecialPage::getTitleFor( $page, $subpage );
823 return $title->getPrefixedText();
824 } else {
825 // unknown special page, just use the given text as its title, if at all possible
826 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
827 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
828 }
829 }
830
831 static function speciale( $parser, $text ) {
832 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
833 }
834
835 /**
836 * @param Parser $parser
837 * @param string $text The sortkey to use
838 * @param string $uarg Either "noreplace" or "noerror" (in en)
839 * both suppress errors, and noreplace does nothing if
840 * a default sortkey already exists.
841 * @return string
842 */
843 public static function defaultsort( $parser, $text, $uarg = '' ) {
844 static $magicWords = null;
845 if ( is_null( $magicWords ) ) {
846 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
847 }
848 $arg = $magicWords->matchStartToEnd( $uarg );
849
850 $text = trim( $text );
851 if ( strlen( $text ) == 0 ) {
852 return '';
853 }
854 $old = $parser->getCustomDefaultSort();
855 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
856 $parser->setDefaultSort( $text );
857 }
858
859 if ( $old === false || $old == $text || $arg ) {
860 return '';
861 } else {
862 $converter = $parser->getConverterLanguage()->getConverter();
863 return '<span class="error">' .
864 wfMessage( 'duplicate-defaultsort',
865 // Message should be parsed, but these params should only be escaped.
866 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
867 $converter->markNoConversion( wfEscapeWikiText( $text ) )
868 )->inContentLanguage()->text() .
869 '</span>';
870 }
871 }
872
873 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}}
874 // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}},
875 // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}.
876 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
877 $file = wfFindFile( $name );
878
879 if ( $argA == 'nowiki' ) {
880 // {{filepath: | option [| size] }}
881 $isNowiki = true;
882 $parsedWidthParam = $parser->parseWidthParam( $argB );
883 } else {
884 // {{filepath: [| size [|option]] }}
885 $parsedWidthParam = $parser->parseWidthParam( $argA );
886 $isNowiki = ( $argB == 'nowiki' );
887 }
888
889 if ( $file ) {
890 $url = $file->getFullUrl();
891
892 // If a size is requested...
893 if ( count( $parsedWidthParam ) ) {
894 $mto = $file->transform( $parsedWidthParam );
895 // ... and we can
896 if ( $mto && !$mto->isError() ) {
897 // ... change the URL to point to a thumbnail.
898 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
899 }
900 }
901 if ( $isNowiki ) {
902 return array( $url, 'nowiki' => true );
903 }
904 return $url;
905 } else {
906 return '';
907 }
908 }
909
910 /**
911 * Parser function to extension tag adaptor
912 * @param Parser $parser
913 * @param PPFrame $frame
914 * @param array $args
915 * @return string
916 */
917 public static function tagObj( $parser, $frame, $args ) {
918 if ( !count( $args ) ) {
919 return '';
920 }
921 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
922
923 if ( count( $args ) ) {
924 $inner = $frame->expand( array_shift( $args ) );
925 } else {
926 $inner = null;
927 }
928
929 $stripList = $parser->getStripList();
930 if ( !in_array( $tagName, $stripList ) ) {
931 return '<span class="error">' .
932 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
933 '</span>';
934 }
935
936 $attributes = array();
937 foreach ( $args as $arg ) {
938 $bits = $arg->splitArg();
939 if ( strval( $bits['index'] ) === '' ) {
940 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
941 $value = trim( $frame->expand( $bits['value'] ) );
942 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
943 $value = isset( $m[1] ) ? $m[1] : '';
944 }
945 $attributes[$name] = $value;
946 }
947 }
948
949 $params = array(
950 'name' => $tagName,
951 'inner' => $inner,
952 'attributes' => $attributes,
953 'close' => "</$tagName>",
954 );
955 return $parser->extensionSubstitution( $params, $frame );
956 }
957
958 /**
959 * Fetched the current revision of the given title and return this.
960 * Will increment the expensive function count and
961 * add a template link to get the value refreshed on changes.
962 * For a given title, which is equal to the current parser title,
963 * the revision object from the parser is used, when that is the current one
964 *
965 * @param Parser $parser
966 * @param Title $title
967 * @return Revision
968 * @since 1.23
969 */
970 private static function getCachedRevisionObject( $parser, $title = null ) {
971 static $cache = array();
972
973 if ( is_null( $title ) ) {
974 return null;
975 }
976
977 // Use the revision from the parser itself, when param is the current page
978 // and the revision is the current one
979 if ( $title->equals( $parser->getTitle() ) ) {
980 $parserRev = $parser->getRevisionObject();
981 if ( $parserRev && $parserRev->isCurrent() ) {
982 // force reparse after edit with vary-revision flag
983 $parser->getOutput()->setFlag( 'vary-revision' );
984 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
985 return $parserRev;
986 }
987 }
988
989 // Normalize name for cache
990 $page = $title->getPrefixedDBkey();
991
992 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
993 return $cache[$page];
994 }
995 if ( $parser->incrementExpensiveFunctionCount() ) {
996 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
997 $pageID = $rev ? $rev->getPage() : 0;
998 $revID = $rev ? $rev->getId() : 0;
999 $cache[$page] = $rev; // maybe null
1000
1001 // Register dependency in templatelinks
1002 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
1003
1004 return $rev;
1005 }
1006 $cache[$page] = null;
1007 return null;
1008 }
1009
1010 /**
1011 * Get the pageid of a specified page
1012 * @param Parser $parser
1013 * @param string $title Title to get the pageid from
1014 * @since 1.23
1015 */
1016 public static function pageid( $parser, $title = null ) {
1017 $t = Title::newFromText( $title );
1018 if ( is_null( $t ) ) {
1019 return '';
1020 }
1021 // Use title from parser to have correct pageid after edit
1022 if ( $t->equals( $parser->getTitle() ) ) {
1023 $t = $parser->getTitle();
1024 return $t->getArticleID();
1025 }
1026
1027 // These can't have ids
1028 if ( !$t->canExist() || $t->isExternal() ) {
1029 return 0;
1030 }
1031
1032 // Check the link cache, maybe something already looked it up.
1033 $linkCache = LinkCache::singleton();
1034 $pdbk = $t->getPrefixedDBkey();
1035 $id = $linkCache->getGoodLinkID( $pdbk );
1036 if ( $id != 0 ) {
1037 $parser->mOutput->addLink( $t, $id );
1038 return $id;
1039 }
1040 if ( $linkCache->isBadLink( $pdbk ) ) {
1041 $parser->mOutput->addLink( $t, 0 );
1042 return $id;
1043 }
1044
1045 // We need to load it from the DB, so mark expensive
1046 if ( $parser->incrementExpensiveFunctionCount() ) {
1047 $id = $t->getArticleID();
1048 $parser->mOutput->addLink( $t, $id );
1049 return $id;
1050 }
1051 return null;
1052 }
1053
1054 /**
1055 * Get the id from the last revision of a specified page.
1056 * @param Parser $parser
1057 * @param string $title Title to get the id from
1058 * @since 1.23
1059 */
1060 public static function revisionid( $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 ? $rev->getId() : '';
1068 }
1069
1070 /**
1071 * Get the day 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 revisionday( $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( 'j' ) : '';
1084 }
1085
1086 /**
1087 * Get the day with leading zeros from the last revision of a specified page.
1088 * @param Parser $parser
1089 * @param string $title Title to get the day from
1090 * @since 1.23
1091 */
1092 public static function revisionday2( $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( 'd' ) : '';
1100 }
1101
1102 /**
1103 * Get the month with leading zeros 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 revisionmonth( $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( 'm' ) : '';
1116 }
1117
1118 /**
1119 * Get the month from the last revision of a specified page.
1120 * @param Parser $parser
1121 * @param string $title Title to get the month from
1122 * @since 1.23
1123 */
1124 public static function revisionmonth1( $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( 'n' ) : '';
1132 }
1133
1134 /**
1135 * Get the year from the last revision of a specified page.
1136 * @param Parser $parser
1137 * @param string $title Title to get the year from
1138 * @since 1.23
1139 */
1140 public static function revisionyear( $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( 'Y' ) : '';
1148 }
1149
1150 /**
1151 * Get the timestamp from the last revision of a specified page.
1152 * @param Parser $parser
1153 * @param string $title Title to get the timestamp from
1154 * @since 1.23
1155 */
1156 public static function revisiontimestamp( $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 ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1164 }
1165
1166 /**
1167 * Get the user from the last revision of a specified page.
1168 * @param Parser $parser
1169 * @param string $title Title to get the user from
1170 * @since 1.23
1171 */
1172 public static function revisionuser( $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 ? $rev->getUserText() : '';
1180 }
1181
1182 /**
1183 * Returns the sources of any cascading protection acting on a specified page.
1184 * Pages will not return their own title unless they transclude themselves.
1185 * This is an expensive parser function and can't be called too many times per page,
1186 * unless cascading protection sources for the page have already been loaded.
1187 *
1188 * @param Parser $parser
1189 * @param string $title
1190 *
1191 * @return string
1192 * @since 1.23
1193 */
1194 public static function cascadingsources( $parser, $title = '' ) {
1195 $titleObject = Title::newFromText( $title );
1196 if ( !( $titleObject instanceof Title ) ) {
1197 $titleObject = $parser->mTitle;
1198 }
1199 if ( $titleObject->areCascadeProtectionSourcesLoaded()
1200 || $parser->incrementExpensiveFunctionCount()
1201 ) {
1202 $names = array();
1203 $sources = $titleObject->getCascadeProtectionSources();
1204 foreach ( $sources[0] as $sourceTitle ) {
1205 $names[] = $sourceTitle->getPrefixedText();
1206 }
1207 return implode( $names, '|' );
1208 }
1209 return '';
1210 }
1211
1212 }