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