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';
59 * Update this version number when the output of serialiseHalfParsedText()
60 * changes in an incompatible way
62 const HALF_PARSED_VERSION
= 2;
64 # Flags for Parser::setFunctionHook
65 # Also available as global constants from Defines.php
66 const SFH_NO_HASH
= 1;
67 const SFH_OBJECT_ARGS
= 2;
69 # Constants needed for external link processing
70 # Everything except bracket, space, or control characters
71 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
72 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
73 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
75 # State constants for the definition list colon extraction
76 const COLON_STATE_TEXT
= 0;
77 const COLON_STATE_TAG
= 1;
78 const COLON_STATE_TAGSTART
= 2;
79 const COLON_STATE_CLOSETAG
= 3;
80 const COLON_STATE_TAGSLASH
= 4;
81 const COLON_STATE_COMMENT
= 5;
82 const COLON_STATE_COMMENTDASH
= 6;
83 const COLON_STATE_COMMENTDASHDASH
= 7;
85 # Flags for preprocessToDom
86 const PTD_FOR_INCLUSION
= 1;
88 # Allowed values for $this->mOutputType
89 # Parameter to startExternalParse().
90 const OT_HTML
= 1; # like parse()
91 const OT_WIKI
= 2; # like preSaveTransform()
92 const OT_PREPROCESS
= 3; # like preprocess()
94 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
96 # Marker Suffix needs to be accessible staticly.
97 const MARKER_SUFFIX
= "-QINU\x7f";
100 var $mTagHooks = array();
101 var $mTransparentTagHooks = array();
102 var $mFunctionHooks = array();
103 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
104 var $mFunctionTagHooks = array();
105 var $mStripList = array();
106 var $mDefaultStripList = array();
107 var $mVarCache = array();
108 var $mImageParams = array();
109 var $mImageParamsMagicArray = array();
110 var $mMarkerIndex = 0;
111 var $mFirstCall = true;
112 var $mVariables, $mSubstWords; # Initialised by initialiseVariables()
113 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
116 # Cleared with clearState():
117 var $mOutput, $mAutonumber, $mDTopen;
124 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
125 var $mLinkHolders, $mLinkID;
126 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
127 var $mTplExpandCache; # empty-frame expansion cache
128 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
129 var $mExpensiveFunctionCount; # number of expensive parser function calls
130 var $mUser; # User object; only used when doing pre-save transform
133 # These are variables reset at least once per parse regardless of $clearState
139 var $mTitle; # Title context, used for self-link rendering and similar things
140 var $mOutputType; # Output type, one of the OT_xxx constants
141 var $ot; # Shortcut alias, see setOutputType()
142 var $mRevisionObject; # The revision object of the specified revision ID
143 var $mRevisionId; # ID to display in {{REVISIONID}} tags
144 var $mRevisionTimestamp; # The timestamp of the specified revision ID
145 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
146 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
153 function __construct( $conf = array() ) {
154 $this->mConf
= $conf;
155 $this->mUrlProtocols
= wfUrlProtocols();
156 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
157 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
158 if ( isset( $conf['preprocessorClass'] ) ) {
159 $this->mPreprocessorClass
= $conf['preprocessorClass'];
160 } elseif ( extension_loaded( 'domxml' ) ) {
161 # PECL extension that conflicts with the core DOM extension (bug 13770)
162 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
163 $this->mPreprocessorClass
= 'Preprocessor_Hash';
164 } elseif ( extension_loaded( 'dom' ) ) {
165 $this->mPreprocessorClass
= 'Preprocessor_DOM';
167 $this->mPreprocessorClass
= 'Preprocessor_Hash';
172 * Reduce memory usage to reduce the impact of circular references
174 function __destruct() {
175 if ( isset( $this->mLinkHolders
) ) {
176 $this->mLinkHolders
->__destruct();
178 foreach ( $this as $name => $value ) {
179 unset( $this->$name );
184 * Do various kinds of initialisation on the first call of the parser
186 function firstCallInit() {
187 if ( !$this->mFirstCall
) {
190 $this->mFirstCall
= false;
192 wfProfileIn( __METHOD__
);
194 CoreParserFunctions
::register( $this );
195 CoreTagHooks
::register( $this );
196 $this->initialiseVariables();
198 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
199 wfProfileOut( __METHOD__
);
207 function clearState() {
208 wfProfileIn( __METHOD__
);
209 if ( $this->mFirstCall
) {
210 $this->firstCallInit();
212 $this->mOutput
= new ParserOutput
;
213 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
214 $this->mAutonumber
= 0;
215 $this->mLastSection
= '';
216 $this->mDTopen
= false;
217 $this->mIncludeCount
= array();
218 $this->mArgStack
= false;
219 $this->mInPre
= false;
220 $this->mLinkHolders
= new LinkHolderArray( $this );
222 $this->mRevisionObject
= $this->mRevisionTimestamp
=
223 $this->mRevisionId
= $this->mRevisionUser
= null;
224 $this->mVarCache
= array();
228 * Prefix for temporary replacement strings for the multipass parser.
229 * \x07 should never appear in input as it's disallowed in XML.
230 * Using it at the front also gives us a little extra robustness
231 * since it shouldn't match when butted up against identifier-like
234 * Must not consist of all title characters, or else it will change
235 * the behaviour of <nowiki> in a link.
237 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
238 # Changed to \x7f to allow XML double-parsing -- TS
239 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
240 $this->mStripState
= new StripState( $this->mUniqPrefix
);
243 # Clear these on every parse, bug 4549
244 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
246 $this->mShowToc
= true;
247 $this->mForceTocPosition
= false;
248 $this->mIncludeSizes
= array(
252 $this->mPPNodeCount
= 0;
253 $this->mDefaultSort
= false;
254 $this->mHeadings
= array();
255 $this->mDoubleUnderscores
= array();
256 $this->mExpensiveFunctionCount
= 0;
259 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
260 $this->mPreprocessor
= null;
263 wfRunHooks( 'ParserClearState', array( &$this ) );
264 wfProfileOut( __METHOD__
);
268 * Convert wikitext to HTML
269 * Do not call this function recursively.
271 * @param $text String: text we want to parse
272 * @param $title A title object
273 * @param $options ParserOptions
274 * @param $linestart boolean
275 * @param $clearState boolean
276 * @param $revid Int: number to pass in {{REVISIONID}}
277 * @return ParserOutput a ParserOutput
279 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
281 * First pass--just handle <nowiki> sections, pass the rest off
282 * to internalParse() which does all the real work.
285 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
286 $fname = __METHOD__
.'-' . wfGetCaller();
287 wfProfileIn( __METHOD__
);
288 wfProfileIn( $fname );
290 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
292 $oldRevisionId = $this->mRevisionId
;
293 $oldRevisionObject = $this->mRevisionObject
;
294 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
295 $oldRevisionUser = $this->mRevisionUser
;
296 if ( $revid !== null ) {
297 $this->mRevisionId
= $revid;
298 $this->mRevisionObject
= null;
299 $this->mRevisionTimestamp
= null;
300 $this->mRevisionUser
= null;
303 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
305 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
306 $text = $this->internalParse( $text );
308 $text = $this->mStripState
->unstripGeneral( $text );
310 # Clean up special characters, only run once, next-to-last before doBlockLevels
312 # french spaces, last one Guillemet-left
313 # only if there is something before the space
314 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
315 # french spaces, Guillemet-right
316 '/(\\302\\253) /' => '\\1 ',
317 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
319 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
321 $text = $this->doBlockLevels( $text, $linestart );
323 $this->replaceLinkHolders( $text );
326 * The page doesn't get language converted if
328 * b) Content isn't converted
329 * c) It's a conversion table
331 if ( !( $wgDisableLangConversion
332 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
333 ||
$this->mTitle
->isConversionTable() ) ) {
335 # The position of the convert() call should not be changed. it
336 # assumes that the links are all replaced and the only thing left
337 # is the <nowiki> mark.
339 $text = $wgContLang->convert( $text );
343 * A converted title will be provided in the output object if title and
344 * content conversion are enabled, the article text does not contain
345 * a conversion-suppressing double-underscore tag, and no
346 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
347 * automatic link conversion.
349 if ( !( $wgDisableLangConversion
350 ||
$wgDisableTitleConversion
351 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
352 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
353 ||
$this->mOutput
->getDisplayTitle() !== false ) )
355 $convruletitle = $wgContLang->getConvRuleTitle();
356 if ( $convruletitle ) {
357 $this->mOutput
->setTitleText( $convruletitle );
359 $titleText = $wgContLang->convertTitle( $title );
360 $this->mOutput
->setTitleText( $titleText );
364 $text = $this->mStripState
->unstripNoWiki( $text );
366 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
368 $text = $this->replaceTransparentTags( $text );
369 $text = $this->mStripState
->unstripGeneral( $text );
371 $text = Sanitizer
::normalizeCharReferences( $text );
373 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
374 $text = MWTidy
::tidy( $text );
376 # attempt to sanitize at least some nesting problems
377 # (bug #2702 and quite a few others)
379 # ''Something [http://www.cool.com cool''] -->
380 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
381 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
382 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
383 # fix up an anchor inside another anchor, only
384 # at least for a single single nested link (bug 3695)
385 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
386 '\\1\\2</a>\\3</a>\\1\\4</a>',
387 # fix div inside inline elements- doBlockLevels won't wrap a line which
388 # contains a div, so fix it up here; replace
389 # div with escaped text
390 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
391 '\\1\\3<div\\5>\\6</div>\\8\\9',
392 # remove empty italic or bold tag pairs, some
393 # introduced by rules above
394 '/<([bi])><\/\\1>/' => '',
397 $text = preg_replace(
398 array_keys( $tidyregs ),
399 array_values( $tidyregs ),
402 global $wgExpensiveParserFunctionLimit;
403 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
404 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
407 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
409 # Information on include size limits, for the benefit of users who try to skirt them
410 if ( $this->mOptions
->getEnableLimitReport() ) {
411 $max = $this->mOptions
->getMaxIncludeSize();
412 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
414 "NewPP limit report\n" .
415 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
416 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
417 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
419 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
420 $text .= "\n<!-- \n$limitReport-->\n";
422 $this->mOutput
->setText( $text );
424 $this->mRevisionId
= $oldRevisionId;
425 $this->mRevisionObject
= $oldRevisionObject;
426 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
427 $this->mRevisionUser
= $oldRevisionUser;
428 wfProfileOut( $fname );
429 wfProfileOut( __METHOD__
);
431 return $this->mOutput
;
435 * Recursive parser entry point that can be called from an extension tag
438 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
440 * @param $text String: text extension wants to have parsed
441 * @param $frame PPFrame: The frame to use for expanding any template variables
443 function recursiveTagParse( $text, $frame=false ) {
444 wfProfileIn( __METHOD__
);
445 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
446 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
447 $text = $this->internalParse( $text, false, $frame );
448 wfProfileOut( __METHOD__
);
453 * Expand templates and variables in the text, producing valid, static wikitext.
454 * Also removes comments.
456 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
457 wfProfileIn( __METHOD__
);
458 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
459 if ( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Process the wikitext for the ?preload= feature. (bug 5210)
473 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
474 * comments, templates, arguments, tags hooks and parser functions are untouched.
476 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
477 # Parser (re)initialisation
478 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
480 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
481 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
482 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
483 $text = $this->mStripState
->unstripBoth( $text );
488 * Get a random string
492 static public function getRandomString() {
493 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
497 * Set the current user.
498 * Should only be used when doing pre-save transform.
500 * @param $user Mixed: User object or null (to reset)
502 function setUser( $user ) {
503 $this->mUser
= $user;
507 * Accessor for mUniqPrefix.
511 public function uniqPrefix() {
512 if ( !isset( $this->mUniqPrefix
) ) {
513 # @todo Fixme: this is probably *horribly wrong*
514 # LanguageConverter seems to want $wgParser's uniqPrefix, however
515 # if this is called for a parser cache hit, the parser may not
516 # have ever been initialized in the first place.
517 # Not really sure what the heck is supposed to be going on here.
519 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
521 return $this->mUniqPrefix
;
525 * Set the context title
527 function setTitle( $t ) {
528 if ( !$t ||
$t instanceof FakeTitle
) {
529 $t = Title
::newFromText( 'NO TITLE' );
532 if ( strval( $t->getFragment() ) !== '' ) {
533 # Strip the fragment to avoid various odd effects
534 $this->mTitle
= clone $t;
535 $this->mTitle
->setFragment( '' );
542 * Accessor for the Title object
544 * @return Title object
546 function getTitle() {
547 return $this->mTitle
;
551 * Accessor/mutator for the Title object
553 * @param $x New Title object or null to just get the current one
554 * @return Title object
556 function Title( $x = null ) {
557 return wfSetVar( $this->mTitle
, $x );
561 * Set the output type
563 * @param $ot Integer: new value
565 function setOutputType( $ot ) {
566 $this->mOutputType
= $ot;
569 'html' => $ot == self
::OT_HTML
,
570 'wiki' => $ot == self
::OT_WIKI
,
571 'pre' => $ot == self
::OT_PREPROCESS
,
572 'plain' => $ot == self
::OT_PLAIN
,
577 * Accessor/mutator for the output type
579 * @param $x New value or null to just get the current one
582 function OutputType( $x = null ) {
583 return wfSetVar( $this->mOutputType
, $x );
587 * Get the ParserOutput object
589 * @return ParserOutput object
591 function getOutput() {
592 return $this->mOutput
;
596 * Get the ParserOptions object
598 * @return ParserOptions object
600 function getOptions() {
601 return $this->mOptions
;
605 * Accessor/mutator for the ParserOptions object
607 * @param $x New value or null to just get the current one
608 * @return Current ParserOptions object
610 function Options( $x = null ) {
611 return wfSetVar( $this->mOptions
, $x );
614 function nextLinkID() {
615 return $this->mLinkID++
;
618 function setLinkID( $id ) {
619 $this->mLinkID
= $id;
625 function getFunctionLang() {
626 global $wgLang, $wgContLang;
628 $target = $this->mOptions
->getTargetLanguage();
629 if ( $target !== null ) {
632 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
637 * Get a User object either from $this->mUser, if set, or from the
638 * ParserOptions object otherwise
640 * @return User object
643 if ( !is_null( $this->mUser
) ) {
646 return $this->mOptions
->getUser();
650 * Get a preprocessor object
652 * @return Preprocessor instance
654 function getPreprocessor() {
655 if ( !isset( $this->mPreprocessor
) ) {
656 $class = $this->mPreprocessorClass
;
657 $this->mPreprocessor
= new $class( $this );
659 return $this->mPreprocessor
;
663 * Replaces all occurrences of HTML-style comments and the given tags
664 * in the text with a random marker and returns the next text. The output
665 * parameter $matches will be an associative array filled with data in
667 * 'UNIQ-xxxxx' => array(
670 * array( 'param' => 'x' ),
671 * '<element param="x">tag content</element>' ) )
673 * @param $elements list of element names. Comments are always extracted.
674 * @param $text Source text string.
675 * @param $matches Out parameter, Array: extracted tags
676 * @param $uniq_prefix
677 * @return String: stripped text
681 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
686 $taglist = implode( '|', $elements );
687 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
689 while ( $text != '' ) {
690 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
692 if ( count( $p ) < 5 ) {
695 if ( count( $p ) > 5 ) {
709 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
710 $stripped .= $marker;
712 if ( $close === '/>' ) {
713 # Empty element tag, <tag />
718 if ( $element === '!--' ) {
721 $end = "/(<\\/$element\\s*>)/i";
723 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
725 if ( count( $q ) < 3 ) {
726 # No end tag -- let it run out to the end of the text.
735 $matches[$marker] = array( $element,
737 Sanitizer
::decodeTagAttributes( $attributes ),
738 "<$element$attributes$close$content$tail" );
744 * Get a list of strippable XML-like elements
746 function getStripList() {
747 return $this->mStripList
;
751 * @deprecated use replaceVariables
753 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
758 * Restores pre, math, and other extensions removed by strip()
760 * always call unstripNoWiki() after this one
762 * @deprecated use $this->mStripState->unstrip()
764 function unstrip( $text, $state ) {
765 return $state->unstripGeneral( $text );
769 * Always call this after unstrip() to preserve the order
772 * @deprecated use $this->mStripState->unstrip()
774 function unstripNoWiki( $text, $state ) {
775 return $state->unstripNoWiki( $text );
779 * @deprecated use $this->mStripState->unstripBoth()
781 function unstripForHTML( $text ) {
782 return $this->mStripState
->unstripBoth( $text );
786 * Add an item to the strip state
787 * Returns the unique tag which must be inserted into the stripped text
788 * The tag will be replaced with the original text in unstrip()
792 function insertStripItem( $text ) {
793 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
794 $this->mMarkerIndex++
;
795 $this->mStripState
->addGeneral( $rnd, $text );
800 * Interface with html tidy
801 * @deprecated Use MWTidy::tidy()
803 public static function tidy( $text ) {
804 wfDeprecated( __METHOD__
);
805 return MWTidy
::tidy( $text );
809 * parse the wiki syntax used to render tables
813 function doTableStuff( $text ) {
814 wfProfileIn( __METHOD__
);
816 $lines = StringUtils
::explode( "\n", $text );
818 $td_history = array(); # Is currently a td tag open?
819 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
820 $tr_history = array(); # Is currently a tr tag open?
821 $tr_attributes = array(); # history of tr attributes
822 $has_opened_tr = array(); # Did this table open a <tr> element?
823 $indent_level = 0; # indent level of the table
825 foreach ( $lines as $outLine ) {
826 $line = trim( $outLine );
828 if ( $line === '' ) { # empty line, go to next line
829 $out .= $outLine."\n";
833 $first_character = $line[0];
836 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
837 # First check if we are starting a new table
838 $indent_level = strlen( $matches[1] );
840 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
841 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
843 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
844 array_push( $td_history , false );
845 array_push( $last_tag_history , '' );
846 array_push( $tr_history , false );
847 array_push( $tr_attributes , '' );
848 array_push( $has_opened_tr , false );
849 } elseif ( count( $td_history ) == 0 ) {
850 # Don't do any of the following
851 $out .= $outLine."\n";
853 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
854 # We are ending a table
855 $line = '</table>' . substr( $line , 2 );
856 $last_tag = array_pop( $last_tag_history );
858 if ( !array_pop( $has_opened_tr ) ) {
859 $line = "<tr><td></td></tr>{$line}";
862 if ( array_pop( $tr_history ) ) {
863 $line = "</tr>{$line}";
866 if ( array_pop( $td_history ) ) {
867 $line = "</{$last_tag}>{$line}";
869 array_pop( $tr_attributes );
870 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
871 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
872 # Now we have a table row
873 $line = preg_replace( '#^\|-+#', '', $line );
875 # Whats after the tag is now only attributes
876 $attributes = $this->mStripState
->unstripBoth( $line );
877 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
878 array_pop( $tr_attributes );
879 array_push( $tr_attributes, $attributes );
882 $last_tag = array_pop( $last_tag_history );
883 array_pop( $has_opened_tr );
884 array_push( $has_opened_tr , true );
886 if ( array_pop( $tr_history ) ) {
890 if ( array_pop( $td_history ) ) {
891 $line = "</{$last_tag}>{$line}";
895 array_push( $tr_history , false );
896 array_push( $td_history , false );
897 array_push( $last_tag_history , '' );
898 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
899 # This might be cell elements, td, th or captions
900 if ( substr( $line , 0 , 2 ) === '|+' ) {
901 $first_character = '+';
902 $line = substr( $line , 1 );
905 $line = substr( $line , 1 );
907 if ( $first_character === '!' ) {
908 $line = str_replace( '!!' , '||' , $line );
911 # Split up multiple cells on the same line.
912 # FIXME : This can result in improper nesting of tags processed
913 # by earlier parser steps, but should avoid splitting up eg
914 # attribute values containing literal "||".
915 $cells = StringUtils
::explodeMarkup( '||' , $line );
919 # Loop through each table cell
920 foreach ( $cells as $cell ) {
922 if ( $first_character !== '+' ) {
923 $tr_after = array_pop( $tr_attributes );
924 if ( !array_pop( $tr_history ) ) {
925 $previous = "<tr{$tr_after}>\n";
927 array_push( $tr_history , true );
928 array_push( $tr_attributes , '' );
929 array_pop( $has_opened_tr );
930 array_push( $has_opened_tr , true );
933 $last_tag = array_pop( $last_tag_history );
935 if ( array_pop( $td_history ) ) {
936 $previous = "</{$last_tag}>\n{$previous}";
939 if ( $first_character === '|' ) {
941 } elseif ( $first_character === '!' ) {
943 } elseif ( $first_character === '+' ) {
944 $last_tag = 'caption';
949 array_push( $last_tag_history , $last_tag );
951 # A cell could contain both parameters and data
952 $cell_data = explode( '|' , $cell , 2 );
954 # Bug 553: Note that a '|' inside an invalid link should not
955 # be mistaken as delimiting cell parameters
956 if ( strpos( $cell_data[0], '[[' ) !== false ) {
957 $cell = "{$previous}<{$last_tag}>{$cell}";
958 } elseif ( count( $cell_data ) == 1 ) {
959 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
961 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
962 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
963 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
967 array_push( $td_history , true );
970 $out .= $outLine . "\n";
973 # Closing open td, tr && table
974 while ( count( $td_history ) > 0 ) {
975 if ( array_pop( $td_history ) ) {
978 if ( array_pop( $tr_history ) ) {
981 if ( !array_pop( $has_opened_tr ) ) {
982 $out .= "<tr><td></td></tr>\n" ;
985 $out .= "</table>\n";
988 # Remove trailing line-ending (b/c)
989 if ( substr( $out, -1 ) === "\n" ) {
990 $out = substr( $out, 0, -1 );
993 # special case: don't return empty table
994 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
998 wfProfileOut( __METHOD__
);
1004 * Helper function for parse() that transforms wiki markup into
1005 * HTML. Only called for $mOutputType == self::OT_HTML.
1009 function internalParse( $text, $isMain = true, $frame=false ) {
1010 wfProfileIn( __METHOD__
);
1014 # Hook to suspend the parser in this state
1015 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1016 wfProfileOut( __METHOD__
);
1020 # if $frame is provided, then use $frame for replacing any variables
1022 # use frame depth to infer how include/noinclude tags should be handled
1023 # depth=0 means this is the top-level document; otherwise it's an included document
1024 if ( !$frame->depth
) {
1027 $flag = Parser
::PTD_FOR_INCLUSION
;
1029 $dom = $this->preprocessToDom( $text, $flag );
1030 $text = $frame->expand( $dom );
1032 # if $frame is not provided, then use old-style replaceVariables
1033 $text = $this->replaceVariables( $text );
1036 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1037 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1039 # Tables need to come after variable replacement for things to work
1040 # properly; putting them before other transformations should keep
1041 # exciting things like link expansions from showing up in surprising
1043 $text = $this->doTableStuff( $text );
1045 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1047 $text = $this->doDoubleUnderscore( $text );
1049 $text = $this->doHeadings( $text );
1050 if ( $this->mOptions
->getUseDynamicDates() ) {
1051 $df = DateFormatter
::getInstance();
1052 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1054 $text = $this->replaceInternalLinks( $text );
1055 $text = $this->doAllQuotes( $text );
1056 $text = $this->replaceExternalLinks( $text );
1058 # replaceInternalLinks may sometimes leave behind
1059 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1060 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1062 $text = $this->doMagicLinks( $text );
1063 $text = $this->formatHeadings( $text, $origText, $isMain );
1065 wfProfileOut( __METHOD__
);
1070 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1071 * magic external links.
1076 function doMagicLinks( $text ) {
1077 wfProfileIn( __METHOD__
);
1078 $prots = $this->mUrlProtocols
;
1079 $urlChar = self
::EXT_LINK_URL_CLASS
;
1080 $text = preg_replace_callback(
1082 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1083 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1084 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1085 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1086 ISBN\s+(\b # m[5]: ISBN, capture number
1087 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1088 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1089 [0-9Xx] # check digit
1091 )!x', array( &$this, 'magicLinkCallback' ), $text );
1092 wfProfileOut( __METHOD__
);
1096 function magicLinkCallback( $m ) {
1097 if ( isset( $m[1] ) && $m[1] !== '' ) {
1100 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1103 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1104 # Free external link
1105 return $this->makeFreeExternalLink( $m[0] );
1106 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1108 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1111 $CssClass = 'mw-magiclink-rfc';
1113 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1115 $urlmsg = 'pubmedurl';
1116 $CssClass = 'mw-magiclink-pmid';
1119 throw new MWException( __METHOD__
.': unrecognised match type "' .
1120 substr( $m[0], 0, 20 ) . '"' );
1122 $url = wfMsgForContent( $urlmsg, $id );
1123 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1124 return $sk->makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1125 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1128 $num = strtr( $isbn, array(
1133 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1135 $titleObj->escapeLocalUrl() .
1136 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1143 * Make a free external link, given a user-supplied URL
1147 function makeFreeExternalLink( $url ) {
1149 wfProfileIn( __METHOD__
);
1151 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1154 # The characters '<' and '>' (which were escaped by
1155 # removeHTMLtags()) should not be included in
1156 # URLs, per RFC 2396.
1158 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1159 $trail = substr( $url, $m2[0][1] ) . $trail;
1160 $url = substr( $url, 0, $m2[0][1] );
1163 # Move trailing punctuation to $trail
1165 # If there is no left bracket, then consider right brackets fair game too
1166 if ( strpos( $url, '(' ) === false ) {
1170 $numSepChars = strspn( strrev( $url ), $sep );
1171 if ( $numSepChars ) {
1172 $trail = substr( $url, -$numSepChars ) . $trail;
1173 $url = substr( $url, 0, -$numSepChars );
1176 $url = Sanitizer
::cleanUrl( $url );
1178 # Is this an external image?
1179 $text = $this->maybeMakeExternalImage( $url );
1180 if ( $text === false ) {
1181 # Not an image, make a link
1182 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1183 $this->getExternalLinkAttribs( $url ) );
1184 # Register it in the output object...
1185 # Replace unnecessary URL escape codes with their equivalent characters
1186 $pasteurized = self
::replaceUnusualEscapes( $url );
1187 $this->mOutput
->addExternalLink( $pasteurized );
1189 wfProfileOut( __METHOD__
);
1190 return $text . $trail;
1195 * Parse headers and return html
1199 function doHeadings( $text ) {
1200 wfProfileIn( __METHOD__
);
1201 for ( $i = 6; $i >= 1; --$i ) {
1202 $h = str_repeat( '=', $i );
1203 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1204 "<h$i>\\1</h$i>", $text );
1206 wfProfileOut( __METHOD__
);
1211 * Replace single quotes with HTML markup
1213 * @return string the altered text
1215 function doAllQuotes( $text ) {
1216 wfProfileIn( __METHOD__
);
1218 $lines = StringUtils
::explode( "\n", $text );
1219 foreach ( $lines as $line ) {
1220 $outtext .= $this->doQuotes( $line ) . "\n";
1222 $outtext = substr( $outtext, 0,-1 );
1223 wfProfileOut( __METHOD__
);
1228 * Helper function for doAllQuotes()
1230 public function doQuotes( $text ) {
1231 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1232 if ( count( $arr ) == 1 ) {
1235 # First, do some preliminary work. This may shift some apostrophes from
1236 # being mark-up to being text. It also counts the number of occurrences
1237 # of bold and italics mark-ups.
1240 for ( $i = 0; $i < count( $arr ); $i++
) {
1241 if ( ( $i %
2 ) == 1 ) {
1242 # If there are ever four apostrophes, assume the first is supposed to
1243 # be text, and the remaining three constitute mark-up for bold text.
1244 if ( strlen( $arr[$i] ) == 4 ) {
1247 } elseif ( strlen( $arr[$i] ) > 5 ) {
1248 # If there are more than 5 apostrophes in a row, assume they're all
1249 # text except for the last 5.
1250 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1253 # Count the number of occurrences of bold and italics mark-ups.
1254 # We are not counting sequences of five apostrophes.
1255 if ( strlen( $arr[$i] ) == 2 ) {
1257 } elseif ( strlen( $arr[$i] ) == 3 ) {
1259 } elseif ( strlen( $arr[$i] ) == 5 ) {
1266 # If there is an odd number of both bold and italics, it is likely
1267 # that one of the bold ones was meant to be an apostrophe followed
1268 # by italics. Which one we cannot know for certain, but it is more
1269 # likely to be one that has a single-letter word before it.
1270 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1272 $firstsingleletterword = -1;
1273 $firstmultiletterword = -1;
1275 foreach ( $arr as $r ) {
1276 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1277 $x1 = substr( $arr[$i-1], -1 );
1278 $x2 = substr( $arr[$i-1], -2, 1 );
1279 if ( $x1 === ' ' ) {
1280 if ( $firstspace == -1 ) {
1283 } elseif ( $x2 === ' ') {
1284 if ( $firstsingleletterword == -1 ) {
1285 $firstsingleletterword = $i;
1288 if ( $firstmultiletterword == -1 ) {
1289 $firstmultiletterword = $i;
1296 # If there is a single-letter word, use it!
1297 if ( $firstsingleletterword > -1 ) {
1298 $arr[$firstsingleletterword] = "''";
1299 $arr[$firstsingleletterword-1] .= "'";
1300 } elseif ( $firstmultiletterword > -1 ) {
1301 # If not, but there's a multi-letter word, use that one.
1302 $arr[$firstmultiletterword] = "''";
1303 $arr[$firstmultiletterword-1] .= "'";
1304 } elseif ( $firstspace > -1 ) {
1305 # ... otherwise use the first one that has neither.
1306 # (notice that it is possible for all three to be -1 if, for example,
1307 # there is only one pentuple-apostrophe in the line)
1308 $arr[$firstspace] = "''";
1309 $arr[$firstspace-1] .= "'";
1313 # Now let's actually convert our apostrophic mush to HTML!
1318 foreach ( $arr as $r ) {
1319 if ( ( $i %
2 ) == 0 ) {
1320 if ( $state === 'both' ) {
1326 if ( strlen( $r ) == 2 ) {
1327 if ( $state === 'i' ) {
1328 $output .= '</i>'; $state = '';
1329 } elseif ( $state === 'bi' ) {
1330 $output .= '</i>'; $state = 'b';
1331 } elseif ( $state === 'ib' ) {
1332 $output .= '</b></i><b>'; $state = 'b';
1333 } elseif ( $state === 'both' ) {
1334 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1335 } else { # $state can be 'b' or ''
1336 $output .= '<i>'; $state .= 'i';
1338 } elseif ( strlen( $r ) == 3 ) {
1339 if ( $state === 'b' ) {
1340 $output .= '</b>'; $state = '';
1341 } elseif ( $state === 'bi' ) {
1342 $output .= '</i></b><i>'; $state = 'i';
1343 } elseif ( $state === 'ib' ) {
1344 $output .= '</b>'; $state = 'i';
1345 } elseif ( $state === 'both' ) {
1346 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1347 } else { # $state can be 'i' or ''
1348 $output .= '<b>'; $state .= 'b';
1350 } elseif ( strlen( $r ) == 5 ) {
1351 if ( $state === 'b' ) {
1352 $output .= '</b><i>'; $state = 'i';
1353 } elseif ( $state === 'i' ) {
1354 $output .= '</i><b>'; $state = 'b';
1355 } elseif ( $state === 'bi' ) {
1356 $output .= '</i></b>'; $state = '';
1357 } elseif ( $state === 'ib' ) {
1358 $output .= '</b></i>'; $state = '';
1359 } elseif ( $state === 'both' ) {
1360 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1361 } else { # ($state == '')
1362 $buffer = ''; $state = 'both';
1368 # Now close all remaining tags. Notice that the order is important.
1369 if ( $state === 'b' ||
$state === 'ib' ) {
1372 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1375 if ( $state === 'bi' ) {
1378 # There might be lonely ''''', so make sure we have a buffer
1379 if ( $state === 'both' && $buffer ) {
1380 $output .= '<b><i>'.$buffer.'</i></b>';
1387 * Replace external links (REL)
1389 * Note: this is all very hackish and the order of execution matters a lot.
1390 * Make sure to run maintenance/parserTests.php if you change this code.
1394 function replaceExternalLinks( $text ) {
1396 wfProfileIn( __METHOD__
);
1398 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1400 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1401 $s = array_shift( $bits );
1404 while ( $i<count( $bits ) ) {
1406 $protocol = $bits[$i++
];
1407 $text = $bits[$i++
];
1408 $trail = $bits[$i++
];
1410 # The characters '<' and '>' (which were escaped by
1411 # removeHTMLtags()) should not be included in
1412 # URLs, per RFC 2396.
1414 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1415 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1416 $url = substr( $url, 0, $m2[0][1] );
1419 # If the link text is an image URL, replace it with an <img> tag
1420 # This happened by accident in the original parser, but some people used it extensively
1421 $img = $this->maybeMakeExternalImage( $text );
1422 if ( $img !== false ) {
1428 # Set linktype for CSS - if URL==text, link is essentially free
1429 $linktype = ( $text === $url ) ?
'free' : 'text';
1431 # No link text, e.g. [http://domain.tld/some.link]
1432 if ( $text == '' ) {
1433 # Autonumber if allowed. See bug #5918
1434 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1435 $langObj = $this->getFunctionLang();
1436 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1437 $linktype = 'autonumber';
1439 # Otherwise just use the URL
1440 $text = htmlspecialchars( $url );
1444 # Have link text, e.g. [http://domain.tld/some.link text]s
1446 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1449 $text = $wgContLang->markNoConversion( $text );
1451 $url = Sanitizer
::cleanUrl( $url );
1453 # Use the encoded URL
1454 # This means that users can paste URLs directly into the text
1455 # Funny characters like ö aren't valid in URLs anyway
1456 # This was changed in August 2004
1457 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1458 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1460 # Register link in the output object.
1461 # Replace unnecessary URL escape codes with the referenced character
1462 # This prevents spammers from hiding links from the filters
1463 $pasteurized = self
::replaceUnusualEscapes( $url );
1464 $this->mOutput
->addExternalLink( $pasteurized );
1467 wfProfileOut( __METHOD__
);
1472 * Get an associative array of additional HTML attributes appropriate for a
1473 * particular external link. This currently may include rel => nofollow
1474 * (depending on configuration, namespace, and the URL's domain) and/or a
1475 * target attribute (depending on configuration).
1477 * @param $url String: optional URL, to extract the domain from for rel =>
1478 * nofollow if appropriate
1479 * @return Array: associative array of HTML attributes
1481 function getExternalLinkAttribs( $url = false ) {
1483 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1484 $ns = $this->mTitle
->getNamespace();
1485 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1486 $attribs['rel'] = 'nofollow';
1488 global $wgNoFollowDomainExceptions;
1489 if ( $wgNoFollowDomainExceptions ) {
1490 $bits = wfParseUrl( $url );
1491 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1492 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1493 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1494 unset( $attribs['rel'] );
1501 if ( $this->mOptions
->getExternalLinkTarget() ) {
1502 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1509 * Replace unusual URL escape codes with their equivalent characters
1511 * @param $url String
1514 * @todo This can merge genuinely required bits in the path or query string,
1515 * breaking legit URLs. A proper fix would treat the various parts of
1516 * the URL differently; as a workaround, just use the output for
1517 * statistical records, not for actual linking/output.
1519 static function replaceUnusualEscapes( $url ) {
1520 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1521 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1525 * Callback function used in replaceUnusualEscapes().
1526 * Replaces unusual URL escape codes with their equivalent character
1528 private static function replaceUnusualEscapesCallback( $matches ) {
1529 $char = urldecode( $matches[0] );
1530 $ord = ord( $char );
1531 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1532 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1533 # No, shouldn't be escaped
1536 # Yes, leave it escaped
1542 * make an image if it's allowed, either through the global
1543 * option, through the exception, or through the on-wiki whitelist
1546 function maybeMakeExternalImage( $url ) {
1547 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1548 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1549 $imagesexception = !empty( $imagesfrom );
1551 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1552 if ( $imagesexception && is_array( $imagesfrom ) ) {
1553 $imagematch = false;
1554 foreach ( $imagesfrom as $match ) {
1555 if ( strpos( $url, $match ) === 0 ) {
1560 } elseif ( $imagesexception ) {
1561 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1563 $imagematch = false;
1565 if ( $this->mOptions
->getAllowExternalImages()
1566 ||
( $imagesexception && $imagematch ) ) {
1567 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1569 $text = $sk->makeExternalImage( $url );
1572 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1573 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1574 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1575 foreach ( $whitelist as $entry ) {
1576 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1577 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1580 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1581 # Image matches a whitelist entry
1582 $text = $sk->makeExternalImage( $url );
1591 * Process [[ ]] wikilinks
1592 * @return String: processed text
1596 function replaceInternalLinks( $s ) {
1597 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1602 * Process [[ ]] wikilinks (RIL)
1603 * @return LinkHolderArray
1607 function replaceInternalLinks2( &$s ) {
1610 wfProfileIn( __METHOD__
);
1612 wfProfileIn( __METHOD__
.'-setup' );
1613 static $tc = FALSE, $e1, $e1_img;
1614 # the % is needed to support urlencoded titles as well
1616 $tc = Title
::legalChars() . '#%';
1617 # Match a link having the form [[namespace:link|alternate]]trail
1618 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1619 # Match cases where there is no "]]", which might still be images
1620 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1623 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1624 $holders = new LinkHolderArray( $this );
1626 # split the entire text string on occurences of [[
1627 $a = StringUtils
::explode( '[[', ' ' . $s );
1628 # get the first element (all text up to first [[), and remove the space we added
1631 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1632 $s = substr( $s, 1 );
1634 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1636 if ( $useLinkPrefixExtension ) {
1637 # Match the end of a line for a word that's not followed by whitespace,
1638 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1639 $e2 = wfMsgForContent( 'linkprefix' );
1642 if ( is_null( $this->mTitle
) ) {
1643 wfProfileOut( __METHOD__
.'-setup' );
1644 wfProfileOut( __METHOD__
);
1645 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1647 $nottalk = !$this->mTitle
->isTalkPage();
1649 if ( $useLinkPrefixExtension ) {
1651 if ( preg_match( $e2, $s, $m ) ) {
1652 $first_prefix = $m[2];
1654 $first_prefix = false;
1660 if ( $wgContLang->hasVariants() ) {
1661 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1663 $selflink = array( $this->mTitle
->getPrefixedText() );
1665 $useSubpages = $this->areSubpagesAllowed();
1666 wfProfileOut( __METHOD__
.'-setup' );
1668 # Loop for each link
1669 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1670 # Check for excessive memory usage
1671 if ( $holders->isBig() ) {
1673 # Do the existence check, replace the link holders and clear the array
1674 $holders->replace( $s );
1678 if ( $useLinkPrefixExtension ) {
1679 wfProfileIn( __METHOD__
.'-prefixhandling' );
1680 if ( preg_match( $e2, $s, $m ) ) {
1687 if ( $first_prefix ) {
1688 $prefix = $first_prefix;
1689 $first_prefix = false;
1691 wfProfileOut( __METHOD__
.'-prefixhandling' );
1694 $might_be_img = false;
1696 wfProfileIn( __METHOD__
."-e1" );
1697 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1699 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1700 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1701 # the real problem is with the $e1 regex
1704 # Still some problems for cases where the ] is meant to be outside punctuation,
1705 # and no image is in sight. See bug 2095.
1707 if ( $text !== '' &&
1708 substr( $m[3], 0, 1 ) === ']' &&
1709 strpos( $text, '[' ) !== false
1712 $text .= ']'; # so that replaceExternalLinks($text) works later
1713 $m[3] = substr( $m[3], 1 );
1715 # fix up urlencoded title texts
1716 if ( strpos( $m[1], '%' ) !== false ) {
1717 # Should anchors '#' also be rejected?
1718 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1721 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1722 $might_be_img = true;
1724 if ( strpos( $m[1], '%' ) !== false ) {
1725 $m[1] = rawurldecode( $m[1] );
1728 } else { # Invalid form; output directly
1729 $s .= $prefix . '[[' . $line ;
1730 wfProfileOut( __METHOD__
."-e1" );
1733 wfProfileOut( __METHOD__
."-e1" );
1734 wfProfileIn( __METHOD__
."-misc" );
1736 # Don't allow internal links to pages containing
1737 # PROTO: where PROTO is a valid URL protocol; these
1738 # should be external links.
1739 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1740 $s .= $prefix . '[[' . $line ;
1741 wfProfileOut( __METHOD__
."-misc" );
1745 # Make subpage if necessary
1746 if ( $useSubpages ) {
1747 $link = $this->maybeDoSubpageLink( $m[1], $text );
1752 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1754 # Strip off leading ':'
1755 $link = substr( $link, 1 );
1758 wfProfileOut( __METHOD__
."-misc" );
1759 wfProfileIn( __METHOD__
."-title" );
1760 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1761 if ( $nt === null ) {
1762 $s .= $prefix . '[[' . $line;
1763 wfProfileOut( __METHOD__
."-title" );
1767 $ns = $nt->getNamespace();
1768 $iw = $nt->getInterWiki();
1769 wfProfileOut( __METHOD__
."-title" );
1771 if ( $might_be_img ) { # if this is actually an invalid link
1772 wfProfileIn( __METHOD__
."-might_be_img" );
1773 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1776 # look at the next 'line' to see if we can close it there
1778 $next_line = $a->current();
1779 if ( $next_line === false ||
$next_line === null ) {
1782 $m = explode( ']]', $next_line, 3 );
1783 if ( count( $m ) == 3 ) {
1784 # the first ]] closes the inner link, the second the image
1786 $text .= "[[{$m[0]}]]{$m[1]}";
1789 } elseif ( count( $m ) == 2 ) {
1790 # if there's exactly one ]] that's fine, we'll keep looking
1791 $text .= "[[{$m[0]}]]{$m[1]}";
1793 # if $next_line is invalid too, we need look no further
1794 $text .= '[[' . $next_line;
1799 # we couldn't find the end of this imageLink, so output it raw
1800 # but don't ignore what might be perfectly normal links in the text we've examined
1801 $holders->merge( $this->replaceInternalLinks2( $text ) );
1802 $s .= "{$prefix}[[$link|$text";
1803 # note: no $trail, because without an end, there *is* no trail
1804 wfProfileOut( __METHOD__
."-might_be_img" );
1807 } else { # it's not an image, so output it raw
1808 $s .= "{$prefix}[[$link|$text";
1809 # note: no $trail, because without an end, there *is* no trail
1810 wfProfileOut( __METHOD__
."-might_be_img" );
1813 wfProfileOut( __METHOD__
."-might_be_img" );
1816 $wasblank = ( $text == '' );
1820 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1821 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1822 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1823 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1824 $text = $this->doQuotes( $text );
1827 # Link not escaped by : , create the various objects
1831 wfProfileIn( __METHOD__
."-interwiki" );
1832 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1833 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1834 $s = rtrim( $s . $prefix );
1835 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1836 wfProfileOut( __METHOD__
."-interwiki" );
1839 wfProfileOut( __METHOD__
."-interwiki" );
1841 if ( $ns == NS_FILE
) {
1842 wfProfileIn( __METHOD__
."-image" );
1843 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1845 # if no parameters were passed, $text
1846 # becomes something like "File:Foo.png",
1847 # which we don't want to pass on to the
1851 # recursively parse links inside the image caption
1852 # actually, this will parse them in any other parameters, too,
1853 # but it might be hard to fix that, and it doesn't matter ATM
1854 $text = $this->replaceExternalLinks( $text );
1855 $holders->merge( $this->replaceInternalLinks2( $text ) );
1857 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1858 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1860 $s .= $prefix . $trail;
1862 $this->mOutput
->addImage( $nt->getDBkey() );
1863 wfProfileOut( __METHOD__
."-image" );
1868 if ( $ns == NS_CATEGORY
) {
1869 wfProfileIn( __METHOD__
."-category" );
1870 $s = rtrim( $s . "\n" ); # bug 87
1873 $sortkey = $this->getDefaultSort();
1877 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1878 $sortkey = str_replace( "\n", '', $sortkey );
1879 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1880 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1883 * Strip the whitespace Category links produce, see bug 87
1884 * @todo We might want to use trim($tmp, "\n") here.
1886 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1888 wfProfileOut( __METHOD__
."-category" );
1893 # Self-link checking
1894 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1895 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1896 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1901 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1902 # FIXME: Should do batch file existence checks, see comment below
1903 if ( $ns == NS_MEDIA
) {
1904 wfProfileIn( __METHOD__
."-media" );
1905 # Give extensions a chance to select the file revision for us
1906 $skip = $time = false;
1907 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1909 $link = $sk->link( $nt );
1911 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1913 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1914 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1915 $this->mOutput
->addImage( $nt->getDBkey() );
1916 wfProfileOut( __METHOD__
."-media" );
1920 wfProfileIn( __METHOD__
."-always_known" );
1921 # Some titles, such as valid special pages or files in foreign repos, should
1922 # be shown as bluelinks even though they're not included in the page table
1924 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1925 # batch file existence checks for NS_FILE and NS_MEDIA
1926 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1927 $this->mOutput
->addLink( $nt );
1928 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1930 # Links will be added to the output link list after checking
1931 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1933 wfProfileOut( __METHOD__
."-always_known" );
1935 wfProfileOut( __METHOD__
);
1940 * Make a link placeholder. The text returned can be later resolved to a real link with
1941 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1942 * parsing of interwiki links, and secondly to allow all existence checks and
1943 * article length checks (for stub links) to be bundled into a single query.
1947 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1948 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1952 * Render a forced-blue link inline; protect against double expansion of
1953 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1954 * Since this little disaster has to split off the trail text to avoid
1955 * breaking URLs in the following text without breaking trails on the
1956 * wiki links, it's been made into a horrible function.
1959 * @param $text String
1960 * @param $query String
1961 * @param $trail String
1962 * @param $prefix String
1963 * @return String: HTML-wikitext mix oh yuck
1965 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1966 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1967 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1968 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1969 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1970 return $this->armorLinks( $link ) . $trail;
1974 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1975 * going to go through further parsing steps before inline URL expansion.
1977 * Not needed quite as much as it used to be since free links are a bit
1978 * more sensible these days. But bracketed links are still an issue.
1980 * @param $text String: more-or-less HTML
1981 * @return String: less-or-more HTML with NOPARSE bits
1983 function armorLinks( $text ) {
1984 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1985 "{$this->mUniqPrefix}NOPARSE$1", $text );
1989 * Return true if subpage links should be expanded on this page.
1992 function areSubpagesAllowed() {
1993 # Some namespaces don't allow subpages
1994 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1998 * Handle link to subpage if necessary
2000 * @param $target String: the source of the link
2001 * @param &$text String: the link text, modified as necessary
2002 * @return string the full name of the link
2005 function maybeDoSubpageLink( $target, &$text ) {
2006 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2010 * Used by doBlockLevels()
2013 function closeParagraph() {
2015 if ( $this->mLastSection
!= '' ) {
2016 $result = '</' . $this->mLastSection
. ">\n";
2018 $this->mInPre
= false;
2019 $this->mLastSection
= '';
2024 * getCommon() returns the length of the longest common substring
2025 * of both arguments, starting at the beginning of both.
2028 function getCommon( $st1, $st2 ) {
2029 $fl = strlen( $st1 );
2030 $shorter = strlen( $st2 );
2031 if ( $fl < $shorter ) {
2035 for ( $i = 0; $i < $shorter; ++
$i ) {
2036 if ( $st1{$i} != $st2{$i} ) {
2044 * These next three functions open, continue, and close the list
2045 * element appropriate to the prefix character passed into them.
2048 function openList( $char ) {
2049 $result = $this->closeParagraph();
2051 if ( '*' === $char ) {
2052 $result .= '<ul><li>';
2053 } elseif ( '#' === $char ) {
2054 $result .= '<ol><li>';
2055 } elseif ( ':' === $char ) {
2056 $result .= '<dl><dd>';
2057 } elseif ( ';' === $char ) {
2058 $result .= '<dl><dt>';
2059 $this->mDTopen
= true;
2061 $result = '<!-- ERR 1 -->';
2069 * @param $char String
2072 function nextItem( $char ) {
2073 if ( '*' === $char ||
'#' === $char ) {
2075 } elseif ( ':' === $char ||
';' === $char ) {
2077 if ( $this->mDTopen
) {
2080 if ( ';' === $char ) {
2081 $this->mDTopen
= true;
2082 return $close . '<dt>';
2084 $this->mDTopen
= false;
2085 return $close . '<dd>';
2088 return '<!-- ERR 2 -->';
2093 * @param $char String
2096 function closeList( $char ) {
2097 if ( '*' === $char ) {
2098 $text = '</li></ul>';
2099 } elseif ( '#' === $char ) {
2100 $text = '</li></ol>';
2101 } elseif ( ':' === $char ) {
2102 if ( $this->mDTopen
) {
2103 $this->mDTopen
= false;
2104 $text = '</dt></dl>';
2106 $text = '</dd></dl>';
2109 return '<!-- ERR 3 -->';
2116 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2118 * @param $text String
2119 * @param $linestart Boolean: whether or not this is at the start of a line.
2121 * @return string the lists rendered as HTML
2123 function doBlockLevels( $text, $linestart ) {
2124 wfProfileIn( __METHOD__
);
2126 # Parsing through the text line by line. The main thing
2127 # happening here is handling of block-level elements p, pre,
2128 # and making lists from lines starting with * # : etc.
2130 $textLines = StringUtils
::explode( "\n", $text );
2132 $lastPrefix = $output = '';
2133 $this->mDTopen
= $inBlockElem = false;
2135 $paragraphStack = false;
2137 foreach ( $textLines as $oLine ) {
2139 if ( !$linestart ) {
2149 $lastPrefixLength = strlen( $lastPrefix );
2150 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2151 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2152 # If not in a <pre> element, scan for and figure out what prefixes are there.
2153 if ( !$this->mInPre
) {
2154 # Multiple prefixes may abut each other for nested lists.
2155 $prefixLength = strspn( $oLine, '*#:;' );
2156 $prefix = substr( $oLine, 0, $prefixLength );
2159 # ; and : are both from definition-lists, so they're equivalent
2160 # for the purposes of determining whether or not we need to open/close
2162 $prefix2 = str_replace( ';', ':', $prefix );
2163 $t = substr( $oLine, $prefixLength );
2164 $this->mInPre
= (bool)$preOpenMatch;
2166 # Don't interpret any other prefixes in preformatted text
2168 $prefix = $prefix2 = '';
2173 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2174 # Same as the last item, so no need to deal with nesting or opening stuff
2175 $output .= $this->nextItem( substr( $prefix, -1 ) );
2176 $paragraphStack = false;
2178 if ( substr( $prefix, -1 ) === ';') {
2179 # The one nasty exception: definition lists work like this:
2180 # ; title : definition text
2181 # So we check for : in the remainder text to split up the
2182 # title and definition, without b0rking links.
2184 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2186 $output .= $term . $this->nextItem( ':' );
2189 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2190 # We need to open or close prefixes, or both.
2192 # Either open or close a level...
2193 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2194 $paragraphStack = false;
2196 # Close all the prefixes which aren't shared.
2197 while ( $commonPrefixLength < $lastPrefixLength ) {
2198 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2199 --$lastPrefixLength;
2202 # Continue the current prefix if appropriate.
2203 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2204 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2207 # Open prefixes where appropriate.
2208 while ( $prefixLength > $commonPrefixLength ) {
2209 $char = substr( $prefix, $commonPrefixLength, 1 );
2210 $output .= $this->openList( $char );
2212 if ( ';' === $char ) {
2213 # FIXME: This is dupe of code above
2214 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2216 $output .= $term . $this->nextItem( ':' );
2219 ++
$commonPrefixLength;
2221 $lastPrefix = $prefix2;
2224 # If we have no prefixes, go to paragraph mode.
2225 if ( 0 == $prefixLength ) {
2226 wfProfileIn( __METHOD__
."-paragraph" );
2227 # No prefix (not in list)--go to paragraph mode
2228 # XXX: use a stack for nestable elements like span, table and div
2229 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2230 $closematch = preg_match(
2231 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2232 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2233 if ( $openmatch or $closematch ) {
2234 $paragraphStack = false;
2235 #Â TODO bug 5718: paragraph closed
2236 $output .= $this->closeParagraph();
2237 if ( $preOpenMatch and !$preCloseMatch ) {
2238 $this->mInPre
= true;
2240 $inBlockElem = !$closematch;
2241 } elseif ( !$inBlockElem && !$this->mInPre
) {
2242 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2244 if ( $this->mLastSection
!== 'pre' ) {
2245 $paragraphStack = false;
2246 $output .= $this->closeParagraph().'<pre>';
2247 $this->mLastSection
= 'pre';
2249 $t = substr( $t, 1 );
2252 if ( trim( $t ) === '' ) {
2253 if ( $paragraphStack ) {
2254 $output .= $paragraphStack.'<br />';
2255 $paragraphStack = false;
2256 $this->mLastSection
= 'p';
2258 if ( $this->mLastSection
!== 'p' ) {
2259 $output .= $this->closeParagraph();
2260 $this->mLastSection
= '';
2261 $paragraphStack = '<p>';
2263 $paragraphStack = '</p><p>';
2267 if ( $paragraphStack ) {
2268 $output .= $paragraphStack;
2269 $paragraphStack = false;
2270 $this->mLastSection
= 'p';
2271 } elseif ( $this->mLastSection
!== 'p' ) {
2272 $output .= $this->closeParagraph().'<p>';
2273 $this->mLastSection
= 'p';
2278 wfProfileOut( __METHOD__
."-paragraph" );
2280 # somewhere above we forget to get out of pre block (bug 785)
2281 if ( $preCloseMatch && $this->mInPre
) {
2282 $this->mInPre
= false;
2284 if ( $paragraphStack === false ) {
2288 while ( $prefixLength ) {
2289 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2292 if ( $this->mLastSection
!= '' ) {
2293 $output .= '</' . $this->mLastSection
. '>';
2294 $this->mLastSection
= '';
2297 wfProfileOut( __METHOD__
);
2302 * Split up a string on ':', ignoring any occurences inside tags
2303 * to prevent illegal overlapping.
2305 * @param $str String: the string to split
2306 * @param &$before String: set to everything before the ':'
2307 * @param &$after String: set to everything after the ':'
2308 * return String: the position of the ':', or false if none found
2310 function findColonNoLinks( $str, &$before, &$after ) {
2311 wfProfileIn( __METHOD__
);
2313 $pos = strpos( $str, ':' );
2314 if ( $pos === false ) {
2316 wfProfileOut( __METHOD__
);
2320 $lt = strpos( $str, '<' );
2321 if ( $lt === false ||
$lt > $pos ) {
2322 # Easy; no tag nesting to worry about
2323 $before = substr( $str, 0, $pos );
2324 $after = substr( $str, $pos+
1 );
2325 wfProfileOut( __METHOD__
);
2329 # Ugly state machine to walk through avoiding tags.
2330 $state = self
::COLON_STATE_TEXT
;
2332 $len = strlen( $str );
2333 for( $i = 0; $i < $len; $i++
) {
2337 # (Using the number is a performance hack for common cases)
2338 case 0: # self::COLON_STATE_TEXT:
2341 # Could be either a <start> tag or an </end> tag
2342 $state = self
::COLON_STATE_TAGSTART
;
2345 if ( $stack == 0 ) {
2347 $before = substr( $str, 0, $i );
2348 $after = substr( $str, $i +
1 );
2349 wfProfileOut( __METHOD__
);
2352 # Embedded in a tag; don't break it.
2355 # Skip ahead looking for something interesting
2356 $colon = strpos( $str, ':', $i );
2357 if ( $colon === false ) {
2358 # Nothing else interesting
2359 wfProfileOut( __METHOD__
);
2362 $lt = strpos( $str, '<', $i );
2363 if ( $stack === 0 ) {
2364 if ( $lt === false ||
$colon < $lt ) {
2366 $before = substr( $str, 0, $colon );
2367 $after = substr( $str, $colon +
1 );
2368 wfProfileOut( __METHOD__
);
2372 if ( $lt === false ) {
2373 # Nothing else interesting to find; abort!
2374 # We're nested, but there's no close tags left. Abort!
2377 # Skip ahead to next tag start
2379 $state = self
::COLON_STATE_TAGSTART
;
2382 case 1: # self::COLON_STATE_TAG:
2387 $state = self
::COLON_STATE_TEXT
;
2390 # Slash may be followed by >?
2391 $state = self
::COLON_STATE_TAGSLASH
;
2397 case 2: # self::COLON_STATE_TAGSTART:
2400 $state = self
::COLON_STATE_CLOSETAG
;
2403 $state = self
::COLON_STATE_COMMENT
;
2406 # Illegal early close? This shouldn't happen D:
2407 $state = self
::COLON_STATE_TEXT
;
2410 $state = self
::COLON_STATE_TAG
;
2413 case 3: # self::COLON_STATE_CLOSETAG:
2418 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2419 wfProfileOut( __METHOD__
);
2422 $state = self
::COLON_STATE_TEXT
;
2425 case self
::COLON_STATE_TAGSLASH
:
2427 # Yes, a self-closed tag <blah/>
2428 $state = self
::COLON_STATE_TEXT
;
2430 # Probably we're jumping the gun, and this is an attribute
2431 $state = self
::COLON_STATE_TAG
;
2434 case 5: # self::COLON_STATE_COMMENT:
2436 $state = self
::COLON_STATE_COMMENTDASH
;
2439 case self
::COLON_STATE_COMMENTDASH
:
2441 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2443 $state = self
::COLON_STATE_COMMENT
;
2446 case self
::COLON_STATE_COMMENTDASHDASH
:
2448 $state = self
::COLON_STATE_TEXT
;
2450 $state = self
::COLON_STATE_COMMENT
;
2454 throw new MWException( "State machine error in " . __METHOD__
);
2458 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2459 wfProfileOut( __METHOD__
);
2462 wfProfileOut( __METHOD__
);
2467 * Return value of a magic variable (like PAGENAME)
2471 function getVariableValue( $index, $frame=false ) {
2472 global $wgContLang, $wgSitename, $wgServer;
2473 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2476 * Some of these require message or data lookups and can be
2477 * expensive to check many times.
2479 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2480 if ( isset( $this->mVarCache
[$index] ) ) {
2481 return $this->mVarCache
[$index];
2485 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2486 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2489 global $wgLocaltimezone;
2490 if ( isset( $wgLocaltimezone ) ) {
2491 $oldtz = date_default_timezone_get();
2492 date_default_timezone_set( $wgLocaltimezone );
2495 $localTimestamp = date( 'YmdHis', $ts );
2496 $localMonth = date( 'm', $ts );
2497 $localMonth1 = date( 'n', $ts );
2498 $localMonthName = date( 'n', $ts );
2499 $localDay = date( 'j', $ts );
2500 $localDay2 = date( 'd', $ts );
2501 $localDayOfWeek = date( 'w', $ts );
2502 $localWeek = date( 'W', $ts );
2503 $localYear = date( 'Y', $ts );
2504 $localHour = date( 'H', $ts );
2505 if ( isset( $wgLocaltimezone ) ) {
2506 date_default_timezone_set( $oldtz );
2510 case 'currentmonth':
2511 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2513 case 'currentmonth1':
2514 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2516 case 'currentmonthname':
2517 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2519 case 'currentmonthnamegen':
2520 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2522 case 'currentmonthabbrev':
2523 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2526 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2529 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2532 $value = $wgContLang->formatNum( $localMonth );
2535 $value = $wgContLang->formatNum( $localMonth1 );
2537 case 'localmonthname':
2538 $value = $wgContLang->getMonthName( $localMonthName );
2540 case 'localmonthnamegen':
2541 $value = $wgContLang->getMonthNameGen( $localMonthName );
2543 case 'localmonthabbrev':
2544 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2547 $value = $wgContLang->formatNum( $localDay );
2550 $value = $wgContLang->formatNum( $localDay2 );
2553 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2556 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2558 case 'fullpagename':
2559 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2561 case 'fullpagenamee':
2562 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2565 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2567 case 'subpagenamee':
2568 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2570 case 'basepagename':
2571 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2573 case 'basepagenamee':
2574 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2576 case 'talkpagename':
2577 if ( $this->mTitle
->canTalk() ) {
2578 $talkPage = $this->mTitle
->getTalkPage();
2579 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2584 case 'talkpagenamee':
2585 if ( $this->mTitle
->canTalk() ) {
2586 $talkPage = $this->mTitle
->getTalkPage();
2587 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2592 case 'subjectpagename':
2593 $subjPage = $this->mTitle
->getSubjectPage();
2594 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2596 case 'subjectpagenamee':
2597 $subjPage = $this->mTitle
->getSubjectPage();
2598 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2601 # Let the edit saving system know we should parse the page
2602 # *after* a revision ID has been assigned.
2603 $this->mOutput
->setFlag( 'vary-revision' );
2604 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2605 $value = $this->mRevisionId
;
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__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2612 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2614 case 'revisionday2':
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__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2619 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2621 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2626 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2628 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2633 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2635 case 'revisionyear':
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__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2640 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2642 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2647 $value = $this->getRevisionTimestamp();
2649 case 'revisionuser':
2650 # Let the edit saving system know we should parse the page
2651 # *after* a revision ID has been assigned. This is for null edits.
2652 $this->mOutput
->setFlag( 'vary-revision' );
2653 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2654 $value = $this->getRevisionUser();
2657 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2660 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2663 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2666 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2668 case 'subjectspace':
2669 $value = $this->mTitle
->getSubjectNsText();
2671 case 'subjectspacee':
2672 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2674 case 'currentdayname':
2675 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2678 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2681 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2684 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2687 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2688 # int to remove the padding
2689 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2692 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2694 case 'localdayname':
2695 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2698 $value = $wgContLang->formatNum( $localYear, true );
2701 $value = $wgContLang->time( $localTimestamp, false, false );
2704 $value = $wgContLang->formatNum( $localHour, true );
2707 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2708 # int to remove the padding
2709 $value = $wgContLang->formatNum( (int)$localWeek );
2712 $value = $wgContLang->formatNum( $localDayOfWeek );
2714 case 'numberofarticles':
2715 $value = $wgContLang->formatNum( SiteStats
::articles() );
2717 case 'numberoffiles':
2718 $value = $wgContLang->formatNum( SiteStats
::images() );
2720 case 'numberofusers':
2721 $value = $wgContLang->formatNum( SiteStats
::users() );
2723 case 'numberofactiveusers':
2724 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2726 case 'numberofpages':
2727 $value = $wgContLang->formatNum( SiteStats
::pages() );
2729 case 'numberofadmins':
2730 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2732 case 'numberofedits':
2733 $value = $wgContLang->formatNum( SiteStats
::edits() );
2735 case 'numberofviews':
2736 $value = $wgContLang->formatNum( SiteStats
::views() );
2738 case 'currenttimestamp':
2739 $value = wfTimestamp( TS_MW
, $ts );
2741 case 'localtimestamp':
2742 $value = $localTimestamp;
2744 case 'currentversion':
2745 $value = SpecialVersion
::getVersion();
2748 return $wgArticlePath;
2754 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2755 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2756 wfRestoreWarnings();
2757 return $serverName ?
$serverName : $wgServer;
2759 return $wgScriptPath;
2761 return $wgStylePath;
2762 case 'directionmark':
2763 return $wgContLang->getDirMark();
2764 case 'contentlanguage':
2765 global $wgLanguageCode;
2766 return $wgLanguageCode;
2769 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2777 $this->mVarCache
[$index] = $value;
2783 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2787 function initialiseVariables() {
2788 wfProfileIn( __METHOD__
);
2789 $variableIDs = MagicWord
::getVariableIDs();
2790 $substIDs = MagicWord
::getSubstIDs();
2792 $this->mVariables
= new MagicWordArray( $variableIDs );
2793 $this->mSubstWords
= new MagicWordArray( $substIDs );
2794 wfProfileOut( __METHOD__
);
2798 * Preprocess some wikitext and return the document tree.
2799 * This is the ghost of replace_variables().
2801 * @param $text String: The text to parse
2802 * @param $flags Integer: bitwise combination of:
2803 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2804 * included. Default is to assume a direct page view.
2806 * The generated DOM tree must depend only on the input text and the flags.
2807 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2809 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2810 * change in the DOM tree for a given text, must be passed through the section identifier
2811 * in the section edit link and thus back to extractSections().
2813 * The output of this function is currently only cached in process memory, but a persistent
2814 * cache may be implemented at a later date which takes further advantage of these strict
2815 * dependency requirements.
2819 function preprocessToDom( $text, $flags = 0 ) {
2820 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2825 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2827 public static function splitWhitespace( $s ) {
2828 $ltrimmed = ltrim( $s );
2829 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2830 $trimmed = rtrim( $ltrimmed );
2831 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2833 $w2 = substr( $ltrimmed, -$diff );
2837 return array( $w1, $trimmed, $w2 );
2841 * Replace magic variables, templates, and template arguments
2842 * with the appropriate text. Templates are substituted recursively,
2843 * taking care to avoid infinite loops.
2845 * Note that the substitution depends on value of $mOutputType:
2846 * self::OT_WIKI: only {{subst:}} templates
2847 * self::OT_PREPROCESS: templates but not extension tags
2848 * self::OT_HTML: all templates and extension tags
2850 * @param $text String: the text to transform
2851 * @param $frame PPFrame Object describing the arguments passed to the template.
2852 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2853 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2854 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2857 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2858 # Is there any text? Also, Prevent too big inclusions!
2859 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2862 wfProfileIn( __METHOD__
);
2864 if ( $frame === false ) {
2865 $frame = $this->getPreprocessor()->newFrame();
2866 } elseif ( !( $frame instanceof PPFrame
) ) {
2867 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2868 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2871 $dom = $this->preprocessToDom( $text );
2872 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2873 $text = $frame->expand( $dom, $flags );
2875 wfProfileOut( __METHOD__
);
2879 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2880 static function createAssocArgs( $args ) {
2881 $assocArgs = array();
2883 foreach ( $args as $arg ) {
2884 $eqpos = strpos( $arg, '=' );
2885 if ( $eqpos === false ) {
2886 $assocArgs[$index++
] = $arg;
2888 $name = trim( substr( $arg, 0, $eqpos ) );
2889 $value = trim( substr( $arg, $eqpos+
1 ) );
2890 if ( $value === false ) {
2893 if ( $name !== false ) {
2894 $assocArgs[$name] = $value;
2903 * Warn the user when a parser limitation is reached
2904 * Will warn at most once the user per limitation type
2906 * @param $limitationType String: should be one of:
2907 * 'expensive-parserfunction' (corresponding messages:
2908 * 'expensive-parserfunction-warning',
2909 * 'expensive-parserfunction-category')
2910 * 'post-expand-template-argument' (corresponding messages:
2911 * 'post-expand-template-argument-warning',
2912 * 'post-expand-template-argument-category')
2913 * 'post-expand-template-inclusion' (corresponding messages:
2914 * 'post-expand-template-inclusion-warning',
2915 * 'post-expand-template-inclusion-category')
2916 * @param $current Current value
2917 * @param $max Maximum allowed, when an explicit limit has been
2918 * exceeded, provide the values (optional)
2920 function limitationWarn( $limitationType, $current=null, $max=null) {
2921 # does no harm if $current and $max are present but are unnecessary for the message
2922 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2923 $this->mOutput
->addWarning( $warning );
2924 $this->addTrackingCategory( "$limitationType-category" );
2928 * Return the text of a template, after recursively
2929 * replacing any variables or templates within the template.
2931 * @param $piece Array: the parts of the template
2932 * $piece['title']: the title, i.e. the part before the |
2933 * $piece['parts']: the parameter array
2934 * $piece['lineStart']: whether the brace was at the start of a line
2935 * @param $frame PPFrame The current frame, contains template arguments
2936 * @return String: the text of the template
2939 function braceSubstitution( $piece, $frame ) {
2940 global $wgContLang, $wgNonincludableNamespaces;
2941 wfProfileIn( __METHOD__
);
2942 wfProfileIn( __METHOD__
.'-setup' );
2945 $found = false; # $text has been filled
2946 $nowiki = false; # wiki markup in $text should be escaped
2947 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2948 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2949 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2950 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2952 # Title object, where $text came from
2955 # $part1 is the bit before the first |, and must contain only title characters.
2956 # Various prefixes will be stripped from it later.
2957 $titleWithSpaces = $frame->expand( $piece['title'] );
2958 $part1 = trim( $titleWithSpaces );
2961 # Original title text preserved for various purposes
2962 $originalTitle = $part1;
2964 # $args is a list of argument nodes, starting from index 0, not including $part1
2965 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2966 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2967 wfProfileOut( __METHOD__
.'-setup' );
2970 wfProfileIn( __METHOD__
.'-modifiers' );
2973 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2975 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2976 # Decide whether to expand template or keep wikitext as-is.
2977 if ( $this->ot
['wiki'] ) {
2978 if ( $substMatch === false ) {
2979 $literal = true; # literal when in PST with no prefix
2981 $literal = false; # expand when in PST with subst: or safesubst:
2984 if ( $substMatch == 'subst' ) {
2985 $literal = true; # literal when not in PST with plain subst:
2987 $literal = false; # expand when not in PST with safesubst: or no prefix
2991 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2998 if ( !$found && $args->getLength() == 0 ) {
2999 $id = $this->mVariables
->matchStartToEnd( $part1 );
3000 if ( $id !== false ) {
3001 $text = $this->getVariableValue( $id, $frame );
3002 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3003 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3009 # MSG, MSGNW and RAW
3012 $mwMsgnw = MagicWord
::get( 'msgnw' );
3013 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3016 # Remove obsolete MSG:
3017 $mwMsg = MagicWord
::get( 'msg' );
3018 $mwMsg->matchStartAndRemove( $part1 );
3022 $mwRaw = MagicWord
::get( 'raw' );
3023 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3024 $forceRawInterwiki = true;
3027 wfProfileOut( __METHOD__
.'-modifiers' );
3031 wfProfileIn( __METHOD__
. '-pfunc' );
3033 $colonPos = strpos( $part1, ':' );
3034 if ( $colonPos !== false ) {
3035 # Case sensitive functions
3036 $function = substr( $part1, 0, $colonPos );
3037 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3038 $function = $this->mFunctionSynonyms
[1][$function];
3040 # Case insensitive functions
3041 $function = $wgContLang->lc( $function );
3042 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3043 $function = $this->mFunctionSynonyms
[0][$function];
3049 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3050 $initialArgs = array( &$this );
3051 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3052 if ( $flags & SFH_OBJECT_ARGS
) {
3053 # Add a frame parameter, and pass the arguments as an array
3054 $allArgs = $initialArgs;
3055 $allArgs[] = $frame;
3056 for ( $i = 0; $i < $args->getLength(); $i++
) {
3057 $funcArgs[] = $args->item( $i );
3059 $allArgs[] = $funcArgs;
3061 # Convert arguments to plain text
3062 for ( $i = 0; $i < $args->getLength(); $i++
) {
3063 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3065 $allArgs = array_merge( $initialArgs, $funcArgs );
3068 # Workaround for PHP bug 35229 and similar
3069 if ( !is_callable( $callback ) ) {
3070 wfProfileOut( __METHOD__
. '-pfunc' );
3071 wfProfileOut( __METHOD__
);
3072 throw new MWException( "Tag hook for $function is not callable\n" );
3074 $result = call_user_func_array( $callback, $allArgs );
3077 $preprocessFlags = 0;
3079 if ( is_array( $result ) ) {
3080 if ( isset( $result[0] ) ) {
3082 unset( $result[0] );
3085 # Extract flags into the local scope
3086 # This allows callers to set flags such as nowiki, found, etc.
3092 $text = $this->preprocessToDom( $text, $preprocessFlags );
3097 wfProfileOut( __METHOD__
. '-pfunc' );
3100 # Finish mangling title and then check for loops.
3101 # Set $title to a Title object and $titleText to the PDBK
3104 # Split the title into page and subpage
3106 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3107 if ( $subpage !== '' ) {
3108 $ns = $this->mTitle
->getNamespace();
3110 $title = Title
::newFromText( $part1, $ns );
3112 $titleText = $title->getPrefixedText();
3113 # Check for language variants if the template is not found
3114 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3115 $wgContLang->findVariantLink( $part1, $title, true );
3117 # Do recursion depth check
3118 $limit = $this->mOptions
->getMaxTemplateDepth();
3119 if ( $frame->depth
>= $limit ) {
3121 $text = '<span class="error">'
3122 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3128 # Load from database
3129 if ( !$found && $title ) {
3130 wfProfileIn( __METHOD__
. '-loadtpl' );
3131 if ( !$title->isExternal() ) {
3132 if ( $title->getNamespace() == NS_SPECIAL
3133 && $this->mOptions
->getAllowSpecialInclusion()
3134 && $this->ot
['html'] )
3136 $text = SpecialPage
::capturePath( $title );
3137 if ( is_string( $text ) ) {
3140 $this->disableCache();
3142 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3143 $found = false; # access denied
3144 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3146 list( $text, $title ) = $this->getTemplateDom( $title );
3147 if ( $text !== false ) {
3153 # If the title is valid but undisplayable, make a link to it
3154 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3155 $text = "[[:$titleText]]";
3158 } elseif ( $title->isTrans() ) {
3159 # Interwiki transclusion
3160 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3161 $text = $this->interwikiTransclude( $title, 'render' );
3164 $text = $this->interwikiTransclude( $title, 'raw' );
3165 # Preprocess it like a template
3166 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3172 # Do infinite loop check
3173 # This has to be done after redirect resolution to avoid infinite loops via redirects
3174 if ( !$frame->loopCheck( $title ) ) {
3176 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3177 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3179 wfProfileOut( __METHOD__
. '-loadtpl' );
3182 # If we haven't found text to substitute by now, we're done
3183 # Recover the source wikitext and return it
3185 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3186 wfProfileOut( __METHOD__
);
3187 return array( 'object' => $text );
3190 # Expand DOM-style return values in a child frame
3191 if ( $isChildObj ) {
3192 # Clean up argument array
3193 $newFrame = $frame->newChild( $args, $title );
3196 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3197 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3198 # Expansion is eligible for the empty-frame cache
3199 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3200 $text = $this->mTplExpandCache
[$titleText];
3202 $text = $newFrame->expand( $text );
3203 $this->mTplExpandCache
[$titleText] = $text;
3206 # Uncached expansion
3207 $text = $newFrame->expand( $text );
3210 if ( $isLocalObj && $nowiki ) {
3211 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3212 $isLocalObj = false;
3215 # Replace raw HTML by a placeholder
3216 # Add a blank line preceding, to prevent it from mucking up
3217 # immediately preceding headings
3219 $text = "\n\n" . $this->insertStripItem( $text );
3220 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3221 # Escape nowiki-style return values
3222 $text = wfEscapeWikiText( $text );
3223 } elseif ( is_string( $text )
3224 && !$piece['lineStart']
3225 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3227 # Bug 529: if the template begins with a table or block-level
3228 # element, it should be treated as beginning a new line.
3229 # This behaviour is somewhat controversial.
3230 $text = "\n" . $text;
3233 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3234 # Error, oversize inclusion
3235 if ( $titleText !== false ) {
3236 # Make a working, properly escaped link if possible (bug 23588)
3237 $text = "[[:$titleText]]";
3239 # This will probably not be a working link, but at least it may
3240 # provide some hint of where the problem is
3241 preg_replace( '/^:/', '', $originalTitle );
3242 $text = "[[:$originalTitle]]";
3244 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3245 $this->limitationWarn( 'post-expand-template-inclusion' );
3248 if ( $isLocalObj ) {
3249 $ret = array( 'object' => $text );
3251 $ret = array( 'text' => $text );
3254 wfProfileOut( __METHOD__
);
3259 * Get the semi-parsed DOM representation of a template with a given title,
3260 * and its redirect destination title. Cached.
3262 function getTemplateDom( $title ) {
3263 $cacheTitle = $title;
3264 $titleText = $title->getPrefixedDBkey();
3266 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3267 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3268 $title = Title
::makeTitle( $ns, $dbk );
3269 $titleText = $title->getPrefixedDBkey();
3271 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3272 return array( $this->mTplDomCache
[$titleText], $title );
3275 # Cache miss, go to the database
3276 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3278 if ( $text === false ) {
3279 $this->mTplDomCache
[$titleText] = false;
3280 return array( false, $title );
3283 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3284 $this->mTplDomCache
[ $titleText ] = $dom;
3286 if ( !$title->equals( $cacheTitle ) ) {
3287 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3288 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3291 return array( $dom, $title );
3295 * Fetch the unparsed text of a template and register a reference to it.
3297 function fetchTemplateAndTitle( $title ) {
3298 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3299 $stuff = call_user_func( $templateCb, $title, $this );
3300 $text = $stuff['text'];
3301 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3302 if ( isset( $stuff['deps'] ) ) {
3303 foreach ( $stuff['deps'] as $dep ) {
3304 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3307 return array( $text, $finalTitle );
3310 function fetchTemplate( $title ) {
3311 $rv = $this->fetchTemplateAndTitle( $title );
3316 * Static function to get a template
3317 * Can be overridden via ParserOptions::setTemplateCallback().
3319 static function statelessFetchTemplate( $title, $parser=false ) {
3320 $text = $skip = false;
3321 $finalTitle = $title;
3324 # Loop to fetch the article, with up to 1 redirect
3325 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3326 # Give extensions a chance to select the revision instead
3327 $id = false; # Assume current
3328 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3334 'page_id' => $title->getArticleID(),
3338 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3339 $rev_id = $rev ?
$rev->getId() : 0;
3340 # If there is no current revision, there is no page
3341 if ( $id === false && !$rev ) {
3342 $linkCache = LinkCache
::singleton();
3343 $linkCache->addBadLinkObj( $title );
3348 'page_id' => $title->getArticleID(),
3349 'rev_id' => $rev_id );
3352 $text = $rev->getText();
3353 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3355 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3356 if ( !$message->exists() ) {
3360 $text = $message->plain();
3364 if ( $text === false ) {
3368 $finalTitle = $title;
3369 $title = Title
::newFromRedirect( $text );
3373 'finalTitle' => $finalTitle,
3378 * Transclude an interwiki link.
3380 function interwikiTransclude( $title, $action ) {
3381 global $wgEnableScaryTranscluding;
3383 if ( !$wgEnableScaryTranscluding ) {
3384 return wfMsgForContent('scarytranscludedisabled');
3387 $url = $title->getFullUrl( "action=$action" );
3389 if ( strlen( $url ) > 255 ) {
3390 return wfMsgForContent( 'scarytranscludetoolong' );
3392 return $this->fetchScaryTemplateMaybeFromCache( $url );
3395 function fetchScaryTemplateMaybeFromCache( $url ) {
3396 global $wgTranscludeCacheExpiry;
3397 $dbr = wfGetDB( DB_SLAVE
);
3398 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3399 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3400 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3402 return $obj->tc_contents
;
3405 $text = Http
::get( $url );
3407 return wfMsgForContent( 'scarytranscludefailed', $url );
3410 $dbw = wfGetDB( DB_MASTER
);
3411 $dbw->replace( 'transcache', array('tc_url'), array(
3413 'tc_time' => $dbw->timestamp( time() ),
3414 'tc_contents' => $text)
3421 * Triple brace replacement -- used for template arguments
3424 function argSubstitution( $piece, $frame ) {
3425 wfProfileIn( __METHOD__
);
3428 $parts = $piece['parts'];
3429 $nameWithSpaces = $frame->expand( $piece['title'] );
3430 $argName = trim( $nameWithSpaces );
3432 $text = $frame->getArgument( $argName );
3433 if ( $text === false && $parts->getLength() > 0
3437 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3440 # No match in frame, use the supplied default
3441 $object = $parts->item( 0 )->getChildren();
3443 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3444 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3445 $this->limitationWarn( 'post-expand-template-argument' );
3448 if ( $text === false && $object === false ) {
3450 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3452 if ( $error !== false ) {
3455 if ( $object !== false ) {
3456 $ret = array( 'object' => $object );
3458 $ret = array( 'text' => $text );
3461 wfProfileOut( __METHOD__
);
3466 * Return the text to be used for a given extension tag.
3467 * This is the ghost of strip().
3469 * @param $params Associative array of parameters:
3470 * name PPNode for the tag name
3471 * attr PPNode for unparsed text where tag attributes are thought to be
3472 * attributes Optional associative array of parsed attributes
3473 * inner Contents of extension element
3474 * noClose Original text did not have a close tag
3475 * @param $frame PPFrame
3477 function extensionSubstitution( $params, $frame ) {
3478 $name = $frame->expand( $params['name'] );
3479 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3480 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3481 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3483 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3484 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3485 if ( $isFunctionTag ) {
3486 $markerType = 'none';
3488 $markerType = 'general';
3490 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3491 $name = strtolower( $name );
3492 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3493 if ( isset( $params['attributes'] ) ) {
3494 $attributes = $attributes +
$params['attributes'];
3497 if ( isset( $this->mTagHooks
[$name] ) ) {
3498 # Workaround for PHP bug 35229 and similar
3499 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3500 throw new MWException( "Tag hook for $name is not callable\n" );
3502 $output = call_user_func_array( $this->mTagHooks
[$name],
3503 array( $content, $attributes, $this, $frame ) );
3504 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3505 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3506 if ( !is_callable( $callback ) ) {
3507 throw new MWException( "Tag hook for $name is not callable\n" );
3510 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3512 $output = '<span class="error">Invalid tag extension name: ' .
3513 htmlspecialchars( $name ) . '</span>';
3516 if ( is_array( $output ) ) {
3517 # Extract flags to local scope (to override $markerType)
3519 $output = $flags[0];
3524 if ( is_null( $attrText ) ) {
3527 if ( isset( $params['attributes'] ) ) {
3528 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3529 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3530 htmlspecialchars( $attrValue ) . '"';
3533 if ( $content === null ) {
3534 $output = "<$name$attrText/>";
3536 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3537 $output = "<$name$attrText>$content$close";
3541 if ( $markerType === 'none' ) {
3543 } elseif ( $markerType === 'nowiki' ) {
3544 $this->mStripState
->addNoWiki( $marker, $output );
3545 } elseif ( $markerType === 'general' ) {
3546 $this->mStripState
->addGeneral( $marker, $output );
3548 throw new MWException( __METHOD__
.': invalid marker type' );
3554 * Increment an include size counter
3556 * @param $type String: the type of expansion
3557 * @param $size Integer: the size of the text
3558 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3560 function incrementIncludeSize( $type, $size ) {
3561 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3564 $this->mIncludeSizes
[$type] +
= $size;
3570 * Increment the expensive function count
3572 * @return Boolean: false if the limit has been exceeded
3574 function incrementExpensiveFunctionCount() {
3575 global $wgExpensiveParserFunctionLimit;
3576 $this->mExpensiveFunctionCount++
;
3577 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3584 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3585 * Fills $this->mDoubleUnderscores, returns the modified text
3587 function doDoubleUnderscore( $text ) {
3588 wfProfileIn( __METHOD__
);
3590 # The position of __TOC__ needs to be recorded
3591 $mw = MagicWord
::get( 'toc' );
3592 if ( $mw->match( $text ) ) {
3593 $this->mShowToc
= true;
3594 $this->mForceTocPosition
= true;
3596 # Set a placeholder. At the end we'll fill it in with the TOC.
3597 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3599 # Only keep the first one.
3600 $text = $mw->replace( '', $text );
3603 # Now match and remove the rest of them
3604 $mwa = MagicWord
::getDoubleUnderscoreArray();
3605 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3607 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3608 $this->mOutput
->mNoGallery
= true;
3610 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3611 $this->mShowToc
= false;
3613 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3614 $this->addTrackingCategory( 'hidden-category-category' );
3616 # (bug 8068) Allow control over whether robots index a page.
3618 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3619 # is not desirable, the last one on the page should win.
3620 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3621 $this->mOutput
->setIndexPolicy( 'noindex' );
3622 $this->addTrackingCategory( 'noindex-category' );
3624 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3625 $this->mOutput
->setIndexPolicy( 'index' );
3626 $this->addTrackingCategory( 'index-category' );
3629 # Cache all double underscores in the database
3630 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3631 $this->mOutput
->setProperty( $key, '' );
3634 wfProfileOut( __METHOD__
);
3639 * Add a tracking category, getting the title from a system message,
3640 * or print a debug message if the title is invalid.
3642 * @param $msg String: message key
3643 * @return Boolean: whether the addition was successful
3645 protected function addTrackingCategory( $msg ) {
3646 $cat = wfMsgForContent( $msg );
3648 # Allow tracking categories to be disabled by setting them to "-"
3649 if ( $cat === '-' ) {
3653 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3654 if ( $containerCategory ) {
3655 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3658 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3664 * This function accomplishes several tasks:
3665 * 1) Auto-number headings if that option is enabled
3666 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3667 * 3) Add a Table of contents on the top for users who have enabled the option
3668 * 4) Auto-anchor headings
3670 * It loops through all headlines, collects the necessary data, then splits up the
3671 * string and re-inserts the newly formatted headlines.
3673 * @param $text String
3674 * @param $origText String: original, untouched wikitext
3675 * @param $isMain Boolean
3678 function formatHeadings( $text, $origText, $isMain=true ) {
3679 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3681 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3683 # Inhibit editsection links if requested in the page
3684 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3687 $showEditLink = $this->mOptions
->getEditSection();
3689 if ( $showEditLink ) {
3690 $this->mOutput
->setEditSectionTokens( true );
3693 # Get all headlines for numbering them and adding funky stuff like [edit]
3694 # links - this is for later, but we need the number of headlines right now
3696 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3698 # if there are fewer than 4 headlines in the article, do not show TOC
3699 # unless it's been explicitly enabled.
3700 $enoughToc = $this->mShowToc
&&
3701 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3703 # Allow user to stipulate that a page should have a "new section"
3704 # link added via __NEWSECTIONLINK__
3705 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3706 $this->mOutput
->setNewSection( true );
3709 # Allow user to remove the "new section"
3710 # link via __NONEWSECTIONLINK__
3711 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3712 $this->mOutput
->hideNewSection( true );
3715 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3716 # override above conditions and always show TOC above first header
3717 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3718 $this->mShowToc
= true;
3722 # We need this to perform operations on the HTML
3723 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3729 # Ugh .. the TOC should have neat indentation levels which can be
3730 # passed to the skin functions. These are determined here
3734 $sublevelCount = array();
3735 $levelCount = array();
3740 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3741 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3742 $oldType = $this->mOutputType
;
3743 $this->setOutputType( self
::OT_WIKI
);
3744 $frame = $this->getPreprocessor()->newFrame();
3745 $root = $this->preprocessToDom( $origText );
3746 $node = $root->getFirstChild();
3751 foreach ( $matches[3] as $headline ) {
3752 $isTemplate = false;
3754 $sectionIndex = false;
3756 $markerMatches = array();
3757 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3758 $serial = $markerMatches[1];
3759 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3760 $isTemplate = ( $titleText != $baseTitleText );
3761 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3765 $prevlevel = $level;
3767 $level = $matches[1][$headlineCount];
3769 if ( $level > $prevlevel ) {
3770 # Increase TOC level
3772 $sublevelCount[$toclevel] = 0;
3773 if ( $toclevel<$wgMaxTocLevel ) {
3774 $prevtoclevel = $toclevel;
3775 $toc .= $sk->tocIndent();
3778 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3779 # Decrease TOC level, find level to jump to
3781 for ( $i = $toclevel; $i > 0; $i-- ) {
3782 if ( $levelCount[$i] == $level ) {
3783 # Found last matching level
3786 } elseif ( $levelCount[$i] < $level ) {
3787 # Found first matching level below current level
3795 if ( $toclevel<$wgMaxTocLevel ) {
3796 if ( $prevtoclevel < $wgMaxTocLevel ) {
3797 # Unindent only if the previous toc level was shown :p
3798 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3799 $prevtoclevel = $toclevel;
3801 $toc .= $sk->tocLineEnd();
3805 # No change in level, end TOC line
3806 if ( $toclevel<$wgMaxTocLevel ) {
3807 $toc .= $sk->tocLineEnd();
3811 $levelCount[$toclevel] = $level;
3813 # count number of headlines for each level
3814 @$sublevelCount[$toclevel]++
;
3816 for( $i = 1; $i <= $toclevel; $i++
) {
3817 if ( !empty( $sublevelCount[$i] ) ) {
3821 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3826 # The safe header is a version of the header text safe to use for links
3827 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3828 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3830 # Remove link placeholders by the link text.
3831 # <!--LINK number-->
3833 # link text with suffix
3834 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3836 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3837 $tocline = preg_replace(
3838 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3839 array( '', '<$1>' ),
3842 $tocline = trim( $tocline );
3844 # For the anchor, strip out HTML-y stuff period
3845 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3846 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3848 # Save headline for section edit hint before it's escaped
3849 $headlineHint = $safeHeadline;
3851 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3852 # For reverse compatibility, provide an id that's
3853 # HTML4-compatible, like we used to.
3855 # It may be worth noting, academically, that it's possible for
3856 # the legacy anchor to conflict with a non-legacy headline
3857 # anchor on the page. In this case likely the "correct" thing
3858 # would be to either drop the legacy anchors or make sure
3859 # they're numbered first. However, this would require people
3860 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3861 # manually, so let's not bother worrying about it.
3862 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3863 array( 'noninitial', 'legacy' ) );
3864 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3866 if ( $legacyHeadline == $safeHeadline ) {
3867 # No reason to have both (in fact, we can't)
3868 $legacyHeadline = false;
3871 $legacyHeadline = false;
3872 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3876 # HTML names must be case-insensitively unique (bug 10721).
3877 # This does not apply to Unicode characters per
3878 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3879 # FIXME: We may be changing them depending on the current locale.
3880 $arrayKey = strtolower( $safeHeadline );
3881 if ( $legacyHeadline === false ) {
3882 $legacyArrayKey = false;
3884 $legacyArrayKey = strtolower( $legacyHeadline );
3887 # count how many in assoc. array so we can track dupes in anchors
3888 if ( isset( $refers[$arrayKey] ) ) {
3889 $refers[$arrayKey]++
;
3891 $refers[$arrayKey] = 1;
3893 if ( isset( $refers[$legacyArrayKey] ) ) {
3894 $refers[$legacyArrayKey]++
;
3896 $refers[$legacyArrayKey] = 1;
3899 # Don't number the heading if it is the only one (looks silly)
3900 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3901 # the two are different if the line contains a link
3902 $headline = $numbering . ' ' . $headline;
3905 # Create the anchor for linking from the TOC to the section
3906 $anchor = $safeHeadline;
3907 $legacyAnchor = $legacyHeadline;
3908 if ( $refers[$arrayKey] > 1 ) {
3909 $anchor .= '_' . $refers[$arrayKey];
3911 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3912 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3914 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3915 $toc .= $sk->tocLine( $anchor, $tocline,
3916 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3919 # Add the section to the section tree
3920 # Find the DOM node for this header
3921 while ( $node && !$isTemplate ) {
3922 if ( $node->getName() === 'h' ) {
3923 $bits = $node->splitHeading();
3924 if ( $bits['i'] == $sectionIndex ) {
3928 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3929 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3930 $node = $node->getNextSibling();
3933 'toclevel' => $toclevel,
3936 'number' => $numbering,
3937 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3938 'fromtitle' => $titleText,
3939 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3940 'anchor' => $anchor,
3943 # give headline the correct <h#> tag
3944 if ( $showEditLink && $sectionIndex !== false ) {
3945 // Output edit section links as markers with styles that can be customized by skins
3946 if ( $isTemplate ) {
3947 # Put a T flag in the section identifier, to indicate to extractSections()
3948 # that sections inside <includeonly> should be counted.
3949 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3951 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3953 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3954 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3955 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3956 // so we don't have to worry about a user trying to input one of these markers directly.
3957 // We use a page and section attribute to stop the language converter from converting these important bits
3958 // of data, but put the headline hint inside a content block because the language converter is supposed to
3959 // be able to convert that piece of data.
3960 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
3961 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
3962 if ( isset($editlinkArgs[2]) ) {
3963 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
3970 $head[$headlineCount] = $sk->makeHeadline( $level,
3971 $matches['attrib'][$headlineCount], $anchor, $headline,
3972 $editlink, $legacyAnchor );
3977 $this->setOutputType( $oldType );
3979 # Never ever show TOC if no headers
3980 if ( $numVisible < 1 ) {
3985 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3986 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3988 $toc = $sk->tocList( $toc, $this->mOptions
->getUserLang() );
3989 $this->mOutput
->setTOCHTML( $toc );
3993 $this->mOutput
->setSections( $tocraw );
3996 # split up and insert constructed headlines
3998 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4001 foreach ( $blocks as $block ) {
4002 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4003 # This is the [edit] link that appears for the top block of text when
4004 # section editing is enabled
4006 # Disabled because it broke block formatting
4007 # For example, a bullet point in the top line
4008 # $full .= $sk->editSectionLink(0);
4011 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4012 # Top anchor now in skin
4016 if ( !empty( $head[$i] ) ) {
4021 if ( $this->mForceTocPosition
) {
4022 return str_replace( '<!--MWTOC-->', $toc, $full );
4029 * Transform wiki markup when saving a page by doing \r\n -> \n
4030 * conversion, substitting signatures, {{subst:}} templates, etc.
4032 * @param $text String: the text to transform
4033 * @param $title Title: the Title object for the current article
4034 * @param $user User: the User object describing the current user
4035 * @param $options ParserOptions: parsing options
4036 * @param $clearState Boolean: whether to clear the parser state first
4037 * @return String: the altered wiki markup
4039 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4040 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4041 $this->setUser( $user );
4046 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4047 if( $options->getPreSaveTransform() ) {
4048 $text = $this->pstPass2( $text, $user );
4050 $text = $this->mStripState
->unstripBoth( $text );
4052 $this->setUser( null ); #Reset
4058 * Pre-save transform helper function
4061 function pstPass2( $text, $user ) {
4062 global $wgContLang, $wgLocaltimezone;
4064 # Note: This is the timestamp saved as hardcoded wikitext to
4065 # the database, we use $wgContLang here in order to give
4066 # everyone the same signature and use the default one rather
4067 # than the one selected in each user's preferences.
4068 # (see also bug 12815)
4069 $ts = $this->mOptions
->getTimestamp();
4070 if ( isset( $wgLocaltimezone ) ) {
4071 $tz = $wgLocaltimezone;
4073 $tz = date_default_timezone_get();
4076 $unixts = wfTimestamp( TS_UNIX
, $ts );
4077 $oldtz = date_default_timezone_get();
4078 date_default_timezone_set( $tz );
4079 $ts = date( 'YmdHis', $unixts );
4080 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4082 # Allow translation of timezones through wiki. date() can return
4083 # whatever crap the system uses, localised or not, so we cannot
4084 # ship premade translations.
4085 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4086 $msg = wfMessage( $key )->inContentLanguage();
4087 if ( $msg->exists() ) {
4088 $tzMsg = $msg->text();
4091 date_default_timezone_set( $oldtz );
4093 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4095 # Variable replacement
4096 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4097 $text = $this->replaceVariables( $text );
4099 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4100 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4103 $sigText = $this->getUserSig( $user );
4104 $text = strtr( $text, array(
4106 '~~~~' => "$sigText $d",
4110 # Context links: [[|name]] and [[name (context)|]]
4111 global $wgLegalTitleChars;
4112 $tc = "[$wgLegalTitleChars]";
4113 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4115 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4116 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4117 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4118 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4120 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4121 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4122 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4123 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4125 $t = $this->mTitle
->getText();
4127 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4128 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4129 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4130 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4132 # if there's no context, don't bother duplicating the title
4133 $text = preg_replace( $p2, '[[\\1]]', $text );
4136 # Trim trailing whitespace
4137 $text = rtrim( $text );
4143 * Fetch the user's signature text, if any, and normalize to
4144 * validated, ready-to-insert wikitext.
4145 * If you have pre-fetched the nickname or the fancySig option, you can
4146 * specify them here to save a database query.
4147 * Do not reuse this parser instance after calling getUserSig(),
4148 * as it may have changed if it's the $wgParser.
4151 * @param $nickname String: nickname to use or false to use user's default nickname
4152 * @param $fancySig Boolean: whether the nicknname is the complete signature
4153 * or null to use default value
4156 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4157 global $wgMaxSigChars;
4159 $username = $user->getName();
4161 # If not given, retrieve from the user object.
4162 if ( $nickname === false )
4163 $nickname = $user->getOption( 'nickname' );
4165 if ( is_null( $fancySig ) ) {
4166 $fancySig = $user->getBoolOption( 'fancysig' );
4169 $nickname = $nickname == null ?
$username : $nickname;
4171 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4172 $nickname = $username;
4173 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4174 } elseif ( $fancySig !== false ) {
4175 # Sig. might contain markup; validate this
4176 if ( $this->validateSig( $nickname ) !== false ) {
4177 # Validated; clean up (if needed) and return it
4178 return $this->cleanSig( $nickname, true );
4180 # Failed to validate; fall back to the default
4181 $nickname = $username;
4182 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4186 # Make sure nickname doesnt get a sig in a sig
4187 $nickname = $this->cleanSigInSig( $nickname );
4189 # If we're still here, make it a link to the user page
4190 $userText = wfEscapeWikiText( $username );
4191 $nickText = wfEscapeWikiText( $nickname );
4192 if ( $user->isAnon() ) {
4193 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4195 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4200 * Check that the user's signature contains no bad XML
4202 * @param $text String
4203 * @return mixed An expanded string, or false if invalid.
4205 function validateSig( $text ) {
4206 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4210 * Clean up signature text
4212 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4213 * 2) Substitute all transclusions
4215 * @param $text String
4216 * @param $parsing Whether we're cleaning (preferences save) or parsing
4217 * @return String: signature text
4219 function cleanSig( $text, $parsing = false ) {
4222 $this->mOptions
= new ParserOptions
;
4223 $this->clearState();
4224 $this->setTitle( $wgTitle );
4225 $this->setOutputType
= self
::OT_PREPROCESS
;
4228 # Option to disable this feature
4229 if ( !$this->mOptions
->getCleanSignatures() ) {
4233 # FIXME: regex doesn't respect extension tags or nowiki
4234 # => Move this logic to braceSubstitution()
4235 $substWord = MagicWord
::get( 'subst' );
4236 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4237 $substText = '{{' . $substWord->getSynonym( 0 );
4239 $text = preg_replace( $substRegex, $substText, $text );
4240 $text = $this->cleanSigInSig( $text );
4241 $dom = $this->preprocessToDom( $text );
4242 $frame = $this->getPreprocessor()->newFrame();
4243 $text = $frame->expand( $dom );
4246 $text = $this->mStripState
->unstripBoth( $text );
4253 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4255 * @param $text String
4256 * @return String: signature text with /~{3,5}/ removed
4258 function cleanSigInSig( $text ) {
4259 $text = preg_replace( '/~{3,5}/', '', $text );
4264 * Set up some variables which are usually set up in parse()
4265 * so that an external function can call some class members with confidence
4267 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4268 $this->startParse( $title, $options, $outputType, $clearState );
4271 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4272 $this->setTitle( $title );
4273 $this->mOptions
= $options;
4274 $this->setOutputType( $outputType );
4275 if ( $clearState ) {
4276 $this->clearState();
4281 * Wrapper for preprocess()
4283 * @param $text String: the text to preprocess
4284 * @param $options ParserOptions: options
4285 * @param $title Title object or null to use $wgTitle
4288 public function transformMsg( $text, $options, $title = null ) {
4289 static $executing = false;
4291 # Guard against infinite recursion
4297 wfProfileIn( __METHOD__
);
4303 # It's not uncommon having a null $wgTitle in scripts. See r80898
4304 # Create a ghost title in such case
4305 $title = Title
::newFromText( 'Dwimmerlaik' );
4307 $text = $this->preprocess( $text, $title, $options );
4310 wfProfileOut( __METHOD__
);
4315 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4316 * The callback should have the following form:
4317 * function myParserHook( $text, $params, $parser ) { ... }
4319 * Transform and return $text. Use $parser for any required context, e.g. use
4320 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4322 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4323 * @param $callback Mixed: the callback function (and object) to use for the tag
4324 * @return The old value of the mTagHooks array associated with the hook
4326 public function setHook( $tag, $callback ) {
4327 $tag = strtolower( $tag );
4328 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4329 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4330 $this->mTagHooks
[$tag] = $callback;
4331 if ( !in_array( $tag, $this->mStripList
) ) {
4332 $this->mStripList
[] = $tag;
4338 function setTransparentTagHook( $tag, $callback ) {
4339 $tag = strtolower( $tag );
4340 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4341 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4342 $this->mTransparentTagHooks
[$tag] = $callback;
4348 * Remove all tag hooks
4350 function clearTagHooks() {
4351 $this->mTagHooks
= array();
4352 $this->mStripList
= $this->mDefaultStripList
;
4356 * Create a function, e.g. {{sum:1|2|3}}
4357 * The callback function should have the form:
4358 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4360 * Or with SFH_OBJECT_ARGS:
4361 * function myParserFunction( $parser, $frame, $args ) { ... }
4363 * The callback may either return the text result of the function, or an array with the text
4364 * in element 0, and a number of flags in the other elements. The names of the flags are
4365 * specified in the keys. Valid flags are:
4366 * found The text returned is valid, stop processing the template. This
4368 * nowiki Wiki markup in the return value should be escaped
4369 * isHTML The returned text is HTML, armour it against wikitext transformation
4371 * @param $id String: The magic word ID
4372 * @param $callback Mixed: the callback function (and object) to use
4373 * @param $flags Integer: a combination of the following flags:
4374 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4376 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4377 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4378 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4379 * the arguments, and to control the way they are expanded.
4381 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4382 * arguments, for instance:
4383 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4385 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4386 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4387 * working if/when this is changed.
4389 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4392 * Please read the documentation in includes/parser/Preprocessor.php for more information
4393 * about the methods available in PPFrame and PPNode.
4395 * @return The old callback function for this name, if any
4397 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4400 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4401 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4403 # Add to function cache
4404 $mw = MagicWord
::get( $id );
4406 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4408 $synonyms = $mw->getSynonyms();
4409 $sensitive = intval( $mw->isCaseSensitive() );
4411 foreach ( $synonyms as $syn ) {
4413 if ( !$sensitive ) {
4414 $syn = $wgContLang->lc( $syn );
4417 if ( !( $flags & SFH_NO_HASH
) ) {
4420 # Remove trailing colon
4421 if ( substr( $syn, -1, 1 ) === ':' ) {
4422 $syn = substr( $syn, 0, -1 );
4424 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4430 * Get all registered function hook identifiers
4434 function getFunctionHooks() {
4435 return array_keys( $this->mFunctionHooks
);
4439 * Create a tag function, e.g. <test>some stuff</test>.
4440 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4441 * Unlike parser functions, their content is not preprocessed.
4443 function setFunctionTagHook( $tag, $callback, $flags ) {
4444 $tag = strtolower( $tag );
4445 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4446 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4447 $this->mFunctionTagHooks
[$tag] : null;
4448 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4450 if ( !in_array( $tag, $this->mStripList
) ) {
4451 $this->mStripList
[] = $tag;
4458 * FIXME: update documentation. makeLinkObj() is deprecated.
4459 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4460 * Placeholders created in Skin::makeLinkObj()
4461 * Returns an array of link CSS classes, indexed by PDBK.
4463 function replaceLinkHolders( &$text, $options = 0 ) {
4464 return $this->mLinkHolders
->replace( $text );
4468 * Replace <!--LINK--> link placeholders with plain text of links
4469 * (not HTML-formatted).
4471 * @param $text String
4474 function replaceLinkHoldersText( $text ) {
4475 return $this->mLinkHolders
->replaceText( $text );
4479 * Renders an image gallery from a text with one line per image.
4480 * text labels may be given by using |-style alternative text. E.g.
4481 * Image:one.jpg|The number "1"
4482 * Image:tree.jpg|A tree
4483 * given as text will return the HTML of a gallery with two images,
4484 * labeled 'The number "1"' and
4487 function renderImageGallery( $text, $params ) {
4488 $ig = new ImageGallery();
4489 $ig->setContextTitle( $this->mTitle
);
4490 $ig->setShowBytes( false );
4491 $ig->setShowFilename( false );
4492 $ig->setParser( $this );
4493 $ig->setHideBadImages();
4494 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4495 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4496 $ig->mRevisionId
= $this->mRevisionId
;
4498 if ( isset( $params['showfilename'] ) ) {
4499 $ig->setShowFilename( true );
4501 $ig->setShowFilename( false );
4503 if ( isset( $params['caption'] ) ) {
4504 $caption = $params['caption'];
4505 $caption = htmlspecialchars( $caption );
4506 $caption = $this->replaceInternalLinks( $caption );
4507 $ig->setCaptionHtml( $caption );
4509 if ( isset( $params['perrow'] ) ) {
4510 $ig->setPerRow( $params['perrow'] );
4512 if ( isset( $params['widths'] ) ) {
4513 $ig->setWidths( $params['widths'] );
4515 if ( isset( $params['heights'] ) ) {
4516 $ig->setHeights( $params['heights'] );
4519 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4521 $lines = StringUtils
::explode( "\n", $text );
4522 foreach ( $lines as $line ) {
4523 # match lines like these:
4524 # Image:someimage.jpg|This is some image
4526 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4528 if ( count( $matches ) == 0 ) {
4532 if ( strpos( $matches[0], '%' ) !== false ) {
4533 $matches[1] = rawurldecode( $matches[1] );
4535 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4537 if ( is_null( $nt ) ) {
4538 # Bogus title. Ignore these so we don't bomb out later.
4541 if ( isset( $matches[3] ) ) {
4542 $label = $matches[3];
4547 $html = $this->recursiveTagParse( trim( $label ) );
4549 $ig->add( $nt, $html );
4551 # Only add real images (bug #5586)
4552 if ( $nt->getNamespace() == NS_FILE
) {
4553 $this->mOutput
->addImage( $nt->getDBkey() );
4556 return $ig->toHTML();
4559 function getImageParams( $handler ) {
4561 $handlerClass = get_class( $handler );
4565 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4566 # Initialise static lists
4567 static $internalParamNames = array(
4568 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4569 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4570 'bottom', 'text-bottom' ),
4571 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4572 'upright', 'border', 'link', 'alt' ),
4574 static $internalParamMap;
4575 if ( !$internalParamMap ) {
4576 $internalParamMap = array();
4577 foreach ( $internalParamNames as $type => $names ) {
4578 foreach ( $names as $name ) {
4579 $magicName = str_replace( '-', '_', "img_$name" );
4580 $internalParamMap[$magicName] = array( $type, $name );
4585 # Add handler params
4586 $paramMap = $internalParamMap;
4588 $handlerParamMap = $handler->getParamMap();
4589 foreach ( $handlerParamMap as $magic => $paramName ) {
4590 $paramMap[$magic] = array( 'handler', $paramName );
4593 $this->mImageParams
[$handlerClass] = $paramMap;
4594 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4596 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4600 * Parse image options text and use it to make an image
4602 * @param $title Title
4603 * @param $options String
4604 * @param $holders LinkHolderArray
4606 function makeImage( $title, $options, $holders = false ) {
4607 # Check if the options text is of the form "options|alt text"
4609 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4610 # * left no resizing, just left align. label is used for alt= only
4611 # * right same, but right aligned
4612 # * none same, but not aligned
4613 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4614 # * center center the image
4615 # * frame Keep original image size, no magnify-button.
4616 # * framed Same as "frame"
4617 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4618 # * upright reduce width for upright images, rounded to full __0 px
4619 # * border draw a 1px border around the image
4620 # * alt Text for HTML alt attribute (defaults to empty)
4621 # * link Set the target of the image link. Can be external, interwiki, or local
4622 # vertical-align values (no % or length right now):
4632 $parts = StringUtils
::explode( "|", $options );
4633 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4635 # Give extensions a chance to select the file revision for us
4636 $skip = $time = $descQuery = false;
4637 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4640 return $sk->link( $title );
4644 $file = wfFindFile( $title, array( 'time' => $time ) );
4646 $handler = $file ?
$file->getHandler() : false;
4648 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4650 # Process the input parameters
4652 $params = array( 'frame' => array(), 'handler' => array(),
4653 'horizAlign' => array(), 'vertAlign' => array() );
4654 foreach ( $parts as $part ) {
4655 $part = trim( $part );
4656 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4658 if ( isset( $paramMap[$magicName] ) ) {
4659 list( $type, $paramName ) = $paramMap[$magicName];
4661 # Special case; width and height come in one variable together
4662 if ( $type === 'handler' && $paramName === 'width' ) {
4664 # (bug 13500) In both cases (width/height and width only),
4665 # permit trailing "px" for backward compatibility.
4666 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4667 $width = intval( $m[1] );
4668 $height = intval( $m[2] );
4669 if ( $handler->validateParam( 'width', $width ) ) {
4670 $params[$type]['width'] = $width;
4673 if ( $handler->validateParam( 'height', $height ) ) {
4674 $params[$type]['height'] = $height;
4677 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4678 $width = intval( $value );
4679 if ( $handler->validateParam( 'width', $width ) ) {
4680 $params[$type]['width'] = $width;
4683 } # else no validation -- bug 13436
4685 if ( $type === 'handler' ) {
4686 # Validate handler parameter
4687 $validated = $handler->validateParam( $paramName, $value );
4689 # Validate internal parameters
4690 switch( $paramName ) {
4693 # @todo Fixme: possibly check validity here for
4694 # manualthumb? downstream behavior seems odd with
4695 # missing manual thumbs.
4697 $value = $this->stripAltText( $value, $holders );
4700 $chars = self
::EXT_LINK_URL_CLASS
;
4701 $prots = $this->mUrlProtocols
;
4702 if ( $value === '' ) {
4703 $paramName = 'no-link';
4706 } elseif ( preg_match( "/^$prots/", $value ) ) {
4707 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4708 $paramName = 'link-url';
4709 $this->mOutput
->addExternalLink( $value );
4710 if ( $this->mOptions
->getExternalLinkTarget() ) {
4711 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4716 $linkTitle = Title
::newFromText( $value );
4718 $paramName = 'link-title';
4719 $value = $linkTitle;
4720 $this->mOutput
->addLink( $linkTitle );
4726 # Most other things appear to be empty or numeric...
4727 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4732 $params[$type][$paramName] = $value;
4736 if ( !$validated ) {
4741 # Process alignment parameters
4742 if ( $params['horizAlign'] ) {
4743 $params['frame']['align'] = key( $params['horizAlign'] );
4745 if ( $params['vertAlign'] ) {
4746 $params['frame']['valign'] = key( $params['vertAlign'] );
4749 $params['frame']['caption'] = $caption;
4751 # Will the image be presented in a frame, with the caption below?
4752 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4753 isset( $params['frame']['framed'] ) ||
4754 isset( $params['frame']['thumbnail'] ) ||
4755 isset( $params['frame']['manualthumb'] );
4757 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4758 # came to also set the caption, ordinary text after the image -- which
4759 # makes no sense, because that just repeats the text multiple times in
4760 # screen readers. It *also* came to set the title attribute.
4762 # Now that we have an alt attribute, we should not set the alt text to
4763 # equal the caption: that's worse than useless, it just repeats the
4764 # text. This is the framed/thumbnail case. If there's no caption, we
4765 # use the unnamed parameter for alt text as well, just for the time be-
4766 # ing, if the unnamed param is set and the alt param is not.
4768 # For the future, we need to figure out if we want to tweak this more,
4769 # e.g., introducing a title= parameter for the title; ignoring the un-
4770 # named parameter entirely for images without a caption; adding an ex-
4771 # plicit caption= parameter and preserving the old magic unnamed para-
4773 if ( $imageIsFramed ) { # Framed image
4774 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4775 # No caption or alt text, add the filename as the alt text so
4776 # that screen readers at least get some description of the image
4777 $params['frame']['alt'] = $title->getText();
4779 # Do not set $params['frame']['title'] because tooltips don't make sense
4781 } else { # Inline image
4782 if ( !isset( $params['frame']['alt'] ) ) {
4783 # No alt text, use the "caption" for the alt text
4784 if ( $caption !== '') {
4785 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4787 # No caption, fall back to using the filename for the
4789 $params['frame']['alt'] = $title->getText();
4792 # Use the "caption" for the tooltip text
4793 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4796 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4798 # Linker does the rest
4799 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4801 # Give the handler a chance to modify the parser object
4803 $handler->parserTransformHook( $this, $file );
4809 protected function stripAltText( $caption, $holders ) {
4810 # Strip bad stuff out of the title (tooltip). We can't just use
4811 # replaceLinkHoldersText() here, because if this function is called
4812 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4814 $tooltip = $holders->replaceText( $caption );
4816 $tooltip = $this->replaceLinkHoldersText( $caption );
4819 # make sure there are no placeholders in thumbnail attributes
4820 # that are later expanded to html- so expand them now and
4822 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4823 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4829 * Set a flag in the output object indicating that the content is dynamic and
4830 * shouldn't be cached.
4832 function disableCache() {
4833 wfDebug( "Parser output marked as uncacheable.\n" );
4834 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4835 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4839 * Callback from the Sanitizer for expanding items found in HTML attribute
4840 * values, so they can be safely tested and escaped.
4842 * @param $text String
4843 * @param $frame PPFrame
4847 function attributeStripCallback( &$text, $frame = false ) {
4848 $text = $this->replaceVariables( $text, $frame );
4849 $text = $this->mStripState
->unstripBoth( $text );
4856 function getTags() {
4857 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4861 * Replace transparent tags in $text with the values given by the callbacks.
4863 * Transparent tag hooks are like regular XML-style tag hooks, except they
4864 * operate late in the transformation sequence, on HTML instead of wikitext.
4866 function replaceTransparentTags( $text ) {
4868 $elements = array_keys( $this->mTransparentTagHooks
);
4869 $text = $this->extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
4871 foreach ( $matches as $marker => $data ) {
4872 list( $element, $content, $params, $tag ) = $data;
4873 $tagName = strtolower( $element );
4874 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
4875 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
4879 $this->mStripState
->addGeneral( $marker, $output );
4885 * Break wikitext input into sections, and either pull or replace
4886 * some particular section's text.
4888 * External callers should use the getSection and replaceSection methods.
4890 * @param $text String: Page wikitext
4891 * @param $section String: a section identifier string of the form:
4892 * <flag1> - <flag2> - ... - <section number>
4894 * Currently the only recognised flag is "T", which means the target section number
4895 * was derived during a template inclusion parse, in other words this is a template
4896 * section edit link. If no flags are given, it was an ordinary section edit link.
4897 * This flag is required to avoid a section numbering mismatch when a section is
4898 * enclosed by <includeonly> (bug 6563).
4900 * The section number 0 pulls the text before the first heading; other numbers will
4901 * pull the given section along with its lower-level subsections. If the section is
4902 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4904 * @param $mode String: one of "get" or "replace"
4905 * @param $newText String: replacement text for section data.
4906 * @return String: for "get", the extracted section text.
4907 * for "replace", the whole page with the section replaced.
4909 private function extractSections( $text, $section, $mode, $newText='' ) {
4910 global $wgTitle; # not generally used but removes an ugly failure mode
4911 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
4913 $frame = $this->getPreprocessor()->newFrame();
4915 # Process section extraction flags
4917 $sectionParts = explode( '-', $section );
4918 $sectionIndex = array_pop( $sectionParts );
4919 foreach ( $sectionParts as $part ) {
4920 if ( $part === 'T' ) {
4921 $flags |
= self
::PTD_FOR_INCLUSION
;
4924 # Preprocess the text
4925 $root = $this->preprocessToDom( $text, $flags );
4927 # <h> nodes indicate section breaks
4928 # They can only occur at the top level, so we can find them by iterating the root's children
4929 $node = $root->getFirstChild();
4931 # Find the target section
4932 if ( $sectionIndex == 0 ) {
4933 # Section zero doesn't nest, level=big
4934 $targetLevel = 1000;
4937 if ( $node->getName() === 'h' ) {
4938 $bits = $node->splitHeading();
4939 if ( $bits['i'] == $sectionIndex ) {
4940 $targetLevel = $bits['level'];
4944 if ( $mode === 'replace' ) {
4945 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4947 $node = $node->getNextSibling();
4953 if ( $mode === 'get' ) {
4960 # Find the end of the section, including nested sections
4962 if ( $node->getName() === 'h' ) {
4963 $bits = $node->splitHeading();
4964 $curLevel = $bits['level'];
4965 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4969 if ( $mode === 'get' ) {
4970 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4972 $node = $node->getNextSibling();
4975 # Write out the remainder (in replace mode only)
4976 if ( $mode === 'replace' ) {
4977 # Output the replacement text
4978 # Add two newlines on -- trailing whitespace in $newText is conventionally
4979 # stripped by the editor, so we need both newlines to restore the paragraph gap
4980 # Only add trailing whitespace if there is newText
4981 if ( $newText != "" ) {
4982 $outText .= $newText . "\n\n";
4986 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4987 $node = $node->getNextSibling();
4991 if ( is_string( $outText ) ) {
4992 # Re-insert stripped tags
4993 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5000 * This function returns the text of a section, specified by a number ($section).
5001 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5002 * the first section before any such heading (section 0).
5004 * If a section contains subsections, these are also returned.
5006 * @param $text String: text to look in
5007 * @param $section String: section identifier
5008 * @param $deftext String: default to return if section is not found
5009 * @return string text of the requested section
5011 public function getSection( $text, $section, $deftext='' ) {
5012 return $this->extractSections( $text, $section, "get", $deftext );
5016 * This function returns $oldtext after the content of the section
5017 * specified by $section has been replaced with $text.
5019 * @param $text String: former text of the article
5020 * @param $section Numeric: section identifier
5021 * @param $text String: replacing text
5022 * #return String: modified text
5024 public function replaceSection( $oldtext, $section, $text ) {
5025 return $this->extractSections( $oldtext, $section, "replace", $text );
5029 * Get the ID of the revision we are parsing
5031 * @return Mixed: integer or null
5033 function getRevisionId() {
5034 return $this->mRevisionId
;
5038 * Get the revision object for $this->mRevisionId
5040 * @return either a Revision object or null
5042 protected function getRevisionObject() {
5043 if ( !is_null( $this->mRevisionObject
) ) {
5044 return $this->mRevisionObject
;
5046 if ( is_null( $this->mRevisionId
) ) {
5050 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5051 return $this->mRevisionObject
;
5055 * Get the timestamp associated with the current revision, adjusted for
5056 * the default server-local timestamp
5058 function getRevisionTimestamp() {
5059 if ( is_null( $this->mRevisionTimestamp
) ) {
5060 wfProfileIn( __METHOD__
);
5062 $revObject = $this->getRevisionObject();
5063 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5065 if( $timestamp !== false ) {
5068 # The cryptic '' timezone parameter tells to use the site-default
5069 # timezone offset instead of the user settings.
5071 # Since this value will be saved into the parser cache, served
5072 # to other users, and potentially even used inside links and such,
5073 # it needs to be consistent for all visitors.
5074 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5077 wfProfileOut( __METHOD__
);
5079 return $this->mRevisionTimestamp
;
5083 * Get the name of the user that edited the last revision
5085 * @return String: user name
5087 function getRevisionUser() {
5088 if( is_null( $this->mRevisionUser
) ) {
5089 $revObject = $this->getRevisionObject();
5091 # if this template is subst: the revision id will be blank,
5092 # so just use the current user's name
5094 $this->mRevisionUser
= $revObject->getUserText();
5095 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5096 $this->mRevisionUser
= $this->getUser()->getName();
5099 return $this->mRevisionUser
;
5103 * Mutator for $mDefaultSort
5105 * @param $sort New value
5107 public function setDefaultSort( $sort ) {
5108 $this->mDefaultSort
= $sort;
5109 $this->mOutput
->setProperty( 'defaultsort', $sort );
5113 * Accessor for $mDefaultSort
5114 * Will use the empty string if none is set.
5116 * This value is treated as a prefix, so the
5117 * empty string is equivalent to sorting by
5122 public function getDefaultSort() {
5123 if ( $this->mDefaultSort
!== false ) {
5124 return $this->mDefaultSort
;
5131 * Accessor for $mDefaultSort
5132 * Unlike getDefaultSort(), will return false if none is set
5134 * @return string or false
5136 public function getCustomDefaultSort() {
5137 return $this->mDefaultSort
;
5141 * Try to guess the section anchor name based on a wikitext fragment
5142 * presumably extracted from a heading, for example "Header" from
5145 public function guessSectionNameFromWikiText( $text ) {
5146 # Strip out wikitext links(they break the anchor)
5147 $text = $this->stripSectionName( $text );
5148 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5149 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5153 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5154 * instead. For use in redirects, since IE6 interprets Redirect: headers
5155 * as something other than UTF-8 (apparently?), resulting in breakage.
5157 * @param $text String: The section name
5158 * @return string An anchor
5160 public function guessLegacySectionNameFromWikiText( $text ) {
5161 # Strip out wikitext links(they break the anchor)
5162 $text = $this->stripSectionName( $text );
5163 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5164 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5168 * Strips a text string of wikitext for use in a section anchor
5170 * Accepts a text string and then removes all wikitext from the
5171 * string and leaves only the resultant text (i.e. the result of
5172 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5173 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5174 * to create valid section anchors by mimicing the output of the
5175 * parser when headings are parsed.
5177 * @param $text String: text string to be stripped of wikitext
5178 * for use in a Section anchor
5179 * @return Filtered text string
5181 public function stripSectionName( $text ) {
5182 # Strip internal link markup
5183 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5184 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5186 # Strip external link markup (FIXME: Not Tolerant to blank link text
5187 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5188 # on how many empty links there are on the page - need to figure that out.
5189 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5191 # Parse wikitext quotes (italics & bold)
5192 $text = $this->doQuotes( $text );
5195 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5200 * strip/replaceVariables/unstrip for preprocessor regression testing
5202 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5203 if ( !$title instanceof Title
) {
5204 $title = Title
::newFromText( $title );
5206 $this->startParse( $title, $options, $outputType, true );
5208 $text = $this->replaceVariables( $text );
5209 $text = $this->mStripState
->unstripBoth( $text );
5210 $text = Sanitizer
::removeHTMLtags( $text );
5214 function testPst( $text, $title, $options ) {
5216 if ( !$title instanceof Title
) {
5217 $title = Title
::newFromText( $title );
5219 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5222 function testPreprocess( $text, $title, $options ) {
5223 if ( !$title instanceof Title
) {
5224 $title = Title
::newFromText( $title );
5226 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5230 * Call a callback function on all regions of the given text that are not
5231 * inside strip markers, and replace those regions with the return value
5232 * of the callback. For example, with input:
5236 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5237 * two strings will be replaced with the value returned by the callback in
5240 function markerSkipCallback( $s, $callback ) {
5243 while ( $i < strlen( $s ) ) {
5244 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5245 if ( $markerStart === false ) {
5246 $out .= call_user_func( $callback, substr( $s, $i ) );
5249 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5250 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5251 if ( $markerEnd === false ) {
5252 $out .= substr( $s, $markerStart );
5255 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5256 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5265 * Save the parser state required to convert the given half-parsed text to
5266 * HTML. "Half-parsed" in this context means the output of
5267 * recursiveTagParse() or internalParse(). This output has strip markers
5268 * from replaceVariables (extensionSubstitution() etc.), and link
5269 * placeholders from replaceLinkHolders().
5271 * Returns an array which can be serialized and stored persistently. This
5272 * array can later be loaded into another parser instance with
5273 * unserializeHalfParsedText(). The text can then be safely incorporated into
5274 * the return value of a parser hook.
5276 function serializeHalfParsedText( $text ) {
5277 wfProfileIn( __METHOD__
);
5280 'version' => self
::HALF_PARSED_VERSION
,
5281 'stripState' => $this->mStripState
->getSubState( $text ),
5282 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5284 wfProfileOut( __METHOD__
);
5289 * Load the parser state given in the $data array, which is assumed to
5290 * have been generated by serializeHalfParsedText(). The text contents is
5291 * extracted from the array, and its markers are transformed into markers
5292 * appropriate for the current Parser instance. This transformed text is
5293 * returned, and can be safely included in the return value of a parser
5296 * If the $data array has been stored persistently, the caller should first
5297 * check whether it is still valid, by calling isValidHalfParsedText().
5299 * @param $data Serialized data
5302 function unserializeHalfParsedText( $data ) {
5303 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5304 throw new MWException( __METHOD__
.': invalid version' );
5307 # First, extract the strip state.
5308 $texts = array( $data['text'] );
5309 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5311 # Now renumber links
5312 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5314 # Should be good to go.
5319 * Returns true if the given array, presumed to be generated by
5320 * serializeHalfParsedText(), is compatible with the current version of the
5323 * @param $data Array.
5325 function isValidHalfParsedText( $data ) {
5326 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;