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