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