Include namespaces in {{CASCADINGSOURCES}} output
[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->getFragment() == '' && $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 if ( strval( $value ) === '' ) {
406 return false;
407 }
408 $mwObject = MagicWord::get( $magicword );
409 return $mwObject->match( $value );
410 }
411
412 static function formatRaw( $num, $raw ) {
413 if ( self::matchAgainstMagicword( 'rawsuffix', $raw ) ) {
414 return $num;
415 } else {
416 global $wgContLang;
417 return $wgContLang->formatNum( $num );
418 }
419 }
420 static function numberofpages( $parser, $raw = null ) {
421 return self::formatRaw( SiteStats::pages(), $raw );
422 }
423 static function numberofusers( $parser, $raw = null ) {
424 return self::formatRaw( SiteStats::users(), $raw );
425 }
426 static function numberofactiveusers( $parser, $raw = null ) {
427 return self::formatRaw( SiteStats::activeUsers(), $raw );
428 }
429 static function numberofarticles( $parser, $raw = null ) {
430 return self::formatRaw( SiteStats::articles(), $raw );
431 }
432 static function numberoffiles( $parser, $raw = null ) {
433 return self::formatRaw( SiteStats::images(), $raw );
434 }
435 static function numberofadmins( $parser, $raw = null ) {
436 return self::formatRaw( SiteStats::numberingroup( 'sysop' ), $raw );
437 }
438 static function numberofedits( $parser, $raw = null ) {
439 return self::formatRaw( SiteStats::edits(), $raw );
440 }
441 static function numberofviews( $parser, $raw = null ) {
442 global $wgDisableCounters;
443 return !$wgDisableCounters ? self::formatRaw( SiteStats::views(), $raw ) : '';
444 }
445 static function pagesinnamespace( $parser, $namespace = 0, $raw = null ) {
446 return self::formatRaw( SiteStats::pagesInNs( intval( $namespace ) ), $raw );
447 }
448 static function numberingroup( $parser, $name = '', $raw = null ) {
449 return self::formatRaw( SiteStats::numberingroup( strtolower( $name ) ), $raw );
450 }
451
452 /**
453 * Given a title, return the namespace name that would be given by the
454 * corresponding magic word
455 * Note: function name changed to "mwnamespace" rather than "namespace"
456 * to not break PHP 5.3
457 * @return mixed|string
458 */
459 static function mwnamespace( $parser, $title = null ) {
460 $t = Title::newFromText( $title );
461 if ( is_null( $t ) ) {
462 return '';
463 }
464 return str_replace( '_', ' ', $t->getNsText() );
465 }
466 static function namespacee( $parser, $title = null ) {
467 $t = Title::newFromText( $title );
468 if ( is_null( $t ) ) {
469 return '';
470 }
471 return wfUrlencode( $t->getNsText() );
472 }
473 static function namespacenumber( $parser, $title = null ) {
474 $t = Title::newFromText( $title );
475 if ( is_null( $t ) ) {
476 return '';
477 }
478 return $t->getNamespace();
479 }
480 static function talkspace( $parser, $title = null ) {
481 $t = Title::newFromText( $title );
482 if ( is_null( $t ) || !$t->canTalk() ) {
483 return '';
484 }
485 return str_replace( '_', ' ', $t->getTalkNsText() );
486 }
487 static function talkspacee( $parser, $title = null ) {
488 $t = Title::newFromText( $title );
489 if ( is_null( $t ) || !$t->canTalk() ) {
490 return '';
491 }
492 return wfUrlencode( $t->getTalkNsText() );
493 }
494 static function subjectspace( $parser, $title = null ) {
495 $t = Title::newFromText( $title );
496 if ( is_null( $t ) ) {
497 return '';
498 }
499 return str_replace( '_', ' ', $t->getSubjectNsText() );
500 }
501 static function subjectspacee( $parser, $title = null ) {
502 $t = Title::newFromText( $title );
503 if ( is_null( $t ) ) {
504 return '';
505 }
506 return wfUrlencode( $t->getSubjectNsText() );
507 }
508
509 /**
510 * Functions to get and normalize pagenames, corresponding to the magic words
511 * of the same names
512 * @return String
513 */
514 static function pagename( $parser, $title = null ) {
515 $t = Title::newFromText( $title );
516 if ( is_null( $t ) ) {
517 return '';
518 }
519 return wfEscapeWikiText( $t->getText() );
520 }
521 static function pagenamee( $parser, $title = null ) {
522 $t = Title::newFromText( $title );
523 if ( is_null( $t ) ) {
524 return '';
525 }
526 return wfEscapeWikiText( $t->getPartialURL() );
527 }
528 static function fullpagename( $parser, $title = null ) {
529 $t = Title::newFromText( $title );
530 if ( is_null( $t ) || !$t->canTalk() ) {
531 return '';
532 }
533 return wfEscapeWikiText( $t->getPrefixedText() );
534 }
535 static function fullpagenamee( $parser, $title = null ) {
536 $t = Title::newFromText( $title );
537 if ( is_null( $t ) || !$t->canTalk() ) {
538 return '';
539 }
540 return wfEscapeWikiText( $t->getPrefixedURL() );
541 }
542 static function subpagename( $parser, $title = null ) {
543 $t = Title::newFromText( $title );
544 if ( is_null( $t ) ) {
545 return '';
546 }
547 return wfEscapeWikiText( $t->getSubpageText() );
548 }
549 static function subpagenamee( $parser, $title = null ) {
550 $t = Title::newFromText( $title );
551 if ( is_null( $t ) ) {
552 return '';
553 }
554 return wfEscapeWikiText( $t->getSubpageUrlForm() );
555 }
556 static function rootpagename( $parser, $title = null ) {
557 $t = Title::newFromText( $title );
558 if ( is_null( $t ) ) {
559 return '';
560 }
561 return wfEscapeWikiText( $t->getRootText() );
562 }
563 static function rootpagenamee( $parser, $title = null ) {
564 $t = Title::newFromText( $title );
565 if ( is_null( $t ) ) {
566 return '';
567 }
568 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getRootText() ) ) );
569 }
570 static function basepagename( $parser, $title = null ) {
571 $t = Title::newFromText( $title );
572 if ( is_null( $t ) ) {
573 return '';
574 }
575 return wfEscapeWikiText( $t->getBaseText() );
576 }
577 static function basepagenamee( $parser, $title = null ) {
578 $t = Title::newFromText( $title );
579 if ( is_null( $t ) ) {
580 return '';
581 }
582 return wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $t->getBaseText() ) ) );
583 }
584 static function talkpagename( $parser, $title = null ) {
585 $t = Title::newFromText( $title );
586 if ( is_null( $t ) || !$t->canTalk() ) {
587 return '';
588 }
589 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedText() );
590 }
591 static function talkpagenamee( $parser, $title = null ) {
592 $t = Title::newFromText( $title );
593 if ( is_null( $t ) || !$t->canTalk() ) {
594 return '';
595 }
596 return wfEscapeWikiText( $t->getTalkPage()->getPrefixedURL() );
597 }
598 static function subjectpagename( $parser, $title = null ) {
599 $t = Title::newFromText( $title );
600 if ( is_null( $t ) ) {
601 return '';
602 }
603 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedText() );
604 }
605 static function subjectpagenamee( $parser, $title = null ) {
606 $t = Title::newFromText( $title );
607 if ( is_null( $t ) ) {
608 return '';
609 }
610 return wfEscapeWikiText( $t->getSubjectPage()->getPrefixedURL() );
611 }
612
613 /**
614 * Return the number of pages, files or subcats in the given category,
615 * or 0 if it's nonexistent. This is an expensive parser function and
616 * can't be called too many times per page.
617 * @return string
618 */
619 static function pagesincategory( $parser, $name = '', $arg1 = null, $arg2 = null ) {
620 global $wgContLang;
621 static $magicWords = null;
622 if ( is_null( $magicWords ) ) {
623 $magicWords = new MagicWordArray( array(
624 'pagesincategory_all',
625 'pagesincategory_pages',
626 'pagesincategory_subcats',
627 'pagesincategory_files'
628 ) );
629 }
630 static $cache = array();
631
632 // split the given option to its variable
633 if ( self::matchAgainstMagicword( 'rawsuffix', $arg1 ) ) {
634 //{{pagesincategory:|raw[|type]}}
635 $raw = $arg1;
636 $type = $magicWords->matchStartToEnd( $arg2 );
637 } else {
638 //{{pagesincategory:[|type[|raw]]}}
639 $type = $magicWords->matchStartToEnd( $arg1 );
640 $raw = $arg2;
641 }
642 if ( !$type ) { //backward compatibility
643 $type = 'pagesincategory_all';
644 }
645
646 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
647 if ( !$title ) { # invalid title
648 return self::formatRaw( 0, $raw );
649 }
650 $wgContLang->findVariantLink( $name, $title, true );
651
652 // Normalize name for cache
653 $name = $title->getDBkey();
654
655 if ( !isset( $cache[$name] ) ) {
656 $category = Category::newFromTitle( $title );
657
658 $allCount = $subcatCount = $fileCount = $pagesCount = 0;
659 if ( $parser->incrementExpensiveFunctionCount() ) {
660 // $allCount is the total number of cat members,
661 // not the count of how many members are normal pages.
662 $allCount = (int)$category->getPageCount();
663 $subcatCount = (int)$category->getSubcatCount();
664 $fileCount = (int)$category->getFileCount();
665 $pagesCount = $allCount - $subcatCount - $fileCount;
666 }
667 $cache[$name]['pagesincategory_all'] = $allCount;
668 $cache[$name]['pagesincategory_pages'] = $pagesCount;
669 $cache[$name]['pagesincategory_subcats'] = $subcatCount;
670 $cache[$name]['pagesincategory_files'] = $fileCount;
671 }
672
673 $count = $cache[$name][$type];
674 return self::formatRaw( $count, $raw );
675 }
676
677 /**
678 * Return the size of the given page, or 0 if it's nonexistent. This is an
679 * expensive parser function and can't be called too many times per page.
680 *
681 * @todo FIXME: Title::getLength() documentation claims that it adds things
682 * to the link cache, so the local cache here should be unnecessary, but
683 * in fact calling getLength() repeatedly for the same $page does seem to
684 * run one query for each call?
685 * @todo Document parameters
686 *
687 * @param $parser Parser
688 * @param $page String Name of page to check (Default: empty string)
689 * @param $raw String Should number be human readable with commas or just number
690 * @return string
691 */
692 static function pagesize( $parser, $page = '', $raw = null ) {
693 $title = Title::newFromText( $page );
694
695 if ( !is_object( $title ) ) {
696 return self::formatRaw( 0, $raw );
697 }
698
699 // fetch revision from cache/database and return the value
700 $rev = self::getCachedRevisionObject( $parser, $title );
701 $length = $rev ? $rev->getSize() : 0;
702 return self::formatRaw( $length, $raw );
703 }
704
705 /**
706 * Returns the requested protection level for the current page
707 *
708 * @param Parser $parser
709 * @param string $type
710 * @param string $title
711 *
712 * @return string
713 */
714 static function protectionlevel( $parser, $type = '', $title = '' ) {
715 $titleObject = Title::newFromText( $title );
716 if ( !( $titleObject instanceof Title ) ) {
717 $titleObject = $parser->mTitle;
718 }
719 $restrictions = $titleObject->getRestrictions( strtolower( $type ) );
720 # Title::getRestrictions returns an array, its possible it may have
721 # multiple values in the future
722 return implode( $restrictions, ',' );
723 }
724
725 /**
726 * Gives language names.
727 * @param $parser Parser
728 * @param string $code Language code (of which to get name)
729 * @param string $inLanguage Language code (in which to get name)
730 * @return String
731 */
732 static function language( $parser, $code = '', $inLanguage = '' ) {
733 $code = strtolower( $code );
734 $inLanguage = strtolower( $inLanguage );
735 $lang = Language::fetchLanguageName( $code, $inLanguage );
736 return $lang !== '' ? $lang : wfBCP47( $code );
737 }
738
739 /**
740 * Unicode-safe str_pad with the restriction that $length is forced to be <= 500
741 * @return string
742 */
743 static function pad( $parser, $string, $length, $padding = '0', $direction = STR_PAD_RIGHT ) {
744 $padding = $parser->killMarkers( $padding );
745 $lengthOfPadding = mb_strlen( $padding );
746 if ( $lengthOfPadding == 0 ) {
747 return $string;
748 }
749
750 # The remaining length to add counts down to 0 as padding is added
751 $length = min( $length, 500 ) - mb_strlen( $string );
752 # $finalPadding is just $padding repeated enough times so that
753 # mb_strlen( $string ) + mb_strlen( $finalPadding ) == $length
754 $finalPadding = '';
755 while ( $length > 0 ) {
756 # If $length < $lengthofPadding, truncate $padding so we get the
757 # exact length desired.
758 $finalPadding .= mb_substr( $padding, 0, $length );
759 $length -= $lengthOfPadding;
760 }
761
762 if ( $direction == STR_PAD_LEFT ) {
763 return $finalPadding . $string;
764 } else {
765 return $string . $finalPadding;
766 }
767 }
768
769 static function padleft( $parser, $string = '', $length = 0, $padding = '0' ) {
770 return self::pad( $parser, $string, $length, $padding, STR_PAD_LEFT );
771 }
772
773 static function padright( $parser, $string = '', $length = 0, $padding = '0' ) {
774 return self::pad( $parser, $string, $length, $padding );
775 }
776
777 /**
778 * @param $parser Parser
779 * @param $text
780 * @return string
781 */
782 static function anchorencode( $parser, $text ) {
783 $text = $parser->killMarkers( $text );
784 return (string)substr( $parser->guessSectionNameFromWikiText( $text ), 1 );
785 }
786
787 static function special( $parser, $text ) {
788 list( $page, $subpage ) = SpecialPageFactory::resolveAlias( $text );
789 if ( $page ) {
790 $title = SpecialPage::getTitleFor( $page, $subpage );
791 return $title->getPrefixedText();
792 } else {
793 // unknown special page, just use the given text as its title, if at all possible
794 $title = Title::makeTitleSafe( NS_SPECIAL, $text );
795 return $title ? $title->getPrefixedText() : self::special( $parser, 'Badtitle' );
796 }
797 }
798
799 static function speciale( $parser, $text ) {
800 return wfUrlencode( str_replace( ' ', '_', self::special( $parser, $text ) ) );
801 }
802
803 /**
804 * @param $parser Parser
805 * @param string $text The sortkey to use
806 * @param string $uarg Either "noreplace" or "noerror" (in en)
807 * both suppress errors, and noreplace does nothing if
808 * a default sortkey already exists.
809 * @return string
810 */
811 public static function defaultsort( $parser, $text, $uarg = '' ) {
812 static $magicWords = null;
813 if ( is_null( $magicWords ) ) {
814 $magicWords = new MagicWordArray( array( 'defaultsort_noerror', 'defaultsort_noreplace' ) );
815 }
816 $arg = $magicWords->matchStartToEnd( $uarg );
817
818 $text = trim( $text );
819 if ( strlen( $text ) == 0 ) {
820 return '';
821 }
822 $old = $parser->getCustomDefaultSort();
823 if ( $old === false || $arg !== 'defaultsort_noreplace' ) {
824 $parser->setDefaultSort( $text );
825 }
826
827 if ( $old === false || $old == $text || $arg ) {
828 return '';
829 } else {
830 $converter = $parser->getConverterLanguage()->getConverter();
831 return '<span class="error">' .
832 wfMessage( 'duplicate-defaultsort',
833 // Message should be parsed, but these params should only be escaped.
834 $converter->markNoConversion( wfEscapeWikiText( $old ) ),
835 $converter->markNoConversion( wfEscapeWikiText( $text ) )
836 )->inContentLanguage()->text() .
837 '</span>';
838 }
839 }
840
841 // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}}
842 // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}
843 public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) {
844 $file = wfFindFile( $name );
845
846 if ( $argA == 'nowiki' ) {
847 // {{filepath: | option [| size] }}
848 $isNowiki = true;
849 $parsedWidthParam = $parser->parseWidthParam( $argB );
850 } else {
851 // {{filepath: [| size [|option]] }}
852 $parsedWidthParam = $parser->parseWidthParam( $argA );
853 $isNowiki = ( $argB == 'nowiki' );
854 }
855
856 if ( $file ) {
857 $url = $file->getFullUrl();
858
859 // If a size is requested...
860 if ( count( $parsedWidthParam ) ) {
861 $mto = $file->transform( $parsedWidthParam );
862 // ... and we can
863 if ( $mto && !$mto->isError() ) {
864 // ... change the URL to point to a thumbnail.
865 $url = wfExpandUrl( $mto->getUrl(), PROTO_RELATIVE );
866 }
867 }
868 if ( $isNowiki ) {
869 return array( $url, 'nowiki' => true );
870 }
871 return $url;
872 } else {
873 return '';
874 }
875 }
876
877 /**
878 * Parser function to extension tag adaptor
879 * @return string
880 */
881 public static function tagObj( $parser, $frame, $args ) {
882 if ( !count( $args ) ) {
883 return '';
884 }
885 $tagName = strtolower( trim( $frame->expand( array_shift( $args ) ) ) );
886
887 if ( count( $args ) ) {
888 $inner = $frame->expand( array_shift( $args ) );
889 } else {
890 $inner = null;
891 }
892
893 $stripList = $parser->getStripList();
894 if ( !in_array( $tagName, $stripList ) ) {
895 return '<span class="error">' .
896 wfMessage( 'unknown_extension_tag', $tagName )->inContentLanguage()->text() .
897 '</span>';
898 }
899
900 $attributes = array();
901 foreach ( $args as $arg ) {
902 $bits = $arg->splitArg();
903 if ( strval( $bits['index'] ) === '' ) {
904 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
905 $value = trim( $frame->expand( $bits['value'] ) );
906 if ( preg_match( '/^(?:["\'](.+)["\']|""|\'\')$/s', $value, $m ) ) {
907 $value = isset( $m[1] ) ? $m[1] : '';
908 }
909 $attributes[$name] = $value;
910 }
911 }
912
913 $params = array(
914 'name' => $tagName,
915 'inner' => $inner,
916 'attributes' => $attributes,
917 'close' => "</$tagName>",
918 );
919 return $parser->extensionSubstitution( $params, $frame );
920 }
921
922 /**
923 * Fetched the current revision of the given title and return this.
924 * Will increment the expensive function count and
925 * add a template link to get the value refreshed on changes.
926 * For a given title, which is equal to the current parser title,
927 * the revision object from the parser is used, when that is the current one
928 *
929 * @param $parser Parser
930 * @param $title Title
931 * @return Revision
932 * @since 1.23
933 */
934 private static function getCachedRevisionObject( $parser, $title = null ) {
935 static $cache = array();
936
937 if ( is_null( $title ) ) {
938 return null;
939 }
940
941 // Use the revision from the parser itself, when param is the current page
942 // and the revision is the current one
943 if ( $title->equals( $parser->getTitle() ) ) {
944 $parserRev = $parser->getRevisionObject();
945 if ( $parserRev && $parserRev->isCurrent() ) {
946 // force reparse after edit with vary-revision flag
947 $parser->getOutput()->setFlag( 'vary-revision' );
948 wfDebug( __METHOD__ . ": use current revision from parser, setting vary-revision...\n" );
949 return $parserRev;
950 }
951 }
952
953 // Normalize name for cache
954 $page = $title->getPrefixedDBkey();
955
956 if ( array_key_exists( $page, $cache ) ) { // cache contains null values
957 return $cache[$page];
958 }
959 if ( $parser->incrementExpensiveFunctionCount() ) {
960 $rev = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
961 $pageID = $rev ? $rev->getPage() : 0;
962 $revID = $rev ? $rev->getId() : 0;
963 $cache[$page] = $rev; // maybe null
964
965 // Register dependency in templatelinks
966 $parser->getOutput()->addTemplate( $title, $pageID, $revID );
967
968 return $rev;
969 }
970 $cache[$page] = null;
971 return null;
972 }
973
974 /**
975 * Get the pageid of a specified page
976 * @param $parser Parser
977 * @param $title string Title to get the pageid from
978 * @since 1.23
979 */
980 public static function pageid( $parser, $title = null ) {
981 $t = Title::newFromText( $title );
982 if ( is_null( $t ) ) {
983 return '';
984 }
985 // Use title from parser to have correct pageid after edit
986 if ( $t->equals( $parser->getTitle() ) ) {
987 $t = $parser->getTitle();
988 }
989 // fetch pageid from cache/database and return the value
990 $pageid = $t->getArticleID();
991 return $pageid ? $pageid : '';
992 }
993
994 /**
995 * Get the id from the last revision of a specified page.
996 * @param $parser Parser
997 * @param $title string Title to get the id from
998 * @since 1.23
999 */
1000 public static function revisionid( $parser, $title = null ) {
1001 $t = Title::newFromText( $title );
1002 if ( is_null( $t ) ) {
1003 return '';
1004 }
1005 // fetch revision from cache/database and return the value
1006 $rev = self::getCachedRevisionObject( $parser, $t );
1007 return $rev ? $rev->getId() : '';
1008 }
1009
1010 /**
1011 * Get the day from the last revision of a specified page.
1012 * @param $parser Parser
1013 * @param $title string Title to get the day from
1014 * @since 1.23
1015 */
1016 public static function revisionday( $parser, $title = null ) {
1017 $t = Title::newFromText( $title );
1018 if ( is_null( $t ) ) {
1019 return '';
1020 }
1021 // fetch revision from cache/database and return the value
1022 $rev = self::getCachedRevisionObject( $parser, $t );
1023 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'j' ) : '';
1024 }
1025
1026 /**
1027 * Get the day with leading zeros from the last revision of a specified page.
1028 * @param $parser Parser
1029 * @param $title string Title to get the day from
1030 * @since 1.23
1031 */
1032 public static function revisionday2( $parser, $title = null ) {
1033 $t = Title::newFromText( $title );
1034 if ( is_null( $t ) ) {
1035 return '';
1036 }
1037 // fetch revision from cache/database and return the value
1038 $rev = self::getCachedRevisionObject( $parser, $t );
1039 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'd' ) : '';
1040 }
1041
1042 /**
1043 * Get the month with leading zeros from the last revision of a specified page.
1044 * @param $parser Parser
1045 * @param $title string Title to get the month from
1046 * @since 1.23
1047 */
1048 public static function revisionmonth( $parser, $title = null ) {
1049 $t = Title::newFromText( $title );
1050 if ( is_null( $t ) ) {
1051 return '';
1052 }
1053 // fetch revision from cache/database and return the value
1054 $rev = self::getCachedRevisionObject( $parser, $t );
1055 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'm' ) : '';
1056 }
1057
1058 /**
1059 * Get the month from the last revision of a specified page.
1060 * @param $parser Parser
1061 * @param $title string Title to get the month from
1062 * @since 1.23
1063 */
1064 public static function revisionmonth1( $parser, $title = null ) {
1065 $t = Title::newFromText( $title );
1066 if ( is_null( $t ) ) {
1067 return '';
1068 }
1069 // fetch revision from cache/database and return the value
1070 $rev = self::getCachedRevisionObject( $parser, $t );
1071 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'n' ) : '';
1072 }
1073
1074 /**
1075 * Get the year from the last revision of a specified page.
1076 * @param $parser Parser
1077 * @param $title string Title to get the year from
1078 * @since 1.23
1079 */
1080 public static function revisionyear( $parser, $title = null ) {
1081 $t = Title::newFromText( $title );
1082 if ( is_null( $t ) ) {
1083 return '';
1084 }
1085 // fetch revision from cache/database and return the value
1086 $rev = self::getCachedRevisionObject( $parser, $t );
1087 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'Y' ) : '';
1088 }
1089
1090 /**
1091 * Get the timestamp from the last revision of a specified page.
1092 * @param $parser Parser
1093 * @param $title string Title to get the timestamp from
1094 * @since 1.23
1095 */
1096 public static function revisiontimestamp( $parser, $title = null ) {
1097 $t = Title::newFromText( $title );
1098 if ( is_null( $t ) ) {
1099 return '';
1100 }
1101 // fetch revision from cache/database and return the value
1102 $rev = self::getCachedRevisionObject( $parser, $t );
1103 return $rev ? MWTimestamp::getLocalInstance( $rev->getTimestamp() )->format( 'YmdHis' ) : '';
1104 }
1105
1106 /**
1107 * Get the user from the last revision of a specified page.
1108 * @param $parser Parser
1109 * @param $title string Title to get the user from
1110 * @since 1.23
1111 */
1112 public static function revisionuser( $parser, $title = null ) {
1113 $t = Title::newFromText( $title );
1114 if ( is_null( $t ) ) {
1115 return '';
1116 }
1117 // fetch revision from cache/database and return the value
1118 $rev = self::getCachedRevisionObject( $parser, $t );
1119 return $rev ? $rev->getUserText() : '';
1120 }
1121
1122 /**
1123 * Returns the sources of any cascading protection acting on a specified page.
1124 * Pages will not return their own title unless they transclude themselves.
1125 * This is an expensive parser function and can't be called too many times per page.
1126 *
1127 * @param Parser $parser
1128 * @param string $title
1129 *
1130 * @return string
1131 * @since 1.23
1132 */
1133 public static function cascadingsources( $parser, $title = '' ) {
1134 $titleObject = Title::newFromText( $title );
1135 if ( !( $titleObject instanceof Title ) ) {
1136 $titleObject = $parser->mTitle;
1137 }
1138 $names = array();
1139 if ( $parser->incrementExpensiveFunctionCount() ) {
1140 $sources = $titleObject->getCascadeProtectionSources();
1141 foreach ( $sources[0] as $sourceTitle ) {
1142 $names[] = $sourceTitle->getPrefixedText();
1143 }
1144 }
1145
1146 return implode( $names, '|' );
1147 }
1148
1149 }