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