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