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