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 if( $this->mOptions
) {
198 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
200 $this->mAutonumber
= 0;
201 $this->mLastSection
= '';
202 $this->mDTopen
= false;
203 $this->mIncludeCount
= array();
204 $this->mStripState
= new StripState
;
205 $this->mArgStack
= false;
206 $this->mInPre
= false;
207 $this->mLinkHolders
= new LinkHolderArray( $this );
209 $this->mRevisionObject
= $this->mRevisionTimestamp
=
210 $this->mRevisionId
= $this->mRevisionUser
= null;
211 $this->mVarCache
= array();
215 * Prefix for temporary replacement strings for the multipass parser.
216 * \x07 should never appear in input as it's disallowed in XML.
217 * Using it at the front also gives us a little extra robustness
218 * since it shouldn't match when butted up against identifier-like
221 * Must not consist of all title characters, or else it will change
222 * the behaviour of <nowiki> in a link.
224 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
225 # Changed to \x7f to allow XML double-parsing -- TS
226 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
229 # Clear these on every parse, bug 4549
230 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
232 $this->mShowToc
= true;
233 $this->mForceTocPosition
= false;
234 $this->mIncludeSizes
= array(
238 $this->mPPNodeCount
= 0;
239 $this->mDefaultSort
= false;
240 $this->mHeadings
= array();
241 $this->mDoubleUnderscores
= array();
242 $this->mExpensiveFunctionCount
= 0;
245 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
246 $this->mPreprocessor
= null;
249 wfRunHooks( 'ParserClearState', array( &$this ) );
250 wfProfileOut( __METHOD__
);
254 * Convert wikitext to HTML
255 * Do not call this function recursively.
257 * @param $text String: text we want to parse
258 * @param $title A title object
259 * @param $options ParserOptions
260 * @param $linestart boolean
261 * @param $clearState boolean
262 * @param $revid Int: number to pass in {{REVISIONID}}
263 * @return ParserOutput a ParserOutput
265 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
267 * First pass--just handle <nowiki> sections, pass the rest off
268 * to internalParse() which does all the real work.
271 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
272 $fname = __METHOD__
.'-' . wfGetCaller();
273 wfProfileIn( __METHOD__
);
274 wfProfileIn( $fname );
276 $this->startExternalParse( $title, $options, self
::OT_HTML
, $clearState );
278 $oldRevisionId = $this->mRevisionId
;
279 $oldRevisionObject = $this->mRevisionObject
;
280 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
281 $oldRevisionUser = $this->mRevisionUser
;
282 if ( $revid !== null ) {
283 $this->mRevisionId
= $revid;
284 $this->mRevisionObject
= null;
285 $this->mRevisionTimestamp
= null;
286 $this->mRevisionUser
= null;
289 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
291 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
292 $text = $this->internalParse( $text );
294 $text = $this->mStripState
->unstripGeneral( $text );
296 # Clean up special characters, only run once, next-to-last before doBlockLevels
298 # french spaces, last one Guillemet-left
299 # only if there is something before the space
300 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
301 # french spaces, Guillemet-right
302 '/(\\302\\253) /' => '\\1 ',
303 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
305 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
307 $text = $this->doBlockLevels( $text, $linestart );
309 $this->replaceLinkHolders( $text );
312 * The page doesn't get language converted if
314 * b) Content isn't converted
315 * c) It's a conversion table
317 if ( !( $wgDisableLangConversion
318 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
319 ||
$this->mTitle
->isConversionTable() ) ) {
321 # The position of the convert() call should not be changed. it
322 # assumes that the links are all replaced and the only thing left
323 # is the <nowiki> mark.
325 $text = $wgContLang->convert( $text );
329 * A converted title will be provided in the output object if title and
330 * content conversion are enabled, the article text does not contain
331 * a conversion-suppressing double-underscore tag, and no
332 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
333 * automatic link conversion.
335 if ( !( $wgDisableLangConversion
336 ||
$wgDisableTitleConversion
337 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
338 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
339 ||
$this->mOutput
->getDisplayTitle() !== false ) )
341 $convruletitle = $wgContLang->getConvRuleTitle();
342 if ( $convruletitle ) {
343 $this->mOutput
->setTitleText( $convruletitle );
345 $titleText = $wgContLang->convertTitle( $title );
346 $this->mOutput
->setTitleText( $titleText );
350 $text = $this->mStripState
->unstripNoWiki( $text );
352 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
354 //!JF Move to its own function
356 $uniq_prefix = $this->mUniqPrefix
;
358 $elements = array_keys( $this->mTransparentTagHooks
);
359 $text = $this->extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
361 foreach ( $matches as $marker => $data ) {
362 list( $element, $content, $params, $tag ) = $data;
363 $tagName = strtolower( $element );
364 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
365 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
369 $this->mStripState
->general
->setPair( $marker, $output );
371 $text = $this->mStripState
->unstripGeneral( $text );
373 $text = Sanitizer
::normalizeCharReferences( $text );
375 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
376 $text = MWTidy
::tidy( $text );
378 # attempt to sanitize at least some nesting problems
379 # (bug #2702 and quite a few others)
381 # ''Something [http://www.cool.com cool''] -->
382 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
383 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
384 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
385 # fix up an anchor inside another anchor, only
386 # at least for a single single nested link (bug 3695)
387 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
388 '\\1\\2</a>\\3</a>\\1\\4</a>',
389 # fix div inside inline elements- doBlockLevels won't wrap a line which
390 # contains a div, so fix it up here; replace
391 # div with escaped text
392 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
393 '\\1\\3<div\\5>\\6</div>\\8\\9',
394 # remove empty italic or bold tag pairs, some
395 # introduced by rules above
396 '/<([bi])><\/\\1>/' => '',
399 $text = preg_replace(
400 array_keys( $tidyregs ),
401 array_values( $tidyregs ),
404 global $wgExpensiveParserFunctionLimit;
405 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
406 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
409 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
411 # Information on include size limits, for the benefit of users who try to skirt them
412 if ( $this->mOptions
->getEnableLimitReport() ) {
413 $max = $this->mOptions
->getMaxIncludeSize();
414 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
416 "NewPP limit report\n" .
417 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
418 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
419 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
421 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
422 $text .= "\n<!-- \n$limitReport-->\n";
424 $this->mOutput
->setText( $text );
426 $this->mRevisionId
= $oldRevisionId;
427 $this->mRevisionObject
= $oldRevisionObject;
428 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
429 $this->mRevisionUser
= $oldRevisionUser;
430 wfProfileOut( $fname );
431 wfProfileOut( __METHOD__
);
433 return $this->mOutput
;
437 * Recursive parser entry point that can be called from an extension tag
440 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
442 * @param $text String: text extension wants to have parsed
443 * @param $frame PPFrame: The frame to use for expanding any template variables
445 function recursiveTagParse( $text, $frame=false ) {
446 wfProfileIn( __METHOD__
);
447 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
448 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
449 $text = $this->internalParse( $text, false, $frame );
450 wfProfileOut( __METHOD__
);
455 * Expand templates and variables in the text, producing valid, static wikitext.
456 * Also removes comments.
458 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
459 wfProfileIn( __METHOD__
);
460 $this->startExternalParse( $title, $options, self
::OT_PREPROCESS
, true );
461 if ( $revid !== null ) {
462 $this->mRevisionId
= $revid;
464 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
465 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
466 $text = $this->replaceVariables( $text );
467 $text = $this->mStripState
->unstripBoth( $text );
468 wfProfileOut( __METHOD__
);
473 * Process the wikitext for the ?preload= feature. (bug 5210)
475 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
476 * comments, templates, arguments, tags hooks and parser functions are untouched.
478 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
479 # Parser (re)initialisation
480 $this->startExternalParse( $title, $options, self
::OT_PLAIN
, true );
482 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
483 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
484 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
488 * Get a random string
493 static private function getRandomString() {
494 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
498 * Set the current user.
499 * Should only be used when doing pre-save transform.
501 * @param $user Mixed: User object or null (to reset)
503 function setUser( $user ) {
504 $this->mUser
= $user;
508 * Accessor for mUniqPrefix.
512 public function uniqPrefix() {
513 if ( !isset( $this->mUniqPrefix
) ) {
514 # @todo Fixme: this is probably *horribly wrong*
515 # LanguageConverter seems to want $wgParser's uniqPrefix, however
516 # if this is called for a parser cache hit, the parser may not
517 # have ever been initialized in the first place.
518 # Not really sure what the heck is supposed to be going on here.
520 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
522 return $this->mUniqPrefix
;
526 * Set the context title
528 function setTitle( $t ) {
529 if ( !$t ||
$t instanceof FakeTitle
) {
530 $t = Title
::newFromText( 'NO TITLE' );
533 if ( strval( $t->getFragment() ) !== '' ) {
534 # Strip the fragment to avoid various odd effects
535 $this->mTitle
= clone $t;
536 $this->mTitle
->setFragment( '' );
543 * Accessor for the Title object
545 * @return Title object
547 function getTitle() {
548 return $this->mTitle
;
552 * Accessor/mutator for the Title object
554 * @param $x New Title object or null to just get the current one
555 * @return Title object
557 function Title( $x = null ) {
558 return wfSetVar( $this->mTitle
, $x );
562 * Set the output type
564 * @param $ot Integer: new value
566 function setOutputType( $ot ) {
567 $this->mOutputType
= $ot;
570 'html' => $ot == self
::OT_HTML
,
571 'wiki' => $ot == self
::OT_WIKI
,
572 'pre' => $ot == self
::OT_PREPROCESS
,
573 'plain' => $ot == self
::OT_PLAIN
,
578 * Accessor/mutator for the output type
580 * @param $x New value or null to just get the current one
583 function OutputType( $x = null ) {
584 return wfSetVar( $this->mOutputType
, $x );
588 * Get the ParserOutput object
590 * @return ParserOutput object
592 function getOutput() {
593 return $this->mOutput
;
597 * Get the ParserOptions object
599 * @return ParserOptions object
601 function getOptions() {
602 return $this->mOptions
;
606 * Accessor/mutator for the ParserOptions object
608 * @param $x New value or null to just get the current one
609 * @return Current ParserOptions object
611 function Options( $x = null ) {
612 return wfSetVar( $this->mOptions
, $x );
615 function nextLinkID() {
616 return $this->mLinkID++
;
619 function getFunctionLang() {
620 global $wgLang, $wgContLang;
622 $target = $this->mOptions
->getTargetLanguage();
623 if ( $target !== null ) {
626 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
631 * Get a User object either from $this->mUser, if set, or from the
632 * ParserOptions object otherwise
634 * @return User object
637 if ( !is_null( $this->mUser
) ) {
640 return $this->mOptions
->getUser();
644 * Get a preprocessor object
646 * @return Preprocessor instance
648 function getPreprocessor() {
649 if ( !isset( $this->mPreprocessor
) ) {
650 $class = $this->mPreprocessorClass
;
651 $this->mPreprocessor
= new $class( $this );
653 return $this->mPreprocessor
;
657 * Replaces all occurrences of HTML-style comments and the given tags
658 * in the text with a random marker and returns the next text. The output
659 * parameter $matches will be an associative array filled with data in
661 * 'UNIQ-xxxxx' => array(
664 * array( 'param' => 'x' ),
665 * '<element param="x">tag content</element>' ) )
667 * @param $elements list of element names. Comments are always extracted.
668 * @param $text Source text string.
669 * @param $matches Out parameter, Array: extracted tags
670 * @param $uniq_prefix
671 * @return String: stripped text
675 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
680 $taglist = implode( '|', $elements );
681 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
683 while ( $text != '' ) {
684 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
686 if ( count( $p ) < 5 ) {
689 if ( count( $p ) > 5 ) {
703 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
704 $stripped .= $marker;
706 if ( $close === '/>' ) {
707 # Empty element tag, <tag />
712 if ( $element === '!--' ) {
715 $end = "/(<\\/$element\\s*>)/i";
717 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
719 if ( count( $q ) < 3 ) {
720 # No end tag -- let it run out to the end of the text.
729 $matches[$marker] = array( $element,
731 Sanitizer
::decodeTagAttributes( $attributes ),
732 "<$element$attributes$close$content$tail" );
738 * Get a list of strippable XML-like elements
740 function getStripList() {
741 return $this->mStripList
;
745 * @deprecated use replaceVariables
747 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
752 * Restores pre, math, and other extensions removed by strip()
754 * always call unstripNoWiki() after this one
756 * @deprecated use $this->mStripState->unstrip()
758 function unstrip( $text, $state ) {
759 return $state->unstripGeneral( $text );
763 * Always call this after unstrip() to preserve the order
766 * @deprecated use $this->mStripState->unstrip()
768 function unstripNoWiki( $text, $state ) {
769 return $state->unstripNoWiki( $text );
773 * @deprecated use $this->mStripState->unstripBoth()
775 function unstripForHTML( $text ) {
776 return $this->mStripState
->unstripBoth( $text );
780 * Add an item to the strip state
781 * Returns the unique tag which must be inserted into the stripped text
782 * The tag will be replaced with the original text in unstrip()
786 function insertStripItem( $text ) {
787 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
788 $this->mMarkerIndex++
;
789 $this->mStripState
->general
->setPair( $rnd, $text );
794 * Interface with html tidy
795 * @deprecated Use MWTidy::tidy()
797 public static function tidy( $text ) {
798 wfDeprecated( __METHOD__
);
799 return MWTidy
::tidy( $text );
803 * parse the wiki syntax used to render tables
807 function doTableStuff( $text ) {
808 wfProfileIn( __METHOD__
);
810 $lines = StringUtils
::explode( "\n", $text );
812 $td_history = array(); # Is currently a td tag open?
813 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
814 $tr_history = array(); # Is currently a tr tag open?
815 $tr_attributes = array(); # history of tr attributes
816 $has_opened_tr = array(); # Did this table open a <tr> element?
817 $indent_level = 0; # indent level of the table
819 foreach ( $lines as $outLine ) {
820 $line = trim( $outLine );
822 if ( $line === '' ) { # empty line, go to next line
823 $out .= $outLine."\n";
827 $first_character = $line[0];
830 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
831 # First check if we are starting a new table
832 $indent_level = strlen( $matches[1] );
834 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
835 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
837 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
838 array_push( $td_history , false );
839 array_push( $last_tag_history , '' );
840 array_push( $tr_history , false );
841 array_push( $tr_attributes , '' );
842 array_push( $has_opened_tr , false );
843 } elseif ( count( $td_history ) == 0 ) {
844 # Don't do any of the following
845 $out .= $outLine."\n";
847 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
848 # We are ending a table
849 $line = '</table>' . substr( $line , 2 );
850 $last_tag = array_pop( $last_tag_history );
852 if ( !array_pop( $has_opened_tr ) ) {
853 $line = "<tr><td></td></tr>{$line}";
856 if ( array_pop( $tr_history ) ) {
857 $line = "</tr>{$line}";
860 if ( array_pop( $td_history ) ) {
861 $line = "</{$last_tag}>{$line}";
863 array_pop( $tr_attributes );
864 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
865 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
866 # Now we have a table row
867 $line = preg_replace( '#^\|-+#', '', $line );
869 # Whats after the tag is now only attributes
870 $attributes = $this->mStripState
->unstripBoth( $line );
871 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
872 array_pop( $tr_attributes );
873 array_push( $tr_attributes, $attributes );
876 $last_tag = array_pop( $last_tag_history );
877 array_pop( $has_opened_tr );
878 array_push( $has_opened_tr , true );
880 if ( array_pop( $tr_history ) ) {
884 if ( array_pop( $td_history ) ) {
885 $line = "</{$last_tag}>{$line}";
889 array_push( $tr_history , false );
890 array_push( $td_history , false );
891 array_push( $last_tag_history , '' );
892 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
893 # This might be cell elements, td, th or captions
894 if ( substr( $line , 0 , 2 ) === '|+' ) {
895 $first_character = '+';
896 $line = substr( $line , 1 );
899 $line = substr( $line , 1 );
901 if ( $first_character === '!' ) {
902 $line = str_replace( '!!' , '||' , $line );
905 # Split up multiple cells on the same line.
906 # FIXME : This can result in improper nesting of tags processed
907 # by earlier parser steps, but should avoid splitting up eg
908 # attribute values containing literal "||".
909 $cells = StringUtils
::explodeMarkup( '||' , $line );
913 # Loop through each table cell
914 foreach ( $cells as $cell ) {
916 if ( $first_character !== '+' ) {
917 $tr_after = array_pop( $tr_attributes );
918 if ( !array_pop( $tr_history ) ) {
919 $previous = "<tr{$tr_after}>\n";
921 array_push( $tr_history , true );
922 array_push( $tr_attributes , '' );
923 array_pop( $has_opened_tr );
924 array_push( $has_opened_tr , true );
927 $last_tag = array_pop( $last_tag_history );
929 if ( array_pop( $td_history ) ) {
930 $previous = "</{$last_tag}>\n{$previous}";
933 if ( $first_character === '|' ) {
935 } elseif ( $first_character === '!' ) {
937 } elseif ( $first_character === '+' ) {
938 $last_tag = 'caption';
943 array_push( $last_tag_history , $last_tag );
945 # A cell could contain both parameters and data
946 $cell_data = explode( '|' , $cell , 2 );
948 # Bug 553: Note that a '|' inside an invalid link should not
949 # be mistaken as delimiting cell parameters
950 if ( strpos( $cell_data[0], '[[' ) !== false ) {
951 $cell = "{$previous}<{$last_tag}>{$cell}";
952 } elseif ( count( $cell_data ) == 1 ) {
953 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
955 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
956 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
957 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
961 array_push( $td_history , true );
964 $out .= $outLine . "\n";
967 # Closing open td, tr && table
968 while ( count( $td_history ) > 0 ) {
969 if ( array_pop( $td_history ) ) {
972 if ( array_pop( $tr_history ) ) {
975 if ( !array_pop( $has_opened_tr ) ) {
976 $out .= "<tr><td></td></tr>\n" ;
979 $out .= "</table>\n";
982 # Remove trailing line-ending (b/c)
983 if ( substr( $out, -1 ) === "\n" ) {
984 $out = substr( $out, 0, -1 );
987 # special case: don't return empty table
988 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
992 wfProfileOut( __METHOD__
);
998 * Helper function for parse() that transforms wiki markup into
999 * HTML. Only called for $mOutputType == self::OT_HTML.
1003 function internalParse( $text, $isMain = true, $frame=false ) {
1004 wfProfileIn( __METHOD__
);
1008 # Hook to suspend the parser in this state
1009 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1010 wfProfileOut( __METHOD__
);
1014 # if $frame is provided, then use $frame for replacing any variables
1016 # use frame depth to infer how include/noinclude tags should be handled
1017 # depth=0 means this is the top-level document; otherwise it's an included document
1018 if ( !$frame->depth
) {
1021 $flag = Parser
::PTD_FOR_INCLUSION
;
1023 $dom = $this->preprocessToDom( $text, $flag );
1024 $text = $frame->expand( $dom );
1026 # if $frame is not provided, then use old-style replaceVariables
1027 $text = $this->replaceVariables( $text );
1030 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1031 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1033 # Tables need to come after variable replacement for things to work
1034 # properly; putting them before other transformations should keep
1035 # exciting things like link expansions from showing up in surprising
1037 $text = $this->doTableStuff( $text );
1039 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1041 $text = $this->doDoubleUnderscore( $text );
1043 $text = $this->doHeadings( $text );
1044 if ( $this->mOptions
->getUseDynamicDates() ) {
1045 $df = DateFormatter
::getInstance();
1046 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1048 $text = $this->replaceInternalLinks( $text );
1049 $text = $this->doAllQuotes( $text );
1050 $text = $this->replaceExternalLinks( $text );
1052 # replaceInternalLinks may sometimes leave behind
1053 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1054 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1056 $text = $this->doMagicLinks( $text );
1057 $text = $this->formatHeadings( $text, $origText, $isMain );
1059 wfProfileOut( __METHOD__
);
1064 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1065 * magic external links.
1070 function doMagicLinks( $text ) {
1071 wfProfileIn( __METHOD__
);
1072 $prots = $this->mUrlProtocols
;
1073 $urlChar = self
::EXT_LINK_URL_CLASS
;
1074 $text = preg_replace_callback(
1076 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1077 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1078 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1079 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1080 ISBN\s+(\b # m[5]: ISBN, capture number
1081 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1082 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1083 [0-9Xx] # check digit
1085 )!x', array( &$this, 'magicLinkCallback' ), $text );
1086 wfProfileOut( __METHOD__
);
1090 function magicLinkCallback( $m ) {
1091 if ( isset( $m[1] ) && $m[1] !== '' ) {
1094 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1097 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1098 # Free external link
1099 return $this->makeFreeExternalLink( $m[0] );
1100 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1102 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1105 $CssClass = 'mw-magiclink-rfc';
1107 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1109 $urlmsg = 'pubmedurl';
1110 $CssClass = 'mw-magiclink-pmid';
1113 throw new MWException( __METHOD__
.': unrecognised match type "' .
1114 substr( $m[0], 0, 20 ) . '"' );
1116 $url = wfMsgForContent( $urlmsg, $id );
1117 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1118 return $sk->makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1119 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1122 $num = strtr( $isbn, array(
1127 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1129 $titleObj->escapeLocalUrl() .
1130 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1137 * Make a free external link, given a user-supplied URL
1141 function makeFreeExternalLink( $url ) {
1143 wfProfileIn( __METHOD__
);
1145 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1148 # The characters '<' and '>' (which were escaped by
1149 # removeHTMLtags()) should not be included in
1150 # URLs, per RFC 2396.
1152 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1153 $trail = substr( $url, $m2[0][1] ) . $trail;
1154 $url = substr( $url, 0, $m2[0][1] );
1157 # Move trailing punctuation to $trail
1159 # If there is no left bracket, then consider right brackets fair game too
1160 if ( strpos( $url, '(' ) === false ) {
1164 $numSepChars = strspn( strrev( $url ), $sep );
1165 if ( $numSepChars ) {
1166 $trail = substr( $url, -$numSepChars ) . $trail;
1167 $url = substr( $url, 0, -$numSepChars );
1170 $url = Sanitizer
::cleanUrl( $url );
1172 # Is this an external image?
1173 $text = $this->maybeMakeExternalImage( $url );
1174 if ( $text === false ) {
1175 # Not an image, make a link
1176 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1177 $this->getExternalLinkAttribs( $url ) );
1178 # Register it in the output object...
1179 # Replace unnecessary URL escape codes with their equivalent characters
1180 $pasteurized = self
::replaceUnusualEscapes( $url );
1181 $this->mOutput
->addExternalLink( $pasteurized );
1183 wfProfileOut( __METHOD__
);
1184 return $text . $trail;
1189 * Parse headers and return html
1193 function doHeadings( $text ) {
1194 wfProfileIn( __METHOD__
);
1195 for ( $i = 6; $i >= 1; --$i ) {
1196 $h = str_repeat( '=', $i );
1197 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1198 "<h$i>\\1</h$i>", $text );
1200 wfProfileOut( __METHOD__
);
1205 * Replace single quotes with HTML markup
1207 * @return string the altered text
1209 function doAllQuotes( $text ) {
1210 wfProfileIn( __METHOD__
);
1212 $lines = StringUtils
::explode( "\n", $text );
1213 foreach ( $lines as $line ) {
1214 $outtext .= $this->doQuotes( $line ) . "\n";
1216 $outtext = substr( $outtext, 0,-1 );
1217 wfProfileOut( __METHOD__
);
1222 * Helper function for doAllQuotes()
1224 public function doQuotes( $text ) {
1225 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1226 if ( count( $arr ) == 1 ) {
1229 # First, do some preliminary work. This may shift some apostrophes from
1230 # being mark-up to being text. It also counts the number of occurrences
1231 # of bold and italics mark-ups.
1234 for ( $i = 0; $i < count( $arr ); $i++
) {
1235 if ( ( $i %
2 ) == 1 ) {
1236 # If there are ever four apostrophes, assume the first is supposed to
1237 # be text, and the remaining three constitute mark-up for bold text.
1238 if ( strlen( $arr[$i] ) == 4 ) {
1241 } elseif ( strlen( $arr[$i] ) > 5 ) {
1242 # If there are more than 5 apostrophes in a row, assume they're all
1243 # text except for the last 5.
1244 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1247 # Count the number of occurrences of bold and italics mark-ups.
1248 # We are not counting sequences of five apostrophes.
1249 if ( strlen( $arr[$i] ) == 2 ) {
1251 } elseif ( strlen( $arr[$i] ) == 3 ) {
1253 } elseif ( strlen( $arr[$i] ) == 5 ) {
1260 # If there is an odd number of both bold and italics, it is likely
1261 # that one of the bold ones was meant to be an apostrophe followed
1262 # by italics. Which one we cannot know for certain, but it is more
1263 # likely to be one that has a single-letter word before it.
1264 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1266 $firstsingleletterword = -1;
1267 $firstmultiletterword = -1;
1269 foreach ( $arr as $r ) {
1270 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1271 $x1 = substr( $arr[$i-1], -1 );
1272 $x2 = substr( $arr[$i-1], -2, 1 );
1273 if ( $x1 === ' ' ) {
1274 if ( $firstspace == -1 ) {
1277 } elseif ( $x2 === ' ') {
1278 if ( $firstsingleletterword == -1 ) {
1279 $firstsingleletterword = $i;
1282 if ( $firstmultiletterword == -1 ) {
1283 $firstmultiletterword = $i;
1290 # If there is a single-letter word, use it!
1291 if ( $firstsingleletterword > -1 ) {
1292 $arr[$firstsingleletterword] = "''";
1293 $arr[$firstsingleletterword-1] .= "'";
1294 } elseif ( $firstmultiletterword > -1 ) {
1295 # If not, but there's a multi-letter word, use that one.
1296 $arr[$firstmultiletterword] = "''";
1297 $arr[$firstmultiletterword-1] .= "'";
1298 } elseif ( $firstspace > -1 ) {
1299 # ... otherwise use the first one that has neither.
1300 # (notice that it is possible for all three to be -1 if, for example,
1301 # there is only one pentuple-apostrophe in the line)
1302 $arr[$firstspace] = "''";
1303 $arr[$firstspace-1] .= "'";
1307 # Now let's actually convert our apostrophic mush to HTML!
1312 foreach ( $arr as $r ) {
1313 if ( ( $i %
2 ) == 0 ) {
1314 if ( $state === 'both' ) {
1320 if ( strlen( $r ) == 2 ) {
1321 if ( $state === 'i' ) {
1322 $output .= '</i>'; $state = '';
1323 } elseif ( $state === 'bi' ) {
1324 $output .= '</i>'; $state = 'b';
1325 } elseif ( $state === 'ib' ) {
1326 $output .= '</b></i><b>'; $state = 'b';
1327 } elseif ( $state === 'both' ) {
1328 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1329 } else { # $state can be 'b' or ''
1330 $output .= '<i>'; $state .= 'i';
1332 } elseif ( strlen( $r ) == 3 ) {
1333 if ( $state === 'b' ) {
1334 $output .= '</b>'; $state = '';
1335 } elseif ( $state === 'bi' ) {
1336 $output .= '</i></b><i>'; $state = 'i';
1337 } elseif ( $state === 'ib' ) {
1338 $output .= '</b>'; $state = 'i';
1339 } elseif ( $state === 'both' ) {
1340 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1341 } else { # $state can be 'i' or ''
1342 $output .= '<b>'; $state .= 'b';
1344 } elseif ( strlen( $r ) == 5 ) {
1345 if ( $state === 'b' ) {
1346 $output .= '</b><i>'; $state = 'i';
1347 } elseif ( $state === 'i' ) {
1348 $output .= '</i><b>'; $state = 'b';
1349 } elseif ( $state === 'bi' ) {
1350 $output .= '</i></b>'; $state = '';
1351 } elseif ( $state === 'ib' ) {
1352 $output .= '</b></i>'; $state = '';
1353 } elseif ( $state === 'both' ) {
1354 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1355 } else { # ($state == '')
1356 $buffer = ''; $state = 'both';
1362 # Now close all remaining tags. Notice that the order is important.
1363 if ( $state === 'b' ||
$state === 'ib' ) {
1366 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1369 if ( $state === 'bi' ) {
1372 # There might be lonely ''''', so make sure we have a buffer
1373 if ( $state === 'both' && $buffer ) {
1374 $output .= '<b><i>'.$buffer.'</i></b>';
1381 * Replace external links (REL)
1383 * Note: this is all very hackish and the order of execution matters a lot.
1384 * Make sure to run maintenance/parserTests.php if you change this code.
1388 function replaceExternalLinks( $text ) {
1390 wfProfileIn( __METHOD__
);
1392 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1394 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1395 $s = array_shift( $bits );
1398 while ( $i<count( $bits ) ) {
1400 $protocol = $bits[$i++
];
1401 $text = $bits[$i++
];
1402 $trail = $bits[$i++
];
1404 # The characters '<' and '>' (which were escaped by
1405 # removeHTMLtags()) should not be included in
1406 # URLs, per RFC 2396.
1408 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1409 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1410 $url = substr( $url, 0, $m2[0][1] );
1413 # If the link text is an image URL, replace it with an <img> tag
1414 # This happened by accident in the original parser, but some people used it extensively
1415 $img = $this->maybeMakeExternalImage( $text );
1416 if ( $img !== false ) {
1422 # Set linktype for CSS - if URL==text, link is essentially free
1423 $linktype = ( $text === $url ) ?
'free' : 'text';
1425 # No link text, e.g. [http://domain.tld/some.link]
1426 if ( $text == '' ) {
1427 # Autonumber if allowed. See bug #5918
1428 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1429 $langObj = $this->getFunctionLang();
1430 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1431 $linktype = 'autonumber';
1433 # Otherwise just use the URL
1434 $text = htmlspecialchars( $url );
1438 # Have link text, e.g. [http://domain.tld/some.link text]s
1440 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1443 $text = $wgContLang->markNoConversion( $text );
1445 $url = Sanitizer
::cleanUrl( $url );
1447 # Use the encoded URL
1448 # This means that users can paste URLs directly into the text
1449 # Funny characters like ö aren't valid in URLs anyway
1450 # This was changed in August 2004
1451 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1452 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1454 # Register link in the output object.
1455 # Replace unnecessary URL escape codes with the referenced character
1456 # This prevents spammers from hiding links from the filters
1457 $pasteurized = self
::replaceUnusualEscapes( $url );
1458 $this->mOutput
->addExternalLink( $pasteurized );
1461 wfProfileOut( __METHOD__
);
1466 * Get an associative array of additional HTML attributes appropriate for a
1467 * particular external link. This currently may include rel => nofollow
1468 * (depending on configuration, namespace, and the URL's domain) and/or a
1469 * target attribute (depending on configuration).
1471 * @param $url String: optional URL, to extract the domain from for rel =>
1472 * nofollow if appropriate
1473 * @return Array: associative array of HTML attributes
1475 function getExternalLinkAttribs( $url = false ) {
1477 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1478 $ns = $this->mTitle
->getNamespace();
1479 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1480 $attribs['rel'] = 'nofollow';
1482 global $wgNoFollowDomainExceptions;
1483 if ( $wgNoFollowDomainExceptions ) {
1484 $bits = wfParseUrl( $url );
1485 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1486 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1487 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1488 unset( $attribs['rel'] );
1495 if ( $this->mOptions
->getExternalLinkTarget() ) {
1496 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1503 * Replace unusual URL escape codes with their equivalent characters
1505 * @param $url String
1508 * @todo This can merge genuinely required bits in the path or query string,
1509 * breaking legit URLs. A proper fix would treat the various parts of
1510 * the URL differently; as a workaround, just use the output for
1511 * statistical records, not for actual linking/output.
1513 static function replaceUnusualEscapes( $url ) {
1514 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1515 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1519 * Callback function used in replaceUnusualEscapes().
1520 * Replaces unusual URL escape codes with their equivalent character
1522 private static function replaceUnusualEscapesCallback( $matches ) {
1523 $char = urldecode( $matches[0] );
1524 $ord = ord( $char );
1525 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1526 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1527 # No, shouldn't be escaped
1530 # Yes, leave it escaped
1536 * make an image if it's allowed, either through the global
1537 * option, through the exception, or through the on-wiki whitelist
1540 function maybeMakeExternalImage( $url ) {
1541 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1542 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1543 $imagesexception = !empty( $imagesfrom );
1545 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1546 if ( $imagesexception && is_array( $imagesfrom ) ) {
1547 $imagematch = false;
1548 foreach ( $imagesfrom as $match ) {
1549 if ( strpos( $url, $match ) === 0 ) {
1554 } elseif ( $imagesexception ) {
1555 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1557 $imagematch = false;
1559 if ( $this->mOptions
->getAllowExternalImages()
1560 ||
( $imagesexception && $imagematch ) ) {
1561 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1563 $text = $sk->makeExternalImage( $url );
1566 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1567 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1568 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1569 foreach ( $whitelist as $entry ) {
1570 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1571 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1574 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1575 # Image matches a whitelist entry
1576 $text = $sk->makeExternalImage( $url );
1585 * Process [[ ]] wikilinks
1586 * @return String: processed text
1590 function replaceInternalLinks( $s ) {
1591 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1596 * Process [[ ]] wikilinks (RIL)
1597 * @return LinkHolderArray
1601 function replaceInternalLinks2( &$s ) {
1604 wfProfileIn( __METHOD__
);
1606 wfProfileIn( __METHOD__
.'-setup' );
1607 static $tc = FALSE, $e1, $e1_img;
1608 # the % is needed to support urlencoded titles as well
1610 $tc = Title
::legalChars() . '#%';
1611 # Match a link having the form [[namespace:link|alternate]]trail
1612 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1613 # Match cases where there is no "]]", which might still be images
1614 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1617 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1618 $holders = new LinkHolderArray( $this );
1620 # split the entire text string on occurences of [[
1621 $a = StringUtils
::explode( '[[', ' ' . $s );
1622 # get the first element (all text up to first [[), and remove the space we added
1625 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1626 $s = substr( $s, 1 );
1628 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1630 if ( $useLinkPrefixExtension ) {
1631 # Match the end of a line for a word that's not followed by whitespace,
1632 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1633 $e2 = wfMsgForContent( 'linkprefix' );
1636 if ( is_null( $this->mTitle
) ) {
1637 wfProfileOut( __METHOD__
.'-setup' );
1638 wfProfileOut( __METHOD__
);
1639 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1641 $nottalk = !$this->mTitle
->isTalkPage();
1643 if ( $useLinkPrefixExtension ) {
1645 if ( preg_match( $e2, $s, $m ) ) {
1646 $first_prefix = $m[2];
1648 $first_prefix = false;
1654 if ( $wgContLang->hasVariants() ) {
1655 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1657 $selflink = array( $this->mTitle
->getPrefixedText() );
1659 $useSubpages = $this->areSubpagesAllowed();
1660 wfProfileOut( __METHOD__
.'-setup' );
1662 # Loop for each link
1663 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1664 # Check for excessive memory usage
1665 if ( $holders->isBig() ) {
1667 # Do the existence check, replace the link holders and clear the array
1668 $holders->replace( $s );
1672 if ( $useLinkPrefixExtension ) {
1673 wfProfileIn( __METHOD__
.'-prefixhandling' );
1674 if ( preg_match( $e2, $s, $m ) ) {
1681 if ( $first_prefix ) {
1682 $prefix = $first_prefix;
1683 $first_prefix = false;
1685 wfProfileOut( __METHOD__
.'-prefixhandling' );
1688 $might_be_img = false;
1690 wfProfileIn( __METHOD__
."-e1" );
1691 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1693 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1694 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1695 # the real problem is with the $e1 regex
1698 # Still some problems for cases where the ] is meant to be outside punctuation,
1699 # and no image is in sight. See bug 2095.
1701 if ( $text !== '' &&
1702 substr( $m[3], 0, 1 ) === ']' &&
1703 strpos( $text, '[' ) !== false
1706 $text .= ']'; # so that replaceExternalLinks($text) works later
1707 $m[3] = substr( $m[3], 1 );
1709 # fix up urlencoded title texts
1710 if ( strpos( $m[1], '%' ) !== false ) {
1711 # Should anchors '#' also be rejected?
1712 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1715 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1716 $might_be_img = true;
1718 if ( strpos( $m[1], '%' ) !== false ) {
1719 $m[1] = rawurldecode( $m[1] );
1722 } else { # Invalid form; output directly
1723 $s .= $prefix . '[[' . $line ;
1724 wfProfileOut( __METHOD__
."-e1" );
1727 wfProfileOut( __METHOD__
."-e1" );
1728 wfProfileIn( __METHOD__
."-misc" );
1730 # Don't allow internal links to pages containing
1731 # PROTO: where PROTO is a valid URL protocol; these
1732 # should be external links.
1733 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1734 $s .= $prefix . '[[' . $line ;
1735 wfProfileOut( __METHOD__
."-misc" );
1739 # Make subpage if necessary
1740 if ( $useSubpages ) {
1741 $link = $this->maybeDoSubpageLink( $m[1], $text );
1746 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1748 # Strip off leading ':'
1749 $link = substr( $link, 1 );
1752 wfProfileOut( __METHOD__
."-misc" );
1753 wfProfileIn( __METHOD__
."-title" );
1754 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1755 if ( $nt === null ) {
1756 $s .= $prefix . '[[' . $line;
1757 wfProfileOut( __METHOD__
."-title" );
1761 $ns = $nt->getNamespace();
1762 $iw = $nt->getInterWiki();
1763 wfProfileOut( __METHOD__
."-title" );
1765 if ( $might_be_img ) { # if this is actually an invalid link
1766 wfProfileIn( __METHOD__
."-might_be_img" );
1767 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1770 # look at the next 'line' to see if we can close it there
1772 $next_line = $a->current();
1773 if ( $next_line === false ||
$next_line === null ) {
1776 $m = explode( ']]', $next_line, 3 );
1777 if ( count( $m ) == 3 ) {
1778 # the first ]] closes the inner link, the second the image
1780 $text .= "[[{$m[0]}]]{$m[1]}";
1783 } elseif ( count( $m ) == 2 ) {
1784 # if there's exactly one ]] that's fine, we'll keep looking
1785 $text .= "[[{$m[0]}]]{$m[1]}";
1787 # if $next_line is invalid too, we need look no further
1788 $text .= '[[' . $next_line;
1793 # we couldn't find the end of this imageLink, so output it raw
1794 # but don't ignore what might be perfectly normal links in the text we've examined
1795 $holders->merge( $this->replaceInternalLinks2( $text ) );
1796 $s .= "{$prefix}[[$link|$text";
1797 # note: no $trail, because without an end, there *is* no trail
1798 wfProfileOut( __METHOD__
."-might_be_img" );
1801 } else { # it's not an image, so output it raw
1802 $s .= "{$prefix}[[$link|$text";
1803 # note: no $trail, because without an end, there *is* no trail
1804 wfProfileOut( __METHOD__
."-might_be_img" );
1807 wfProfileOut( __METHOD__
."-might_be_img" );
1810 $wasblank = ( $text == '' );
1814 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1815 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1816 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1817 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1818 $text = $this->doQuotes( $text );
1821 # Link not escaped by : , create the various objects
1825 wfProfileIn( __METHOD__
."-interwiki" );
1826 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1827 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1828 $s = rtrim( $s . $prefix );
1829 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1830 wfProfileOut( __METHOD__
."-interwiki" );
1833 wfProfileOut( __METHOD__
."-interwiki" );
1835 if ( $ns == NS_FILE
) {
1836 wfProfileIn( __METHOD__
."-image" );
1837 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1839 # if no parameters were passed, $text
1840 # becomes something like "File:Foo.png",
1841 # which we don't want to pass on to the
1845 # recursively parse links inside the image caption
1846 # actually, this will parse them in any other parameters, too,
1847 # but it might be hard to fix that, and it doesn't matter ATM
1848 $text = $this->replaceExternalLinks( $text );
1849 $holders->merge( $this->replaceInternalLinks2( $text ) );
1851 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1852 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1854 $s .= $prefix . $trail;
1856 $this->mOutput
->addImage( $nt->getDBkey() );
1857 wfProfileOut( __METHOD__
."-image" );
1862 if ( $ns == NS_CATEGORY
) {
1863 wfProfileIn( __METHOD__
."-category" );
1864 $s = rtrim( $s . "\n" ); # bug 87
1867 $sortkey = $this->getDefaultSort();
1871 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1872 $sortkey = str_replace( "\n", '', $sortkey );
1873 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1874 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1877 * Strip the whitespace Category links produce, see bug 87
1878 * @todo We might want to use trim($tmp, "\n") here.
1880 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1882 wfProfileOut( __METHOD__
."-category" );
1887 # Self-link checking
1888 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1889 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1890 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1895 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1896 # FIXME: Should do batch file existence checks, see comment below
1897 if ( $ns == NS_MEDIA
) {
1898 wfProfileIn( __METHOD__
."-media" );
1899 # Give extensions a chance to select the file revision for us
1900 $skip = $time = false;
1901 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1903 $link = $sk->link( $nt );
1905 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1907 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1908 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1909 $this->mOutput
->addImage( $nt->getDBkey() );
1910 wfProfileOut( __METHOD__
."-media" );
1914 wfProfileIn( __METHOD__
."-always_known" );
1915 # Some titles, such as valid special pages or files in foreign repos, should
1916 # be shown as bluelinks even though they're not included in the page table
1918 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1919 # batch file existence checks for NS_FILE and NS_MEDIA
1920 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1921 $this->mOutput
->addLink( $nt );
1922 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1924 # Links will be added to the output link list after checking
1925 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1927 wfProfileOut( __METHOD__
."-always_known" );
1929 wfProfileOut( __METHOD__
);
1934 * Make a link placeholder. The text returned can be later resolved to a real link with
1935 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1936 * parsing of interwiki links, and secondly to allow all existence checks and
1937 * article length checks (for stub links) to be bundled into a single query.
1941 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1942 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1946 * Render a forced-blue link inline; protect against double expansion of
1947 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1948 * Since this little disaster has to split off the trail text to avoid
1949 * breaking URLs in the following text without breaking trails on the
1950 * wiki links, it's been made into a horrible function.
1953 * @param $text String
1954 * @param $query String
1955 * @param $trail String
1956 * @param $prefix String
1957 * @return String: HTML-wikitext mix oh yuck
1959 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1960 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1961 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1962 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1963 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1964 return $this->armorLinks( $link ) . $trail;
1968 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1969 * going to go through further parsing steps before inline URL expansion.
1971 * Not needed quite as much as it used to be since free links are a bit
1972 * more sensible these days. But bracketed links are still an issue.
1974 * @param $text String: more-or-less HTML
1975 * @return String: less-or-more HTML with NOPARSE bits
1977 function armorLinks( $text ) {
1978 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1979 "{$this->mUniqPrefix}NOPARSE$1", $text );
1983 * Return true if subpage links should be expanded on this page.
1986 function areSubpagesAllowed() {
1987 # Some namespaces don't allow subpages
1988 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1992 * Handle link to subpage if necessary
1994 * @param $target String: the source of the link
1995 * @param &$text String: the link text, modified as necessary
1996 * @return string the full name of the link
1999 function maybeDoSubpageLink( $target, &$text ) {
2000 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2004 * Used by doBlockLevels()
2007 function closeParagraph() {
2009 if ( $this->mLastSection
!= '' ) {
2010 $result = '</' . $this->mLastSection
. ">\n";
2012 $this->mInPre
= false;
2013 $this->mLastSection
= '';
2018 * getCommon() returns the length of the longest common substring
2019 * of both arguments, starting at the beginning of both.
2022 function getCommon( $st1, $st2 ) {
2023 $fl = strlen( $st1 );
2024 $shorter = strlen( $st2 );
2025 if ( $fl < $shorter ) {
2029 for ( $i = 0; $i < $shorter; ++
$i ) {
2030 if ( $st1{$i} != $st2{$i} ) {
2038 * These next three functions open, continue, and close the list
2039 * element appropriate to the prefix character passed into them.
2042 function openList( $char ) {
2043 $result = $this->closeParagraph();
2045 if ( '*' === $char ) {
2046 $result .= '<ul><li>';
2047 } elseif ( '#' === $char ) {
2048 $result .= '<ol><li>';
2049 } elseif ( ':' === $char ) {
2050 $result .= '<dl><dd>';
2051 } elseif ( ';' === $char ) {
2052 $result .= '<dl><dt>';
2053 $this->mDTopen
= true;
2055 $result = '<!-- ERR 1 -->';
2063 * @param $char String
2066 function nextItem( $char ) {
2067 if ( '*' === $char ||
'#' === $char ) {
2069 } elseif ( ':' === $char ||
';' === $char ) {
2071 if ( $this->mDTopen
) {
2074 if ( ';' === $char ) {
2075 $this->mDTopen
= true;
2076 return $close . '<dt>';
2078 $this->mDTopen
= false;
2079 return $close . '<dd>';
2082 return '<!-- ERR 2 -->';
2087 * @param $char String
2090 function closeList( $char ) {
2091 if ( '*' === $char ) {
2092 $text = '</li></ul>';
2093 } elseif ( '#' === $char ) {
2094 $text = '</li></ol>';
2095 } elseif ( ':' === $char ) {
2096 if ( $this->mDTopen
) {
2097 $this->mDTopen
= false;
2098 $text = '</dt></dl>';
2100 $text = '</dd></dl>';
2103 return '<!-- ERR 3 -->';
2110 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2112 * @param $text String
2113 * @param $linestart Boolean: whether or not this is at the start of a line.
2115 * @return string the lists rendered as HTML
2117 function doBlockLevels( $text, $linestart ) {
2118 wfProfileIn( __METHOD__
);
2120 # Parsing through the text line by line. The main thing
2121 # happening here is handling of block-level elements p, pre,
2122 # and making lists from lines starting with * # : etc.
2124 $textLines = StringUtils
::explode( "\n", $text );
2126 $lastPrefix = $output = '';
2127 $this->mDTopen
= $inBlockElem = false;
2129 $paragraphStack = false;
2131 foreach ( $textLines as $oLine ) {
2133 if ( !$linestart ) {
2143 $lastPrefixLength = strlen( $lastPrefix );
2144 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2145 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2146 # If not in a <pre> element, scan for and figure out what prefixes are there.
2147 if ( !$this->mInPre
) {
2148 # Multiple prefixes may abut each other for nested lists.
2149 $prefixLength = strspn( $oLine, '*#:;' );
2150 $prefix = substr( $oLine, 0, $prefixLength );
2153 # ; and : are both from definition-lists, so they're equivalent
2154 # for the purposes of determining whether or not we need to open/close
2156 $prefix2 = str_replace( ';', ':', $prefix );
2157 $t = substr( $oLine, $prefixLength );
2158 $this->mInPre
= (bool)$preOpenMatch;
2160 # Don't interpret any other prefixes in preformatted text
2162 $prefix = $prefix2 = '';
2167 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2168 # Same as the last item, so no need to deal with nesting or opening stuff
2169 $output .= $this->nextItem( substr( $prefix, -1 ) );
2170 $paragraphStack = false;
2172 if ( substr( $prefix, -1 ) === ';') {
2173 # The one nasty exception: definition lists work like this:
2174 # ; title : definition text
2175 # So we check for : in the remainder text to split up the
2176 # title and definition, without b0rking links.
2178 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2180 $output .= $term . $this->nextItem( ':' );
2183 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2184 # We need to open or close prefixes, or both.
2186 # Either open or close a level...
2187 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2188 $paragraphStack = false;
2190 # Close all the prefixes which aren't shared.
2191 while ( $commonPrefixLength < $lastPrefixLength ) {
2192 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2193 --$lastPrefixLength;
2196 # Continue the current prefix if appropriate.
2197 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2198 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2201 # Open prefixes where appropriate.
2202 while ( $prefixLength > $commonPrefixLength ) {
2203 $char = substr( $prefix, $commonPrefixLength, 1 );
2204 $output .= $this->openList( $char );
2206 if ( ';' === $char ) {
2207 # FIXME: This is dupe of code above
2208 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2210 $output .= $term . $this->nextItem( ':' );
2213 ++
$commonPrefixLength;
2215 $lastPrefix = $prefix2;
2218 # If we have no prefixes, go to paragraph mode.
2219 if ( 0 == $prefixLength ) {
2220 wfProfileIn( __METHOD__
."-paragraph" );
2221 # No prefix (not in list)--go to paragraph mode
2222 # XXX: use a stack for nestable elements like span, table and div
2223 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2224 $closematch = preg_match(
2225 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2226 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2227 if ( $openmatch or $closematch ) {
2228 $paragraphStack = false;
2229 #Â TODO bug 5718: paragraph closed
2230 $output .= $this->closeParagraph();
2231 if ( $preOpenMatch and !$preCloseMatch ) {
2232 $this->mInPre
= true;
2234 $inBlockElem = !$closematch;
2235 } elseif ( !$inBlockElem && !$this->mInPre
) {
2236 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2238 if ( $this->mLastSection
!== 'pre' ) {
2239 $paragraphStack = false;
2240 $output .= $this->closeParagraph().'<pre>';
2241 $this->mLastSection
= 'pre';
2243 $t = substr( $t, 1 );
2246 if ( trim( $t ) === '' ) {
2247 if ( $paragraphStack ) {
2248 $output .= $paragraphStack.'<br />';
2249 $paragraphStack = false;
2250 $this->mLastSection
= 'p';
2252 if ( $this->mLastSection
!== 'p' ) {
2253 $output .= $this->closeParagraph();
2254 $this->mLastSection
= '';
2255 $paragraphStack = '<p>';
2257 $paragraphStack = '</p><p>';
2261 if ( $paragraphStack ) {
2262 $output .= $paragraphStack;
2263 $paragraphStack = false;
2264 $this->mLastSection
= 'p';
2265 } elseif ( $this->mLastSection
!== 'p' ) {
2266 $output .= $this->closeParagraph().'<p>';
2267 $this->mLastSection
= 'p';
2272 wfProfileOut( __METHOD__
."-paragraph" );
2274 # somewhere above we forget to get out of pre block (bug 785)
2275 if ( $preCloseMatch && $this->mInPre
) {
2276 $this->mInPre
= false;
2278 if ( $paragraphStack === false ) {
2282 while ( $prefixLength ) {
2283 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2286 if ( $this->mLastSection
!= '' ) {
2287 $output .= '</' . $this->mLastSection
. '>';
2288 $this->mLastSection
= '';
2291 wfProfileOut( __METHOD__
);
2296 * Split up a string on ':', ignoring any occurences inside tags
2297 * to prevent illegal overlapping.
2299 * @param $str String: the string to split
2300 * @param &$before String: set to everything before the ':'
2301 * @param &$after String: set to everything after the ':'
2302 * return String: the position of the ':', or false if none found
2304 function findColonNoLinks( $str, &$before, &$after ) {
2305 wfProfileIn( __METHOD__
);
2307 $pos = strpos( $str, ':' );
2308 if ( $pos === false ) {
2310 wfProfileOut( __METHOD__
);
2314 $lt = strpos( $str, '<' );
2315 if ( $lt === false ||
$lt > $pos ) {
2316 # Easy; no tag nesting to worry about
2317 $before = substr( $str, 0, $pos );
2318 $after = substr( $str, $pos+
1 );
2319 wfProfileOut( __METHOD__
);
2323 # Ugly state machine to walk through avoiding tags.
2324 $state = self
::COLON_STATE_TEXT
;
2326 $len = strlen( $str );
2327 for( $i = 0; $i < $len; $i++
) {
2331 # (Using the number is a performance hack for common cases)
2332 case 0: # self::COLON_STATE_TEXT:
2335 # Could be either a <start> tag or an </end> tag
2336 $state = self
::COLON_STATE_TAGSTART
;
2339 if ( $stack == 0 ) {
2341 $before = substr( $str, 0, $i );
2342 $after = substr( $str, $i +
1 );
2343 wfProfileOut( __METHOD__
);
2346 # Embedded in a tag; don't break it.
2349 # Skip ahead looking for something interesting
2350 $colon = strpos( $str, ':', $i );
2351 if ( $colon === false ) {
2352 # Nothing else interesting
2353 wfProfileOut( __METHOD__
);
2356 $lt = strpos( $str, '<', $i );
2357 if ( $stack === 0 ) {
2358 if ( $lt === false ||
$colon < $lt ) {
2360 $before = substr( $str, 0, $colon );
2361 $after = substr( $str, $colon +
1 );
2362 wfProfileOut( __METHOD__
);
2366 if ( $lt === false ) {
2367 # Nothing else interesting to find; abort!
2368 # We're nested, but there's no close tags left. Abort!
2371 # Skip ahead to next tag start
2373 $state = self
::COLON_STATE_TAGSTART
;
2376 case 1: # self::COLON_STATE_TAG:
2381 $state = self
::COLON_STATE_TEXT
;
2384 # Slash may be followed by >?
2385 $state = self
::COLON_STATE_TAGSLASH
;
2391 case 2: # self::COLON_STATE_TAGSTART:
2394 $state = self
::COLON_STATE_CLOSETAG
;
2397 $state = self
::COLON_STATE_COMMENT
;
2400 # Illegal early close? This shouldn't happen D:
2401 $state = self
::COLON_STATE_TEXT
;
2404 $state = self
::COLON_STATE_TAG
;
2407 case 3: # self::COLON_STATE_CLOSETAG:
2412 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2413 wfProfileOut( __METHOD__
);
2416 $state = self
::COLON_STATE_TEXT
;
2419 case self
::COLON_STATE_TAGSLASH
:
2421 # Yes, a self-closed tag <blah/>
2422 $state = self
::COLON_STATE_TEXT
;
2424 # Probably we're jumping the gun, and this is an attribute
2425 $state = self
::COLON_STATE_TAG
;
2428 case 5: # self::COLON_STATE_COMMENT:
2430 $state = self
::COLON_STATE_COMMENTDASH
;
2433 case self
::COLON_STATE_COMMENTDASH
:
2435 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2437 $state = self
::COLON_STATE_COMMENT
;
2440 case self
::COLON_STATE_COMMENTDASHDASH
:
2442 $state = self
::COLON_STATE_TEXT
;
2444 $state = self
::COLON_STATE_COMMENT
;
2448 throw new MWException( "State machine error in " . __METHOD__
);
2452 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2455 wfProfileOut( __METHOD__
);
2460 * Return value of a magic variable (like PAGENAME)
2464 function getVariableValue( $index, $frame=false ) {
2465 global $wgContLang, $wgSitename, $wgServer;
2466 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2469 * Some of these require message or data lookups and can be
2470 * expensive to check many times.
2472 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2473 if ( isset( $this->mVarCache
[$index] ) ) {
2474 return $this->mVarCache
[$index];
2478 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2479 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2482 global $wgLocaltimezone;
2483 if ( isset( $wgLocaltimezone ) ) {
2484 $oldtz = date_default_timezone_get();
2485 date_default_timezone_set( $wgLocaltimezone );
2488 $localTimestamp = date( 'YmdHis', $ts );
2489 $localMonth = date( 'm', $ts );
2490 $localMonth1 = date( 'n', $ts );
2491 $localMonthName = date( 'n', $ts );
2492 $localDay = date( 'j', $ts );
2493 $localDay2 = date( 'd', $ts );
2494 $localDayOfWeek = date( 'w', $ts );
2495 $localWeek = date( 'W', $ts );
2496 $localYear = date( 'Y', $ts );
2497 $localHour = date( 'H', $ts );
2498 if ( isset( $wgLocaltimezone ) ) {
2499 date_default_timezone_set( $oldtz );
2503 case 'currentmonth':
2504 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2506 case 'currentmonth1':
2507 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2509 case 'currentmonthname':
2510 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2512 case 'currentmonthnamegen':
2513 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2515 case 'currentmonthabbrev':
2516 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2519 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2522 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2525 $value = $wgContLang->formatNum( $localMonth );
2528 $value = $wgContLang->formatNum( $localMonth1 );
2530 case 'localmonthname':
2531 $value = $wgContLang->getMonthName( $localMonthName );
2533 case 'localmonthnamegen':
2534 $value = $wgContLang->getMonthNameGen( $localMonthName );
2536 case 'localmonthabbrev':
2537 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2540 $value = $wgContLang->formatNum( $localDay );
2543 $value = $wgContLang->formatNum( $localDay2 );
2546 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2549 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2551 case 'fullpagename':
2552 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2554 case 'fullpagenamee':
2555 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2558 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2560 case 'subpagenamee':
2561 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2563 case 'basepagename':
2564 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2566 case 'basepagenamee':
2567 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2569 case 'talkpagename':
2570 if ( $this->mTitle
->canTalk() ) {
2571 $talkPage = $this->mTitle
->getTalkPage();
2572 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2577 case 'talkpagenamee':
2578 if ( $this->mTitle
->canTalk() ) {
2579 $talkPage = $this->mTitle
->getTalkPage();
2580 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2585 case 'subjectpagename':
2586 $subjPage = $this->mTitle
->getSubjectPage();
2587 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2589 case 'subjectpagenamee':
2590 $subjPage = $this->mTitle
->getSubjectPage();
2591 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2594 # Let the edit saving system know we should parse the page
2595 # *after* a revision ID has been assigned.
2596 $this->mOutput
->setFlag( 'vary-revision' );
2597 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2598 $value = $this->mRevisionId
;
2601 # Let the edit saving system know we should parse the page
2602 # *after* a revision ID has been assigned. This is for null edits.
2603 $this->mOutput
->setFlag( 'vary-revision' );
2604 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2605 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2607 case 'revisionday2':
2608 # Let the edit saving system know we should parse the page
2609 # *after* a revision ID has been assigned. This is for null edits.
2610 $this->mOutput
->setFlag( 'vary-revision' );
2611 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2612 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2614 case 'revisionmonth':
2615 # Let the edit saving system know we should parse the page
2616 # *after* a revision ID has been assigned. This is for null edits.
2617 $this->mOutput
->setFlag( 'vary-revision' );
2618 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2619 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2621 case 'revisionmonth1':
2622 # Let the edit saving system know we should parse the page
2623 # *after* a revision ID has been assigned. This is for null edits.
2624 $this->mOutput
->setFlag( 'vary-revision' );
2625 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2626 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2628 case 'revisionyear':
2629 # Let the edit saving system know we should parse the page
2630 # *after* a revision ID has been assigned. This is for null edits.
2631 $this->mOutput
->setFlag( 'vary-revision' );
2632 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2633 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2635 case 'revisiontimestamp':
2636 # Let the edit saving system know we should parse the page
2637 # *after* a revision ID has been assigned. This is for null edits.
2638 $this->mOutput
->setFlag( 'vary-revision' );
2639 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2640 $value = $this->getRevisionTimestamp();
2642 case 'revisionuser':
2643 # Let the edit saving system know we should parse the page
2644 # *after* a revision ID has been assigned. This is for null edits.
2645 $this->mOutput
->setFlag( 'vary-revision' );
2646 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2647 $value = $this->getRevisionUser();
2650 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2653 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2656 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2659 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2661 case 'subjectspace':
2662 $value = $this->mTitle
->getSubjectNsText();
2664 case 'subjectspacee':
2665 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2667 case 'currentdayname':
2668 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2671 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2674 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2677 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2680 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2681 # int to remove the padding
2682 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2685 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2687 case 'localdayname':
2688 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2691 $value = $wgContLang->formatNum( $localYear, true );
2694 $value = $wgContLang->time( $localTimestamp, false, false );
2697 $value = $wgContLang->formatNum( $localHour, true );
2700 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2701 # int to remove the padding
2702 $value = $wgContLang->formatNum( (int)$localWeek );
2705 $value = $wgContLang->formatNum( $localDayOfWeek );
2707 case 'numberofarticles':
2708 $value = $wgContLang->formatNum( SiteStats
::articles() );
2710 case 'numberoffiles':
2711 $value = $wgContLang->formatNum( SiteStats
::images() );
2713 case 'numberofusers':
2714 $value = $wgContLang->formatNum( SiteStats
::users() );
2716 case 'numberofactiveusers':
2717 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2719 case 'numberofpages':
2720 $value = $wgContLang->formatNum( SiteStats
::pages() );
2722 case 'numberofadmins':
2723 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2725 case 'numberofedits':
2726 $value = $wgContLang->formatNum( SiteStats
::edits() );
2728 case 'numberofviews':
2729 $value = $wgContLang->formatNum( SiteStats
::views() );
2731 case 'currenttimestamp':
2732 $value = wfTimestamp( TS_MW
, $ts );
2734 case 'localtimestamp':
2735 $value = $localTimestamp;
2737 case 'currentversion':
2738 $value = SpecialVersion
::getVersion();
2741 return $wgArticlePath;
2747 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2748 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2749 wfRestoreWarnings();
2750 return $serverName ?
$serverName : $wgServer;
2752 return $wgScriptPath;
2754 return $wgStylePath;
2755 case 'directionmark':
2756 return $wgContLang->getDirMark();
2757 case 'contentlanguage':
2758 global $wgLanguageCode;
2759 return $wgLanguageCode;
2762 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2770 $this->mVarCache
[$index] = $value;
2776 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2780 function initialiseVariables() {
2781 wfProfileIn( __METHOD__
);
2782 $variableIDs = MagicWord
::getVariableIDs();
2783 $substIDs = MagicWord
::getSubstIDs();
2785 $this->mVariables
= new MagicWordArray( $variableIDs );
2786 $this->mSubstWords
= new MagicWordArray( $substIDs );
2787 wfProfileOut( __METHOD__
);
2791 * Preprocess some wikitext and return the document tree.
2792 * This is the ghost of replace_variables().
2794 * @param $text String: The text to parse
2795 * @param $flags Integer: bitwise combination of:
2796 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2797 * included. Default is to assume a direct page view.
2799 * The generated DOM tree must depend only on the input text and the flags.
2800 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2802 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2803 * change in the DOM tree for a given text, must be passed through the section identifier
2804 * in the section edit link and thus back to extractSections().
2806 * The output of this function is currently only cached in process memory, but a persistent
2807 * cache may be implemented at a later date which takes further advantage of these strict
2808 * dependency requirements.
2812 function preprocessToDom( $text, $flags = 0 ) {
2813 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2818 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2820 public static function splitWhitespace( $s ) {
2821 $ltrimmed = ltrim( $s );
2822 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2823 $trimmed = rtrim( $ltrimmed );
2824 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2826 $w2 = substr( $ltrimmed, -$diff );
2830 return array( $w1, $trimmed, $w2 );
2834 * Replace magic variables, templates, and template arguments
2835 * with the appropriate text. Templates are substituted recursively,
2836 * taking care to avoid infinite loops.
2838 * Note that the substitution depends on value of $mOutputType:
2839 * self::OT_WIKI: only {{subst:}} templates
2840 * self::OT_PREPROCESS: templates but not extension tags
2841 * self::OT_HTML: all templates and extension tags
2843 * @param $text String: the text to transform
2844 * @param $frame PPFrame Object describing the arguments passed to the template.
2845 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2846 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2847 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2850 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2851 # Is there any text? Also, Prevent too big inclusions!
2852 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2855 wfProfileIn( __METHOD__
);
2857 if ( $frame === false ) {
2858 $frame = $this->getPreprocessor()->newFrame();
2859 } elseif ( !( $frame instanceof PPFrame
) ) {
2860 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2861 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2864 $dom = $this->preprocessToDom( $text );
2865 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2866 $text = $frame->expand( $dom, $flags );
2868 wfProfileOut( __METHOD__
);
2872 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2873 static function createAssocArgs( $args ) {
2874 $assocArgs = array();
2876 foreach ( $args as $arg ) {
2877 $eqpos = strpos( $arg, '=' );
2878 if ( $eqpos === false ) {
2879 $assocArgs[$index++
] = $arg;
2881 $name = trim( substr( $arg, 0, $eqpos ) );
2882 $value = trim( substr( $arg, $eqpos+
1 ) );
2883 if ( $value === false ) {
2886 if ( $name !== false ) {
2887 $assocArgs[$name] = $value;
2896 * Warn the user when a parser limitation is reached
2897 * Will warn at most once the user per limitation type
2899 * @param $limitationType String: should be one of:
2900 * 'expensive-parserfunction' (corresponding messages:
2901 * 'expensive-parserfunction-warning',
2902 * 'expensive-parserfunction-category')
2903 * 'post-expand-template-argument' (corresponding messages:
2904 * 'post-expand-template-argument-warning',
2905 * 'post-expand-template-argument-category')
2906 * 'post-expand-template-inclusion' (corresponding messages:
2907 * 'post-expand-template-inclusion-warning',
2908 * 'post-expand-template-inclusion-category')
2909 * @param $current Current value
2910 * @param $max Maximum allowed, when an explicit limit has been
2911 * exceeded, provide the values (optional)
2913 function limitationWarn( $limitationType, $current=null, $max=null) {
2914 # does no harm if $current and $max are present but are unnecessary for the message
2915 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2916 $this->mOutput
->addWarning( $warning );
2917 $this->addTrackingCategory( "$limitationType-category" );
2921 * Return the text of a template, after recursively
2922 * replacing any variables or templates within the template.
2924 * @param $piece Array: the parts of the template
2925 * $piece['title']: the title, i.e. the part before the |
2926 * $piece['parts']: the parameter array
2927 * $piece['lineStart']: whether the brace was at the start of a line
2928 * @param $frame PPFrame The current frame, contains template arguments
2929 * @return String: the text of the template
2932 function braceSubstitution( $piece, $frame ) {
2933 global $wgContLang, $wgNonincludableNamespaces;
2934 wfProfileIn( __METHOD__
);
2935 wfProfileIn( __METHOD__
.'-setup' );
2938 $found = false; # $text has been filled
2939 $nowiki = false; # wiki markup in $text should be escaped
2940 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2941 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2942 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2943 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2945 # Title object, where $text came from
2948 # $part1 is the bit before the first |, and must contain only title characters.
2949 # Various prefixes will be stripped from it later.
2950 $titleWithSpaces = $frame->expand( $piece['title'] );
2951 $part1 = trim( $titleWithSpaces );
2954 # Original title text preserved for various purposes
2955 $originalTitle = $part1;
2957 # $args is a list of argument nodes, starting from index 0, not including $part1
2958 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2959 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2960 wfProfileOut( __METHOD__
.'-setup' );
2963 wfProfileIn( __METHOD__
.'-modifiers' );
2966 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2968 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2969 # Decide whether to expand template or keep wikitext as-is.
2970 if ( $this->ot
['wiki'] ) {
2971 if ( $substMatch === false ) {
2972 $literal = true; # literal when in PST with no prefix
2974 $literal = false; # expand when in PST with subst: or safesubst:
2977 if ( $substMatch == 'subst' ) {
2978 $literal = true; # literal when not in PST with plain subst:
2980 $literal = false; # expand when not in PST with safesubst: or no prefix
2984 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2991 if ( !$found && $args->getLength() == 0 ) {
2992 $id = $this->mVariables
->matchStartToEnd( $part1 );
2993 if ( $id !== false ) {
2994 $text = $this->getVariableValue( $id, $frame );
2995 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2996 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3002 # MSG, MSGNW and RAW
3005 $mwMsgnw = MagicWord
::get( 'msgnw' );
3006 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3009 # Remove obsolete MSG:
3010 $mwMsg = MagicWord
::get( 'msg' );
3011 $mwMsg->matchStartAndRemove( $part1 );
3015 $mwRaw = MagicWord
::get( 'raw' );
3016 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3017 $forceRawInterwiki = true;
3020 wfProfileOut( __METHOD__
.'-modifiers' );
3024 wfProfileIn( __METHOD__
. '-pfunc' );
3026 $colonPos = strpos( $part1, ':' );
3027 if ( $colonPos !== false ) {
3028 # Case sensitive functions
3029 $function = substr( $part1, 0, $colonPos );
3030 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3031 $function = $this->mFunctionSynonyms
[1][$function];
3033 # Case insensitive functions
3034 $function = $wgContLang->lc( $function );
3035 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3036 $function = $this->mFunctionSynonyms
[0][$function];
3042 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3043 $initialArgs = array( &$this );
3044 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3045 if ( $flags & SFH_OBJECT_ARGS
) {
3046 # Add a frame parameter, and pass the arguments as an array
3047 $allArgs = $initialArgs;
3048 $allArgs[] = $frame;
3049 for ( $i = 0; $i < $args->getLength(); $i++
) {
3050 $funcArgs[] = $args->item( $i );
3052 $allArgs[] = $funcArgs;
3054 # Convert arguments to plain text
3055 for ( $i = 0; $i < $args->getLength(); $i++
) {
3056 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3058 $allArgs = array_merge( $initialArgs, $funcArgs );
3061 # Workaround for PHP bug 35229 and similar
3062 if ( !is_callable( $callback ) ) {
3063 wfProfileOut( __METHOD__
. '-pfunc' );
3064 wfProfileOut( __METHOD__
);
3065 throw new MWException( "Tag hook for $function is not callable\n" );
3067 $result = call_user_func_array( $callback, $allArgs );
3070 $preprocessFlags = 0;
3072 if ( is_array( $result ) ) {
3073 if ( isset( $result[0] ) ) {
3075 unset( $result[0] );
3078 # Extract flags into the local scope
3079 # This allows callers to set flags such as nowiki, found, etc.
3085 $text = $this->preprocessToDom( $text, $preprocessFlags );
3090 wfProfileOut( __METHOD__
. '-pfunc' );
3093 # Finish mangling title and then check for loops.
3094 # Set $title to a Title object and $titleText to the PDBK
3097 # Split the title into page and subpage
3099 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3100 if ( $subpage !== '' ) {
3101 $ns = $this->mTitle
->getNamespace();
3103 $title = Title
::newFromText( $part1, $ns );
3105 $titleText = $title->getPrefixedText();
3106 # Check for language variants if the template is not found
3107 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3108 $wgContLang->findVariantLink( $part1, $title, true );
3110 # Do recursion depth check
3111 $limit = $this->mOptions
->getMaxTemplateDepth();
3112 if ( $frame->depth
>= $limit ) {
3114 $text = '<span class="error">'
3115 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3121 # Load from database
3122 if ( !$found && $title ) {
3123 wfProfileIn( __METHOD__
. '-loadtpl' );
3124 if ( !$title->isExternal() ) {
3125 if ( $title->getNamespace() == NS_SPECIAL
3126 && $this->mOptions
->getAllowSpecialInclusion()
3127 && $this->ot
['html'] )
3129 $text = SpecialPage
::capturePath( $title );
3130 if ( is_string( $text ) ) {
3133 $this->disableCache();
3135 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3136 $found = false; # access denied
3137 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3139 list( $text, $title ) = $this->getTemplateDom( $title );
3140 if ( $text !== false ) {
3146 # If the title is valid but undisplayable, make a link to it
3147 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3148 $text = "[[:$titleText]]";
3151 } elseif ( $title->isTrans() ) {
3152 # Interwiki transclusion
3153 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3154 $text = $this->interwikiTransclude( $title, 'render' );
3157 $text = $this->interwikiTransclude( $title, 'raw' );
3158 # Preprocess it like a template
3159 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3165 # Do infinite loop check
3166 # This has to be done after redirect resolution to avoid infinite loops via redirects
3167 if ( !$frame->loopCheck( $title ) ) {
3169 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3170 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3172 wfProfileOut( __METHOD__
. '-loadtpl' );
3175 # If we haven't found text to substitute by now, we're done
3176 # Recover the source wikitext and return it
3178 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3179 wfProfileOut( __METHOD__
);
3180 return array( 'object' => $text );
3183 # Expand DOM-style return values in a child frame
3184 if ( $isChildObj ) {
3185 # Clean up argument array
3186 $newFrame = $frame->newChild( $args, $title );
3189 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3190 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3191 # Expansion is eligible for the empty-frame cache
3192 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3193 $text = $this->mTplExpandCache
[$titleText];
3195 $text = $newFrame->expand( $text );
3196 $this->mTplExpandCache
[$titleText] = $text;
3199 # Uncached expansion
3200 $text = $newFrame->expand( $text );
3203 if ( $isLocalObj && $nowiki ) {
3204 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3205 $isLocalObj = false;
3208 # Replace raw HTML by a placeholder
3209 # Add a blank line preceding, to prevent it from mucking up
3210 # immediately preceding headings
3212 $text = "\n\n" . $this->insertStripItem( $text );
3213 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3214 # Escape nowiki-style return values
3215 $text = wfEscapeWikiText( $text );
3216 } elseif ( is_string( $text )
3217 && !$piece['lineStart']
3218 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3220 # Bug 529: if the template begins with a table or block-level
3221 # element, it should be treated as beginning a new line.
3222 # This behaviour is somewhat controversial.
3223 $text = "\n" . $text;
3226 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3227 # Error, oversize inclusion
3228 if ( $titleText !== false ) {
3229 # Make a working, properly escaped link if possible (bug 23588)
3230 $text = "[[:$titleText]]";
3232 # This will probably not be a working link, but at least it may
3233 # provide some hint of where the problem is
3234 preg_replace( '/^:/', '', $originalTitle );
3235 $text = "[[:$originalTitle]]";
3237 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3238 $this->limitationWarn( 'post-expand-template-inclusion' );
3241 if ( $isLocalObj ) {
3242 $ret = array( 'object' => $text );
3244 $ret = array( 'text' => $text );
3247 wfProfileOut( __METHOD__
);
3252 * Get the semi-parsed DOM representation of a template with a given title,
3253 * and its redirect destination title. Cached.
3255 function getTemplateDom( $title ) {
3256 $cacheTitle = $title;
3257 $titleText = $title->getPrefixedDBkey();
3259 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3260 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3261 $title = Title
::makeTitle( $ns, $dbk );
3262 $titleText = $title->getPrefixedDBkey();
3264 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3265 return array( $this->mTplDomCache
[$titleText], $title );
3268 # Cache miss, go to the database
3269 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3271 if ( $text === false ) {
3272 $this->mTplDomCache
[$titleText] = false;
3273 return array( false, $title );
3276 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3277 $this->mTplDomCache
[ $titleText ] = $dom;
3279 if ( !$title->equals( $cacheTitle ) ) {
3280 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3281 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3284 return array( $dom, $title );
3288 * Fetch the unparsed text of a template and register a reference to it.
3290 function fetchTemplateAndTitle( $title ) {
3291 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3292 $stuff = call_user_func( $templateCb, $title, $this );
3293 $text = $stuff['text'];
3294 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3295 if ( isset( $stuff['deps'] ) ) {
3296 foreach ( $stuff['deps'] as $dep ) {
3297 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3300 return array( $text, $finalTitle );
3303 function fetchTemplate( $title ) {
3304 $rv = $this->fetchTemplateAndTitle( $title );
3309 * Static function to get a template
3310 * Can be overridden via ParserOptions::setTemplateCallback().
3312 static function statelessFetchTemplate( $title, $parser=false ) {
3313 $text = $skip = false;
3314 $finalTitle = $title;
3317 # Loop to fetch the article, with up to 1 redirect
3318 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3319 # Give extensions a chance to select the revision instead
3320 $id = false; # Assume current
3321 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3327 'page_id' => $title->getArticleID(),
3331 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3332 $rev_id = $rev ?
$rev->getId() : 0;
3333 # If there is no current revision, there is no page
3334 if ( $id === false && !$rev ) {
3335 $linkCache = LinkCache
::singleton();
3336 $linkCache->addBadLinkObj( $title );
3341 'page_id' => $title->getArticleID(),
3342 'rev_id' => $rev_id );
3345 $text = $rev->getText();
3346 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3348 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3349 if ( !$message->exists() ) {
3353 $text = $message->plain();
3357 if ( $text === false ) {
3361 $finalTitle = $title;
3362 $title = Title
::newFromRedirect( $text );
3366 'finalTitle' => $finalTitle,
3371 * Transclude an interwiki link.
3373 function interwikiTransclude( $title, $action ) {
3374 global $wgEnableScaryTranscluding;
3376 if ( !$wgEnableScaryTranscluding ) {
3377 return wfMsgForContent('scarytranscludedisabled');
3380 $url = $title->getFullUrl( "action=$action" );
3382 if ( strlen( $url ) > 255 ) {
3383 return wfMsgForContent( 'scarytranscludetoolong' );
3385 return $this->fetchScaryTemplateMaybeFromCache( $url );
3388 function fetchScaryTemplateMaybeFromCache( $url ) {
3389 global $wgTranscludeCacheExpiry;
3390 $dbr = wfGetDB( DB_SLAVE
);
3391 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3392 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3393 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3395 return $obj->tc_contents
;
3398 $text = Http
::get( $url );
3400 return wfMsgForContent( 'scarytranscludefailed', $url );
3403 $dbw = wfGetDB( DB_MASTER
);
3404 $dbw->replace( 'transcache', array('tc_url'), array(
3406 'tc_time' => $dbw->timestamp( time() ),
3407 'tc_contents' => $text)
3414 * Triple brace replacement -- used for template arguments
3417 function argSubstitution( $piece, $frame ) {
3418 wfProfileIn( __METHOD__
);
3421 $parts = $piece['parts'];
3422 $nameWithSpaces = $frame->expand( $piece['title'] );
3423 $argName = trim( $nameWithSpaces );
3425 $text = $frame->getArgument( $argName );
3426 if ( $text === false && $parts->getLength() > 0
3430 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3433 # No match in frame, use the supplied default
3434 $object = $parts->item( 0 )->getChildren();
3436 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3437 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3438 $this->limitationWarn( 'post-expand-template-argument' );
3441 if ( $text === false && $object === false ) {
3443 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3445 if ( $error !== false ) {
3448 if ( $object !== false ) {
3449 $ret = array( 'object' => $object );
3451 $ret = array( 'text' => $text );
3454 wfProfileOut( __METHOD__
);
3459 * Return the text to be used for a given extension tag.
3460 * This is the ghost of strip().
3462 * @param $params Associative array of parameters:
3463 * name PPNode for the tag name
3464 * attr PPNode for unparsed text where tag attributes are thought to be
3465 * attributes Optional associative array of parsed attributes
3466 * inner Contents of extension element
3467 * noClose Original text did not have a close tag
3468 * @param $frame PPFrame
3470 function extensionSubstitution( $params, $frame ) {
3471 $name = $frame->expand( $params['name'] );
3472 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3473 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3474 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3476 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3477 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3478 if ( $isFunctionTag ) {
3479 $markerType = 'none';
3481 $markerType = 'general';
3483 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3484 $name = strtolower( $name );
3485 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3486 if ( isset( $params['attributes'] ) ) {
3487 $attributes = $attributes +
$params['attributes'];
3490 if ( isset( $this->mTagHooks
[$name] ) ) {
3491 # Workaround for PHP bug 35229 and similar
3492 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3493 throw new MWException( "Tag hook for $name is not callable\n" );
3495 $output = call_user_func_array( $this->mTagHooks
[$name],
3496 array( $content, $attributes, $this, $frame ) );
3497 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3498 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3499 if ( !is_callable( $callback ) ) {
3500 throw new MWException( "Tag hook for $name is not callable\n" );
3503 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3505 $output = '<span class="error">Invalid tag extension name: ' .
3506 htmlspecialchars( $name ) . '</span>';
3509 if ( is_array( $output ) ) {
3510 # Extract flags to local scope (to override $markerType)
3512 $output = $flags[0];
3517 if ( is_null( $attrText ) ) {
3520 if ( isset( $params['attributes'] ) ) {
3521 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3522 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3523 htmlspecialchars( $attrValue ) . '"';
3526 if ( $content === null ) {
3527 $output = "<$name$attrText/>";
3529 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3530 $output = "<$name$attrText>$content$close";
3534 if ( $markerType === 'none' ) {
3536 } elseif ( $markerType === 'nowiki' ) {
3537 $this->mStripState
->nowiki
->setPair( $marker, $output );
3538 } elseif ( $markerType === 'general' ) {
3539 $this->mStripState
->general
->setPair( $marker, $output );
3541 throw new MWException( __METHOD__
.': invalid marker type' );
3547 * Increment an include size counter
3549 * @param $type String: the type of expansion
3550 * @param $size Integer: the size of the text
3551 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3553 function incrementIncludeSize( $type, $size ) {
3554 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3557 $this->mIncludeSizes
[$type] +
= $size;
3563 * Increment the expensive function count
3565 * @return Boolean: false if the limit has been exceeded
3567 function incrementExpensiveFunctionCount() {
3568 global $wgExpensiveParserFunctionLimit;
3569 $this->mExpensiveFunctionCount++
;
3570 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3577 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3578 * Fills $this->mDoubleUnderscores, returns the modified text
3580 function doDoubleUnderscore( $text ) {
3581 wfProfileIn( __METHOD__
);
3583 # The position of __TOC__ needs to be recorded
3584 $mw = MagicWord
::get( 'toc' );
3585 if ( $mw->match( $text ) ) {
3586 $this->mShowToc
= true;
3587 $this->mForceTocPosition
= true;
3589 # Set a placeholder. At the end we'll fill it in with the TOC.
3590 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3592 # Only keep the first one.
3593 $text = $mw->replace( '', $text );
3596 # Now match and remove the rest of them
3597 $mwa = MagicWord
::getDoubleUnderscoreArray();
3598 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3600 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3601 $this->mOutput
->mNoGallery
= true;
3603 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3604 $this->mShowToc
= false;
3606 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3607 $this->addTrackingCategory( 'hidden-category-category' );
3609 # (bug 8068) Allow control over whether robots index a page.
3611 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3612 # is not desirable, the last one on the page should win.
3613 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3614 $this->mOutput
->setIndexPolicy( 'noindex' );
3615 $this->addTrackingCategory( 'noindex-category' );
3617 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3618 $this->mOutput
->setIndexPolicy( 'index' );
3619 $this->addTrackingCategory( 'index-category' );
3622 # Cache all double underscores in the database
3623 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3624 $this->mOutput
->setProperty( $key, '' );
3627 wfProfileOut( __METHOD__
);
3632 * Add a tracking category, getting the title from a system message,
3633 * or print a debug message if the title is invalid.
3635 * @param $msg String: message key
3636 * @return Boolean: whether the addition was successful
3638 protected function addTrackingCategory( $msg ) {
3639 $cat = wfMsgForContent( $msg );
3641 # Allow tracking categories to be disabled by setting them to "-"
3642 if ( $cat === '-' ) {
3646 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3647 if ( $containerCategory ) {
3648 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3651 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3657 * This function accomplishes several tasks:
3658 * 1) Auto-number headings if that option is enabled
3659 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3660 * 3) Add a Table of contents on the top for users who have enabled the option
3661 * 4) Auto-anchor headings
3663 * It loops through all headlines, collects the necessary data, then splits up the
3664 * string and re-inserts the newly formatted headlines.
3666 * @param $text String
3667 * @param $origText String: original, untouched wikitext
3668 * @param $isMain Boolean
3671 function formatHeadings( $text, $origText, $isMain=true ) {
3672 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3674 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3676 # Inhibit editsection links if requested in the page
3677 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3680 $showEditLink = $this->mOptions
->getEditSection();
3682 if ( $showEditLink ) {
3683 $this->mOutput
->setEditSectionTokens( true );
3686 # Get all headlines for numbering them and adding funky stuff like [edit]
3687 # links - this is for later, but we need the number of headlines right now
3689 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3691 # if there are fewer than 4 headlines in the article, do not show TOC
3692 # unless it's been explicitly enabled.
3693 $enoughToc = $this->mShowToc
&&
3694 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3696 # Allow user to stipulate that a page should have a "new section"
3697 # link added via __NEWSECTIONLINK__
3698 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3699 $this->mOutput
->setNewSection( true );
3702 # Allow user to remove the "new section"
3703 # link via __NONEWSECTIONLINK__
3704 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3705 $this->mOutput
->hideNewSection( true );
3708 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3709 # override above conditions and always show TOC above first header
3710 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3711 $this->mShowToc
= true;
3715 # We need this to perform operations on the HTML
3716 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3722 # Ugh .. the TOC should have neat indentation levels which can be
3723 # passed to the skin functions. These are determined here
3727 $sublevelCount = array();
3728 $levelCount = array();
3733 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3734 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3735 $oldType = $this->mOutputType
;
3736 $this->setOutputType( self
::OT_WIKI
);
3737 $frame = $this->getPreprocessor()->newFrame();
3738 $root = $this->preprocessToDom( $origText );
3739 $node = $root->getFirstChild();
3744 foreach ( $matches[3] as $headline ) {
3745 $isTemplate = false;
3747 $sectionIndex = false;
3749 $markerMatches = array();
3750 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3751 $serial = $markerMatches[1];
3752 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3753 $isTemplate = ( $titleText != $baseTitleText );
3754 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3758 $prevlevel = $level;
3760 $level = $matches[1][$headlineCount];
3762 if ( $level > $prevlevel ) {
3763 # Increase TOC level
3765 $sublevelCount[$toclevel] = 0;
3766 if ( $toclevel<$wgMaxTocLevel ) {
3767 $prevtoclevel = $toclevel;
3768 $toc .= $sk->tocIndent();
3771 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3772 # Decrease TOC level, find level to jump to
3774 for ( $i = $toclevel; $i > 0; $i-- ) {
3775 if ( $levelCount[$i] == $level ) {
3776 # Found last matching level
3779 } elseif ( $levelCount[$i] < $level ) {
3780 # Found first matching level below current level
3788 if ( $toclevel<$wgMaxTocLevel ) {
3789 if ( $prevtoclevel < $wgMaxTocLevel ) {
3790 # Unindent only if the previous toc level was shown :p
3791 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3792 $prevtoclevel = $toclevel;
3794 $toc .= $sk->tocLineEnd();
3798 # No change in level, end TOC line
3799 if ( $toclevel<$wgMaxTocLevel ) {
3800 $toc .= $sk->tocLineEnd();
3804 $levelCount[$toclevel] = $level;
3806 # count number of headlines for each level
3807 @$sublevelCount[$toclevel]++
;
3809 for( $i = 1; $i <= $toclevel; $i++
) {
3810 if ( !empty( $sublevelCount[$i] ) ) {
3814 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3819 # The safe header is a version of the header text safe to use for links
3820 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3821 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3823 # Remove link placeholders by the link text.
3824 # <!--LINK number-->
3826 # link text with suffix
3827 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3829 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3830 $tocline = preg_replace(
3831 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3832 array( '', '<$1>' ),
3835 $tocline = trim( $tocline );
3837 # For the anchor, strip out HTML-y stuff period
3838 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3839 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3841 # Save headline for section edit hint before it's escaped
3842 $headlineHint = $safeHeadline;
3844 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3845 # For reverse compatibility, provide an id that's
3846 # HTML4-compatible, like we used to.
3848 # It may be worth noting, academically, that it's possible for
3849 # the legacy anchor to conflict with a non-legacy headline
3850 # anchor on the page. In this case likely the "correct" thing
3851 # would be to either drop the legacy anchors or make sure
3852 # they're numbered first. However, this would require people
3853 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3854 # manually, so let's not bother worrying about it.
3855 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3856 array( 'noninitial', 'legacy' ) );
3857 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3859 if ( $legacyHeadline == $safeHeadline ) {
3860 # No reason to have both (in fact, we can't)
3861 $legacyHeadline = false;
3864 $legacyHeadline = false;
3865 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3869 # HTML names must be case-insensitively unique (bug 10721).
3870 # This does not apply to Unicode characters per
3871 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3872 # FIXME: We may be changing them depending on the current locale.
3873 $arrayKey = strtolower( $safeHeadline );
3874 if ( $legacyHeadline === false ) {
3875 $legacyArrayKey = false;
3877 $legacyArrayKey = strtolower( $legacyHeadline );
3880 # count how many in assoc. array so we can track dupes in anchors
3881 if ( isset( $refers[$arrayKey] ) ) {
3882 $refers[$arrayKey]++
;
3884 $refers[$arrayKey] = 1;
3886 if ( isset( $refers[$legacyArrayKey] ) ) {
3887 $refers[$legacyArrayKey]++
;
3889 $refers[$legacyArrayKey] = 1;
3892 # Don't number the heading if it is the only one (looks silly)
3893 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3894 # the two are different if the line contains a link
3895 $headline = $numbering . ' ' . $headline;
3898 # Create the anchor for linking from the TOC to the section
3899 $anchor = $safeHeadline;
3900 $legacyAnchor = $legacyHeadline;
3901 if ( $refers[$arrayKey] > 1 ) {
3902 $anchor .= '_' . $refers[$arrayKey];
3904 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3905 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3907 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3908 $toc .= $sk->tocLine( $anchor, $tocline,
3909 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3912 # Add the section to the section tree
3913 # Find the DOM node for this header
3914 while ( $node && !$isTemplate ) {
3915 if ( $node->getName() === 'h' ) {
3916 $bits = $node->splitHeading();
3917 if ( $bits['i'] == $sectionIndex ) {
3921 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3922 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3923 $node = $node->getNextSibling();
3926 'toclevel' => $toclevel,
3929 'number' => $numbering,
3930 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3931 'fromtitle' => $titleText,
3932 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3933 'anchor' => $anchor,
3936 # give headline the correct <h#> tag
3937 if ( $showEditLink && $sectionIndex !== false ) {
3938 // Output edit section links as markers with styles that can be customized by skins
3939 if ( $isTemplate ) {
3940 # Put a T flag in the section identifier, to indicate to extractSections()
3941 # that sections inside <includeonly> should be counted.
3942 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3944 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3946 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3947 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3948 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3949 // so we don't have to worry about a user trying to input one of these markers directly.
3950 // We use a page and section attribute to stop the language converter from converting these important bits
3951 // of data, but put the headline hint inside a content block because the language converter is supposed to
3952 // be able to convert that piece of data.
3953 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
3954 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
3955 if ( isset($editlinkArgs[2]) ) {
3956 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
3963 $head[$headlineCount] = $sk->makeHeadline( $level,
3964 $matches['attrib'][$headlineCount], $anchor, $headline,
3965 $editlink, $legacyAnchor );
3970 $this->setOutputType( $oldType );
3972 # Never ever show TOC if no headers
3973 if ( $numVisible < 1 ) {
3978 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3979 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3981 $toc = $sk->tocList( $toc );
3982 $this->mOutput
->setTOCHTML( $toc );
3986 $this->mOutput
->setSections( $tocraw );
3989 # split up and insert constructed headlines
3991 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3994 foreach ( $blocks as $block ) {
3995 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3996 # This is the [edit] link that appears for the top block of text when
3997 # section editing is enabled
3999 # Disabled because it broke block formatting
4000 # For example, a bullet point in the top line
4001 # $full .= $sk->editSectionLink(0);
4004 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4005 # Top anchor now in skin
4009 if ( !empty( $head[$i] ) ) {
4014 if ( $this->mForceTocPosition
) {
4015 return str_replace( '<!--MWTOC-->', $toc, $full );
4022 * Transform wiki markup when saving a page by doing \r\n -> \n
4023 * conversion, substitting signatures, {{subst:}} templates, etc.
4025 * @param $text String: the text to transform
4026 * @param $title Title: the Title object for the current article
4027 * @param $user User: the User object describing the current user
4028 * @param $options ParserOptions: parsing options
4029 * @param $clearState Boolean: whether to clear the parser state first
4030 * @return String: the altered wiki markup
4032 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4033 $this->startExternalParse( $title, $options, self
::OT_WIKI
, $clearState );
4034 $this->setUser( $user );
4039 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4040 if( $options->getPreSaveTransform() ) {
4041 $text = $this->pstPass2( $text, $user );
4043 $text = $this->mStripState
->unstripBoth( $text );
4045 $this->setUser( null ); #Reset
4051 * Pre-save transform helper function
4054 function pstPass2( $text, $user ) {
4055 global $wgContLang, $wgLocaltimezone;
4057 # Note: This is the timestamp saved as hardcoded wikitext to
4058 # the database, we use $wgContLang here in order to give
4059 # everyone the same signature and use the default one rather
4060 # than the one selected in each user's preferences.
4061 # (see also bug 12815)
4062 $ts = $this->mOptions
->getTimestamp();
4063 if ( isset( $wgLocaltimezone ) ) {
4064 $tz = $wgLocaltimezone;
4066 $tz = date_default_timezone_get();
4069 $unixts = wfTimestamp( TS_UNIX
, $ts );
4070 $oldtz = date_default_timezone_get();
4071 date_default_timezone_set( $tz );
4072 $ts = date( 'YmdHis', $unixts );
4073 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4075 # Allow translation of timezones through wiki. date() can return
4076 # whatever crap the system uses, localised or not, so we cannot
4077 # ship premade translations.
4078 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4079 $msg = wfMessage( $key )->inContentLanguage();
4080 if ( $msg->exists() ) {
4081 $tzMsg = $msg->text();
4084 date_default_timezone_set( $oldtz );
4086 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4088 # Variable replacement
4089 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4090 $text = $this->replaceVariables( $text );
4092 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4093 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4096 $sigText = $this->getUserSig( $user );
4097 $text = strtr( $text, array(
4099 '~~~~' => "$sigText $d",
4103 # Context links: [[|name]] and [[name (context)|]]
4104 global $wgLegalTitleChars;
4105 $tc = "[$wgLegalTitleChars]";
4106 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4108 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4109 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4110 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4111 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4113 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4114 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4115 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4116 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4118 $t = $this->mTitle
->getText();
4120 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4121 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4122 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4123 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4125 # if there's no context, don't bother duplicating the title
4126 $text = preg_replace( $p2, '[[\\1]]', $text );
4129 # Trim trailing whitespace
4130 $text = rtrim( $text );
4136 * Fetch the user's signature text, if any, and normalize to
4137 * validated, ready-to-insert wikitext.
4138 * If you have pre-fetched the nickname or the fancySig option, you can
4139 * specify them here to save a database query.
4140 * Do not reuse this parser instance after calling getUserSig(),
4141 * as it may have changed if it's the $wgParser.
4144 * @param $nickname String: nickname to use or false to use user's default nickname
4145 * @param $fancySig Boolean: whether the nicknname is the complete signature
4146 * or null to use default value
4149 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4150 global $wgMaxSigChars;
4152 $username = $user->getName();
4154 # If not given, retrieve from the user object.
4155 if ( $nickname === false )
4156 $nickname = $user->getOption( 'nickname' );
4158 if ( is_null( $fancySig ) ) {
4159 $fancySig = $user->getBoolOption( 'fancysig' );
4162 $nickname = $nickname == null ?
$username : $nickname;
4164 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4165 $nickname = $username;
4166 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4167 } elseif ( $fancySig !== false ) {
4168 # Sig. might contain markup; validate this
4169 if ( $this->validateSig( $nickname ) !== false ) {
4170 # Validated; clean up (if needed) and return it
4171 return $this->cleanSig( $nickname, true );
4173 # Failed to validate; fall back to the default
4174 $nickname = $username;
4175 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4179 # Make sure nickname doesnt get a sig in a sig
4180 $nickname = $this->cleanSigInSig( $nickname );
4182 # If we're still here, make it a link to the user page
4183 $userText = wfEscapeWikiText( $username );
4184 $nickText = wfEscapeWikiText( $nickname );
4185 if ( $user->isAnon() ) {
4186 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4188 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4193 * Check that the user's signature contains no bad XML
4195 * @param $text String
4196 * @return mixed An expanded string, or false if invalid.
4198 function validateSig( $text ) {
4199 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4203 * Clean up signature text
4205 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4206 * 2) Substitute all transclusions
4208 * @param $text String
4209 * @param $parsing Whether we're cleaning (preferences save) or parsing
4210 * @return String: signature text
4212 function cleanSig( $text, $parsing = false ) {
4215 $this->mOptions
= new ParserOptions
;
4216 $this->clearState();
4217 $this->setTitle( $wgTitle );
4218 $this->setOutputType
= self
::OT_PREPROCESS
;
4221 # Option to disable this feature
4222 if ( !$this->mOptions
->getCleanSignatures() ) {
4226 # FIXME: regex doesn't respect extension tags or nowiki
4227 # => Move this logic to braceSubstitution()
4228 $substWord = MagicWord
::get( 'subst' );
4229 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4230 $substText = '{{' . $substWord->getSynonym( 0 );
4232 $text = preg_replace( $substRegex, $substText, $text );
4233 $text = $this->cleanSigInSig( $text );
4234 $dom = $this->preprocessToDom( $text );
4235 $frame = $this->getPreprocessor()->newFrame();
4236 $text = $frame->expand( $dom );
4239 $text = $this->mStripState
->unstripBoth( $text );
4246 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4248 * @param $text String
4249 * @return String: signature text with /~{3,5}/ removed
4251 function cleanSigInSig( $text ) {
4252 $text = preg_replace( '/~{3,5}/', '', $text );
4257 * Set up some variables which are usually set up in parse()
4258 * so that an external function can call some class members with confidence
4260 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4261 $this->setTitle( $title );
4262 $this->mOptions
= $options;
4263 $this->setOutputType( $outputType );
4264 if ( $clearState ) {
4265 $this->clearState();
4270 * Wrapper for preprocess()
4272 * @param $text String: the text to preprocess
4273 * @param $options ParserOptions: options
4276 public function transformMsg( $text, $options ) {
4278 static $executing = false;
4280 # Guard against infinite recursion
4286 wfProfileIn( __METHOD__
);
4289 # It's not uncommon having a null $wgTitle in scripts. See r80898
4290 # Create a ghost title in such case
4291 $title = Title
::newFromText( 'Dwimmerlaik' );
4293 $text = $this->preprocess( $text, $title, $options );
4296 wfProfileOut( __METHOD__
);
4301 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4302 * The callback should have the following form:
4303 * function myParserHook( $text, $params, $parser ) { ... }
4305 * Transform and return $text. Use $parser for any required context, e.g. use
4306 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4308 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4309 * @param $callback Mixed: the callback function (and object) to use for the tag
4310 * @return The old value of the mTagHooks array associated with the hook
4312 public function setHook( $tag, $callback ) {
4313 $tag = strtolower( $tag );
4314 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4315 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4316 $this->mTagHooks
[$tag] = $callback;
4317 if ( !in_array( $tag, $this->mStripList
) ) {
4318 $this->mStripList
[] = $tag;
4324 function setTransparentTagHook( $tag, $callback ) {
4325 $tag = strtolower( $tag );
4326 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4327 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4328 $this->mTransparentTagHooks
[$tag] = $callback;
4334 * Remove all tag hooks
4336 function clearTagHooks() {
4337 $this->mTagHooks
= array();
4338 $this->mStripList
= $this->mDefaultStripList
;
4342 * Create a function, e.g. {{sum:1|2|3}}
4343 * The callback function should have the form:
4344 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4346 * Or with SFH_OBJECT_ARGS:
4347 * function myParserFunction( $parser, $frame, $args ) { ... }
4349 * The callback may either return the text result of the function, or an array with the text
4350 * in element 0, and a number of flags in the other elements. The names of the flags are
4351 * specified in the keys. Valid flags are:
4352 * found The text returned is valid, stop processing the template. This
4354 * nowiki Wiki markup in the return value should be escaped
4355 * isHTML The returned text is HTML, armour it against wikitext transformation
4357 * @param $id String: The magic word ID
4358 * @param $callback Mixed: the callback function (and object) to use
4359 * @param $flags Integer: a combination of the following flags:
4360 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4362 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4363 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4364 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4365 * the arguments, and to control the way they are expanded.
4367 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4368 * arguments, for instance:
4369 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4371 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4372 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4373 * working if/when this is changed.
4375 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4378 * Please read the documentation in includes/parser/Preprocessor.php for more information
4379 * about the methods available in PPFrame and PPNode.
4381 * @return The old callback function for this name, if any
4383 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4386 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4387 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4389 # Add to function cache
4390 $mw = MagicWord
::get( $id );
4392 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4394 $synonyms = $mw->getSynonyms();
4395 $sensitive = intval( $mw->isCaseSensitive() );
4397 foreach ( $synonyms as $syn ) {
4399 if ( !$sensitive ) {
4400 $syn = $wgContLang->lc( $syn );
4403 if ( !( $flags & SFH_NO_HASH
) ) {
4406 # Remove trailing colon
4407 if ( substr( $syn, -1, 1 ) === ':' ) {
4408 $syn = substr( $syn, 0, -1 );
4410 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4416 * Get all registered function hook identifiers
4420 function getFunctionHooks() {
4421 return array_keys( $this->mFunctionHooks
);
4425 * Create a tag function, e.g. <test>some stuff</test>.
4426 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4427 * Unlike parser functions, their content is not preprocessed.
4429 function setFunctionTagHook( $tag, $callback, $flags ) {
4430 $tag = strtolower( $tag );
4431 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4432 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4433 $this->mFunctionTagHooks
[$tag] : null;
4434 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4436 if ( !in_array( $tag, $this->mStripList
) ) {
4437 $this->mStripList
[] = $tag;
4444 * FIXME: update documentation. makeLinkObj() is deprecated.
4445 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4446 * Placeholders created in Skin::makeLinkObj()
4447 * Returns an array of link CSS classes, indexed by PDBK.
4449 function replaceLinkHolders( &$text, $options = 0 ) {
4450 return $this->mLinkHolders
->replace( $text );
4454 * Replace <!--LINK--> link placeholders with plain text of links
4455 * (not HTML-formatted).
4457 * @param $text String
4460 function replaceLinkHoldersText( $text ) {
4461 return $this->mLinkHolders
->replaceText( $text );
4465 * Renders an image gallery from a text with one line per image.
4466 * text labels may be given by using |-style alternative text. E.g.
4467 * Image:one.jpg|The number "1"
4468 * Image:tree.jpg|A tree
4469 * given as text will return the HTML of a gallery with two images,
4470 * labeled 'The number "1"' and
4473 function renderImageGallery( $text, $params ) {
4474 $ig = new ImageGallery();
4475 $ig->setContextTitle( $this->mTitle
);
4476 $ig->setShowBytes( false );
4477 $ig->setShowFilename( false );
4478 $ig->setParser( $this );
4479 $ig->setHideBadImages();
4480 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4481 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4482 $ig->mRevisionId
= $this->mRevisionId
;
4484 if ( isset( $params['showfilename'] ) ) {
4485 $ig->setShowFilename( true );
4487 $ig->setShowFilename( false );
4489 if ( isset( $params['caption'] ) ) {
4490 $caption = $params['caption'];
4491 $caption = htmlspecialchars( $caption );
4492 $caption = $this->replaceInternalLinks( $caption );
4493 $ig->setCaptionHtml( $caption );
4495 if ( isset( $params['perrow'] ) ) {
4496 $ig->setPerRow( $params['perrow'] );
4498 if ( isset( $params['widths'] ) ) {
4499 $ig->setWidths( $params['widths'] );
4501 if ( isset( $params['heights'] ) ) {
4502 $ig->setHeights( $params['heights'] );
4505 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4507 $lines = StringUtils
::explode( "\n", $text );
4508 foreach ( $lines as $line ) {
4509 # match lines like these:
4510 # Image:someimage.jpg|This is some image
4512 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4514 if ( count( $matches ) == 0 ) {
4518 if ( strpos( $matches[0], '%' ) !== false ) {
4519 $matches[1] = rawurldecode( $matches[1] );
4521 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4523 if ( is_null( $nt ) ) {
4524 # Bogus title. Ignore these so we don't bomb out later.
4527 if ( isset( $matches[3] ) ) {
4528 $label = $matches[3];
4533 $html = $this->recursiveTagParse( trim( $label ) );
4535 $ig->add( $nt, $html );
4537 # Only add real images (bug #5586)
4538 if ( $nt->getNamespace() == NS_FILE
) {
4539 $this->mOutput
->addImage( $nt->getDBkey() );
4542 return $ig->toHTML();
4545 function getImageParams( $handler ) {
4547 $handlerClass = get_class( $handler );
4551 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4552 # Initialise static lists
4553 static $internalParamNames = array(
4554 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4555 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4556 'bottom', 'text-bottom' ),
4557 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4558 'upright', 'border', 'link', 'alt' ),
4560 static $internalParamMap;
4561 if ( !$internalParamMap ) {
4562 $internalParamMap = array();
4563 foreach ( $internalParamNames as $type => $names ) {
4564 foreach ( $names as $name ) {
4565 $magicName = str_replace( '-', '_', "img_$name" );
4566 $internalParamMap[$magicName] = array( $type, $name );
4571 # Add handler params
4572 $paramMap = $internalParamMap;
4574 $handlerParamMap = $handler->getParamMap();
4575 foreach ( $handlerParamMap as $magic => $paramName ) {
4576 $paramMap[$magic] = array( 'handler', $paramName );
4579 $this->mImageParams
[$handlerClass] = $paramMap;
4580 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4582 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4586 * Parse image options text and use it to make an image
4588 * @param $title Title
4589 * @param $options String
4590 * @param $holders LinkHolderArray
4592 function makeImage( $title, $options, $holders = false ) {
4593 # Check if the options text is of the form "options|alt text"
4595 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4596 # * left no resizing, just left align. label is used for alt= only
4597 # * right same, but right aligned
4598 # * none same, but not aligned
4599 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4600 # * center center the image
4601 # * frame Keep original image size, no magnify-button.
4602 # * framed Same as "frame"
4603 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4604 # * upright reduce width for upright images, rounded to full __0 px
4605 # * border draw a 1px border around the image
4606 # * alt Text for HTML alt attribute (defaults to empty)
4607 # * link Set the target of the image link. Can be external, interwiki, or local
4608 # vertical-align values (no % or length right now):
4618 $parts = StringUtils
::explode( "|", $options );
4619 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4621 # Give extensions a chance to select the file revision for us
4622 $skip = $time = $descQuery = false;
4623 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4626 return $sk->link( $title );
4630 $file = wfFindFile( $title, array( 'time' => $time ) );
4632 $handler = $file ?
$file->getHandler() : false;
4634 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4636 # Process the input parameters
4638 $params = array( 'frame' => array(), 'handler' => array(),
4639 'horizAlign' => array(), 'vertAlign' => array() );
4640 foreach ( $parts as $part ) {
4641 $part = trim( $part );
4642 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4644 if ( isset( $paramMap[$magicName] ) ) {
4645 list( $type, $paramName ) = $paramMap[$magicName];
4647 # Special case; width and height come in one variable together
4648 if ( $type === 'handler' && $paramName === 'width' ) {
4650 # (bug 13500) In both cases (width/height and width only),
4651 # permit trailing "px" for backward compatibility.
4652 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4653 $width = intval( $m[1] );
4654 $height = intval( $m[2] );
4655 if ( $handler->validateParam( 'width', $width ) ) {
4656 $params[$type]['width'] = $width;
4659 if ( $handler->validateParam( 'height', $height ) ) {
4660 $params[$type]['height'] = $height;
4663 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4664 $width = intval( $value );
4665 if ( $handler->validateParam( 'width', $width ) ) {
4666 $params[$type]['width'] = $width;
4669 } # else no validation -- bug 13436
4671 if ( $type === 'handler' ) {
4672 # Validate handler parameter
4673 $validated = $handler->validateParam( $paramName, $value );
4675 # Validate internal parameters
4676 switch( $paramName ) {
4679 # @todo Fixme: possibly check validity here for
4680 # manualthumb? downstream behavior seems odd with
4681 # missing manual thumbs.
4683 $value = $this->stripAltText( $value, $holders );
4686 $chars = self
::EXT_LINK_URL_CLASS
;
4687 $prots = $this->mUrlProtocols
;
4688 if ( $value === '' ) {
4689 $paramName = 'no-link';
4692 } elseif ( preg_match( "/^$prots/", $value ) ) {
4693 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4694 $paramName = 'link-url';
4695 $this->mOutput
->addExternalLink( $value );
4696 if ( $this->mOptions
->getExternalLinkTarget() ) {
4697 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4702 $linkTitle = Title
::newFromText( $value );
4704 $paramName = 'link-title';
4705 $value = $linkTitle;
4706 $this->mOutput
->addLink( $linkTitle );
4712 # Most other things appear to be empty or numeric...
4713 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4718 $params[$type][$paramName] = $value;
4722 if ( !$validated ) {
4727 # Process alignment parameters
4728 if ( $params['horizAlign'] ) {
4729 $params['frame']['align'] = key( $params['horizAlign'] );
4731 if ( $params['vertAlign'] ) {
4732 $params['frame']['valign'] = key( $params['vertAlign'] );
4735 $params['frame']['caption'] = $caption;
4737 # Will the image be presented in a frame, with the caption below?
4738 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4739 isset( $params['frame']['framed'] ) ||
4740 isset( $params['frame']['thumbnail'] ) ||
4741 isset( $params['frame']['manualthumb'] );
4743 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4744 # came to also set the caption, ordinary text after the image -- which
4745 # makes no sense, because that just repeats the text multiple times in
4746 # screen readers. It *also* came to set the title attribute.
4748 # Now that we have an alt attribute, we should not set the alt text to
4749 # equal the caption: that's worse than useless, it just repeats the
4750 # text. This is the framed/thumbnail case. If there's no caption, we
4751 # use the unnamed parameter for alt text as well, just for the time be-
4752 # ing, if the unnamed param is set and the alt param is not.
4754 # For the future, we need to figure out if we want to tweak this more,
4755 # e.g., introducing a title= parameter for the title; ignoring the un-
4756 # named parameter entirely for images without a caption; adding an ex-
4757 # plicit caption= parameter and preserving the old magic unnamed para-
4759 if ( $imageIsFramed ) { # Framed image
4760 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4761 # No caption or alt text, add the filename as the alt text so
4762 # that screen readers at least get some description of the image
4763 $params['frame']['alt'] = $title->getText();
4765 # Do not set $params['frame']['title'] because tooltips don't make sense
4767 } else { # Inline image
4768 if ( !isset( $params['frame']['alt'] ) ) {
4769 # No alt text, use the "caption" for the alt text
4770 if ( $caption !== '') {
4771 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4773 # No caption, fall back to using the filename for the
4775 $params['frame']['alt'] = $title->getText();
4778 # Use the "caption" for the tooltip text
4779 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4782 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4784 # Linker does the rest
4785 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4787 # Give the handler a chance to modify the parser object
4789 $handler->parserTransformHook( $this, $file );
4795 protected function stripAltText( $caption, $holders ) {
4796 # Strip bad stuff out of the title (tooltip). We can't just use
4797 # replaceLinkHoldersText() here, because if this function is called
4798 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4800 $tooltip = $holders->replaceText( $caption );
4802 $tooltip = $this->replaceLinkHoldersText( $caption );
4805 # make sure there are no placeholders in thumbnail attributes
4806 # that are later expanded to html- so expand them now and
4808 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4809 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4815 * Set a flag in the output object indicating that the content is dynamic and
4816 * shouldn't be cached.
4818 function disableCache() {
4819 wfDebug( "Parser output marked as uncacheable.\n" );
4820 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4821 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4825 * Callback from the Sanitizer for expanding items found in HTML attribute
4826 * values, so they can be safely tested and escaped.
4828 * @param $text String
4829 * @param $frame PPFrame
4833 function attributeStripCallback( &$text, $frame = false ) {
4834 $text = $this->replaceVariables( $text, $frame );
4835 $text = $this->mStripState
->unstripBoth( $text );
4842 function getTags() {
4843 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4847 * Break wikitext input into sections, and either pull or replace
4848 * some particular section's text.
4850 * External callers should use the getSection and replaceSection methods.
4852 * @param $text String: Page wikitext
4853 * @param $section String: a section identifier string of the form:
4854 * <flag1> - <flag2> - ... - <section number>
4856 * Currently the only recognised flag is "T", which means the target section number
4857 * was derived during a template inclusion parse, in other words this is a template
4858 * section edit link. If no flags are given, it was an ordinary section edit link.
4859 * This flag is required to avoid a section numbering mismatch when a section is
4860 * enclosed by <includeonly> (bug 6563).
4862 * The section number 0 pulls the text before the first heading; other numbers will
4863 * pull the given section along with its lower-level subsections. If the section is
4864 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4866 * @param $mode String: one of "get" or "replace"
4867 * @param $newText String: replacement text for section data.
4868 * @return String: for "get", the extracted section text.
4869 * for "replace", the whole page with the section replaced.
4871 private function extractSections( $text, $section, $mode, $newText='' ) {
4872 global $wgTitle; # not generally used but removes an ugly failure mode
4873 $this->startExternalParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
4875 $frame = $this->getPreprocessor()->newFrame();
4877 # Process section extraction flags
4879 $sectionParts = explode( '-', $section );
4880 $sectionIndex = array_pop( $sectionParts );
4881 foreach ( $sectionParts as $part ) {
4882 if ( $part === 'T' ) {
4883 $flags |
= self
::PTD_FOR_INCLUSION
;
4886 # Preprocess the text
4887 $root = $this->preprocessToDom( $text, $flags );
4889 # <h> nodes indicate section breaks
4890 # They can only occur at the top level, so we can find them by iterating the root's children
4891 $node = $root->getFirstChild();
4893 # Find the target section
4894 if ( $sectionIndex == 0 ) {
4895 # Section zero doesn't nest, level=big
4896 $targetLevel = 1000;
4899 if ( $node->getName() === 'h' ) {
4900 $bits = $node->splitHeading();
4901 if ( $bits['i'] == $sectionIndex ) {
4902 $targetLevel = $bits['level'];
4906 if ( $mode === 'replace' ) {
4907 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4909 $node = $node->getNextSibling();
4915 if ( $mode === 'get' ) {
4922 # Find the end of the section, including nested sections
4924 if ( $node->getName() === 'h' ) {
4925 $bits = $node->splitHeading();
4926 $curLevel = $bits['level'];
4927 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4931 if ( $mode === 'get' ) {
4932 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4934 $node = $node->getNextSibling();
4937 # Write out the remainder (in replace mode only)
4938 if ( $mode === 'replace' ) {
4939 # Output the replacement text
4940 # Add two newlines on -- trailing whitespace in $newText is conventionally
4941 # stripped by the editor, so we need both newlines to restore the paragraph gap
4942 # Only add trailing whitespace if there is newText
4943 if ( $newText != "" ) {
4944 $outText .= $newText . "\n\n";
4948 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4949 $node = $node->getNextSibling();
4953 if ( is_string( $outText ) ) {
4954 # Re-insert stripped tags
4955 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4962 * This function returns the text of a section, specified by a number ($section).
4963 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4964 * the first section before any such heading (section 0).
4966 * If a section contains subsections, these are also returned.
4968 * @param $text String: text to look in
4969 * @param $section String: section identifier
4970 * @param $deftext String: default to return if section is not found
4971 * @return string text of the requested section
4973 public function getSection( $text, $section, $deftext='' ) {
4974 return $this->extractSections( $text, $section, "get", $deftext );
4978 * This function returns $oldtext after the content of the section
4979 * specified by $section has been replaced with $text.
4981 * @param $text String: former text of the article
4982 * @param $section Numeric: section identifier
4983 * @param $text String: replacing text
4984 * #return String: modified text
4986 public function replaceSection( $oldtext, $section, $text ) {
4987 return $this->extractSections( $oldtext, $section, "replace", $text );
4991 * Get the ID of the revision we are parsing
4993 * @return Mixed: integer or null
4995 function getRevisionId() {
4996 return $this->mRevisionId
;
5000 * Get the revision object for $this->mRevisionId
5002 * @return either a Revision object or null
5004 protected function getRevisionObject() {
5005 if ( !is_null( $this->mRevisionObject
) ) {
5006 return $this->mRevisionObject
;
5008 if ( is_null( $this->mRevisionId
) ) {
5012 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5013 return $this->mRevisionObject
;
5017 * Get the timestamp associated with the current revision, adjusted for
5018 * the default server-local timestamp
5020 function getRevisionTimestamp() {
5021 if ( is_null( $this->mRevisionTimestamp
) ) {
5022 wfProfileIn( __METHOD__
);
5024 $revObject = $this->getRevisionObject();
5025 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5027 if( $timestamp !== false ) {
5030 # The cryptic '' timezone parameter tells to use the site-default
5031 # timezone offset instead of the user settings.
5033 # Since this value will be saved into the parser cache, served
5034 # to other users, and potentially even used inside links and such,
5035 # it needs to be consistent for all visitors.
5036 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5039 wfProfileOut( __METHOD__
);
5041 return $this->mRevisionTimestamp
;
5045 * Get the name of the user that edited the last revision
5047 * @return String: user name
5049 function getRevisionUser() {
5050 if( is_null( $this->mRevisionUser
) ) {
5051 $revObject = $this->getRevisionObject();
5053 # if this template is subst: the revision id will be blank,
5054 # so just use the current user's name
5056 $this->mRevisionUser
= $revObject->getUserText();
5057 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5058 $this->mRevisionUser
= $this->getUser()->getName();
5061 return $this->mRevisionUser
;
5065 * Mutator for $mDefaultSort
5067 * @param $sort New value
5069 public function setDefaultSort( $sort ) {
5070 $this->mDefaultSort
= $sort;
5071 $this->mOutput
->setProperty( 'defaultsort', $sort );
5075 * Accessor for $mDefaultSort
5076 * Will use the empty string if none is set.
5078 * This value is treated as a prefix, so the
5079 * empty string is equivalent to sorting by
5084 public function getDefaultSort() {
5085 if ( $this->mDefaultSort
!== false ) {
5086 return $this->mDefaultSort
;
5093 * Accessor for $mDefaultSort
5094 * Unlike getDefaultSort(), will return false if none is set
5096 * @return string or false
5098 public function getCustomDefaultSort() {
5099 return $this->mDefaultSort
;
5103 * Try to guess the section anchor name based on a wikitext fragment
5104 * presumably extracted from a heading, for example "Header" from
5107 public function guessSectionNameFromWikiText( $text ) {
5108 # Strip out wikitext links(they break the anchor)
5109 $text = $this->stripSectionName( $text );
5110 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5111 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5115 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5116 * instead. For use in redirects, since IE6 interprets Redirect: headers
5117 * as something other than UTF-8 (apparently?), resulting in breakage.
5119 * @param $text String: The section name
5120 * @return string An anchor
5122 public function guessLegacySectionNameFromWikiText( $text ) {
5123 # Strip out wikitext links(they break the anchor)
5124 $text = $this->stripSectionName( $text );
5125 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5126 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5130 * Strips a text string of wikitext for use in a section anchor
5132 * Accepts a text string and then removes all wikitext from the
5133 * string and leaves only the resultant text (i.e. the result of
5134 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5135 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5136 * to create valid section anchors by mimicing the output of the
5137 * parser when headings are parsed.
5139 * @param $text String: text string to be stripped of wikitext
5140 * for use in a Section anchor
5141 * @return Filtered text string
5143 public function stripSectionName( $text ) {
5144 # Strip internal link markup
5145 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5146 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5148 # Strip external link markup (FIXME: Not Tolerant to blank link text
5149 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5150 # on how many empty links there are on the page - need to figure that out.
5151 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5153 # Parse wikitext quotes (italics & bold)
5154 $text = $this->doQuotes( $text );
5157 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5162 * strip/replaceVariables/unstrip for preprocessor regression testing
5164 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5165 if ( !$title instanceof Title
) {
5166 $title = Title
::newFromText( $title );
5168 $this->startExternalParse( $title, $options, $outputType, true );
5170 $text = $this->replaceVariables( $text );
5171 $text = $this->mStripState
->unstripBoth( $text );
5172 $text = Sanitizer
::removeHTMLtags( $text );
5176 function testPst( $text, $title, $options ) {
5178 if ( !$title instanceof Title
) {
5179 $title = Title
::newFromText( $title );
5181 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5184 function testPreprocess( $text, $title, $options ) {
5185 if ( !$title instanceof Title
) {
5186 $title = Title
::newFromText( $title );
5188 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5191 function markerSkipCallback( $s, $callback ) {
5194 while ( $i < strlen( $s ) ) {
5195 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5196 if ( $markerStart === false ) {
5197 $out .= call_user_func( $callback, substr( $s, $i ) );
5200 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5201 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5202 if ( $markerEnd === false ) {
5203 $out .= substr( $s, $markerStart );
5206 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5207 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5215 function serialiseHalfParsedText( $text ) {
5217 $data['text'] = $text;
5219 # First, find all strip markers, and store their
5221 $stripState = new StripState
;
5223 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5224 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5226 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5227 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5229 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5230 $replaceArray = $stripState->general
;
5231 $stripText = $this->mStripState
->general
->data
[$marker];
5232 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5233 $replaceArray = $stripState->nowiki
;
5234 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5236 throw new MWException( "Hanging strip marker: '$marker'." );
5239 $replaceArray->setPair( $marker, $stripText );
5242 $data['stripstate'] = $stripState;
5244 # Now, find all of our links, and store THEIR
5245 # data in an array! :)
5246 $links = array( 'internal' => array(), 'interwiki' => array() );
5250 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5251 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5254 if ( empty( $links['internal'][$ns] ) ) {
5255 $links['internal'][$ns] = array();
5258 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5259 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5260 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5266 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5267 $data = substr( $text, $start_pos );
5268 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5269 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5270 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5273 $data['linkholder'] = $links;
5280 * @param $data Array
5281 * @param $intPrefix String unique identifying prefix
5284 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5285 if ( !$intPrefix ) {
5286 $intPrefix = self
::getRandomString();
5289 # First, extract the strip state.
5290 $stripState = $data['stripstate'];
5291 $this->mStripState
->general
->merge( $stripState->general
);
5292 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5294 # Now, extract the text, and renumber links
5295 $text = $data['text'];
5296 $links = $data['linkholder'];
5299 foreach ( $links['internal'] as $ns => $nsLinks ) {
5300 foreach ( $nsLinks as $key => $entry ) {
5301 $newKey = $intPrefix . '-' . $key;
5302 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5304 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5309 foreach ( $links['interwiki'] as $key => $entry ) {
5310 $newKey = "$intPrefix-$key";
5311 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5313 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5316 # Should be good to go.
5322 * @todo document, briefly.
5326 var $general, $nowiki;
5328 function __construct() {
5329 $this->general
= new ReplacementArray
;
5330 $this->nowiki
= new ReplacementArray
;
5333 function unstripGeneral( $text ) {
5334 wfProfileIn( __METHOD__
);
5337 $text = $this->general
->replace( $text );
5338 } while ( $text !== $oldText );
5339 wfProfileOut( __METHOD__
);
5343 function unstripNoWiki( $text ) {
5344 wfProfileIn( __METHOD__
);
5347 $text = $this->nowiki
->replace( $text );
5348 } while ( $text !== $oldText );
5349 wfProfileOut( __METHOD__
);
5353 function unstripBoth( $text ) {
5354 wfProfileIn( __METHOD__
);
5357 $text = $this->general
->replace( $text );
5358 $text = $this->nowiki
->replace( $text );
5359 } while ( $text !== $oldText );
5360 wfProfileOut( __METHOD__
);
5366 * @todo document, briefly.
5369 class OnlyIncludeReplacer
{
5372 function replace( $matches ) {
5373 if ( substr( $matches[1], -1 ) === "\n" ) {
5374 $this->output
.= substr( $matches[1], 0, -1 );
5376 $this->output
.= $matches[1];