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 foreach ( $lines as $outLine ) {
829 $line = trim( $outLine );
831 if ( $line === '' ) { # empty line, go to next line
832 $out .= $outLine."\n";
836 $first_character = $line[0];
839 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
840 # First check if we are starting a new table
841 $indent_level = strlen( $matches[1] );
843 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
844 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
846 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
847 array_push( $td_history , false );
848 array_push( $last_tag_history , '' );
849 array_push( $tr_history , false );
850 array_push( $tr_attributes , '' );
851 array_push( $has_opened_tr , false );
852 } elseif ( count( $td_history ) == 0 ) {
853 # Don't do any of the following
854 $out .= $outLine."\n";
856 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
857 # We are ending a table
858 $line = '</table>' . substr( $line , 2 );
859 $last_tag = array_pop( $last_tag_history );
861 if ( !array_pop( $has_opened_tr ) ) {
862 $line = "<tr><td></td></tr>{$line}";
865 if ( array_pop( $tr_history ) ) {
866 $line = "</tr>{$line}";
869 if ( array_pop( $td_history ) ) {
870 $line = "</{$last_tag}>{$line}";
872 array_pop( $tr_attributes );
873 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
874 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
875 # Now we have a table row
876 $line = preg_replace( '#^\|-+#', '', $line );
878 # Whats after the tag is now only attributes
879 $attributes = $this->mStripState
->unstripBoth( $line );
880 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
881 array_pop( $tr_attributes );
882 array_push( $tr_attributes, $attributes );
885 $last_tag = array_pop( $last_tag_history );
886 array_pop( $has_opened_tr );
887 array_push( $has_opened_tr , true );
889 if ( array_pop( $tr_history ) ) {
893 if ( array_pop( $td_history ) ) {
894 $line = "</{$last_tag}>{$line}";
898 array_push( $tr_history , false );
899 array_push( $td_history , false );
900 array_push( $last_tag_history , '' );
901 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
902 # This might be cell elements, td, th or captions
903 if ( substr( $line , 0 , 2 ) === '|+' ) {
904 $first_character = '+';
905 $line = substr( $line , 1 );
908 $line = substr( $line , 1 );
910 if ( $first_character === '!' ) {
911 $line = str_replace( '!!' , '||' , $line );
914 # Split up multiple cells on the same line.
915 # FIXME : This can result in improper nesting of tags processed
916 # by earlier parser steps, but should avoid splitting up eg
917 # attribute values containing literal "||".
918 $cells = StringUtils
::explodeMarkup( '||' , $line );
922 # Loop through each table cell
923 foreach ( $cells as $cell ) {
925 if ( $first_character !== '+' ) {
926 $tr_after = array_pop( $tr_attributes );
927 if ( !array_pop( $tr_history ) ) {
928 $previous = "<tr{$tr_after}>\n";
930 array_push( $tr_history , true );
931 array_push( $tr_attributes , '' );
932 array_pop( $has_opened_tr );
933 array_push( $has_opened_tr , true );
936 $last_tag = array_pop( $last_tag_history );
938 if ( array_pop( $td_history ) ) {
939 $previous = "</{$last_tag}>\n{$previous}";
942 if ( $first_character === '|' ) {
944 } elseif ( $first_character === '!' ) {
946 } elseif ( $first_character === '+' ) {
947 $last_tag = 'caption';
952 array_push( $last_tag_history , $last_tag );
954 # A cell could contain both parameters and data
955 $cell_data = explode( '|' , $cell , 2 );
957 # Bug 553: Note that a '|' inside an invalid link should not
958 # be mistaken as delimiting cell parameters
959 if ( strpos( $cell_data[0], '[[' ) !== false ) {
960 $cell = "{$previous}<{$last_tag}>{$cell}";
961 } elseif ( count( $cell_data ) == 1 ) {
962 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
964 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
965 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
966 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
970 array_push( $td_history , true );
973 $out .= $outLine . "\n";
976 # Closing open td, tr && table
977 while ( count( $td_history ) > 0 ) {
978 if ( array_pop( $td_history ) ) {
981 if ( array_pop( $tr_history ) ) {
984 if ( !array_pop( $has_opened_tr ) ) {
985 $out .= "<tr><td></td></tr>\n" ;
988 $out .= "</table>\n";
991 # Remove trailing line-ending (b/c)
992 if ( substr( $out, -1 ) === "\n" ) {
993 $out = substr( $out, 0, -1 );
996 # special case: don't return empty table
997 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1001 wfProfileOut( __METHOD__
);
1007 * Helper function for parse() that transforms wiki markup into
1008 * HTML. Only called for $mOutputType == self::OT_HTML.
1012 function internalParse( $text, $isMain = true, $frame=false ) {
1013 wfProfileIn( __METHOD__
);
1017 # Hook to suspend the parser in this state
1018 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1019 wfProfileOut( __METHOD__
);
1023 # if $frame is provided, then use $frame for replacing any variables
1025 # use frame depth to infer how include/noinclude tags should be handled
1026 # depth=0 means this is the top-level document; otherwise it's an included document
1027 if ( !$frame->depth
) {
1030 $flag = Parser
::PTD_FOR_INCLUSION
;
1032 $dom = $this->preprocessToDom( $text, $flag );
1033 $text = $frame->expand( $dom );
1035 # if $frame is not provided, then use old-style replaceVariables
1036 $text = $this->replaceVariables( $text );
1039 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1040 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1042 # Tables need to come after variable replacement for things to work
1043 # properly; putting them before other transformations should keep
1044 # exciting things like link expansions from showing up in surprising
1046 $text = $this->doTableStuff( $text );
1048 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1050 $text = $this->doDoubleUnderscore( $text );
1052 $text = $this->doHeadings( $text );
1053 if ( $this->mOptions
->getUseDynamicDates() ) {
1054 $df = DateFormatter
::getInstance();
1055 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1057 $text = $this->replaceInternalLinks( $text );
1058 $text = $this->doAllQuotes( $text );
1059 $text = $this->replaceExternalLinks( $text );
1061 # replaceInternalLinks may sometimes leave behind
1062 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1063 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1065 $text = $this->doMagicLinks( $text );
1066 $text = $this->formatHeadings( $text, $origText, $isMain );
1068 wfProfileOut( __METHOD__
);
1073 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1074 * magic external links.
1079 function doMagicLinks( $text ) {
1080 wfProfileIn( __METHOD__
);
1081 $prots = $this->mUrlProtocols
;
1082 $urlChar = self
::EXT_LINK_URL_CLASS
;
1083 $text = preg_replace_callback(
1085 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1086 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1087 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1088 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1089 ISBN\s+(\b # m[5]: ISBN, capture number
1090 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1091 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1092 [0-9Xx] # check digit
1094 )!x', array( &$this, 'magicLinkCallback' ), $text );
1095 wfProfileOut( __METHOD__
);
1099 function magicLinkCallback( $m ) {
1100 if ( isset( $m[1] ) && $m[1] !== '' ) {
1103 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1106 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1107 # Free external link
1108 return $this->makeFreeExternalLink( $m[0] );
1109 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1111 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1114 $CssClass = 'mw-magiclink-rfc';
1116 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1118 $urlmsg = 'pubmedurl';
1119 $CssClass = 'mw-magiclink-pmid';
1122 throw new MWException( __METHOD__
.': unrecognised match type "' .
1123 substr( $m[0], 0, 20 ) . '"' );
1125 $url = wfMsgForContent( $urlmsg, $id);
1126 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1127 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1128 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1129 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1132 $num = strtr( $isbn, array(
1137 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1139 $titleObj->escapeLocalUrl() .
1140 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1147 * Make a free external link, given a user-supplied URL
1151 function makeFreeExternalLink( $url ) {
1153 wfProfileIn( __METHOD__
);
1155 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1158 # The characters '<' and '>' (which were escaped by
1159 # removeHTMLtags()) should not be included in
1160 # URLs, per RFC 2396.
1162 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1163 $trail = substr( $url, $m2[0][1] ) . $trail;
1164 $url = substr( $url, 0, $m2[0][1] );
1167 # Move trailing punctuation to $trail
1169 # If there is no left bracket, then consider right brackets fair game too
1170 if ( strpos( $url, '(' ) === false ) {
1174 $numSepChars = strspn( strrev( $url ), $sep );
1175 if ( $numSepChars ) {
1176 $trail = substr( $url, -$numSepChars ) . $trail;
1177 $url = substr( $url, 0, -$numSepChars );
1180 $url = Sanitizer
::cleanUrl( $url );
1182 # Is this an external image?
1183 $text = $this->maybeMakeExternalImage( $url );
1184 if ( $text === false ) {
1185 # Not an image, make a link
1186 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1187 $this->getExternalLinkAttribs( $url ) );
1188 # Register it in the output object...
1189 # Replace unnecessary URL escape codes with their equivalent characters
1190 $pasteurized = self
::replaceUnusualEscapes( $url );
1191 $this->mOutput
->addExternalLink( $pasteurized );
1193 wfProfileOut( __METHOD__
);
1194 return $text . $trail;
1199 * Parse headers and return html
1203 function doHeadings( $text ) {
1204 wfProfileIn( __METHOD__
);
1205 for ( $i = 6; $i >= 1; --$i ) {
1206 $h = str_repeat( '=', $i );
1207 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1208 "<h$i>\\1</h$i>", $text );
1210 wfProfileOut( __METHOD__
);
1215 * Replace single quotes with HTML markup
1217 * @return string the altered text
1219 function doAllQuotes( $text ) {
1220 wfProfileIn( __METHOD__
);
1222 $lines = StringUtils
::explode( "\n", $text );
1223 foreach ( $lines as $line ) {
1224 $outtext .= $this->doQuotes( $line ) . "\n";
1226 $outtext = substr( $outtext, 0,-1 );
1227 wfProfileOut( __METHOD__
);
1232 * Helper function for doAllQuotes()
1234 public function doQuotes( $text ) {
1235 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1236 if ( count( $arr ) == 1 ) {
1239 # First, do some preliminary work. This may shift some apostrophes from
1240 # being mark-up to being text. It also counts the number of occurrences
1241 # of bold and italics mark-ups.
1244 for ( $i = 0; $i < count( $arr ); $i++
) {
1245 if ( ( $i %
2 ) == 1 ) {
1246 # If there are ever four apostrophes, assume the first is supposed to
1247 # be text, and the remaining three constitute mark-up for bold text.
1248 if ( strlen( $arr[$i] ) == 4 ) {
1251 } elseif ( strlen( $arr[$i] ) > 5 ) {
1252 # If there are more than 5 apostrophes in a row, assume they're all
1253 # text except for the last 5.
1254 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1257 # Count the number of occurrences of bold and italics mark-ups.
1258 # We are not counting sequences of five apostrophes.
1259 if ( strlen( $arr[$i] ) == 2 ) {
1261 } elseif ( strlen( $arr[$i] ) == 3 ) {
1263 } elseif ( strlen( $arr[$i] ) == 5 ) {
1270 # If there is an odd number of both bold and italics, it is likely
1271 # that one of the bold ones was meant to be an apostrophe followed
1272 # by italics. Which one we cannot know for certain, but it is more
1273 # likely to be one that has a single-letter word before it.
1274 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1276 $firstsingleletterword = -1;
1277 $firstmultiletterword = -1;
1279 foreach ( $arr as $r ) {
1280 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1281 $x1 = substr( $arr[$i-1], -1 );
1282 $x2 = substr( $arr[$i-1], -2, 1 );
1283 if ( $x1 === ' ' ) {
1284 if ( $firstspace == -1 ) {
1287 } elseif ( $x2 === ' ') {
1288 if ( $firstsingleletterword == -1 ) {
1289 $firstsingleletterword = $i;
1292 if ( $firstmultiletterword == -1 ) {
1293 $firstmultiletterword = $i;
1300 # If there is a single-letter word, use it!
1301 if ( $firstsingleletterword > -1 ) {
1302 $arr[$firstsingleletterword] = "''";
1303 $arr[$firstsingleletterword-1] .= "'";
1304 } elseif ( $firstmultiletterword > -1 ) {
1305 # If not, but there's a multi-letter word, use that one.
1306 $arr[$firstmultiletterword] = "''";
1307 $arr[$firstmultiletterword-1] .= "'";
1308 } elseif ( $firstspace > -1 ) {
1309 # ... otherwise use the first one that has neither.
1310 # (notice that it is possible for all three to be -1 if, for example,
1311 # there is only one pentuple-apostrophe in the line)
1312 $arr[$firstspace] = "''";
1313 $arr[$firstspace-1] .= "'";
1317 # Now let's actually convert our apostrophic mush to HTML!
1322 foreach ( $arr as $r ) {
1323 if ( ( $i %
2 ) == 0 ) {
1324 if ( $state === 'both' ) {
1330 if ( strlen( $r ) == 2 ) {
1331 if ( $state === 'i' ) {
1332 $output .= '</i>'; $state = '';
1333 } elseif ( $state === 'bi' ) {
1334 $output .= '</i>'; $state = 'b';
1335 } elseif ( $state === 'ib' ) {
1336 $output .= '</b></i><b>'; $state = 'b';
1337 } elseif ( $state === 'both' ) {
1338 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1339 } else { # $state can be 'b' or ''
1340 $output .= '<i>'; $state .= 'i';
1342 } elseif ( strlen( $r ) == 3 ) {
1343 if ( $state === 'b' ) {
1344 $output .= '</b>'; $state = '';
1345 } elseif ( $state === 'bi' ) {
1346 $output .= '</i></b><i>'; $state = 'i';
1347 } elseif ( $state === 'ib' ) {
1348 $output .= '</b>'; $state = 'i';
1349 } elseif ( $state === 'both' ) {
1350 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1351 } else { # $state can be 'i' or ''
1352 $output .= '<b>'; $state .= 'b';
1354 } elseif ( strlen( $r ) == 5 ) {
1355 if ( $state === 'b' ) {
1356 $output .= '</b><i>'; $state = 'i';
1357 } elseif ( $state === 'i' ) {
1358 $output .= '</i><b>'; $state = 'b';
1359 } elseif ( $state === 'bi' ) {
1360 $output .= '</i></b>'; $state = '';
1361 } elseif ( $state === 'ib' ) {
1362 $output .= '</b></i>'; $state = '';
1363 } elseif ( $state === 'both' ) {
1364 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1365 } else { # ($state == '')
1366 $buffer = ''; $state = 'both';
1372 # Now close all remaining tags. Notice that the order is important.
1373 if ( $state === 'b' ||
$state === 'ib' ) {
1376 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1379 if ( $state === 'bi' ) {
1382 # There might be lonely ''''', so make sure we have a buffer
1383 if ( $state === 'both' && $buffer ) {
1384 $output .= '<b><i>'.$buffer.'</i></b>';
1391 * Replace external links (REL)
1393 * Note: this is all very hackish and the order of execution matters a lot.
1394 * Make sure to run maintenance/parserTests.php if you change this code.
1398 function replaceExternalLinks( $text ) {
1400 wfProfileIn( __METHOD__
);
1402 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1404 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1405 $s = array_shift( $bits );
1408 while ( $i<count( $bits ) ) {
1410 $protocol = $bits[$i++
];
1411 $text = $bits[$i++
];
1412 $trail = $bits[$i++
];
1414 # The characters '<' and '>' (which were escaped by
1415 # removeHTMLtags()) should not be included in
1416 # URLs, per RFC 2396.
1418 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1419 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1420 $url = substr( $url, 0, $m2[0][1] );
1423 # If the link text is an image URL, replace it with an <img> tag
1424 # This happened by accident in the original parser, but some people used it extensively
1425 $img = $this->maybeMakeExternalImage( $text );
1426 if ( $img !== false ) {
1432 # Set linktype for CSS - if URL==text, link is essentially free
1433 $linktype = ( $text === $url ) ?
'free' : 'text';
1435 # No link text, e.g. [http://domain.tld/some.link]
1436 if ( $text == '' ) {
1437 # Autonumber if allowed. See bug #5918
1438 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1439 $langObj = $this->getFunctionLang();
1440 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1441 $linktype = 'autonumber';
1443 # Otherwise just use the URL
1444 $text = htmlspecialchars( $url );
1448 # Have link text, e.g. [http://domain.tld/some.link text]s
1450 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1453 $text = $wgContLang->markNoConversion( $text );
1455 $url = Sanitizer
::cleanUrl( $url );
1457 # Use the encoded URL
1458 # This means that users can paste URLs directly into the text
1459 # Funny characters like ö aren't valid in URLs anyway
1460 # This was changed in August 2004
1461 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1462 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1464 # Register link in the output object.
1465 # Replace unnecessary URL escape codes with the referenced character
1466 # This prevents spammers from hiding links from the filters
1467 $pasteurized = self
::replaceUnusualEscapes( $url );
1468 $this->mOutput
->addExternalLink( $pasteurized );
1471 wfProfileOut( __METHOD__
);
1476 * Get an associative array of additional HTML attributes appropriate for a
1477 * particular external link. This currently may include rel => nofollow
1478 * (depending on configuration, namespace, and the URL's domain) and/or a
1479 * target attribute (depending on configuration).
1481 * @param $url String: optional URL, to extract the domain from for rel =>
1482 * nofollow if appropriate
1483 * @return Array: associative array of HTML attributes
1485 function getExternalLinkAttribs( $url = false ) {
1487 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1488 $ns = $this->mTitle
->getNamespace();
1489 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1490 $attribs['rel'] = 'nofollow';
1492 global $wgNoFollowDomainExceptions;
1493 if ( $wgNoFollowDomainExceptions ) {
1494 $bits = wfParseUrl( $url );
1495 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1496 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1497 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1498 unset( $attribs['rel'] );
1505 if ( $this->mOptions
->getExternalLinkTarget() ) {
1506 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1513 * Replace unusual URL escape codes with their equivalent characters
1515 * @param $url String
1518 * @todo This can merge genuinely required bits in the path or query string,
1519 * breaking legit URLs. A proper fix would treat the various parts of
1520 * the URL differently; as a workaround, just use the output for
1521 * statistical records, not for actual linking/output.
1523 static function replaceUnusualEscapes( $url ) {
1524 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1525 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1529 * Callback function used in replaceUnusualEscapes().
1530 * Replaces unusual URL escape codes with their equivalent character
1532 private static function replaceUnusualEscapesCallback( $matches ) {
1533 $char = urldecode( $matches[0] );
1534 $ord = ord( $char );
1535 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1536 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1537 # No, shouldn't be escaped
1540 # Yes, leave it escaped
1546 * make an image if it's allowed, either through the global
1547 * option, through the exception, or through the on-wiki whitelist
1550 function maybeMakeExternalImage( $url ) {
1551 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1552 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1553 $imagesexception = !empty( $imagesfrom );
1555 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1556 if ( $imagesexception && is_array( $imagesfrom ) ) {
1557 $imagematch = false;
1558 foreach ( $imagesfrom as $match ) {
1559 if ( strpos( $url, $match ) === 0 ) {
1564 } elseif ( $imagesexception ) {
1565 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1567 $imagematch = false;
1569 if ( $this->mOptions
->getAllowExternalImages()
1570 ||
( $imagesexception && $imagematch ) ) {
1571 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1573 $text = $sk->makeExternalImage( $url );
1576 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1577 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1578 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1579 foreach ( $whitelist as $entry ) {
1580 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1581 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1584 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1585 # Image matches a whitelist entry
1586 $text = $sk->makeExternalImage( $url );
1595 * Process [[ ]] wikilinks
1596 * @return String: processed text
1600 function replaceInternalLinks( $s ) {
1601 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1606 * Process [[ ]] wikilinks (RIL)
1607 * @return LinkHolderArray
1611 function replaceInternalLinks2( &$s ) {
1614 wfProfileIn( __METHOD__
);
1616 wfProfileIn( __METHOD__
.'-setup' );
1617 static $tc = FALSE, $e1, $e1_img;
1618 # the % is needed to support urlencoded titles as well
1620 $tc = Title
::legalChars() . '#%';
1621 # Match a link having the form [[namespace:link|alternate]]trail
1622 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1623 # Match cases where there is no "]]", which might still be images
1624 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1627 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1628 $holders = new LinkHolderArray( $this );
1630 # split the entire text string on occurences of [[
1631 $a = StringUtils
::explode( '[[', ' ' . $s );
1632 # get the first element (all text up to first [[), and remove the space we added
1635 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1636 $s = substr( $s, 1 );
1638 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1640 if ( $useLinkPrefixExtension ) {
1641 # Match the end of a line for a word that's not followed by whitespace,
1642 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1643 $e2 = wfMsgForContent( 'linkprefix' );
1646 if ( is_null( $this->mTitle
) ) {
1647 wfProfileOut( __METHOD__
.'-setup' );
1648 wfProfileOut( __METHOD__
);
1649 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1651 $nottalk = !$this->mTitle
->isTalkPage();
1653 if ( $useLinkPrefixExtension ) {
1655 if ( preg_match( $e2, $s, $m ) ) {
1656 $first_prefix = $m[2];
1658 $first_prefix = false;
1664 if ( $wgContLang->hasVariants() ) {
1665 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1667 $selflink = array( $this->mTitle
->getPrefixedText() );
1669 $useSubpages = $this->areSubpagesAllowed();
1670 wfProfileOut( __METHOD__
.'-setup' );
1672 # Loop for each link
1673 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1674 # Check for excessive memory usage
1675 if ( $holders->isBig() ) {
1677 # Do the existence check, replace the link holders and clear the array
1678 $holders->replace( $s );
1682 if ( $useLinkPrefixExtension ) {
1683 wfProfileIn( __METHOD__
.'-prefixhandling' );
1684 if ( preg_match( $e2, $s, $m ) ) {
1691 if ( $first_prefix ) {
1692 $prefix = $first_prefix;
1693 $first_prefix = false;
1695 wfProfileOut( __METHOD__
.'-prefixhandling' );
1698 $might_be_img = false;
1700 wfProfileIn( __METHOD__
."-e1" );
1701 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1703 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1704 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1705 # the real problem is with the $e1 regex
1708 # Still some problems for cases where the ] is meant to be outside punctuation,
1709 # and no image is in sight. See bug 2095.
1711 if ( $text !== '' &&
1712 substr( $m[3], 0, 1 ) === ']' &&
1713 strpos( $text, '[' ) !== false
1716 $text .= ']'; # so that replaceExternalLinks($text) works later
1717 $m[3] = substr( $m[3], 1 );
1719 # fix up urlencoded title texts
1720 if ( strpos( $m[1], '%' ) !== false ) {
1721 # Should anchors '#' also be rejected?
1722 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1725 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1726 $might_be_img = true;
1728 if ( strpos( $m[1], '%' ) !== false ) {
1729 $m[1] = rawurldecode( $m[1] );
1732 } else { # Invalid form; output directly
1733 $s .= $prefix . '[[' . $line ;
1734 wfProfileOut( __METHOD__
."-e1" );
1737 wfProfileOut( __METHOD__
."-e1" );
1738 wfProfileIn( __METHOD__
."-misc" );
1740 # Don't allow internal links to pages containing
1741 # PROTO: where PROTO is a valid URL protocol; these
1742 # should be external links.
1743 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1744 $s .= $prefix . '[[' . $line ;
1745 wfProfileOut( __METHOD__
."-misc" );
1749 # Make subpage if necessary
1750 if ( $useSubpages ) {
1751 $link = $this->maybeDoSubpageLink( $m[1], $text );
1756 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1758 # Strip off leading ':'
1759 $link = substr( $link, 1 );
1762 wfProfileOut( __METHOD__
."-misc" );
1763 wfProfileIn( __METHOD__
."-title" );
1764 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1765 if ( $nt === null ) {
1766 $s .= $prefix . '[[' . $line;
1767 wfProfileOut( __METHOD__
."-title" );
1771 $ns = $nt->getNamespace();
1772 $iw = $nt->getInterWiki();
1773 wfProfileOut( __METHOD__
."-title" );
1775 if ( $might_be_img ) { # if this is actually an invalid link
1776 wfProfileIn( __METHOD__
."-might_be_img" );
1777 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1780 # look at the next 'line' to see if we can close it there
1782 $next_line = $a->current();
1783 if ( $next_line === false ||
$next_line === null ) {
1786 $m = explode( ']]', $next_line, 3 );
1787 if ( count( $m ) == 3 ) {
1788 # the first ]] closes the inner link, the second the image
1790 $text .= "[[{$m[0]}]]{$m[1]}";
1793 } elseif ( count( $m ) == 2 ) {
1794 # if there's exactly one ]] that's fine, we'll keep looking
1795 $text .= "[[{$m[0]}]]{$m[1]}";
1797 # if $next_line is invalid too, we need look no further
1798 $text .= '[[' . $next_line;
1803 # we couldn't find the end of this imageLink, so output it raw
1804 # but don't ignore what might be perfectly normal links in the text we've examined
1805 $holders->merge( $this->replaceInternalLinks2( $text ) );
1806 $s .= "{$prefix}[[$link|$text";
1807 # note: no $trail, because without an end, there *is* no trail
1808 wfProfileOut( __METHOD__
."-might_be_img" );
1811 } else { # it's not an image, so output it raw
1812 $s .= "{$prefix}[[$link|$text";
1813 # note: no $trail, because without an end, there *is* no trail
1814 wfProfileOut( __METHOD__
."-might_be_img" );
1817 wfProfileOut( __METHOD__
."-might_be_img" );
1820 $wasblank = ( $text == '' );
1824 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1825 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1826 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1827 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1828 $text = $this->doQuotes( $text );
1831 # Link not escaped by : , create the various objects
1835 wfProfileIn( __METHOD__
."-interwiki" );
1836 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1837 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1838 $s = rtrim( $s . $prefix );
1839 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1840 wfProfileOut( __METHOD__
."-interwiki" );
1843 wfProfileOut( __METHOD__
."-interwiki" );
1845 if ( $ns == NS_FILE
) {
1846 wfProfileIn( __METHOD__
."-image" );
1847 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1849 # if no parameters were passed, $text
1850 # becomes something like "File:Foo.png",
1851 # which we don't want to pass on to the
1855 # recursively parse links inside the image caption
1856 # actually, this will parse them in any other parameters, too,
1857 # but it might be hard to fix that, and it doesn't matter ATM
1858 $text = $this->replaceExternalLinks( $text );
1859 $holders->merge( $this->replaceInternalLinks2( $text ) );
1861 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1862 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1864 $s .= $prefix . $trail;
1866 $this->mOutput
->addImage( $nt->getDBkey() );
1867 wfProfileOut( __METHOD__
."-image" );
1872 if ( $ns == NS_CATEGORY
) {
1873 wfProfileIn( __METHOD__
."-category" );
1874 $s = rtrim( $s . "\n" ); # bug 87
1877 $sortkey = $this->getDefaultSort();
1881 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1882 $sortkey = str_replace( "\n", '', $sortkey );
1883 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1884 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1887 * Strip the whitespace Category links produce, see bug 87
1888 * @todo We might want to use trim($tmp, "\n") here.
1890 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1892 wfProfileOut( __METHOD__
."-category" );
1897 # Self-link checking
1898 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1899 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1900 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1905 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1906 # FIXME: Should do batch file existence checks, see comment below
1907 if ( $ns == NS_MEDIA
) {
1908 wfProfileIn( __METHOD__
."-media" );
1909 # Give extensions a chance to select the file revision for us
1910 $skip = $time = false;
1911 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1913 $link = $sk->link( $nt );
1915 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1917 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1918 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1919 $this->mOutput
->addImage( $nt->getDBkey() );
1920 wfProfileOut( __METHOD__
."-media" );
1924 wfProfileIn( __METHOD__
."-always_known" );
1925 # Some titles, such as valid special pages or files in foreign repos, should
1926 # be shown as bluelinks even though they're not included in the page table
1928 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1929 # batch file existence checks for NS_FILE and NS_MEDIA
1930 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1931 $this->mOutput
->addLink( $nt );
1932 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1934 # Links will be added to the output link list after checking
1935 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1937 wfProfileOut( __METHOD__
."-always_known" );
1939 wfProfileOut( __METHOD__
);
1944 * Make a link placeholder. The text returned can be later resolved to a real link with
1945 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1946 * parsing of interwiki links, and secondly to allow all existence checks and
1947 * article length checks (for stub links) to be bundled into a single query.
1951 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1952 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1956 * Render a forced-blue link inline; protect against double expansion of
1957 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1958 * Since this little disaster has to split off the trail text to avoid
1959 * breaking URLs in the following text without breaking trails on the
1960 * wiki links, it's been made into a horrible function.
1963 * @param $text String
1964 * @param $query String
1965 * @param $trail String
1966 * @param $prefix String
1967 * @return String: HTML-wikitext mix oh yuck
1969 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1970 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1971 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1972 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1973 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1974 return $this->armorLinks( $link ) . $trail;
1978 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1979 * going to go through further parsing steps before inline URL expansion.
1981 * Not needed quite as much as it used to be since free links are a bit
1982 * more sensible these days. But bracketed links are still an issue.
1984 * @param $text String: more-or-less HTML
1985 * @return String: less-or-more HTML with NOPARSE bits
1987 function armorLinks( $text ) {
1988 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1989 "{$this->mUniqPrefix}NOPARSE$1", $text );
1993 * Return true if subpage links should be expanded on this page.
1996 function areSubpagesAllowed() {
1997 # Some namespaces don't allow subpages
1998 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2002 * Handle link to subpage if necessary
2004 * @param $target String: the source of the link
2005 * @param &$text String: the link text, modified as necessary
2006 * @return string the full name of the link
2009 function maybeDoSubpageLink( $target, &$text ) {
2010 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2014 * Used by doBlockLevels()
2017 function closeParagraph() {
2019 if ( $this->mLastSection
!= '' ) {
2020 $result = '</' . $this->mLastSection
. ">\n";
2022 $this->mInPre
= false;
2023 $this->mLastSection
= '';
2028 * getCommon() returns the length of the longest common substring
2029 * of both arguments, starting at the beginning of both.
2032 function getCommon( $st1, $st2 ) {
2033 $fl = strlen( $st1 );
2034 $shorter = strlen( $st2 );
2035 if ( $fl < $shorter ) {
2039 for ( $i = 0; $i < $shorter; ++
$i ) {
2040 if ( $st1{$i} != $st2{$i} ) {
2048 * These next three functions open, continue, and close the list
2049 * element appropriate to the prefix character passed into them.
2052 function openList( $char ) {
2053 $result = $this->closeParagraph();
2055 if ( '*' === $char ) {
2056 $result .= '<ul><li>';
2057 } elseif ( '#' === $char ) {
2058 $result .= '<ol><li>';
2059 } elseif ( ':' === $char ) {
2060 $result .= '<dl><dd>';
2061 } elseif ( ';' === $char ) {
2062 $result .= '<dl><dt>';
2063 $this->mDTopen
= true;
2065 $result = '<!-- ERR 1 -->';
2073 * @param $char String
2076 function nextItem( $char ) {
2077 if ( '*' === $char ||
'#' === $char ) {
2079 } elseif ( ':' === $char ||
';' === $char ) {
2081 if ( $this->mDTopen
) {
2084 if ( ';' === $char ) {
2085 $this->mDTopen
= true;
2086 return $close . '<dt>';
2088 $this->mDTopen
= false;
2089 return $close . '<dd>';
2092 return '<!-- ERR 2 -->';
2097 * @param $char String
2100 function closeList( $char ) {
2101 if ( '*' === $char ) {
2102 $text = '</li></ul>';
2103 } elseif ( '#' === $char ) {
2104 $text = '</li></ol>';
2105 } elseif ( ':' === $char ) {
2106 if ( $this->mDTopen
) {
2107 $this->mDTopen
= false;
2108 $text = '</dt></dl>';
2110 $text = '</dd></dl>';
2113 return '<!-- ERR 3 -->';
2120 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2122 * @param $text String
2123 * @param $linestart Boolean: whether or not this is at the start of a line.
2125 * @return string the lists rendered as HTML
2127 function doBlockLevels( $text, $linestart ) {
2128 wfProfileIn( __METHOD__
);
2130 # Parsing through the text line by line. The main thing
2131 # happening here is handling of block-level elements p, pre,
2132 # and making lists from lines starting with * # : etc.
2134 $textLines = StringUtils
::explode( "\n", $text );
2136 $lastPrefix = $output = '';
2137 $this->mDTopen
= $inBlockElem = false;
2139 $paragraphStack = false;
2141 foreach ( $textLines as $oLine ) {
2143 if ( !$linestart ) {
2153 $lastPrefixLength = strlen( $lastPrefix );
2154 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2155 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2156 # If not in a <pre> element, scan for and figure out what prefixes are there.
2157 if ( !$this->mInPre
) {
2158 # Multiple prefixes may abut each other for nested lists.
2159 $prefixLength = strspn( $oLine, '*#:;' );
2160 $prefix = substr( $oLine, 0, $prefixLength );
2163 # ; and : are both from definition-lists, so they're equivalent
2164 # for the purposes of determining whether or not we need to open/close
2166 $prefix2 = str_replace( ';', ':', $prefix );
2167 $t = substr( $oLine, $prefixLength );
2168 $this->mInPre
= (bool)$preOpenMatch;
2170 # Don't interpret any other prefixes in preformatted text
2172 $prefix = $prefix2 = '';
2177 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2178 # Same as the last item, so no need to deal with nesting or opening stuff
2179 $output .= $this->nextItem( substr( $prefix, -1 ) );
2180 $paragraphStack = false;
2182 if ( substr( $prefix, -1 ) === ';') {
2183 # The one nasty exception: definition lists work like this:
2184 # ; title : definition text
2185 # So we check for : in the remainder text to split up the
2186 # title and definition, without b0rking links.
2188 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2190 $output .= $term . $this->nextItem( ':' );
2193 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2194 # We need to open or close prefixes, or both.
2196 # Either open or close a level...
2197 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2198 $paragraphStack = false;
2200 # Close all the prefixes which aren't shared.
2201 while ( $commonPrefixLength < $lastPrefixLength ) {
2202 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2203 --$lastPrefixLength;
2206 # Continue the current prefix if appropriate.
2207 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2208 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2211 # Open prefixes where appropriate.
2212 while ( $prefixLength > $commonPrefixLength ) {
2213 $char = substr( $prefix, $commonPrefixLength, 1 );
2214 $output .= $this->openList( $char );
2216 if ( ';' === $char ) {
2217 # FIXME: This is dupe of code above
2218 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2220 $output .= $term . $this->nextItem( ':' );
2223 ++
$commonPrefixLength;
2225 $lastPrefix = $prefix2;
2228 # If we have no prefixes, go to paragraph mode.
2229 if ( 0 == $prefixLength ) {
2230 wfProfileIn( __METHOD__
."-paragraph" );
2231 # No prefix (not in list)--go to paragraph mode
2232 # XXX: use a stack for nestable elements like span, table and div
2233 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2234 $closematch = preg_match(
2235 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2236 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2237 if ( $openmatch or $closematch ) {
2238 $paragraphStack = false;
2239 #Â TODO bug 5718: paragraph closed
2240 $output .= $this->closeParagraph();
2241 if ( $preOpenMatch and !$preCloseMatch ) {
2242 $this->mInPre
= true;
2244 $inBlockElem = !$closematch;
2245 } elseif ( !$inBlockElem && !$this->mInPre
) {
2246 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2248 if ( $this->mLastSection
!== 'pre' ) {
2249 $paragraphStack = false;
2250 $output .= $this->closeParagraph().'<pre>';
2251 $this->mLastSection
= 'pre';
2253 $t = substr( $t, 1 );
2256 if ( trim( $t ) === '' ) {
2257 if ( $paragraphStack ) {
2258 $output .= $paragraphStack.'<br />';
2259 $paragraphStack = false;
2260 $this->mLastSection
= 'p';
2262 if ( $this->mLastSection
!== 'p' ) {
2263 $output .= $this->closeParagraph();
2264 $this->mLastSection
= '';
2265 $paragraphStack = '<p>';
2267 $paragraphStack = '</p><p>';
2271 if ( $paragraphStack ) {
2272 $output .= $paragraphStack;
2273 $paragraphStack = false;
2274 $this->mLastSection
= 'p';
2275 } elseif ( $this->mLastSection
!== 'p' ) {
2276 $output .= $this->closeParagraph().'<p>';
2277 $this->mLastSection
= 'p';
2282 wfProfileOut( __METHOD__
."-paragraph" );
2284 # somewhere above we forget to get out of pre block (bug 785)
2285 if ( $preCloseMatch && $this->mInPre
) {
2286 $this->mInPre
= false;
2288 if ( $paragraphStack === false ) {
2292 while ( $prefixLength ) {
2293 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2296 if ( $this->mLastSection
!= '' ) {
2297 $output .= '</' . $this->mLastSection
. '>';
2298 $this->mLastSection
= '';
2301 wfProfileOut( __METHOD__
);
2306 * Split up a string on ':', ignoring any occurences inside tags
2307 * to prevent illegal overlapping.
2309 * @param $str String: the string to split
2310 * @param &$before String: set to everything before the ':'
2311 * @param &$after String: set to everything after the ':'
2312 * return String: the position of the ':', or false if none found
2314 function findColonNoLinks( $str, &$before, &$after ) {
2315 wfProfileIn( __METHOD__
);
2317 $pos = strpos( $str, ':' );
2318 if ( $pos === false ) {
2320 wfProfileOut( __METHOD__
);
2324 $lt = strpos( $str, '<' );
2325 if ( $lt === false ||
$lt > $pos ) {
2326 # Easy; no tag nesting to worry about
2327 $before = substr( $str, 0, $pos );
2328 $after = substr( $str, $pos+
1 );
2329 wfProfileOut( __METHOD__
);
2333 # Ugly state machine to walk through avoiding tags.
2334 $state = self
::COLON_STATE_TEXT
;
2336 $len = strlen( $str );
2337 for( $i = 0; $i < $len; $i++
) {
2341 # (Using the number is a performance hack for common cases)
2342 case 0: # self::COLON_STATE_TEXT:
2345 # Could be either a <start> tag or an </end> tag
2346 $state = self
::COLON_STATE_TAGSTART
;
2349 if ( $stack == 0 ) {
2351 $before = substr( $str, 0, $i );
2352 $after = substr( $str, $i +
1 );
2353 wfProfileOut( __METHOD__
);
2356 # Embedded in a tag; don't break it.
2359 # Skip ahead looking for something interesting
2360 $colon = strpos( $str, ':', $i );
2361 if ( $colon === false ) {
2362 # Nothing else interesting
2363 wfProfileOut( __METHOD__
);
2366 $lt = strpos( $str, '<', $i );
2367 if ( $stack === 0 ) {
2368 if ( $lt === false ||
$colon < $lt ) {
2370 $before = substr( $str, 0, $colon );
2371 $after = substr( $str, $colon +
1 );
2372 wfProfileOut( __METHOD__
);
2376 if ( $lt === false ) {
2377 # Nothing else interesting to find; abort!
2378 # We're nested, but there's no close tags left. Abort!
2381 # Skip ahead to next tag start
2383 $state = self
::COLON_STATE_TAGSTART
;
2386 case 1: # self::COLON_STATE_TAG:
2391 $state = self
::COLON_STATE_TEXT
;
2394 # Slash may be followed by >?
2395 $state = self
::COLON_STATE_TAGSLASH
;
2401 case 2: # self::COLON_STATE_TAGSTART:
2404 $state = self
::COLON_STATE_CLOSETAG
;
2407 $state = self
::COLON_STATE_COMMENT
;
2410 # Illegal early close? This shouldn't happen D:
2411 $state = self
::COLON_STATE_TEXT
;
2414 $state = self
::COLON_STATE_TAG
;
2417 case 3: # self::COLON_STATE_CLOSETAG:
2422 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2423 wfProfileOut( __METHOD__
);
2426 $state = self
::COLON_STATE_TEXT
;
2429 case self
::COLON_STATE_TAGSLASH
:
2431 # Yes, a self-closed tag <blah/>
2432 $state = self
::COLON_STATE_TEXT
;
2434 # Probably we're jumping the gun, and this is an attribute
2435 $state = self
::COLON_STATE_TAG
;
2438 case 5: # self::COLON_STATE_COMMENT:
2440 $state = self
::COLON_STATE_COMMENTDASH
;
2443 case self
::COLON_STATE_COMMENTDASH
:
2445 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2447 $state = self
::COLON_STATE_COMMENT
;
2450 case self
::COLON_STATE_COMMENTDASHDASH
:
2452 $state = self
::COLON_STATE_TEXT
;
2454 $state = self
::COLON_STATE_COMMENT
;
2458 throw new MWException( "State machine error in " . __METHOD__
);
2462 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2465 wfProfileOut( __METHOD__
);
2470 * Return value of a magic variable (like PAGENAME)
2474 function getVariableValue( $index, $frame=false ) {
2475 global $wgContLang, $wgSitename, $wgServer;
2476 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2479 * Some of these require message or data lookups and can be
2480 * expensive to check many times.
2482 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2483 if ( isset( $this->mVarCache
[$index] ) ) {
2484 return $this->mVarCache
[$index];
2488 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2489 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2492 global $wgLocaltimezone;
2493 if ( isset( $wgLocaltimezone ) ) {
2494 $oldtz = date_default_timezone_get();
2495 date_default_timezone_set( $wgLocaltimezone );
2498 $localTimestamp = date( 'YmdHis', $ts );
2499 $localMonth = date( 'm', $ts );
2500 $localMonth1 = date( 'n', $ts );
2501 $localMonthName = date( 'n', $ts );
2502 $localDay = date( 'j', $ts );
2503 $localDay2 = date( 'd', $ts );
2504 $localDayOfWeek = date( 'w', $ts );
2505 $localWeek = date( 'W', $ts );
2506 $localYear = date( 'Y', $ts );
2507 $localHour = date( 'H', $ts );
2508 if ( isset( $wgLocaltimezone ) ) {
2509 date_default_timezone_set( $oldtz );
2513 case 'currentmonth':
2514 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2516 case 'currentmonth1':
2517 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2519 case 'currentmonthname':
2520 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2522 case 'currentmonthnamegen':
2523 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2525 case 'currentmonthabbrev':
2526 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2529 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2532 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2535 $value = $wgContLang->formatNum( $localMonth );
2538 $value = $wgContLang->formatNum( $localMonth1 );
2540 case 'localmonthname':
2541 $value = $wgContLang->getMonthName( $localMonthName );
2543 case 'localmonthnamegen':
2544 $value = $wgContLang->getMonthNameGen( $localMonthName );
2546 case 'localmonthabbrev':
2547 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2550 $value = $wgContLang->formatNum( $localDay );
2553 $value = $wgContLang->formatNum( $localDay2 );
2556 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2559 $value = $this->mTitle
->getPartialURL();
2561 case 'fullpagename':
2562 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2564 case 'fullpagenamee':
2565 $value = $this->mTitle
->getPrefixedURL();
2568 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2570 case 'subpagenamee':
2571 $value = $this->mTitle
->getSubpageUrlForm();
2573 case 'basepagename':
2574 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2576 case 'basepagenamee':
2577 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2579 case 'talkpagename':
2580 if ( $this->mTitle
->canTalk() ) {
2581 $talkPage = $this->mTitle
->getTalkPage();
2582 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2587 case 'talkpagenamee':
2588 if ( $this->mTitle
->canTalk() ) {
2589 $talkPage = $this->mTitle
->getTalkPage();
2590 $value = $talkPage->getPrefixedUrl();
2595 case 'subjectpagename':
2596 $subjPage = $this->mTitle
->getSubjectPage();
2597 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2599 case 'subjectpagenamee':
2600 $subjPage = $this->mTitle
->getSubjectPage();
2601 $value = $subjPage->getPrefixedUrl();
2604 # Let the edit saving system know we should parse the page
2605 # *after* a revision ID has been assigned.
2606 $this->mOutput
->setFlag( 'vary-revision' );
2607 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2608 $value = $this->mRevisionId
;
2611 # Let the edit saving system know we should parse the page
2612 # *after* a revision ID has been assigned. This is for null edits.
2613 $this->mOutput
->setFlag( 'vary-revision' );
2614 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2615 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2617 case 'revisionday2':
2618 # Let the edit saving system know we should parse the page
2619 # *after* a revision ID has been assigned. This is for null edits.
2620 $this->mOutput
->setFlag( 'vary-revision' );
2621 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2622 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2624 case 'revisionmonth':
2625 # Let the edit saving system know we should parse the page
2626 # *after* a revision ID has been assigned. This is for null edits.
2627 $this->mOutput
->setFlag( 'vary-revision' );
2628 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2629 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2631 case 'revisionmonth1':
2632 # Let the edit saving system know we should parse the page
2633 # *after* a revision ID has been assigned. This is for null edits.
2634 $this->mOutput
->setFlag( 'vary-revision' );
2635 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2636 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2638 case 'revisionyear':
2639 # Let the edit saving system know we should parse the page
2640 # *after* a revision ID has been assigned. This is for null edits.
2641 $this->mOutput
->setFlag( 'vary-revision' );
2642 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2643 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2645 case 'revisiontimestamp':
2646 # Let the edit saving system know we should parse the page
2647 # *after* a revision ID has been assigned. This is for null edits.
2648 $this->mOutput
->setFlag( 'vary-revision' );
2649 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2650 $value = $this->getRevisionTimestamp();
2652 case 'revisionuser':
2653 # Let the edit saving system know we should parse the page
2654 # *after* a revision ID has been assigned. This is for null edits.
2655 $this->mOutput
->setFlag( 'vary-revision' );
2656 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2657 $value = $this->getRevisionUser();
2660 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2663 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2666 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2669 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2671 case 'subjectspace':
2672 $value = $this->mTitle
->getSubjectNsText();
2674 case 'subjectspacee':
2675 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2677 case 'currentdayname':
2678 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2681 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2684 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2687 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2690 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2691 # int to remove the padding
2692 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2695 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2697 case 'localdayname':
2698 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2701 $value = $wgContLang->formatNum( $localYear, true );
2704 $value = $wgContLang->time( $localTimestamp, false, false );
2707 $value = $wgContLang->formatNum( $localHour, true );
2710 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2711 # int to remove the padding
2712 $value = $wgContLang->formatNum( (int)$localWeek );
2715 $value = $wgContLang->formatNum( $localDayOfWeek );
2717 case 'numberofarticles':
2718 $value = $wgContLang->formatNum( SiteStats
::articles() );
2720 case 'numberoffiles':
2721 $value = $wgContLang->formatNum( SiteStats
::images() );
2723 case 'numberofusers':
2724 $value = $wgContLang->formatNum( SiteStats
::users() );
2726 case 'numberofactiveusers':
2727 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2729 case 'numberofpages':
2730 $value = $wgContLang->formatNum( SiteStats
::pages() );
2732 case 'numberofadmins':
2733 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2735 case 'numberofedits':
2736 $value = $wgContLang->formatNum( SiteStats
::edits() );
2738 case 'numberofviews':
2739 $value = $wgContLang->formatNum( SiteStats
::views() );
2741 case 'currenttimestamp':
2742 $value = wfTimestamp( TS_MW
, $ts );
2744 case 'localtimestamp':
2745 $value = $localTimestamp;
2747 case 'currentversion':
2748 $value = SpecialVersion
::getVersion();
2751 return $wgArticlePath;
2757 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2758 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2759 wfRestoreWarnings();
2760 return $serverName ?
$serverName : $wgServer;
2762 return $wgScriptPath;
2764 return $wgStylePath;
2765 case 'directionmark':
2766 return $wgContLang->getDirMark();
2767 case 'contentlanguage':
2768 global $wgLanguageCode;
2769 return $wgLanguageCode;
2772 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2780 $this->mVarCache
[$index] = $value;
2786 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2790 function initialiseVariables() {
2791 wfProfileIn( __METHOD__
);
2792 $variableIDs = MagicWord
::getVariableIDs();
2793 $substIDs = MagicWord
::getSubstIDs();
2795 $this->mVariables
= new MagicWordArray( $variableIDs );
2796 $this->mSubstWords
= new MagicWordArray( $substIDs );
2797 wfProfileOut( __METHOD__
);
2801 * Preprocess some wikitext and return the document tree.
2802 * This is the ghost of replace_variables().
2804 * @param $text String: The text to parse
2805 * @param $flags Integer: bitwise combination of:
2806 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2807 * included. Default is to assume a direct page view.
2809 * The generated DOM tree must depend only on the input text and the flags.
2810 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2812 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2813 * change in the DOM tree for a given text, must be passed through the section identifier
2814 * in the section edit link and thus back to extractSections().
2816 * The output of this function is currently only cached in process memory, but a persistent
2817 * cache may be implemented at a later date which takes further advantage of these strict
2818 * dependency requirements.
2822 function preprocessToDom( $text, $flags = 0 ) {
2823 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2828 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2830 public static function splitWhitespace( $s ) {
2831 $ltrimmed = ltrim( $s );
2832 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2833 $trimmed = rtrim( $ltrimmed );
2834 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2836 $w2 = substr( $ltrimmed, -$diff );
2840 return array( $w1, $trimmed, $w2 );
2844 * Replace magic variables, templates, and template arguments
2845 * with the appropriate text. Templates are substituted recursively,
2846 * taking care to avoid infinite loops.
2848 * Note that the substitution depends on value of $mOutputType:
2849 * self::OT_WIKI: only {{subst:}} templates
2850 * self::OT_PREPROCESS: templates but not extension tags
2851 * self::OT_HTML: all templates and extension tags
2853 * @param $text String: the text to transform
2854 * @param $frame PPFrame Object describing the arguments passed to the template.
2855 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2856 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2857 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2860 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2861 # Is there any text? Also, Prevent too big inclusions!
2862 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2865 wfProfileIn( __METHOD__
);
2867 if ( $frame === false ) {
2868 $frame = $this->getPreprocessor()->newFrame();
2869 } elseif ( !( $frame instanceof PPFrame
) ) {
2870 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2871 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2874 $dom = $this->preprocessToDom( $text );
2875 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2876 $text = $frame->expand( $dom, $flags );
2878 wfProfileOut( __METHOD__
);
2882 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2883 static function createAssocArgs( $args ) {
2884 $assocArgs = array();
2886 foreach ( $args as $arg ) {
2887 $eqpos = strpos( $arg, '=' );
2888 if ( $eqpos === false ) {
2889 $assocArgs[$index++
] = $arg;
2891 $name = trim( substr( $arg, 0, $eqpos ) );
2892 $value = trim( substr( $arg, $eqpos+
1 ) );
2893 if ( $value === false ) {
2896 if ( $name !== false ) {
2897 $assocArgs[$name] = $value;
2906 * Warn the user when a parser limitation is reached
2907 * Will warn at most once the user per limitation type
2909 * @param $limitationType String: should be one of:
2910 * 'expensive-parserfunction' (corresponding messages:
2911 * 'expensive-parserfunction-warning',
2912 * 'expensive-parserfunction-category')
2913 * 'post-expand-template-argument' (corresponding messages:
2914 * 'post-expand-template-argument-warning',
2915 * 'post-expand-template-argument-category')
2916 * 'post-expand-template-inclusion' (corresponding messages:
2917 * 'post-expand-template-inclusion-warning',
2918 * 'post-expand-template-inclusion-category')
2919 * @param $current Current value
2920 * @param $max Maximum allowed, when an explicit limit has been
2921 * exceeded, provide the values (optional)
2923 function limitationWarn( $limitationType, $current=null, $max=null) {
2924 # does no harm if $current and $max are present but are unnecessary for the message
2925 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2926 $this->mOutput
->addWarning( $warning );
2927 $this->addTrackingCategory( "$limitationType-category" );
2931 * Return the text of a template, after recursively
2932 * replacing any variables or templates within the template.
2934 * @param $piece Array: the parts of the template
2935 * $piece['title']: the title, i.e. the part before the |
2936 * $piece['parts']: the parameter array
2937 * $piece['lineStart']: whether the brace was at the start of a line
2938 * @param $frame PPFrame The current frame, contains template arguments
2939 * @return String: the text of the template
2942 function braceSubstitution( $piece, $frame ) {
2943 global $wgContLang, $wgNonincludableNamespaces;
2944 wfProfileIn( __METHOD__
);
2945 wfProfileIn( __METHOD__
.'-setup' );
2948 $found = false; # $text has been filled
2949 $nowiki = false; # wiki markup in $text should be escaped
2950 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2951 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2952 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2953 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2955 # Title object, where $text came from
2958 # $part1 is the bit before the first |, and must contain only title characters.
2959 # Various prefixes will be stripped from it later.
2960 $titleWithSpaces = $frame->expand( $piece['title'] );
2961 $part1 = trim( $titleWithSpaces );
2964 # Original title text preserved for various purposes
2965 $originalTitle = $part1;
2967 # $args is a list of argument nodes, starting from index 0, not including $part1
2968 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2969 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2970 wfProfileOut( __METHOD__
.'-setup' );
2973 wfProfileIn( __METHOD__
.'-modifiers' );
2976 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2978 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2979 # Decide whether to expand template or keep wikitext as-is.
2980 if ( $this->ot
['wiki'] ) {
2981 if ( $substMatch === false ) {
2982 $literal = true; # literal when in PST with no prefix
2984 $literal = false; # expand when in PST with subst: or safesubst:
2987 if ( $substMatch == 'subst' ) {
2988 $literal = true; # literal when not in PST with plain subst:
2990 $literal = false; # expand when not in PST with safesubst: or no prefix
2994 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3001 if ( !$found && $args->getLength() == 0 ) {
3002 $id = $this->mVariables
->matchStartToEnd( $part1 );
3003 if ( $id !== false ) {
3004 $text = $this->getVariableValue( $id, $frame );
3005 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3006 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3012 # MSG, MSGNW and RAW
3015 $mwMsgnw = MagicWord
::get( 'msgnw' );
3016 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3019 # Remove obsolete MSG:
3020 $mwMsg = MagicWord
::get( 'msg' );
3021 $mwMsg->matchStartAndRemove( $part1 );
3025 $mwRaw = MagicWord
::get( 'raw' );
3026 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3027 $forceRawInterwiki = true;
3030 wfProfileOut( __METHOD__
.'-modifiers' );
3034 wfProfileIn( __METHOD__
. '-pfunc' );
3036 $colonPos = strpos( $part1, ':' );
3037 if ( $colonPos !== false ) {
3038 # Case sensitive functions
3039 $function = substr( $part1, 0, $colonPos );
3040 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3041 $function = $this->mFunctionSynonyms
[1][$function];
3043 # Case insensitive functions
3044 $function = $wgContLang->lc( $function );
3045 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3046 $function = $this->mFunctionSynonyms
[0][$function];
3052 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3053 $initialArgs = array( &$this );
3054 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3055 if ( $flags & SFH_OBJECT_ARGS
) {
3056 # Add a frame parameter, and pass the arguments as an array
3057 $allArgs = $initialArgs;
3058 $allArgs[] = $frame;
3059 for ( $i = 0; $i < $args->getLength(); $i++
) {
3060 $funcArgs[] = $args->item( $i );
3062 $allArgs[] = $funcArgs;
3064 # Convert arguments to plain text
3065 for ( $i = 0; $i < $args->getLength(); $i++
) {
3066 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3068 $allArgs = array_merge( $initialArgs, $funcArgs );
3071 # Workaround for PHP bug 35229 and similar
3072 if ( !is_callable( $callback ) ) {
3073 wfProfileOut( __METHOD__
. '-pfunc' );
3074 wfProfileOut( __METHOD__
);
3075 throw new MWException( "Tag hook for $function is not callable\n" );
3077 $result = call_user_func_array( $callback, $allArgs );
3080 $preprocessFlags = 0;
3082 if ( is_array( $result ) ) {
3083 if ( isset( $result[0] ) ) {
3085 unset( $result[0] );
3088 # Extract flags into the local scope
3089 # This allows callers to set flags such as nowiki, found, etc.
3095 $text = $this->preprocessToDom( $text, $preprocessFlags );
3100 wfProfileOut( __METHOD__
. '-pfunc' );
3103 # Finish mangling title and then check for loops.
3104 # Set $title to a Title object and $titleText to the PDBK
3107 # Split the title into page and subpage
3109 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3110 if ( $subpage !== '' ) {
3111 $ns = $this->mTitle
->getNamespace();
3113 $title = Title
::newFromText( $part1, $ns );
3115 $titleText = $title->getPrefixedText();
3116 # Check for language variants if the template is not found
3117 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3118 $wgContLang->findVariantLink( $part1, $title, true );
3120 # Do recursion depth check
3121 $limit = $this->mOptions
->getMaxTemplateDepth();
3122 if ( $frame->depth
>= $limit ) {
3124 $text = '<span class="error">'
3125 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3131 # Load from database
3132 if ( !$found && $title ) {
3133 wfProfileIn( __METHOD__
. '-loadtpl' );
3134 if ( !$title->isExternal() ) {
3135 if ( $title->getNamespace() == NS_SPECIAL
3136 && $this->mOptions
->getAllowSpecialInclusion()
3137 && $this->ot
['html'] )
3139 $text = SpecialPage
::capturePath( $title );
3140 if ( is_string( $text ) ) {
3143 $this->disableCache();
3145 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3146 $found = false; # access denied
3147 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3149 list( $text, $title ) = $this->getTemplateDom( $title );
3150 if ( $text !== false ) {
3156 # If the title is valid but undisplayable, make a link to it
3157 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3158 $text = "[[:$titleText]]";
3161 } elseif ( $title->isTrans() ) {
3162 # Interwiki transclusion
3163 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3164 $text = $this->interwikiTransclude( $title, 'render' );
3167 $text = $this->interwikiTransclude( $title, 'raw' );
3168 # Preprocess it like a template
3169 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3175 # Do infinite loop check
3176 # This has to be done after redirect resolution to avoid infinite loops via redirects
3177 if ( !$frame->loopCheck( $title ) ) {
3179 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3180 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3182 wfProfileOut( __METHOD__
. '-loadtpl' );
3185 # If we haven't found text to substitute by now, we're done
3186 # Recover the source wikitext and return it
3188 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3189 wfProfileOut( __METHOD__
);
3190 return array( 'object' => $text );
3193 # Expand DOM-style return values in a child frame
3194 if ( $isChildObj ) {
3195 # Clean up argument array
3196 $newFrame = $frame->newChild( $args, $title );
3199 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3200 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3201 # Expansion is eligible for the empty-frame cache
3202 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3203 $text = $this->mTplExpandCache
[$titleText];
3205 $text = $newFrame->expand( $text );
3206 $this->mTplExpandCache
[$titleText] = $text;
3209 # Uncached expansion
3210 $text = $newFrame->expand( $text );
3213 if ( $isLocalObj && $nowiki ) {
3214 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3215 $isLocalObj = false;
3218 # Replace raw HTML by a placeholder
3219 # Add a blank line preceding, to prevent it from mucking up
3220 # immediately preceding headings
3222 $text = "\n\n" . $this->insertStripItem( $text );
3223 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3224 # Escape nowiki-style return values
3225 $text = wfEscapeWikiText( $text );
3226 } elseif ( is_string( $text )
3227 && !$piece['lineStart']
3228 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3230 # Bug 529: if the template begins with a table or block-level
3231 # element, it should be treated as beginning a new line.
3232 # This behaviour is somewhat controversial.
3233 $text = "\n" . $text;
3236 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3237 # Error, oversize inclusion
3238 if ( $titleText !== false ) {
3239 # Make a working, properly escaped link if possible (bug 23588)
3240 $text = "[[:$titleText]]";
3242 # This will probably not be a working link, but at least it may
3243 # provide some hint of where the problem is
3244 preg_replace( '/^:/', '', $originalTitle );
3245 $text = "[[:$originalTitle]]";
3247 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3248 $this->limitationWarn( 'post-expand-template-inclusion' );
3251 if ( $isLocalObj ) {
3252 $ret = array( 'object' => $text );
3254 $ret = array( 'text' => $text );
3257 wfProfileOut( __METHOD__
);
3262 * Get the semi-parsed DOM representation of a template with a given title,
3263 * and its redirect destination title. Cached.
3265 function getTemplateDom( $title ) {
3266 $cacheTitle = $title;
3267 $titleText = $title->getPrefixedDBkey();
3269 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3270 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3271 $title = Title
::makeTitle( $ns, $dbk );
3272 $titleText = $title->getPrefixedDBkey();
3274 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3275 return array( $this->mTplDomCache
[$titleText], $title );
3278 # Cache miss, go to the database
3279 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3281 if ( $text === false ) {
3282 $this->mTplDomCache
[$titleText] = false;
3283 return array( false, $title );
3286 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3287 $this->mTplDomCache
[ $titleText ] = $dom;
3289 if ( !$title->equals( $cacheTitle ) ) {
3290 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3291 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3294 return array( $dom, $title );
3298 * Fetch the unparsed text of a template and register a reference to it.
3300 function fetchTemplateAndTitle( $title ) {
3301 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3302 $stuff = call_user_func( $templateCb, $title, $this );
3303 $text = $stuff['text'];
3304 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3305 if ( isset( $stuff['deps'] ) ) {
3306 foreach ( $stuff['deps'] as $dep ) {
3307 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3310 return array( $text, $finalTitle );
3313 function fetchTemplate( $title ) {
3314 $rv = $this->fetchTemplateAndTitle( $title );
3319 * Static function to get a template
3320 * Can be overridden via ParserOptions::setTemplateCallback().
3322 static function statelessFetchTemplate( $title, $parser=false ) {
3323 $text = $skip = false;
3324 $finalTitle = $title;
3327 # Loop to fetch the article, with up to 1 redirect
3328 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3329 # Give extensions a chance to select the revision instead
3330 $id = false; # Assume current
3331 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3337 'page_id' => $title->getArticleID(),
3341 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3342 $rev_id = $rev ?
$rev->getId() : 0;
3343 # If there is no current revision, there is no page
3344 if ( $id === false && !$rev ) {
3345 $linkCache = LinkCache
::singleton();
3346 $linkCache->addBadLinkObj( $title );
3351 'page_id' => $title->getArticleID(),
3352 'rev_id' => $rev_id );
3355 $text = $rev->getText();
3356 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3358 $message = $wgContLang->lcfirst( $title->getText() );
3359 $text = wfMsgForContentNoTrans( $message );
3360 if ( wfEmptyMsg( $message, $text ) ) {
3367 if ( $text === false ) {
3371 $finalTitle = $title;
3372 $title = Title
::newFromRedirect( $text );
3376 'finalTitle' => $finalTitle,
3381 * Transclude an interwiki link.
3383 function interwikiTransclude( $title, $action ) {
3384 global $wgEnableScaryTranscluding;
3386 if ( !$wgEnableScaryTranscluding ) {
3387 return wfMsgForContent('scarytranscludedisabled');
3390 $url = $title->getFullUrl( "action=$action" );
3392 if ( strlen( $url ) > 255 ) {
3393 return wfMsgForContent( 'scarytranscludetoolong' );
3395 return $this->fetchScaryTemplateMaybeFromCache( $url );
3398 function fetchScaryTemplateMaybeFromCache( $url ) {
3399 global $wgTranscludeCacheExpiry;
3400 $dbr = wfGetDB( DB_SLAVE
);
3401 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3402 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3403 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3405 return $obj->tc_contents
;
3408 $text = Http
::get( $url );
3410 return wfMsgForContent( 'scarytranscludefailed', $url );
3413 $dbw = wfGetDB( DB_MASTER
);
3414 $dbw->replace( 'transcache', array('tc_url'), array(
3416 'tc_time' => $dbw->timestamp( time() ),
3417 'tc_contents' => $text)
3424 * Triple brace replacement -- used for template arguments
3427 function argSubstitution( $piece, $frame ) {
3428 wfProfileIn( __METHOD__
);
3431 $parts = $piece['parts'];
3432 $nameWithSpaces = $frame->expand( $piece['title'] );
3433 $argName = trim( $nameWithSpaces );
3435 $text = $frame->getArgument( $argName );
3436 if ( $text === false && $parts->getLength() > 0
3440 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3443 # No match in frame, use the supplied default
3444 $object = $parts->item( 0 )->getChildren();
3446 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3447 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3448 $this->limitationWarn( 'post-expand-template-argument' );
3451 if ( $text === false && $object === false ) {
3453 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3455 if ( $error !== false ) {
3458 if ( $object !== false ) {
3459 $ret = array( 'object' => $object );
3461 $ret = array( 'text' => $text );
3464 wfProfileOut( __METHOD__
);
3469 * Return the text to be used for a given extension tag.
3470 * This is the ghost of strip().
3472 * @param $params Associative array of parameters:
3473 * name PPNode for the tag name
3474 * attr PPNode for unparsed text where tag attributes are thought to be
3475 * attributes Optional associative array of parsed attributes
3476 * inner Contents of extension element
3477 * noClose Original text did not have a close tag
3478 * @param $frame PPFrame
3480 function extensionSubstitution( $params, $frame ) {
3481 $name = $frame->expand( $params['name'] );
3482 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3483 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3484 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3486 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3487 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3488 if ( $isFunctionTag ) {
3489 $markerType = 'none';
3491 $markerType = 'general';
3493 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3494 $name = strtolower( $name );
3495 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3496 if ( isset( $params['attributes'] ) ) {
3497 $attributes = $attributes +
$params['attributes'];
3500 if ( isset( $this->mTagHooks
[$name] ) ) {
3501 # Workaround for PHP bug 35229 and similar
3502 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3503 throw new MWException( "Tag hook for $name is not callable\n" );
3505 $output = call_user_func_array( $this->mTagHooks
[$name],
3506 array( $content, $attributes, $this, $frame ) );
3507 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3508 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3509 if ( !is_callable( $callback ) ) {
3510 throw new MWException( "Tag hook for $name is not callable\n" );
3513 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3515 $output = '<span class="error">Invalid tag extension name: ' .
3516 htmlspecialchars( $name ) . '</span>';
3519 if ( is_array( $output ) ) {
3520 # Extract flags to local scope (to override $markerType)
3522 $output = $flags[0];
3527 if ( is_null( $attrText ) ) {
3530 if ( isset( $params['attributes'] ) ) {
3531 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3532 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3533 htmlspecialchars( $attrValue ) . '"';
3536 if ( $content === null ) {
3537 $output = "<$name$attrText/>";
3539 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3540 $output = "<$name$attrText>$content$close";
3544 if ( $markerType === 'none' ) {
3546 } elseif ( $markerType === 'nowiki' ) {
3547 $this->mStripState
->nowiki
->setPair( $marker, $output );
3548 } elseif ( $markerType === 'general' ) {
3549 $this->mStripState
->general
->setPair( $marker, $output );
3551 throw new MWException( __METHOD__
.': invalid marker type' );
3557 * Increment an include size counter
3559 * @param $type String: the type of expansion
3560 * @param $size Integer: the size of the text
3561 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3563 function incrementIncludeSize( $type, $size ) {
3564 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3567 $this->mIncludeSizes
[$type] +
= $size;
3573 * Increment the expensive function count
3575 * @return Boolean: false if the limit has been exceeded
3577 function incrementExpensiveFunctionCount() {
3578 global $wgExpensiveParserFunctionLimit;
3579 $this->mExpensiveFunctionCount++
;
3580 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3587 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3588 * Fills $this->mDoubleUnderscores, returns the modified text
3590 function doDoubleUnderscore( $text ) {
3591 wfProfileIn( __METHOD__
);
3593 # The position of __TOC__ needs to be recorded
3594 $mw = MagicWord
::get( 'toc' );
3595 if ( $mw->match( $text ) ) {
3596 $this->mShowToc
= true;
3597 $this->mForceTocPosition
= true;
3599 # Set a placeholder. At the end we'll fill it in with the TOC.
3600 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3602 # Only keep the first one.
3603 $text = $mw->replace( '', $text );
3606 # Now match and remove the rest of them
3607 $mwa = MagicWord
::getDoubleUnderscoreArray();
3608 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3610 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3611 $this->mOutput
->mNoGallery
= true;
3613 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3614 $this->mShowToc
= false;
3616 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3617 $this->addTrackingCategory( 'hidden-category-category' );
3619 # (bug 8068) Allow control over whether robots index a page.
3621 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3622 # is not desirable, the last one on the page should win.
3623 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3624 $this->mOutput
->setIndexPolicy( 'noindex' );
3625 $this->addTrackingCategory( 'noindex-category' );
3627 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3628 $this->mOutput
->setIndexPolicy( 'index' );
3629 $this->addTrackingCategory( 'index-category' );
3632 # Cache all double underscores in the database
3633 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3634 $this->mOutput
->setProperty( $key, '' );
3637 wfProfileOut( __METHOD__
);
3642 * Add a tracking category, getting the title from a system message,
3643 * or print a debug message if the title is invalid.
3645 * @param $msg String: message key
3646 * @return Boolean: whether the addition was successful
3648 protected function addTrackingCategory( $msg ) {
3649 $cat = wfMsgForContent( $msg );
3651 # Allow tracking categories to be disabled by setting them to "-"
3652 if ( $cat === '-' ) {
3656 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3657 if ( $containerCategory ) {
3658 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3661 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3667 * This function accomplishes several tasks:
3668 * 1) Auto-number headings if that option is enabled
3669 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3670 * 3) Add a Table of contents on the top for users who have enabled the option
3671 * 4) Auto-anchor headings
3673 * It loops through all headlines, collects the necessary data, then splits up the
3674 * string and re-inserts the newly formatted headlines.
3676 * @param $text String
3677 * @param $origText String: original, untouched wikitext
3678 * @param $isMain Boolean
3681 function formatHeadings( $text, $origText, $isMain=true ) {
3682 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3684 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3686 # Inhibit editsection links if requested in the page
3687 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3690 $showEditLink = $this->mOptions
->getEditSection();
3692 if ( $showEditLink ) {
3693 $this->mOutput
->setEditSectionTokens( true );
3696 # Get all headlines for numbering them and adding funky stuff like [edit]
3697 # links - this is for later, but we need the number of headlines right now
3699 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3701 # if there are fewer than 4 headlines in the article, do not show TOC
3702 # unless it's been explicitly enabled.
3703 $enoughToc = $this->mShowToc
&&
3704 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3706 # Allow user to stipulate that a page should have a "new section"
3707 # link added via __NEWSECTIONLINK__
3708 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3709 $this->mOutput
->setNewSection( true );
3712 # Allow user to remove the "new section"
3713 # link via __NONEWSECTIONLINK__
3714 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3715 $this->mOutput
->hideNewSection( true );
3718 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3719 # override above conditions and always show TOC above first header
3720 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3721 $this->mShowToc
= true;
3725 # We need this to perform operations on the HTML
3726 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3732 # Ugh .. the TOC should have neat indentation levels which can be
3733 # passed to the skin functions. These are determined here
3737 $sublevelCount = array();
3738 $levelCount = array();
3743 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3744 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3745 $oldType = $this->mOutputType
;
3746 $this->setOutputType( self
::OT_WIKI
);
3747 $frame = $this->getPreprocessor()->newFrame();
3748 $root = $this->preprocessToDom( $origText );
3749 $node = $root->getFirstChild();
3754 foreach ( $matches[3] as $headline ) {
3755 $isTemplate = false;
3757 $sectionIndex = false;
3759 $markerMatches = array();
3760 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3761 $serial = $markerMatches[1];
3762 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3763 $isTemplate = ( $titleText != $baseTitleText );
3764 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3768 $prevlevel = $level;
3770 $level = $matches[1][$headlineCount];
3772 if ( $level > $prevlevel ) {
3773 # Increase TOC level
3775 $sublevelCount[$toclevel] = 0;
3776 if ( $toclevel<$wgMaxTocLevel ) {
3777 $prevtoclevel = $toclevel;
3778 $toc .= $sk->tocIndent();
3781 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3782 # Decrease TOC level, find level to jump to
3784 for ( $i = $toclevel; $i > 0; $i-- ) {
3785 if ( $levelCount[$i] == $level ) {
3786 # Found last matching level
3789 } elseif ( $levelCount[$i] < $level ) {
3790 # Found first matching level below current level
3798 if ( $toclevel<$wgMaxTocLevel ) {
3799 if ( $prevtoclevel < $wgMaxTocLevel ) {
3800 # Unindent only if the previous toc level was shown :p
3801 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3802 $prevtoclevel = $toclevel;
3804 $toc .= $sk->tocLineEnd();
3808 # No change in level, end TOC line
3809 if ( $toclevel<$wgMaxTocLevel ) {
3810 $toc .= $sk->tocLineEnd();
3814 $levelCount[$toclevel] = $level;
3816 # count number of headlines for each level
3817 @$sublevelCount[$toclevel]++
;
3819 for( $i = 1; $i <= $toclevel; $i++
) {
3820 if ( !empty( $sublevelCount[$i] ) ) {
3824 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3829 # The safe header is a version of the header text safe to use for links
3830 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3831 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3833 # Remove link placeholders by the link text.
3834 # <!--LINK number-->
3836 # link text with suffix
3837 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3839 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3840 $tocline = preg_replace(
3841 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3842 array( '', '<$1>' ),
3845 $tocline = trim( $tocline );
3847 # For the anchor, strip out HTML-y stuff period
3848 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3849 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3851 # Save headline for section edit hint before it's escaped
3852 $headlineHint = $safeHeadline;
3854 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3855 # For reverse compatibility, provide an id that's
3856 # HTML4-compatible, like we used to.
3858 # It may be worth noting, academically, that it's possible for
3859 # the legacy anchor to conflict with a non-legacy headline
3860 # anchor on the page. In this case likely the "correct" thing
3861 # would be to either drop the legacy anchors or make sure
3862 # they're numbered first. However, this would require people
3863 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3864 # manually, so let's not bother worrying about it.
3865 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3866 array( 'noninitial', 'legacy' ) );
3867 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3869 if ( $legacyHeadline == $safeHeadline ) {
3870 # No reason to have both (in fact, we can't)
3871 $legacyHeadline = false;
3874 $legacyHeadline = false;
3875 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3879 # HTML names must be case-insensitively unique (bug 10721).
3880 # This does not apply to Unicode characters per
3881 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3882 # FIXME: We may be changing them depending on the current locale.
3883 $arrayKey = strtolower( $safeHeadline );
3884 if ( $legacyHeadline === false ) {
3885 $legacyArrayKey = false;
3887 $legacyArrayKey = strtolower( $legacyHeadline );
3890 # count how many in assoc. array so we can track dupes in anchors
3891 if ( isset( $refers[$arrayKey] ) ) {
3892 $refers[$arrayKey]++
;
3894 $refers[$arrayKey] = 1;
3896 if ( isset( $refers[$legacyArrayKey] ) ) {
3897 $refers[$legacyArrayKey]++
;
3899 $refers[$legacyArrayKey] = 1;
3902 # Don't number the heading if it is the only one (looks silly)
3903 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3904 # the two are different if the line contains a link
3905 $headline = $numbering . ' ' . $headline;
3908 # Create the anchor for linking from the TOC to the section
3909 $anchor = $safeHeadline;
3910 $legacyAnchor = $legacyHeadline;
3911 if ( $refers[$arrayKey] > 1 ) {
3912 $anchor .= '_' . $refers[$arrayKey];
3914 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3915 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3917 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3918 $toc .= $sk->tocLine( $anchor, $tocline,
3919 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3922 # Add the section to the section tree
3923 # Find the DOM node for this header
3924 while ( $node && !$isTemplate ) {
3925 if ( $node->getName() === 'h' ) {
3926 $bits = $node->splitHeading();
3927 if ( $bits['i'] == $sectionIndex ) {
3931 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3932 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3933 $node = $node->getNextSibling();
3936 'toclevel' => $toclevel,
3939 'number' => $numbering,
3940 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3941 'fromtitle' => $titleText,
3942 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3943 'anchor' => $anchor,
3946 # give headline the correct <h#> tag
3947 if ( $showEditLink && $sectionIndex !== false ) {
3948 // Output edit section links as markers with styles that can be customized by skins
3949 if ( $isTemplate ) {
3950 # Put a T flag in the section identifier, to indicate to extractSections()
3951 # that sections inside <includeonly> should be counted.
3952 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3954 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3956 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3957 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3958 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3959 // so we don't have to worry about a user trying to input one of these markers directly.
3960 // We use a page and section attribute to stop the language converter from converting these important bits
3961 // of data, but put the headline hint inside a content block because the language converter is supposed to
3962 // be able to convert that piece of data.
3963 $editlink = '<editsection page="' . htmlspecialchars($editlinkArgs[0]);
3964 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
3965 if ( isset($editlinkArgs[2]) ) {
3966 $editlink .= '>' . $editlinkArgs[2] . '</editsection>';
3973 $head[$headlineCount] = $sk->makeHeadline( $level,
3974 $matches['attrib'][$headlineCount], $anchor, $headline,
3975 $editlink, $legacyAnchor );
3980 $this->setOutputType( $oldType );
3982 # Never ever show TOC if no headers
3983 if ( $numVisible < 1 ) {
3988 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3989 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3991 $toc = $sk->tocList( $toc );
3992 $this->mOutput
->setTOCHTML( $toc );
3996 $this->mOutput
->setSections( $tocraw );
3999 # split up and insert constructed headlines
4001 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4004 foreach ( $blocks as $block ) {
4005 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4006 # This is the [edit] link that appears for the top block of text when
4007 # section editing is enabled
4009 # Disabled because it broke block formatting
4010 # For example, a bullet point in the top line
4011 # $full .= $sk->editSectionLink(0);
4014 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4015 # Top anchor now in skin
4019 if ( !empty( $head[$i] ) ) {
4024 if ( $this->mForceTocPosition
) {
4025 return str_replace( '<!--MWTOC-->', $toc, $full );
4032 * Transform wiki markup when saving a page by doing \r\n -> \n
4033 * conversion, substitting signatures, {{subst:}} templates, etc.
4035 * @param $text String: the text to transform
4036 * @param $title Title: the Title object for the current article
4037 * @param $user User: the User object describing the current user
4038 * @param $options ParserOptions: parsing options
4039 * @param $clearState Boolean: whether to clear the parser state first
4040 * @return String: the altered wiki markup
4042 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4043 $this->mOptions
= $options;
4044 $this->setTitle( $title );
4045 $this->setUser( $user );
4046 $this->setOutputType( self
::OT_WIKI
);
4048 if ( $clearState ) {
4049 $this->clearState();
4055 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4056 $text = $this->pstPass2( $text, $user );
4057 $text = $this->mStripState
->unstripBoth( $text );
4059 $this->setUser( null ); #Reset
4065 * Pre-save transform helper function
4068 function pstPass2( $text, $user ) {
4069 global $wgContLang, $wgLocaltimezone;
4071 # Note: This is the timestamp saved as hardcoded wikitext to
4072 # the database, we use $wgContLang here in order to give
4073 # everyone the same signature and use the default one rather
4074 # than the one selected in each user's preferences.
4075 # (see also bug 12815)
4076 $ts = $this->mOptions
->getTimestamp();
4077 if ( isset( $wgLocaltimezone ) ) {
4078 $tz = $wgLocaltimezone;
4080 $tz = date_default_timezone_get();
4083 $unixts = wfTimestamp( TS_UNIX
, $ts );
4084 $oldtz = date_default_timezone_get();
4085 date_default_timezone_set( $tz );
4086 $ts = date( 'YmdHis', $unixts );
4087 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4089 # Allow translation of timezones through wiki. date() can return
4090 # whatever crap the system uses, localised or not, so we cannot
4091 # ship premade translations.
4092 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4093 $msg = wfMessage( $key )->inContentLanguage();
4094 if ( $msg->exists() ) {
4095 $tzMsg = $msg->text();
4098 date_default_timezone_set( $oldtz );
4100 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4102 # Variable replacement
4103 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4104 $text = $this->replaceVariables( $text );
4107 $sigText = $this->getUserSig( $user );
4108 $text = strtr( $text, array(
4110 '~~~~' => "$sigText $d",
4114 # Context links: [[|name]] and [[name (context)|]]
4115 global $wgLegalTitleChars;
4116 $tc = "[$wgLegalTitleChars]";
4117 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4119 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4120 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4121 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4122 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4124 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4125 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4126 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4127 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4129 $t = $this->mTitle
->getText();
4131 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4132 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4133 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4134 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4136 # if there's no context, don't bother duplicating the title
4137 $text = preg_replace( $p2, '[[\\1]]', $text );
4140 # Trim trailing whitespace
4141 $text = rtrim( $text );
4147 * Fetch the user's signature text, if any, and normalize to
4148 * validated, ready-to-insert wikitext.
4149 * If you have pre-fetched the nickname or the fancySig option, you can
4150 * specify them here to save a database query.
4153 * @param $nickname String: nickname to use or false to use user's default nickname
4154 * @param $fancySig Boolean: whether the nicknname is the complete signature
4155 * or null to use default value
4158 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4159 global $wgMaxSigChars;
4161 $username = $user->getName();
4163 # If not given, retrieve from the user object.
4164 if ( $nickname === false )
4165 $nickname = $user->getOption( 'nickname' );
4167 if ( is_null( $fancySig ) ) {
4168 $fancySig = $user->getBoolOption( 'fancysig' );
4171 $nickname = $nickname == null ?
$username : $nickname;
4173 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4174 $nickname = $username;
4175 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4176 } elseif ( $fancySig !== false ) {
4177 # Sig. might contain markup; validate this
4178 if ( $this->validateSig( $nickname ) !== false ) {
4179 # Validated; clean up (if needed) and return it
4180 return $this->cleanSig( $nickname, true );
4182 # Failed to validate; fall back to the default
4183 $nickname = $username;
4184 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4188 # Make sure nickname doesnt get a sig in a sig
4189 $nickname = $this->cleanSigInSig( $nickname );
4191 # If we're still here, make it a link to the user page
4192 $userText = wfEscapeWikiText( $username );
4193 $nickText = wfEscapeWikiText( $nickname );
4194 if ( $user->isAnon() ) {
4195 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4197 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4202 * Check that the user's signature contains no bad XML
4204 * @param $text String
4205 * @return mixed An expanded string, or false if invalid.
4207 function validateSig( $text ) {
4208 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4212 * Clean up signature text
4214 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4215 * 2) Substitute all transclusions
4217 * @param $text String
4218 * @param $parsing Whether we're cleaning (preferences save) or parsing
4219 * @return String: signature text
4221 function cleanSig( $text, $parsing = false ) {
4224 $this->mOptions
= new ParserOptions
;
4225 $this->clearState();
4226 $this->setTitle( $wgTitle );
4227 $this->setOutputType
= self
::OT_PREPROCESS
;
4230 # Option to disable this feature
4231 if ( !$this->mOptions
->getCleanSignatures() ) {
4235 # FIXME: regex doesn't respect extension tags or nowiki
4236 # => Move this logic to braceSubstitution()
4237 $substWord = MagicWord
::get( 'subst' );
4238 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4239 $substText = '{{' . $substWord->getSynonym( 0 );
4241 $text = preg_replace( $substRegex, $substText, $text );
4242 $text = $this->cleanSigInSig( $text );
4243 $dom = $this->preprocessToDom( $text );
4244 $frame = $this->getPreprocessor()->newFrame();
4245 $text = $frame->expand( $dom );
4248 $text = $this->mStripState
->unstripBoth( $text );
4255 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4257 * @param $text String
4258 * @return String: signature text with /~{3,5}/ removed
4260 function cleanSigInSig( $text ) {
4261 $text = preg_replace( '/~{3,5}/', '', $text );
4266 * Set up some variables which are usually set up in parse()
4267 * so that an external function can call some class members with confidence
4269 public function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4270 $this->setTitle( $title );
4271 $options->resetUsage();
4272 $this->mOptions
= $options;
4273 $this->setOutputType( $outputType );
4274 if ( $clearState ) {
4275 $this->clearState();
4280 * Wrapper for preprocess()
4282 * @param $text String: the text to preprocess
4283 * @param $options ParserOptions: options
4286 public function transformMsg( $text, $options ) {
4288 static $executing = false;
4290 # Guard against infinite recursion
4296 wfProfileIn( __METHOD__
);
4297 $text = $this->preprocess( $text, $wgTitle, $options );
4300 wfProfileOut( __METHOD__
);
4305 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4306 * The callback should have the following form:
4307 * function myParserHook( $text, $params, $parser ) { ... }
4309 * Transform and return $text. Use $parser for any required context, e.g. use
4310 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4312 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4313 * @param $callback Mixed: the callback function (and object) to use for the tag
4314 * @return The old value of the mTagHooks array associated with the hook
4316 public function setHook( $tag, $callback ) {
4317 $tag = strtolower( $tag );
4318 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4319 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4320 $this->mTagHooks
[$tag] = $callback;
4321 if ( !in_array( $tag, $this->mStripList
) ) {
4322 $this->mStripList
[] = $tag;
4328 function setTransparentTagHook( $tag, $callback ) {
4329 $tag = strtolower( $tag );
4330 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4331 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4332 $this->mTransparentTagHooks
[$tag] = $callback;
4338 * Remove all tag hooks
4340 function clearTagHooks() {
4341 $this->mTagHooks
= array();
4342 $this->mStripList
= $this->mDefaultStripList
;
4346 * Create a function, e.g. {{sum:1|2|3}}
4347 * The callback function should have the form:
4348 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4350 * Or with SFH_OBJECT_ARGS:
4351 * function myParserFunction( $parser, $frame, $args ) { ... }
4353 * The callback may either return the text result of the function, or an array with the text
4354 * in element 0, and a number of flags in the other elements. The names of the flags are
4355 * specified in the keys. Valid flags are:
4356 * found The text returned is valid, stop processing the template. This
4358 * nowiki Wiki markup in the return value should be escaped
4359 * isHTML The returned text is HTML, armour it against wikitext transformation
4361 * @param $id String: The magic word ID
4362 * @param $callback Mixed: the callback function (and object) to use
4363 * @param $flags Integer: a combination of the following flags:
4364 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4366 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4367 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4368 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4369 * the arguments, and to control the way they are expanded.
4371 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4372 * arguments, for instance:
4373 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4375 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4376 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4377 * working if/when this is changed.
4379 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4382 * Please read the documentation in includes/parser/Preprocessor.php for more information
4383 * about the methods available in PPFrame and PPNode.
4385 * @return The old callback function for this name, if any
4387 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4390 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4391 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4393 # Add to function cache
4394 $mw = MagicWord
::get( $id );
4396 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4398 $synonyms = $mw->getSynonyms();
4399 $sensitive = intval( $mw->isCaseSensitive() );
4401 foreach ( $synonyms as $syn ) {
4403 if ( !$sensitive ) {
4404 $syn = $wgContLang->lc( $syn );
4407 if ( !( $flags & SFH_NO_HASH
) ) {
4410 # Remove trailing colon
4411 if ( substr( $syn, -1, 1 ) === ':' ) {
4412 $syn = substr( $syn, 0, -1 );
4414 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4420 * Get all registered function hook identifiers
4424 function getFunctionHooks() {
4425 return array_keys( $this->mFunctionHooks
);
4429 * Create a tag function, e.g. <test>some stuff</test>.
4430 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4431 * Unlike parser functions, their content is not preprocessed.
4433 function setFunctionTagHook( $tag, $callback, $flags ) {
4434 $tag = strtolower( $tag );
4435 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4436 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4437 $this->mFunctionTagHooks
[$tag] : null;
4438 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4440 if ( !in_array( $tag, $this->mStripList
) ) {
4441 $this->mStripList
[] = $tag;
4448 * FIXME: update documentation. makeLinkObj() is deprecated.
4449 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4450 * Placeholders created in Skin::makeLinkObj()
4451 * Returns an array of link CSS classes, indexed by PDBK.
4453 function replaceLinkHolders( &$text, $options = 0 ) {
4454 return $this->mLinkHolders
->replace( $text );
4458 * Replace <!--LINK--> link placeholders with plain text of links
4459 * (not HTML-formatted).
4461 * @param $text String
4464 function replaceLinkHoldersText( $text ) {
4465 return $this->mLinkHolders
->replaceText( $text );
4469 * Renders an image gallery from a text with one line per image.
4470 * text labels may be given by using |-style alternative text. E.g.
4471 * Image:one.jpg|The number "1"
4472 * Image:tree.jpg|A tree
4473 * given as text will return the HTML of a gallery with two images,
4474 * labeled 'The number "1"' and
4477 function renderImageGallery( $text, $params ) {
4478 $ig = new ImageGallery();
4479 $ig->setContextTitle( $this->mTitle
);
4480 $ig->setShowBytes( false );
4481 $ig->setShowFilename( false );
4482 $ig->setParser( $this );
4483 $ig->setHideBadImages();
4484 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4485 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4486 $ig->mRevisionId
= $this->mRevisionId
;
4488 if ( isset( $params['showfilename'] ) ) {
4489 $ig->setShowFilename( true );
4491 $ig->setShowFilename( false );
4493 if ( isset( $params['caption'] ) ) {
4494 $caption = $params['caption'];
4495 $caption = htmlspecialchars( $caption );
4496 $caption = $this->replaceInternalLinks( $caption );
4497 $ig->setCaptionHtml( $caption );
4499 if ( isset( $params['perrow'] ) ) {
4500 $ig->setPerRow( $params['perrow'] );
4502 if ( isset( $params['widths'] ) ) {
4503 $ig->setWidths( $params['widths'] );
4505 if ( isset( $params['heights'] ) ) {
4506 $ig->setHeights( $params['heights'] );
4509 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4511 $lines = StringUtils
::explode( "\n", $text );
4512 foreach ( $lines as $line ) {
4513 # match lines like these:
4514 # Image:someimage.jpg|This is some image
4516 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4518 if ( count( $matches ) == 0 ) {
4522 if ( strpos( $matches[0], '%' ) !== false ) {
4523 $matches[1] = rawurldecode( $matches[1] );
4525 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4527 if ( is_null( $nt ) ) {
4528 # Bogus title. Ignore these so we don't bomb out later.
4531 if ( isset( $matches[3] ) ) {
4532 $label = $matches[3];
4537 $html = $this->recursiveTagParse( trim( $label ) );
4539 $ig->add( $nt, $html );
4541 # Only add real images (bug #5586)
4542 if ( $nt->getNamespace() == NS_FILE
) {
4543 $this->mOutput
->addImage( $nt->getDBkey() );
4546 return $ig->toHTML();
4549 function getImageParams( $handler ) {
4551 $handlerClass = get_class( $handler );
4555 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4556 # Initialise static lists
4557 static $internalParamNames = array(
4558 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4559 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4560 'bottom', 'text-bottom' ),
4561 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4562 'upright', 'border', 'link', 'alt' ),
4564 static $internalParamMap;
4565 if ( !$internalParamMap ) {
4566 $internalParamMap = array();
4567 foreach ( $internalParamNames as $type => $names ) {
4568 foreach ( $names as $name ) {
4569 $magicName = str_replace( '-', '_', "img_$name" );
4570 $internalParamMap[$magicName] = array( $type, $name );
4575 # Add handler params
4576 $paramMap = $internalParamMap;
4578 $handlerParamMap = $handler->getParamMap();
4579 foreach ( $handlerParamMap as $magic => $paramName ) {
4580 $paramMap[$magic] = array( 'handler', $paramName );
4583 $this->mImageParams
[$handlerClass] = $paramMap;
4584 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4586 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4590 * Parse image options text and use it to make an image
4592 * @param $title Title
4593 * @param $options String
4594 * @param $holders LinkHolderArray
4596 function makeImage( $title, $options, $holders = false ) {
4597 # Check if the options text is of the form "options|alt text"
4599 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4600 # * left no resizing, just left align. label is used for alt= only
4601 # * right same, but right aligned
4602 # * none same, but not aligned
4603 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4604 # * center center the image
4605 # * frame Keep original image size, no magnify-button.
4606 # * framed Same as "frame"
4607 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4608 # * upright reduce width for upright images, rounded to full __0 px
4609 # * border draw a 1px border around the image
4610 # * alt Text for HTML alt attribute (defaults to empty)
4611 # * link Set the target of the image link. Can be external, interwiki, or local
4612 # vertical-align values (no % or length right now):
4622 $parts = StringUtils
::explode( "|", $options );
4623 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4625 # Give extensions a chance to select the file revision for us
4626 $skip = $time = $descQuery = false;
4627 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4630 return $sk->link( $title );
4634 $file = wfFindFile( $title, array( 'time' => $time ) );
4636 $handler = $file ?
$file->getHandler() : false;
4638 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4640 # Process the input parameters
4642 $params = array( 'frame' => array(), 'handler' => array(),
4643 'horizAlign' => array(), 'vertAlign' => array() );
4644 foreach ( $parts as $part ) {
4645 $part = trim( $part );
4646 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4648 if ( isset( $paramMap[$magicName] ) ) {
4649 list( $type, $paramName ) = $paramMap[$magicName];
4651 # Special case; width and height come in one variable together
4652 if ( $type === 'handler' && $paramName === 'width' ) {
4654 # (bug 13500) In both cases (width/height and width only),
4655 # permit trailing "px" for backward compatibility.
4656 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4657 $width = intval( $m[1] );
4658 $height = intval( $m[2] );
4659 if ( $handler->validateParam( 'width', $width ) ) {
4660 $params[$type]['width'] = $width;
4663 if ( $handler->validateParam( 'height', $height ) ) {
4664 $params[$type]['height'] = $height;
4667 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4668 $width = intval( $value );
4669 if ( $handler->validateParam( 'width', $width ) ) {
4670 $params[$type]['width'] = $width;
4673 } # else no validation -- bug 13436
4675 if ( $type === 'handler' ) {
4676 # Validate handler parameter
4677 $validated = $handler->validateParam( $paramName, $value );
4679 # Validate internal parameters
4680 switch( $paramName ) {
4683 # @todo Fixme: possibly check validity here for
4684 # manualthumb? downstream behavior seems odd with
4685 # missing manual thumbs.
4687 $value = $this->stripAltText( $value, $holders );
4690 $chars = self
::EXT_LINK_URL_CLASS
;
4691 $prots = $this->mUrlProtocols
;
4692 if ( $value === '' ) {
4693 $paramName = 'no-link';
4696 } elseif ( preg_match( "/^$prots/", $value ) ) {
4697 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4698 $paramName = 'link-url';
4699 $this->mOutput
->addExternalLink( $value );
4700 if ( $this->mOptions
->getExternalLinkTarget() ) {
4701 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4706 $linkTitle = Title
::newFromText( $value );
4708 $paramName = 'link-title';
4709 $value = $linkTitle;
4710 $this->mOutput
->addLink( $linkTitle );
4716 # Most other things appear to be empty or numeric...
4717 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4722 $params[$type][$paramName] = $value;
4726 if ( !$validated ) {
4731 # Process alignment parameters
4732 if ( $params['horizAlign'] ) {
4733 $params['frame']['align'] = key( $params['horizAlign'] );
4735 if ( $params['vertAlign'] ) {
4736 $params['frame']['valign'] = key( $params['vertAlign'] );
4739 $params['frame']['caption'] = $caption;
4741 # Will the image be presented in a frame, with the caption below?
4742 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4743 isset( $params['frame']['framed'] ) ||
4744 isset( $params['frame']['thumbnail'] ) ||
4745 isset( $params['frame']['manualthumb'] );
4747 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4748 # came to also set the caption, ordinary text after the image -- which
4749 # makes no sense, because that just repeats the text multiple times in
4750 # screen readers. It *also* came to set the title attribute.
4752 # Now that we have an alt attribute, we should not set the alt text to
4753 # equal the caption: that's worse than useless, it just repeats the
4754 # text. This is the framed/thumbnail case. If there's no caption, we
4755 # use the unnamed parameter for alt text as well, just for the time be-
4756 # ing, if the unnamed param is set and the alt param is not.
4758 # For the future, we need to figure out if we want to tweak this more,
4759 # e.g., introducing a title= parameter for the title; ignoring the un-
4760 # named parameter entirely for images without a caption; adding an ex-
4761 # plicit caption= parameter and preserving the old magic unnamed para-
4763 if ( $imageIsFramed ) { # Framed image
4764 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4765 # No caption or alt text, add the filename as the alt text so
4766 # that screen readers at least get some description of the image
4767 $params['frame']['alt'] = $title->getText();
4769 # Do not set $params['frame']['title'] because tooltips don't make sense
4771 } else { # Inline image
4772 if ( !isset( $params['frame']['alt'] ) ) {
4773 # No alt text, use the "caption" for the alt text
4774 if ( $caption !== '') {
4775 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4777 # No caption, fall back to using the filename for the
4779 $params['frame']['alt'] = $title->getText();
4782 # Use the "caption" for the tooltip text
4783 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4786 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4788 # Linker does the rest
4789 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4791 # Give the handler a chance to modify the parser object
4793 $handler->parserTransformHook( $this, $file );
4799 protected function stripAltText( $caption, $holders ) {
4800 # Strip bad stuff out of the title (tooltip). We can't just use
4801 # replaceLinkHoldersText() here, because if this function is called
4802 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4804 $tooltip = $holders->replaceText( $caption );
4806 $tooltip = $this->replaceLinkHoldersText( $caption );
4809 # make sure there are no placeholders in thumbnail attributes
4810 # that are later expanded to html- so expand them now and
4812 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4813 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4819 * Set a flag in the output object indicating that the content is dynamic and
4820 * shouldn't be cached.
4822 function disableCache() {
4823 wfDebug( "Parser output marked as uncacheable.\n" );
4824 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4825 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4829 * Callback from the Sanitizer for expanding items found in HTML attribute
4830 * values, so they can be safely tested and escaped.
4832 * @param $text String
4833 * @param $frame PPFrame
4837 function attributeStripCallback( &$text, $frame = false ) {
4838 $text = $this->replaceVariables( $text, $frame );
4839 $text = $this->mStripState
->unstripBoth( $text );
4846 function getTags() {
4847 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4851 * Break wikitext input into sections, and either pull or replace
4852 * some particular section's text.
4854 * External callers should use the getSection and replaceSection methods.
4856 * @param $text String: Page wikitext
4857 * @param $section String: a section identifier string of the form:
4858 * <flag1> - <flag2> - ... - <section number>
4860 * Currently the only recognised flag is "T", which means the target section number
4861 * was derived during a template inclusion parse, in other words this is a template
4862 * section edit link. If no flags are given, it was an ordinary section edit link.
4863 * This flag is required to avoid a section numbering mismatch when a section is
4864 * enclosed by <includeonly> (bug 6563).
4866 * The section number 0 pulls the text before the first heading; other numbers will
4867 * pull the given section along with its lower-level subsections. If the section is
4868 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4870 * @param $mode String: one of "get" or "replace"
4871 * @param $newText String: replacement text for section data.
4872 * @return String: for "get", the extracted section text.
4873 * for "replace", the whole page with the section replaced.
4875 private function extractSections( $text, $section, $mode, $newText='' ) {
4877 $this->mOptions
= new ParserOptions
;
4878 $this->clearState();
4879 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4880 $this->setOutputType( self
::OT_PLAIN
);
4882 $frame = $this->getPreprocessor()->newFrame();
4884 # Process section extraction flags
4886 $sectionParts = explode( '-', $section );
4887 $sectionIndex = array_pop( $sectionParts );
4888 foreach ( $sectionParts as $part ) {
4889 if ( $part === 'T' ) {
4890 $flags |
= self
::PTD_FOR_INCLUSION
;
4893 # Preprocess the text
4894 $root = $this->preprocessToDom( $text, $flags );
4896 # <h> nodes indicate section breaks
4897 # They can only occur at the top level, so we can find them by iterating the root's children
4898 $node = $root->getFirstChild();
4900 # Find the target section
4901 if ( $sectionIndex == 0 ) {
4902 # Section zero doesn't nest, level=big
4903 $targetLevel = 1000;
4906 if ( $node->getName() === 'h' ) {
4907 $bits = $node->splitHeading();
4908 if ( $bits['i'] == $sectionIndex ) {
4909 $targetLevel = $bits['level'];
4913 if ( $mode === 'replace' ) {
4914 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4916 $node = $node->getNextSibling();
4922 if ( $mode === 'get' ) {
4929 # Find the end of the section, including nested sections
4931 if ( $node->getName() === 'h' ) {
4932 $bits = $node->splitHeading();
4933 $curLevel = $bits['level'];
4934 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4938 if ( $mode === 'get' ) {
4939 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4941 $node = $node->getNextSibling();
4944 # Write out the remainder (in replace mode only)
4945 if ( $mode === 'replace' ) {
4946 # Output the replacement text
4947 # Add two newlines on -- trailing whitespace in $newText is conventionally
4948 # stripped by the editor, so we need both newlines to restore the paragraph gap
4949 # Only add trailing whitespace if there is newText
4950 if ( $newText != "" ) {
4951 $outText .= $newText . "\n\n";
4955 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4956 $node = $node->getNextSibling();
4960 if ( is_string( $outText ) ) {
4961 # Re-insert stripped tags
4962 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4969 * This function returns the text of a section, specified by a number ($section).
4970 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4971 * the first section before any such heading (section 0).
4973 * If a section contains subsections, these are also returned.
4975 * @param $text String: text to look in
4976 * @param $section String: section identifier
4977 * @param $deftext String: default to return if section is not found
4978 * @return string text of the requested section
4980 public function getSection( $text, $section, $deftext='' ) {
4981 return $this->extractSections( $text, $section, "get", $deftext );
4985 * This function returns $oldtext after the content of the section
4986 * specified by $section has been replaced with $text.
4988 * @param $text String: former text of the article
4989 * @param $section Numeric: section identifier
4990 * @param $text String: replacing text
4991 * #return String: modified text
4993 public function replaceSection( $oldtext, $section, $text ) {
4994 return $this->extractSections( $oldtext, $section, "replace", $text );
4998 * Get the ID of the revision we are parsing
5000 * @return Mixed: integer or null
5002 function getRevisionId() {
5003 return $this->mRevisionId
;
5007 * Get the revision object for $this->mRevisionId
5009 * @return either a Revision object or null
5011 protected function getRevisionObject() {
5012 if ( !is_null( $this->mRevisionObject
) ) {
5013 return $this->mRevisionObject
;
5015 if ( is_null( $this->mRevisionId
) ) {
5019 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5020 return $this->mRevisionObject
;
5024 * Get the timestamp associated with the current revision, adjusted for
5025 * the default server-local timestamp
5027 function getRevisionTimestamp() {
5028 if ( is_null( $this->mRevisionTimestamp
) ) {
5029 wfProfileIn( __METHOD__
);
5031 $revObject = $this->getRevisionObject();
5032 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5034 if( $timestamp !== false ) {
5037 # The cryptic '' timezone parameter tells to use the site-default
5038 # timezone offset instead of the user settings.
5040 # Since this value will be saved into the parser cache, served
5041 # to other users, and potentially even used inside links and such,
5042 # it needs to be consistent for all visitors.
5043 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5046 wfProfileOut( __METHOD__
);
5048 return $this->mRevisionTimestamp
;
5052 * Get the name of the user that edited the last revision
5054 * @return String: user name
5056 function getRevisionUser() {
5057 if( is_null( $this->mRevisionUser
) ) {
5058 $revObject = $this->getRevisionObject();
5060 # if this template is subst: the revision id will be blank,
5061 # so just use the current user's name
5063 $this->mRevisionUser
= $revObject->getUserText();
5064 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5065 $this->mRevisionUser
= $this->getUser()->getName();
5068 return $this->mRevisionUser
;
5072 * Mutator for $mDefaultSort
5074 * @param $sort New value
5076 public function setDefaultSort( $sort ) {
5077 $this->mDefaultSort
= $sort;
5078 $this->mOutput
->setProperty( 'defaultsort', $sort );
5082 * Accessor for $mDefaultSort
5083 * Will use the title/prefixed title if none is set
5087 public function getDefaultSort() {
5088 if ( $this->mDefaultSort
!== false ) {
5089 return $this->mDefaultSort
;
5091 return $this->mTitle
->getCategorySortkey();
5096 * Accessor for $mDefaultSort
5097 * Unlike getDefaultSort(), will return false if none is set
5099 * @return string or false
5101 public function getCustomDefaultSort() {
5102 return $this->mDefaultSort
;
5106 * Try to guess the section anchor name based on a wikitext fragment
5107 * presumably extracted from a heading, for example "Header" from
5110 public function guessSectionNameFromWikiText( $text ) {
5111 # Strip out wikitext links(they break the anchor)
5112 $text = $this->stripSectionName( $text );
5113 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5114 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5118 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5119 * instead. For use in redirects, since IE6 interprets Redirect: headers
5120 * as something other than UTF-8 (apparently?), resulting in breakage.
5122 * @param $text String: The section name
5123 * @return string An anchor
5125 public function guessLegacySectionNameFromWikiText( $text ) {
5126 # Strip out wikitext links(they break the anchor)
5127 $text = $this->stripSectionName( $text );
5128 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5129 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5133 * Strips a text string of wikitext for use in a section anchor
5135 * Accepts a text string and then removes all wikitext from the
5136 * string and leaves only the resultant text (i.e. the result of
5137 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5138 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5139 * to create valid section anchors by mimicing the output of the
5140 * parser when headings are parsed.
5142 * @param $text String: text string to be stripped of wikitext
5143 * for use in a Section anchor
5144 * @return Filtered text string
5146 public function stripSectionName( $text ) {
5147 # Strip internal link markup
5148 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5149 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5151 # Strip external link markup (FIXME: Not Tolerant to blank link text
5152 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5153 # on how many empty links there are on the page - need to figure that out.
5154 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5156 # Parse wikitext quotes (italics & bold)
5157 $text = $this->doQuotes( $text );
5160 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5165 * strip/replaceVariables/unstrip for preprocessor regression testing
5167 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5168 $this->mOptions
= $options;
5169 $this->clearState();
5170 if ( !$title instanceof Title
) {
5171 $title = Title
::newFromText( $title );
5173 $this->mTitle
= $title;
5174 $options->resetUsage();
5175 $this->setOutputType( $outputType );
5176 $text = $this->replaceVariables( $text );
5177 $text = $this->mStripState
->unstripBoth( $text );
5178 $text = Sanitizer
::removeHTMLtags( $text );
5182 function testPst( $text, $title, $options ) {
5184 if ( !$title instanceof Title
) {
5185 $title = Title
::newFromText( $title );
5187 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5190 function testPreprocess( $text, $title, $options ) {
5191 if ( !$title instanceof Title
) {
5192 $title = Title
::newFromText( $title );
5194 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5197 function markerSkipCallback( $s, $callback ) {
5200 while ( $i < strlen( $s ) ) {
5201 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5202 if ( $markerStart === false ) {
5203 $out .= call_user_func( $callback, substr( $s, $i ) );
5206 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5207 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5208 if ( $markerEnd === false ) {
5209 $out .= substr( $s, $markerStart );
5212 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5213 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5221 function serialiseHalfParsedText( $text ) {
5223 $data['text'] = $text;
5225 # First, find all strip markers, and store their
5227 $stripState = new StripState
;
5229 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5230 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5232 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5233 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5235 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5236 $replaceArray = $stripState->general
;
5237 $stripText = $this->mStripState
->general
->data
[$marker];
5238 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5239 $replaceArray = $stripState->nowiki
;
5240 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5242 throw new MWException( "Hanging strip marker: '$marker'." );
5245 $replaceArray->setPair( $marker, $stripText );
5248 $data['stripstate'] = $stripState;
5250 # Now, find all of our links, and store THEIR
5251 # data in an array! :)
5252 $links = array( 'internal' => array(), 'interwiki' => array() );
5256 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5257 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5260 if ( empty( $links['internal'][$ns] ) ) {
5261 $links['internal'][$ns] = array();
5264 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5265 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5266 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5272 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5273 $data = substr( $text, $start_pos );
5274 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5275 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5276 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5279 $data['linkholder'] = $links;
5286 * @param $data Array
5287 * @param $intPrefix String unique identifying prefix
5290 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5291 if ( !$intPrefix ) {
5292 $intPrefix = self
::getRandomString();
5295 # First, extract the strip state.
5296 $stripState = $data['stripstate'];
5297 $this->mStripState
->general
->merge( $stripState->general
);
5298 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5300 # Now, extract the text, and renumber links
5301 $text = $data['text'];
5302 $links = $data['linkholder'];
5305 foreach ( $links['internal'] as $ns => $nsLinks ) {
5306 foreach ( $nsLinks as $key => $entry ) {
5307 $newKey = $intPrefix . '-' . $key;
5308 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5310 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5315 foreach ( $links['interwiki'] as $key => $entry ) {
5316 $newKey = "$intPrefix-$key";
5317 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5319 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5322 # Should be good to go.
5328 * @todo document, briefly.
5332 var $general, $nowiki;
5334 function __construct() {
5335 $this->general
= new ReplacementArray
;
5336 $this->nowiki
= new ReplacementArray
;
5339 function unstripGeneral( $text ) {
5340 wfProfileIn( __METHOD__
);
5343 $text = $this->general
->replace( $text );
5344 } while ( $text !== $oldText );
5345 wfProfileOut( __METHOD__
);
5349 function unstripNoWiki( $text ) {
5350 wfProfileIn( __METHOD__
);
5353 $text = $this->nowiki
->replace( $text );
5354 } while ( $text !== $oldText );
5355 wfProfileOut( __METHOD__
);
5359 function unstripBoth( $text ) {
5360 wfProfileIn( __METHOD__
);
5363 $text = $this->general
->replace( $text );
5364 $text = $this->nowiki
->replace( $text );
5365 } while ( $text !== $oldText );
5366 wfProfileOut( __METHOD__
);
5372 * @todo document, briefly.
5375 class OnlyIncludeReplacer
{
5378 function replace( $matches ) {
5379 if ( substr( $matches[1], -1 ) === "\n" ) {
5380 $this->output
.= substr( $matches[1], 0, -1 );
5382 $this->output
.= $matches[1];