3 * @defgroup Parser Parser
7 * File for Parser and related classes
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).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Return the content of a section from an article for section editing
30 * Replaces a section by number inside an article
32 * Removes <noinclude> sections, and <includeonly> tags.
35 * objects: $wgLang, $wgContLang
37 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
40 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
41 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
42 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
45 * * only within ParserOptions
52 * Update this version number when the ParserOutput format
53 * changes in an incompatible way, so the parser cache
54 * can automatically discard old data.
56 const VERSION
= '1.6.4';
58 # Flags for Parser::setFunctionHook
59 # Also available as global constants from Defines.php
60 const SFH_NO_HASH
= 1;
61 const SFH_OBJECT_ARGS
= 2;
63 # Constants needed for external link processing
64 # Everything except bracket, space, or control characters
65 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
66 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
67 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
69 # State constants for the definition list colon extraction
70 const COLON_STATE_TEXT
= 0;
71 const COLON_STATE_TAG
= 1;
72 const COLON_STATE_TAGSTART
= 2;
73 const COLON_STATE_CLOSETAG
= 3;
74 const COLON_STATE_TAGSLASH
= 4;
75 const COLON_STATE_COMMENT
= 5;
76 const COLON_STATE_COMMENTDASH
= 6;
77 const COLON_STATE_COMMENTDASHDASH
= 7;
79 # Flags for preprocessToDom
80 const PTD_FOR_INCLUSION
= 1;
82 # Allowed values for $this->mOutputType
83 # Parameter to startExternalParse().
84 const OT_HTML
= 1; # like parse()
85 const OT_WIKI
= 2; # like preSaveTransform()
86 const OT_PREPROCESS
= 3; # like preprocess()
88 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
90 # Marker Suffix needs to be accessible staticly.
91 const MARKER_SUFFIX
= "-QINU\x7f";
94 var $mTagHooks = array();
95 var $mTransparentTagHooks = array();
96 var $mFunctionHooks = array();
97 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
98 var $mFunctionTagHooks = array();
99 var $mStripList = array();
100 var $mDefaultStripList = array();
101 var $mVarCache = array();
102 var $mImageParams = array();
103 var $mImageParamsMagicArray = array();
104 var $mMarkerIndex = 0;
105 var $mFirstCall = true;
106 var $mVariables, $mSubstWords; # Initialised by initialiseVariables()
107 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
110 # Cleared with clearState():
111 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
112 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
113 var $mLinkHolders, $mLinkID;
114 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
115 var $mTplExpandCache; # empty-frame expansion cache
116 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
117 var $mExpensiveFunctionCount; # number of expensive parser function calls
118 var $mUser; # User object; only used when doing pre-save transform
121 # These are variables reset at least once per parse regardless of $clearState
122 var $mOptions; # ParserOptions object
123 var $mTitle; # Title context, used for self-link rendering and similar things
124 var $mOutputType; # Output type, one of the OT_xxx constants
125 var $ot; # Shortcut alias, see setOutputType()
126 var $mRevisionObject; # The revision object of the specified revision ID
127 var $mRevisionId; # ID to display in {{REVISIONID}} tags
128 var $mRevisionTimestamp; # The timestamp of the specified revision ID
129 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
130 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
137 function __construct( $conf = array() ) {
138 $this->mConf
= $conf;
139 $this->mUrlProtocols
= wfUrlProtocols();
140 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
141 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
142 if ( isset( $conf['preprocessorClass'] ) ) {
143 $this->mPreprocessorClass
= $conf['preprocessorClass'];
144 } elseif ( extension_loaded( 'domxml' ) ) {
145 # PECL extension that conflicts with the core DOM extension (bug 13770)
146 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
147 $this->mPreprocessorClass
= 'Preprocessor_Hash';
148 } elseif ( extension_loaded( 'dom' ) ) {
149 $this->mPreprocessorClass
= 'Preprocessor_DOM';
151 $this->mPreprocessorClass
= 'Preprocessor_Hash';
156 * Reduce memory usage to reduce the impact of circular references
158 function __destruct() {
159 if ( isset( $this->mLinkHolders
) ) {
160 $this->mLinkHolders
->__destruct();
162 foreach ( $this as $name => $value ) {
163 unset( $this->$name );
168 * Do various kinds of initialisation on the first call of the parser
170 function firstCallInit() {
171 if ( !$this->mFirstCall
) {
174 $this->mFirstCall
= false;
176 wfProfileIn( __METHOD__
);
178 CoreParserFunctions
::register( $this );
179 CoreTagHooks
::register( $this );
180 $this->initialiseVariables();
182 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
183 wfProfileOut( __METHOD__
);
191 function clearState() {
192 wfProfileIn( __METHOD__
);
193 if ( $this->mFirstCall
) {
194 $this->firstCallInit();
196 $this->mOutput
= new ParserOutput
;
197 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
198 $this->mAutonumber
= 0;
199 $this->mLastSection
= '';
200 $this->mDTopen
= false;
201 $this->mIncludeCount
= array();
202 $this->mStripState
= new StripState
;
203 $this->mArgStack
= false;
204 $this->mInPre
= false;
205 $this->mLinkHolders
= new LinkHolderArray( $this );
207 $this->mRevisionObject
= $this->mRevisionTimestamp
=
208 $this->mRevisionId
= $this->mRevisionUser
= null;
209 $this->mVarCache
= array();
213 * Prefix for temporary replacement strings for the multipass parser.
214 * \x07 should never appear in input as it's disallowed in XML.
215 * Using it at the front also gives us a little extra robustness
216 * since it shouldn't match when butted up against identifier-like
219 * Must not consist of all title characters, or else it will change
220 * the behaviour of <nowiki> in a link.
222 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
223 # Changed to \x7f to allow XML double-parsing -- TS
224 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
227 # Clear these on every parse, bug 4549
228 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
230 $this->mShowToc
= true;
231 $this->mForceTocPosition
= false;
232 $this->mIncludeSizes
= array(
236 $this->mPPNodeCount
= 0;
237 $this->mDefaultSort
= false;
238 $this->mHeadings
= array();
239 $this->mDoubleUnderscores
= array();
240 $this->mExpensiveFunctionCount
= 0;
243 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
244 $this->mPreprocessor
= null;
247 wfRunHooks( 'ParserClearState', array( &$this ) );
248 wfProfileOut( __METHOD__
);
252 * Convert wikitext to HTML
253 * Do not call this function recursively.
255 * @param $text String: text we want to parse
256 * @param $title A title object
257 * @param $options ParserOptions
258 * @param $linestart boolean
259 * @param $clearState boolean
260 * @param $revid Int: number to pass in {{REVISIONID}}
261 * @return ParserOutput a ParserOutput
263 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
265 * First pass--just handle <nowiki> sections, pass the rest off
266 * to internalParse() which does all the real work.
269 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
270 $fname = __METHOD__
.'-' . wfGetCaller();
271 wfProfileIn( __METHOD__
);
272 wfProfileIn( $fname );
274 $this->mOptions
= $options;
279 $this->setTitle( $title ); # Page title has to be set for the pre-processor
281 $oldRevisionId = $this->mRevisionId
;
282 $oldRevisionObject = $this->mRevisionObject
;
283 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
284 $oldRevisionUser = $this->mRevisionUser
;
285 if ( $revid !== null ) {
286 $this->mRevisionId
= $revid;
287 $this->mRevisionObject
= null;
288 $this->mRevisionTimestamp
= null;
289 $this->mRevisionUser
= null;
291 $this->setOutputType( self
::OT_HTML
);
292 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
294 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
295 $text = $this->internalParse( $text );
297 $text = $this->mStripState
->unstripGeneral( $text );
299 # Clean up special characters, only run once, next-to-last before doBlockLevels
301 # french spaces, last one Guillemet-left
302 # only if there is something before the space
303 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
304 # french spaces, Guillemet-right
305 '/(\\302\\253) /' => '\\1 ',
306 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
308 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
310 $text = $this->doBlockLevels( $text, $linestart );
312 $this->replaceLinkHolders( $text );
315 * The page doesn't get language converted if
317 * b) Content isn't converted
318 * c) It's a conversion table
320 if ( !( $wgDisableLangConversion
321 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
322 ||
$this->mTitle
->isConversionTable() ) ) {
324 # The position of the convert() call should not be changed. it
325 # assumes that the links are all replaced and the only thing left
326 # is the <nowiki> mark.
328 $text = $wgContLang->convert( $text );
332 * A converted title will be provided in the output object if title and
333 * content conversion are enabled, the article text does not contain
334 * a conversion-suppressing double-underscore tag, and no
335 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
336 * automatic link conversion.
338 if ( !( $wgDisableLangConversion
339 ||
$wgDisableTitleConversion
340 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
341 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
342 ||
$this->mOutput
->getDisplayTitle() !== false ) )
344 $convruletitle = $wgContLang->getConvRuleTitle();
345 if ( $convruletitle ) {
346 $this->mOutput
->setTitleText( $convruletitle );
348 $titleText = $wgContLang->convertTitle( $title );
349 $this->mOutput
->setTitleText( $titleText );
353 $text = $this->mStripState
->unstripNoWiki( $text );
355 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
357 //!JF Move to its own function
359 $uniq_prefix = $this->mUniqPrefix
;
361 $elements = array_keys( $this->mTransparentTagHooks
);
362 $text = $this->extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
364 foreach ( $matches as $marker => $data ) {
365 list( $element, $content, $params, $tag ) = $data;
366 $tagName = strtolower( $element );
367 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
368 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
372 $this->mStripState
->general
->setPair( $marker, $output );
374 $text = $this->mStripState
->unstripGeneral( $text );
376 $text = Sanitizer
::normalizeCharReferences( $text );
378 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
379 $text = MWTidy
::tidy( $text );
381 # attempt to sanitize at least some nesting problems
382 # (bug #2702 and quite a few others)
384 # ''Something [http://www.cool.com cool''] -->
385 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
386 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
387 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
388 # fix up an anchor inside another anchor, only
389 # at least for a single single nested link (bug 3695)
390 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
391 '\\1\\2</a>\\3</a>\\1\\4</a>',
392 # fix div inside inline elements- doBlockLevels won't wrap a line which
393 # contains a div, so fix it up here; replace
394 # div with escaped text
395 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
396 '\\1\\3<div\\5>\\6</div>\\8\\9',
397 # remove empty italic or bold tag pairs, some
398 # introduced by rules above
399 '/<([bi])><\/\\1>/' => '',
402 $text = preg_replace(
403 array_keys( $tidyregs ),
404 array_values( $tidyregs ),
407 global $wgExpensiveParserFunctionLimit;
408 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
409 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
412 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
414 # Information on include size limits, for the benefit of users who try to skirt them
415 if ( $this->mOptions
->getEnableLimitReport() ) {
416 $max = $this->mOptions
->getMaxIncludeSize();
417 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
419 "NewPP limit report\n" .
420 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
421 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
422 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
424 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
425 $text .= "\n<!-- \n$limitReport-->\n";
427 $this->mOutput
->setText( $text );
429 $this->mRevisionId
= $oldRevisionId;
430 $this->mRevisionObject
= $oldRevisionObject;
431 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
432 $this->mRevisionUser
= $oldRevisionUser;
433 wfProfileOut( $fname );
434 wfProfileOut( __METHOD__
);
436 return $this->mOutput
;
440 * Recursive parser entry point that can be called from an extension tag
443 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
445 * @param $text String: text extension wants to have parsed
446 * @param $frame PPFrame: The frame to use for expanding any template variables
448 function recursiveTagParse( $text, $frame=false ) {
449 wfProfileIn( __METHOD__
);
450 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
451 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
452 $text = $this->internalParse( $text, false, $frame );
453 wfProfileOut( __METHOD__
);
458 * Expand templates and variables in the text, producing valid, static wikitext.
459 * Also removes comments.
461 function preprocess( $text, $title, $options, $revid = null ) {
462 wfProfileIn( __METHOD__
);
463 $this->mOptions
= $options;
465 $this->setOutputType( self
::OT_PREPROCESS
);
466 $this->setTitle( $title );
467 if ( $revid !== null ) {
468 $this->mRevisionId
= $revid;
470 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
471 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
472 $text = $this->replaceVariables( $text );
473 $text = $this->mStripState
->unstripBoth( $text );
474 wfProfileOut( __METHOD__
);
479 * Process the wikitext for the ?preload= feature. (bug 5210)
481 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
482 * comments, templates, arguments, tags hooks and parser functions are untouched.
484 public function getPreloadText( $text, $title, $options ) {
485 # Parser (re)initialisation
486 $this->mOptions
= $options;
488 $this->setOutputType( self
::OT_PLAIN
);
489 $this->setTitle( $title );
491 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
492 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
493 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
497 * Get a random string
502 static private function getRandomString() {
503 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
507 * Set the current user.
508 * Should only be used when doing pre-save transform.
510 * @param $user Mixed: User object or null (to reset)
512 function setUser( $user ) {
513 $this->mUser
= $user;
517 * Accessor for mUniqPrefix.
521 public function uniqPrefix() {
522 if ( !isset( $this->mUniqPrefix
) ) {
523 # @todo Fixme: this is probably *horribly wrong*
524 # LanguageConverter seems to want $wgParser's uniqPrefix, however
525 # if this is called for a parser cache hit, the parser may not
526 # have ever been initialized in the first place.
527 # Not really sure what the heck is supposed to be going on here.
529 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
531 return $this->mUniqPrefix
;
535 * Set the context title
537 function setTitle( $t ) {
538 if ( !$t ||
$t instanceof FakeTitle
) {
539 $t = Title
::newFromText( 'NO TITLE' );
542 if ( strval( $t->getFragment() ) !== '' ) {
543 # Strip the fragment to avoid various odd effects
544 $this->mTitle
= clone $t;
545 $this->mTitle
->setFragment( '' );
552 * Accessor for the Title object
554 * @return Title object
556 function getTitle() {
557 return $this->mTitle
;
561 * Accessor/mutator for the Title object
563 * @param $x New Title object or null to just get the current one
564 * @return Title object
566 function Title( $x = null ) {
567 return wfSetVar( $this->mTitle
, $x );
571 * Set the output type
573 * @param $ot Integer: new value
575 function setOutputType( $ot ) {
576 $this->mOutputType
= $ot;
579 'html' => $ot == self
::OT_HTML
,
580 'wiki' => $ot == self
::OT_WIKI
,
581 'pre' => $ot == self
::OT_PREPROCESS
,
582 'plain' => $ot == self
::OT_PLAIN
,
587 * Accessor/mutator for the output type
589 * @param $x New value or null to just get the current one
592 function OutputType( $x = null ) {
593 return wfSetVar( $this->mOutputType
, $x );
597 * Get the ParserOutput object
599 * @return ParserOutput object
601 function getOutput() {
602 return $this->mOutput
;
606 * Get the ParserOptions object
608 * @return ParserOptions object
610 function getOptions() {
611 return $this->mOptions
;
615 * Accessor/mutator for the ParserOptions object
617 * @param $x New value or null to just get the current one
618 * @return Current ParserOptions object
620 function Options( $x = null ) {
621 return wfSetVar( $this->mOptions
, $x );
624 function nextLinkID() {
625 return $this->mLinkID++
;
628 function getFunctionLang() {
629 global $wgLang, $wgContLang;
631 $target = $this->mOptions
->getTargetLanguage();
632 if ( $target !== null ) {
635 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
640 * Get a User object either from $this->mUser, if set, or from the
641 * ParserOptions object otherwise
643 * @return User object
646 if ( !is_null( $this->mUser
) ) {
649 return $this->mOptions
->getUser();
653 * Get a preprocessor object
655 * @return Preprocessor instance
657 function getPreprocessor() {
658 if ( !isset( $this->mPreprocessor
) ) {
659 $class = $this->mPreprocessorClass
;
660 $this->mPreprocessor
= new $class( $this );
662 return $this->mPreprocessor
;
666 * Replaces all occurrences of HTML-style comments and the given tags
667 * in the text with a random marker and returns the next text. The output
668 * parameter $matches will be an associative array filled with data in
670 * 'UNIQ-xxxxx' => array(
673 * array( 'param' => 'x' ),
674 * '<element param="x">tag content</element>' ) )
676 * @param $elements list of element names. Comments are always extracted.
677 * @param $text Source text string.
678 * @param $matches Out parameter, Array: extracted tags
679 * @param $uniq_prefix
680 * @return String: stripped text
684 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
689 $taglist = implode( '|', $elements );
690 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
692 while ( $text != '' ) {
693 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
695 if ( count( $p ) < 5 ) {
698 if ( count( $p ) > 5 ) {
712 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
713 $stripped .= $marker;
715 if ( $close === '/>' ) {
716 # Empty element tag, <tag />
721 if ( $element === '!--' ) {
724 $end = "/(<\\/$element\\s*>)/i";
726 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
728 if ( count( $q ) < 3 ) {
729 # No end tag -- let it run out to the end of the text.
738 $matches[$marker] = array( $element,
740 Sanitizer
::decodeTagAttributes( $attributes ),
741 "<$element$attributes$close$content$tail" );
747 * Get a list of strippable XML-like elements
749 function getStripList() {
750 return $this->mStripList
;
754 * @deprecated use replaceVariables
756 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
761 * Restores pre, math, and other extensions removed by strip()
763 * always call unstripNoWiki() after this one
765 * @deprecated use $this->mStripState->unstrip()
767 function unstrip( $text, $state ) {
768 return $state->unstripGeneral( $text );
772 * Always call this after unstrip() to preserve the order
775 * @deprecated use $this->mStripState->unstrip()
777 function unstripNoWiki( $text, $state ) {
778 return $state->unstripNoWiki( $text );
782 * @deprecated use $this->mStripState->unstripBoth()
784 function unstripForHTML( $text ) {
785 return $this->mStripState
->unstripBoth( $text );
789 * Add an item to the strip state
790 * Returns the unique tag which must be inserted into the stripped text
791 * The tag will be replaced with the original text in unstrip()
795 function insertStripItem( $text ) {
796 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
797 $this->mMarkerIndex++
;
798 $this->mStripState
->general
->setPair( $rnd, $text );
803 * Interface with html tidy
804 * @deprecated Use MWTidy::tidy()
806 public static function tidy( $text ) {
807 wfDeprecated( __METHOD__
);
808 return MWTidy
::tidy( $text );
812 * parse the wiki syntax used to render tables
816 function doTableStuff( $text ) {
817 wfProfileIn( __METHOD__
);
819 $lines = StringUtils
::explode( "\n", $text );
821 $td_history = array(); # Is currently a td tag open?
822 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
823 $tr_history = array(); # Is currently a tr tag open?
824 $tr_attributes = array(); # history of tr attributes
825 $has_opened_tr = array(); # Did this table open a <tr> element?
826 $indent_level = 0; # indent level of the table
828 # Keep pulling lines off the front of the array until they're all gone.
829 # we want to be able to push lines back on to the front of the stream,
830 # but StringUtils::explode() returns funky optimised Iterators which don't
831 # support insertion. So maintain a separate buffer and draw on that first if
832 # there's anything in it
833 $extraLines = array();
837 $outLine = array_shift( $extraLines );
838 } elseif( $lines->valid() ) {
839 $outLine = $lines->current();
844 $line = trim( $outLine );
846 if ( $line === '' ) { # empty line, go to next line
847 $out .= $outLine."\n";
851 $first_character = $line[0];
854 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
855 # First check if we are starting a new table
856 $indent_level = strlen( $matches[1] );
858 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
859 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
861 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
862 array_push( $td_history , false );
863 array_push( $last_tag_history , '' );
864 array_push( $tr_history , false );
865 array_push( $tr_attributes , '' );
866 array_push( $has_opened_tr , false );
867 } elseif ( count( $td_history ) == 0 ) {
868 # Don't do any of the following
869 $out .= $outLine."\n";
871 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
872 # We are ending a table
873 $line = '</table>' . substr( $line , 2 );
874 $last_tag = array_pop( $last_tag_history );
876 if ( !array_pop( $has_opened_tr ) ) {
877 $line = "<tr><td></td></tr>{$line}";
880 if ( array_pop( $tr_history ) ) {
881 $line = "</tr>{$line}";
884 if ( array_pop( $td_history ) ) {
885 $line = "</{$last_tag}>{$line}";
887 array_pop( $tr_attributes );
888 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
889 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
890 # Now we have a table row
891 $line = preg_replace( '#^\|-+#', '', $line );
893 # Whats after the tag is now only attributes
894 $attributes = $this->mStripState
->unstripBoth( $line );
895 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
896 array_pop( $tr_attributes );
897 array_push( $tr_attributes, $attributes );
900 $last_tag = array_pop( $last_tag_history );
901 array_pop( $has_opened_tr );
902 array_push( $has_opened_tr , true );
904 if ( array_pop( $tr_history ) ) {
908 if ( array_pop( $td_history ) ) {
909 $line = "</{$last_tag}>{$line}";
913 array_push( $tr_history , false );
914 array_push( $td_history , false );
915 array_push( $last_tag_history , '' );
916 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
917 # This might be cell elements, td, th or captions
918 if ( substr( $line , 0 , 2 ) === '|+' ) {
919 $first_character = '|+';
922 $line = substr( $line , strlen( $first_character ) );
924 if ( $first_character === '!' ) {
925 $line = str_replace( '!!' , '||' , $line );
928 # Split up multiple cells on the same line.
929 # FIXME : This can result in improper nesting of tags processed
930 # by earlier parser steps, but should avoid splitting up eg
931 # attribute values containing literal "||".
932 $cells = StringUtils
::explodeMarkup( '||' , $line );
933 $cell = array_shift( $cells );
935 # Inject cells back into the stream to be dealt with later
936 # TODO: really we should do the whole thing as a stream...
937 # but that would be too much like a sensible implementation :P
938 if( count( $cells ) ){
939 foreach( array_reverse( $cells ) as $extraCell ){
940 array_unshift( $extraLines, $first_character . $extraCell );
947 if ( $first_character !== '|+' ) {
948 $tr_after = array_pop( $tr_attributes );
949 if ( !array_pop( $tr_history ) ) {
950 $previous = "<tr{$tr_after}>\n";
952 array_push( $tr_history , true );
953 array_push( $tr_attributes , '' );
954 array_pop( $has_opened_tr );
955 array_push( $has_opened_tr , true );
958 $last_tag = array_pop( $last_tag_history );
960 if ( array_pop( $td_history ) ) {
961 $previous = "</{$last_tag}>\n{$previous}";
964 if ( $first_character === '|' ) {
966 } elseif ( $first_character === '!' ) {
968 } elseif ( $first_character === '|+' ) {
969 $last_tag = 'caption';
974 array_push( $last_tag_history , $last_tag );
976 # A cell could contain both parameters and data... but the pipe could
977 # also be the start of a nested table, or a raw pipe inside an invalid
979 $cell_data = preg_split( '/(?<!\{)\|/', $cell, 2 );
981 # Bug 553: a '|' inside an invalid link should not
982 # be mistaken as delimiting cell parameters
983 if ( strpos( $cell_data[0], '[[' ) !== false ) {
985 $cell = "{$previous}<{$last_tag}>";
986 } elseif ( count( $cell_data ) == 1 ) {
987 $cell = "{$previous}<{$last_tag}>";
988 $data = $cell_data[0];
990 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
991 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
992 $cell = "{$previous}<{$last_tag}{$attributes}>";
993 $data = $cell_data[1];
996 # Bug 529: the start of a table cell should be a linestart context for
997 # processing other block markup, including nested tables. The original
998 # implementation of this was to add a newline before every brace construct,
999 # which broke all manner of other things. Instead, push the contents
1000 # of the cell back into the stream and come back to it later. But don't
1001 # do that if the first line is empty, or you may get extra whitespace
1003 array_unshift( $extraLines, trim( $data ) );
1007 array_push( $td_history , true );
1009 $out .= $outLine . "\n";
1010 } while( $lines->valid() ||
count( $extraLines ) );
1012 # Closing open td, tr && table
1013 while ( count( $td_history ) > 0 ) {
1014 if ( array_pop( $td_history ) ) {
1017 if ( array_pop( $tr_history ) ) {
1020 if ( !array_pop( $has_opened_tr ) ) {
1021 $out .= "<tr><td></td></tr>\n" ;
1024 $out .= "</table>\n";
1027 # Remove trailing line-ending (b/c)
1028 if ( substr( $out, -1 ) === "\n" ) {
1029 $out = substr( $out, 0, -1 );
1032 # special case: don't return empty table
1033 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1037 wfProfileOut( __METHOD__
);
1043 * Helper function for parse() that transforms wiki markup into
1044 * HTML. Only called for $mOutputType == self::OT_HTML.
1048 function internalParse( $text, $isMain = true, $frame=false ) {
1049 wfProfileIn( __METHOD__
);
1053 # Hook to suspend the parser in this state
1054 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1055 wfProfileOut( __METHOD__
);
1059 # if $frame is provided, then use $frame for replacing any variables
1061 # use frame depth to infer how include/noinclude tags should be handled
1062 # depth=0 means this is the top-level document; otherwise it's an included document
1063 if ( !$frame->depth
) {
1066 $flag = Parser
::PTD_FOR_INCLUSION
;
1068 $dom = $this->preprocessToDom( $text, $flag );
1069 $text = $frame->expand( $dom );
1071 # if $frame is not provided, then use old-style replaceVariables
1072 $text = $this->replaceVariables( $text );
1075 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1076 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1078 # Tables need to come after variable replacement for things to work
1079 # properly; putting them before other transformations should keep
1080 # exciting things like link expansions from showing up in surprising
1082 $text = $this->doTableStuff( $text );
1084 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1086 $text = $this->doDoubleUnderscore( $text );
1088 $text = $this->doHeadings( $text );
1089 if ( $this->mOptions
->getUseDynamicDates() ) {
1090 $df = DateFormatter
::getInstance();
1091 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1093 $text = $this->replaceInternalLinks( $text );
1094 $text = $this->doAllQuotes( $text );
1095 $text = $this->replaceExternalLinks( $text );
1097 # replaceInternalLinks may sometimes leave behind
1098 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1099 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1101 $text = $this->doMagicLinks( $text );
1102 $text = $this->formatHeadings( $text, $origText, $isMain );
1104 wfProfileOut( __METHOD__
);
1109 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1110 * magic external links.
1115 function doMagicLinks( $text ) {
1116 wfProfileIn( __METHOD__
);
1117 $prots = $this->mUrlProtocols
;
1118 $urlChar = self
::EXT_LINK_URL_CLASS
;
1119 $text = preg_replace_callback(
1121 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1122 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1123 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1124 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1125 ISBN\s+(\b # m[5]: ISBN, capture number
1126 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1127 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1128 [0-9Xx] # check digit
1130 )!x', array( &$this, 'magicLinkCallback' ), $text );
1131 wfProfileOut( __METHOD__
);
1135 function magicLinkCallback( $m ) {
1136 if ( isset( $m[1] ) && $m[1] !== '' ) {
1139 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1142 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1143 # Free external link
1144 return $this->makeFreeExternalLink( $m[0] );
1145 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1147 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1150 $CssClass = 'mw-magiclink-rfc';
1152 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1154 $urlmsg = 'pubmedurl';
1155 $CssClass = 'mw-magiclink-pmid';
1158 throw new MWException( __METHOD__
.': unrecognised match type "' .
1159 substr( $m[0], 0, 20 ) . '"' );
1161 $url = wfMsgForContent( $urlmsg, $id);
1162 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1163 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1164 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1165 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1168 $num = strtr( $isbn, array(
1173 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1175 $titleObj->escapeLocalUrl() .
1176 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1183 * Make a free external link, given a user-supplied URL
1187 function makeFreeExternalLink( $url ) {
1189 wfProfileIn( __METHOD__
);
1191 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1194 # The characters '<' and '>' (which were escaped by
1195 # removeHTMLtags()) should not be included in
1196 # URLs, per RFC 2396.
1198 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1199 $trail = substr( $url, $m2[0][1] ) . $trail;
1200 $url = substr( $url, 0, $m2[0][1] );
1203 # Move trailing punctuation to $trail
1205 # If there is no left bracket, then consider right brackets fair game too
1206 if ( strpos( $url, '(' ) === false ) {
1210 $numSepChars = strspn( strrev( $url ), $sep );
1211 if ( $numSepChars ) {
1212 $trail = substr( $url, -$numSepChars ) . $trail;
1213 $url = substr( $url, 0, -$numSepChars );
1216 $url = Sanitizer
::cleanUrl( $url );
1218 # Is this an external image?
1219 $text = $this->maybeMakeExternalImage( $url );
1220 if ( $text === false ) {
1221 # Not an image, make a link
1222 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1223 $this->getExternalLinkAttribs( $url ) );
1224 # Register it in the output object...
1225 # Replace unnecessary URL escape codes with their equivalent characters
1226 $pasteurized = self
::replaceUnusualEscapes( $url );
1227 $this->mOutput
->addExternalLink( $pasteurized );
1229 wfProfileOut( __METHOD__
);
1230 return $text . $trail;
1235 * Parse headers and return html
1239 function doHeadings( $text ) {
1240 wfProfileIn( __METHOD__
);
1241 for ( $i = 6; $i >= 1; --$i ) {
1242 $h = str_repeat( '=', $i );
1243 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1244 "<h$i>\\1</h$i>", $text );
1246 wfProfileOut( __METHOD__
);
1251 * Replace single quotes with HTML markup
1253 * @return string the altered text
1255 function doAllQuotes( $text ) {
1256 wfProfileIn( __METHOD__
);
1258 $lines = StringUtils
::explode( "\n", $text );
1259 foreach ( $lines as $line ) {
1260 $outtext .= $this->doQuotes( $line ) . "\n";
1262 $outtext = substr( $outtext, 0,-1 );
1263 wfProfileOut( __METHOD__
);
1268 * Helper function for doAllQuotes()
1270 public function doQuotes( $text ) {
1271 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1272 if ( count( $arr ) == 1 ) {
1275 # First, do some preliminary work. This may shift some apostrophes from
1276 # being mark-up to being text. It also counts the number of occurrences
1277 # of bold and italics mark-ups.
1280 for ( $i = 0; $i < count( $arr ); $i++
) {
1281 if ( ( $i %
2 ) == 1 ) {
1282 # If there are ever four apostrophes, assume the first is supposed to
1283 # be text, and the remaining three constitute mark-up for bold text.
1284 if ( strlen( $arr[$i] ) == 4 ) {
1287 } elseif ( strlen( $arr[$i] ) > 5 ) {
1288 # If there are more than 5 apostrophes in a row, assume they're all
1289 # text except for the last 5.
1290 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1293 # Count the number of occurrences of bold and italics mark-ups.
1294 # We are not counting sequences of five apostrophes.
1295 if ( strlen( $arr[$i] ) == 2 ) {
1297 } elseif ( strlen( $arr[$i] ) == 3 ) {
1299 } elseif ( strlen( $arr[$i] ) == 5 ) {
1306 # If there is an odd number of both bold and italics, it is likely
1307 # that one of the bold ones was meant to be an apostrophe followed
1308 # by italics. Which one we cannot know for certain, but it is more
1309 # likely to be one that has a single-letter word before it.
1310 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1312 $firstsingleletterword = -1;
1313 $firstmultiletterword = -1;
1315 foreach ( $arr as $r ) {
1316 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1317 $x1 = substr( $arr[$i-1], -1 );
1318 $x2 = substr( $arr[$i-1], -2, 1 );
1319 if ( $x1 === ' ' ) {
1320 if ( $firstspace == -1 ) {
1323 } elseif ( $x2 === ' ') {
1324 if ( $firstsingleletterword == -1 ) {
1325 $firstsingleletterword = $i;
1328 if ( $firstmultiletterword == -1 ) {
1329 $firstmultiletterword = $i;
1336 # If there is a single-letter word, use it!
1337 if ( $firstsingleletterword > -1 ) {
1338 $arr[$firstsingleletterword] = "''";
1339 $arr[$firstsingleletterword-1] .= "'";
1340 } elseif ( $firstmultiletterword > -1 ) {
1341 # If not, but there's a multi-letter word, use that one.
1342 $arr[$firstmultiletterword] = "''";
1343 $arr[$firstmultiletterword-1] .= "'";
1344 } elseif ( $firstspace > -1 ) {
1345 # ... otherwise use the first one that has neither.
1346 # (notice that it is possible for all three to be -1 if, for example,
1347 # there is only one pentuple-apostrophe in the line)
1348 $arr[$firstspace] = "''";
1349 $arr[$firstspace-1] .= "'";
1353 # Now let's actually convert our apostrophic mush to HTML!
1358 foreach ( $arr as $r ) {
1359 if ( ( $i %
2 ) == 0 ) {
1360 if ( $state === 'both' ) {
1366 if ( strlen( $r ) == 2 ) {
1367 if ( $state === 'i' ) {
1368 $output .= '</i>'; $state = '';
1369 } elseif ( $state === 'bi' ) {
1370 $output .= '</i>'; $state = 'b';
1371 } elseif ( $state === 'ib' ) {
1372 $output .= '</b></i><b>'; $state = 'b';
1373 } elseif ( $state === 'both' ) {
1374 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1375 } else { # $state can be 'b' or ''
1376 $output .= '<i>'; $state .= 'i';
1378 } elseif ( strlen( $r ) == 3 ) {
1379 if ( $state === 'b' ) {
1380 $output .= '</b>'; $state = '';
1381 } elseif ( $state === 'bi' ) {
1382 $output .= '</i></b><i>'; $state = 'i';
1383 } elseif ( $state === 'ib' ) {
1384 $output .= '</b>'; $state = 'i';
1385 } elseif ( $state === 'both' ) {
1386 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1387 } else { # $state can be 'i' or ''
1388 $output .= '<b>'; $state .= 'b';
1390 } elseif ( strlen( $r ) == 5 ) {
1391 if ( $state === 'b' ) {
1392 $output .= '</b><i>'; $state = 'i';
1393 } elseif ( $state === 'i' ) {
1394 $output .= '</i><b>'; $state = 'b';
1395 } elseif ( $state === 'bi' ) {
1396 $output .= '</i></b>'; $state = '';
1397 } elseif ( $state === 'ib' ) {
1398 $output .= '</b></i>'; $state = '';
1399 } elseif ( $state === 'both' ) {
1400 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1401 } else { # ($state == '')
1402 $buffer = ''; $state = 'both';
1408 # Now close all remaining tags. Notice that the order is important.
1409 if ( $state === 'b' ||
$state === 'ib' ) {
1412 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1415 if ( $state === 'bi' ) {
1418 # There might be lonely ''''', so make sure we have a buffer
1419 if ( $state === 'both' && $buffer ) {
1420 $output .= '<b><i>'.$buffer.'</i></b>';
1427 * Replace external links (REL)
1429 * Note: this is all very hackish and the order of execution matters a lot.
1430 * Make sure to run maintenance/parserTests.php if you change this code.
1434 function replaceExternalLinks( $text ) {
1436 wfProfileIn( __METHOD__
);
1438 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1440 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1441 $s = array_shift( $bits );
1444 while ( $i<count( $bits ) ) {
1446 $protocol = $bits[$i++
];
1447 $text = $bits[$i++
];
1448 $trail = $bits[$i++
];
1450 # The characters '<' and '>' (which were escaped by
1451 # removeHTMLtags()) should not be included in
1452 # URLs, per RFC 2396.
1454 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1455 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1456 $url = substr( $url, 0, $m2[0][1] );
1459 # If the link text is an image URL, replace it with an <img> tag
1460 # This happened by accident in the original parser, but some people used it extensively
1461 $img = $this->maybeMakeExternalImage( $text );
1462 if ( $img !== false ) {
1468 # Set linktype for CSS - if URL==text, link is essentially free
1469 $linktype = ( $text === $url ) ?
'free' : 'text';
1471 # No link text, e.g. [http://domain.tld/some.link]
1472 if ( $text == '' ) {
1473 # Autonumber if allowed. See bug #5918
1474 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1475 $langObj = $this->getFunctionLang();
1476 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1477 $linktype = 'autonumber';
1479 # Otherwise just use the URL
1480 $text = htmlspecialchars( $url );
1484 # Have link text, e.g. [http://domain.tld/some.link text]s
1486 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1489 $text = $wgContLang->markNoConversion( $text );
1491 $url = Sanitizer
::cleanUrl( $url );
1493 # Use the encoded URL
1494 # This means that users can paste URLs directly into the text
1495 # Funny characters like ö aren't valid in URLs anyway
1496 # This was changed in August 2004
1497 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1498 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1500 # Register link in the output object.
1501 # Replace unnecessary URL escape codes with the referenced character
1502 # This prevents spammers from hiding links from the filters
1503 $pasteurized = self
::replaceUnusualEscapes( $url );
1504 $this->mOutput
->addExternalLink( $pasteurized );
1507 wfProfileOut( __METHOD__
);
1512 * Get an associative array of additional HTML attributes appropriate for a
1513 * particular external link. This currently may include rel => nofollow
1514 * (depending on configuration, namespace, and the URL's domain) and/or a
1515 * target attribute (depending on configuration).
1517 * @param $url String: optional URL, to extract the domain from for rel =>
1518 * nofollow if appropriate
1519 * @return Array: associative array of HTML attributes
1521 function getExternalLinkAttribs( $url = false ) {
1523 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1524 $ns = $this->mTitle
->getNamespace();
1525 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1526 $attribs['rel'] = 'nofollow';
1528 global $wgNoFollowDomainExceptions;
1529 if ( $wgNoFollowDomainExceptions ) {
1530 $bits = wfParseUrl( $url );
1531 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1532 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1533 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1534 unset( $attribs['rel'] );
1541 if ( $this->mOptions
->getExternalLinkTarget() ) {
1542 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1549 * Replace unusual URL escape codes with their equivalent characters
1551 * @param $url String
1554 * @todo This can merge genuinely required bits in the path or query string,
1555 * breaking legit URLs. A proper fix would treat the various parts of
1556 * the URL differently; as a workaround, just use the output for
1557 * statistical records, not for actual linking/output.
1559 static function replaceUnusualEscapes( $url ) {
1560 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1561 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1565 * Callback function used in replaceUnusualEscapes().
1566 * Replaces unusual URL escape codes with their equivalent character
1568 private static function replaceUnusualEscapesCallback( $matches ) {
1569 $char = urldecode( $matches[0] );
1570 $ord = ord( $char );
1571 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1572 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1573 # No, shouldn't be escaped
1576 # Yes, leave it escaped
1582 * make an image if it's allowed, either through the global
1583 * option, through the exception, or through the on-wiki whitelist
1586 function maybeMakeExternalImage( $url ) {
1587 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1588 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1589 $imagesexception = !empty( $imagesfrom );
1591 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1592 if ( $imagesexception && is_array( $imagesfrom ) ) {
1593 $imagematch = false;
1594 foreach ( $imagesfrom as $match ) {
1595 if ( strpos( $url, $match ) === 0 ) {
1600 } elseif ( $imagesexception ) {
1601 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1603 $imagematch = false;
1605 if ( $this->mOptions
->getAllowExternalImages()
1606 ||
( $imagesexception && $imagematch ) ) {
1607 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1609 $text = $sk->makeExternalImage( $url );
1612 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1613 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1614 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1615 foreach ( $whitelist as $entry ) {
1616 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1617 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1620 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1621 # Image matches a whitelist entry
1622 $text = $sk->makeExternalImage( $url );
1631 * Process [[ ]] wikilinks
1632 * @return String: processed text
1636 function replaceInternalLinks( $s ) {
1637 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1642 * Process [[ ]] wikilinks (RIL)
1643 * @return LinkHolderArray
1647 function replaceInternalLinks2( &$s ) {
1650 wfProfileIn( __METHOD__
);
1652 wfProfileIn( __METHOD__
.'-setup' );
1653 static $tc = FALSE, $e1, $e1_img;
1654 # the % is needed to support urlencoded titles as well
1656 $tc = Title
::legalChars() . '#%';
1657 # Match a link having the form [[namespace:link|alternate]]trail
1658 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1659 # Match cases where there is no "]]", which might still be images
1660 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1663 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1664 $holders = new LinkHolderArray( $this );
1666 # split the entire text string on occurences of [[
1667 $a = StringUtils
::explode( '[[', ' ' . $s );
1668 # get the first element (all text up to first [[), and remove the space we added
1671 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1672 $s = substr( $s, 1 );
1674 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1676 if ( $useLinkPrefixExtension ) {
1677 # Match the end of a line for a word that's not followed by whitespace,
1678 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1679 $e2 = wfMsgForContent( 'linkprefix' );
1682 if ( is_null( $this->mTitle
) ) {
1683 wfProfileOut( __METHOD__
.'-setup' );
1684 wfProfileOut( __METHOD__
);
1685 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1687 $nottalk = !$this->mTitle
->isTalkPage();
1689 if ( $useLinkPrefixExtension ) {
1691 if ( preg_match( $e2, $s, $m ) ) {
1692 $first_prefix = $m[2];
1694 $first_prefix = false;
1700 if ( $wgContLang->hasVariants() ) {
1701 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1703 $selflink = array( $this->mTitle
->getPrefixedText() );
1705 $useSubpages = $this->areSubpagesAllowed();
1706 wfProfileOut( __METHOD__
.'-setup' );
1708 # Loop for each link
1709 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1710 # Check for excessive memory usage
1711 if ( $holders->isBig() ) {
1713 # Do the existence check, replace the link holders and clear the array
1714 $holders->replace( $s );
1718 if ( $useLinkPrefixExtension ) {
1719 wfProfileIn( __METHOD__
.'-prefixhandling' );
1720 if ( preg_match( $e2, $s, $m ) ) {
1727 if ( $first_prefix ) {
1728 $prefix = $first_prefix;
1729 $first_prefix = false;
1731 wfProfileOut( __METHOD__
.'-prefixhandling' );
1734 $might_be_img = false;
1736 wfProfileIn( __METHOD__
."-e1" );
1737 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1739 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1740 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1741 # the real problem is with the $e1 regex
1744 # Still some problems for cases where the ] is meant to be outside punctuation,
1745 # and no image is in sight. See bug 2095.
1747 if ( $text !== '' &&
1748 substr( $m[3], 0, 1 ) === ']' &&
1749 strpos( $text, '[' ) !== false
1752 $text .= ']'; # so that replaceExternalLinks($text) works later
1753 $m[3] = substr( $m[3], 1 );
1755 # fix up urlencoded title texts
1756 if ( strpos( $m[1], '%' ) !== false ) {
1757 # Should anchors '#' also be rejected?
1758 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1761 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1762 $might_be_img = true;
1764 if ( strpos( $m[1], '%' ) !== false ) {
1765 $m[1] = rawurldecode( $m[1] );
1768 } else { # Invalid form; output directly
1769 $s .= $prefix . '[[' . $line ;
1770 wfProfileOut( __METHOD__
."-e1" );
1773 wfProfileOut( __METHOD__
."-e1" );
1774 wfProfileIn( __METHOD__
."-misc" );
1776 # Don't allow internal links to pages containing
1777 # PROTO: where PROTO is a valid URL protocol; these
1778 # should be external links.
1779 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1780 $s .= $prefix . '[[' . $line ;
1781 wfProfileOut( __METHOD__
."-misc" );
1785 # Make subpage if necessary
1786 if ( $useSubpages ) {
1787 $link = $this->maybeDoSubpageLink( $m[1], $text );
1792 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1794 # Strip off leading ':'
1795 $link = substr( $link, 1 );
1798 wfProfileOut( __METHOD__
."-misc" );
1799 wfProfileIn( __METHOD__
."-title" );
1800 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1801 if ( $nt === null ) {
1802 $s .= $prefix . '[[' . $line;
1803 wfProfileOut( __METHOD__
."-title" );
1807 $ns = $nt->getNamespace();
1808 $iw = $nt->getInterWiki();
1809 wfProfileOut( __METHOD__
."-title" );
1811 if ( $might_be_img ) { # if this is actually an invalid link
1812 wfProfileIn( __METHOD__
."-might_be_img" );
1813 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1816 # look at the next 'line' to see if we can close it there
1818 $next_line = $a->current();
1819 if ( $next_line === false ||
$next_line === null ) {
1822 $m = explode( ']]', $next_line, 3 );
1823 if ( count( $m ) == 3 ) {
1824 # the first ]] closes the inner link, the second the image
1826 $text .= "[[{$m[0]}]]{$m[1]}";
1829 } elseif ( count( $m ) == 2 ) {
1830 # if there's exactly one ]] that's fine, we'll keep looking
1831 $text .= "[[{$m[0]}]]{$m[1]}";
1833 # if $next_line is invalid too, we need look no further
1834 $text .= '[[' . $next_line;
1839 # we couldn't find the end of this imageLink, so output it raw
1840 # but don't ignore what might be perfectly normal links in the text we've examined
1841 $holders->merge( $this->replaceInternalLinks2( $text ) );
1842 $s .= "{$prefix}[[$link|$text";
1843 # note: no $trail, because without an end, there *is* no trail
1844 wfProfileOut( __METHOD__
."-might_be_img" );
1847 } else { # it's not an image, so output it raw
1848 $s .= "{$prefix}[[$link|$text";
1849 # note: no $trail, because without an end, there *is* no trail
1850 wfProfileOut( __METHOD__
."-might_be_img" );
1853 wfProfileOut( __METHOD__
."-might_be_img" );
1856 $wasblank = ( $text == '' );
1860 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1861 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1862 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1863 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1864 $text = $this->doQuotes( $text );
1867 # Link not escaped by : , create the various objects
1871 wfProfileIn( __METHOD__
."-interwiki" );
1872 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1873 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1874 $s = rtrim( $s . $prefix );
1875 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1876 wfProfileOut( __METHOD__
."-interwiki" );
1879 wfProfileOut( __METHOD__
."-interwiki" );
1881 if ( $ns == NS_FILE
) {
1882 wfProfileIn( __METHOD__
."-image" );
1883 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1885 # if no parameters were passed, $text
1886 # becomes something like "File:Foo.png",
1887 # which we don't want to pass on to the
1891 # recursively parse links inside the image caption
1892 # actually, this will parse them in any other parameters, too,
1893 # but it might be hard to fix that, and it doesn't matter ATM
1894 $text = $this->replaceExternalLinks( $text );
1895 $holders->merge( $this->replaceInternalLinks2( $text ) );
1897 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1898 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1900 $s .= $prefix . $trail;
1902 $this->mOutput
->addImage( $nt->getDBkey() );
1903 wfProfileOut( __METHOD__
."-image" );
1908 if ( $ns == NS_CATEGORY
) {
1909 wfProfileIn( __METHOD__
."-category" );
1910 $s = rtrim( $s . "\n" ); # bug 87
1913 $sortkey = $this->getDefaultSort();
1917 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1918 $sortkey = str_replace( "\n", '', $sortkey );
1919 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1920 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1923 * Strip the whitespace Category links produce, see bug 87
1924 * @todo We might want to use trim($tmp, "\n") here.
1926 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1928 wfProfileOut( __METHOD__
."-category" );
1933 # Self-link checking
1934 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1935 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1936 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1941 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1942 # FIXME: Should do batch file existence checks, see comment below
1943 if ( $ns == NS_MEDIA
) {
1944 wfProfileIn( __METHOD__
."-media" );
1945 # Give extensions a chance to select the file revision for us
1946 $skip = $time = false;
1947 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1949 $link = $sk->link( $nt );
1951 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1953 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1954 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1955 $this->mOutput
->addImage( $nt->getDBkey() );
1956 wfProfileOut( __METHOD__
."-media" );
1960 wfProfileIn( __METHOD__
."-always_known" );
1961 # Some titles, such as valid special pages or files in foreign repos, should
1962 # be shown as bluelinks even though they're not included in the page table
1964 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1965 # batch file existence checks for NS_FILE and NS_MEDIA
1966 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1967 $this->mOutput
->addLink( $nt );
1968 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1970 # Links will be added to the output link list after checking
1971 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1973 wfProfileOut( __METHOD__
."-always_known" );
1975 wfProfileOut( __METHOD__
);
1980 * Make a link placeholder. The text returned can be later resolved to a real link with
1981 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1982 * parsing of interwiki links, and secondly to allow all existence checks and
1983 * article length checks (for stub links) to be bundled into a single query.
1987 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1988 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1992 * Render a forced-blue link inline; protect against double expansion of
1993 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1994 * Since this little disaster has to split off the trail text to avoid
1995 * breaking URLs in the following text without breaking trails on the
1996 * wiki links, it's been made into a horrible function.
1999 * @param $text String
2000 * @param $query String
2001 * @param $trail String
2002 * @param $prefix String
2003 * @return String: HTML-wikitext mix oh yuck
2005 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2006 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2007 $sk = $this->mOptions
->getSkin( $this->mTitle
);
2008 # FIXME: use link() instead of deprecated makeKnownLinkObj()
2009 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
2010 return $this->armorLinks( $link ) . $trail;
2014 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2015 * going to go through further parsing steps before inline URL expansion.
2017 * Not needed quite as much as it used to be since free links are a bit
2018 * more sensible these days. But bracketed links are still an issue.
2020 * @param $text String: more-or-less HTML
2021 * @return String: less-or-more HTML with NOPARSE bits
2023 function armorLinks( $text ) {
2024 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2025 "{$this->mUniqPrefix}NOPARSE$1", $text );
2029 * Return true if subpage links should be expanded on this page.
2032 function areSubpagesAllowed() {
2033 # Some namespaces don't allow subpages
2034 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2038 * Handle link to subpage if necessary
2040 * @param $target String: the source of the link
2041 * @param &$text String: the link text, modified as necessary
2042 * @return string the full name of the link
2045 function maybeDoSubpageLink( $target, &$text ) {
2046 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2050 * Used by doBlockLevels()
2053 function closeParagraph() {
2055 if ( $this->mLastSection
!= '' ) {
2056 $result = '</' . $this->mLastSection
. ">\n";
2058 $this->mInPre
= false;
2059 $this->mLastSection
= '';
2064 * getCommon() returns the length of the longest common substring
2065 * of both arguments, starting at the beginning of both.
2068 function getCommon( $st1, $st2 ) {
2069 $fl = strlen( $st1 );
2070 $shorter = strlen( $st2 );
2071 if ( $fl < $shorter ) {
2075 for ( $i = 0; $i < $shorter; ++
$i ) {
2076 if ( $st1{$i} != $st2{$i} ) {
2084 * These next three functions open, continue, and close the list
2085 * element appropriate to the prefix character passed into them.
2088 function openList( $char ) {
2089 $result = $this->closeParagraph();
2091 if ( '*' === $char ) {
2092 $result .= '<ul><li>';
2093 } elseif ( '#' === $char ) {
2094 $result .= '<ol><li>';
2095 } elseif ( ':' === $char ) {
2096 $result .= '<dl><dd>';
2097 } elseif ( ';' === $char ) {
2098 $result .= '<dl><dt>';
2099 $this->mDTopen
= true;
2101 $result = '<!-- ERR 1 -->';
2109 * @param $char String
2112 function nextItem( $char ) {
2113 if ( '*' === $char ||
'#' === $char ) {
2115 } elseif ( ':' === $char ||
';' === $char ) {
2117 if ( $this->mDTopen
) {
2120 if ( ';' === $char ) {
2121 $this->mDTopen
= true;
2122 return $close . '<dt>';
2124 $this->mDTopen
= false;
2125 return $close . '<dd>';
2128 return '<!-- ERR 2 -->';
2133 * @param $char String
2136 function closeList( $char ) {
2137 if ( '*' === $char ) {
2138 $text = '</li></ul>';
2139 } elseif ( '#' === $char ) {
2140 $text = '</li></ol>';
2141 } elseif ( ':' === $char ) {
2142 if ( $this->mDTopen
) {
2143 $this->mDTopen
= false;
2144 $text = '</dt></dl>';
2146 $text = '</dd></dl>';
2149 return '<!-- ERR 3 -->';
2156 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2158 * @param $text String
2159 * @param $linestart Boolean: whether or not this is at the start of a line.
2161 * @return string the lists rendered as HTML
2163 function doBlockLevels( $text, $linestart ) {
2164 wfProfileIn( __METHOD__
);
2166 # Parsing through the text line by line. The main thing
2167 # happening here is handling of block-level elements p, pre,
2168 # and making lists from lines starting with * # : etc.
2170 $textLines = StringUtils
::explode( "\n", $text );
2172 $lastPrefix = $output = '';
2173 $this->mDTopen
= $inBlockElem = false;
2175 $paragraphStack = false;
2177 foreach ( $textLines as $oLine ) {
2179 if ( !$linestart ) {
2189 $lastPrefixLength = strlen( $lastPrefix );
2190 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2191 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2192 # If not in a <pre> element, scan for and figure out what prefixes are there.
2193 if ( !$this->mInPre
) {
2194 # Multiple prefixes may abut each other for nested lists.
2195 $prefixLength = strspn( $oLine, '*#:;' );
2196 $prefix = substr( $oLine, 0, $prefixLength );
2199 # ; and : are both from definition-lists, so they're equivalent
2200 # for the purposes of determining whether or not we need to open/close
2202 $prefix2 = str_replace( ';', ':', $prefix );
2203 $t = substr( $oLine, $prefixLength );
2204 $this->mInPre
= (bool)$preOpenMatch;
2206 # Don't interpret any other prefixes in preformatted text
2208 $prefix = $prefix2 = '';
2213 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2214 # Same as the last item, so no need to deal with nesting or opening stuff
2215 $output .= $this->nextItem( substr( $prefix, -1 ) );
2216 $paragraphStack = false;
2218 if ( substr( $prefix, -1 ) === ';') {
2219 # The one nasty exception: definition lists work like this:
2220 # ; title : definition text
2221 # So we check for : in the remainder text to split up the
2222 # title and definition, without b0rking links.
2224 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2226 $output .= $term . $this->nextItem( ':' );
2229 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2230 # We need to open or close prefixes, or both.
2232 # Either open or close a level...
2233 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2234 $paragraphStack = false;
2236 # Close all the prefixes which aren't shared.
2237 while ( $commonPrefixLength < $lastPrefixLength ) {
2238 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2239 --$lastPrefixLength;
2242 # Continue the current prefix if appropriate.
2243 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2244 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2247 # Open prefixes where appropriate.
2248 while ( $prefixLength > $commonPrefixLength ) {
2249 $char = substr( $prefix, $commonPrefixLength, 1 );
2250 $output .= $this->openList( $char );
2252 if ( ';' === $char ) {
2253 # FIXME: This is dupe of code above
2254 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2256 $output .= $term . $this->nextItem( ':' );
2259 ++
$commonPrefixLength;
2261 $lastPrefix = $prefix2;
2264 # If we have no prefixes, go to paragraph mode.
2265 if ( 0 == $prefixLength ) {
2266 wfProfileIn( __METHOD__
."-paragraph" );
2267 # No prefix (not in list)--go to paragraph mode
2268 # XXX: use a stack for nestable elements like span, table and div
2269 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2270 $closematch = preg_match(
2271 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2272 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2273 if ( $openmatch or $closematch ) {
2275 $paragraphStack = false;
2276 #Â TODO bug 5718: paragraph closed
2277 $output .= $this->closeParagraph();
2278 if ( $preOpenMatch and !$preCloseMatch ) {
2279 $this->mInPre
= true;
2281 $inBlockElem = !$closematch;
2282 } elseif ( !$inBlockElem && !$this->mInPre
) {
2283 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2285 if ( $this->mLastSection
!== 'pre' ) {
2286 $paragraphStack = false;
2287 $output .= $this->closeParagraph().'<pre>';
2288 $this->mLastSection
= 'pre';
2290 $t = substr( $t, 1 );
2293 if ( trim( $t ) === '' ) {
2294 if ( $paragraphStack ) {
2295 $output .= $paragraphStack.'<br />';
2296 $paragraphStack = false;
2297 $this->mLastSection
= 'p';
2299 if ( $this->mLastSection
!== 'p' ) {
2300 $output .= $this->closeParagraph();
2301 $this->mLastSection
= '';
2302 $paragraphStack = '<p>';
2304 $paragraphStack = '</p><p>';
2308 if ( $paragraphStack ) {
2309 $output .= $paragraphStack;
2310 $paragraphStack = false;
2311 $this->mLastSection
= 'p';
2312 } elseif ( $this->mLastSection
!== 'p' ) {
2313 $output .= $this->closeParagraph().'<p>';
2314 $this->mLastSection
= 'p';
2319 wfProfileOut( __METHOD__
."-paragraph" );
2321 # somewhere above we forget to get out of pre block (bug 785)
2322 if ( $preCloseMatch && $this->mInPre
) {
2323 $this->mInPre
= false;
2325 if ( $paragraphStack === false ) {
2329 while ( $prefixLength ) {
2330 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2333 if ( $this->mLastSection
!= '' ) {
2334 $output .= '</' . $this->mLastSection
. '>';
2335 $this->mLastSection
= '';
2338 wfProfileOut( __METHOD__
);
2343 * Split up a string on ':', ignoring any occurences inside tags
2344 * to prevent illegal overlapping.
2346 * @param $str String: the string to split
2347 * @param &$before String: set to everything before the ':'
2348 * @param &$after String: set to everything after the ':'
2349 * return String: the position of the ':', or false if none found
2351 function findColonNoLinks( $str, &$before, &$after ) {
2352 wfProfileIn( __METHOD__
);
2354 $pos = strpos( $str, ':' );
2355 if ( $pos === false ) {
2357 wfProfileOut( __METHOD__
);
2361 $lt = strpos( $str, '<' );
2362 if ( $lt === false ||
$lt > $pos ) {
2363 # Easy; no tag nesting to worry about
2364 $before = substr( $str, 0, $pos );
2365 $after = substr( $str, $pos+
1 );
2366 wfProfileOut( __METHOD__
);
2370 # Ugly state machine to walk through avoiding tags.
2371 $state = self
::COLON_STATE_TEXT
;
2373 $len = strlen( $str );
2374 for( $i = 0; $i < $len; $i++
) {
2378 # (Using the number is a performance hack for common cases)
2379 case 0: # self::COLON_STATE_TEXT:
2382 # Could be either a <start> tag or an </end> tag
2383 $state = self
::COLON_STATE_TAGSTART
;
2386 if ( $stack == 0 ) {
2388 $before = substr( $str, 0, $i );
2389 $after = substr( $str, $i +
1 );
2390 wfProfileOut( __METHOD__
);
2393 # Embedded in a tag; don't break it.
2396 # Skip ahead looking for something interesting
2397 $colon = strpos( $str, ':', $i );
2398 if ( $colon === false ) {
2399 # Nothing else interesting
2400 wfProfileOut( __METHOD__
);
2403 $lt = strpos( $str, '<', $i );
2404 if ( $stack === 0 ) {
2405 if ( $lt === false ||
$colon < $lt ) {
2407 $before = substr( $str, 0, $colon );
2408 $after = substr( $str, $colon +
1 );
2409 wfProfileOut( __METHOD__
);
2413 if ( $lt === false ) {
2414 # Nothing else interesting to find; abort!
2415 # We're nested, but there's no close tags left. Abort!
2418 # Skip ahead to next tag start
2420 $state = self
::COLON_STATE_TAGSTART
;
2423 case 1: # self::COLON_STATE_TAG:
2428 $state = self
::COLON_STATE_TEXT
;
2431 # Slash may be followed by >?
2432 $state = self
::COLON_STATE_TAGSLASH
;
2438 case 2: # self::COLON_STATE_TAGSTART:
2441 $state = self
::COLON_STATE_CLOSETAG
;
2444 $state = self
::COLON_STATE_COMMENT
;
2447 # Illegal early close? This shouldn't happen D:
2448 $state = self
::COLON_STATE_TEXT
;
2451 $state = self
::COLON_STATE_TAG
;
2454 case 3: # self::COLON_STATE_CLOSETAG:
2459 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2460 wfProfileOut( __METHOD__
);
2463 $state = self
::COLON_STATE_TEXT
;
2466 case self
::COLON_STATE_TAGSLASH
:
2468 # Yes, a self-closed tag <blah/>
2469 $state = self
::COLON_STATE_TEXT
;
2471 # Probably we're jumping the gun, and this is an attribute
2472 $state = self
::COLON_STATE_TAG
;
2475 case 5: # self::COLON_STATE_COMMENT:
2477 $state = self
::COLON_STATE_COMMENTDASH
;
2480 case self
::COLON_STATE_COMMENTDASH
:
2482 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2484 $state = self
::COLON_STATE_COMMENT
;
2487 case self
::COLON_STATE_COMMENTDASHDASH
:
2489 $state = self
::COLON_STATE_TEXT
;
2491 $state = self
::COLON_STATE_COMMENT
;
2495 throw new MWException( "State machine error in " . __METHOD__
);
2499 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2502 wfProfileOut( __METHOD__
);
2507 * Return value of a magic variable (like PAGENAME)
2511 function getVariableValue( $index, $frame=false ) {
2512 global $wgContLang, $wgSitename, $wgServer;
2513 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2516 * Some of these require message or data lookups and can be
2517 * expensive to check many times.
2519 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2520 if ( isset( $this->mVarCache
[$index] ) ) {
2521 return $this->mVarCache
[$index];
2525 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2526 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2529 global $wgLocaltimezone;
2530 if ( isset( $wgLocaltimezone ) ) {
2531 $oldtz = date_default_timezone_get();
2532 date_default_timezone_set( $wgLocaltimezone );
2535 $localTimestamp = date( 'YmdHis', $ts );
2536 $localMonth = date( 'm', $ts );
2537 $localMonth1 = date( 'n', $ts );
2538 $localMonthName = date( 'n', $ts );
2539 $localDay = date( 'j', $ts );
2540 $localDay2 = date( 'd', $ts );
2541 $localDayOfWeek = date( 'w', $ts );
2542 $localWeek = date( 'W', $ts );
2543 $localYear = date( 'Y', $ts );
2544 $localHour = date( 'H', $ts );
2545 if ( isset( $wgLocaltimezone ) ) {
2546 date_default_timezone_set( $oldtz );
2550 case 'currentmonth':
2551 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2553 case 'currentmonth1':
2554 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2556 case 'currentmonthname':
2557 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2559 case 'currentmonthnamegen':
2560 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2562 case 'currentmonthabbrev':
2563 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2566 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2569 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2572 $value = $wgContLang->formatNum( $localMonth );
2575 $value = $wgContLang->formatNum( $localMonth1 );
2577 case 'localmonthname':
2578 $value = $wgContLang->getMonthName( $localMonthName );
2580 case 'localmonthnamegen':
2581 $value = $wgContLang->getMonthNameGen( $localMonthName );
2583 case 'localmonthabbrev':
2584 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2587 $value = $wgContLang->formatNum( $localDay );
2590 $value = $wgContLang->formatNum( $localDay2 );
2593 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2596 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2598 case 'fullpagename':
2599 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2601 case 'fullpagenamee':
2602 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2605 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2607 case 'subpagenamee':
2608 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2610 case 'basepagename':
2611 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2613 case 'basepagenamee':
2614 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2616 case 'talkpagename':
2617 if ( $this->mTitle
->canTalk() ) {
2618 $talkPage = $this->mTitle
->getTalkPage();
2619 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2624 case 'talkpagenamee':
2625 if ( $this->mTitle
->canTalk() ) {
2626 $talkPage = $this->mTitle
->getTalkPage();
2627 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2632 case 'subjectpagename':
2633 $subjPage = $this->mTitle
->getSubjectPage();
2634 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2636 case 'subjectpagenamee':
2637 $subjPage = $this->mTitle
->getSubjectPage();
2638 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2641 # Let the edit saving system know we should parse the page
2642 # *after* a revision ID has been assigned.
2643 $this->mOutput
->setFlag( 'vary-revision' );
2644 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2645 $value = $this->mRevisionId
;
2648 # Let the edit saving system know we should parse the page
2649 # *after* a revision ID has been assigned. This is for null edits.
2650 $this->mOutput
->setFlag( 'vary-revision' );
2651 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2652 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2654 case 'revisionday2':
2655 # Let the edit saving system know we should parse the page
2656 # *after* a revision ID has been assigned. This is for null edits.
2657 $this->mOutput
->setFlag( 'vary-revision' );
2658 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2659 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2661 case 'revisionmonth':
2662 # Let the edit saving system know we should parse the page
2663 # *after* a revision ID has been assigned. This is for null edits.
2664 $this->mOutput
->setFlag( 'vary-revision' );
2665 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2666 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2668 case 'revisionmonth1':
2669 # Let the edit saving system know we should parse the page
2670 # *after* a revision ID has been assigned. This is for null edits.
2671 $this->mOutput
->setFlag( 'vary-revision' );
2672 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2673 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2675 case 'revisionyear':
2676 # Let the edit saving system know we should parse the page
2677 # *after* a revision ID has been assigned. This is for null edits.
2678 $this->mOutput
->setFlag( 'vary-revision' );
2679 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2680 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2682 case 'revisiontimestamp':
2683 # Let the edit saving system know we should parse the page
2684 # *after* a revision ID has been assigned. This is for null edits.
2685 $this->mOutput
->setFlag( 'vary-revision' );
2686 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2687 $value = $this->getRevisionTimestamp();
2689 case 'revisionuser':
2690 # Let the edit saving system know we should parse the page
2691 # *after* a revision ID has been assigned. This is for null edits.
2692 $this->mOutput
->setFlag( 'vary-revision' );
2693 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2694 $value = $this->getRevisionUser();
2697 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2700 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2703 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2706 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2708 case 'subjectspace':
2709 $value = $this->mTitle
->getSubjectNsText();
2711 case 'subjectspacee':
2712 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2714 case 'currentdayname':
2715 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2718 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2721 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2724 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2727 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2728 # int to remove the padding
2729 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2732 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2734 case 'localdayname':
2735 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2738 $value = $wgContLang->formatNum( $localYear, true );
2741 $value = $wgContLang->time( $localTimestamp, false, false );
2744 $value = $wgContLang->formatNum( $localHour, true );
2747 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2748 # int to remove the padding
2749 $value = $wgContLang->formatNum( (int)$localWeek );
2752 $value = $wgContLang->formatNum( $localDayOfWeek );
2754 case 'numberofarticles':
2755 $value = $wgContLang->formatNum( SiteStats
::articles() );
2757 case 'numberoffiles':
2758 $value = $wgContLang->formatNum( SiteStats
::images() );
2760 case 'numberofusers':
2761 $value = $wgContLang->formatNum( SiteStats
::users() );
2763 case 'numberofactiveusers':
2764 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2766 case 'numberofpages':
2767 $value = $wgContLang->formatNum( SiteStats
::pages() );
2769 case 'numberofadmins':
2770 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2772 case 'numberofedits':
2773 $value = $wgContLang->formatNum( SiteStats
::edits() );
2775 case 'numberofviews':
2776 $value = $wgContLang->formatNum( SiteStats
::views() );
2778 case 'currenttimestamp':
2779 $value = wfTimestamp( TS_MW
, $ts );
2781 case 'localtimestamp':
2782 $value = $localTimestamp;
2784 case 'currentversion':
2785 $value = SpecialVersion
::getVersion();
2788 return $wgArticlePath;
2794 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2795 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2796 wfRestoreWarnings();
2797 return $serverName ?
$serverName : $wgServer;
2799 return $wgScriptPath;
2801 return $wgStylePath;
2802 case 'directionmark':
2803 return $wgContLang->getDirMark();
2804 case 'contentlanguage':
2805 global $wgLanguageCode;
2806 return $wgLanguageCode;
2809 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2817 $this->mVarCache
[$index] = $value;
2823 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2827 function initialiseVariables() {
2828 wfProfileIn( __METHOD__
);
2829 $variableIDs = MagicWord
::getVariableIDs();
2830 $substIDs = MagicWord
::getSubstIDs();
2832 $this->mVariables
= new MagicWordArray( $variableIDs );
2833 $this->mSubstWords
= new MagicWordArray( $substIDs );
2834 wfProfileOut( __METHOD__
);
2838 * Preprocess some wikitext and return the document tree.
2839 * This is the ghost of replace_variables().
2841 * @param $text String: The text to parse
2842 * @param $flags Integer: bitwise combination of:
2843 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2844 * included. Default is to assume a direct page view.
2846 * The generated DOM tree must depend only on the input text and the flags.
2847 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2849 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2850 * change in the DOM tree for a given text, must be passed through the section identifier
2851 * in the section edit link and thus back to extractSections().
2853 * The output of this function is currently only cached in process memory, but a persistent
2854 * cache may be implemented at a later date which takes further advantage of these strict
2855 * dependency requirements.
2859 function preprocessToDom( $text, $flags = 0 ) {
2860 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2865 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2867 public static function splitWhitespace( $s ) {
2868 $ltrimmed = ltrim( $s );
2869 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2870 $trimmed = rtrim( $ltrimmed );
2871 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2873 $w2 = substr( $ltrimmed, -$diff );
2877 return array( $w1, $trimmed, $w2 );
2881 * Replace magic variables, templates, and template arguments
2882 * with the appropriate text. Templates are substituted recursively,
2883 * taking care to avoid infinite loops.
2885 * Note that the substitution depends on value of $mOutputType:
2886 * self::OT_WIKI: only {{subst:}} templates
2887 * self::OT_PREPROCESS: templates but not extension tags
2888 * self::OT_HTML: all templates and extension tags
2890 * @param $text String: the text to transform
2891 * @param $frame PPFrame Object describing the arguments passed to the template.
2892 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2893 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2894 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2897 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2898 # Is there any text? Also, Prevent too big inclusions!
2899 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2902 wfProfileIn( __METHOD__
);
2904 if ( $frame === false ) {
2905 $frame = $this->getPreprocessor()->newFrame();
2906 } elseif ( !( $frame instanceof PPFrame
) ) {
2907 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2908 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2911 $dom = $this->preprocessToDom( $text );
2912 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2913 $text = $frame->expand( $dom, $flags );
2915 wfProfileOut( __METHOD__
);
2919 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2920 static function createAssocArgs( $args ) {
2921 $assocArgs = array();
2923 foreach ( $args as $arg ) {
2924 $eqpos = strpos( $arg, '=' );
2925 if ( $eqpos === false ) {
2926 $assocArgs[$index++
] = $arg;
2928 $name = trim( substr( $arg, 0, $eqpos ) );
2929 $value = trim( substr( $arg, $eqpos+
1 ) );
2930 if ( $value === false ) {
2933 if ( $name !== false ) {
2934 $assocArgs[$name] = $value;
2943 * Warn the user when a parser limitation is reached
2944 * Will warn at most once the user per limitation type
2946 * @param $limitationType String: should be one of:
2947 * 'expensive-parserfunction' (corresponding messages:
2948 * 'expensive-parserfunction-warning',
2949 * 'expensive-parserfunction-category')
2950 * 'post-expand-template-argument' (corresponding messages:
2951 * 'post-expand-template-argument-warning',
2952 * 'post-expand-template-argument-category')
2953 * 'post-expand-template-inclusion' (corresponding messages:
2954 * 'post-expand-template-inclusion-warning',
2955 * 'post-expand-template-inclusion-category')
2956 * @param $current Current value
2957 * @param $max Maximum allowed, when an explicit limit has been
2958 * exceeded, provide the values (optional)
2960 function limitationWarn( $limitationType, $current=null, $max=null) {
2961 # does no harm if $current and $max are present but are unnecessary for the message
2962 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2963 $this->mOutput
->addWarning( $warning );
2964 $this->addTrackingCategory( "$limitationType-category" );
2968 * Return the text of a template, after recursively
2969 * replacing any variables or templates within the template.
2971 * @param $piece Array: the parts of the template
2972 * $piece['title']: the title, i.e. the part before the |
2973 * $piece['parts']: the parameter array
2974 * $piece['lineStart']: whether the brace was at the start of a line
2975 * @param $frame PPFrame The current frame, contains template arguments
2976 * @return String: the text of the template
2979 function braceSubstitution( $piece, $frame ) {
2980 global $wgContLang, $wgNonincludableNamespaces;
2981 wfProfileIn( __METHOD__
);
2982 wfProfileIn( __METHOD__
.'-setup' );
2985 $found = false; # $text has been filled
2986 $nowiki = false; # wiki markup in $text should be escaped
2987 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2988 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2989 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2990 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2992 # Title object, where $text came from
2995 # $part1 is the bit before the first |, and must contain only title characters.
2996 # Various prefixes will be stripped from it later.
2997 $titleWithSpaces = $frame->expand( $piece['title'] );
2998 $part1 = trim( $titleWithSpaces );
3001 # Original title text preserved for various purposes
3002 $originalTitle = $part1;
3004 # $args is a list of argument nodes, starting from index 0, not including $part1
3005 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3006 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3007 wfProfileOut( __METHOD__
.'-setup' );
3010 wfProfileIn( __METHOD__
.'-modifiers' );
3013 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3015 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3016 # Decide whether to expand template or keep wikitext as-is.
3017 if ( $this->ot
['wiki'] ) {
3018 if ( $substMatch === false ) {
3019 $literal = true; # literal when in PST with no prefix
3021 $literal = false; # expand when in PST with subst: or safesubst:
3024 if ( $substMatch == 'subst' ) {
3025 $literal = true; # literal when not in PST with plain subst:
3027 $literal = false; # expand when not in PST with safesubst: or no prefix
3031 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3038 if ( !$found && $args->getLength() == 0 ) {
3039 $id = $this->mVariables
->matchStartToEnd( $part1 );
3040 if ( $id !== false ) {
3041 $text = $this->getVariableValue( $id, $frame );
3042 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3043 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3049 # MSG, MSGNW and RAW
3052 $mwMsgnw = MagicWord
::get( 'msgnw' );
3053 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3056 # Remove obsolete MSG:
3057 $mwMsg = MagicWord
::get( 'msg' );
3058 $mwMsg->matchStartAndRemove( $part1 );
3062 $mwRaw = MagicWord
::get( 'raw' );
3063 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3064 $forceRawInterwiki = true;
3067 wfProfileOut( __METHOD__
.'-modifiers' );
3071 wfProfileIn( __METHOD__
. '-pfunc' );
3073 $colonPos = strpos( $part1, ':' );
3074 if ( $colonPos !== false ) {
3075 # Case sensitive functions
3076 $function = substr( $part1, 0, $colonPos );
3077 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3078 $function = $this->mFunctionSynonyms
[1][$function];
3080 # Case insensitive functions
3081 $function = $wgContLang->lc( $function );
3082 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3083 $function = $this->mFunctionSynonyms
[0][$function];
3089 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3090 $initialArgs = array( &$this );
3091 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3092 if ( $flags & SFH_OBJECT_ARGS
) {
3093 # Add a frame parameter, and pass the arguments as an array
3094 $allArgs = $initialArgs;
3095 $allArgs[] = $frame;
3096 for ( $i = 0; $i < $args->getLength(); $i++
) {
3097 $funcArgs[] = $args->item( $i );
3099 $allArgs[] = $funcArgs;
3101 # Convert arguments to plain text
3102 for ( $i = 0; $i < $args->getLength(); $i++
) {
3103 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3105 $allArgs = array_merge( $initialArgs, $funcArgs );
3108 # Workaround for PHP bug 35229 and similar
3109 if ( !is_callable( $callback ) ) {
3110 wfProfileOut( __METHOD__
. '-pfunc' );
3111 wfProfileOut( __METHOD__
);
3112 throw new MWException( "Tag hook for $function is not callable\n" );
3114 $result = call_user_func_array( $callback, $allArgs );
3117 $preprocessFlags = 0;
3119 if ( is_array( $result ) ) {
3120 if ( isset( $result[0] ) ) {
3122 unset( $result[0] );
3125 # Extract flags into the local scope
3126 # This allows callers to set flags such as nowiki, found, etc.
3132 $text = $this->preprocessToDom( $text, $preprocessFlags );
3137 wfProfileOut( __METHOD__
. '-pfunc' );
3140 # Finish mangling title and then check for loops.
3141 # Set $title to a Title object and $titleText to the PDBK
3144 # Split the title into page and subpage
3146 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3147 if ( $subpage !== '' ) {
3148 $ns = $this->mTitle
->getNamespace();
3150 $title = Title
::newFromText( $part1, $ns );
3152 $titleText = $title->getPrefixedText();
3153 # Check for language variants if the template is not found
3154 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3155 $wgContLang->findVariantLink( $part1, $title, true );
3157 # Do recursion depth check
3158 $limit = $this->mOptions
->getMaxTemplateDepth();
3159 if ( $frame->depth
>= $limit ) {
3161 $text = '<span class="error">'
3162 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3168 # Load from database
3169 if ( !$found && $title ) {
3170 wfProfileIn( __METHOD__
. '-loadtpl' );
3171 if ( !$title->isExternal() ) {
3172 if ( $title->getNamespace() == NS_SPECIAL
3173 && $this->mOptions
->getAllowSpecialInclusion()
3174 && $this->ot
['html'] )
3176 $text = SpecialPage
::capturePath( $title );
3177 if ( is_string( $text ) ) {
3180 $this->disableCache();
3182 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3183 $found = false; # access denied
3184 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3186 list( $text, $title ) = $this->getTemplateDom( $title );
3187 if ( $text !== false ) {
3193 # If the title is valid but undisplayable, make a link to it
3194 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3195 $text = "[[:$titleText]]";
3198 } elseif ( $title->isTrans() ) {
3199 # Interwiki transclusion
3200 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3201 $text = $this->interwikiTransclude( $title, 'render' );
3204 $text = $this->interwikiTransclude( $title, 'raw' );
3205 # Preprocess it like a template
3206 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3212 # Do infinite loop check
3213 # This has to be done after redirect resolution to avoid infinite loops via redirects
3214 if ( !$frame->loopCheck( $title ) ) {
3216 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3217 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3219 wfProfileOut( __METHOD__
. '-loadtpl' );
3222 # If we haven't found text to substitute by now, we're done
3223 # Recover the source wikitext and return it
3225 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3226 wfProfileOut( __METHOD__
);
3227 return array( 'object' => $text );
3230 # Expand DOM-style return values in a child frame
3231 if ( $isChildObj ) {
3232 # Clean up argument array
3233 $newFrame = $frame->newChild( $args, $title );
3236 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3237 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3238 # Expansion is eligible for the empty-frame cache
3239 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3240 $text = $this->mTplExpandCache
[$titleText];
3242 $text = $newFrame->expand( $text );
3243 $this->mTplExpandCache
[$titleText] = $text;
3246 # Uncached expansion
3247 $text = $newFrame->expand( $text );
3250 if ( $isLocalObj && $nowiki ) {
3251 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3252 $isLocalObj = false;
3255 # Replace raw HTML by a placeholder
3256 # Add a blank line preceding, to prevent it from mucking up
3257 # immediately preceding headings
3259 $text = "\n\n" . $this->insertStripItem( $text );
3260 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3261 # Escape nowiki-style return values
3262 $text = wfEscapeWikiText( $text );
3263 } elseif ( is_string( $text )
3264 && !$piece['lineStart']
3265 && preg_match( '/^{\\|/', $text ) )
3267 # Bug 529: if the template begins with a table, it should be treated as
3268 # beginning a new line. This previously handled other block-level elements
3269 # such as #, :, etc, but these have many false-positives (bug 12974).
3270 $text = "\n" . $text;
3273 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3274 # Error, oversize inclusion
3275 if ( $titleText !== false ) {
3276 # Make a working, properly escaped link if possible (bug 23588)
3277 $text = "[[:$titleText]]";
3279 # This will probably not be a working link, but at least it may
3280 # provide some hint of where the problem is
3281 preg_replace( '/^:/', '', $originalTitle );
3282 $text = "[[:$originalTitle]]";
3284 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3285 $this->limitationWarn( 'post-expand-template-inclusion' );
3288 if ( $isLocalObj ) {
3289 $ret = array( 'object' => $text );
3291 $ret = array( 'text' => $text );
3294 wfProfileOut( __METHOD__
);
3299 * Get the semi-parsed DOM representation of a template with a given title,
3300 * and its redirect destination title. Cached.
3302 function getTemplateDom( $title ) {
3303 $cacheTitle = $title;
3304 $titleText = $title->getPrefixedDBkey();
3306 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3307 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3308 $title = Title
::makeTitle( $ns, $dbk );
3309 $titleText = $title->getPrefixedDBkey();
3311 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3312 return array( $this->mTplDomCache
[$titleText], $title );
3315 # Cache miss, go to the database
3316 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3318 if ( $text === false ) {
3319 $this->mTplDomCache
[$titleText] = false;
3320 return array( false, $title );
3323 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3324 $this->mTplDomCache
[ $titleText ] = $dom;
3326 if ( !$title->equals( $cacheTitle ) ) {
3327 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3328 array( $title->getNamespace(), $title->getDBkey() );
3331 return array( $dom, $title );
3335 * Fetch the unparsed text of a template and register a reference to it.
3337 function fetchTemplateAndTitle( $title ) {
3338 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3339 $stuff = call_user_func( $templateCb, $title, $this );
3340 $text = $stuff['text'];
3341 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3342 if ( isset( $stuff['deps'] ) ) {
3343 foreach ( $stuff['deps'] as $dep ) {
3344 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3347 return array( $text, $finalTitle );
3350 function fetchTemplate( $title ) {
3351 $rv = $this->fetchTemplateAndTitle( $title );
3356 * Static function to get a template
3357 * Can be overridden via ParserOptions::setTemplateCallback().
3359 static function statelessFetchTemplate( $title, $parser=false ) {
3360 $text = $skip = false;
3361 $finalTitle = $title;
3364 # Loop to fetch the article, with up to 1 redirect
3365 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3366 # Give extensions a chance to select the revision instead
3367 $id = false; # Assume current
3368 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3374 'page_id' => $title->getArticleID(),
3378 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3379 $rev_id = $rev ?
$rev->getId() : 0;
3380 # If there is no current revision, there is no page
3381 if ( $id === false && !$rev ) {
3382 $linkCache = LinkCache
::singleton();
3383 $linkCache->addBadLinkObj( $title );
3388 'page_id' => $title->getArticleID(),
3389 'rev_id' => $rev_id );
3392 $text = $rev->getText();
3393 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3395 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3396 if ( !$message->exists() ) {
3400 $text = $message->plain();
3404 if ( $text === false ) {
3408 $finalTitle = $title;
3409 $title = Title
::newFromRedirect( $text );
3413 'finalTitle' => $finalTitle,
3418 * Transclude an interwiki link.
3420 function interwikiTransclude( $title, $action ) {
3421 global $wgEnableScaryTranscluding;
3423 if ( !$wgEnableScaryTranscluding ) {
3424 return wfMsgForContent('scarytranscludedisabled');
3427 $url = $title->getFullUrl( "action=$action" );
3429 if ( strlen( $url ) > 255 ) {
3430 return wfMsgForContent( 'scarytranscludetoolong' );
3432 return $this->fetchScaryTemplateMaybeFromCache( $url );
3435 function fetchScaryTemplateMaybeFromCache( $url ) {
3436 global $wgTranscludeCacheExpiry;
3437 $dbr = wfGetDB( DB_SLAVE
);
3438 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3439 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3440 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3442 return $obj->tc_contents
;
3445 $text = Http
::get( $url );
3447 return wfMsgForContent( 'scarytranscludefailed', $url );
3450 $dbw = wfGetDB( DB_MASTER
);
3451 $dbw->replace( 'transcache', array('tc_url'), array(
3453 'tc_time' => $dbw->timestamp( time() ),
3454 'tc_contents' => $text)
3461 * Triple brace replacement -- used for template arguments
3464 function argSubstitution( $piece, $frame ) {
3465 wfProfileIn( __METHOD__
);
3468 $parts = $piece['parts'];
3469 $nameWithSpaces = $frame->expand( $piece['title'] );
3470 $argName = trim( $nameWithSpaces );
3472 $text = $frame->getArgument( $argName );
3473 if ( $text === false && $parts->getLength() > 0
3477 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3480 # No match in frame, use the supplied default
3481 $object = $parts->item( 0 )->getChildren();
3483 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3484 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3485 $this->limitationWarn( 'post-expand-template-argument' );
3488 if ( $text === false && $object === false ) {
3490 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3492 if ( $error !== false ) {
3495 if ( $object !== false ) {
3496 $ret = array( 'object' => $object );
3498 $ret = array( 'text' => $text );
3501 wfProfileOut( __METHOD__
);
3506 * Return the text to be used for a given extension tag.
3507 * This is the ghost of strip().
3509 * @param $params Associative array of parameters:
3510 * name PPNode for the tag name
3511 * attr PPNode for unparsed text where tag attributes are thought to be
3512 * attributes Optional associative array of parsed attributes
3513 * inner Contents of extension element
3514 * noClose Original text did not have a close tag
3515 * @param $frame PPFrame
3517 function extensionSubstitution( $params, $frame ) {
3518 $name = $frame->expand( $params['name'] );
3519 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3520 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3521 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3523 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3524 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3525 if ( $isFunctionTag ) {
3526 $markerType = 'none';
3528 $markerType = 'general';
3530 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3531 $name = strtolower( $name );
3532 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3533 if ( isset( $params['attributes'] ) ) {
3534 $attributes = $attributes +
$params['attributes'];
3537 if ( isset( $this->mTagHooks
[$name] ) ) {
3538 # Workaround for PHP bug 35229 and similar
3539 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3540 throw new MWException( "Tag hook for $name is not callable\n" );
3542 $output = call_user_func_array( $this->mTagHooks
[$name],
3543 array( $content, $attributes, $this, $frame ) );
3544 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3545 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3546 if ( !is_callable( $callback ) ) {
3547 throw new MWException( "Tag hook for $name is not callable\n" );
3550 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3552 $output = '<span class="error">Invalid tag extension name: ' .
3553 htmlspecialchars( $name ) . '</span>';
3556 if ( is_array( $output ) ) {
3557 # Extract flags to local scope (to override $markerType)
3559 $output = $flags[0];
3564 if ( is_null( $attrText ) ) {
3567 if ( isset( $params['attributes'] ) ) {
3568 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3569 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3570 htmlspecialchars( $attrValue ) . '"';
3573 if ( $content === null ) {
3574 $output = "<$name$attrText/>";
3576 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3577 $output = "<$name$attrText>$content$close";
3581 if ( $markerType === 'none' ) {
3583 } elseif ( $markerType === 'nowiki' ) {
3584 $this->mStripState
->nowiki
->setPair( $marker, $output );
3585 } elseif ( $markerType === 'general' ) {
3586 $this->mStripState
->general
->setPair( $marker, $output );
3588 throw new MWException( __METHOD__
.': invalid marker type' );
3594 * Increment an include size counter
3596 * @param $type String: the type of expansion
3597 * @param $size Integer: the size of the text
3598 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3600 function incrementIncludeSize( $type, $size ) {
3601 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3604 $this->mIncludeSizes
[$type] +
= $size;
3610 * Increment the expensive function count
3612 * @return Boolean: false if the limit has been exceeded
3614 function incrementExpensiveFunctionCount() {
3615 global $wgExpensiveParserFunctionLimit;
3616 $this->mExpensiveFunctionCount++
;
3617 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3624 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3625 * Fills $this->mDoubleUnderscores, returns the modified text
3627 function doDoubleUnderscore( $text ) {
3628 wfProfileIn( __METHOD__
);
3630 # The position of __TOC__ needs to be recorded
3631 $mw = MagicWord
::get( 'toc' );
3632 if ( $mw->match( $text ) ) {
3633 $this->mShowToc
= true;
3634 $this->mForceTocPosition
= true;
3636 # Set a placeholder. At the end we'll fill it in with the TOC.
3637 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3639 # Only keep the first one.
3640 $text = $mw->replace( '', $text );
3643 # Now match and remove the rest of them
3644 $mwa = MagicWord
::getDoubleUnderscoreArray();
3645 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3647 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3648 $this->mOutput
->mNoGallery
= true;
3650 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3651 $this->mShowToc
= false;
3653 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3654 $this->addTrackingCategory( 'hidden-category-category' );
3656 # (bug 8068) Allow control over whether robots index a page.
3658 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3659 # is not desirable, the last one on the page should win.
3660 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3661 $this->mOutput
->setIndexPolicy( 'noindex' );
3662 $this->addTrackingCategory( 'noindex-category' );
3664 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3665 $this->mOutput
->setIndexPolicy( 'index' );
3666 $this->addTrackingCategory( 'index-category' );
3669 # Cache all double underscores in the database
3670 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3671 $this->mOutput
->setProperty( $key, '' );
3674 wfProfileOut( __METHOD__
);
3679 * Add a tracking category, getting the title from a system message,
3680 * or print a debug message if the title is invalid.
3682 * @param $msg String: message key
3683 * @return Boolean: whether the addition was successful
3685 protected function addTrackingCategory( $msg ) {
3686 $cat = wfMsgForContent( $msg );
3688 # Allow tracking categories to be disabled by setting them to "-"
3689 if ( $cat === '-' ) {
3693 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3694 if ( $containerCategory ) {
3695 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3698 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3704 * This function accomplishes several tasks:
3705 * 1) Auto-number headings if that option is enabled
3706 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3707 * 3) Add a Table of contents on the top for users who have enabled the option
3708 * 4) Auto-anchor headings
3710 * It loops through all headlines, collects the necessary data, then splits up the
3711 * string and re-inserts the newly formatted headlines.
3713 * @param $text String
3714 * @param $origText String: original, untouched wikitext
3715 * @param $isMain Boolean
3718 function formatHeadings( $text, $origText, $isMain=true ) {
3719 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3721 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3723 # Inhibit editsection links if requested in the page
3724 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3727 $showEditLink = $this->mOptions
->getEditSection();
3729 if ( $showEditLink ) {
3730 $this->mOutput
->setEditSectionTokens( true );
3733 # Get all headlines for numbering them and adding funky stuff like [edit]
3734 # links - this is for later, but we need the number of headlines right now
3736 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3738 # if there are fewer than 4 headlines in the article, do not show TOC
3739 # unless it's been explicitly enabled.
3740 $enoughToc = $this->mShowToc
&&
3741 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3743 # Allow user to stipulate that a page should have a "new section"
3744 # link added via __NEWSECTIONLINK__
3745 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3746 $this->mOutput
->setNewSection( true );
3749 # Allow user to remove the "new section"
3750 # link via __NONEWSECTIONLINK__
3751 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3752 $this->mOutput
->hideNewSection( true );
3755 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3756 # override above conditions and always show TOC above first header
3757 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3758 $this->mShowToc
= true;
3762 # We need this to perform operations on the HTML
3763 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3769 # Ugh .. the TOC should have neat indentation levels which can be
3770 # passed to the skin functions. These are determined here
3774 $sublevelCount = array();
3775 $levelCount = array();
3780 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3781 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3782 $oldType = $this->mOutputType
;
3783 $this->setOutputType( self
::OT_WIKI
);
3784 $frame = $this->getPreprocessor()->newFrame();
3785 $root = $this->preprocessToDom( $origText );
3786 $node = $root->getFirstChild();
3791 foreach ( $matches[3] as $headline ) {
3792 $isTemplate = false;
3794 $sectionIndex = false;
3796 $markerMatches = array();
3797 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3798 $serial = $markerMatches[1];
3799 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3800 $isTemplate = ( $titleText != $baseTitleText );
3801 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3805 $prevlevel = $level;
3807 $level = $matches[1][$headlineCount];
3809 if ( $level > $prevlevel ) {
3810 # Increase TOC level
3812 $sublevelCount[$toclevel] = 0;
3813 if ( $toclevel<$wgMaxTocLevel ) {
3814 $prevtoclevel = $toclevel;
3815 $toc .= $sk->tocIndent();
3818 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3819 # Decrease TOC level, find level to jump to
3821 for ( $i = $toclevel; $i > 0; $i-- ) {
3822 if ( $levelCount[$i] == $level ) {
3823 # Found last matching level
3826 } elseif ( $levelCount[$i] < $level ) {
3827 # Found first matching level below current level
3835 if ( $toclevel<$wgMaxTocLevel ) {
3836 if ( $prevtoclevel < $wgMaxTocLevel ) {
3837 # Unindent only if the previous toc level was shown :p
3838 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3839 $prevtoclevel = $toclevel;
3841 $toc .= $sk->tocLineEnd();
3845 # No change in level, end TOC line
3846 if ( $toclevel<$wgMaxTocLevel ) {
3847 $toc .= $sk->tocLineEnd();
3851 $levelCount[$toclevel] = $level;
3853 # count number of headlines for each level
3854 @$sublevelCount[$toclevel]++
;
3856 for( $i = 1; $i <= $toclevel; $i++
) {
3857 if ( !empty( $sublevelCount[$i] ) ) {
3861 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3866 # The safe header is a version of the header text safe to use for links
3867 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3868 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3870 # Remove link placeholders by the link text.
3871 # <!--LINK number-->
3873 # link text with suffix
3874 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3876 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3877 $tocline = preg_replace(
3878 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3879 array( '', '<$1>' ),
3882 $tocline = trim( $tocline );
3884 # For the anchor, strip out HTML-y stuff period
3885 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3886 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3888 # Save headline for section edit hint before it's escaped
3889 $headlineHint = $safeHeadline;
3891 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3892 # For reverse compatibility, provide an id that's
3893 # HTML4-compatible, like we used to.
3895 # It may be worth noting, academically, that it's possible for
3896 # the legacy anchor to conflict with a non-legacy headline
3897 # anchor on the page. In this case likely the "correct" thing
3898 # would be to either drop the legacy anchors or make sure
3899 # they're numbered first. However, this would require people
3900 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3901 # manually, so let's not bother worrying about it.
3902 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3903 array( 'noninitial', 'legacy' ) );
3904 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3906 if ( $legacyHeadline == $safeHeadline ) {
3907 # No reason to have both (in fact, we can't)
3908 $legacyHeadline = false;
3911 $legacyHeadline = false;
3912 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3916 # HTML names must be case-insensitively unique (bug 10721).
3917 # This does not apply to Unicode characters per
3918 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3919 # FIXME: We may be changing them depending on the current locale.
3920 $arrayKey = strtolower( $safeHeadline );
3921 if ( $legacyHeadline === false ) {
3922 $legacyArrayKey = false;
3924 $legacyArrayKey = strtolower( $legacyHeadline );
3927 # count how many in assoc. array so we can track dupes in anchors
3928 if ( isset( $refers[$arrayKey] ) ) {
3929 $refers[$arrayKey]++
;
3931 $refers[$arrayKey] = 1;
3933 if ( isset( $refers[$legacyArrayKey] ) ) {
3934 $refers[$legacyArrayKey]++
;
3936 $refers[$legacyArrayKey] = 1;
3939 # Don't number the heading if it is the only one (looks silly)
3940 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3941 # the two are different if the line contains a link
3942 $headline = $numbering . ' ' . $headline;
3945 # Create the anchor for linking from the TOC to the section
3946 $anchor = $safeHeadline;
3947 $legacyAnchor = $legacyHeadline;
3948 if ( $refers[$arrayKey] > 1 ) {
3949 $anchor .= '_' . $refers[$arrayKey];
3951 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3952 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3954 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3955 $toc .= $sk->tocLine( $anchor, $tocline,
3956 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3959 # Add the section to the section tree
3960 # Find the DOM node for this header
3961 while ( $node && !$isTemplate ) {
3962 if ( $node->getName() === 'h' ) {
3963 $bits = $node->splitHeading();
3964 if ( $bits['i'] == $sectionIndex ) {
3968 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3969 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3970 $node = $node->getNextSibling();
3973 'toclevel' => $toclevel,
3976 'number' => $numbering,
3977 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3978 'fromtitle' => $titleText,
3979 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3980 'anchor' => $anchor,
3983 # give headline the correct <h#> tag
3984 if ( $showEditLink && $sectionIndex !== false ) {
3985 // Output edit section links as markers with styles that can be customized by skins
3986 if ( $isTemplate ) {
3987 # Put a T flag in the section identifier, to indicate to extractSections()
3988 # that sections inside <includeonly> should be counted.
3989 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3991 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3993 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3994 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3995 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3996 // so we don't have to worry about a user trying to input one of these markers directly.
3997 // We use a page and section attribute to stop the language converter from converting these important bits
3998 // of data, but put the headline hint inside a content block because the language converter is supposed to
3999 // be able to convert that piece of data.
4000 $editlink = '<editsection page="' . htmlspecialchars($editlinkArgs[0]);
4001 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4002 if ( isset($editlinkArgs[2]) ) {
4003 $editlink .= '>' . $editlinkArgs[2] . '</editsection>';
4010 $head[$headlineCount] = $sk->makeHeadline( $level,
4011 $matches['attrib'][$headlineCount], $anchor, $headline,
4012 $editlink, $legacyAnchor );
4017 $this->setOutputType( $oldType );
4019 # Never ever show TOC if no headers
4020 if ( $numVisible < 1 ) {
4025 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4026 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
4028 $toc = $sk->tocList( $toc );
4029 $this->mOutput
->setTOCHTML( $toc );
4033 $this->mOutput
->setSections( $tocraw );
4036 # split up and insert constructed headlines
4038 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4041 foreach ( $blocks as $block ) {
4042 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4043 # This is the [edit] link that appears for the top block of text when
4044 # section editing is enabled
4046 # Disabled because it broke block formatting
4047 # For example, a bullet point in the top line
4048 # $full .= $sk->editSectionLink(0);
4051 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4052 # Top anchor now in skin
4056 if ( !empty( $head[$i] ) ) {
4061 if ( $this->mForceTocPosition
) {
4062 return str_replace( '<!--MWTOC-->', $toc, $full );
4069 * Transform wiki markup when saving a page by doing \r\n -> \n
4070 * conversion, substitting signatures, {{subst:}} templates, etc.
4072 * @param $text String: the text to transform
4073 * @param $title Title: the Title object for the current article
4074 * @param $user User: the User object describing the current user
4075 * @param $options ParserOptions: parsing options
4076 * @param $clearState Boolean: whether to clear the parser state first
4077 * @return String: the altered wiki markup
4079 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4080 $this->mOptions
= $options;
4081 $this->setTitle( $title );
4082 $this->setUser( $user );
4083 $this->setOutputType( self
::OT_WIKI
);
4085 if ( $clearState ) {
4086 $this->clearState();
4092 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4093 if( $options->getPreSaveTransform() ) {
4094 $text = $this->pstPass2( $text, $user );
4096 $text = $this->mStripState
->unstripBoth( $text );
4098 $this->setUser( null ); #Reset
4104 * Pre-save transform helper function
4107 function pstPass2( $text, $user ) {
4108 global $wgContLang, $wgLocaltimezone;
4110 # Note: This is the timestamp saved as hardcoded wikitext to
4111 # the database, we use $wgContLang here in order to give
4112 # everyone the same signature and use the default one rather
4113 # than the one selected in each user's preferences.
4114 # (see also bug 12815)
4115 $ts = $this->mOptions
->getTimestamp();
4116 if ( isset( $wgLocaltimezone ) ) {
4117 $tz = $wgLocaltimezone;
4119 $tz = date_default_timezone_get();
4122 $unixts = wfTimestamp( TS_UNIX
, $ts );
4123 $oldtz = date_default_timezone_get();
4124 date_default_timezone_set( $tz );
4125 $ts = date( 'YmdHis', $unixts );
4126 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4128 # Allow translation of timezones through wiki. date() can return
4129 # whatever crap the system uses, localised or not, so we cannot
4130 # ship premade translations.
4131 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4132 $msg = wfMessage( $key )->inContentLanguage();
4133 if ( $msg->exists() ) {
4134 $tzMsg = $msg->text();
4137 date_default_timezone_set( $oldtz );
4139 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4141 # Variable replacement
4142 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4143 $text = $this->replaceVariables( $text );
4146 $sigText = $this->getUserSig( $user );
4147 $text = strtr( $text, array(
4149 '~~~~' => "$sigText $d",
4153 # Context links: [[|name]] and [[name (context)|]]
4154 global $wgLegalTitleChars;
4155 $tc = "[$wgLegalTitleChars]";
4156 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4158 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4159 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4160 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4161 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4163 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4164 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4165 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4166 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4168 $t = $this->mTitle
->getText();
4170 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4171 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4172 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4173 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4175 # if there's no context, don't bother duplicating the title
4176 $text = preg_replace( $p2, '[[\\1]]', $text );
4179 # Trim trailing whitespace
4180 $text = rtrim( $text );
4186 * Fetch the user's signature text, if any, and normalize to
4187 * validated, ready-to-insert wikitext.
4188 * If you have pre-fetched the nickname or the fancySig option, you can
4189 * specify them here to save a database query.
4192 * @param $nickname String: nickname to use or false to use user's default nickname
4193 * @param $fancySig Boolean: whether the nicknname is the complete signature
4194 * or null to use default value
4197 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4198 global $wgMaxSigChars;
4200 $username = $user->getName();
4202 # If not given, retrieve from the user object.
4203 if ( $nickname === false )
4204 $nickname = $user->getOption( 'nickname' );
4206 if ( is_null( $fancySig ) ) {
4207 $fancySig = $user->getBoolOption( 'fancysig' );
4210 $nickname = $nickname == null ?
$username : $nickname;
4212 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4213 $nickname = $username;
4214 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4215 } elseif ( $fancySig !== false ) {
4216 # Sig. might contain markup; validate this
4217 if ( $this->validateSig( $nickname ) !== false ) {
4218 # Validated; clean up (if needed) and return it
4219 return $this->cleanSig( $nickname, true );
4221 # Failed to validate; fall back to the default
4222 $nickname = $username;
4223 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4227 # Make sure nickname doesnt get a sig in a sig
4228 $nickname = $this->cleanSigInSig( $nickname );
4230 # If we're still here, make it a link to the user page
4231 $userText = wfEscapeWikiText( $username );
4232 $nickText = wfEscapeWikiText( $nickname );
4233 if ( $user->isAnon() ) {
4234 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4236 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4241 * Check that the user's signature contains no bad XML
4243 * @param $text String
4244 * @return mixed An expanded string, or false if invalid.
4246 function validateSig( $text ) {
4247 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4251 * Clean up signature text
4253 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4254 * 2) Substitute all transclusions
4256 * @param $text String
4257 * @param $parsing Whether we're cleaning (preferences save) or parsing
4258 * @return String: signature text
4260 function cleanSig( $text, $parsing = false ) {
4263 $this->mOptions
= new ParserOptions
;
4264 $this->clearState();
4265 $this->setTitle( $wgTitle );
4266 $this->setOutputType
= self
::OT_PREPROCESS
;
4269 # Option to disable this feature
4270 if ( !$this->mOptions
->getCleanSignatures() ) {
4274 # FIXME: regex doesn't respect extension tags or nowiki
4275 # => Move this logic to braceSubstitution()
4276 $substWord = MagicWord
::get( 'subst' );
4277 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4278 $substText = '{{' . $substWord->getSynonym( 0 );
4280 $text = preg_replace( $substRegex, $substText, $text );
4281 $text = $this->cleanSigInSig( $text );
4282 $dom = $this->preprocessToDom( $text );
4283 $frame = $this->getPreprocessor()->newFrame();
4284 $text = $frame->expand( $dom );
4287 $text = $this->mStripState
->unstripBoth( $text );
4294 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4296 * @param $text String
4297 * @return String: signature text with /~{3,5}/ removed
4299 function cleanSigInSig( $text ) {
4300 $text = preg_replace( '/~{3,5}/', '', $text );
4305 * Set up some variables which are usually set up in parse()
4306 * so that an external function can call some class members with confidence
4308 public function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4309 $this->setTitle( $title );
4310 $this->mOptions
= $options;
4311 $this->setOutputType( $outputType );
4312 if ( $clearState ) {
4313 $this->clearState();
4318 * Wrapper for preprocess()
4320 * @param $text String: the text to preprocess
4321 * @param $options ParserOptions: options
4324 public function transformMsg( $text, $options ) {
4326 static $executing = false;
4328 # Guard against infinite recursion
4334 wfProfileIn( __METHOD__
);
4335 $text = $this->preprocess( $text, $wgTitle, $options );
4338 wfProfileOut( __METHOD__
);
4343 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4344 * The callback should have the following form:
4345 * function myParserHook( $text, $params, $parser ) { ... }
4347 * Transform and return $text. Use $parser for any required context, e.g. use
4348 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4350 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4351 * @param $callback Mixed: the callback function (and object) to use for the tag
4352 * @return The old value of the mTagHooks array associated with the hook
4354 public function setHook( $tag, $callback ) {
4355 $tag = strtolower( $tag );
4356 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4357 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4358 $this->mTagHooks
[$tag] = $callback;
4359 if ( !in_array( $tag, $this->mStripList
) ) {
4360 $this->mStripList
[] = $tag;
4366 function setTransparentTagHook( $tag, $callback ) {
4367 $tag = strtolower( $tag );
4368 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4369 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4370 $this->mTransparentTagHooks
[$tag] = $callback;
4376 * Remove all tag hooks
4378 function clearTagHooks() {
4379 $this->mTagHooks
= array();
4380 $this->mStripList
= $this->mDefaultStripList
;
4384 * Create a function, e.g. {{sum:1|2|3}}
4385 * The callback function should have the form:
4386 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4388 * Or with SFH_OBJECT_ARGS:
4389 * function myParserFunction( $parser, $frame, $args ) { ... }
4391 * The callback may either return the text result of the function, or an array with the text
4392 * in element 0, and a number of flags in the other elements. The names of the flags are
4393 * specified in the keys. Valid flags are:
4394 * found The text returned is valid, stop processing the template. This
4396 * nowiki Wiki markup in the return value should be escaped
4397 * isHTML The returned text is HTML, armour it against wikitext transformation
4399 * @param $id String: The magic word ID
4400 * @param $callback Mixed: the callback function (and object) to use
4401 * @param $flags Integer: a combination of the following flags:
4402 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4404 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4405 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4406 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4407 * the arguments, and to control the way they are expanded.
4409 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4410 * arguments, for instance:
4411 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4413 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4414 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4415 * working if/when this is changed.
4417 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4420 * Please read the documentation in includes/parser/Preprocessor.php for more information
4421 * about the methods available in PPFrame and PPNode.
4423 * @return The old callback function for this name, if any
4425 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4428 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4429 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4431 # Add to function cache
4432 $mw = MagicWord
::get( $id );
4434 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4436 $synonyms = $mw->getSynonyms();
4437 $sensitive = intval( $mw->isCaseSensitive() );
4439 foreach ( $synonyms as $syn ) {
4441 if ( !$sensitive ) {
4442 $syn = $wgContLang->lc( $syn );
4445 if ( !( $flags & SFH_NO_HASH
) ) {
4448 # Remove trailing colon
4449 if ( substr( $syn, -1, 1 ) === ':' ) {
4450 $syn = substr( $syn, 0, -1 );
4452 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4458 * Get all registered function hook identifiers
4462 function getFunctionHooks() {
4463 return array_keys( $this->mFunctionHooks
);
4467 * Create a tag function, e.g. <test>some stuff</test>.
4468 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4469 * Unlike parser functions, their content is not preprocessed.
4471 function setFunctionTagHook( $tag, $callback, $flags ) {
4472 $tag = strtolower( $tag );
4473 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4474 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4475 $this->mFunctionTagHooks
[$tag] : null;
4476 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4478 if ( !in_array( $tag, $this->mStripList
) ) {
4479 $this->mStripList
[] = $tag;
4486 * FIXME: update documentation. makeLinkObj() is deprecated.
4487 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4488 * Placeholders created in Skin::makeLinkObj()
4489 * Returns an array of link CSS classes, indexed by PDBK.
4491 function replaceLinkHolders( &$text, $options = 0 ) {
4492 return $this->mLinkHolders
->replace( $text );
4496 * Replace <!--LINK--> link placeholders with plain text of links
4497 * (not HTML-formatted).
4499 * @param $text String
4502 function replaceLinkHoldersText( $text ) {
4503 return $this->mLinkHolders
->replaceText( $text );
4507 * Renders an image gallery from a text with one line per image.
4508 * text labels may be given by using |-style alternative text. E.g.
4509 * Image:one.jpg|The number "1"
4510 * Image:tree.jpg|A tree
4511 * given as text will return the HTML of a gallery with two images,
4512 * labeled 'The number "1"' and
4515 function renderImageGallery( $text, $params ) {
4516 $ig = new ImageGallery();
4517 $ig->setContextTitle( $this->mTitle
);
4518 $ig->setShowBytes( false );
4519 $ig->setShowFilename( false );
4520 $ig->setParser( $this );
4521 $ig->setHideBadImages();
4522 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4523 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4524 $ig->mRevisionId
= $this->mRevisionId
;
4526 if ( isset( $params['showfilename'] ) ) {
4527 $ig->setShowFilename( true );
4529 $ig->setShowFilename( false );
4531 if ( isset( $params['caption'] ) ) {
4532 $caption = $params['caption'];
4533 $caption = htmlspecialchars( $caption );
4534 $caption = $this->replaceInternalLinks( $caption );
4535 $ig->setCaptionHtml( $caption );
4537 if ( isset( $params['perrow'] ) ) {
4538 $ig->setPerRow( $params['perrow'] );
4540 if ( isset( $params['widths'] ) ) {
4541 $ig->setWidths( $params['widths'] );
4543 if ( isset( $params['heights'] ) ) {
4544 $ig->setHeights( $params['heights'] );
4547 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4549 $lines = StringUtils
::explode( "\n", $text );
4550 foreach ( $lines as $line ) {
4551 # match lines like these:
4552 # Image:someimage.jpg|This is some image
4554 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4556 if ( count( $matches ) == 0 ) {
4560 if ( strpos( $matches[0], '%' ) !== false ) {
4561 $matches[1] = rawurldecode( $matches[1] );
4563 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4565 if ( is_null( $nt ) ) {
4566 # Bogus title. Ignore these so we don't bomb out later.
4569 if ( isset( $matches[3] ) ) {
4570 $label = $matches[3];
4575 $html = $this->recursiveTagParse( trim( $label ) );
4577 $ig->add( $nt, $html );
4579 # Only add real images (bug #5586)
4580 if ( $nt->getNamespace() == NS_FILE
) {
4581 $this->mOutput
->addImage( $nt->getDBkey() );
4584 return $ig->toHTML();
4587 function getImageParams( $handler ) {
4589 $handlerClass = get_class( $handler );
4593 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4594 # Initialise static lists
4595 static $internalParamNames = array(
4596 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4597 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4598 'bottom', 'text-bottom' ),
4599 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4600 'upright', 'border', 'link', 'alt' ),
4602 static $internalParamMap;
4603 if ( !$internalParamMap ) {
4604 $internalParamMap = array();
4605 foreach ( $internalParamNames as $type => $names ) {
4606 foreach ( $names as $name ) {
4607 $magicName = str_replace( '-', '_', "img_$name" );
4608 $internalParamMap[$magicName] = array( $type, $name );
4613 # Add handler params
4614 $paramMap = $internalParamMap;
4616 $handlerParamMap = $handler->getParamMap();
4617 foreach ( $handlerParamMap as $magic => $paramName ) {
4618 $paramMap[$magic] = array( 'handler', $paramName );
4621 $this->mImageParams
[$handlerClass] = $paramMap;
4622 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4624 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4628 * Parse image options text and use it to make an image
4630 * @param $title Title
4631 * @param $options String
4632 * @param $holders LinkHolderArray
4634 function makeImage( $title, $options, $holders = false ) {
4635 # Check if the options text is of the form "options|alt text"
4637 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4638 # * left no resizing, just left align. label is used for alt= only
4639 # * right same, but right aligned
4640 # * none same, but not aligned
4641 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4642 # * center center the image
4643 # * frame Keep original image size, no magnify-button.
4644 # * framed Same as "frame"
4645 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4646 # * upright reduce width for upright images, rounded to full __0 px
4647 # * border draw a 1px border around the image
4648 # * alt Text for HTML alt attribute (defaults to empty)
4649 # * link Set the target of the image link. Can be external, interwiki, or local
4650 # vertical-align values (no % or length right now):
4660 $parts = StringUtils
::explode( "|", $options );
4661 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4663 # Give extensions a chance to select the file revision for us
4664 $skip = $time = $descQuery = false;
4665 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4668 return $sk->link( $title );
4672 $file = wfFindFile( $title, array( 'time' => $time ) );
4674 $handler = $file ?
$file->getHandler() : false;
4676 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4678 # Process the input parameters
4680 $params = array( 'frame' => array(), 'handler' => array(),
4681 'horizAlign' => array(), 'vertAlign' => array() );
4682 foreach ( $parts as $part ) {
4683 $part = trim( $part );
4684 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4686 if ( isset( $paramMap[$magicName] ) ) {
4687 list( $type, $paramName ) = $paramMap[$magicName];
4689 # Special case; width and height come in one variable together
4690 if ( $type === 'handler' && $paramName === 'width' ) {
4692 # (bug 13500) In both cases (width/height and width only),
4693 # permit trailing "px" for backward compatibility.
4694 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4695 $width = intval( $m[1] );
4696 $height = intval( $m[2] );
4697 if ( $handler->validateParam( 'width', $width ) ) {
4698 $params[$type]['width'] = $width;
4701 if ( $handler->validateParam( 'height', $height ) ) {
4702 $params[$type]['height'] = $height;
4705 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4706 $width = intval( $value );
4707 if ( $handler->validateParam( 'width', $width ) ) {
4708 $params[$type]['width'] = $width;
4711 } # else no validation -- bug 13436
4713 if ( $type === 'handler' ) {
4714 # Validate handler parameter
4715 $validated = $handler->validateParam( $paramName, $value );
4717 # Validate internal parameters
4718 switch( $paramName ) {
4721 # @todo Fixme: possibly check validity here for
4722 # manualthumb? downstream behavior seems odd with
4723 # missing manual thumbs.
4725 $value = $this->stripAltText( $value, $holders );
4728 $chars = self
::EXT_LINK_URL_CLASS
;
4729 $prots = $this->mUrlProtocols
;
4730 if ( $value === '' ) {
4731 $paramName = 'no-link';
4734 } elseif ( preg_match( "/^$prots/", $value ) ) {
4735 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4736 $paramName = 'link-url';
4737 $this->mOutput
->addExternalLink( $value );
4738 if ( $this->mOptions
->getExternalLinkTarget() ) {
4739 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4744 $linkTitle = Title
::newFromText( $value );
4746 $paramName = 'link-title';
4747 $value = $linkTitle;
4748 $this->mOutput
->addLink( $linkTitle );
4754 # Most other things appear to be empty or numeric...
4755 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4760 $params[$type][$paramName] = $value;
4764 if ( !$validated ) {
4769 # Process alignment parameters
4770 if ( $params['horizAlign'] ) {
4771 $params['frame']['align'] = key( $params['horizAlign'] );
4773 if ( $params['vertAlign'] ) {
4774 $params['frame']['valign'] = key( $params['vertAlign'] );
4777 $params['frame']['caption'] = $caption;
4779 # Will the image be presented in a frame, with the caption below?
4780 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4781 isset( $params['frame']['framed'] ) ||
4782 isset( $params['frame']['thumbnail'] ) ||
4783 isset( $params['frame']['manualthumb'] );
4785 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4786 # came to also set the caption, ordinary text after the image -- which
4787 # makes no sense, because that just repeats the text multiple times in
4788 # screen readers. It *also* came to set the title attribute.
4790 # Now that we have an alt attribute, we should not set the alt text to
4791 # equal the caption: that's worse than useless, it just repeats the
4792 # text. This is the framed/thumbnail case. If there's no caption, we
4793 # use the unnamed parameter for alt text as well, just for the time be-
4794 # ing, if the unnamed param is set and the alt param is not.
4796 # For the future, we need to figure out if we want to tweak this more,
4797 # e.g., introducing a title= parameter for the title; ignoring the un-
4798 # named parameter entirely for images without a caption; adding an ex-
4799 # plicit caption= parameter and preserving the old magic unnamed para-
4801 if ( $imageIsFramed ) { # Framed image
4802 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4803 # No caption or alt text, add the filename as the alt text so
4804 # that screen readers at least get some description of the image
4805 $params['frame']['alt'] = $title->getText();
4807 # Do not set $params['frame']['title'] because tooltips don't make sense
4809 } else { # Inline image
4810 if ( !isset( $params['frame']['alt'] ) ) {
4811 # No alt text, use the "caption" for the alt text
4812 if ( $caption !== '') {
4813 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4815 # No caption, fall back to using the filename for the
4817 $params['frame']['alt'] = $title->getText();
4820 # Use the "caption" for the tooltip text
4821 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4824 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4826 # Linker does the rest
4827 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4829 # Give the handler a chance to modify the parser object
4831 $handler->parserTransformHook( $this, $file );
4837 protected function stripAltText( $caption, $holders ) {
4838 # Strip bad stuff out of the title (tooltip). We can't just use
4839 # replaceLinkHoldersText() here, because if this function is called
4840 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4842 $tooltip = $holders->replaceText( $caption );
4844 $tooltip = $this->replaceLinkHoldersText( $caption );
4847 # make sure there are no placeholders in thumbnail attributes
4848 # that are later expanded to html- so expand them now and
4850 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4851 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4857 * Set a flag in the output object indicating that the content is dynamic and
4858 * shouldn't be cached.
4860 function disableCache() {
4861 wfDebug( "Parser output marked as uncacheable.\n" );
4862 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4863 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4867 * Callback from the Sanitizer for expanding items found in HTML attribute
4868 * values, so they can be safely tested and escaped.
4870 * @param $text String
4871 * @param $frame PPFrame
4875 function attributeStripCallback( &$text, $frame = false ) {
4876 $text = $this->replaceVariables( $text, $frame );
4877 $text = $this->mStripState
->unstripBoth( $text );
4884 function getTags() {
4885 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4889 * Break wikitext input into sections, and either pull or replace
4890 * some particular section's text.
4892 * External callers should use the getSection and replaceSection methods.
4894 * @param $text String: Page wikitext
4895 * @param $section String: a section identifier string of the form:
4896 * <flag1> - <flag2> - ... - <section number>
4898 * Currently the only recognised flag is "T", which means the target section number
4899 * was derived during a template inclusion parse, in other words this is a template
4900 * section edit link. If no flags are given, it was an ordinary section edit link.
4901 * This flag is required to avoid a section numbering mismatch when a section is
4902 * enclosed by <includeonly> (bug 6563).
4904 * The section number 0 pulls the text before the first heading; other numbers will
4905 * pull the given section along with its lower-level subsections. If the section is
4906 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4908 * @param $mode String: one of "get" or "replace"
4909 * @param $newText String: replacement text for section data.
4910 * @return String: for "get", the extracted section text.
4911 * for "replace", the whole page with the section replaced.
4913 private function extractSections( $text, $section, $mode, $newText='' ) {
4915 $this->mOptions
= new ParserOptions
;
4916 $this->clearState();
4917 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4918 $this->setOutputType( self
::OT_PLAIN
);
4920 $frame = $this->getPreprocessor()->newFrame();
4922 # Process section extraction flags
4924 $sectionParts = explode( '-', $section );
4925 $sectionIndex = array_pop( $sectionParts );
4926 foreach ( $sectionParts as $part ) {
4927 if ( $part === 'T' ) {
4928 $flags |
= self
::PTD_FOR_INCLUSION
;
4931 # Preprocess the text
4932 $root = $this->preprocessToDom( $text, $flags );
4934 # <h> nodes indicate section breaks
4935 # They can only occur at the top level, so we can find them by iterating the root's children
4936 $node = $root->getFirstChild();
4938 # Find the target section
4939 if ( $sectionIndex == 0 ) {
4940 # Section zero doesn't nest, level=big
4941 $targetLevel = 1000;
4944 if ( $node->getName() === 'h' ) {
4945 $bits = $node->splitHeading();
4946 if ( $bits['i'] == $sectionIndex ) {
4947 $targetLevel = $bits['level'];
4951 if ( $mode === 'replace' ) {
4952 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4954 $node = $node->getNextSibling();
4960 if ( $mode === 'get' ) {
4967 # Find the end of the section, including nested sections
4969 if ( $node->getName() === 'h' ) {
4970 $bits = $node->splitHeading();
4971 $curLevel = $bits['level'];
4972 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4976 if ( $mode === 'get' ) {
4977 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4979 $node = $node->getNextSibling();
4982 # Write out the remainder (in replace mode only)
4983 if ( $mode === 'replace' ) {
4984 # Output the replacement text
4985 # Add two newlines on -- trailing whitespace in $newText is conventionally
4986 # stripped by the editor, so we need both newlines to restore the paragraph gap
4987 # Only add trailing whitespace if there is newText
4988 if ( $newText != "" ) {
4989 $outText .= $newText . "\n\n";
4993 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4994 $node = $node->getNextSibling();
4998 if ( is_string( $outText ) ) {
4999 # Re-insert stripped tags
5000 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5007 * This function returns the text of a section, specified by a number ($section).
5008 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5009 * the first section before any such heading (section 0).
5011 * If a section contains subsections, these are also returned.
5013 * @param $text String: text to look in
5014 * @param $section String: section identifier
5015 * @param $deftext String: default to return if section is not found
5016 * @return string text of the requested section
5018 public function getSection( $text, $section, $deftext='' ) {
5019 return $this->extractSections( $text, $section, "get", $deftext );
5023 * This function returns $oldtext after the content of the section
5024 * specified by $section has been replaced with $text.
5026 * @param $text String: former text of the article
5027 * @param $section Numeric: section identifier
5028 * @param $text String: replacing text
5029 * #return String: modified text
5031 public function replaceSection( $oldtext, $section, $text ) {
5032 return $this->extractSections( $oldtext, $section, "replace", $text );
5036 * Get the ID of the revision we are parsing
5038 * @return Mixed: integer or null
5040 function getRevisionId() {
5041 return $this->mRevisionId
;
5045 * Get the revision object for $this->mRevisionId
5047 * @return either a Revision object or null
5049 protected function getRevisionObject() {
5050 if ( !is_null( $this->mRevisionObject
) ) {
5051 return $this->mRevisionObject
;
5053 if ( is_null( $this->mRevisionId
) ) {
5057 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5058 return $this->mRevisionObject
;
5062 * Get the timestamp associated with the current revision, adjusted for
5063 * the default server-local timestamp
5065 function getRevisionTimestamp() {
5066 if ( is_null( $this->mRevisionTimestamp
) ) {
5067 wfProfileIn( __METHOD__
);
5069 $revObject = $this->getRevisionObject();
5070 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5072 if( $timestamp !== false ) {
5075 # The cryptic '' timezone parameter tells to use the site-default
5076 # timezone offset instead of the user settings.
5078 # Since this value will be saved into the parser cache, served
5079 # to other users, and potentially even used inside links and such,
5080 # it needs to be consistent for all visitors.
5081 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5084 wfProfileOut( __METHOD__
);
5086 return $this->mRevisionTimestamp
;
5090 * Get the name of the user that edited the last revision
5092 * @return String: user name
5094 function getRevisionUser() {
5095 if( is_null( $this->mRevisionUser
) ) {
5096 $revObject = $this->getRevisionObject();
5098 # if this template is subst: the revision id will be blank,
5099 # so just use the current user's name
5101 $this->mRevisionUser
= $revObject->getUserText();
5102 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5103 $this->mRevisionUser
= $this->getUser()->getName();
5106 return $this->mRevisionUser
;
5110 * Mutator for $mDefaultSort
5112 * @param $sort New value
5114 public function setDefaultSort( $sort ) {
5115 $this->mDefaultSort
= $sort;
5116 $this->mOutput
->setProperty( 'defaultsort', $sort );
5120 * Accessor for $mDefaultSort
5121 * Will use the title/prefixed title if none is set
5125 public function getDefaultSort() {
5126 if ( $this->mDefaultSort
!== false ) {
5127 return $this->mDefaultSort
;
5129 return $this->mTitle
->getCategorySortkey();
5134 * Accessor for $mDefaultSort
5135 * Unlike getDefaultSort(), will return false if none is set
5137 * @return string or false
5139 public function getCustomDefaultSort() {
5140 return $this->mDefaultSort
;
5144 * Try to guess the section anchor name based on a wikitext fragment
5145 * presumably extracted from a heading, for example "Header" from
5148 public function guessSectionNameFromWikiText( $text ) {
5149 # Strip out wikitext links(they break the anchor)
5150 $text = $this->stripSectionName( $text );
5151 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5152 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5156 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5157 * instead. For use in redirects, since IE6 interprets Redirect: headers
5158 * as something other than UTF-8 (apparently?), resulting in breakage.
5160 * @param $text String: The section name
5161 * @return string An anchor
5163 public function guessLegacySectionNameFromWikiText( $text ) {
5164 # Strip out wikitext links(they break the anchor)
5165 $text = $this->stripSectionName( $text );
5166 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5167 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5171 * Strips a text string of wikitext for use in a section anchor
5173 * Accepts a text string and then removes all wikitext from the
5174 * string and leaves only the resultant text (i.e. the result of
5175 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5176 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5177 * to create valid section anchors by mimicing the output of the
5178 * parser when headings are parsed.
5180 * @param $text String: text string to be stripped of wikitext
5181 * for use in a Section anchor
5182 * @return Filtered text string
5184 public function stripSectionName( $text ) {
5185 # Strip internal link markup
5186 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5187 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5189 # Strip external link markup (FIXME: Not Tolerant to blank link text
5190 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5191 # on how many empty links there are on the page - need to figure that out.
5192 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5194 # Parse wikitext quotes (italics & bold)
5195 $text = $this->doQuotes( $text );
5198 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5203 * strip/replaceVariables/unstrip for preprocessor regression testing
5205 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5206 $this->mOptions
= $options;
5207 $this->clearState();
5208 if ( !$title instanceof Title
) {
5209 $title = Title
::newFromText( $title );
5211 $this->mTitle
= $title;
5212 $this->setOutputType( $outputType );
5213 $text = $this->replaceVariables( $text );
5214 $text = $this->mStripState
->unstripBoth( $text );
5215 $text = Sanitizer
::removeHTMLtags( $text );
5219 function testPst( $text, $title, $options ) {
5221 if ( !$title instanceof Title
) {
5222 $title = Title
::newFromText( $title );
5224 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5227 function testPreprocess( $text, $title, $options ) {
5228 if ( !$title instanceof Title
) {
5229 $title = Title
::newFromText( $title );
5231 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5234 function markerSkipCallback( $s, $callback ) {
5237 while ( $i < strlen( $s ) ) {
5238 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5239 if ( $markerStart === false ) {
5240 $out .= call_user_func( $callback, substr( $s, $i ) );
5243 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5244 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5245 if ( $markerEnd === false ) {
5246 $out .= substr( $s, $markerStart );
5249 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5250 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5258 function serialiseHalfParsedText( $text ) {
5260 $data['text'] = $text;
5262 # First, find all strip markers, and store their
5264 $stripState = new StripState
;
5266 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5267 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5269 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5270 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5272 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5273 $replaceArray = $stripState->general
;
5274 $stripText = $this->mStripState
->general
->data
[$marker];
5275 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5276 $replaceArray = $stripState->nowiki
;
5277 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5279 throw new MWException( "Hanging strip marker: '$marker'." );
5282 $replaceArray->setPair( $marker, $stripText );
5285 $data['stripstate'] = $stripState;
5287 # Now, find all of our links, and store THEIR
5288 # data in an array! :)
5289 $links = array( 'internal' => array(), 'interwiki' => array() );
5293 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5294 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5297 if ( empty( $links['internal'][$ns] ) ) {
5298 $links['internal'][$ns] = array();
5301 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5302 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5303 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5309 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5310 $data = substr( $text, $start_pos );
5311 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5312 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5313 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5316 $data['linkholder'] = $links;
5323 * @param $data Array
5324 * @param $intPrefix String unique identifying prefix
5327 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5328 if ( !$intPrefix ) {
5329 $intPrefix = self
::getRandomString();
5332 # First, extract the strip state.
5333 $stripState = $data['stripstate'];
5334 $this->mStripState
->general
->merge( $stripState->general
);
5335 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5337 # Now, extract the text, and renumber links
5338 $text = $data['text'];
5339 $links = $data['linkholder'];
5342 foreach ( $links['internal'] as $ns => $nsLinks ) {
5343 foreach ( $nsLinks as $key => $entry ) {
5344 $newKey = $intPrefix . '-' . $key;
5345 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5347 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5352 foreach ( $links['interwiki'] as $key => $entry ) {
5353 $newKey = "$intPrefix-$key";
5354 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5356 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5359 # Should be good to go.
5365 * @todo document, briefly.
5369 var $general, $nowiki;
5371 function __construct() {
5372 $this->general
= new ReplacementArray
;
5373 $this->nowiki
= new ReplacementArray
;
5376 function unstripGeneral( $text ) {
5377 wfProfileIn( __METHOD__
);
5380 $text = $this->general
->replace( $text );
5381 } while ( $text !== $oldText );
5382 wfProfileOut( __METHOD__
);
5386 function unstripNoWiki( $text ) {
5387 wfProfileIn( __METHOD__
);
5390 $text = $this->nowiki
->replace( $text );
5391 } while ( $text !== $oldText );
5392 wfProfileOut( __METHOD__
);
5396 function unstripBoth( $text ) {
5397 wfProfileIn( __METHOD__
);
5400 $text = $this->general
->replace( $text );
5401 $text = $this->nowiki
->replace( $text );
5402 } while ( $text !== $oldText );
5403 wfProfileOut( __METHOD__
);
5409 * @todo document, briefly.
5412 class OnlyIncludeReplacer
{
5415 function replace( $matches ) {
5416 if ( substr( $matches[1], -1 ) === "\n" ) {
5417 $this->output
.= substr( $matches[1], 0, -1 );
5419 $this->output
.= $matches[1];