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