* Move escaping of image gallery captions to ImageGallery::setCaption()
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /**
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
13 */
14 define( 'MW_PARSER_VERSION', '1.6.1' );
15
16 define( 'RLH_FOR_UPDATE', 1 );
17
18 # Allowed values for $mOutputType
19 define( 'OT_HTML', 1 );
20 define( 'OT_WIKI', 2 );
21 define( 'OT_MSG' , 3 );
22 define( 'OT_PREPROCESS', 4 );
23
24 # Flags for setFunctionHook
25 define( 'SFH_NO_HASH', 1 );
26
27 # string parameter for extractTags which will cause it
28 # to strip HTML comments in addition to regular
29 # <XML>-style tags. This should not be anything we
30 # may want to use in wikisyntax
31 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
32
33 # Constants needed for external link processing
34 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
35 # Everything except bracket, space, or control characters
36 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
37 # Including space, but excluding newlines
38 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
39 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
40 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
41 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
42 EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
43 define( 'EXT_IMAGE_REGEX',
44 '/^('.HTTP_PROTOCOLS.')'. # Protocol
45 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
46 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
47 );
48
49 // State constants for the definition list colon extraction
50 define( 'MW_COLON_STATE_TEXT', 0 );
51 define( 'MW_COLON_STATE_TAG', 1 );
52 define( 'MW_COLON_STATE_TAGSTART', 2 );
53 define( 'MW_COLON_STATE_CLOSETAG', 3 );
54 define( 'MW_COLON_STATE_TAGSLASH', 4 );
55 define( 'MW_COLON_STATE_COMMENT', 5 );
56 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
57 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
58
59 /**
60 * PHP Parser
61 *
62 * Processes wiki markup
63 *
64 * <pre>
65 * There are four main entry points into the Parser class:
66 * parse()
67 * produces HTML output
68 * preSaveTransform().
69 * produces altered wiki markup.
70 * transformMsg()
71 * performs brace substitution on MediaWiki messages
72 * preprocess()
73 * removes HTML comments and expands templates
74 *
75 * Globals used:
76 * objects: $wgLang, $wgContLang
77 *
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 *
80 * settings:
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
84 * $wgMaxArticleSize*
85 *
86 * * only within ParserOptions
87 * </pre>
88 *
89 * @package MediaWiki
90 */
91 class Parser
92 {
93 /**#@+
94 * @private
95 */
96 # Persistent:
97 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
98
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
103 var $mIncludeSizes, $mDefaultSort;
104 var $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
108
109 # Temporary
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId, // ID to display in {{REVISIONID}} tags
116 $mRevisionTimestamp, // The timestamp of the specified revision ID
117 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
118
119 /**#@-*/
120
121 /**
122 * Constructor
123 *
124 * @public
125 */
126 function Parser() {
127 $this->mTagHooks = array();
128 $this->mFunctionHooks = array();
129 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
130 $this->mFirstCall = true;
131 }
132
133 /**
134 * Do various kinds of initialisation on the first call of the parser
135 */
136 function firstCallInit() {
137 if ( !$this->mFirstCall ) {
138 return;
139 }
140
141 wfProfileIn( __METHOD__ );
142 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
143
144 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
145
146 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH );
147 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH );
148 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH );
149 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH );
150 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH );
151 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH );
152 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH );
153 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH );
154 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH );
155 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH );
156 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH );
157 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH );
158 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH );
159 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH );
160 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH );
161 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH );
162 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH );
163 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH );
164 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH );
165 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH );
166 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH );
167 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH );
168 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH );
169 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
170 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH );
171
172 if ( $wgAllowDisplayTitle ) {
173 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH );
174 }
175 if ( $wgAllowSlowParserFunctions ) {
176 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH );
177 }
178
179 $this->initialiseVariables();
180 $this->mFirstCall = false;
181 wfProfileOut( __METHOD__ );
182 }
183
184 /**
185 * Clear Parser state
186 *
187 * @private
188 */
189 function clearState() {
190 wfProfileIn( __METHOD__ );
191 if ( $this->mFirstCall ) {
192 $this->firstCallInit();
193 }
194 $this->mOutput = new ParserOutput;
195 $this->mAutonumber = 0;
196 $this->mLastSection = '';
197 $this->mDTopen = false;
198 $this->mIncludeCount = array();
199 $this->mStripState = new StripState;
200 $this->mArgStack = array();
201 $this->mInPre = false;
202 $this->mInterwikiLinkHolders = array(
203 'texts' => array(),
204 'titles' => array()
205 );
206 $this->mLinkHolders = array(
207 'namespaces' => array(),
208 'dbkeys' => array(),
209 'queries' => array(),
210 'texts' => array(),
211 'titles' => array()
212 );
213 $this->mRevisionTimestamp = $this->mRevisionId = null;
214
215 /**
216 * Prefix for temporary replacement strings for the multipass parser.
217 * \x07 should never appear in input as it's disallowed in XML.
218 * Using it at the front also gives us a little extra robustness
219 * since it shouldn't match when butted up against identifier-like
220 * string constructs.
221 */
222 $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
223
224 # Clear these on every parse, bug 4549
225 $this->mTemplates = array();
226 $this->mTemplatePath = array();
227
228 $this->mShowToc = true;
229 $this->mForceTocPosition = false;
230 $this->mIncludeSizes = array(
231 'pre-expand' => 0,
232 'post-expand' => 0,
233 'arg' => 0
234 );
235 $this->mDefaultSort = false;
236
237 wfRunHooks( 'ParserClearState', array( &$this ) );
238 wfProfileOut( __METHOD__ );
239 }
240
241 function setOutputType( $ot ) {
242 $this->mOutputType = $ot;
243 // Shortcut alias
244 $this->ot = array(
245 'html' => $ot == OT_HTML,
246 'wiki' => $ot == OT_WIKI,
247 'msg' => $ot == OT_MSG,
248 'pre' => $ot == OT_PREPROCESS,
249 );
250 }
251
252 /**
253 * Accessor for mUniqPrefix.
254 *
255 * @public
256 */
257 function uniqPrefix() {
258 return $this->mUniqPrefix;
259 }
260
261 /**
262 * Convert wikitext to HTML
263 * Do not call this function recursively.
264 *
265 * @private
266 * @param string $text Text we want to parse
267 * @param Title &$title A title object
268 * @param array $options
269 * @param boolean $linestart
270 * @param boolean $clearState
271 * @param int $revid number to pass in {{REVISIONID}}
272 * @return ParserOutput a ParserOutput
273 */
274 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
275 /**
276 * First pass--just handle <nowiki> sections, pass the rest off
277 * to internalParse() which does all the real work.
278 */
279
280 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
281 $fname = 'Parser::parse-' . wfGetCaller();
282 wfProfileIn( __METHOD__ );
283 wfProfileIn( $fname );
284
285 if ( $clearState ) {
286 $this->clearState();
287 }
288
289 $this->mOptions = $options;
290 $this->mTitle =& $title;
291 $oldRevisionId = $this->mRevisionId;
292 $oldRevisionTimestamp = $this->mRevisionTimestamp;
293 if( $revid !== null ) {
294 $this->mRevisionId = $revid;
295 $this->mRevisionTimestamp = null;
296 }
297 $this->setOutputType( OT_HTML );
298 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
299 $text = $this->strip( $text, $this->mStripState );
300 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
301 $text = $this->internalParse( $text );
302 $text = $this->mStripState->unstripGeneral( $text );
303
304 # Clean up special characters, only run once, next-to-last before doBlockLevels
305 $fixtags = array(
306 # french spaces, last one Guillemet-left
307 # only if there is something before the space
308 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
309 # french spaces, Guillemet-right
310 '/(\\302\\253) /' => '\\1&nbsp;',
311 );
312 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
313
314 # only once and last
315 $text = $this->doBlockLevels( $text, $linestart );
316
317 $this->replaceLinkHolders( $text );
318
319 # the position of the parserConvert() call should not be changed. it
320 # assumes that the links are all replaced and the only thing left
321 # is the <nowiki> mark.
322 # Side-effects: this calls $this->mOutput->setTitleText()
323 $text = $wgContLang->parserConvert( $text, $this );
324
325 $text = $this->mStripState->unstripNoWiki( $text );
326
327 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
328
329 $text = Sanitizer::normalizeCharReferences( $text );
330
331 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
332 $text = Parser::tidy($text);
333 } else {
334 # attempt to sanitize at least some nesting problems
335 # (bug #2702 and quite a few others)
336 $tidyregs = array(
337 # ''Something [http://www.cool.com cool''] -->
338 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
339 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
340 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
341 # fix up an anchor inside another anchor, only
342 # at least for a single single nested link (bug 3695)
343 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
344 '\\1\\2</a>\\3</a>\\1\\4</a>',
345 # fix div inside inline elements- doBlockLevels won't wrap a line which
346 # contains a div, so fix it up here; replace
347 # div with escaped text
348 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
349 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
350 # remove empty italic or bold tag pairs, some
351 # introduced by rules above
352 '/<([bi])><\/\\1>/' => '',
353 );
354
355 $text = preg_replace(
356 array_keys( $tidyregs ),
357 array_values( $tidyregs ),
358 $text );
359 }
360
361 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
362
363 # Information on include size limits, for the benefit of users who try to skirt them
364 if ( max( $this->mIncludeSizes ) > 1000 ) {
365 $max = $this->mOptions->getMaxIncludeSize();
366 $text .= "<!-- \n" .
367 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
368 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
369 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
370 "Maximum: $max bytes\n" .
371 "-->\n";
372 }
373 $this->mOutput->setText( $text );
374 $this->mRevisionId = $oldRevisionId;
375 $this->mRevisionTimestamp = $oldRevisionTimestamp;
376 wfProfileOut( $fname );
377 wfProfileOut( __METHOD__ );
378
379 return $this->mOutput;
380 }
381
382 /**
383 * Recursive parser entry point that can be called from an extension tag
384 * hook.
385 */
386 function recursiveTagParse( $text ) {
387 wfProfileIn( __METHOD__ );
388 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
389 $text = $this->strip( $text, $this->mStripState );
390 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
391 $text = $this->internalParse( $text );
392 wfProfileOut( __METHOD__ );
393 return $text;
394 }
395
396 /**
397 * Expand templates and variables in the text, producing valid, static wikitext.
398 * Also removes comments.
399 */
400 function preprocess( $text, $title, $options ) {
401 wfProfileIn( __METHOD__ );
402 $this->clearState();
403 $this->setOutputType( OT_PREPROCESS );
404 $this->mOptions = $options;
405 $this->mTitle = $title;
406 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
407 $text = $this->strip( $text, $this->mStripState );
408 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
409 if ( $this->mOptions->getRemoveComments() ) {
410 $text = Sanitizer::removeHTMLcomments( $text );
411 }
412 $text = $this->replaceVariables( $text );
413 $text = $this->mStripState->unstripBoth( $text );
414 wfProfileOut( __METHOD__ );
415 return $text;
416 }
417
418 /**
419 * Get a random string
420 *
421 * @private
422 * @static
423 */
424 function getRandomString() {
425 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
426 }
427
428 function &getTitle() { return $this->mTitle; }
429 function getOptions() { return $this->mOptions; }
430
431 function getFunctionLang() {
432 global $wgLang, $wgContLang;
433 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
434 }
435
436 /**
437 * Replaces all occurrences of HTML-style comments and the given tags
438 * in the text with a random marker and returns teh next text. The output
439 * parameter $matches will be an associative array filled with data in
440 * the form:
441 * 'UNIQ-xxxxx' => array(
442 * 'element',
443 * 'tag content',
444 * array( 'param' => 'x' ),
445 * '<element param="x">tag content</element>' ) )
446 *
447 * @param $elements list of element names. Comments are always extracted.
448 * @param $text Source text string.
449 * @param $uniq_prefix
450 *
451 * @private
452 * @static
453 */
454 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
455 static $n = 1;
456 $stripped = '';
457 $matches = array();
458
459 $taglist = implode( '|', $elements );
460 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
461
462 while ( '' != $text ) {
463 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
464 $stripped .= $p[0];
465 if( count( $p ) < 5 ) {
466 break;
467 }
468 if( count( $p ) > 5 ) {
469 // comment
470 $element = $p[4];
471 $attributes = '';
472 $close = '';
473 $inside = $p[5];
474 } else {
475 // tag
476 $element = $p[1];
477 $attributes = $p[2];
478 $close = $p[3];
479 $inside = $p[4];
480 }
481
482 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . '-QINU';
483 $stripped .= $marker;
484
485 if ( $close === '/>' ) {
486 // Empty element tag, <tag />
487 $content = null;
488 $text = $inside;
489 $tail = null;
490 } else {
491 if( $element == '!--' ) {
492 $end = '/(-->)/';
493 } else {
494 $end = "/(<\\/$element\\s*>)/i";
495 }
496 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
497 $content = $q[0];
498 if( count( $q ) < 3 ) {
499 # No end tag -- let it run out to the end of the text.
500 $tail = '';
501 $text = '';
502 } else {
503 $tail = $q[1];
504 $text = $q[2];
505 }
506 }
507
508 $matches[$marker] = array( $element,
509 $content,
510 Sanitizer::decodeTagAttributes( $attributes ),
511 "<$element$attributes$close$content$tail" );
512 }
513 return $stripped;
514 }
515
516 /**
517 * Strips and renders nowiki, pre, math, hiero
518 * If $render is set, performs necessary rendering operations on plugins
519 * Returns the text, and fills an array with data needed in unstrip()
520 *
521 * @param StripState $state
522 *
523 * @param bool $stripcomments when set, HTML comments <!-- like this -->
524 * will be stripped in addition to other tags. This is important
525 * for section editing, where these comments cause confusion when
526 * counting the sections in the wikisource
527 *
528 * @param array dontstrip contains tags which should not be stripped;
529 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
530 *
531 * @private
532 */
533 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
534 global $wgContLang;
535 wfProfileIn( __METHOD__ );
536 $render = ($this->mOutputType == OT_HTML);
537
538 $uniq_prefix = $this->mUniqPrefix;
539 $commentState = new ReplacementArray;
540
541 $elements = array_merge(
542 array( 'nowiki', 'gallery' ),
543 array_keys( $this->mTagHooks ) );
544 global $wgRawHtml;
545 if( $wgRawHtml ) {
546 $elements[] = 'html';
547 }
548 if( $this->mOptions->getUseTeX() ) {
549 $elements[] = 'math';
550 }
551
552 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
553 foreach ( $elements AS $k => $v ) {
554 if ( !in_array ( $v , $dontstrip ) ) continue;
555 unset ( $elements[$k] );
556 }
557
558 $matches = array();
559 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
560
561 foreach( $matches as $marker => $data ) {
562 list( $element, $content, $params, $tag ) = $data;
563 if( $render ) {
564 $tagName = strtolower( $element );
565 wfProfileIn( __METHOD__."-render-$tagName" );
566 switch( $tagName ) {
567 case '!--':
568 // Comment
569 if( substr( $tag, -3 ) == '-->' ) {
570 $output = $tag;
571 } else {
572 // Unclosed comment in input.
573 // Close it so later stripping can remove it
574 $output = "$tag-->";
575 }
576 break;
577 case 'html':
578 if( $wgRawHtml ) {
579 $output = $content;
580 break;
581 }
582 // Shouldn't happen otherwise. :)
583 case 'nowiki':
584 $output = Xml::escapeTagsOnly( $content );
585 break;
586 case 'math':
587 $output = $wgContLang->armourMath( MathRenderer::renderMath( $content ) );
588 break;
589 case 'gallery':
590 $output = $this->renderImageGallery( $content, $params );
591 break;
592 default:
593 if( isset( $this->mTagHooks[$tagName] ) ) {
594 $output = call_user_func_array( $this->mTagHooks[$tagName],
595 array( $content, $params, $this ) );
596 } else {
597 throw new MWException( "Invalid call hook $element" );
598 }
599 }
600 wfProfileOut( __METHOD__."-render-$tagName" );
601 } else {
602 // Just stripping tags; keep the source
603 $output = $tag;
604 }
605
606 // Unstrip the output, because unstrip() is no longer recursive so
607 // it won't do it itself
608 $output = $state->unstripBoth( $output );
609
610 if( !$stripcomments && $element == '!--' ) {
611 $commentState->setPair( $marker, $output );
612 } elseif ( $element == 'html' || $element == 'nowiki' ) {
613 $state->nowiki->setPair( $marker, $output );
614 } else {
615 $state->general->setPair( $marker, $output );
616 }
617 }
618
619 # Unstrip comments unless explicitly told otherwise.
620 # (The comments are always stripped prior to this point, so as to
621 # not invoke any extension tags / parser hooks contained within
622 # a comment.)
623 if ( !$stripcomments ) {
624 // Put them all back and forget them
625 $text = $commentState->replace( $text );
626 }
627
628 wfProfileOut( __METHOD__ );
629 return $text;
630 }
631
632 /**
633 * Restores pre, math, and other extensions removed by strip()
634 *
635 * always call unstripNoWiki() after this one
636 * @private
637 * @deprecated use $this->mStripState->unstrip()
638 */
639 function unstrip( $text, $state ) {
640 return $state->unstripGeneral( $text );
641 }
642
643 /**
644 * Always call this after unstrip() to preserve the order
645 *
646 * @private
647 * @deprecated use $this->mStripState->unstrip()
648 */
649 function unstripNoWiki( $text, $state ) {
650 return $state->unstripNoWiki( $text );
651 }
652
653 /**
654 * @deprecated use $this->mStripState->unstripBoth()
655 */
656 function unstripForHTML( $text ) {
657 return $this->mStripState->unstripBoth( $text );
658 }
659
660 /**
661 * Add an item to the strip state
662 * Returns the unique tag which must be inserted into the stripped text
663 * The tag will be replaced with the original text in unstrip()
664 *
665 * @private
666 */
667 function insertStripItem( $text, &$state ) {
668 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
669 $state->general->setPair( $rnd, $text );
670 return $rnd;
671 }
672
673 /**
674 * Interface with html tidy, used if $wgUseTidy = true.
675 * If tidy isn't able to correct the markup, the original will be
676 * returned in all its glory with a warning comment appended.
677 *
678 * Either the external tidy program or the in-process tidy extension
679 * will be used depending on availability. Override the default
680 * $wgTidyInternal setting to disable the internal if it's not working.
681 *
682 * @param string $text Hideous HTML input
683 * @return string Corrected HTML output
684 * @public
685 * @static
686 */
687 function tidy( $text ) {
688 global $wgTidyInternal;
689 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
690 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
691 '<head><title>test</title></head><body>'.$text.'</body></html>';
692 if( $wgTidyInternal ) {
693 $correctedtext = Parser::internalTidy( $wrappedtext );
694 } else {
695 $correctedtext = Parser::externalTidy( $wrappedtext );
696 }
697 if( is_null( $correctedtext ) ) {
698 wfDebug( "Tidy error detected!\n" );
699 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
700 }
701 return $correctedtext;
702 }
703
704 /**
705 * Spawn an external HTML tidy process and get corrected markup back from it.
706 *
707 * @private
708 * @static
709 */
710 function externalTidy( $text ) {
711 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
712 $fname = 'Parser::externalTidy';
713 wfProfileIn( $fname );
714
715 $cleansource = '';
716 $opts = ' -utf8';
717
718 $descriptorspec = array(
719 0 => array('pipe', 'r'),
720 1 => array('pipe', 'w'),
721 2 => array('file', '/dev/null', 'a')
722 );
723 $pipes = array();
724 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
725 if (is_resource($process)) {
726 // Theoretically, this style of communication could cause a deadlock
727 // here. If the stdout buffer fills up, then writes to stdin could
728 // block. This doesn't appear to happen with tidy, because tidy only
729 // writes to stdout after it's finished reading from stdin. Search
730 // for tidyParseStdin and tidySaveStdout in console/tidy.c
731 fwrite($pipes[0], $text);
732 fclose($pipes[0]);
733 while (!feof($pipes[1])) {
734 $cleansource .= fgets($pipes[1], 1024);
735 }
736 fclose($pipes[1]);
737 proc_close($process);
738 }
739
740 wfProfileOut( $fname );
741
742 if( $cleansource == '' && $text != '') {
743 // Some kind of error happened, so we couldn't get the corrected text.
744 // Just give up; we'll use the source text and append a warning.
745 return null;
746 } else {
747 return $cleansource;
748 }
749 }
750
751 /**
752 * Use the HTML tidy PECL extension to use the tidy library in-process,
753 * saving the overhead of spawning a new process. Currently written to
754 * the PHP 4.3.x version of the extension, may not work on PHP 5.
755 *
756 * 'pear install tidy' should be able to compile the extension module.
757 *
758 * @private
759 * @static
760 */
761 function internalTidy( $text ) {
762 global $wgTidyConf;
763 $fname = 'Parser::internalTidy';
764 wfProfileIn( $fname );
765
766 tidy_load_config( $wgTidyConf );
767 tidy_set_encoding( 'utf8' );
768 tidy_parse_string( $text );
769 tidy_clean_repair();
770 if( tidy_get_status() == 2 ) {
771 // 2 is magic number for fatal error
772 // http://www.php.net/manual/en/function.tidy-get-status.php
773 $cleansource = null;
774 } else {
775 $cleansource = tidy_get_output();
776 }
777 wfProfileOut( $fname );
778 return $cleansource;
779 }
780
781 /**
782 * parse the wiki syntax used to render tables
783 *
784 * @private
785 */
786 function doTableStuff ( $text ) {
787 $fname = 'Parser::doTableStuff';
788 wfProfileIn( $fname );
789
790 $lines = explode ( "\n" , $text );
791 $td_history = array (); // Is currently a td tag open?
792 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
793 $tr_history = array (); // Is currently a tr tag open?
794 $tr_attributes = array (); // history of tr attributes
795 $has_opened_tr = array(); // Did this table open a <tr> element?
796 $indent_level = 0; // indent level of the table
797 foreach ( $lines as $key => $line )
798 {
799 $line = trim ( $line );
800
801 if( $line == '' ) { // empty line, go to next line
802 continue;
803 }
804 $first_character = $line{0};
805 $matches = array();
806
807 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
808 // First check if we are starting a new table
809 $indent_level = strlen( $matches[1] );
810
811 $attributes = $this->mStripState->unstripBoth( $matches[2] );
812 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
813
814 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
815 array_push ( $td_history , false );
816 array_push ( $last_tag_history , '' );
817 array_push ( $tr_history , false );
818 array_push ( $tr_attributes , '' );
819 array_push ( $has_opened_tr , false );
820 } else if ( count ( $td_history ) == 0 ) {
821 // Don't do any of the following
822 continue;
823 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
824 // We are ending a table
825 $line = '</table>' . substr ( $line , 2 );
826 $last_tag = array_pop ( $last_tag_history );
827
828 if ( !array_pop ( $has_opened_tr ) ) {
829 $line = "<tr><td></td></tr>{$line}";
830 }
831
832 if ( array_pop ( $tr_history ) ) {
833 $line = "</tr>{$line}";
834 }
835
836 if ( array_pop ( $td_history ) ) {
837 $line = "</{$last_tag}>{$line}";
838 }
839 array_pop ( $tr_attributes );
840 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
841 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
842 // Now we have a table row
843 $line = preg_replace( '#^\|-+#', '', $line );
844
845 // Whats after the tag is now only attributes
846 $attributes = $this->mStripState->unstripBoth( $line );
847 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
848 array_pop ( $tr_attributes );
849 array_push ( $tr_attributes , $attributes );
850
851 $line = '';
852 $last_tag = array_pop ( $last_tag_history );
853 array_pop ( $has_opened_tr );
854 array_push ( $has_opened_tr , true );
855
856 if ( array_pop ( $tr_history ) ) {
857 $line = '</tr>';
858 }
859
860 if ( array_pop ( $td_history ) ) {
861 $line = "</{$last_tag}>{$line}";
862 }
863
864 $lines[$key] = $line;
865 array_push ( $tr_history , false );
866 array_push ( $td_history , false );
867 array_push ( $last_tag_history , '' );
868 }
869 else if ( $first_character == '|' || $first_character == '!' || substr ( $line , 0 , 2 ) == '|+' ) {
870 // This might be cell elements, td, th or captions
871 if ( substr ( $line , 0 , 2 ) == '|+' ) {
872 $first_character = '+';
873 $line = substr ( $line , 1 );
874 }
875
876 $line = substr ( $line , 1 );
877
878 if ( $first_character == '!' ) {
879 $line = str_replace ( '!!' , '||' , $line );
880 }
881
882 // Split up multiple cells on the same line.
883 // FIXME : This can result in improper nesting of tags processed
884 // by earlier parser steps, but should avoid splitting up eg
885 // attribute values containing literal "||".
886 $cells = StringUtils::explodeMarkup( '||' , $line );
887
888 $lines[$key] = '';
889
890 // Loop through each table cell
891 foreach ( $cells as $cell )
892 {
893 $previous = '';
894 if ( $first_character != '+' )
895 {
896 $tr_after = array_pop ( $tr_attributes );
897 if ( !array_pop ( $tr_history ) ) {
898 $previous = "<tr{$tr_after}>\n";
899 }
900 array_push ( $tr_history , true );
901 array_push ( $tr_attributes , '' );
902 array_pop ( $has_opened_tr );
903 array_push ( $has_opened_tr , true );
904 }
905
906 $last_tag = array_pop ( $last_tag_history );
907
908 if ( array_pop ( $td_history ) ) {
909 $previous = "</{$last_tag}>{$previous}";
910 }
911
912 if ( $first_character == '|' ) {
913 $last_tag = 'td';
914 } else if ( $first_character == '!' ) {
915 $last_tag = 'th';
916 } else if ( $first_character == '+' ) {
917 $last_tag = 'caption';
918 } else {
919 $last_tag = '';
920 }
921
922 array_push ( $last_tag_history , $last_tag );
923
924 // A cell could contain both parameters and data
925 $cell_data = explode ( '|' , $cell , 2 );
926
927 // Bug 553: Note that a '|' inside an invalid link should not
928 // be mistaken as delimiting cell parameters
929 if ( strpos( $cell_data[0], '[[' ) !== false ) {
930 $cell = "{$previous}<{$last_tag}>{$cell}";
931 } else if ( count ( $cell_data ) == 1 )
932 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
933 else {
934 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
935 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
936 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
937 }
938
939 $lines[$key] .= $cell;
940 array_push ( $td_history , true );
941 }
942 }
943 }
944
945 // Closing open td, tr && table
946 while ( count ( $td_history ) > 0 )
947 {
948 if ( array_pop ( $td_history ) ) {
949 $lines[] = '</td>' ;
950 }
951 if ( array_pop ( $tr_history ) ) {
952 $lines[] = '</tr>' ;
953 }
954 if ( !array_pop ( $has_opened_tr ) ) {
955 $lines[] = "<tr><td></td></tr>" ;
956 }
957
958 $lines[] = '</table>' ;
959 }
960
961 $output = implode ( "\n" , $lines ) ;
962
963 // special case: don't return empty table
964 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
965 $output = '';
966 }
967
968 wfProfileOut( $fname );
969
970 return $output;
971 }
972
973 /**
974 * Helper function for parse() that transforms wiki markup into
975 * HTML. Only called for $mOutputType == OT_HTML.
976 *
977 * @private
978 */
979 function internalParse( $text ) {
980 $args = array();
981 $isMain = true;
982 $fname = 'Parser::internalParse';
983 wfProfileIn( $fname );
984
985 # Hook to suspend the parser in this state
986 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
987 wfProfileOut( $fname );
988 return $text ;
989 }
990
991 # Remove <noinclude> tags and <includeonly> sections
992 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
993 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
994 $text = StringUtils::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
995
996 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
997
998 $text = $this->replaceVariables( $text, $args );
999
1000 // Tables need to come after variable replacement for things to work
1001 // properly; putting them before other transformations should keep
1002 // exciting things like link expansions from showing up in surprising
1003 // places.
1004 $text = $this->doTableStuff( $text );
1005
1006 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1007
1008 $text = $this->stripToc( $text );
1009 $this->stripNoGallery( $text );
1010 $text = $this->doHeadings( $text );
1011 if($this->mOptions->getUseDynamicDates()) {
1012 $df =& DateFormatter::getInstance();
1013 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
1014 }
1015 $text = $this->doAllQuotes( $text );
1016 $text = $this->replaceInternalLinks( $text );
1017 $text = $this->replaceExternalLinks( $text );
1018
1019 # replaceInternalLinks may sometimes leave behind
1020 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1021 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
1022
1023 $text = $this->doMagicLinks( $text );
1024 $text = $this->formatHeadings( $text, $isMain );
1025
1026 wfProfileOut( $fname );
1027 return $text;
1028 }
1029
1030 /**
1031 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1032 * magic external links.
1033 *
1034 * @private
1035 */
1036 function &doMagicLinks( &$text ) {
1037 wfProfileIn( __METHOD__ );
1038 $text = preg_replace_callback(
1039 '!(?: # Start cases
1040 <a.*?</a> | # Skip link text
1041 <.*?> | # Skip stuff inside HTML elements
1042 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1043 ISBN\s+(\b # ISBN, capture number as m[2]
1044 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1045 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1046 [0-9Xx] # check digit
1047 \b)
1048 )!x', array( &$this, 'magicLinkCallback' ), $text );
1049 wfProfileOut( __METHOD__ );
1050 return $text;
1051 }
1052
1053 function magicLinkCallback( $m ) {
1054 if ( substr( $m[0], 0, 1 ) == '<' ) {
1055 # Skip HTML element
1056 return $m[0];
1057 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1058 $isbn = $m[2];
1059 $num = strtr( $isbn, array(
1060 '-' => '',
1061 ' ' => '',
1062 'x' => 'X',
1063 ));
1064 $titleObj = SpecialPage::getTitleFor( 'Booksources' );
1065 $text = '<a href="' .
1066 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1067 "\" class=\"internal\">ISBN $isbn</a>";
1068 } else {
1069 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1070 $keyword = 'RFC';
1071 $urlmsg = 'rfcurl';
1072 $id = $m[1];
1073 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1074 $keyword = 'PMID';
1075 $urlmsg = 'pubmedurl';
1076 $id = $m[1];
1077 } else {
1078 throw new MWException( __METHOD__.': unrecognised match type "' .
1079 substr($m[0], 0, 20 ) . '"' );
1080 }
1081
1082 $url = wfMsg( $urlmsg, $id);
1083 $sk =& $this->mOptions->getSkin();
1084 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1085 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1086 }
1087 return $text;
1088 }
1089
1090 /**
1091 * Parse headers and return html
1092 *
1093 * @private
1094 */
1095 function doHeadings( $text ) {
1096 $fname = 'Parser::doHeadings';
1097 wfProfileIn( $fname );
1098 for ( $i = 6; $i >= 1; --$i ) {
1099 $h = str_repeat( '=', $i );
1100 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1101 "<h{$i}>\\1</h{$i}>\\2", $text );
1102 }
1103 wfProfileOut( $fname );
1104 return $text;
1105 }
1106
1107 /**
1108 * Replace single quotes with HTML markup
1109 * @private
1110 * @return string the altered text
1111 */
1112 function doAllQuotes( $text ) {
1113 $fname = 'Parser::doAllQuotes';
1114 wfProfileIn( $fname );
1115 $outtext = '';
1116 $lines = explode( "\n", $text );
1117 foreach ( $lines as $line ) {
1118 $outtext .= $this->doQuotes ( $line ) . "\n";
1119 }
1120 $outtext = substr($outtext, 0,-1);
1121 wfProfileOut( $fname );
1122 return $outtext;
1123 }
1124
1125 /**
1126 * Helper function for doAllQuotes()
1127 * @private
1128 */
1129 function doQuotes( $text ) {
1130 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1131 if ( count( $arr ) == 1 )
1132 return $text;
1133 else
1134 {
1135 # First, do some preliminary work. This may shift some apostrophes from
1136 # being mark-up to being text. It also counts the number of occurrences
1137 # of bold and italics mark-ups.
1138 $i = 0;
1139 $numbold = 0;
1140 $numitalics = 0;
1141 foreach ( $arr as $r )
1142 {
1143 if ( ( $i % 2 ) == 1 )
1144 {
1145 # If there are ever four apostrophes, assume the first is supposed to
1146 # be text, and the remaining three constitute mark-up for bold text.
1147 if ( strlen( $arr[$i] ) == 4 )
1148 {
1149 $arr[$i-1] .= "'";
1150 $arr[$i] = "'''";
1151 }
1152 # If there are more than 5 apostrophes in a row, assume they're all
1153 # text except for the last 5.
1154 else if ( strlen( $arr[$i] ) > 5 )
1155 {
1156 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1157 $arr[$i] = "'''''";
1158 }
1159 # Count the number of occurrences of bold and italics mark-ups.
1160 # We are not counting sequences of five apostrophes.
1161 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1162 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1163 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1164 }
1165 $i++;
1166 }
1167
1168 # If there is an odd number of both bold and italics, it is likely
1169 # that one of the bold ones was meant to be an apostrophe followed
1170 # by italics. Which one we cannot know for certain, but it is more
1171 # likely to be one that has a single-letter word before it.
1172 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1173 {
1174 $i = 0;
1175 $firstsingleletterword = -1;
1176 $firstmultiletterword = -1;
1177 $firstspace = -1;
1178 foreach ( $arr as $r )
1179 {
1180 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1181 {
1182 $x1 = substr ($arr[$i-1], -1);
1183 $x2 = substr ($arr[$i-1], -2, 1);
1184 if ($x1 == ' ') {
1185 if ($firstspace == -1) $firstspace = $i;
1186 } else if ($x2 == ' ') {
1187 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1188 } else {
1189 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1190 }
1191 }
1192 $i++;
1193 }
1194
1195 # If there is a single-letter word, use it!
1196 if ($firstsingleletterword > -1)
1197 {
1198 $arr [ $firstsingleletterword ] = "''";
1199 $arr [ $firstsingleletterword-1 ] .= "'";
1200 }
1201 # If not, but there's a multi-letter word, use that one.
1202 else if ($firstmultiletterword > -1)
1203 {
1204 $arr [ $firstmultiletterword ] = "''";
1205 $arr [ $firstmultiletterword-1 ] .= "'";
1206 }
1207 # ... otherwise use the first one that has neither.
1208 # (notice that it is possible for all three to be -1 if, for example,
1209 # there is only one pentuple-apostrophe in the line)
1210 else if ($firstspace > -1)
1211 {
1212 $arr [ $firstspace ] = "''";
1213 $arr [ $firstspace-1 ] .= "'";
1214 }
1215 }
1216
1217 # Now let's actually convert our apostrophic mush to HTML!
1218 $output = '';
1219 $buffer = '';
1220 $state = '';
1221 $i = 0;
1222 foreach ($arr as $r)
1223 {
1224 if (($i % 2) == 0)
1225 {
1226 if ($state == 'both')
1227 $buffer .= $r;
1228 else
1229 $output .= $r;
1230 }
1231 else
1232 {
1233 if (strlen ($r) == 2)
1234 {
1235 if ($state == 'i')
1236 { $output .= '</i>'; $state = ''; }
1237 else if ($state == 'bi')
1238 { $output .= '</i>'; $state = 'b'; }
1239 else if ($state == 'ib')
1240 { $output .= '</b></i><b>'; $state = 'b'; }
1241 else if ($state == 'both')
1242 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1243 else # $state can be 'b' or ''
1244 { $output .= '<i>'; $state .= 'i'; }
1245 }
1246 else if (strlen ($r) == 3)
1247 {
1248 if ($state == 'b')
1249 { $output .= '</b>'; $state = ''; }
1250 else if ($state == 'bi')
1251 { $output .= '</i></b><i>'; $state = 'i'; }
1252 else if ($state == 'ib')
1253 { $output .= '</b>'; $state = 'i'; }
1254 else if ($state == 'both')
1255 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1256 else # $state can be 'i' or ''
1257 { $output .= '<b>'; $state .= 'b'; }
1258 }
1259 else if (strlen ($r) == 5)
1260 {
1261 if ($state == 'b')
1262 { $output .= '</b><i>'; $state = 'i'; }
1263 else if ($state == 'i')
1264 { $output .= '</i><b>'; $state = 'b'; }
1265 else if ($state == 'bi')
1266 { $output .= '</i></b>'; $state = ''; }
1267 else if ($state == 'ib')
1268 { $output .= '</b></i>'; $state = ''; }
1269 else if ($state == 'both')
1270 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1271 else # ($state == '')
1272 { $buffer = ''; $state = 'both'; }
1273 }
1274 }
1275 $i++;
1276 }
1277 # Now close all remaining tags. Notice that the order is important.
1278 if ($state == 'b' || $state == 'ib')
1279 $output .= '</b>';
1280 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1281 $output .= '</i>';
1282 if ($state == 'bi')
1283 $output .= '</b>';
1284 if ($state == 'both')
1285 $output .= '<b><i>'.$buffer.'</i></b>';
1286 return $output;
1287 }
1288 }
1289
1290 /**
1291 * Replace external links
1292 *
1293 * Note: this is all very hackish and the order of execution matters a lot.
1294 * Make sure to run maintenance/parserTests.php if you change this code.
1295 *
1296 * @private
1297 */
1298 function replaceExternalLinks( $text ) {
1299 global $wgContLang;
1300 $fname = 'Parser::replaceExternalLinks';
1301 wfProfileIn( $fname );
1302
1303 $sk =& $this->mOptions->getSkin();
1304
1305 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1306
1307 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1308
1309 $i = 0;
1310 while ( $i<count( $bits ) ) {
1311 $url = $bits[$i++];
1312 $protocol = $bits[$i++];
1313 $text = $bits[$i++];
1314 $trail = $bits[$i++];
1315
1316 # The characters '<' and '>' (which were escaped by
1317 # removeHTMLtags()) should not be included in
1318 # URLs, per RFC 2396.
1319 $m2 = array();
1320 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1321 $text = substr($url, $m2[0][1]) . ' ' . $text;
1322 $url = substr($url, 0, $m2[0][1]);
1323 }
1324
1325 # If the link text is an image URL, replace it with an <img> tag
1326 # This happened by accident in the original parser, but some people used it extensively
1327 $img = $this->maybeMakeExternalImage( $text );
1328 if ( $img !== false ) {
1329 $text = $img;
1330 }
1331
1332 $dtrail = '';
1333
1334 # Set linktype for CSS - if URL==text, link is essentially free
1335 $linktype = ($text == $url) ? 'free' : 'text';
1336
1337 # No link text, e.g. [http://domain.tld/some.link]
1338 if ( $text == '' ) {
1339 # Autonumber if allowed. See bug #5918
1340 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1341 $text = '[' . ++$this->mAutonumber . ']';
1342 $linktype = 'autonumber';
1343 } else {
1344 # Otherwise just use the URL
1345 $text = htmlspecialchars( $url );
1346 $linktype = 'free';
1347 }
1348 } else {
1349 # Have link text, e.g. [http://domain.tld/some.link text]s
1350 # Check for trail
1351 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1352 }
1353
1354 $text = $wgContLang->markNoConversion($text);
1355
1356 $url = Sanitizer::cleanUrl( $url );
1357
1358 # Process the trail (i.e. everything after this link up until start of the next link),
1359 # replacing any non-bracketed links
1360 $trail = $this->replaceFreeExternalLinks( $trail );
1361
1362 # Use the encoded URL
1363 # This means that users can paste URLs directly into the text
1364 # Funny characters like &ouml; aren't valid in URLs anyway
1365 # This was changed in August 2004
1366 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1367
1368 # Register link in the output object.
1369 # Replace unnecessary URL escape codes with the referenced character
1370 # This prevents spammers from hiding links from the filters
1371 $pasteurized = Parser::replaceUnusualEscapes( $url );
1372 $this->mOutput->addExternalLink( $pasteurized );
1373 }
1374
1375 wfProfileOut( $fname );
1376 return $s;
1377 }
1378
1379 /**
1380 * Replace anything that looks like a URL with a link
1381 * @private
1382 */
1383 function replaceFreeExternalLinks( $text ) {
1384 global $wgContLang;
1385 $fname = 'Parser::replaceFreeExternalLinks';
1386 wfProfileIn( $fname );
1387
1388 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1389 $s = array_shift( $bits );
1390 $i = 0;
1391
1392 $sk =& $this->mOptions->getSkin();
1393
1394 while ( $i < count( $bits ) ){
1395 $protocol = $bits[$i++];
1396 $remainder = $bits[$i++];
1397
1398 $m = array();
1399 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1400 # Found some characters after the protocol that look promising
1401 $url = $protocol . $m[1];
1402 $trail = $m[2];
1403
1404 # special case: handle urls as url args:
1405 # http://www.example.com/foo?=http://www.example.com/bar
1406 if(strlen($trail) == 0 &&
1407 isset($bits[$i]) &&
1408 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1409 preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1410 {
1411 # add protocol, arg
1412 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1413 $i += 2;
1414 $trail = $m[2];
1415 }
1416
1417 # The characters '<' and '>' (which were escaped by
1418 # removeHTMLtags()) should not be included in
1419 # URLs, per RFC 2396.
1420 $m2 = array();
1421 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1422 $trail = substr($url, $m2[0][1]) . $trail;
1423 $url = substr($url, 0, $m2[0][1]);
1424 }
1425
1426 # Move trailing punctuation to $trail
1427 $sep = ',;\.:!?';
1428 # If there is no left bracket, then consider right brackets fair game too
1429 if ( strpos( $url, '(' ) === false ) {
1430 $sep .= ')';
1431 }
1432
1433 $numSepChars = strspn( strrev( $url ), $sep );
1434 if ( $numSepChars ) {
1435 $trail = substr( $url, -$numSepChars ) . $trail;
1436 $url = substr( $url, 0, -$numSepChars );
1437 }
1438
1439 $url = Sanitizer::cleanUrl( $url );
1440
1441 # Is this an external image?
1442 $text = $this->maybeMakeExternalImage( $url );
1443 if ( $text === false ) {
1444 # Not an image, make a link
1445 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1446 # Register it in the output object...
1447 # Replace unnecessary URL escape codes with their equivalent characters
1448 $pasteurized = Parser::replaceUnusualEscapes( $url );
1449 $this->mOutput->addExternalLink( $pasteurized );
1450 }
1451 $s .= $text . $trail;
1452 } else {
1453 $s .= $protocol . $remainder;
1454 }
1455 }
1456 wfProfileOut( $fname );
1457 return $s;
1458 }
1459
1460 /**
1461 * Replace unusual URL escape codes with their equivalent characters
1462 * @param string
1463 * @return string
1464 * @static
1465 * @fixme This can merge genuinely required bits in the path or query string,
1466 * breaking legit URLs. A proper fix would treat the various parts of
1467 * the URL differently; as a workaround, just use the output for
1468 * statistical records, not for actual linking/output.
1469 */
1470 static function replaceUnusualEscapes( $url ) {
1471 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1472 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1473 }
1474
1475 /**
1476 * Callback function used in replaceUnusualEscapes().
1477 * Replaces unusual URL escape codes with their equivalent character
1478 * @static
1479 * @private
1480 */
1481 private static function replaceUnusualEscapesCallback( $matches ) {
1482 $char = urldecode( $matches[0] );
1483 $ord = ord( $char );
1484 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1485 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1486 // No, shouldn't be escaped
1487 return $char;
1488 } else {
1489 // Yes, leave it escaped
1490 return $matches[0];
1491 }
1492 }
1493
1494 /**
1495 * make an image if it's allowed, either through the global
1496 * option or through the exception
1497 * @private
1498 */
1499 function maybeMakeExternalImage( $url ) {
1500 $sk =& $this->mOptions->getSkin();
1501 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1502 $imagesexception = !empty($imagesfrom);
1503 $text = false;
1504 if ( $this->mOptions->getAllowExternalImages()
1505 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1506 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1507 # Image found
1508 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1509 }
1510 }
1511 return $text;
1512 }
1513
1514 /**
1515 * Process [[ ]] wikilinks
1516 *
1517 * @private
1518 */
1519 function replaceInternalLinks( $s ) {
1520 global $wgContLang;
1521 static $fname = 'Parser::replaceInternalLinks' ;
1522
1523 wfProfileIn( $fname );
1524
1525 wfProfileIn( $fname.'-setup' );
1526 static $tc = FALSE;
1527 # the % is needed to support urlencoded titles as well
1528 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1529
1530 $sk =& $this->mOptions->getSkin();
1531
1532 #split the entire text string on occurences of [[
1533 $a = explode( '[[', ' ' . $s );
1534 #get the first element (all text up to first [[), and remove the space we added
1535 $s = array_shift( $a );
1536 $s = substr( $s, 1 );
1537
1538 # Match a link having the form [[namespace:link|alternate]]trail
1539 static $e1 = FALSE;
1540 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1541 # Match cases where there is no "]]", which might still be images
1542 static $e1_img = FALSE;
1543 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1544 # Match the end of a line for a word that's not followed by whitespace,
1545 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1546 $e2 = wfMsgForContent( 'linkprefix' );
1547
1548 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1549
1550 if( is_null( $this->mTitle ) ) {
1551 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1552 }
1553 $nottalk = !$this->mTitle->isTalkPage();
1554
1555 if ( $useLinkPrefixExtension ) {
1556 $m = array();
1557 if ( preg_match( $e2, $s, $m ) ) {
1558 $first_prefix = $m[2];
1559 } else {
1560 $first_prefix = false;
1561 }
1562 } else {
1563 $prefix = '';
1564 }
1565
1566 if($wgContLang->hasVariants())
1567 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1568 else
1569 $selflink = array($this->mTitle->getPrefixedText());
1570 $useSubpages = $this->areSubpagesAllowed();
1571 wfProfileOut( $fname.'-setup' );
1572
1573 # Loop for each link
1574 for ($k = 0; isset( $a[$k] ); $k++) {
1575 $line = $a[$k];
1576 if ( $useLinkPrefixExtension ) {
1577 wfProfileIn( $fname.'-prefixhandling' );
1578 if ( preg_match( $e2, $s, $m ) ) {
1579 $prefix = $m[2];
1580 $s = $m[1];
1581 } else {
1582 $prefix='';
1583 }
1584 # first link
1585 if($first_prefix) {
1586 $prefix = $first_prefix;
1587 $first_prefix = false;
1588 }
1589 wfProfileOut( $fname.'-prefixhandling' );
1590 }
1591
1592 $might_be_img = false;
1593
1594 wfProfileIn( "$fname-e1" );
1595 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1596 $text = $m[2];
1597 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1598 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1599 # the real problem is with the $e1 regex
1600 # See bug 1300.
1601 #
1602 # Still some problems for cases where the ] is meant to be outside punctuation,
1603 # and no image is in sight. See bug 2095.
1604 #
1605 if( $text !== '' &&
1606 substr( $m[3], 0, 1 ) === ']' &&
1607 strpos($text, '[') !== false
1608 )
1609 {
1610 $text .= ']'; # so that replaceExternalLinks($text) works later
1611 $m[3] = substr( $m[3], 1 );
1612 }
1613 # fix up urlencoded title texts
1614 if( strpos( $m[1], '%' ) !== false ) {
1615 # Should anchors '#' also be rejected?
1616 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1617 }
1618 $trail = $m[3];
1619 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1620 $might_be_img = true;
1621 $text = $m[2];
1622 if ( strpos( $m[1], '%' ) !== false ) {
1623 $m[1] = urldecode($m[1]);
1624 }
1625 $trail = "";
1626 } else { # Invalid form; output directly
1627 $s .= $prefix . '[[' . $line ;
1628 wfProfileOut( "$fname-e1" );
1629 continue;
1630 }
1631 wfProfileOut( "$fname-e1" );
1632 wfProfileIn( "$fname-misc" );
1633
1634 # Don't allow internal links to pages containing
1635 # PROTO: where PROTO is a valid URL protocol; these
1636 # should be external links.
1637 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1638 $s .= $prefix . '[[' . $line ;
1639 continue;
1640 }
1641
1642 # Make subpage if necessary
1643 if( $useSubpages ) {
1644 $link = $this->maybeDoSubpageLink( $m[1], $text );
1645 } else {
1646 $link = $m[1];
1647 }
1648
1649 $noforce = (substr($m[1], 0, 1) != ':');
1650 if (!$noforce) {
1651 # Strip off leading ':'
1652 $link = substr($link, 1);
1653 }
1654
1655 wfProfileOut( "$fname-misc" );
1656 wfProfileIn( "$fname-title" );
1657 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1658 if( !$nt ) {
1659 $s .= $prefix . '[[' . $line;
1660 wfProfileOut( "$fname-title" );
1661 continue;
1662 }
1663
1664 $ns = $nt->getNamespace();
1665 $iw = $nt->getInterWiki();
1666 wfProfileOut( "$fname-title" );
1667
1668 if ($might_be_img) { # if this is actually an invalid link
1669 wfProfileIn( "$fname-might_be_img" );
1670 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1671 $found = false;
1672 while (isset ($a[$k+1]) ) {
1673 #look at the next 'line' to see if we can close it there
1674 $spliced = array_splice( $a, $k + 1, 1 );
1675 $next_line = array_shift( $spliced );
1676 $m = explode( ']]', $next_line, 3 );
1677 if ( count( $m ) == 3 ) {
1678 # the first ]] closes the inner link, the second the image
1679 $found = true;
1680 $text .= "[[{$m[0]}]]{$m[1]}";
1681 $trail = $m[2];
1682 break;
1683 } elseif ( count( $m ) == 2 ) {
1684 #if there's exactly one ]] that's fine, we'll keep looking
1685 $text .= "[[{$m[0]}]]{$m[1]}";
1686 } else {
1687 #if $next_line is invalid too, we need look no further
1688 $text .= '[[' . $next_line;
1689 break;
1690 }
1691 }
1692 if ( !$found ) {
1693 # we couldn't find the end of this imageLink, so output it raw
1694 #but don't ignore what might be perfectly normal links in the text we've examined
1695 $text = $this->replaceInternalLinks($text);
1696 $s .= "{$prefix}[[$link|$text";
1697 # note: no $trail, because without an end, there *is* no trail
1698 wfProfileOut( "$fname-might_be_img" );
1699 continue;
1700 }
1701 } else { #it's not an image, so output it raw
1702 $s .= "{$prefix}[[$link|$text";
1703 # note: no $trail, because without an end, there *is* no trail
1704 wfProfileOut( "$fname-might_be_img" );
1705 continue;
1706 }
1707 wfProfileOut( "$fname-might_be_img" );
1708 }
1709
1710 $wasblank = ( '' == $text );
1711 if( $wasblank ) $text = $link;
1712
1713 # Link not escaped by : , create the various objects
1714 if( $noforce ) {
1715
1716 # Interwikis
1717 wfProfileIn( "$fname-interwiki" );
1718 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1719 $this->mOutput->addLanguageLink( $nt->getFullText() );
1720 $s = rtrim($s . "\n");
1721 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1722 wfProfileOut( "$fname-interwiki" );
1723 continue;
1724 }
1725 wfProfileOut( "$fname-interwiki" );
1726
1727 if ( $ns == NS_IMAGE ) {
1728 wfProfileIn( "$fname-image" );
1729 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1730 # recursively parse links inside the image caption
1731 # actually, this will parse them in any other parameters, too,
1732 # but it might be hard to fix that, and it doesn't matter ATM
1733 $text = $this->replaceExternalLinks($text);
1734 $text = $this->replaceInternalLinks($text);
1735
1736 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1737 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1738 $this->mOutput->addImage( $nt->getDBkey() );
1739
1740 wfProfileOut( "$fname-image" );
1741 continue;
1742 } else {
1743 # We still need to record the image's presence on the page
1744 $this->mOutput->addImage( $nt->getDBkey() );
1745 }
1746 wfProfileOut( "$fname-image" );
1747
1748 }
1749
1750 if ( $ns == NS_CATEGORY ) {
1751 wfProfileIn( "$fname-category" );
1752 $s = rtrim($s . "\n"); # bug 87
1753
1754 if ( $wasblank ) {
1755 $sortkey = $this->getDefaultSort();
1756 } else {
1757 $sortkey = $text;
1758 }
1759 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1760 $sortkey = str_replace( "\n", '', $sortkey );
1761 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1762 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1763
1764 /**
1765 * Strip the whitespace Category links produce, see bug 87
1766 * @todo We might want to use trim($tmp, "\n") here.
1767 */
1768 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1769
1770 wfProfileOut( "$fname-category" );
1771 continue;
1772 }
1773 }
1774
1775 if( ( in_array( $nt->getPrefixedText(), $selflink ) ) &&
1776 ( $nt->getFragment() === '' ) ) {
1777 # Self-links are handled specially; generally de-link and change to bold.
1778 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1779 continue;
1780 }
1781
1782 # Special and Media are pseudo-namespaces; no pages actually exist in them
1783 if( $ns == NS_MEDIA ) {
1784 $link = $sk->makeMediaLinkObj( $nt, $text );
1785 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1786 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1787 $this->mOutput->addImage( $nt->getDBkey() );
1788 continue;
1789 } elseif( $ns == NS_SPECIAL ) {
1790 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1791 continue;
1792 } elseif( $ns == NS_IMAGE ) {
1793 $img = new Image( $nt );
1794 if( $img->exists() ) {
1795 // Force a blue link if the file exists; may be a remote
1796 // upload on the shared repository, and we want to see its
1797 // auto-generated page.
1798 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1799 $this->mOutput->addLink( $nt );
1800 continue;
1801 }
1802 }
1803 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1804 }
1805 wfProfileOut( $fname );
1806 return $s;
1807 }
1808
1809 /**
1810 * Make a link placeholder. The text returned can be later resolved to a real link with
1811 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1812 * parsing of interwiki links, and secondly to allow all existence checks and
1813 * article length checks (for stub links) to be bundled into a single query.
1814 *
1815 */
1816 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1817 wfProfileIn( __METHOD__ );
1818 if ( ! is_object($nt) ) {
1819 # Fail gracefully
1820 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1821 } else {
1822 # Separate the link trail from the rest of the link
1823 list( $inside, $trail ) = Linker::splitTrail( $trail );
1824
1825 if ( $nt->isExternal() ) {
1826 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1827 $this->mInterwikiLinkHolders['titles'][] = $nt;
1828 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1829 } else {
1830 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1831 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1832 $this->mLinkHolders['queries'][] = $query;
1833 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1834 $this->mLinkHolders['titles'][] = $nt;
1835
1836 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1837 }
1838 }
1839 wfProfileOut( __METHOD__ );
1840 return $retVal;
1841 }
1842
1843 /**
1844 * Render a forced-blue link inline; protect against double expansion of
1845 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1846 * Since this little disaster has to split off the trail text to avoid
1847 * breaking URLs in the following text without breaking trails on the
1848 * wiki links, it's been made into a horrible function.
1849 *
1850 * @param Title $nt
1851 * @param string $text
1852 * @param string $query
1853 * @param string $trail
1854 * @param string $prefix
1855 * @return string HTML-wikitext mix oh yuck
1856 */
1857 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1858 list( $inside, $trail ) = Linker::splitTrail( $trail );
1859 $sk =& $this->mOptions->getSkin();
1860 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1861 return $this->armorLinks( $link ) . $trail;
1862 }
1863
1864 /**
1865 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1866 * going to go through further parsing steps before inline URL expansion.
1867 *
1868 * In particular this is important when using action=render, which causes
1869 * full URLs to be included.
1870 *
1871 * Oh man I hate our multi-layer parser!
1872 *
1873 * @param string more-or-less HTML
1874 * @return string less-or-more HTML with NOPARSE bits
1875 */
1876 function armorLinks( $text ) {
1877 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1878 "{$this->mUniqPrefix}NOPARSE$1", $text );
1879 }
1880
1881 /**
1882 * Return true if subpage links should be expanded on this page.
1883 * @return bool
1884 */
1885 function areSubpagesAllowed() {
1886 # Some namespaces don't allow subpages
1887 global $wgNamespacesWithSubpages;
1888 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1889 }
1890
1891 /**
1892 * Handle link to subpage if necessary
1893 * @param string $target the source of the link
1894 * @param string &$text the link text, modified as necessary
1895 * @return string the full name of the link
1896 * @private
1897 */
1898 function maybeDoSubpageLink($target, &$text) {
1899 # Valid link forms:
1900 # Foobar -- normal
1901 # :Foobar -- override special treatment of prefix (images, language links)
1902 # /Foobar -- convert to CurrentPage/Foobar
1903 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1904 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1905 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1906
1907 $fname = 'Parser::maybeDoSubpageLink';
1908 wfProfileIn( $fname );
1909 $ret = $target; # default return value is no change
1910
1911 # bug 7425
1912 $target = trim( $target );
1913
1914 # Some namespaces don't allow subpages,
1915 # so only perform processing if subpages are allowed
1916 if( $this->areSubpagesAllowed() ) {
1917 # Look at the first character
1918 if( $target != '' && $target{0} == '/' ) {
1919 # / at end means we don't want the slash to be shown
1920 if( substr( $target, -1, 1 ) == '/' ) {
1921 $target = substr( $target, 1, -1 );
1922 $noslash = $target;
1923 } else {
1924 $noslash = substr( $target, 1 );
1925 }
1926
1927 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1928 if( '' === $text ) {
1929 $text = $target;
1930 } # this might be changed for ugliness reasons
1931 } else {
1932 # check for .. subpage backlinks
1933 $dotdotcount = 0;
1934 $nodotdot = $target;
1935 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1936 ++$dotdotcount;
1937 $nodotdot = substr( $nodotdot, 3 );
1938 }
1939 if($dotdotcount > 0) {
1940 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1941 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1942 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1943 # / at the end means don't show full path
1944 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1945 $nodotdot = substr( $nodotdot, 0, -1 );
1946 if( '' === $text ) {
1947 $text = $nodotdot;
1948 }
1949 }
1950 $nodotdot = trim( $nodotdot );
1951 if( $nodotdot != '' ) {
1952 $ret .= '/' . $nodotdot;
1953 }
1954 }
1955 }
1956 }
1957 }
1958
1959 wfProfileOut( $fname );
1960 return $ret;
1961 }
1962
1963 /**#@+
1964 * Used by doBlockLevels()
1965 * @private
1966 */
1967 /* private */ function closeParagraph() {
1968 $result = '';
1969 if ( '' != $this->mLastSection ) {
1970 $result = '</' . $this->mLastSection . ">\n";
1971 }
1972 $this->mInPre = false;
1973 $this->mLastSection = '';
1974 return $result;
1975 }
1976 # getCommon() returns the length of the longest common substring
1977 # of both arguments, starting at the beginning of both.
1978 #
1979 /* private */ function getCommon( $st1, $st2 ) {
1980 $fl = strlen( $st1 );
1981 $shorter = strlen( $st2 );
1982 if ( $fl < $shorter ) { $shorter = $fl; }
1983
1984 for ( $i = 0; $i < $shorter; ++$i ) {
1985 if ( $st1{$i} != $st2{$i} ) { break; }
1986 }
1987 return $i;
1988 }
1989 # These next three functions open, continue, and close the list
1990 # element appropriate to the prefix character passed into them.
1991 #
1992 /* private */ function openList( $char ) {
1993 $result = $this->closeParagraph();
1994
1995 if ( '*' == $char ) { $result .= '<ul><li>'; }
1996 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1997 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1998 else if ( ';' == $char ) {
1999 $result .= '<dl><dt>';
2000 $this->mDTopen = true;
2001 }
2002 else { $result = '<!-- ERR 1 -->'; }
2003
2004 return $result;
2005 }
2006
2007 /* private */ function nextItem( $char ) {
2008 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
2009 else if ( ':' == $char || ';' == $char ) {
2010 $close = '</dd>';
2011 if ( $this->mDTopen ) { $close = '</dt>'; }
2012 if ( ';' == $char ) {
2013 $this->mDTopen = true;
2014 return $close . '<dt>';
2015 } else {
2016 $this->mDTopen = false;
2017 return $close . '<dd>';
2018 }
2019 }
2020 return '<!-- ERR 2 -->';
2021 }
2022
2023 /* private */ function closeList( $char ) {
2024 if ( '*' == $char ) { $text = '</li></ul>'; }
2025 else if ( '#' == $char ) { $text = '</li></ol>'; }
2026 else if ( ':' == $char ) {
2027 if ( $this->mDTopen ) {
2028 $this->mDTopen = false;
2029 $text = '</dt></dl>';
2030 } else {
2031 $text = '</dd></dl>';
2032 }
2033 }
2034 else { return '<!-- ERR 3 -->'; }
2035 return $text."\n";
2036 }
2037 /**#@-*/
2038
2039 /**
2040 * Make lists from lines starting with ':', '*', '#', etc.
2041 *
2042 * @private
2043 * @return string the lists rendered as HTML
2044 */
2045 function doBlockLevels( $text, $linestart ) {
2046 $fname = 'Parser::doBlockLevels';
2047 wfProfileIn( $fname );
2048
2049 # Parsing through the text line by line. The main thing
2050 # happening here is handling of block-level elements p, pre,
2051 # and making lists from lines starting with * # : etc.
2052 #
2053 $textLines = explode( "\n", $text );
2054
2055 $lastPrefix = $output = '';
2056 $this->mDTopen = $inBlockElem = false;
2057 $prefixLength = 0;
2058 $paragraphStack = false;
2059
2060 if ( !$linestart ) {
2061 $output .= array_shift( $textLines );
2062 }
2063 foreach ( $textLines as $oLine ) {
2064 $lastPrefixLength = strlen( $lastPrefix );
2065 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2066 $preOpenMatch = preg_match('/<pre/i', $oLine );
2067 if ( !$this->mInPre ) {
2068 # Multiple prefixes may abut each other for nested lists.
2069 $prefixLength = strspn( $oLine, '*#:;' );
2070 $pref = substr( $oLine, 0, $prefixLength );
2071
2072 # eh?
2073 $pref2 = str_replace( ';', ':', $pref );
2074 $t = substr( $oLine, $prefixLength );
2075 $this->mInPre = !empty($preOpenMatch);
2076 } else {
2077 # Don't interpret any other prefixes in preformatted text
2078 $prefixLength = 0;
2079 $pref = $pref2 = '';
2080 $t = $oLine;
2081 }
2082
2083 # List generation
2084 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2085 # Same as the last item, so no need to deal with nesting or opening stuff
2086 $output .= $this->nextItem( substr( $pref, -1 ) );
2087 $paragraphStack = false;
2088
2089 if ( substr( $pref, -1 ) == ';') {
2090 # The one nasty exception: definition lists work like this:
2091 # ; title : definition text
2092 # So we check for : in the remainder text to split up the
2093 # title and definition, without b0rking links.
2094 $term = $t2 = '';
2095 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2096 $t = $t2;
2097 $output .= $term . $this->nextItem( ':' );
2098 }
2099 }
2100 } elseif( $prefixLength || $lastPrefixLength ) {
2101 # Either open or close a level...
2102 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2103 $paragraphStack = false;
2104
2105 while( $commonPrefixLength < $lastPrefixLength ) {
2106 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2107 --$lastPrefixLength;
2108 }
2109 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2110 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2111 }
2112 while ( $prefixLength > $commonPrefixLength ) {
2113 $char = substr( $pref, $commonPrefixLength, 1 );
2114 $output .= $this->openList( $char );
2115
2116 if ( ';' == $char ) {
2117 # FIXME: This is dupe of code above
2118 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2119 $t = $t2;
2120 $output .= $term . $this->nextItem( ':' );
2121 }
2122 }
2123 ++$commonPrefixLength;
2124 }
2125 $lastPrefix = $pref2;
2126 }
2127 if( 0 == $prefixLength ) {
2128 wfProfileIn( "$fname-paragraph" );
2129 # No prefix (not in list)--go to paragraph mode
2130 // XXX: use a stack for nestable elements like span, table and div
2131 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2132 $closematch = preg_match(
2133 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2134 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2135 if ( $openmatch or $closematch ) {
2136 $paragraphStack = false;
2137 # TODO bug 5718: paragraph closed
2138 $output .= $this->closeParagraph();
2139 if ( $preOpenMatch and !$preCloseMatch ) {
2140 $this->mInPre = true;
2141 }
2142 if ( $closematch ) {
2143 $inBlockElem = false;
2144 } else {
2145 $inBlockElem = true;
2146 }
2147 } else if ( !$inBlockElem && !$this->mInPre ) {
2148 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
2149 // pre
2150 if ($this->mLastSection != 'pre') {
2151 $paragraphStack = false;
2152 $output .= $this->closeParagraph().'<pre>';
2153 $this->mLastSection = 'pre';
2154 }
2155 $t = substr( $t, 1 );
2156 } else {
2157 // paragraph
2158 if ( '' == trim($t) ) {
2159 if ( $paragraphStack ) {
2160 $output .= $paragraphStack.'<br />';
2161 $paragraphStack = false;
2162 $this->mLastSection = 'p';
2163 } else {
2164 if ($this->mLastSection != 'p' ) {
2165 $output .= $this->closeParagraph();
2166 $this->mLastSection = '';
2167 $paragraphStack = '<p>';
2168 } else {
2169 $paragraphStack = '</p><p>';
2170 }
2171 }
2172 } else {
2173 if ( $paragraphStack ) {
2174 $output .= $paragraphStack;
2175 $paragraphStack = false;
2176 $this->mLastSection = 'p';
2177 } else if ($this->mLastSection != 'p') {
2178 $output .= $this->closeParagraph().'<p>';
2179 $this->mLastSection = 'p';
2180 }
2181 }
2182 }
2183 }
2184 wfProfileOut( "$fname-paragraph" );
2185 }
2186 // somewhere above we forget to get out of pre block (bug 785)
2187 if($preCloseMatch && $this->mInPre) {
2188 $this->mInPre = false;
2189 }
2190 if ($paragraphStack === false) {
2191 $output .= $t."\n";
2192 }
2193 }
2194 while ( $prefixLength ) {
2195 $output .= $this->closeList( $pref2{$prefixLength-1} );
2196 --$prefixLength;
2197 }
2198 if ( '' != $this->mLastSection ) {
2199 $output .= '</' . $this->mLastSection . '>';
2200 $this->mLastSection = '';
2201 }
2202
2203 wfProfileOut( $fname );
2204 return $output;
2205 }
2206
2207 /**
2208 * Split up a string on ':', ignoring any occurences inside tags
2209 * to prevent illegal overlapping.
2210 * @param string $str the string to split
2211 * @param string &$before set to everything before the ':'
2212 * @param string &$after set to everything after the ':'
2213 * return string the position of the ':', or false if none found
2214 */
2215 function findColonNoLinks($str, &$before, &$after) {
2216 $fname = 'Parser::findColonNoLinks';
2217 wfProfileIn( $fname );
2218
2219 $pos = strpos( $str, ':' );
2220 if( $pos === false ) {
2221 // Nothing to find!
2222 wfProfileOut( $fname );
2223 return false;
2224 }
2225
2226 $lt = strpos( $str, '<' );
2227 if( $lt === false || $lt > $pos ) {
2228 // Easy; no tag nesting to worry about
2229 $before = substr( $str, 0, $pos );
2230 $after = substr( $str, $pos+1 );
2231 wfProfileOut( $fname );
2232 return $pos;
2233 }
2234
2235 // Ugly state machine to walk through avoiding tags.
2236 $state = MW_COLON_STATE_TEXT;
2237 $stack = 0;
2238 $len = strlen( $str );
2239 for( $i = 0; $i < $len; $i++ ) {
2240 $c = $str{$i};
2241
2242 switch( $state ) {
2243 // (Using the number is a performance hack for common cases)
2244 case 0: // MW_COLON_STATE_TEXT:
2245 switch( $c ) {
2246 case "<":
2247 // Could be either a <start> tag or an </end> tag
2248 $state = MW_COLON_STATE_TAGSTART;
2249 break;
2250 case ":":
2251 if( $stack == 0 ) {
2252 // We found it!
2253 $before = substr( $str, 0, $i );
2254 $after = substr( $str, $i + 1 );
2255 wfProfileOut( $fname );
2256 return $i;
2257 }
2258 // Embedded in a tag; don't break it.
2259 break;
2260 default:
2261 // Skip ahead looking for something interesting
2262 $colon = strpos( $str, ':', $i );
2263 if( $colon === false ) {
2264 // Nothing else interesting
2265 wfProfileOut( $fname );
2266 return false;
2267 }
2268 $lt = strpos( $str, '<', $i );
2269 if( $stack === 0 ) {
2270 if( $lt === false || $colon < $lt ) {
2271 // We found it!
2272 $before = substr( $str, 0, $colon );
2273 $after = substr( $str, $colon + 1 );
2274 wfProfileOut( $fname );
2275 return $i;
2276 }
2277 }
2278 if( $lt === false ) {
2279 // Nothing else interesting to find; abort!
2280 // We're nested, but there's no close tags left. Abort!
2281 break 2;
2282 }
2283 // Skip ahead to next tag start
2284 $i = $lt;
2285 $state = MW_COLON_STATE_TAGSTART;
2286 }
2287 break;
2288 case 1: // MW_COLON_STATE_TAG:
2289 // In a <tag>
2290 switch( $c ) {
2291 case ">":
2292 $stack++;
2293 $state = MW_COLON_STATE_TEXT;
2294 break;
2295 case "/":
2296 // Slash may be followed by >?
2297 $state = MW_COLON_STATE_TAGSLASH;
2298 break;
2299 default:
2300 // ignore
2301 }
2302 break;
2303 case 2: // MW_COLON_STATE_TAGSTART:
2304 switch( $c ) {
2305 case "/":
2306 $state = MW_COLON_STATE_CLOSETAG;
2307 break;
2308 case "!":
2309 $state = MW_COLON_STATE_COMMENT;
2310 break;
2311 case ">":
2312 // Illegal early close? This shouldn't happen D:
2313 $state = MW_COLON_STATE_TEXT;
2314 break;
2315 default:
2316 $state = MW_COLON_STATE_TAG;
2317 }
2318 break;
2319 case 3: // MW_COLON_STATE_CLOSETAG:
2320 // In a </tag>
2321 if( $c == ">" ) {
2322 $stack--;
2323 if( $stack < 0 ) {
2324 wfDebug( "Invalid input in $fname; too many close tags\n" );
2325 wfProfileOut( $fname );
2326 return false;
2327 }
2328 $state = MW_COLON_STATE_TEXT;
2329 }
2330 break;
2331 case MW_COLON_STATE_TAGSLASH:
2332 if( $c == ">" ) {
2333 // Yes, a self-closed tag <blah/>
2334 $state = MW_COLON_STATE_TEXT;
2335 } else {
2336 // Probably we're jumping the gun, and this is an attribute
2337 $state = MW_COLON_STATE_TAG;
2338 }
2339 break;
2340 case 5: // MW_COLON_STATE_COMMENT:
2341 if( $c == "-" ) {
2342 $state = MW_COLON_STATE_COMMENTDASH;
2343 }
2344 break;
2345 case MW_COLON_STATE_COMMENTDASH:
2346 if( $c == "-" ) {
2347 $state = MW_COLON_STATE_COMMENTDASHDASH;
2348 } else {
2349 $state = MW_COLON_STATE_COMMENT;
2350 }
2351 break;
2352 case MW_COLON_STATE_COMMENTDASHDASH:
2353 if( $c == ">" ) {
2354 $state = MW_COLON_STATE_TEXT;
2355 } else {
2356 $state = MW_COLON_STATE_COMMENT;
2357 }
2358 break;
2359 default:
2360 throw new MWException( "State machine error in $fname" );
2361 }
2362 }
2363 if( $stack > 0 ) {
2364 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2365 return false;
2366 }
2367 wfProfileOut( $fname );
2368 return false;
2369 }
2370
2371 /**
2372 * Return value of a magic variable (like PAGENAME)
2373 *
2374 * @private
2375 */
2376 function getVariableValue( $index ) {
2377 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2378
2379 /**
2380 * Some of these require message or data lookups and can be
2381 * expensive to check many times.
2382 */
2383 static $varCache = array();
2384 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2385 if ( isset( $varCache[$index] ) ) {
2386 return $varCache[$index];
2387 }
2388 }
2389
2390 $ts = time();
2391 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2392
2393 # Use the time zone
2394 global $wgLocaltimezone;
2395 if ( isset( $wgLocaltimezone ) ) {
2396 $oldtz = getenv( 'TZ' );
2397 putenv( 'TZ='.$wgLocaltimezone );
2398 }
2399 $localTimestamp = date( 'YmdHis', $ts );
2400 $localMonth = date( 'm', $ts );
2401 $localMonthName = date( 'n', $ts );
2402 $localDay = date( 'j', $ts );
2403 $localDay2 = date( 'd', $ts );
2404 $localDayOfWeek = date( 'w', $ts );
2405 $localWeek = date( 'W', $ts );
2406 $localYear = date( 'Y', $ts );
2407 $localHour = date( 'H', $ts );
2408 if ( isset( $wgLocaltimezone ) ) {
2409 putenv( 'TZ='.$oldtz );
2410 }
2411
2412 switch ( $index ) {
2413 case 'currentmonth':
2414 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2415 case 'currentmonthname':
2416 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2417 case 'currentmonthnamegen':
2418 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2419 case 'currentmonthabbrev':
2420 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2421 case 'currentday':
2422 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2423 case 'currentday2':
2424 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2425 case 'localmonth':
2426 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2427 case 'localmonthname':
2428 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2429 case 'localmonthnamegen':
2430 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2431 case 'localmonthabbrev':
2432 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2433 case 'localday':
2434 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2435 case 'localday2':
2436 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2437 case 'pagename':
2438 return $this->mTitle->getText();
2439 case 'pagenamee':
2440 return $this->mTitle->getPartialURL();
2441 case 'fullpagename':
2442 return $this->mTitle->getPrefixedText();
2443 case 'fullpagenamee':
2444 return $this->mTitle->getPrefixedURL();
2445 case 'subpagename':
2446 return $this->mTitle->getSubpageText();
2447 case 'subpagenamee':
2448 return $this->mTitle->getSubpageUrlForm();
2449 case 'basepagename':
2450 return $this->mTitle->getBaseText();
2451 case 'basepagenamee':
2452 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2453 case 'talkpagename':
2454 if( $this->mTitle->canTalk() ) {
2455 $talkPage = $this->mTitle->getTalkPage();
2456 return $talkPage->getPrefixedText();
2457 } else {
2458 return '';
2459 }
2460 case 'talkpagenamee':
2461 if( $this->mTitle->canTalk() ) {
2462 $talkPage = $this->mTitle->getTalkPage();
2463 return $talkPage->getPrefixedUrl();
2464 } else {
2465 return '';
2466 }
2467 case 'subjectpagename':
2468 $subjPage = $this->mTitle->getSubjectPage();
2469 return $subjPage->getPrefixedText();
2470 case 'subjectpagenamee':
2471 $subjPage = $this->mTitle->getSubjectPage();
2472 return $subjPage->getPrefixedUrl();
2473 case 'revisionid':
2474 return $this->mRevisionId;
2475 case 'revisionday':
2476 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2477 case 'revisionday2':
2478 return substr( $this->getRevisionTimestamp(), 6, 2 );
2479 case 'revisionmonth':
2480 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2481 case 'revisionyear':
2482 return substr( $this->getRevisionTimestamp(), 0, 4 );
2483 case 'revisiontimestamp':
2484 return $this->getRevisionTimestamp();
2485 case 'namespace':
2486 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2487 case 'namespacee':
2488 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2489 case 'talkspace':
2490 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2491 case 'talkspacee':
2492 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2493 case 'subjectspace':
2494 return $this->mTitle->getSubjectNsText();
2495 case 'subjectspacee':
2496 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2497 case 'currentdayname':
2498 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2499 case 'currentyear':
2500 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2501 case 'currenttime':
2502 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2503 case 'currenthour':
2504 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2505 case 'currentweek':
2506 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2507 // int to remove the padding
2508 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2509 case 'currentdow':
2510 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2511 case 'localdayname':
2512 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2513 case 'localyear':
2514 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2515 case 'localtime':
2516 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2517 case 'localhour':
2518 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2519 case 'localweek':
2520 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2521 // int to remove the padding
2522 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2523 case 'localdow':
2524 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2525 case 'numberofarticles':
2526 return $varCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2527 case 'numberoffiles':
2528 return $varCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2529 case 'numberofusers':
2530 return $varCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2531 case 'numberofpages':
2532 return $varCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2533 case 'numberofadmins':
2534 return $varCache[$index] = $wgContLang->formatNum( SiteStats::admins() );
2535 case 'currenttimestamp':
2536 return $varCache[$index] = wfTimestampNow();
2537 case 'localtimestamp':
2538 return $varCache[$index] = $localTimestamp;
2539 case 'currentversion':
2540 return $varCache[$index] = SpecialVersion::getVersion();
2541 case 'sitename':
2542 return $wgSitename;
2543 case 'server':
2544 return $wgServer;
2545 case 'servername':
2546 return $wgServerName;
2547 case 'scriptpath':
2548 return $wgScriptPath;
2549 case 'directionmark':
2550 return $wgContLang->getDirMark();
2551 case 'contentlanguage':
2552 global $wgContLanguageCode;
2553 return $wgContLanguageCode;
2554 default:
2555 $ret = null;
2556 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2557 return $ret;
2558 else
2559 return null;
2560 }
2561 }
2562
2563 /**
2564 * initialise the magic variables (like CURRENTMONTHNAME)
2565 *
2566 * @private
2567 */
2568 function initialiseVariables() {
2569 $fname = 'Parser::initialiseVariables';
2570 wfProfileIn( $fname );
2571 $variableIDs = MagicWord::getVariableIDs();
2572
2573 $this->mVariables = array();
2574 foreach ( $variableIDs as $id ) {
2575 $mw =& MagicWord::get( $id );
2576 $mw->addToArray( $this->mVariables, $id );
2577 }
2578 wfProfileOut( $fname );
2579 }
2580
2581 /**
2582 * parse any parentheses in format ((title|part|part))
2583 * and call callbacks to get a replacement text for any found piece
2584 *
2585 * @param string $text The text to parse
2586 * @param array $callbacks rules in form:
2587 * '{' => array( # opening parentheses
2588 * 'end' => '}', # closing parentheses
2589 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2590 * 3 => callback # replacement callback to call if {{{..}}} is found
2591 * )
2592 * )
2593 * 'min' => 2, # Minimum parenthesis count in cb
2594 * 'max' => 3, # Maximum parenthesis count in cb
2595 * @private
2596 */
2597 function replace_callback ($text, $callbacks) {
2598 wfProfileIn( __METHOD__ );
2599 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2600 $lastOpeningBrace = -1; # last not closed parentheses
2601
2602 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2603
2604 $i = 0;
2605 while ( $i < strlen( $text ) ) {
2606 # Find next opening brace, closing brace or pipe
2607 if ( $lastOpeningBrace == -1 ) {
2608 $currentClosing = '';
2609 $search = $validOpeningBraces;
2610 } else {
2611 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2612 $search = $validOpeningBraces . '|' . $currentClosing;
2613 }
2614 $rule = null;
2615 $i += strcspn( $text, $search, $i );
2616 if ( $i < strlen( $text ) ) {
2617 if ( $text[$i] == '|' ) {
2618 $found = 'pipe';
2619 } elseif ( $text[$i] == $currentClosing ) {
2620 $found = 'close';
2621 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2622 $found = 'open';
2623 $rule = $callbacks[$text[$i]];
2624 } else {
2625 # Some versions of PHP have a strcspn which stops on null characters
2626 # Ignore and continue
2627 ++$i;
2628 continue;
2629 }
2630 } else {
2631 # All done
2632 break;
2633 }
2634
2635 if ( $found == 'open' ) {
2636 # found opening brace, let's add it to parentheses stack
2637 $piece = array('brace' => $text[$i],
2638 'braceEnd' => $rule['end'],
2639 'title' => '',
2640 'parts' => null);
2641
2642 # count opening brace characters
2643 $piece['count'] = strspn( $text, $piece['brace'], $i );
2644 $piece['startAt'] = $piece['partStart'] = $i + $piece['count'];
2645 $i += $piece['count'];
2646
2647 # we need to add to stack only if opening brace count is enough for one of the rules
2648 if ( $piece['count'] >= $rule['min'] ) {
2649 $lastOpeningBrace ++;
2650 $openingBraceStack[$lastOpeningBrace] = $piece;
2651 }
2652 } elseif ( $found == 'close' ) {
2653 # lets check if it is enough characters for closing brace
2654 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2655 $count = strspn( $text, $text[$i], $i, $maxCount );
2656
2657 # check for maximum matching characters (if there are 5 closing
2658 # characters, we will probably need only 3 - depending on the rules)
2659 $matchingCount = 0;
2660 $matchingCallback = null;
2661 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2662 if ( $count > $cbType['max'] ) {
2663 # The specified maximum exists in the callback array, unless the caller
2664 # has made an error
2665 $matchingCount = $cbType['max'];
2666 } else {
2667 # Count is less than the maximum
2668 # Skip any gaps in the callback array to find the true largest match
2669 # Need to use array_key_exists not isset because the callback can be null
2670 $matchingCount = $count;
2671 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2672 --$matchingCount;
2673 }
2674 }
2675
2676 if ($matchingCount <= 0) {
2677 $i += $count;
2678 continue;
2679 }
2680 $matchingCallback = $cbType['cb'][$matchingCount];
2681
2682 # let's set a title or last part (if '|' was found)
2683 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2684 $openingBraceStack[$lastOpeningBrace]['title'] =
2685 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2686 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2687 } else {
2688 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2689 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2690 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2691 }
2692
2693 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2694 $pieceEnd = $i + $matchingCount;
2695
2696 if( is_callable( $matchingCallback ) ) {
2697 $cbArgs = array (
2698 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2699 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2700 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2701 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2702 );
2703 # finally we can call a user callback and replace piece of text
2704 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2705 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2706 $i = $pieceStart + strlen($replaceWith);
2707 } else {
2708 # null value for callback means that parentheses should be parsed, but not replaced
2709 $i += $matchingCount;
2710 }
2711
2712 # reset last opening parentheses, but keep it in case there are unused characters
2713 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2714 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2715 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2716 'title' => '',
2717 'parts' => null,
2718 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2719 $openingBraceStack[$lastOpeningBrace--] = null;
2720
2721 if ($matchingCount < $piece['count']) {
2722 $piece['count'] -= $matchingCount;
2723 $piece['startAt'] -= $matchingCount;
2724 $piece['partStart'] = $piece['startAt'];
2725 # do we still qualify for any callback with remaining count?
2726 $currentCbList = $callbacks[$piece['brace']]['cb'];
2727 while ( $piece['count'] ) {
2728 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2729 $lastOpeningBrace++;
2730 $openingBraceStack[$lastOpeningBrace] = $piece;
2731 break;
2732 }
2733 --$piece['count'];
2734 }
2735 }
2736 } elseif ( $found == 'pipe' ) {
2737 # lets set a title if it is a first separator, or next part otherwise
2738 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2739 $openingBraceStack[$lastOpeningBrace]['title'] =
2740 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2741 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2742 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2743 } else {
2744 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2745 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2746 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2747 }
2748 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++$i;
2749 }
2750 }
2751
2752 wfProfileOut( __METHOD__ );
2753 return $text;
2754 }
2755
2756 /**
2757 * Replace magic variables, templates, and template arguments
2758 * with the appropriate text. Templates are substituted recursively,
2759 * taking care to avoid infinite loops.
2760 *
2761 * Note that the substitution depends on value of $mOutputType:
2762 * OT_WIKI: only {{subst:}} templates
2763 * OT_MSG: only magic variables
2764 * OT_HTML: all templates and magic variables
2765 *
2766 * @param string $tex The text to transform
2767 * @param array $args Key-value pairs representing template parameters to substitute
2768 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2769 * @private
2770 */
2771 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2772 # Prevent too big inclusions
2773 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2774 return $text;
2775 }
2776
2777 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2778 wfProfileIn( $fname );
2779
2780 # This function is called recursively. To keep track of arguments we need a stack:
2781 array_push( $this->mArgStack, $args );
2782
2783 $braceCallbacks = array();
2784 if ( !$argsOnly ) {
2785 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2786 }
2787 if ( $this->mOutputType != OT_MSG ) {
2788 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2789 }
2790 if ( $braceCallbacks ) {
2791 $callbacks = array(
2792 '{' => array(
2793 'end' => '}',
2794 'cb' => $braceCallbacks,
2795 'min' => $argsOnly ? 3 : 2,
2796 'max' => isset( $braceCallbacks[3] ) ? 3 : 2,
2797 ),
2798 '[' => array(
2799 'end' => ']',
2800 'cb' => array(2=>null),
2801 'min' => 2,
2802 'max' => 2,
2803 )
2804 );
2805 $text = $this->replace_callback ($text, $callbacks);
2806
2807 array_pop( $this->mArgStack );
2808 }
2809 wfProfileOut( $fname );
2810 return $text;
2811 }
2812
2813 /**
2814 * Replace magic variables
2815 * @private
2816 */
2817 function variableSubstitution( $matches ) {
2818 global $wgContLang;
2819 $fname = 'Parser::variableSubstitution';
2820 $varname = $wgContLang->lc($matches[1]);
2821 wfProfileIn( $fname );
2822 $skip = false;
2823 if ( $this->mOutputType == OT_WIKI ) {
2824 # Do only magic variables prefixed by SUBST
2825 $mwSubst =& MagicWord::get( 'subst' );
2826 if (!$mwSubst->matchStartAndRemove( $varname ))
2827 $skip = true;
2828 # Note that if we don't substitute the variable below,
2829 # we don't remove the {{subst:}} magic word, in case
2830 # it is a template rather than a magic variable.
2831 }
2832 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2833 $id = $this->mVariables[$varname];
2834 # Now check if we did really match, case sensitive or not
2835 $mw =& MagicWord::get( $id );
2836 if ($mw->match($matches[1])) {
2837 $text = $this->getVariableValue( $id );
2838 $this->mOutput->mContainsOldMagic = true;
2839 } else {
2840 $text = $matches[0];
2841 }
2842 } else {
2843 $text = $matches[0];
2844 }
2845 wfProfileOut( $fname );
2846 return $text;
2847 }
2848
2849
2850 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2851 static function createAssocArgs( $args ) {
2852 $assocArgs = array();
2853 $index = 1;
2854 foreach( $args as $arg ) {
2855 $eqpos = strpos( $arg, '=' );
2856 if ( $eqpos === false ) {
2857 $assocArgs[$index++] = $arg;
2858 } else {
2859 $name = trim( substr( $arg, 0, $eqpos ) );
2860 $value = trim( substr( $arg, $eqpos+1 ) );
2861 if ( $value === false ) {
2862 $value = '';
2863 }
2864 if ( $name !== false ) {
2865 $assocArgs[$name] = $value;
2866 }
2867 }
2868 }
2869
2870 return $assocArgs;
2871 }
2872
2873 /**
2874 * Return the text of a template, after recursively
2875 * replacing any variables or templates within the template.
2876 *
2877 * @param array $piece The parts of the template
2878 * $piece['text']: matched text
2879 * $piece['title']: the title, i.e. the part before the |
2880 * $piece['parts']: the parameter array
2881 * @return string the text of the template
2882 * @private
2883 */
2884 function braceSubstitution( $piece ) {
2885 global $wgContLang, $wgLang, $wgAllowDisplayTitle;
2886 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2887 wfProfileIn( $fname );
2888 wfProfileIn( __METHOD__.'-setup' );
2889
2890 # Flags
2891 $found = false; # $text has been filled
2892 $nowiki = false; # wiki markup in $text should be escaped
2893 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2894 $noargs = false; # Don't replace triple-brace arguments in $text
2895 $replaceHeadings = false; # Make the edit section links go to the template not the article
2896 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2897 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2898 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2899
2900 # Title object, where $text came from
2901 $title = NULL;
2902
2903 $linestart = '';
2904
2905
2906 # $part1 is the bit before the first |, and must contain only title characters
2907 # $args is a list of arguments, starting from index 0, not including $part1
2908
2909 $titleText = $part1 = $piece['title'];
2910 # If the third subpattern matched anything, it will start with |
2911
2912 if (null == $piece['parts']) {
2913 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2914 if ($replaceWith != $piece['text']) {
2915 $text = $replaceWith;
2916 $found = true;
2917 $noparse = true;
2918 $noargs = true;
2919 }
2920 }
2921
2922 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2923 wfProfileOut( __METHOD__.'-setup' );
2924
2925 # SUBST
2926 wfProfileIn( __METHOD__.'-modifiers' );
2927 if ( !$found ) {
2928 $mwSubst =& MagicWord::get( 'subst' );
2929 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2930 # One of two possibilities is true:
2931 # 1) Found SUBST but not in the PST phase
2932 # 2) Didn't find SUBST and in the PST phase
2933 # In either case, return without further processing
2934 $text = $piece['text'];
2935 $found = true;
2936 $noparse = true;
2937 $noargs = true;
2938 }
2939 }
2940
2941 # MSG, MSGNW and RAW
2942 if ( !$found ) {
2943 # Check for MSGNW:
2944 $mwMsgnw =& MagicWord::get( 'msgnw' );
2945 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2946 $nowiki = true;
2947 } else {
2948 # Remove obsolete MSG:
2949 $mwMsg =& MagicWord::get( 'msg' );
2950 $mwMsg->matchStartAndRemove( $part1 );
2951 }
2952
2953 # Check for RAW:
2954 $mwRaw =& MagicWord::get( 'raw' );
2955 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2956 $forceRawInterwiki = true;
2957 }
2958 }
2959 wfProfileOut( __METHOD__.'-modifiers' );
2960
2961 //save path level before recursing into functions & templates.
2962 $lastPathLevel = $this->mTemplatePath;
2963
2964 # Parser functions
2965 if ( !$found ) {
2966 wfProfileIn( __METHOD__ . '-pfunc' );
2967
2968 $colonPos = strpos( $part1, ':' );
2969 if ( $colonPos !== false ) {
2970 # Case sensitive functions
2971 $function = substr( $part1, 0, $colonPos );
2972 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2973 $function = $this->mFunctionSynonyms[1][$function];
2974 } else {
2975 # Case insensitive functions
2976 $function = strtolower( $function );
2977 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2978 $function = $this->mFunctionSynonyms[0][$function];
2979 } else {
2980 $function = false;
2981 }
2982 }
2983 if ( $function ) {
2984 $funcArgs = array_map( 'trim', $args );
2985 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
2986 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
2987 $found = true;
2988
2989 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2990 //$noargs = true;
2991 //$noparse = true;
2992
2993 if ( is_array( $result ) ) {
2994 if ( isset( $result[0] ) ) {
2995 $text = $linestart . $result[0];
2996 unset( $result[0] );
2997 }
2998
2999 // Extract flags into the local scope
3000 // This allows callers to set flags such as nowiki, noparse, found, etc.
3001 extract( $result );
3002 } else {
3003 $text = $linestart . $result;
3004 }
3005 }
3006 }
3007 wfProfileOut( __METHOD__ . '-pfunc' );
3008 }
3009
3010 # Template table test
3011
3012 # Did we encounter this template already? If yes, it is in the cache
3013 # and we need to check for loops.
3014 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
3015 $found = true;
3016
3017 # Infinite loop test
3018 if ( isset( $this->mTemplatePath[$part1] ) ) {
3019 $noparse = true;
3020 $noargs = true;
3021 $found = true;
3022 $text = $linestart .
3023 "[[$part1]]<!-- WARNING: template loop detected -->";
3024 wfDebug( __METHOD__.": template loop broken at '$part1'\n" );
3025 } else {
3026 # set $text to cached message.
3027 $text = $linestart . $this->mTemplates[$piece['title']];
3028 }
3029 }
3030
3031 # Load from database
3032 if ( !$found ) {
3033 wfProfileIn( __METHOD__ . '-loadtpl' );
3034 $ns = NS_TEMPLATE;
3035 # declaring $subpage directly in the function call
3036 # does not work correctly with references and breaks
3037 # {{/subpage}}-style inclusions
3038 $subpage = '';
3039 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3040 if ($subpage !== '') {
3041 $ns = $this->mTitle->getNamespace();
3042 }
3043 $title = Title::newFromText( $part1, $ns );
3044
3045
3046 if ( !is_null( $title ) ) {
3047 $titleText = $title->getPrefixedText();
3048 # Check for language variants if the template is not found
3049 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3050 $wgContLang->findVariantLink($part1, $title);
3051 }
3052
3053 if ( !$title->isExternal() ) {
3054 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
3055 $text = SpecialPage::capturePath( $title );
3056 if ( is_string( $text ) ) {
3057 $found = true;
3058 $noparse = true;
3059 $noargs = true;
3060 $isHTML = true;
3061 $this->disableCache();
3062 }
3063 } else {
3064 $articleContent = $this->fetchTemplate( $title );
3065 if ( $articleContent !== false ) {
3066 $found = true;
3067 $text = $articleContent;
3068 $replaceHeadings = true;
3069 }
3070 }
3071
3072 # If the title is valid but undisplayable, make a link to it
3073 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3074 $text = "[[:$titleText]]";
3075 $found = true;
3076 }
3077 } elseif ( $title->isTrans() ) {
3078 // Interwiki transclusion
3079 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3080 $text = $this->interwikiTransclude( $title, 'render' );
3081 $isHTML = true;
3082 $noparse = true;
3083 } else {
3084 $text = $this->interwikiTransclude( $title, 'raw' );
3085 $replaceHeadings = true;
3086 }
3087 $found = true;
3088 }
3089
3090 # Template cache array insertion
3091 # Use the original $piece['title'] not the mangled $part1, so that
3092 # modifiers such as RAW: produce separate cache entries
3093 if( $found ) {
3094 if( $isHTML ) {
3095 // A special page; don't store it in the template cache.
3096 } else {
3097 $this->mTemplates[$piece['title']] = $text;
3098 }
3099 $text = $linestart . $text;
3100 }
3101 }
3102 wfProfileOut( __METHOD__ . '-loadtpl' );
3103 }
3104
3105 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3106 # Error, oversize inclusion
3107 $text = $linestart .
3108 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3109 $noparse = true;
3110 $noargs = true;
3111 }
3112
3113 # Recursive parsing, escaping and link table handling
3114 # Only for HTML output
3115 if ( $nowiki && $found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3116 $text = wfEscapeWikiText( $text );
3117 } elseif ( !$this->ot['msg'] && $found ) {
3118 if ( $noargs ) {
3119 $assocArgs = array();
3120 } else {
3121 # Clean up argument array
3122 $assocArgs = self::createAssocArgs($args);
3123 # Add a new element to the templace recursion path
3124 $this->mTemplatePath[$part1] = 1;
3125 }
3126
3127 if ( !$noparse ) {
3128 # If there are any <onlyinclude> tags, only include them
3129 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3130 $replacer = new OnlyIncludeReplacer;
3131 StringUtils::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3132 array( &$replacer, 'replace' ), $text );
3133 $text = $replacer->output;
3134 }
3135 # Remove <noinclude> sections and <includeonly> tags
3136 $text = StringUtils::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3137 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3138
3139 if( $this->ot['html'] || $this->ot['pre'] ) {
3140 # Strip <nowiki>, <pre>, etc.
3141 $text = $this->strip( $text, $this->mStripState );
3142 if ( $this->ot['html'] ) {
3143 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3144 } elseif ( $this->ot['pre'] && $this->mOptions->getRemoveComments() ) {
3145 $text = Sanitizer::removeHTMLcomments( $text );
3146 }
3147 }
3148 $text = $this->replaceVariables( $text, $assocArgs );
3149
3150 # If the template begins with a table or block-level
3151 # element, it should be treated as beginning a new line.
3152 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3153 $text = "\n" . $text;
3154 }
3155 } elseif ( !$noargs ) {
3156 # $noparse and !$noargs
3157 # Just replace the arguments, not any double-brace items
3158 # This is used for rendered interwiki transclusion
3159 $text = $this->replaceVariables( $text, $assocArgs, true );
3160 }
3161 }
3162 # Prune lower levels off the recursion check path
3163 $this->mTemplatePath = $lastPathLevel;
3164
3165 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3166 # Error, oversize inclusion
3167 $text = $linestart .
3168 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3169 $noparse = true;
3170 $noargs = true;
3171 }
3172
3173 if ( !$found ) {
3174 wfProfileOut( $fname );
3175 return $piece['text'];
3176 } else {
3177 wfProfileIn( __METHOD__ . '-placeholders' );
3178 if ( $isHTML ) {
3179 # Replace raw HTML by a placeholder
3180 # Add a blank line preceding, to prevent it from mucking up
3181 # immediately preceding headings
3182 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3183 } else {
3184 # replace ==section headers==
3185 # XXX this needs to go away once we have a better parser.
3186 if ( !$this->ot['wiki'] && !$this->ot['pre'] && $replaceHeadings ) {
3187 if( !is_null( $title ) )
3188 $encodedname = base64_encode($title->getPrefixedDBkey());
3189 else
3190 $encodedname = base64_encode("");
3191 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3192 PREG_SPLIT_DELIM_CAPTURE);
3193 $text = '';
3194 $nsec = $headingOffset;
3195 for( $i = 0; $i < count($m); $i += 2 ) {
3196 $text .= $m[$i];
3197 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3198 $hl = $m[$i + 1];
3199 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3200 $text .= $hl;
3201 continue;
3202 }
3203 $m2 = array();
3204 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3205 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3206 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3207
3208 $nsec++;
3209 }
3210 }
3211 }
3212 wfProfileOut( __METHOD__ . '-placeholders' );
3213 }
3214
3215 # Prune lower levels off the recursion check path
3216 $this->mTemplatePath = $lastPathLevel;
3217
3218 if ( !$found ) {
3219 wfProfileOut( $fname );
3220 return $piece['text'];
3221 } else {
3222 wfProfileOut( $fname );
3223 return $text;
3224 }
3225 }
3226
3227 /**
3228 * Fetch the unparsed text of a template and register a reference to it.
3229 */
3230 function fetchTemplate( $title ) {
3231 $text = false;
3232 // Loop to fetch the article, with up to 1 redirect
3233 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3234 $rev = Revision::newFromTitle( $title );
3235 $this->mOutput->addTemplate( $title, $title->getArticleID() );
3236 if ( !$rev ) {
3237 break;
3238 }
3239 $text = $rev->getText();
3240 if ( $text === false ) {
3241 break;
3242 }
3243 // Redirect?
3244 $title = Title::newFromRedirect( $text );
3245 }
3246 return $text;
3247 }
3248
3249 /**
3250 * Transclude an interwiki link.
3251 */
3252 function interwikiTransclude( $title, $action ) {
3253 global $wgEnableScaryTranscluding;
3254
3255 if (!$wgEnableScaryTranscluding)
3256 return wfMsg('scarytranscludedisabled');
3257
3258 $url = $title->getFullUrl( "action=$action" );
3259
3260 if (strlen($url) > 255)
3261 return wfMsg('scarytranscludetoolong');
3262 return $this->fetchScaryTemplateMaybeFromCache($url);
3263 }
3264
3265 function fetchScaryTemplateMaybeFromCache($url) {
3266 global $wgTranscludeCacheExpiry;
3267 $dbr =& wfGetDB(DB_SLAVE);
3268 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3269 array('tc_url' => $url));
3270 if ($obj) {
3271 $time = $obj->tc_time;
3272 $text = $obj->tc_contents;
3273 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3274 return $text;
3275 }
3276 }
3277
3278 $text = Http::get($url);
3279 if (!$text)
3280 return wfMsg('scarytranscludefailed', $url);
3281
3282 $dbw =& wfGetDB(DB_MASTER);
3283 $dbw->replace('transcache', array('tc_url'), array(
3284 'tc_url' => $url,
3285 'tc_time' => time(),
3286 'tc_contents' => $text));
3287 return $text;
3288 }
3289
3290
3291 /**
3292 * Triple brace replacement -- used for template arguments
3293 * @private
3294 */
3295 function argSubstitution( $matches ) {
3296 $arg = trim( $matches['title'] );
3297 $text = $matches['text'];
3298 $inputArgs = end( $this->mArgStack );
3299
3300 if ( array_key_exists( $arg, $inputArgs ) ) {
3301 $text = $inputArgs[$arg];
3302 } else if (($this->mOutputType == OT_HTML || $this->mOutputType == OT_PREPROCESS ) &&
3303 null != $matches['parts'] && count($matches['parts']) > 0) {
3304 $text = $matches['parts'][0];
3305 }
3306 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3307 $text = $matches['text'] .
3308 '<!-- WARNING: argument omitted, expansion size too large -->';
3309 }
3310
3311 return $text;
3312 }
3313
3314 /**
3315 * Increment an include size counter
3316 *
3317 * @param string $type The type of expansion
3318 * @param integer $size The size of the text
3319 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3320 */
3321 function incrementIncludeSize( $type, $size ) {
3322 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3323 return false;
3324 } else {
3325 $this->mIncludeSizes[$type] += $size;
3326 return true;
3327 }
3328 }
3329
3330 /**
3331 * Detect __NOGALLERY__ magic word and set a placeholder
3332 */
3333 function stripNoGallery( &$text ) {
3334 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3335 # do not add TOC
3336 $mw = MagicWord::get( 'nogallery' );
3337 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3338 }
3339
3340 /**
3341 * Detect __TOC__ magic word and set a placeholder
3342 */
3343 function stripToc( $text ) {
3344 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3345 # do not add TOC
3346 $mw = MagicWord::get( 'notoc' );
3347 if( $mw->matchAndRemove( $text ) ) {
3348 $this->mShowToc = false;
3349 }
3350
3351 $mw = MagicWord::get( 'toc' );
3352 if( $mw->match( $text ) ) {
3353 $this->mShowToc = true;
3354 $this->mForceTocPosition = true;
3355
3356 // Set a placeholder. At the end we'll fill it in with the TOC.
3357 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3358
3359 // Only keep the first one.
3360 $text = $mw->replace( '', $text );
3361 }
3362 return $text;
3363 }
3364
3365 /**
3366 * This function accomplishes several tasks:
3367 * 1) Auto-number headings if that option is enabled
3368 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3369 * 3) Add a Table of contents on the top for users who have enabled the option
3370 * 4) Auto-anchor headings
3371 *
3372 * It loops through all headlines, collects the necessary data, then splits up the
3373 * string and re-inserts the newly formatted headlines.
3374 *
3375 * @param string $text
3376 * @param boolean $isMain
3377 * @private
3378 */
3379 function formatHeadings( $text, $isMain=true ) {
3380 global $wgMaxTocLevel, $wgContLang;
3381
3382 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3383 if( !$this->mTitle->userCanEdit() ) {
3384 $showEditLink = 0;
3385 } else {
3386 $showEditLink = $this->mOptions->getEditSection();
3387 }
3388
3389 # Inhibit editsection links if requested in the page
3390 $esw =& MagicWord::get( 'noeditsection' );
3391 if( $esw->matchAndRemove( $text ) ) {
3392 $showEditLink = 0;
3393 }
3394
3395 # Get all headlines for numbering them and adding funky stuff like [edit]
3396 # links - this is for later, but we need the number of headlines right now
3397 $matches = array();
3398 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3399
3400 # if there are fewer than 4 headlines in the article, do not show TOC
3401 # unless it's been explicitly enabled.
3402 $enoughToc = $this->mShowToc &&
3403 (($numMatches >= 4) || $this->mForceTocPosition);
3404
3405 # Allow user to stipulate that a page should have a "new section"
3406 # link added via __NEWSECTIONLINK__
3407 $mw =& MagicWord::get( 'newsectionlink' );
3408 if( $mw->matchAndRemove( $text ) )
3409 $this->mOutput->setNewSection( true );
3410
3411 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3412 # override above conditions and always show TOC above first header
3413 $mw =& MagicWord::get( 'forcetoc' );
3414 if ($mw->matchAndRemove( $text ) ) {
3415 $this->mShowToc = true;
3416 $enoughToc = true;
3417 }
3418
3419 # Never ever show TOC if no headers
3420 if( $numMatches < 1 ) {
3421 $enoughToc = false;
3422 }
3423
3424 # We need this to perform operations on the HTML
3425 $sk =& $this->mOptions->getSkin();
3426
3427 # headline counter
3428 $headlineCount = 0;
3429 $sectionCount = 0; # headlineCount excluding template sections
3430
3431 # Ugh .. the TOC should have neat indentation levels which can be
3432 # passed to the skin functions. These are determined here
3433 $toc = '';
3434 $full = '';
3435 $head = array();
3436 $sublevelCount = array();
3437 $levelCount = array();
3438 $toclevel = 0;
3439 $level = 0;
3440 $prevlevel = 0;
3441 $toclevel = 0;
3442 $prevtoclevel = 0;
3443
3444 foreach( $matches[3] as $headline ) {
3445 $istemplate = 0;
3446 $templatetitle = '';
3447 $templatesection = 0;
3448 $numbering = '';
3449 $mat = array();
3450 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3451 $istemplate = 1;
3452 $templatetitle = base64_decode($mat[1]);
3453 $templatesection = 1 + (int)base64_decode($mat[2]);
3454 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3455 }
3456
3457 if( $toclevel ) {
3458 $prevlevel = $level;
3459 $prevtoclevel = $toclevel;
3460 }
3461 $level = $matches[1][$headlineCount];
3462
3463 if( $doNumberHeadings || $enoughToc ) {
3464
3465 if ( $level > $prevlevel ) {
3466 # Increase TOC level
3467 $toclevel++;
3468 $sublevelCount[$toclevel] = 0;
3469 if( $toclevel<$wgMaxTocLevel ) {
3470 $toc .= $sk->tocIndent();
3471 }
3472 }
3473 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3474 # Decrease TOC level, find level to jump to
3475
3476 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3477 # Can only go down to level 1
3478 $toclevel = 1;
3479 } else {
3480 for ($i = $toclevel; $i > 0; $i--) {
3481 if ( $levelCount[$i] == $level ) {
3482 # Found last matching level
3483 $toclevel = $i;
3484 break;
3485 }
3486 elseif ( $levelCount[$i] < $level ) {
3487 # Found first matching level below current level
3488 $toclevel = $i + 1;
3489 break;
3490 }
3491 }
3492 }
3493 if( $toclevel<$wgMaxTocLevel ) {
3494 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3495 }
3496 }
3497 else {
3498 # No change in level, end TOC line
3499 if( $toclevel<$wgMaxTocLevel ) {
3500 $toc .= $sk->tocLineEnd();
3501 }
3502 }
3503
3504 $levelCount[$toclevel] = $level;
3505
3506 # count number of headlines for each level
3507 @$sublevelCount[$toclevel]++;
3508 $dot = 0;
3509 for( $i = 1; $i <= $toclevel; $i++ ) {
3510 if( !empty( $sublevelCount[$i] ) ) {
3511 if( $dot ) {
3512 $numbering .= '.';
3513 }
3514 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3515 $dot = 1;
3516 }
3517 }
3518 }
3519
3520 # The canonized header is a version of the header text safe to use for links
3521 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3522 $canonized_headline = $this->mStripState->unstripBoth( $headline );
3523
3524 # Remove link placeholders by the link text.
3525 # <!--LINK number-->
3526 # turns into
3527 # link text with suffix
3528 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3529 "\$this->mLinkHolders['texts'][\$1]",
3530 $canonized_headline );
3531 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3532 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3533 $canonized_headline );
3534
3535 # strip out HTML
3536 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3537 $tocline = trim( $canonized_headline );
3538 # Save headline for section edit hint before it's escaped
3539 $headline_hint = trim( $canonized_headline );
3540 $canonized_headline = Sanitizer::escapeId( $tocline );
3541 $refers[$headlineCount] = $canonized_headline;
3542
3543 # count how many in assoc. array so we can track dupes in anchors
3544 isset( $refers[$canonized_headline] ) ? $refers[$canonized_headline]++ : $refers[$canonized_headline] = 1;
3545 $refcount[$headlineCount]=$refers[$canonized_headline];
3546
3547 # Don't number the heading if it is the only one (looks silly)
3548 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3549 # the two are different if the line contains a link
3550 $headline=$numbering . ' ' . $headline;
3551 }
3552
3553 # Create the anchor for linking from the TOC to the section
3554 $anchor = $canonized_headline;
3555 if($refcount[$headlineCount] > 1 ) {
3556 $anchor .= '_' . $refcount[$headlineCount];
3557 }
3558 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3559 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3560 }
3561 # give headline the correct <h#> tag
3562 $head[$headlineCount] = "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount];
3563
3564 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3565 if ( empty( $head[$headlineCount] ) ) {
3566 $head[$headlineCount] = '';
3567 }
3568 if( $istemplate )
3569 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3570 else
3571 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3572 }
3573 // Yes, the headline logically goes before the edit section. Why isn't it there
3574 // in source? Ask the CSS people. The float gets screwed up if you do that.
3575 // This might be moved to before the editsection at some point so that it will
3576 // display a bit more prettily without CSS, so please don't rely on the order.
3577 $head[$headlineCount] .= ' <span class="mw-headline">'.$headline.'</span></h'.$level.'>';
3578
3579 $headlineCount++;
3580 if( !$istemplate )
3581 $sectionCount++;
3582 }
3583
3584 if( $enoughToc ) {
3585 if( $toclevel<$wgMaxTocLevel ) {
3586 $toc .= $sk->tocUnindent( $toclevel - 1 );
3587 }
3588 $toc = $sk->tocList( $toc );
3589 }
3590
3591 # split up and insert constructed headlines
3592
3593 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3594 $i = 0;
3595
3596 foreach( $blocks as $block ) {
3597 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3598 # This is the [edit] link that appears for the top block of text when
3599 # section editing is enabled
3600
3601 # Disabled because it broke block formatting
3602 # For example, a bullet point in the top line
3603 # $full .= $sk->editSectionLink(0);
3604 }
3605 $full .= $block;
3606 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3607 # Top anchor now in skin
3608 $full = $full.$toc;
3609 }
3610
3611 if( !empty( $head[$i] ) ) {
3612 $full .= $head[$i];
3613 }
3614 $i++;
3615 }
3616 if( $this->mForceTocPosition ) {
3617 return str_replace( '<!--MWTOC-->', $toc, $full );
3618 } else {
3619 return $full;
3620 }
3621 }
3622
3623 /**
3624 * Transform wiki markup when saving a page by doing \r\n -> \n
3625 * conversion, substitting signatures, {{subst:}} templates, etc.
3626 *
3627 * @param string $text the text to transform
3628 * @param Title &$title the Title object for the current article
3629 * @param User &$user the User object describing the current user
3630 * @param ParserOptions $options parsing options
3631 * @param bool $clearState whether to clear the parser state first
3632 * @return string the altered wiki markup
3633 * @public
3634 */
3635 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3636 $this->mOptions = $options;
3637 $this->mTitle =& $title;
3638 $this->setOutputType( OT_WIKI );
3639
3640 if ( $clearState ) {
3641 $this->clearState();
3642 }
3643
3644 $stripState = new StripState;
3645 $pairs = array(
3646 "\r\n" => "\n",
3647 );
3648 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3649 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3650 $text = $this->pstPass2( $text, $stripState, $user );
3651 $text = $stripState->unstripBoth( $text );
3652 return $text;
3653 }
3654
3655 /**
3656 * Pre-save transform helper function
3657 * @private
3658 */
3659 function pstPass2( $text, &$stripState, $user ) {
3660 global $wgContLang, $wgLocaltimezone;
3661
3662 /* Note: This is the timestamp saved as hardcoded wikitext to
3663 * the database, we use $wgContLang here in order to give
3664 * everyone the same signature and use the default one rather
3665 * than the one selected in each user's preferences.
3666 */
3667 if ( isset( $wgLocaltimezone ) ) {
3668 $oldtz = getenv( 'TZ' );
3669 putenv( 'TZ='.$wgLocaltimezone );
3670 }
3671 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3672 ' (' . date( 'T' ) . ')';
3673 if ( isset( $wgLocaltimezone ) ) {
3674 putenv( 'TZ='.$oldtz );
3675 }
3676
3677 # Variable replacement
3678 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3679 $text = $this->replaceVariables( $text );
3680
3681 # Strip out <nowiki> etc. added via replaceVariables
3682 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3683
3684 # Signatures
3685 $sigText = $this->getUserSig( $user );
3686 $text = strtr( $text, array(
3687 '~~~~~' => $d,
3688 '~~~~' => "$sigText $d",
3689 '~~~' => $sigText
3690 ) );
3691
3692 # Context links: [[|name]] and [[name (context)|]]
3693 #
3694 global $wgLegalTitleChars;
3695 $tc = "[$wgLegalTitleChars]";
3696 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3697
3698 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3699 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3700 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3701
3702 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3703 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3704 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3705
3706 $t = $this->mTitle->getText();
3707 $m = array();
3708 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3709 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3710 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3711 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3712 } else {
3713 # if there's no context, don't bother duplicating the title
3714 $text = preg_replace( $p2, '[[\\1]]', $text );
3715 }
3716
3717 # Trim trailing whitespace
3718 # __END__ tag allows for trailing
3719 # whitespace to be deliberately included
3720 $text = rtrim( $text );
3721 $mw =& MagicWord::get( 'end' );
3722 $mw->matchAndRemove( $text );
3723
3724 return $text;
3725 }
3726
3727 /**
3728 * Fetch the user's signature text, if any, and normalize to
3729 * validated, ready-to-insert wikitext.
3730 *
3731 * @param User $user
3732 * @return string
3733 * @private
3734 */
3735 function getUserSig( &$user ) {
3736 $username = $user->getName();
3737 $nickname = $user->getOption( 'nickname' );
3738 $nickname = $nickname === '' ? $username : $nickname;
3739
3740 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3741 # Sig. might contain markup; validate this
3742 if( $this->validateSig( $nickname ) !== false ) {
3743 # Validated; clean up (if needed) and return it
3744 return $this->cleanSig( $nickname, true );
3745 } else {
3746 # Failed to validate; fall back to the default
3747 $nickname = $username;
3748 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3749 }
3750 }
3751
3752 // Make sure nickname doesnt get a sig in a sig
3753 $nickname = $this->cleanSigInSig( $nickname );
3754
3755 # If we're still here, make it a link to the user page
3756 $userpage = $user->getUserPage();
3757 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3758 }
3759
3760 /**
3761 * Check that the user's signature contains no bad XML
3762 *
3763 * @param string $text
3764 * @return mixed An expanded string, or false if invalid.
3765 */
3766 function validateSig( $text ) {
3767 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3768 }
3769
3770 /**
3771 * Clean up signature text
3772 *
3773 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3774 * 2) Substitute all transclusions
3775 *
3776 * @param string $text
3777 * @param $parsing Whether we're cleaning (preferences save) or parsing
3778 * @return string Signature text
3779 */
3780 function cleanSig( $text, $parsing = false ) {
3781 global $wgTitle;
3782 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3783
3784 $substWord = MagicWord::get( 'subst' );
3785 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3786 $substText = '{{' . $substWord->getSynonym( 0 );
3787
3788 $text = preg_replace( $substRegex, $substText, $text );
3789 $text = $this->cleanSigInSig( $text );
3790 $text = $this->replaceVariables( $text );
3791
3792 $this->clearState();
3793 return $text;
3794 }
3795
3796 /**
3797 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3798 * @param string $text
3799 * @return string Signature text with /~{3,5}/ removed
3800 */
3801 function cleanSigInSig( $text ) {
3802 $text = preg_replace( '/~{3,5}/', '', $text );
3803 return $text;
3804 }
3805
3806 /**
3807 * Set up some variables which are usually set up in parse()
3808 * so that an external function can call some class members with confidence
3809 * @public
3810 */
3811 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3812 $this->mTitle =& $title;
3813 $this->mOptions = $options;
3814 $this->setOutputType( $outputType );
3815 if ( $clearState ) {
3816 $this->clearState();
3817 }
3818 }
3819
3820 /**
3821 * Transform a MediaWiki message by replacing magic variables.
3822 *
3823 * @param string $text the text to transform
3824 * @param ParserOptions $options options
3825 * @return string the text with variables substituted
3826 * @public
3827 */
3828 function transformMsg( $text, $options ) {
3829 global $wgTitle;
3830 static $executing = false;
3831
3832 $fname = "Parser::transformMsg";
3833
3834 # Guard against infinite recursion
3835 if ( $executing ) {
3836 return $text;
3837 }
3838 $executing = true;
3839
3840 wfProfileIn($fname);
3841
3842 if ( $wgTitle ) {
3843 $this->mTitle = $wgTitle;
3844 } else {
3845 $this->mTitle = Title::newFromText('msg');
3846 }
3847 $this->mOptions = $options;
3848 $this->setOutputType( OT_MSG );
3849 $this->clearState();
3850 $text = $this->replaceVariables( $text );
3851
3852 $executing = false;
3853 wfProfileOut($fname);
3854 return $text;
3855 }
3856
3857 /**
3858 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3859 * The callback should have the following form:
3860 * function myParserHook( $text, $params, &$parser ) { ... }
3861 *
3862 * Transform and return $text. Use $parser for any required context, e.g. use
3863 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3864 *
3865 * @public
3866 *
3867 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3868 * @param mixed $callback The callback function (and object) to use for the tag
3869 *
3870 * @return The old value of the mTagHooks array associated with the hook
3871 */
3872 function setHook( $tag, $callback ) {
3873 $tag = strtolower( $tag );
3874 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3875 $this->mTagHooks[$tag] = $callback;
3876
3877 return $oldVal;
3878 }
3879
3880 /**
3881 * Create a function, e.g. {{sum:1|2|3}}
3882 * The callback function should have the form:
3883 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3884 *
3885 * The callback may either return the text result of the function, or an array with the text
3886 * in element 0, and a number of flags in the other elements. The names of the flags are
3887 * specified in the keys. Valid flags are:
3888 * found The text returned is valid, stop processing the template. This
3889 * is on by default.
3890 * nowiki Wiki markup in the return value should be escaped
3891 * noparse Unsafe HTML tags should not be stripped, etc.
3892 * noargs Don't replace triple-brace arguments in the return value
3893 * isHTML The returned text is HTML, armour it against wikitext transformation
3894 *
3895 * @public
3896 *
3897 * @param string $id The magic word ID
3898 * @param mixed $callback The callback function (and object) to use
3899 * @param integer $flags a combination of the following flags:
3900 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3901 *
3902 * @return The old callback function for this name, if any
3903 */
3904 function setFunctionHook( $id, $callback, $flags = 0 ) {
3905 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id] : null;
3906 $this->mFunctionHooks[$id] = $callback;
3907
3908 # Add to function cache
3909 $mw = MagicWord::get( $id );
3910 if( !$mw )
3911 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3912
3913 $synonyms = $mw->getSynonyms();
3914 $sensitive = intval( $mw->isCaseSensitive() );
3915
3916 foreach ( $synonyms as $syn ) {
3917 # Case
3918 if ( !$sensitive ) {
3919 $syn = strtolower( $syn );
3920 }
3921 # Add leading hash
3922 if ( !( $flags & SFH_NO_HASH ) ) {
3923 $syn = '#' . $syn;
3924 }
3925 # Remove trailing colon
3926 if ( substr( $syn, -1, 1 ) == ':' ) {
3927 $syn = substr( $syn, 0, -1 );
3928 }
3929 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
3930 }
3931 return $oldVal;
3932 }
3933
3934 /**
3935 * Get all registered function hook identifiers
3936 *
3937 * @return array
3938 */
3939 function getFunctionHooks() {
3940 return array_keys( $this->mFunctionHooks );
3941 }
3942
3943 /**
3944 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3945 * Placeholders created in Skin::makeLinkObj()
3946 * Returns an array of links found, indexed by PDBK:
3947 * 0 - broken
3948 * 1 - normal link
3949 * 2 - stub
3950 * $options is a bit field, RLH_FOR_UPDATE to select for update
3951 */
3952 function replaceLinkHolders( &$text, $options = 0 ) {
3953 global $wgUser;
3954 global $wgContLang;
3955
3956 $fname = 'Parser::replaceLinkHolders';
3957 wfProfileIn( $fname );
3958
3959 $pdbks = array();
3960 $colours = array();
3961 $sk =& $this->mOptions->getSkin();
3962 $linkCache =& LinkCache::singleton();
3963
3964 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3965 wfProfileIn( $fname.'-check' );
3966 $dbr =& wfGetDB( DB_SLAVE );
3967 $page = $dbr->tableName( 'page' );
3968 $threshold = $wgUser->getOption('stubthreshold');
3969
3970 # Sort by namespace
3971 asort( $this->mLinkHolders['namespaces'] );
3972
3973 # Generate query
3974 $query = false;
3975 $current = null;
3976 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3977 # Make title object
3978 $title = $this->mLinkHolders['titles'][$key];
3979
3980 # Skip invalid entries.
3981 # Result will be ugly, but prevents crash.
3982 if ( is_null( $title ) ) {
3983 continue;
3984 }
3985 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3986
3987 # Check if it's a static known link, e.g. interwiki
3988 if ( $title->isAlwaysKnown() ) {
3989 $colours[$pdbk] = 1;
3990 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3991 $colours[$pdbk] = 1;
3992 $this->mOutput->addLink( $title, $id );
3993 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3994 $colours[$pdbk] = 0;
3995 } else {
3996 # Not in the link cache, add it to the query
3997 if ( !isset( $current ) ) {
3998 $current = $ns;
3999 $query = "SELECT page_id, page_namespace, page_title";
4000 if ( $threshold > 0 ) {
4001 $query .= ', page_len, page_is_redirect';
4002 }
4003 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4004 } elseif ( $current != $ns ) {
4005 $current = $ns;
4006 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4007 } else {
4008 $query .= ', ';
4009 }
4010
4011 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4012 }
4013 }
4014 if ( $query ) {
4015 $query .= '))';
4016 if ( $options & RLH_FOR_UPDATE ) {
4017 $query .= ' FOR UPDATE';
4018 }
4019
4020 $res = $dbr->query( $query, $fname );
4021
4022 # Fetch data and form into an associative array
4023 # non-existent = broken
4024 # 1 = known
4025 # 2 = stub
4026 while ( $s = $dbr->fetchObject($res) ) {
4027 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4028 $pdbk = $title->getPrefixedDBkey();
4029 $linkCache->addGoodLinkObj( $s->page_id, $title );
4030 $this->mOutput->addLink( $title, $s->page_id );
4031
4032 if ( $threshold > 0 ) {
4033 $size = $s->page_len;
4034 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4035 $colours[$pdbk] = 1;
4036 } else {
4037 $colours[$pdbk] = 2;
4038 }
4039 } else {
4040 $colours[$pdbk] = 1;
4041 }
4042 }
4043 }
4044 wfProfileOut( $fname.'-check' );
4045
4046 # Do a second query for different language variants of links and categories
4047 if($wgContLang->hasVariants()){
4048 $linkBatch = new LinkBatch();
4049 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4050 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4051 $varCategories = array(); // category replacements oldDBkey => newDBkey
4052
4053 $categories = $this->mOutput->getCategoryLinks();
4054
4055 // Add variants of links to link batch
4056 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4057 $title = $this->mLinkHolders['titles'][$key];
4058 if ( is_null( $title ) )
4059 continue;
4060
4061 $pdbk = $title->getPrefixedDBkey();
4062 $titleText = $title->getText();
4063
4064 // generate all variants of the link title text
4065 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4066
4067 // if link was not found (in first query), add all variants to query
4068 if ( !isset($colours[$pdbk]) ){
4069 foreach($allTextVariants as $textVariant){
4070 if($textVariant != $titleText){
4071 $variantTitle = Title::makeTitle( $ns, $textVariant );
4072 if(is_null($variantTitle)) continue;
4073 $linkBatch->addObj( $variantTitle );
4074 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4075 }
4076 }
4077 }
4078 }
4079
4080 // process categories, check if a category exists in some variant
4081 foreach( $categories as $category){
4082 $variants = $wgContLang->convertLinkToAllVariants($category);
4083 foreach($variants as $variant){
4084 if($variant != $category){
4085 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4086 if(is_null($variantTitle)) continue;
4087 $linkBatch->addObj( $variantTitle );
4088 $categoryMap[$variant] = $category;
4089 }
4090 }
4091 }
4092
4093
4094 if(!$linkBatch->isEmpty()){
4095 // construct query
4096 $titleClause = $linkBatch->constructSet('page', $dbr);
4097
4098 $variantQuery = "SELECT page_id, page_namespace, page_title";
4099 if ( $threshold > 0 ) {
4100 $variantQuery .= ', page_len, page_is_redirect';
4101 }
4102
4103 $variantQuery .= " FROM $page WHERE $titleClause";
4104 if ( $options & RLH_FOR_UPDATE ) {
4105 $variantQuery .= ' FOR UPDATE';
4106 }
4107
4108 $varRes = $dbr->query( $variantQuery, $fname );
4109
4110 // for each found variants, figure out link holders and replace
4111 while ( $s = $dbr->fetchObject($varRes) ) {
4112
4113 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4114 $varPdbk = $variantTitle->getPrefixedDBkey();
4115 $vardbk = $variantTitle->getDBkey();
4116
4117 $holderKeys = array();
4118 if(isset($variantMap[$varPdbk])){
4119 $holderKeys = $variantMap[$varPdbk];
4120 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4121 $this->mOutput->addLink( $variantTitle, $s->page_id );
4122 }
4123
4124 // loop over link holders
4125 foreach($holderKeys as $key){
4126 $title = $this->mLinkHolders['titles'][$key];
4127 if ( is_null( $title ) ) continue;
4128
4129 $pdbk = $title->getPrefixedDBkey();
4130
4131 if(!isset($colours[$pdbk])){
4132 // found link in some of the variants, replace the link holder data
4133 $this->mLinkHolders['titles'][$key] = $variantTitle;
4134 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4135
4136 // set pdbk and colour
4137 $pdbks[$key] = $varPdbk;
4138 if ( $threshold > 0 ) {
4139 $size = $s->page_len;
4140 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4141 $colours[$varPdbk] = 1;
4142 } else {
4143 $colours[$varPdbk] = 2;
4144 }
4145 }
4146 else {
4147 $colours[$varPdbk] = 1;
4148 }
4149 }
4150 }
4151
4152 // check if the object is a variant of a category
4153 if(isset($categoryMap[$vardbk])){
4154 $oldkey = $categoryMap[$vardbk];
4155 if($oldkey != $vardbk)
4156 $varCategories[$oldkey]=$vardbk;
4157 }
4158 }
4159
4160 // rebuild the categories in original order (if there are replacements)
4161 if(count($varCategories)>0){
4162 $newCats = array();
4163 $originalCats = $this->mOutput->getCategories();
4164 foreach($originalCats as $cat => $sortkey){
4165 // make the replacement
4166 if( array_key_exists($cat,$varCategories) )
4167 $newCats[$varCategories[$cat]] = $sortkey;
4168 else $newCats[$cat] = $sortkey;
4169 }
4170 $this->mOutput->setCategoryLinks($newCats);
4171 }
4172 }
4173 }
4174
4175 # Construct search and replace arrays
4176 wfProfileIn( $fname.'-construct' );
4177 $replacePairs = array();
4178 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4179 $pdbk = $pdbks[$key];
4180 $searchkey = "<!--LINK $key-->";
4181 $title = $this->mLinkHolders['titles'][$key];
4182 if ( empty( $colours[$pdbk] ) ) {
4183 $linkCache->addBadLinkObj( $title );
4184 $colours[$pdbk] = 0;
4185 $this->mOutput->addLink( $title, 0 );
4186 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4187 $this->mLinkHolders['texts'][$key],
4188 $this->mLinkHolders['queries'][$key] );
4189 } elseif ( $colours[$pdbk] == 1 ) {
4190 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4191 $this->mLinkHolders['texts'][$key],
4192 $this->mLinkHolders['queries'][$key] );
4193 } elseif ( $colours[$pdbk] == 2 ) {
4194 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4195 $this->mLinkHolders['texts'][$key],
4196 $this->mLinkHolders['queries'][$key] );
4197 }
4198 }
4199 $replacer = new HashtableReplacer( $replacePairs, 1 );
4200 wfProfileOut( $fname.'-construct' );
4201
4202 # Do the thing
4203 wfProfileIn( $fname.'-replace' );
4204 $text = preg_replace_callback(
4205 '/(<!--LINK .*?-->)/',
4206 $replacer->cb(),
4207 $text);
4208
4209 wfProfileOut( $fname.'-replace' );
4210 }
4211
4212 # Now process interwiki link holders
4213 # This is quite a bit simpler than internal links
4214 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4215 wfProfileIn( $fname.'-interwiki' );
4216 # Make interwiki link HTML
4217 $replacePairs = array();
4218 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4219 $title = $this->mInterwikiLinkHolders['titles'][$key];
4220 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4221 }
4222 $replacer = new HashtableReplacer( $replacePairs, 1 );
4223
4224 $text = preg_replace_callback(
4225 '/<!--IWLINK (.*?)-->/',
4226 $replacer->cb(),
4227 $text );
4228 wfProfileOut( $fname.'-interwiki' );
4229 }
4230
4231 wfProfileOut( $fname );
4232 return $colours;
4233 }
4234
4235 /**
4236 * Replace <!--LINK--> link placeholders with plain text of links
4237 * (not HTML-formatted).
4238 * @param string $text
4239 * @return string
4240 */
4241 function replaceLinkHoldersText( $text ) {
4242 $fname = 'Parser::replaceLinkHoldersText';
4243 wfProfileIn( $fname );
4244
4245 $text = preg_replace_callback(
4246 '/<!--(LINK|IWLINK) (.*?)-->/',
4247 array( &$this, 'replaceLinkHoldersTextCallback' ),
4248 $text );
4249
4250 wfProfileOut( $fname );
4251 return $text;
4252 }
4253
4254 /**
4255 * @param array $matches
4256 * @return string
4257 * @private
4258 */
4259 function replaceLinkHoldersTextCallback( $matches ) {
4260 $type = $matches[1];
4261 $key = $matches[2];
4262 if( $type == 'LINK' ) {
4263 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4264 return $this->mLinkHolders['texts'][$key];
4265 }
4266 } elseif( $type == 'IWLINK' ) {
4267 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4268 return $this->mInterwikiLinkHolders['texts'][$key];
4269 }
4270 }
4271 return $matches[0];
4272 }
4273
4274 /**
4275 * Tag hook handler for 'pre'.
4276 */
4277 function renderPreTag( $text, $attribs ) {
4278 // Backwards-compatibility hack
4279 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4280
4281 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4282 return wfOpenElement( 'pre', $attribs ) .
4283 Xml::escapeTagsOnly( $content ) .
4284 '</pre>';
4285 }
4286
4287 /**
4288 * Renders an image gallery from a text with one line per image.
4289 * text labels may be given by using |-style alternative text. E.g.
4290 * Image:one.jpg|The number "1"
4291 * Image:tree.jpg|A tree
4292 * given as text will return the HTML of a gallery with two images,
4293 * labeled 'The number "1"' and
4294 * 'A tree'.
4295 */
4296 function renderImageGallery( $text, $params ) {
4297 $ig = new ImageGallery();
4298 $ig->setShowBytes( false );
4299 $ig->setShowFilename( false );
4300 $ig->setParsing();
4301 $ig->useSkin( $this->mOptions->getSkin() );
4302
4303 if( isset( $params['caption'] ) ) {
4304 $caption = $params['caption'];
4305 $caption = htmlspecialchars( $caption );
4306 $caption = $this->replaceInternalLinks( $caption );
4307 $ig->setCaptionSafe( $caption );
4308 }
4309
4310 $lines = explode( "\n", $text );
4311 foreach ( $lines as $line ) {
4312 # match lines like these:
4313 # Image:someimage.jpg|This is some image
4314 $matches = array();
4315 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4316 # Skip empty lines
4317 if ( count( $matches ) == 0 ) {
4318 continue;
4319 }
4320 $tp = Title::newFromText( $matches[1] );
4321 $nt =& $tp;
4322 if( is_null( $nt ) ) {
4323 # Bogus title. Ignore these so we don't bomb out later.
4324 continue;
4325 }
4326 if ( isset( $matches[3] ) ) {
4327 $label = $matches[3];
4328 } else {
4329 $label = '';
4330 }
4331
4332 $pout = $this->parse( $label,
4333 $this->mTitle,
4334 $this->mOptions,
4335 false, // Strip whitespace...?
4336 false // Don't clear state!
4337 );
4338 $html = $pout->getText();
4339
4340 $ig->add( new Image( $nt ), $html );
4341
4342 # Only add real images (bug #5586)
4343 if ( $nt->getNamespace() == NS_IMAGE ) {
4344 $this->mOutput->addImage( $nt->getDBkey() );
4345 }
4346 }
4347 return $ig->toHTML();
4348 }
4349
4350 /**
4351 * Parse image options text and use it to make an image
4352 */
4353 function makeImage( $nt, $options ) {
4354 global $wgUseImageResize, $wgDjvuRenderer;
4355
4356 $align = '';
4357
4358 # Check if the options text is of the form "options|alt text"
4359 # Options are:
4360 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4361 # * left no resizing, just left align. label is used for alt= only
4362 # * right same, but right aligned
4363 # * none same, but not aligned
4364 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4365 # * center center the image
4366 # * framed Keep original image size, no magnify-button.
4367
4368 $part = explode( '|', $options);
4369
4370 $mwThumb =& MagicWord::get( 'img_thumbnail' );
4371 $mwManualThumb =& MagicWord::get( 'img_manualthumb' );
4372 $mwLeft =& MagicWord::get( 'img_left' );
4373 $mwRight =& MagicWord::get( 'img_right' );
4374 $mwNone =& MagicWord::get( 'img_none' );
4375 $mwWidth =& MagicWord::get( 'img_width' );
4376 $mwCenter =& MagicWord::get( 'img_center' );
4377 $mwFramed =& MagicWord::get( 'img_framed' );
4378 $mwPage =& MagicWord::get( 'img_page' );
4379 $caption = '';
4380
4381 $width = $height = $framed = $thumb = false;
4382 $page = null;
4383 $manual_thumb = '' ;
4384
4385 foreach( $part as $val ) {
4386 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4387 $thumb=true;
4388 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4389 # use manually specified thumbnail
4390 $thumb=true;
4391 $manual_thumb = $match;
4392 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4393 # remember to set an alignment, don't render immediately
4394 $align = 'right';
4395 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4396 # remember to set an alignment, don't render immediately
4397 $align = 'left';
4398 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4399 # remember to set an alignment, don't render immediately
4400 $align = 'center';
4401 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4402 # remember to set an alignment, don't render immediately
4403 $align = 'none';
4404 } elseif ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4405 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4406 # Select a page in a multipage document
4407 $page = $match;
4408 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4409 wfDebug( "img_width match: $match\n" );
4410 # $match is the image width in pixels
4411 $m = array();
4412 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4413 $width = intval( $m[1] );
4414 $height = intval( $m[2] );
4415 } else {
4416 $width = intval($match);
4417 }
4418 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4419 $framed=true;
4420 } else {
4421 $caption = $val;
4422 }
4423 }
4424 # Strip bad stuff out of the alt text
4425 $alt = $this->replaceLinkHoldersText( $caption );
4426
4427 # make sure there are no placeholders in thumbnail attributes
4428 # that are later expanded to html- so expand them now and
4429 # remove the tags
4430 $alt = $this->mStripState->unstripBoth( $alt );
4431 $alt = Sanitizer::stripAllTags( $alt );
4432
4433 # Linker does the rest
4434 $sk =& $this->mOptions->getSkin();
4435 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page );
4436 }
4437
4438 /**
4439 * Set a flag in the output object indicating that the content is dynamic and
4440 * shouldn't be cached.
4441 */
4442 function disableCache() {
4443 wfDebug( "Parser output marked as uncacheable.\n" );
4444 $this->mOutput->mCacheTime = -1;
4445 }
4446
4447 /**#@+
4448 * Callback from the Sanitizer for expanding items found in HTML attribute
4449 * values, so they can be safely tested and escaped.
4450 * @param string $text
4451 * @param array $args
4452 * @return string
4453 * @private
4454 */
4455 function attributeStripCallback( &$text, $args ) {
4456 $text = $this->replaceVariables( $text, $args );
4457 $text = $this->mStripState->unstripBoth( $text );
4458 return $text;
4459 }
4460
4461 /**#@-*/
4462
4463 /**#@+
4464 * Accessor/mutator
4465 */
4466 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4467 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4468 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4469 /**#@-*/
4470
4471 /**#@+
4472 * Accessor
4473 */
4474 function getTags() { return array_keys( $this->mTagHooks ); }
4475 /**#@-*/
4476
4477
4478 /**
4479 * Break wikitext input into sections, and either pull or replace
4480 * some particular section's text.
4481 *
4482 * External callers should use the getSection and replaceSection methods.
4483 *
4484 * @param $text Page wikitext
4485 * @param $section Numbered section. 0 pulls the text before the first
4486 * heading; other numbers will pull the given section
4487 * along with its lower-level subsections.
4488 * @param $mode One of "get" or "replace"
4489 * @param $newtext Replacement text for section data.
4490 * @return string for "get", the extracted section text.
4491 * for "replace", the whole page with the section replaced.
4492 */
4493 private function extractSections( $text, $section, $mode, $newtext='' ) {
4494 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4495 # comments to be stripped as well)
4496 $stripState = new StripState;
4497
4498 $oldOutputType = $this->mOutputType;
4499 $oldOptions = $this->mOptions;
4500 $this->mOptions = new ParserOptions();
4501 $this->setOutputType( OT_WIKI );
4502
4503 $striptext = $this->strip( $text, $stripState, true );
4504
4505 $this->setOutputType( $oldOutputType );
4506 $this->mOptions = $oldOptions;
4507
4508 # now that we can be sure that no pseudo-sections are in the source,
4509 # split it up by section
4510 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4511 $comment = "(?:$uniq-!--.*?QINU)";
4512 $secs = preg_split(
4513 /*
4514 "/
4515 ^(
4516 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4517 (?:
4518 (=+) # Should this be limited to 6?
4519 .+? # Section title...
4520 \\2 # Ending = count must match start
4521 |
4522 ^
4523 <h([1-6])\b.*?>
4524 .*?
4525 <\/h\\3\s*>
4526 )
4527 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4528 )$
4529 /mix",
4530 */
4531 "/
4532 (
4533 ^
4534 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4535 (=+) # Should this be limited to 6?
4536 .+? # Section title...
4537 \\2 # Ending = count must match start
4538 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4539 $
4540 |
4541 <h([1-6])\b.*?>
4542 .*?
4543 <\/h\\3\s*>
4544 )
4545 /mix",
4546 $striptext, -1,
4547 PREG_SPLIT_DELIM_CAPTURE);
4548
4549 if( $mode == "get" ) {
4550 if( $section == 0 ) {
4551 // "Section 0" returns the content before any other section.
4552 $rv = $secs[0];
4553 } else {
4554 $rv = "";
4555 }
4556 } elseif( $mode == "replace" ) {
4557 if( $section == 0 ) {
4558 $rv = $newtext . "\n\n";
4559 $remainder = true;
4560 } else {
4561 $rv = $secs[0];
4562 $remainder = false;
4563 }
4564 }
4565 $count = 0;
4566 $sectionLevel = 0;
4567 for( $index = 1; $index < count( $secs ); ) {
4568 $headerLine = $secs[$index++];
4569 if( $secs[$index] ) {
4570 // A wiki header
4571 $headerLevel = strlen( $secs[$index++] );
4572 } else {
4573 // An HTML header
4574 $index++;
4575 $headerLevel = intval( $secs[$index++] );
4576 }
4577 $content = $secs[$index++];
4578
4579 $count++;
4580 if( $mode == "get" ) {
4581 if( $count == $section ) {
4582 $rv = $headerLine . $content;
4583 $sectionLevel = $headerLevel;
4584 } elseif( $count > $section ) {
4585 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4586 $rv .= $headerLine . $content;
4587 } else {
4588 // Broke out to a higher-level section
4589 break;
4590 }
4591 }
4592 } elseif( $mode == "replace" ) {
4593 if( $count < $section ) {
4594 $rv .= $headerLine . $content;
4595 } elseif( $count == $section ) {
4596 $rv .= $newtext . "\n\n";
4597 $sectionLevel = $headerLevel;
4598 } elseif( $count > $section ) {
4599 if( $headerLevel <= $sectionLevel ) {
4600 // Passed the section's sub-parts.
4601 $remainder = true;
4602 }
4603 if( $remainder ) {
4604 $rv .= $headerLine . $content;
4605 }
4606 }
4607 }
4608 }
4609 # reinsert stripped tags
4610 $rv = trim( $stripState->unstripBoth( $rv ) );
4611 return $rv;
4612 }
4613
4614 /**
4615 * This function returns the text of a section, specified by a number ($section).
4616 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4617 * the first section before any such heading (section 0).
4618 *
4619 * If a section contains subsections, these are also returned.
4620 *
4621 * @param $text String: text to look in
4622 * @param $section Integer: section number
4623 * @return string text of the requested section
4624 */
4625 function getSection( $text, $section ) {
4626 return $this->extractSections( $text, $section, "get" );
4627 }
4628
4629 function replaceSection( $oldtext, $section, $text ) {
4630 return $this->extractSections( $oldtext, $section, "replace", $text );
4631 }
4632
4633 /**
4634 * Get the timestamp associated with the current revision, adjusted for
4635 * the default server-local timestamp
4636 */
4637 function getRevisionTimestamp() {
4638 if ( is_null( $this->mRevisionTimestamp ) ) {
4639 wfProfileIn( __METHOD__ );
4640 global $wgContLang;
4641 $dbr =& wfGetDB( DB_SLAVE );
4642 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4643 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4644
4645 // Normalize timestamp to internal MW format for timezone processing.
4646 // This has the added side-effect of replacing a null value with
4647 // the current time, which gives us more sensible behavior for
4648 // previews.
4649 $timestamp = wfTimestamp( TS_MW, $timestamp );
4650
4651 // The cryptic '' timezone parameter tells to use the site-default
4652 // timezone offset instead of the user settings.
4653 //
4654 // Since this value will be saved into the parser cache, served
4655 // to other users, and potentially even used inside links and such,
4656 // it needs to be consistent for all visitors.
4657 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4658
4659 wfProfileOut( __METHOD__ );
4660 }
4661 return $this->mRevisionTimestamp;
4662 }
4663
4664 /**
4665 * Mutator for $mDefaultSort
4666 *
4667 * @param $sort New value
4668 */
4669 public function setDefaultSort( $sort ) {
4670 $this->mDefaultSort = $sort;
4671 }
4672
4673 /**
4674 * Accessor for $mDefaultSort
4675 * Will use the title/prefixed title if none is set
4676 *
4677 * @return string
4678 */
4679 public function getDefaultSort() {
4680 if( $this->mDefaultSort !== false ) {
4681 return $this->mDefaultSort;
4682 } else {
4683 return $this->mTitle->getNamespace() == NS_CATEGORY
4684 ? $this->mTitle->getText()
4685 : $this->mTitle->getPrefixedText();
4686 }
4687 }
4688
4689 }
4690
4691 /**
4692 * @todo document
4693 * @package MediaWiki
4694 */
4695 class ParserOutput
4696 {
4697 var $mText, # The output text
4698 $mLanguageLinks, # List of the full text of language links, in the order they appear
4699 $mCategories, # Map of category names to sort keys
4700 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4701 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4702 $mVersion, # Compatibility check
4703 $mTitleText, # title text of the chosen language variant
4704 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4705 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4706 $mImages, # DB keys of the images used, in the array key only
4707 $mExternalLinks, # External link URLs, in the key only
4708 $mHTMLtitle, # Display HTML title
4709 $mSubtitle, # Additional subtitle
4710 $mNewSection, # Show a new section link?
4711 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4712
4713 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4714 $containsOldMagic = false, $titletext = '' )
4715 {
4716 $this->mText = $text;
4717 $this->mLanguageLinks = $languageLinks;
4718 $this->mCategories = $categoryLinks;
4719 $this->mContainsOldMagic = $containsOldMagic;
4720 $this->mCacheTime = '';
4721 $this->mVersion = MW_PARSER_VERSION;
4722 $this->mTitleText = $titletext;
4723 $this->mLinks = array();
4724 $this->mTemplates = array();
4725 $this->mImages = array();
4726 $this->mExternalLinks = array();
4727 $this->mHTMLtitle = "" ;
4728 $this->mSubtitle = "" ;
4729 $this->mNewSection = false;
4730 $this->mNoGallery = false;
4731 }
4732
4733 function getText() { return $this->mText; }
4734 function &getLanguageLinks() { return $this->mLanguageLinks; }
4735 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4736 function &getCategories() { return $this->mCategories; }
4737 function getCacheTime() { return $this->mCacheTime; }
4738 function getTitleText() { return $this->mTitleText; }
4739 function &getLinks() { return $this->mLinks; }
4740 function &getTemplates() { return $this->mTemplates; }
4741 function &getImages() { return $this->mImages; }
4742 function &getExternalLinks() { return $this->mExternalLinks; }
4743 function getNoGallery() { return $this->mNoGallery; }
4744 function getSubtitle() { return $this->mSubtitle; }
4745
4746 function containsOldMagic() { return $this->mContainsOldMagic; }
4747 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4748 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4749 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4750 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4751 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4752 function setTitleText( $t ) { return wfSetVar($this->mTitleText, $t); }
4753 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle, $st ); }
4754
4755 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4756 function addImage( $name ) { $this->mImages[$name] = 1; }
4757 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4758 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4759
4760 function setNewSection( $value ) {
4761 $this->mNewSection = (bool)$value;
4762 }
4763 function getNewSection() {
4764 return (bool)$this->mNewSection;
4765 }
4766
4767 function addLink( $title, $id = null ) {
4768 $ns = $title->getNamespace();
4769 $dbk = $title->getDBkey();
4770 if ( !isset( $this->mLinks[$ns] ) ) {
4771 $this->mLinks[$ns] = array();
4772 }
4773 if ( is_null( $id ) ) {
4774 $id = $title->getArticleID();
4775 }
4776 $this->mLinks[$ns][$dbk] = $id;
4777 }
4778
4779 function addTemplate( $title, $id ) {
4780 $ns = $title->getNamespace();
4781 $dbk = $title->getDBkey();
4782 if ( !isset( $this->mTemplates[$ns] ) ) {
4783 $this->mTemplates[$ns] = array();
4784 }
4785 $this->mTemplates[$ns][$dbk] = $id;
4786 }
4787
4788 /**
4789 * Return true if this cached output object predates the global or
4790 * per-article cache invalidation timestamps, or if it comes from
4791 * an incompatible older version.
4792 *
4793 * @param string $touched the affected article's last touched timestamp
4794 * @return bool
4795 * @public
4796 */
4797 function expired( $touched ) {
4798 global $wgCacheEpoch;
4799 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4800 $this->getCacheTime() < $touched ||
4801 $this->getCacheTime() <= $wgCacheEpoch ||
4802 !isset( $this->mVersion ) ||
4803 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4804 }
4805 }
4806
4807 /**
4808 * Set options of the Parser
4809 * @todo document
4810 * @package MediaWiki
4811 */
4812 class ParserOptions
4813 {
4814 # All variables are supposed to be private in theory, although in practise this is not the case.
4815 var $mUseTeX; # Use texvc to expand <math> tags
4816 var $mUseDynamicDates; # Use DateFormatter to format dates
4817 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4818 var $mAllowExternalImages; # Allow external images inline
4819 var $mAllowExternalImagesFrom; # If not, any exception?
4820 var $mSkin; # Reference to the preferred skin
4821 var $mDateFormat; # Date format index
4822 var $mEditSection; # Create "edit section" links
4823 var $mNumberHeadings; # Automatically number headings
4824 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4825 var $mTidy; # Ask for tidy cleanup
4826 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4827 var $mMaxIncludeSize; # Maximum size of template expansions, in bytes
4828 var $mRemoveComments; # Remove HTML comments. ONLY APPLIES TO PREPROCESS OPERATIONS
4829
4830 var $mUser; # Stored user object, just used to initialise the skin
4831
4832 function getUseTeX() { return $this->mUseTeX; }
4833 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4834 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4835 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4836 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4837 function getEditSection() { return $this->mEditSection; }
4838 function getNumberHeadings() { return $this->mNumberHeadings; }
4839 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4840 function getTidy() { return $this->mTidy; }
4841 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4842 function getMaxIncludeSize() { return $this->mMaxIncludeSize; }
4843 function getRemoveComments() { return $this->mRemoveComments; }
4844
4845 function &getSkin() {
4846 if ( !isset( $this->mSkin ) ) {
4847 $this->mSkin = $this->mUser->getSkin();
4848 }
4849 return $this->mSkin;
4850 }
4851
4852 function getDateFormat() {
4853 if ( !isset( $this->mDateFormat ) ) {
4854 $this->mDateFormat = $this->mUser->getDatePreference();
4855 }
4856 return $this->mDateFormat;
4857 }
4858
4859 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4860 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4861 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4862 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4863 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4864 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4865 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4866 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4867 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4868 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4869 function setSkin( $x ) { $this->mSkin = $x; }
4870 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4871 function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize, $x ); }
4872 function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments, $x ); }
4873
4874 function ParserOptions( $user = null ) {
4875 $this->initialiseFromUser( $user );
4876 }
4877
4878 /**
4879 * Get parser options
4880 * @static
4881 */
4882 static function newFromUser( $user ) {
4883 return new ParserOptions( $user );
4884 }
4885
4886 /** Get user options */
4887 function initialiseFromUser( $userInput ) {
4888 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4889 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion, $wgMaxArticleSize;
4890 $fname = 'ParserOptions::initialiseFromUser';
4891 wfProfileIn( $fname );
4892 if ( !$userInput ) {
4893 global $wgUser;
4894 if ( isset( $wgUser ) ) {
4895 $user = $wgUser;
4896 } else {
4897 $user = new User;
4898 }
4899 } else {
4900 $user =& $userInput;
4901 }
4902
4903 $this->mUser = $user;
4904
4905 $this->mUseTeX = $wgUseTeX;
4906 $this->mUseDynamicDates = $wgUseDynamicDates;
4907 $this->mInterwikiMagic = $wgInterwikiMagic;
4908 $this->mAllowExternalImages = $wgAllowExternalImages;
4909 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4910 $this->mSkin = null; # Deferred
4911 $this->mDateFormat = null; # Deferred
4912 $this->mEditSection = true;
4913 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4914 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4915 $this->mTidy = false;
4916 $this->mInterfaceMessage = false;
4917 $this->mMaxIncludeSize = $wgMaxArticleSize * 1024;
4918 $this->mRemoveComments = true;
4919 wfProfileOut( $fname );
4920 }
4921 }
4922
4923 class OnlyIncludeReplacer {
4924 var $output = '';
4925
4926 function replace( $matches ) {
4927 if ( substr( $matches[1], -1 ) == "\n" ) {
4928 $this->output .= substr( $matches[1], 0, -1 );
4929 } else {
4930 $this->output .= $matches[1];
4931 }
4932 }
4933 }
4934
4935 class StripState {
4936 var $general, $nowiki;
4937
4938 function __construct() {
4939 $this->general = new ReplacementArray;
4940 $this->nowiki = new ReplacementArray;
4941 }
4942
4943 function unstripGeneral( $text ) {
4944 wfProfileIn( __METHOD__ );
4945 $text = $this->general->replace( $text );
4946 wfProfileOut( __METHOD__ );
4947 return $text;
4948 }
4949
4950 function unstripNoWiki( $text ) {
4951 wfProfileIn( __METHOD__ );
4952 $text = $this->nowiki->replace( $text );
4953 wfProfileOut( __METHOD__ );
4954 return $text;
4955 }
4956
4957 function unstripBoth( $text ) {
4958 wfProfileIn( __METHOD__ );
4959 $text = $this->general->replace( $text );
4960 $text = $this->nowiki->replace( $text );
4961 wfProfileOut( __METHOD__ );
4962 return $text;
4963 }
4964 }
4965
4966 ?>