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, $mStripState;
118 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
119 var $mLinkHolders, $mLinkID;
120 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
121 var $mTplExpandCache; # empty-frame expansion cache
122 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
123 var $mExpensiveFunctionCount; # number of expensive parser function calls
124 var $mUser; # User object; only used when doing pre-save transform
127 # These are variables reset at least once per parse regardless of $clearState
133 var $mTitle; # Title context, used for self-link rendering and similar things
134 var $mOutputType; # Output type, one of the OT_xxx constants
135 var $ot; # Shortcut alias, see setOutputType()
136 var $mRevisionObject; # The revision object of the specified revision ID
137 var $mRevisionId; # ID to display in {{REVISIONID}} tags
138 var $mRevisionTimestamp; # The timestamp of the specified revision ID
139 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
140 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
147 function __construct( $conf = array() ) {
148 $this->mConf
= $conf;
149 $this->mUrlProtocols
= wfUrlProtocols();
150 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
151 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
152 if ( isset( $conf['preprocessorClass'] ) ) {
153 $this->mPreprocessorClass
= $conf['preprocessorClass'];
154 } elseif ( extension_loaded( 'domxml' ) ) {
155 # PECL extension that conflicts with the core DOM extension (bug 13770)
156 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
157 $this->mPreprocessorClass
= 'Preprocessor_Hash';
158 } elseif ( extension_loaded( 'dom' ) ) {
159 $this->mPreprocessorClass
= 'Preprocessor_DOM';
161 $this->mPreprocessorClass
= 'Preprocessor_Hash';
166 * Reduce memory usage to reduce the impact of circular references
168 function __destruct() {
169 if ( isset( $this->mLinkHolders
) ) {
170 $this->mLinkHolders
->__destruct();
172 foreach ( $this as $name => $value ) {
173 unset( $this->$name );
178 * Do various kinds of initialisation on the first call of the parser
180 function firstCallInit() {
181 if ( !$this->mFirstCall
) {
184 $this->mFirstCall
= false;
186 wfProfileIn( __METHOD__
);
188 CoreParserFunctions
::register( $this );
189 CoreTagHooks
::register( $this );
190 $this->initialiseVariables();
192 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
193 wfProfileOut( __METHOD__
);
201 function clearState() {
202 wfProfileIn( __METHOD__
);
203 if ( $this->mFirstCall
) {
204 $this->firstCallInit();
206 $this->mOutput
= new ParserOutput
;
207 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
208 $this->mAutonumber
= 0;
209 $this->mLastSection
= '';
210 $this->mDTopen
= false;
211 $this->mIncludeCount
= array();
212 $this->mArgStack
= false;
213 $this->mInPre
= false;
214 $this->mLinkHolders
= new LinkHolderArray( $this );
216 $this->mRevisionObject
= $this->mRevisionTimestamp
=
217 $this->mRevisionId
= $this->mRevisionUser
= null;
218 $this->mVarCache
= array();
222 * Prefix for temporary replacement strings for the multipass parser.
223 * \x07 should never appear in input as it's disallowed in XML.
224 * Using it at the front also gives us a little extra robustness
225 * since it shouldn't match when butted up against identifier-like
228 * Must not consist of all title characters, or else it will change
229 * the behaviour of <nowiki> in a link.
231 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
232 # Changed to \x7f to allow XML double-parsing -- TS
233 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
234 $this->mStripState
= new StripState( $this->mUniqPrefix
);
237 # Clear these on every parse, bug 4549
238 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
240 $this->mShowToc
= true;
241 $this->mForceTocPosition
= false;
242 $this->mIncludeSizes
= array(
246 $this->mPPNodeCount
= 0;
247 $this->mDefaultSort
= false;
248 $this->mHeadings
= array();
249 $this->mDoubleUnderscores
= array();
250 $this->mExpensiveFunctionCount
= 0;
253 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
254 $this->mPreprocessor
= null;
257 wfRunHooks( 'ParserClearState', array( &$this ) );
258 wfProfileOut( __METHOD__
);
262 * Convert wikitext to HTML
263 * Do not call this function recursively.
265 * @param $text String: text we want to parse
266 * @param $title A title object
267 * @param $options ParserOptions
268 * @param $linestart boolean
269 * @param $clearState boolean
270 * @param $revid Int: number to pass in {{REVISIONID}}
271 * @return ParserOutput a ParserOutput
273 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
275 * First pass--just handle <nowiki> sections, pass the rest off
276 * to internalParse() which does all the real work.
279 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
280 $fname = __METHOD__
.'-' . wfGetCaller();
281 wfProfileIn( __METHOD__
);
282 wfProfileIn( $fname );
284 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
286 $oldRevisionId = $this->mRevisionId
;
287 $oldRevisionObject = $this->mRevisionObject
;
288 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
289 $oldRevisionUser = $this->mRevisionUser
;
290 if ( $revid !== null ) {
291 $this->mRevisionId
= $revid;
292 $this->mRevisionObject
= null;
293 $this->mRevisionTimestamp
= null;
294 $this->mRevisionUser
= null;
297 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
299 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
300 $text = $this->internalParse( $text );
302 $text = $this->mStripState
->unstripGeneral( $text );
304 # Clean up special characters, only run once, next-to-last before doBlockLevels
306 # french spaces, last one Guillemet-left
307 # only if there is something before the space
308 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
309 # french spaces, Guillemet-right
310 '/(\\302\\253) /' => '\\1 ',
311 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
313 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
315 $text = $this->doBlockLevels( $text, $linestart );
317 $this->replaceLinkHolders( $text );
320 * The page doesn't get language converted if
322 * b) Content isn't converted
323 * c) It's a conversion table
325 if ( !( $wgDisableLangConversion
326 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
327 ||
$this->mTitle
->isConversionTable() ) ) {
329 # The position of the convert() call should not be changed. it
330 # assumes that the links are all replaced and the only thing left
331 # is the <nowiki> mark.
333 $text = $wgContLang->convert( $text );
337 * A converted title will be provided in the output object if title and
338 * content conversion are enabled, the article text does not contain
339 * a conversion-suppressing double-underscore tag, and no
340 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
341 * automatic link conversion.
343 if ( !( $wgDisableLangConversion
344 ||
$wgDisableTitleConversion
345 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
346 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
347 ||
$this->mOutput
->getDisplayTitle() !== false ) )
349 $convruletitle = $wgContLang->getConvRuleTitle();
350 if ( $convruletitle ) {
351 $this->mOutput
->setTitleText( $convruletitle );
353 $titleText = $wgContLang->convertTitle( $title );
354 $this->mOutput
->setTitleText( $titleText );
358 $text = $this->mStripState
->unstripNoWiki( $text );
360 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
362 $text = $this->replaceTransparentTags( $text );
363 $text = $this->mStripState
->unstripGeneral( $text );
365 $text = Sanitizer
::normalizeCharReferences( $text );
367 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
368 $text = MWTidy
::tidy( $text );
370 # attempt to sanitize at least some nesting problems
371 # (bug #2702 and quite a few others)
373 # ''Something [http://www.cool.com cool''] -->
374 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
375 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
376 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
377 # fix up an anchor inside another anchor, only
378 # at least for a single single nested link (bug 3695)
379 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
380 '\\1\\2</a>\\3</a>\\1\\4</a>',
381 # fix div inside inline elements- doBlockLevels won't wrap a line which
382 # contains a div, so fix it up here; replace
383 # div with escaped text
384 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
385 '\\1\\3<div\\5>\\6</div>\\8\\9',
386 # remove empty italic or bold tag pairs, some
387 # introduced by rules above
388 '/<([bi])><\/\\1>/' => '',
391 $text = preg_replace(
392 array_keys( $tidyregs ),
393 array_values( $tidyregs ),
396 global $wgExpensiveParserFunctionLimit;
397 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
398 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
401 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
403 # Information on include size limits, for the benefit of users who try to skirt them
404 if ( $this->mOptions
->getEnableLimitReport() ) {
405 $max = $this->mOptions
->getMaxIncludeSize();
406 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
408 "NewPP limit report\n" .
409 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
410 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
411 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
413 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
414 $text .= "\n<!-- \n$limitReport-->\n";
416 $this->mOutput
->setText( $text );
418 $this->mRevisionId
= $oldRevisionId;
419 $this->mRevisionObject
= $oldRevisionObject;
420 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
421 $this->mRevisionUser
= $oldRevisionUser;
422 wfProfileOut( $fname );
423 wfProfileOut( __METHOD__
);
425 return $this->mOutput
;
429 * Recursive parser entry point that can be called from an extension tag
432 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
434 * @param $text String: text extension wants to have parsed
435 * @param $frame PPFrame: The frame to use for expanding any template variables
437 function recursiveTagParse( $text, $frame=false ) {
438 wfProfileIn( __METHOD__
);
439 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
440 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
441 $text = $this->internalParse( $text, false, $frame );
442 wfProfileOut( __METHOD__
);
447 * Expand templates and variables in the text, producing valid, static wikitext.
448 * Also removes comments.
450 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
451 wfProfileIn( __METHOD__
);
452 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
453 if ( $revid !== null ) {
454 $this->mRevisionId
= $revid;
456 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
457 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
458 $text = $this->replaceVariables( $text );
459 $text = $this->mStripState
->unstripBoth( $text );
460 wfProfileOut( __METHOD__
);
465 * Process the wikitext for the ?preload= feature. (bug 5210)
467 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
468 * comments, templates, arguments, tags hooks and parser functions are untouched.
470 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
471 # Parser (re)initialisation
472 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
474 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
475 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
476 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
477 $text = $this->mStripState
->unstripBoth( $text );
482 * Get a random string
487 static private function getRandomString() {
488 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
492 * Set the current user.
493 * Should only be used when doing pre-save transform.
495 * @param $user Mixed: User object or null (to reset)
497 function setUser( $user ) {
498 $this->mUser
= $user;
502 * Accessor for mUniqPrefix.
506 public function uniqPrefix() {
507 if ( !isset( $this->mUniqPrefix
) ) {
508 # @todo Fixme: this is probably *horribly wrong*
509 # LanguageConverter seems to want $wgParser's uniqPrefix, however
510 # if this is called for a parser cache hit, the parser may not
511 # have ever been initialized in the first place.
512 # Not really sure what the heck is supposed to be going on here.
514 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
516 return $this->mUniqPrefix
;
520 * Set the context title
522 function setTitle( $t ) {
523 if ( !$t ||
$t instanceof FakeTitle
) {
524 $t = Title
::newFromText( 'NO TITLE' );
527 if ( strval( $t->getFragment() ) !== '' ) {
528 # Strip the fragment to avoid various odd effects
529 $this->mTitle
= clone $t;
530 $this->mTitle
->setFragment( '' );
537 * Accessor for the Title object
539 * @return Title object
541 function getTitle() {
542 return $this->mTitle
;
546 * Accessor/mutator for the Title object
548 * @param $x New Title object or null to just get the current one
549 * @return Title object
551 function Title( $x = null ) {
552 return wfSetVar( $this->mTitle
, $x );
556 * Set the output type
558 * @param $ot Integer: new value
560 function setOutputType( $ot ) {
561 $this->mOutputType
= $ot;
564 'html' => $ot == self
::OT_HTML
,
565 'wiki' => $ot == self
::OT_WIKI
,
566 'pre' => $ot == self
::OT_PREPROCESS
,
567 'plain' => $ot == self
::OT_PLAIN
,
572 * Accessor/mutator for the output type
574 * @param $x New value or null to just get the current one
577 function OutputType( $x = null ) {
578 return wfSetVar( $this->mOutputType
, $x );
582 * Get the ParserOutput object
584 * @return ParserOutput object
586 function getOutput() {
587 return $this->mOutput
;
591 * Get the ParserOptions object
593 * @return ParserOptions object
595 function getOptions() {
596 return $this->mOptions
;
600 * Accessor/mutator for the ParserOptions object
602 * @param $x New value or null to just get the current one
603 * @return Current ParserOptions object
605 function Options( $x = null ) {
606 return wfSetVar( $this->mOptions
, $x );
609 function nextLinkID() {
610 return $this->mLinkID++
;
613 function setLinkID( $id ) {
614 $this->mLinkID
= $id;
620 function getFunctionLang() {
621 global $wgLang, $wgContLang;
623 $target = $this->mOptions
->getTargetLanguage();
624 if ( $target !== null ) {
627 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
632 * Get a User object either from $this->mUser, if set, or from the
633 * ParserOptions object otherwise
635 * @return User object
638 if ( !is_null( $this->mUser
) ) {
641 return $this->mOptions
->getUser();
645 * Get a preprocessor object
647 * @return Preprocessor instance
649 function getPreprocessor() {
650 if ( !isset( $this->mPreprocessor
) ) {
651 $class = $this->mPreprocessorClass
;
652 $this->mPreprocessor
= new $class( $this );
654 return $this->mPreprocessor
;
658 * Replaces all occurrences of HTML-style comments and the given tags
659 * in the text with a random marker and returns the next text. The output
660 * parameter $matches will be an associative array filled with data in
662 * 'UNIQ-xxxxx' => array(
665 * array( 'param' => 'x' ),
666 * '<element param="x">tag content</element>' ) )
668 * @param $elements list of element names. Comments are always extracted.
669 * @param $text Source text string.
670 * @param $matches Out parameter, Array: extracted tags
671 * @param $uniq_prefix
672 * @return String: stripped text
676 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
681 $taglist = implode( '|', $elements );
682 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
684 while ( $text != '' ) {
685 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
687 if ( count( $p ) < 5 ) {
690 if ( count( $p ) > 5 ) {
704 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
705 $stripped .= $marker;
707 if ( $close === '/>' ) {
708 # Empty element tag, <tag />
713 if ( $element === '!--' ) {
716 $end = "/(<\\/$element\\s*>)/i";
718 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
720 if ( count( $q ) < 3 ) {
721 # No end tag -- let it run out to the end of the text.
730 $matches[$marker] = array( $element,
732 Sanitizer
::decodeTagAttributes( $attributes ),
733 "<$element$attributes$close$content$tail" );
739 * Get a list of strippable XML-like elements
741 function getStripList() {
742 return $this->mStripList
;
746 * @deprecated use replaceVariables
748 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
753 * Restores pre, math, and other extensions removed by strip()
755 * always call unstripNoWiki() after this one
757 * @deprecated use $this->mStripState->unstrip()
759 function unstrip( $text, $state ) {
760 return $state->unstripGeneral( $text );
764 * Always call this after unstrip() to preserve the order
767 * @deprecated use $this->mStripState->unstrip()
769 function unstripNoWiki( $text, $state ) {
770 return $state->unstripNoWiki( $text );
774 * @deprecated use $this->mStripState->unstripBoth()
776 function unstripForHTML( $text ) {
777 return $this->mStripState
->unstripBoth( $text );
781 * Add an item to the strip state
782 * Returns the unique tag which must be inserted into the stripped text
783 * The tag will be replaced with the original text in unstrip()
787 function insertStripItem( $text ) {
788 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
789 $this->mMarkerIndex++
;
790 $this->mStripState
->addGeneral( $rnd, $text );
795 * Interface with html tidy
796 * @deprecated Use MWTidy::tidy()
798 public static function tidy( $text ) {
799 wfDeprecated( __METHOD__
);
800 return MWTidy
::tidy( $text );
804 * parse the wiki syntax used to render tables
808 function doTableStuff( $text ) {
809 wfProfileIn( __METHOD__
);
811 $lines = StringUtils
::explode( "\n", $text );
813 $td_history = array(); # Is currently a td tag open?
814 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
815 $tr_history = array(); # Is currently a tr tag open?
816 $tr_attributes = array(); # history of tr attributes
817 $has_opened_tr = array(); # Did this table open a <tr> element?
818 $indent_level = 0; # indent level of the table
820 foreach ( $lines as $outLine ) {
821 $line = trim( $outLine );
823 if ( $line === '' ) { # empty line, go to next line
824 $out .= $outLine."\n";
828 $first_character = $line[0];
831 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
832 # First check if we are starting a new table
833 $indent_level = strlen( $matches[1] );
835 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
836 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
838 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
839 array_push( $td_history , false );
840 array_push( $last_tag_history , '' );
841 array_push( $tr_history , false );
842 array_push( $tr_attributes , '' );
843 array_push( $has_opened_tr , false );
844 } elseif ( count( $td_history ) == 0 ) {
845 # Don't do any of the following
846 $out .= $outLine."\n";
848 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
849 # We are ending a table
850 $line = '</table>' . substr( $line , 2 );
851 $last_tag = array_pop( $last_tag_history );
853 if ( !array_pop( $has_opened_tr ) ) {
854 $line = "<tr><td></td></tr>{$line}";
857 if ( array_pop( $tr_history ) ) {
858 $line = "</tr>{$line}";
861 if ( array_pop( $td_history ) ) {
862 $line = "</{$last_tag}>{$line}";
864 array_pop( $tr_attributes );
865 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
866 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
867 # Now we have a table row
868 $line = preg_replace( '#^\|-+#', '', $line );
870 # Whats after the tag is now only attributes
871 $attributes = $this->mStripState
->unstripBoth( $line );
872 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
873 array_pop( $tr_attributes );
874 array_push( $tr_attributes, $attributes );
877 $last_tag = array_pop( $last_tag_history );
878 array_pop( $has_opened_tr );
879 array_push( $has_opened_tr , true );
881 if ( array_pop( $tr_history ) ) {
885 if ( array_pop( $td_history ) ) {
886 $line = "</{$last_tag}>{$line}";
890 array_push( $tr_history , false );
891 array_push( $td_history , false );
892 array_push( $last_tag_history , '' );
893 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
894 # This might be cell elements, td, th or captions
895 if ( substr( $line , 0 , 2 ) === '|+' ) {
896 $first_character = '+';
897 $line = substr( $line , 1 );
900 $line = substr( $line , 1 );
902 if ( $first_character === '!' ) {
903 $line = str_replace( '!!' , '||' , $line );
906 # Split up multiple cells on the same line.
907 # FIXME : This can result in improper nesting of tags processed
908 # by earlier parser steps, but should avoid splitting up eg
909 # attribute values containing literal "||".
910 $cells = StringUtils
::explodeMarkup( '||' , $line );
914 # Loop through each table cell
915 foreach ( $cells as $cell ) {
917 if ( $first_character !== '+' ) {
918 $tr_after = array_pop( $tr_attributes );
919 if ( !array_pop( $tr_history ) ) {
920 $previous = "<tr{$tr_after}>\n";
922 array_push( $tr_history , true );
923 array_push( $tr_attributes , '' );
924 array_pop( $has_opened_tr );
925 array_push( $has_opened_tr , true );
928 $last_tag = array_pop( $last_tag_history );
930 if ( array_pop( $td_history ) ) {
931 $previous = "</{$last_tag}>\n{$previous}";
934 if ( $first_character === '|' ) {
936 } elseif ( $first_character === '!' ) {
938 } elseif ( $first_character === '+' ) {
939 $last_tag = 'caption';
944 array_push( $last_tag_history , $last_tag );
946 # A cell could contain both parameters and data
947 $cell_data = explode( '|' , $cell , 2 );
949 # Bug 553: Note that a '|' inside an invalid link should not
950 # be mistaken as delimiting cell parameters
951 if ( strpos( $cell_data[0], '[[' ) !== false ) {
952 $cell = "{$previous}<{$last_tag}>{$cell}";
953 } elseif ( count( $cell_data ) == 1 ) {
954 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
956 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
957 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
958 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
962 array_push( $td_history , true );
965 $out .= $outLine . "\n";
968 # Closing open td, tr && table
969 while ( count( $td_history ) > 0 ) {
970 if ( array_pop( $td_history ) ) {
973 if ( array_pop( $tr_history ) ) {
976 if ( !array_pop( $has_opened_tr ) ) {
977 $out .= "<tr><td></td></tr>\n" ;
980 $out .= "</table>\n";
983 # Remove trailing line-ending (b/c)
984 if ( substr( $out, -1 ) === "\n" ) {
985 $out = substr( $out, 0, -1 );
988 # special case: don't return empty table
989 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
993 wfProfileOut( __METHOD__
);
999 * Helper function for parse() that transforms wiki markup into
1000 * HTML. Only called for $mOutputType == self::OT_HTML.
1004 function internalParse( $text, $isMain = true, $frame=false ) {
1005 wfProfileIn( __METHOD__
);
1009 # Hook to suspend the parser in this state
1010 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1011 wfProfileOut( __METHOD__
);
1015 # if $frame is provided, then use $frame for replacing any variables
1017 # use frame depth to infer how include/noinclude tags should be handled
1018 # depth=0 means this is the top-level document; otherwise it's an included document
1019 if ( !$frame->depth
) {
1022 $flag = Parser
::PTD_FOR_INCLUSION
;
1024 $dom = $this->preprocessToDom( $text, $flag );
1025 $text = $frame->expand( $dom );
1027 # if $frame is not provided, then use old-style replaceVariables
1028 $text = $this->replaceVariables( $text );
1031 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1032 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1034 # Tables need to come after variable replacement for things to work
1035 # properly; putting them before other transformations should keep
1036 # exciting things like link expansions from showing up in surprising
1038 $text = $this->doTableStuff( $text );
1040 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1042 $text = $this->doDoubleUnderscore( $text );
1044 $text = $this->doHeadings( $text );
1045 if ( $this->mOptions
->getUseDynamicDates() ) {
1046 $df = DateFormatter
::getInstance();
1047 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1049 $text = $this->replaceInternalLinks( $text );
1050 $text = $this->doAllQuotes( $text );
1051 $text = $this->replaceExternalLinks( $text );
1053 # replaceInternalLinks may sometimes leave behind
1054 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1055 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1057 $text = $this->doMagicLinks( $text );
1058 $text = $this->formatHeadings( $text, $origText, $isMain );
1060 wfProfileOut( __METHOD__
);
1065 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1066 * magic external links.
1071 function doMagicLinks( $text ) {
1072 wfProfileIn( __METHOD__
);
1073 $prots = $this->mUrlProtocols
;
1074 $urlChar = self
::EXT_LINK_URL_CLASS
;
1075 $text = preg_replace_callback(
1077 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1078 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1079 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1080 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1081 ISBN\s+(\b # m[5]: ISBN, capture number
1082 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1083 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1084 [0-9Xx] # check digit
1086 )!x', array( &$this, 'magicLinkCallback' ), $text );
1087 wfProfileOut( __METHOD__
);
1091 function magicLinkCallback( $m ) {
1092 if ( isset( $m[1] ) && $m[1] !== '' ) {
1095 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1098 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1099 # Free external link
1100 return $this->makeFreeExternalLink( $m[0] );
1101 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1103 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1106 $CssClass = 'mw-magiclink-rfc';
1108 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1110 $urlmsg = 'pubmedurl';
1111 $CssClass = 'mw-magiclink-pmid';
1114 throw new MWException( __METHOD__
.': unrecognised match type "' .
1115 substr( $m[0], 0, 20 ) . '"' );
1117 $url = wfMsgForContent( $urlmsg, $id );
1118 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1119 return $sk->makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1120 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1123 $num = strtr( $isbn, array(
1128 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1130 $titleObj->escapeLocalUrl() .
1131 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1138 * Make a free external link, given a user-supplied URL
1142 function makeFreeExternalLink( $url ) {
1144 wfProfileIn( __METHOD__
);
1146 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1149 # The characters '<' and '>' (which were escaped by
1150 # removeHTMLtags()) should not be included in
1151 # URLs, per RFC 2396.
1153 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1154 $trail = substr( $url, $m2[0][1] ) . $trail;
1155 $url = substr( $url, 0, $m2[0][1] );
1158 # Move trailing punctuation to $trail
1160 # If there is no left bracket, then consider right brackets fair game too
1161 if ( strpos( $url, '(' ) === false ) {
1165 $numSepChars = strspn( strrev( $url ), $sep );
1166 if ( $numSepChars ) {
1167 $trail = substr( $url, -$numSepChars ) . $trail;
1168 $url = substr( $url, 0, -$numSepChars );
1171 $url = Sanitizer
::cleanUrl( $url );
1173 # Is this an external image?
1174 $text = $this->maybeMakeExternalImage( $url );
1175 if ( $text === false ) {
1176 # Not an image, make a link
1177 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1178 $this->getExternalLinkAttribs( $url ) );
1179 # Register it in the output object...
1180 # Replace unnecessary URL escape codes with their equivalent characters
1181 $pasteurized = self
::replaceUnusualEscapes( $url );
1182 $this->mOutput
->addExternalLink( $pasteurized );
1184 wfProfileOut( __METHOD__
);
1185 return $text . $trail;
1190 * Parse headers and return html
1194 function doHeadings( $text ) {
1195 wfProfileIn( __METHOD__
);
1196 for ( $i = 6; $i >= 1; --$i ) {
1197 $h = str_repeat( '=', $i );
1198 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1199 "<h$i>\\1</h$i>", $text );
1201 wfProfileOut( __METHOD__
);
1206 * Replace single quotes with HTML markup
1208 * @return string the altered text
1210 function doAllQuotes( $text ) {
1211 wfProfileIn( __METHOD__
);
1213 $lines = StringUtils
::explode( "\n", $text );
1214 foreach ( $lines as $line ) {
1215 $outtext .= $this->doQuotes( $line ) . "\n";
1217 $outtext = substr( $outtext, 0,-1 );
1218 wfProfileOut( __METHOD__
);
1223 * Helper function for doAllQuotes()
1225 public function doQuotes( $text ) {
1226 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1227 if ( count( $arr ) == 1 ) {
1230 # First, do some preliminary work. This may shift some apostrophes from
1231 # being mark-up to being text. It also counts the number of occurrences
1232 # of bold and italics mark-ups.
1235 for ( $i = 0; $i < count( $arr ); $i++
) {
1236 if ( ( $i %
2 ) == 1 ) {
1237 # If there are ever four apostrophes, assume the first is supposed to
1238 # be text, and the remaining three constitute mark-up for bold text.
1239 if ( strlen( $arr[$i] ) == 4 ) {
1242 } elseif ( strlen( $arr[$i] ) > 5 ) {
1243 # If there are more than 5 apostrophes in a row, assume they're all
1244 # text except for the last 5.
1245 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1248 # Count the number of occurrences of bold and italics mark-ups.
1249 # We are not counting sequences of five apostrophes.
1250 if ( strlen( $arr[$i] ) == 2 ) {
1252 } elseif ( strlen( $arr[$i] ) == 3 ) {
1254 } elseif ( strlen( $arr[$i] ) == 5 ) {
1261 # If there is an odd number of both bold and italics, it is likely
1262 # that one of the bold ones was meant to be an apostrophe followed
1263 # by italics. Which one we cannot know for certain, but it is more
1264 # likely to be one that has a single-letter word before it.
1265 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1267 $firstsingleletterword = -1;
1268 $firstmultiletterword = -1;
1270 foreach ( $arr as $r ) {
1271 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1272 $x1 = substr( $arr[$i-1], -1 );
1273 $x2 = substr( $arr[$i-1], -2, 1 );
1274 if ( $x1 === ' ' ) {
1275 if ( $firstspace == -1 ) {
1278 } elseif ( $x2 === ' ') {
1279 if ( $firstsingleletterword == -1 ) {
1280 $firstsingleletterword = $i;
1283 if ( $firstmultiletterword == -1 ) {
1284 $firstmultiletterword = $i;
1291 # If there is a single-letter word, use it!
1292 if ( $firstsingleletterword > -1 ) {
1293 $arr[$firstsingleletterword] = "''";
1294 $arr[$firstsingleletterword-1] .= "'";
1295 } elseif ( $firstmultiletterword > -1 ) {
1296 # If not, but there's a multi-letter word, use that one.
1297 $arr[$firstmultiletterword] = "''";
1298 $arr[$firstmultiletterword-1] .= "'";
1299 } elseif ( $firstspace > -1 ) {
1300 # ... otherwise use the first one that has neither.
1301 # (notice that it is possible for all three to be -1 if, for example,
1302 # there is only one pentuple-apostrophe in the line)
1303 $arr[$firstspace] = "''";
1304 $arr[$firstspace-1] .= "'";
1308 # Now let's actually convert our apostrophic mush to HTML!
1313 foreach ( $arr as $r ) {
1314 if ( ( $i %
2 ) == 0 ) {
1315 if ( $state === 'both' ) {
1321 if ( strlen( $r ) == 2 ) {
1322 if ( $state === 'i' ) {
1323 $output .= '</i>'; $state = '';
1324 } elseif ( $state === 'bi' ) {
1325 $output .= '</i>'; $state = 'b';
1326 } elseif ( $state === 'ib' ) {
1327 $output .= '</b></i><b>'; $state = 'b';
1328 } elseif ( $state === 'both' ) {
1329 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1330 } else { # $state can be 'b' or ''
1331 $output .= '<i>'; $state .= 'i';
1333 } elseif ( strlen( $r ) == 3 ) {
1334 if ( $state === 'b' ) {
1335 $output .= '</b>'; $state = '';
1336 } elseif ( $state === 'bi' ) {
1337 $output .= '</i></b><i>'; $state = 'i';
1338 } elseif ( $state === 'ib' ) {
1339 $output .= '</b>'; $state = 'i';
1340 } elseif ( $state === 'both' ) {
1341 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1342 } else { # $state can be 'i' or ''
1343 $output .= '<b>'; $state .= 'b';
1345 } elseif ( strlen( $r ) == 5 ) {
1346 if ( $state === 'b' ) {
1347 $output .= '</b><i>'; $state = 'i';
1348 } elseif ( $state === 'i' ) {
1349 $output .= '</i><b>'; $state = 'b';
1350 } elseif ( $state === 'bi' ) {
1351 $output .= '</i></b>'; $state = '';
1352 } elseif ( $state === 'ib' ) {
1353 $output .= '</b></i>'; $state = '';
1354 } elseif ( $state === 'both' ) {
1355 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1356 } else { # ($state == '')
1357 $buffer = ''; $state = 'both';
1363 # Now close all remaining tags. Notice that the order is important.
1364 if ( $state === 'b' ||
$state === 'ib' ) {
1367 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1370 if ( $state === 'bi' ) {
1373 # There might be lonely ''''', so make sure we have a buffer
1374 if ( $state === 'both' && $buffer ) {
1375 $output .= '<b><i>'.$buffer.'</i></b>';
1382 * Replace external links (REL)
1384 * Note: this is all very hackish and the order of execution matters a lot.
1385 * Make sure to run maintenance/parserTests.php if you change this code.
1389 function replaceExternalLinks( $text ) {
1391 wfProfileIn( __METHOD__
);
1393 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1395 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1396 $s = array_shift( $bits );
1399 while ( $i<count( $bits ) ) {
1401 $protocol = $bits[$i++
];
1402 $text = $bits[$i++
];
1403 $trail = $bits[$i++
];
1405 # The characters '<' and '>' (which were escaped by
1406 # removeHTMLtags()) should not be included in
1407 # URLs, per RFC 2396.
1409 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1410 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1411 $url = substr( $url, 0, $m2[0][1] );
1414 # If the link text is an image URL, replace it with an <img> tag
1415 # This happened by accident in the original parser, but some people used it extensively
1416 $img = $this->maybeMakeExternalImage( $text );
1417 if ( $img !== false ) {
1423 # Set linktype for CSS - if URL==text, link is essentially free
1424 $linktype = ( $text === $url ) ?
'free' : 'text';
1426 # No link text, e.g. [http://domain.tld/some.link]
1427 if ( $text == '' ) {
1428 # Autonumber if allowed. See bug #5918
1429 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1430 $langObj = $this->getFunctionLang();
1431 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1432 $linktype = 'autonumber';
1434 # Otherwise just use the URL
1435 $text = htmlspecialchars( $url );
1439 # Have link text, e.g. [http://domain.tld/some.link text]s
1441 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1444 $text = $wgContLang->markNoConversion( $text );
1446 $url = Sanitizer
::cleanUrl( $url );
1448 # Use the encoded URL
1449 # This means that users can paste URLs directly into the text
1450 # Funny characters like ö aren't valid in URLs anyway
1451 # This was changed in August 2004
1452 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1453 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1455 # Register link in the output object.
1456 # Replace unnecessary URL escape codes with the referenced character
1457 # This prevents spammers from hiding links from the filters
1458 $pasteurized = self
::replaceUnusualEscapes( $url );
1459 $this->mOutput
->addExternalLink( $pasteurized );
1462 wfProfileOut( __METHOD__
);
1467 * Get an associative array of additional HTML attributes appropriate for a
1468 * particular external link. This currently may include rel => nofollow
1469 * (depending on configuration, namespace, and the URL's domain) and/or a
1470 * target attribute (depending on configuration).
1472 * @param $url String: optional URL, to extract the domain from for rel =>
1473 * nofollow if appropriate
1474 * @return Array: associative array of HTML attributes
1476 function getExternalLinkAttribs( $url = false ) {
1478 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1479 $ns = $this->mTitle
->getNamespace();
1480 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1481 $attribs['rel'] = 'nofollow';
1483 global $wgNoFollowDomainExceptions;
1484 if ( $wgNoFollowDomainExceptions ) {
1485 $bits = wfParseUrl( $url );
1486 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1487 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1488 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1489 unset( $attribs['rel'] );
1496 if ( $this->mOptions
->getExternalLinkTarget() ) {
1497 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1504 * Replace unusual URL escape codes with their equivalent characters
1506 * @param $url String
1509 * @todo This can merge genuinely required bits in the path or query string,
1510 * breaking legit URLs. A proper fix would treat the various parts of
1511 * the URL differently; as a workaround, just use the output for
1512 * statistical records, not for actual linking/output.
1514 static function replaceUnusualEscapes( $url ) {
1515 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1516 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1520 * Callback function used in replaceUnusualEscapes().
1521 * Replaces unusual URL escape codes with their equivalent character
1523 private static function replaceUnusualEscapesCallback( $matches ) {
1524 $char = urldecode( $matches[0] );
1525 $ord = ord( $char );
1526 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1527 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1528 # No, shouldn't be escaped
1531 # Yes, leave it escaped
1537 * make an image if it's allowed, either through the global
1538 * option, through the exception, or through the on-wiki whitelist
1541 function maybeMakeExternalImage( $url ) {
1542 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1543 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1544 $imagesexception = !empty( $imagesfrom );
1546 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1547 if ( $imagesexception && is_array( $imagesfrom ) ) {
1548 $imagematch = false;
1549 foreach ( $imagesfrom as $match ) {
1550 if ( strpos( $url, $match ) === 0 ) {
1555 } elseif ( $imagesexception ) {
1556 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1558 $imagematch = false;
1560 if ( $this->mOptions
->getAllowExternalImages()
1561 ||
( $imagesexception && $imagematch ) ) {
1562 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1564 $text = $sk->makeExternalImage( $url );
1567 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1568 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1569 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1570 foreach ( $whitelist as $entry ) {
1571 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1572 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1575 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1576 # Image matches a whitelist entry
1577 $text = $sk->makeExternalImage( $url );
1586 * Process [[ ]] wikilinks
1587 * @return String: processed text
1591 function replaceInternalLinks( $s ) {
1592 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1597 * Process [[ ]] wikilinks (RIL)
1598 * @return LinkHolderArray
1602 function replaceInternalLinks2( &$s ) {
1605 wfProfileIn( __METHOD__
);
1607 wfProfileIn( __METHOD__
.'-setup' );
1608 static $tc = FALSE, $e1, $e1_img;
1609 # the % is needed to support urlencoded titles as well
1611 $tc = Title
::legalChars() . '#%';
1612 # Match a link having the form [[namespace:link|alternate]]trail
1613 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1614 # Match cases where there is no "]]", which might still be images
1615 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1618 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1619 $holders = new LinkHolderArray( $this );
1621 # split the entire text string on occurences of [[
1622 $a = StringUtils
::explode( '[[', ' ' . $s );
1623 # get the first element (all text up to first [[), and remove the space we added
1626 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1627 $s = substr( $s, 1 );
1629 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1631 if ( $useLinkPrefixExtension ) {
1632 # Match the end of a line for a word that's not followed by whitespace,
1633 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1634 $e2 = wfMsgForContent( 'linkprefix' );
1637 if ( is_null( $this->mTitle
) ) {
1638 wfProfileOut( __METHOD__
.'-setup' );
1639 wfProfileOut( __METHOD__
);
1640 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1642 $nottalk = !$this->mTitle
->isTalkPage();
1644 if ( $useLinkPrefixExtension ) {
1646 if ( preg_match( $e2, $s, $m ) ) {
1647 $first_prefix = $m[2];
1649 $first_prefix = false;
1655 if ( $wgContLang->hasVariants() ) {
1656 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1658 $selflink = array( $this->mTitle
->getPrefixedText() );
1660 $useSubpages = $this->areSubpagesAllowed();
1661 wfProfileOut( __METHOD__
.'-setup' );
1663 # Loop for each link
1664 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1665 # Check for excessive memory usage
1666 if ( $holders->isBig() ) {
1668 # Do the existence check, replace the link holders and clear the array
1669 $holders->replace( $s );
1673 if ( $useLinkPrefixExtension ) {
1674 wfProfileIn( __METHOD__
.'-prefixhandling' );
1675 if ( preg_match( $e2, $s, $m ) ) {
1682 if ( $first_prefix ) {
1683 $prefix = $first_prefix;
1684 $first_prefix = false;
1686 wfProfileOut( __METHOD__
.'-prefixhandling' );
1689 $might_be_img = false;
1691 wfProfileIn( __METHOD__
."-e1" );
1692 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1694 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1695 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1696 # the real problem is with the $e1 regex
1699 # Still some problems for cases where the ] is meant to be outside punctuation,
1700 # and no image is in sight. See bug 2095.
1702 if ( $text !== '' &&
1703 substr( $m[3], 0, 1 ) === ']' &&
1704 strpos( $text, '[' ) !== false
1707 $text .= ']'; # so that replaceExternalLinks($text) works later
1708 $m[3] = substr( $m[3], 1 );
1710 # fix up urlencoded title texts
1711 if ( strpos( $m[1], '%' ) !== false ) {
1712 # Should anchors '#' also be rejected?
1713 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1716 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1717 $might_be_img = true;
1719 if ( strpos( $m[1], '%' ) !== false ) {
1720 $m[1] = rawurldecode( $m[1] );
1723 } else { # Invalid form; output directly
1724 $s .= $prefix . '[[' . $line ;
1725 wfProfileOut( __METHOD__
."-e1" );
1728 wfProfileOut( __METHOD__
."-e1" );
1729 wfProfileIn( __METHOD__
."-misc" );
1731 # Don't allow internal links to pages containing
1732 # PROTO: where PROTO is a valid URL protocol; these
1733 # should be external links.
1734 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1735 $s .= $prefix . '[[' . $line ;
1736 wfProfileOut( __METHOD__
."-misc" );
1740 # Make subpage if necessary
1741 if ( $useSubpages ) {
1742 $link = $this->maybeDoSubpageLink( $m[1], $text );
1747 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1749 # Strip off leading ':'
1750 $link = substr( $link, 1 );
1753 wfProfileOut( __METHOD__
."-misc" );
1754 wfProfileIn( __METHOD__
."-title" );
1755 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1756 if ( $nt === null ) {
1757 $s .= $prefix . '[[' . $line;
1758 wfProfileOut( __METHOD__
."-title" );
1762 $ns = $nt->getNamespace();
1763 $iw = $nt->getInterWiki();
1764 wfProfileOut( __METHOD__
."-title" );
1766 if ( $might_be_img ) { # if this is actually an invalid link
1767 wfProfileIn( __METHOD__
."-might_be_img" );
1768 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1771 # look at the next 'line' to see if we can close it there
1773 $next_line = $a->current();
1774 if ( $next_line === false ||
$next_line === null ) {
1777 $m = explode( ']]', $next_line, 3 );
1778 if ( count( $m ) == 3 ) {
1779 # the first ]] closes the inner link, the second the image
1781 $text .= "[[{$m[0]}]]{$m[1]}";
1784 } elseif ( count( $m ) == 2 ) {
1785 # if there's exactly one ]] that's fine, we'll keep looking
1786 $text .= "[[{$m[0]}]]{$m[1]}";
1788 # if $next_line is invalid too, we need look no further
1789 $text .= '[[' . $next_line;
1794 # we couldn't find the end of this imageLink, so output it raw
1795 # but don't ignore what might be perfectly normal links in the text we've examined
1796 $holders->merge( $this->replaceInternalLinks2( $text ) );
1797 $s .= "{$prefix}[[$link|$text";
1798 # note: no $trail, because without an end, there *is* no trail
1799 wfProfileOut( __METHOD__
."-might_be_img" );
1802 } else { # it's not an image, so output it raw
1803 $s .= "{$prefix}[[$link|$text";
1804 # note: no $trail, because without an end, there *is* no trail
1805 wfProfileOut( __METHOD__
."-might_be_img" );
1808 wfProfileOut( __METHOD__
."-might_be_img" );
1811 $wasblank = ( $text == '' );
1815 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1816 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1817 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1818 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1819 $text = $this->doQuotes( $text );
1822 # Link not escaped by : , create the various objects
1826 wfProfileIn( __METHOD__
."-interwiki" );
1827 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1828 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1829 $s = rtrim( $s . $prefix );
1830 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1831 wfProfileOut( __METHOD__
."-interwiki" );
1834 wfProfileOut( __METHOD__
."-interwiki" );
1836 if ( $ns == NS_FILE
) {
1837 wfProfileIn( __METHOD__
."-image" );
1838 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1840 # if no parameters were passed, $text
1841 # becomes something like "File:Foo.png",
1842 # which we don't want to pass on to the
1846 # recursively parse links inside the image caption
1847 # actually, this will parse them in any other parameters, too,
1848 # but it might be hard to fix that, and it doesn't matter ATM
1849 $text = $this->replaceExternalLinks( $text );
1850 $holders->merge( $this->replaceInternalLinks2( $text ) );
1852 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1853 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1855 $s .= $prefix . $trail;
1857 $this->mOutput
->addImage( $nt->getDBkey() );
1858 wfProfileOut( __METHOD__
."-image" );
1863 if ( $ns == NS_CATEGORY
) {
1864 wfProfileIn( __METHOD__
."-category" );
1865 $s = rtrim( $s . "\n" ); # bug 87
1868 $sortkey = $this->getDefaultSort();
1872 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1873 $sortkey = str_replace( "\n", '', $sortkey );
1874 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1875 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1878 * Strip the whitespace Category links produce, see bug 87
1879 * @todo We might want to use trim($tmp, "\n") here.
1881 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1883 wfProfileOut( __METHOD__
."-category" );
1888 # Self-link checking
1889 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1890 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1891 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1896 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1897 # FIXME: Should do batch file existence checks, see comment below
1898 if ( $ns == NS_MEDIA
) {
1899 wfProfileIn( __METHOD__
."-media" );
1900 # Give extensions a chance to select the file revision for us
1901 $skip = $time = false;
1902 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1904 $link = $sk->link( $nt );
1906 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1908 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1909 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1910 $this->mOutput
->addImage( $nt->getDBkey() );
1911 wfProfileOut( __METHOD__
."-media" );
1915 wfProfileIn( __METHOD__
."-always_known" );
1916 # Some titles, such as valid special pages or files in foreign repos, should
1917 # be shown as bluelinks even though they're not included in the page table
1919 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1920 # batch file existence checks for NS_FILE and NS_MEDIA
1921 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1922 $this->mOutput
->addLink( $nt );
1923 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1925 # Links will be added to the output link list after checking
1926 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1928 wfProfileOut( __METHOD__
."-always_known" );
1930 wfProfileOut( __METHOD__
);
1935 * Make a link placeholder. The text returned can be later resolved to a real link with
1936 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1937 * parsing of interwiki links, and secondly to allow all existence checks and
1938 * article length checks (for stub links) to be bundled into a single query.
1942 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1943 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1947 * Render a forced-blue link inline; protect against double expansion of
1948 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1949 * Since this little disaster has to split off the trail text to avoid
1950 * breaking URLs in the following text without breaking trails on the
1951 * wiki links, it's been made into a horrible function.
1954 * @param $text String
1955 * @param $query String
1956 * @param $trail String
1957 * @param $prefix String
1958 * @return String: HTML-wikitext mix oh yuck
1960 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1961 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1962 $sk = $this->mOptions
->getSkin( $this->mTitle
);
1963 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1964 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1965 return $this->armorLinks( $link ) . $trail;
1969 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1970 * going to go through further parsing steps before inline URL expansion.
1972 * Not needed quite as much as it used to be since free links are a bit
1973 * more sensible these days. But bracketed links are still an issue.
1975 * @param $text String: more-or-less HTML
1976 * @return String: less-or-more HTML with NOPARSE bits
1978 function armorLinks( $text ) {
1979 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1980 "{$this->mUniqPrefix}NOPARSE$1", $text );
1984 * Return true if subpage links should be expanded on this page.
1987 function areSubpagesAllowed() {
1988 # Some namespaces don't allow subpages
1989 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1993 * Handle link to subpage if necessary
1995 * @param $target String: the source of the link
1996 * @param &$text String: the link text, modified as necessary
1997 * @return string the full name of the link
2000 function maybeDoSubpageLink( $target, &$text ) {
2001 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2005 * Used by doBlockLevels()
2008 function closeParagraph() {
2010 if ( $this->mLastSection
!= '' ) {
2011 $result = '</' . $this->mLastSection
. ">\n";
2013 $this->mInPre
= false;
2014 $this->mLastSection
= '';
2019 * getCommon() returns the length of the longest common substring
2020 * of both arguments, starting at the beginning of both.
2023 function getCommon( $st1, $st2 ) {
2024 $fl = strlen( $st1 );
2025 $shorter = strlen( $st2 );
2026 if ( $fl < $shorter ) {
2030 for ( $i = 0; $i < $shorter; ++
$i ) {
2031 if ( $st1{$i} != $st2{$i} ) {
2039 * These next three functions open, continue, and close the list
2040 * element appropriate to the prefix character passed into them.
2043 function openList( $char ) {
2044 $result = $this->closeParagraph();
2046 if ( '*' === $char ) {
2047 $result .= '<ul><li>';
2048 } elseif ( '#' === $char ) {
2049 $result .= '<ol><li>';
2050 } elseif ( ':' === $char ) {
2051 $result .= '<dl><dd>';
2052 } elseif ( ';' === $char ) {
2053 $result .= '<dl><dt>';
2054 $this->mDTopen
= true;
2056 $result = '<!-- ERR 1 -->';
2064 * @param $char String
2067 function nextItem( $char ) {
2068 if ( '*' === $char ||
'#' === $char ) {
2070 } elseif ( ':' === $char ||
';' === $char ) {
2072 if ( $this->mDTopen
) {
2075 if ( ';' === $char ) {
2076 $this->mDTopen
= true;
2077 return $close . '<dt>';
2079 $this->mDTopen
= false;
2080 return $close . '<dd>';
2083 return '<!-- ERR 2 -->';
2088 * @param $char String
2091 function closeList( $char ) {
2092 if ( '*' === $char ) {
2093 $text = '</li></ul>';
2094 } elseif ( '#' === $char ) {
2095 $text = '</li></ol>';
2096 } elseif ( ':' === $char ) {
2097 if ( $this->mDTopen
) {
2098 $this->mDTopen
= false;
2099 $text = '</dt></dl>';
2101 $text = '</dd></dl>';
2104 return '<!-- ERR 3 -->';
2111 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2113 * @param $text String
2114 * @param $linestart Boolean: whether or not this is at the start of a line.
2116 * @return string the lists rendered as HTML
2118 function doBlockLevels( $text, $linestart ) {
2119 wfProfileIn( __METHOD__
);
2121 # Parsing through the text line by line. The main thing
2122 # happening here is handling of block-level elements p, pre,
2123 # and making lists from lines starting with * # : etc.
2125 $textLines = StringUtils
::explode( "\n", $text );
2127 $lastPrefix = $output = '';
2128 $this->mDTopen
= $inBlockElem = false;
2130 $paragraphStack = false;
2132 foreach ( $textLines as $oLine ) {
2134 if ( !$linestart ) {
2144 $lastPrefixLength = strlen( $lastPrefix );
2145 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2146 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2147 # If not in a <pre> element, scan for and figure out what prefixes are there.
2148 if ( !$this->mInPre
) {
2149 # Multiple prefixes may abut each other for nested lists.
2150 $prefixLength = strspn( $oLine, '*#:;' );
2151 $prefix = substr( $oLine, 0, $prefixLength );
2154 # ; and : are both from definition-lists, so they're equivalent
2155 # for the purposes of determining whether or not we need to open/close
2157 $prefix2 = str_replace( ';', ':', $prefix );
2158 $t = substr( $oLine, $prefixLength );
2159 $this->mInPre
= (bool)$preOpenMatch;
2161 # Don't interpret any other prefixes in preformatted text
2163 $prefix = $prefix2 = '';
2168 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2169 # Same as the last item, so no need to deal with nesting or opening stuff
2170 $output .= $this->nextItem( substr( $prefix, -1 ) );
2171 $paragraphStack = false;
2173 if ( substr( $prefix, -1 ) === ';') {
2174 # The one nasty exception: definition lists work like this:
2175 # ; title : definition text
2176 # So we check for : in the remainder text to split up the
2177 # title and definition, without b0rking links.
2179 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2181 $output .= $term . $this->nextItem( ':' );
2184 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2185 # We need to open or close prefixes, or both.
2187 # Either open or close a level...
2188 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2189 $paragraphStack = false;
2191 # Close all the prefixes which aren't shared.
2192 while ( $commonPrefixLength < $lastPrefixLength ) {
2193 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2194 --$lastPrefixLength;
2197 # Continue the current prefix if appropriate.
2198 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2199 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2202 # Open prefixes where appropriate.
2203 while ( $prefixLength > $commonPrefixLength ) {
2204 $char = substr( $prefix, $commonPrefixLength, 1 );
2205 $output .= $this->openList( $char );
2207 if ( ';' === $char ) {
2208 # FIXME: This is dupe of code above
2209 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2211 $output .= $term . $this->nextItem( ':' );
2214 ++
$commonPrefixLength;
2216 $lastPrefix = $prefix2;
2219 # If we have no prefixes, go to paragraph mode.
2220 if ( 0 == $prefixLength ) {
2221 wfProfileIn( __METHOD__
."-paragraph" );
2222 # No prefix (not in list)--go to paragraph mode
2223 # XXX: use a stack for nestable elements like span, table and div
2224 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2225 $closematch = preg_match(
2226 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2227 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2228 if ( $openmatch or $closematch ) {
2229 $paragraphStack = false;
2230 #Â TODO bug 5718: paragraph closed
2231 $output .= $this->closeParagraph();
2232 if ( $preOpenMatch and !$preCloseMatch ) {
2233 $this->mInPre
= true;
2235 $inBlockElem = !$closematch;
2236 } elseif ( !$inBlockElem && !$this->mInPre
) {
2237 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2239 if ( $this->mLastSection
!== 'pre' ) {
2240 $paragraphStack = false;
2241 $output .= $this->closeParagraph().'<pre>';
2242 $this->mLastSection
= 'pre';
2244 $t = substr( $t, 1 );
2247 if ( trim( $t ) === '' ) {
2248 if ( $paragraphStack ) {
2249 $output .= $paragraphStack.'<br />';
2250 $paragraphStack = false;
2251 $this->mLastSection
= 'p';
2253 if ( $this->mLastSection
!== 'p' ) {
2254 $output .= $this->closeParagraph();
2255 $this->mLastSection
= '';
2256 $paragraphStack = '<p>';
2258 $paragraphStack = '</p><p>';
2262 if ( $paragraphStack ) {
2263 $output .= $paragraphStack;
2264 $paragraphStack = false;
2265 $this->mLastSection
= 'p';
2266 } elseif ( $this->mLastSection
!== 'p' ) {
2267 $output .= $this->closeParagraph().'<p>';
2268 $this->mLastSection
= 'p';
2273 wfProfileOut( __METHOD__
."-paragraph" );
2275 # somewhere above we forget to get out of pre block (bug 785)
2276 if ( $preCloseMatch && $this->mInPre
) {
2277 $this->mInPre
= false;
2279 if ( $paragraphStack === false ) {
2283 while ( $prefixLength ) {
2284 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2287 if ( $this->mLastSection
!= '' ) {
2288 $output .= '</' . $this->mLastSection
. '>';
2289 $this->mLastSection
= '';
2292 wfProfileOut( __METHOD__
);
2297 * Split up a string on ':', ignoring any occurences inside tags
2298 * to prevent illegal overlapping.
2300 * @param $str String: the string to split
2301 * @param &$before String: set to everything before the ':'
2302 * @param &$after String: set to everything after the ':'
2303 * return String: the position of the ':', or false if none found
2305 function findColonNoLinks( $str, &$before, &$after ) {
2306 wfProfileIn( __METHOD__
);
2308 $pos = strpos( $str, ':' );
2309 if ( $pos === false ) {
2311 wfProfileOut( __METHOD__
);
2315 $lt = strpos( $str, '<' );
2316 if ( $lt === false ||
$lt > $pos ) {
2317 # Easy; no tag nesting to worry about
2318 $before = substr( $str, 0, $pos );
2319 $after = substr( $str, $pos+
1 );
2320 wfProfileOut( __METHOD__
);
2324 # Ugly state machine to walk through avoiding tags.
2325 $state = self
::COLON_STATE_TEXT
;
2327 $len = strlen( $str );
2328 for( $i = 0; $i < $len; $i++
) {
2332 # (Using the number is a performance hack for common cases)
2333 case 0: # self::COLON_STATE_TEXT:
2336 # Could be either a <start> tag or an </end> tag
2337 $state = self
::COLON_STATE_TAGSTART
;
2340 if ( $stack == 0 ) {
2342 $before = substr( $str, 0, $i );
2343 $after = substr( $str, $i +
1 );
2344 wfProfileOut( __METHOD__
);
2347 # Embedded in a tag; don't break it.
2350 # Skip ahead looking for something interesting
2351 $colon = strpos( $str, ':', $i );
2352 if ( $colon === false ) {
2353 # Nothing else interesting
2354 wfProfileOut( __METHOD__
);
2357 $lt = strpos( $str, '<', $i );
2358 if ( $stack === 0 ) {
2359 if ( $lt === false ||
$colon < $lt ) {
2361 $before = substr( $str, 0, $colon );
2362 $after = substr( $str, $colon +
1 );
2363 wfProfileOut( __METHOD__
);
2367 if ( $lt === false ) {
2368 # Nothing else interesting to find; abort!
2369 # We're nested, but there's no close tags left. Abort!
2372 # Skip ahead to next tag start
2374 $state = self
::COLON_STATE_TAGSTART
;
2377 case 1: # self::COLON_STATE_TAG:
2382 $state = self
::COLON_STATE_TEXT
;
2385 # Slash may be followed by >?
2386 $state = self
::COLON_STATE_TAGSLASH
;
2392 case 2: # self::COLON_STATE_TAGSTART:
2395 $state = self
::COLON_STATE_CLOSETAG
;
2398 $state = self
::COLON_STATE_COMMENT
;
2401 # Illegal early close? This shouldn't happen D:
2402 $state = self
::COLON_STATE_TEXT
;
2405 $state = self
::COLON_STATE_TAG
;
2408 case 3: # self::COLON_STATE_CLOSETAG:
2413 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2414 wfProfileOut( __METHOD__
);
2417 $state = self
::COLON_STATE_TEXT
;
2420 case self
::COLON_STATE_TAGSLASH
:
2422 # Yes, a self-closed tag <blah/>
2423 $state = self
::COLON_STATE_TEXT
;
2425 # Probably we're jumping the gun, and this is an attribute
2426 $state = self
::COLON_STATE_TAG
;
2429 case 5: # self::COLON_STATE_COMMENT:
2431 $state = self
::COLON_STATE_COMMENTDASH
;
2434 case self
::COLON_STATE_COMMENTDASH
:
2436 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2438 $state = self
::COLON_STATE_COMMENT
;
2441 case self
::COLON_STATE_COMMENTDASHDASH
:
2443 $state = self
::COLON_STATE_TEXT
;
2445 $state = self
::COLON_STATE_COMMENT
;
2449 throw new MWException( "State machine error in " . __METHOD__
);
2453 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2454 wfProfileOut( __METHOD__
);
2457 wfProfileOut( __METHOD__
);
2462 * Return value of a magic variable (like PAGENAME)
2466 function getVariableValue( $index, $frame=false ) {
2467 global $wgContLang, $wgSitename, $wgServer;
2468 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2471 * Some of these require message or data lookups and can be
2472 * expensive to check many times.
2474 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2475 if ( isset( $this->mVarCache
[$index] ) ) {
2476 return $this->mVarCache
[$index];
2480 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2481 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2484 global $wgLocaltimezone;
2485 if ( isset( $wgLocaltimezone ) ) {
2486 $oldtz = date_default_timezone_get();
2487 date_default_timezone_set( $wgLocaltimezone );
2490 $localTimestamp = date( 'YmdHis', $ts );
2491 $localMonth = date( 'm', $ts );
2492 $localMonth1 = date( 'n', $ts );
2493 $localMonthName = date( 'n', $ts );
2494 $localDay = date( 'j', $ts );
2495 $localDay2 = date( 'd', $ts );
2496 $localDayOfWeek = date( 'w', $ts );
2497 $localWeek = date( 'W', $ts );
2498 $localYear = date( 'Y', $ts );
2499 $localHour = date( 'H', $ts );
2500 if ( isset( $wgLocaltimezone ) ) {
2501 date_default_timezone_set( $oldtz );
2505 case 'currentmonth':
2506 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2508 case 'currentmonth1':
2509 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2511 case 'currentmonthname':
2512 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2514 case 'currentmonthnamegen':
2515 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2517 case 'currentmonthabbrev':
2518 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2521 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2524 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2527 $value = $wgContLang->formatNum( $localMonth );
2530 $value = $wgContLang->formatNum( $localMonth1 );
2532 case 'localmonthname':
2533 $value = $wgContLang->getMonthName( $localMonthName );
2535 case 'localmonthnamegen':
2536 $value = $wgContLang->getMonthNameGen( $localMonthName );
2538 case 'localmonthabbrev':
2539 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2542 $value = $wgContLang->formatNum( $localDay );
2545 $value = $wgContLang->formatNum( $localDay2 );
2548 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2551 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2553 case 'fullpagename':
2554 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2556 case 'fullpagenamee':
2557 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2560 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2562 case 'subpagenamee':
2563 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2565 case 'basepagename':
2566 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2568 case 'basepagenamee':
2569 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2571 case 'talkpagename':
2572 if ( $this->mTitle
->canTalk() ) {
2573 $talkPage = $this->mTitle
->getTalkPage();
2574 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2579 case 'talkpagenamee':
2580 if ( $this->mTitle
->canTalk() ) {
2581 $talkPage = $this->mTitle
->getTalkPage();
2582 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2587 case 'subjectpagename':
2588 $subjPage = $this->mTitle
->getSubjectPage();
2589 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2591 case 'subjectpagenamee':
2592 $subjPage = $this->mTitle
->getSubjectPage();
2593 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2596 # Let the edit saving system know we should parse the page
2597 # *after* a revision ID has been assigned.
2598 $this->mOutput
->setFlag( 'vary-revision' );
2599 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2600 $value = $this->mRevisionId
;
2603 # Let the edit saving system know we should parse the page
2604 # *after* a revision ID has been assigned. This is for null edits.
2605 $this->mOutput
->setFlag( 'vary-revision' );
2606 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2607 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2609 case 'revisionday2':
2610 # Let the edit saving system know we should parse the page
2611 # *after* a revision ID has been assigned. This is for null edits.
2612 $this->mOutput
->setFlag( 'vary-revision' );
2613 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2614 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2616 case 'revisionmonth':
2617 # Let the edit saving system know we should parse the page
2618 # *after* a revision ID has been assigned. This is for null edits.
2619 $this->mOutput
->setFlag( 'vary-revision' );
2620 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2621 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2623 case 'revisionmonth1':
2624 # Let the edit saving system know we should parse the page
2625 # *after* a revision ID has been assigned. This is for null edits.
2626 $this->mOutput
->setFlag( 'vary-revision' );
2627 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2628 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2630 case 'revisionyear':
2631 # Let the edit saving system know we should parse the page
2632 # *after* a revision ID has been assigned. This is for null edits.
2633 $this->mOutput
->setFlag( 'vary-revision' );
2634 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2635 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2637 case 'revisiontimestamp':
2638 # Let the edit saving system know we should parse the page
2639 # *after* a revision ID has been assigned. This is for null edits.
2640 $this->mOutput
->setFlag( 'vary-revision' );
2641 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2642 $value = $this->getRevisionTimestamp();
2644 case 'revisionuser':
2645 # Let the edit saving system know we should parse the page
2646 # *after* a revision ID has been assigned. This is for null edits.
2647 $this->mOutput
->setFlag( 'vary-revision' );
2648 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2649 $value = $this->getRevisionUser();
2652 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2655 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2658 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2661 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2663 case 'subjectspace':
2664 $value = $this->mTitle
->getSubjectNsText();
2666 case 'subjectspacee':
2667 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2669 case 'currentdayname':
2670 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2673 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2676 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2679 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2682 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2683 # int to remove the padding
2684 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2687 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2689 case 'localdayname':
2690 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2693 $value = $wgContLang->formatNum( $localYear, true );
2696 $value = $wgContLang->time( $localTimestamp, false, false );
2699 $value = $wgContLang->formatNum( $localHour, true );
2702 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2703 # int to remove the padding
2704 $value = $wgContLang->formatNum( (int)$localWeek );
2707 $value = $wgContLang->formatNum( $localDayOfWeek );
2709 case 'numberofarticles':
2710 $value = $wgContLang->formatNum( SiteStats
::articles() );
2712 case 'numberoffiles':
2713 $value = $wgContLang->formatNum( SiteStats
::images() );
2715 case 'numberofusers':
2716 $value = $wgContLang->formatNum( SiteStats
::users() );
2718 case 'numberofactiveusers':
2719 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2721 case 'numberofpages':
2722 $value = $wgContLang->formatNum( SiteStats
::pages() );
2724 case 'numberofadmins':
2725 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2727 case 'numberofedits':
2728 $value = $wgContLang->formatNum( SiteStats
::edits() );
2730 case 'numberofviews':
2731 $value = $wgContLang->formatNum( SiteStats
::views() );
2733 case 'currenttimestamp':
2734 $value = wfTimestamp( TS_MW
, $ts );
2736 case 'localtimestamp':
2737 $value = $localTimestamp;
2739 case 'currentversion':
2740 $value = SpecialVersion
::getVersion();
2743 return $wgArticlePath;
2749 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2750 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2751 wfRestoreWarnings();
2752 return $serverName ?
$serverName : $wgServer;
2754 return $wgScriptPath;
2756 return $wgStylePath;
2757 case 'directionmark':
2758 return $wgContLang->getDirMark();
2759 case 'contentlanguage':
2760 global $wgLanguageCode;
2761 return $wgLanguageCode;
2764 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2772 $this->mVarCache
[$index] = $value;
2778 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2782 function initialiseVariables() {
2783 wfProfileIn( __METHOD__
);
2784 $variableIDs = MagicWord
::getVariableIDs();
2785 $substIDs = MagicWord
::getSubstIDs();
2787 $this->mVariables
= new MagicWordArray( $variableIDs );
2788 $this->mSubstWords
= new MagicWordArray( $substIDs );
2789 wfProfileOut( __METHOD__
);
2793 * Preprocess some wikitext and return the document tree.
2794 * This is the ghost of replace_variables().
2796 * @param $text String: The text to parse
2797 * @param $flags Integer: bitwise combination of:
2798 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2799 * included. Default is to assume a direct page view.
2801 * The generated DOM tree must depend only on the input text and the flags.
2802 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2804 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2805 * change in the DOM tree for a given text, must be passed through the section identifier
2806 * in the section edit link and thus back to extractSections().
2808 * The output of this function is currently only cached in process memory, but a persistent
2809 * cache may be implemented at a later date which takes further advantage of these strict
2810 * dependency requirements.
2814 function preprocessToDom( $text, $flags = 0 ) {
2815 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2820 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2822 public static function splitWhitespace( $s ) {
2823 $ltrimmed = ltrim( $s );
2824 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2825 $trimmed = rtrim( $ltrimmed );
2826 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2828 $w2 = substr( $ltrimmed, -$diff );
2832 return array( $w1, $trimmed, $w2 );
2836 * Replace magic variables, templates, and template arguments
2837 * with the appropriate text. Templates are substituted recursively,
2838 * taking care to avoid infinite loops.
2840 * Note that the substitution depends on value of $mOutputType:
2841 * self::OT_WIKI: only {{subst:}} templates
2842 * self::OT_PREPROCESS: templates but not extension tags
2843 * self::OT_HTML: all templates and extension tags
2845 * @param $text String: the text to transform
2846 * @param $frame PPFrame Object describing the arguments passed to the template.
2847 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2848 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2849 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2852 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2853 # Is there any text? Also, Prevent too big inclusions!
2854 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2857 wfProfileIn( __METHOD__
);
2859 if ( $frame === false ) {
2860 $frame = $this->getPreprocessor()->newFrame();
2861 } elseif ( !( $frame instanceof PPFrame
) ) {
2862 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2863 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2866 $dom = $this->preprocessToDom( $text );
2867 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2868 $text = $frame->expand( $dom, $flags );
2870 wfProfileOut( __METHOD__
);
2874 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2875 static function createAssocArgs( $args ) {
2876 $assocArgs = array();
2878 foreach ( $args as $arg ) {
2879 $eqpos = strpos( $arg, '=' );
2880 if ( $eqpos === false ) {
2881 $assocArgs[$index++
] = $arg;
2883 $name = trim( substr( $arg, 0, $eqpos ) );
2884 $value = trim( substr( $arg, $eqpos+
1 ) );
2885 if ( $value === false ) {
2888 if ( $name !== false ) {
2889 $assocArgs[$name] = $value;
2898 * Warn the user when a parser limitation is reached
2899 * Will warn at most once the user per limitation type
2901 * @param $limitationType String: should be one of:
2902 * 'expensive-parserfunction' (corresponding messages:
2903 * 'expensive-parserfunction-warning',
2904 * 'expensive-parserfunction-category')
2905 * 'post-expand-template-argument' (corresponding messages:
2906 * 'post-expand-template-argument-warning',
2907 * 'post-expand-template-argument-category')
2908 * 'post-expand-template-inclusion' (corresponding messages:
2909 * 'post-expand-template-inclusion-warning',
2910 * 'post-expand-template-inclusion-category')
2911 * @param $current Current value
2912 * @param $max Maximum allowed, when an explicit limit has been
2913 * exceeded, provide the values (optional)
2915 function limitationWarn( $limitationType, $current=null, $max=null) {
2916 # does no harm if $current and $max are present but are unnecessary for the message
2917 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2918 $this->mOutput
->addWarning( $warning );
2919 $this->addTrackingCategory( "$limitationType-category" );
2923 * Return the text of a template, after recursively
2924 * replacing any variables or templates within the template.
2926 * @param $piece Array: the parts of the template
2927 * $piece['title']: the title, i.e. the part before the |
2928 * $piece['parts']: the parameter array
2929 * $piece['lineStart']: whether the brace was at the start of a line
2930 * @param $frame PPFrame The current frame, contains template arguments
2931 * @return String: the text of the template
2934 function braceSubstitution( $piece, $frame ) {
2935 global $wgContLang, $wgNonincludableNamespaces;
2936 wfProfileIn( __METHOD__
);
2937 wfProfileIn( __METHOD__
.'-setup' );
2940 $found = false; # $text has been filled
2941 $nowiki = false; # wiki markup in $text should be escaped
2942 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2943 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2944 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2945 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2947 # Title object, where $text came from
2950 # $part1 is the bit before the first |, and must contain only title characters.
2951 # Various prefixes will be stripped from it later.
2952 $titleWithSpaces = $frame->expand( $piece['title'] );
2953 $part1 = trim( $titleWithSpaces );
2956 # Original title text preserved for various purposes
2957 $originalTitle = $part1;
2959 # $args is a list of argument nodes, starting from index 0, not including $part1
2960 # *** FIXME if piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
2961 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2962 wfProfileOut( __METHOD__
.'-setup' );
2965 wfProfileIn( __METHOD__
.'-modifiers' );
2968 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2970 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2971 # Decide whether to expand template or keep wikitext as-is.
2972 if ( $this->ot
['wiki'] ) {
2973 if ( $substMatch === false ) {
2974 $literal = true; # literal when in PST with no prefix
2976 $literal = false; # expand when in PST with subst: or safesubst:
2979 if ( $substMatch == 'subst' ) {
2980 $literal = true; # literal when not in PST with plain subst:
2982 $literal = false; # expand when not in PST with safesubst: or no prefix
2986 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2993 if ( !$found && $args->getLength() == 0 ) {
2994 $id = $this->mVariables
->matchStartToEnd( $part1 );
2995 if ( $id !== false ) {
2996 $text = $this->getVariableValue( $id, $frame );
2997 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2998 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3004 # MSG, MSGNW and RAW
3007 $mwMsgnw = MagicWord
::get( 'msgnw' );
3008 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3011 # Remove obsolete MSG:
3012 $mwMsg = MagicWord
::get( 'msg' );
3013 $mwMsg->matchStartAndRemove( $part1 );
3017 $mwRaw = MagicWord
::get( 'raw' );
3018 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3019 $forceRawInterwiki = true;
3022 wfProfileOut( __METHOD__
.'-modifiers' );
3026 wfProfileIn( __METHOD__
. '-pfunc' );
3028 $colonPos = strpos( $part1, ':' );
3029 if ( $colonPos !== false ) {
3030 # Case sensitive functions
3031 $function = substr( $part1, 0, $colonPos );
3032 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3033 $function = $this->mFunctionSynonyms
[1][$function];
3035 # Case insensitive functions
3036 $function = $wgContLang->lc( $function );
3037 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3038 $function = $this->mFunctionSynonyms
[0][$function];
3044 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3045 $initialArgs = array( &$this );
3046 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3047 if ( $flags & SFH_OBJECT_ARGS
) {
3048 # Add a frame parameter, and pass the arguments as an array
3049 $allArgs = $initialArgs;
3050 $allArgs[] = $frame;
3051 for ( $i = 0; $i < $args->getLength(); $i++
) {
3052 $funcArgs[] = $args->item( $i );
3054 $allArgs[] = $funcArgs;
3056 # Convert arguments to plain text
3057 for ( $i = 0; $i < $args->getLength(); $i++
) {
3058 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3060 $allArgs = array_merge( $initialArgs, $funcArgs );
3063 # Workaround for PHP bug 35229 and similar
3064 if ( !is_callable( $callback ) ) {
3065 wfProfileOut( __METHOD__
. '-pfunc' );
3066 wfProfileOut( __METHOD__
);
3067 throw new MWException( "Tag hook for $function is not callable\n" );
3069 $result = call_user_func_array( $callback, $allArgs );
3072 $preprocessFlags = 0;
3074 if ( is_array( $result ) ) {
3075 if ( isset( $result[0] ) ) {
3077 unset( $result[0] );
3080 # Extract flags into the local scope
3081 # This allows callers to set flags such as nowiki, found, etc.
3087 $text = $this->preprocessToDom( $text, $preprocessFlags );
3092 wfProfileOut( __METHOD__
. '-pfunc' );
3095 # Finish mangling title and then check for loops.
3096 # Set $title to a Title object and $titleText to the PDBK
3099 # Split the title into page and subpage
3101 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3102 if ( $subpage !== '' ) {
3103 $ns = $this->mTitle
->getNamespace();
3105 $title = Title
::newFromText( $part1, $ns );
3107 $titleText = $title->getPrefixedText();
3108 # Check for language variants if the template is not found
3109 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3110 $wgContLang->findVariantLink( $part1, $title, true );
3112 # Do recursion depth check
3113 $limit = $this->mOptions
->getMaxTemplateDepth();
3114 if ( $frame->depth
>= $limit ) {
3116 $text = '<span class="error">'
3117 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3123 # Load from database
3124 if ( !$found && $title ) {
3125 wfProfileIn( __METHOD__
. '-loadtpl' );
3126 if ( !$title->isExternal() ) {
3127 if ( $title->getNamespace() == NS_SPECIAL
3128 && $this->mOptions
->getAllowSpecialInclusion()
3129 && $this->ot
['html'] )
3131 $text = SpecialPage
::capturePath( $title );
3132 if ( is_string( $text ) ) {
3135 $this->disableCache();
3137 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3138 $found = false; # access denied
3139 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3141 list( $text, $title ) = $this->getTemplateDom( $title );
3142 if ( $text !== false ) {
3148 # If the title is valid but undisplayable, make a link to it
3149 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3150 $text = "[[:$titleText]]";
3153 } elseif ( $title->isTrans() ) {
3154 # Interwiki transclusion
3155 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3156 $text = $this->interwikiTransclude( $title, 'render' );
3159 $text = $this->interwikiTransclude( $title, 'raw' );
3160 # Preprocess it like a template
3161 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3167 # Do infinite loop check
3168 # This has to be done after redirect resolution to avoid infinite loops via redirects
3169 if ( !$frame->loopCheck( $title ) ) {
3171 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3172 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3174 wfProfileOut( __METHOD__
. '-loadtpl' );
3177 # If we haven't found text to substitute by now, we're done
3178 # Recover the source wikitext and return it
3180 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3181 wfProfileOut( __METHOD__
);
3182 return array( 'object' => $text );
3185 # Expand DOM-style return values in a child frame
3186 if ( $isChildObj ) {
3187 # Clean up argument array
3188 $newFrame = $frame->newChild( $args, $title );
3191 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3192 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3193 # Expansion is eligible for the empty-frame cache
3194 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3195 $text = $this->mTplExpandCache
[$titleText];
3197 $text = $newFrame->expand( $text );
3198 $this->mTplExpandCache
[$titleText] = $text;
3201 # Uncached expansion
3202 $text = $newFrame->expand( $text );
3205 if ( $isLocalObj && $nowiki ) {
3206 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3207 $isLocalObj = false;
3210 # Replace raw HTML by a placeholder
3211 # Add a blank line preceding, to prevent it from mucking up
3212 # immediately preceding headings
3214 $text = "\n\n" . $this->insertStripItem( $text );
3215 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3216 # Escape nowiki-style return values
3217 $text = wfEscapeWikiText( $text );
3218 } elseif ( is_string( $text )
3219 && !$piece['lineStart']
3220 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3222 # Bug 529: if the template begins with a table or block-level
3223 # element, it should be treated as beginning a new line.
3224 # This behaviour is somewhat controversial.
3225 $text = "\n" . $text;
3228 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3229 # Error, oversize inclusion
3230 if ( $titleText !== false ) {
3231 # Make a working, properly escaped link if possible (bug 23588)
3232 $text = "[[:$titleText]]";
3234 # This will probably not be a working link, but at least it may
3235 # provide some hint of where the problem is
3236 preg_replace( '/^:/', '', $originalTitle );
3237 $text = "[[:$originalTitle]]";
3239 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3240 $this->limitationWarn( 'post-expand-template-inclusion' );
3243 if ( $isLocalObj ) {
3244 $ret = array( 'object' => $text );
3246 $ret = array( 'text' => $text );
3249 wfProfileOut( __METHOD__
);
3254 * Get the semi-parsed DOM representation of a template with a given title,
3255 * and its redirect destination title. Cached.
3257 function getTemplateDom( $title ) {
3258 $cacheTitle = $title;
3259 $titleText = $title->getPrefixedDBkey();
3261 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3262 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3263 $title = Title
::makeTitle( $ns, $dbk );
3264 $titleText = $title->getPrefixedDBkey();
3266 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3267 return array( $this->mTplDomCache
[$titleText], $title );
3270 # Cache miss, go to the database
3271 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3273 if ( $text === false ) {
3274 $this->mTplDomCache
[$titleText] = false;
3275 return array( false, $title );
3278 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3279 $this->mTplDomCache
[ $titleText ] = $dom;
3281 if ( !$title->equals( $cacheTitle ) ) {
3282 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3283 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3286 return array( $dom, $title );
3290 * Fetch the unparsed text of a template and register a reference to it.
3292 function fetchTemplateAndTitle( $title ) {
3293 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3294 $stuff = call_user_func( $templateCb, $title, $this );
3295 $text = $stuff['text'];
3296 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3297 if ( isset( $stuff['deps'] ) ) {
3298 foreach ( $stuff['deps'] as $dep ) {
3299 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3302 return array( $text, $finalTitle );
3305 function fetchTemplate( $title ) {
3306 $rv = $this->fetchTemplateAndTitle( $title );
3311 * Static function to get a template
3312 * Can be overridden via ParserOptions::setTemplateCallback().
3314 static function statelessFetchTemplate( $title, $parser=false ) {
3315 $text = $skip = false;
3316 $finalTitle = $title;
3319 # Loop to fetch the article, with up to 1 redirect
3320 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3321 # Give extensions a chance to select the revision instead
3322 $id = false; # Assume current
3323 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3329 'page_id' => $title->getArticleID(),
3333 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3334 $rev_id = $rev ?
$rev->getId() : 0;
3335 # If there is no current revision, there is no page
3336 if ( $id === false && !$rev ) {
3337 $linkCache = LinkCache
::singleton();
3338 $linkCache->addBadLinkObj( $title );
3343 'page_id' => $title->getArticleID(),
3344 'rev_id' => $rev_id );
3347 $text = $rev->getText();
3348 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3350 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3351 if ( !$message->exists() ) {
3355 $text = $message->plain();
3359 if ( $text === false ) {
3363 $finalTitle = $title;
3364 $title = Title
::newFromRedirect( $text );
3368 'finalTitle' => $finalTitle,
3373 * Transclude an interwiki link.
3375 function interwikiTransclude( $title, $action ) {
3376 global $wgEnableScaryTranscluding;
3378 if ( !$wgEnableScaryTranscluding ) {
3379 return wfMsgForContent('scarytranscludedisabled');
3382 $url = $title->getFullUrl( "action=$action" );
3384 if ( strlen( $url ) > 255 ) {
3385 return wfMsgForContent( 'scarytranscludetoolong' );
3387 return $this->fetchScaryTemplateMaybeFromCache( $url );
3390 function fetchScaryTemplateMaybeFromCache( $url ) {
3391 global $wgTranscludeCacheExpiry;
3392 $dbr = wfGetDB( DB_SLAVE
);
3393 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3394 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3395 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3397 return $obj->tc_contents
;
3400 $text = Http
::get( $url );
3402 return wfMsgForContent( 'scarytranscludefailed', $url );
3405 $dbw = wfGetDB( DB_MASTER
);
3406 $dbw->replace( 'transcache', array('tc_url'), array(
3408 'tc_time' => $dbw->timestamp( time() ),
3409 'tc_contents' => $text)
3416 * Triple brace replacement -- used for template arguments
3419 function argSubstitution( $piece, $frame ) {
3420 wfProfileIn( __METHOD__
);
3423 $parts = $piece['parts'];
3424 $nameWithSpaces = $frame->expand( $piece['title'] );
3425 $argName = trim( $nameWithSpaces );
3427 $text = $frame->getArgument( $argName );
3428 if ( $text === false && $parts->getLength() > 0
3432 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3435 # No match in frame, use the supplied default
3436 $object = $parts->item( 0 )->getChildren();
3438 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3439 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3440 $this->limitationWarn( 'post-expand-template-argument' );
3443 if ( $text === false && $object === false ) {
3445 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3447 if ( $error !== false ) {
3450 if ( $object !== false ) {
3451 $ret = array( 'object' => $object );
3453 $ret = array( 'text' => $text );
3456 wfProfileOut( __METHOD__
);
3461 * Return the text to be used for a given extension tag.
3462 * This is the ghost of strip().
3464 * @param $params Associative array of parameters:
3465 * name PPNode for the tag name
3466 * attr PPNode for unparsed text where tag attributes are thought to be
3467 * attributes Optional associative array of parsed attributes
3468 * inner Contents of extension element
3469 * noClose Original text did not have a close tag
3470 * @param $frame PPFrame
3472 function extensionSubstitution( $params, $frame ) {
3473 $name = $frame->expand( $params['name'] );
3474 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3475 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3476 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3478 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3479 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3480 if ( $isFunctionTag ) {
3481 $markerType = 'none';
3483 $markerType = 'general';
3485 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3486 $name = strtolower( $name );
3487 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3488 if ( isset( $params['attributes'] ) ) {
3489 $attributes = $attributes +
$params['attributes'];
3492 if ( isset( $this->mTagHooks
[$name] ) ) {
3493 # Workaround for PHP bug 35229 and similar
3494 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3495 throw new MWException( "Tag hook for $name is not callable\n" );
3497 $output = call_user_func_array( $this->mTagHooks
[$name],
3498 array( $content, $attributes, $this, $frame ) );
3499 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3500 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3501 if ( !is_callable( $callback ) ) {
3502 throw new MWException( "Tag hook for $name is not callable\n" );
3505 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3507 $output = '<span class="error">Invalid tag extension name: ' .
3508 htmlspecialchars( $name ) . '</span>';
3511 if ( is_array( $output ) ) {
3512 # Extract flags to local scope (to override $markerType)
3514 $output = $flags[0];
3519 if ( is_null( $attrText ) ) {
3522 if ( isset( $params['attributes'] ) ) {
3523 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3524 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3525 htmlspecialchars( $attrValue ) . '"';
3528 if ( $content === null ) {
3529 $output = "<$name$attrText/>";
3531 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3532 $output = "<$name$attrText>$content$close";
3536 if ( $markerType === 'none' ) {
3538 } elseif ( $markerType === 'nowiki' ) {
3539 $this->mStripState
->addNoWiki( $marker, $output );
3540 } elseif ( $markerType === 'general' ) {
3541 $this->mStripState
->addGeneral( $marker, $output );
3543 throw new MWException( __METHOD__
.': invalid marker type' );
3549 * Increment an include size counter
3551 * @param $type String: the type of expansion
3552 * @param $size Integer: the size of the text
3553 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3555 function incrementIncludeSize( $type, $size ) {
3556 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3559 $this->mIncludeSizes
[$type] +
= $size;
3565 * Increment the expensive function count
3567 * @return Boolean: false if the limit has been exceeded
3569 function incrementExpensiveFunctionCount() {
3570 global $wgExpensiveParserFunctionLimit;
3571 $this->mExpensiveFunctionCount++
;
3572 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3579 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3580 * Fills $this->mDoubleUnderscores, returns the modified text
3582 function doDoubleUnderscore( $text ) {
3583 wfProfileIn( __METHOD__
);
3585 # The position of __TOC__ needs to be recorded
3586 $mw = MagicWord
::get( 'toc' );
3587 if ( $mw->match( $text ) ) {
3588 $this->mShowToc
= true;
3589 $this->mForceTocPosition
= true;
3591 # Set a placeholder. At the end we'll fill it in with the TOC.
3592 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3594 # Only keep the first one.
3595 $text = $mw->replace( '', $text );
3598 # Now match and remove the rest of them
3599 $mwa = MagicWord
::getDoubleUnderscoreArray();
3600 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3602 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3603 $this->mOutput
->mNoGallery
= true;
3605 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3606 $this->mShowToc
= false;
3608 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3609 $this->addTrackingCategory( 'hidden-category-category' );
3611 # (bug 8068) Allow control over whether robots index a page.
3613 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3614 # is not desirable, the last one on the page should win.
3615 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3616 $this->mOutput
->setIndexPolicy( 'noindex' );
3617 $this->addTrackingCategory( 'noindex-category' );
3619 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3620 $this->mOutput
->setIndexPolicy( 'index' );
3621 $this->addTrackingCategory( 'index-category' );
3624 # Cache all double underscores in the database
3625 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3626 $this->mOutput
->setProperty( $key, '' );
3629 wfProfileOut( __METHOD__
);
3634 * Add a tracking category, getting the title from a system message,
3635 * or print a debug message if the title is invalid.
3637 * @param $msg String: message key
3638 * @return Boolean: whether the addition was successful
3640 protected function addTrackingCategory( $msg ) {
3641 $cat = wfMsgForContent( $msg );
3643 # Allow tracking categories to be disabled by setting them to "-"
3644 if ( $cat === '-' ) {
3648 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3649 if ( $containerCategory ) {
3650 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3653 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3659 * This function accomplishes several tasks:
3660 * 1) Auto-number headings if that option is enabled
3661 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3662 * 3) Add a Table of contents on the top for users who have enabled the option
3663 * 4) Auto-anchor headings
3665 * It loops through all headlines, collects the necessary data, then splits up the
3666 * string and re-inserts the newly formatted headlines.
3668 * @param $text String
3669 * @param $origText String: original, untouched wikitext
3670 * @param $isMain Boolean
3673 function formatHeadings( $text, $origText, $isMain=true ) {
3674 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3676 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3678 # Inhibit editsection links if requested in the page
3679 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3682 $showEditLink = $this->mOptions
->getEditSection();
3684 if ( $showEditLink ) {
3685 $this->mOutput
->setEditSectionTokens( true );
3688 # Get all headlines for numbering them and adding funky stuff like [edit]
3689 # links - this is for later, but we need the number of headlines right now
3691 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3693 # if there are fewer than 4 headlines in the article, do not show TOC
3694 # unless it's been explicitly enabled.
3695 $enoughToc = $this->mShowToc
&&
3696 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3698 # Allow user to stipulate that a page should have a "new section"
3699 # link added via __NEWSECTIONLINK__
3700 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3701 $this->mOutput
->setNewSection( true );
3704 # Allow user to remove the "new section"
3705 # link via __NONEWSECTIONLINK__
3706 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3707 $this->mOutput
->hideNewSection( true );
3710 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3711 # override above conditions and always show TOC above first header
3712 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3713 $this->mShowToc
= true;
3717 # We need this to perform operations on the HTML
3718 $sk = $this->mOptions
->getSkin( $this->mTitle
);
3724 # Ugh .. the TOC should have neat indentation levels which can be
3725 # passed to the skin functions. These are determined here
3729 $sublevelCount = array();
3730 $levelCount = array();
3735 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3736 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3737 $oldType = $this->mOutputType
;
3738 $this->setOutputType( self
::OT_WIKI
);
3739 $frame = $this->getPreprocessor()->newFrame();
3740 $root = $this->preprocessToDom( $origText );
3741 $node = $root->getFirstChild();
3746 foreach ( $matches[3] as $headline ) {
3747 $isTemplate = false;
3749 $sectionIndex = false;
3751 $markerMatches = array();
3752 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3753 $serial = $markerMatches[1];
3754 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3755 $isTemplate = ( $titleText != $baseTitleText );
3756 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3760 $prevlevel = $level;
3762 $level = $matches[1][$headlineCount];
3764 if ( $level > $prevlevel ) {
3765 # Increase TOC level
3767 $sublevelCount[$toclevel] = 0;
3768 if ( $toclevel<$wgMaxTocLevel ) {
3769 $prevtoclevel = $toclevel;
3770 $toc .= $sk->tocIndent();
3773 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3774 # Decrease TOC level, find level to jump to
3776 for ( $i = $toclevel; $i > 0; $i-- ) {
3777 if ( $levelCount[$i] == $level ) {
3778 # Found last matching level
3781 } elseif ( $levelCount[$i] < $level ) {
3782 # Found first matching level below current level
3790 if ( $toclevel<$wgMaxTocLevel ) {
3791 if ( $prevtoclevel < $wgMaxTocLevel ) {
3792 # Unindent only if the previous toc level was shown :p
3793 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3794 $prevtoclevel = $toclevel;
3796 $toc .= $sk->tocLineEnd();
3800 # No change in level, end TOC line
3801 if ( $toclevel<$wgMaxTocLevel ) {
3802 $toc .= $sk->tocLineEnd();
3806 $levelCount[$toclevel] = $level;
3808 # count number of headlines for each level
3809 @$sublevelCount[$toclevel]++
;
3811 for( $i = 1; $i <= $toclevel; $i++
) {
3812 if ( !empty( $sublevelCount[$i] ) ) {
3816 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3821 # The safe header is a version of the header text safe to use for links
3822 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3823 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3825 # Remove link placeholders by the link text.
3826 # <!--LINK number-->
3828 # link text with suffix
3829 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3831 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3832 $tocline = preg_replace(
3833 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3834 array( '', '<$1>' ),
3837 $tocline = trim( $tocline );
3839 # For the anchor, strip out HTML-y stuff period
3840 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3841 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3843 # Save headline for section edit hint before it's escaped
3844 $headlineHint = $safeHeadline;
3846 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3847 # For reverse compatibility, provide an id that's
3848 # HTML4-compatible, like we used to.
3850 # It may be worth noting, academically, that it's possible for
3851 # the legacy anchor to conflict with a non-legacy headline
3852 # anchor on the page. In this case likely the "correct" thing
3853 # would be to either drop the legacy anchors or make sure
3854 # they're numbered first. However, this would require people
3855 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3856 # manually, so let's not bother worrying about it.
3857 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3858 array( 'noninitial', 'legacy' ) );
3859 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3861 if ( $legacyHeadline == $safeHeadline ) {
3862 # No reason to have both (in fact, we can't)
3863 $legacyHeadline = false;
3866 $legacyHeadline = false;
3867 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3871 # HTML names must be case-insensitively unique (bug 10721).
3872 # This does not apply to Unicode characters per
3873 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3874 # FIXME: We may be changing them depending on the current locale.
3875 $arrayKey = strtolower( $safeHeadline );
3876 if ( $legacyHeadline === false ) {
3877 $legacyArrayKey = false;
3879 $legacyArrayKey = strtolower( $legacyHeadline );
3882 # count how many in assoc. array so we can track dupes in anchors
3883 if ( isset( $refers[$arrayKey] ) ) {
3884 $refers[$arrayKey]++
;
3886 $refers[$arrayKey] = 1;
3888 if ( isset( $refers[$legacyArrayKey] ) ) {
3889 $refers[$legacyArrayKey]++
;
3891 $refers[$legacyArrayKey] = 1;
3894 # Don't number the heading if it is the only one (looks silly)
3895 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3896 # the two are different if the line contains a link
3897 $headline = $numbering . ' ' . $headline;
3900 # Create the anchor for linking from the TOC to the section
3901 $anchor = $safeHeadline;
3902 $legacyAnchor = $legacyHeadline;
3903 if ( $refers[$arrayKey] > 1 ) {
3904 $anchor .= '_' . $refers[$arrayKey];
3906 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3907 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3909 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3910 $toc .= $sk->tocLine( $anchor, $tocline,
3911 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3914 # Add the section to the section tree
3915 # Find the DOM node for this header
3916 while ( $node && !$isTemplate ) {
3917 if ( $node->getName() === 'h' ) {
3918 $bits = $node->splitHeading();
3919 if ( $bits['i'] == $sectionIndex ) {
3923 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3924 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3925 $node = $node->getNextSibling();
3928 'toclevel' => $toclevel,
3931 'number' => $numbering,
3932 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3933 'fromtitle' => $titleText,
3934 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3935 'anchor' => $anchor,
3938 # give headline the correct <h#> tag
3939 if ( $showEditLink && $sectionIndex !== false ) {
3940 // Output edit section links as markers with styles that can be customized by skins
3941 if ( $isTemplate ) {
3942 # Put a T flag in the section identifier, to indicate to extractSections()
3943 # that sections inside <includeonly> should be counted.
3944 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
3946 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
3948 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
3949 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
3950 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
3951 // so we don't have to worry about a user trying to input one of these markers directly.
3952 // We use a page and section attribute to stop the language converter from converting these important bits
3953 // of data, but put the headline hint inside a content block because the language converter is supposed to
3954 // be able to convert that piece of data.
3955 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
3956 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
3957 if ( isset($editlinkArgs[2]) ) {
3958 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
3965 $head[$headlineCount] = $sk->makeHeadline( $level,
3966 $matches['attrib'][$headlineCount], $anchor, $headline,
3967 $editlink, $legacyAnchor );
3972 $this->setOutputType( $oldType );
3974 # Never ever show TOC if no headers
3975 if ( $numVisible < 1 ) {
3980 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3981 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3983 $toc = $sk->tocList( $toc );
3984 $this->mOutput
->setTOCHTML( $toc );
3988 $this->mOutput
->setSections( $tocraw );
3991 # split up and insert constructed headlines
3993 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3996 foreach ( $blocks as $block ) {
3997 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3998 # This is the [edit] link that appears for the top block of text when
3999 # section editing is enabled
4001 # Disabled because it broke block formatting
4002 # For example, a bullet point in the top line
4003 # $full .= $sk->editSectionLink(0);
4006 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4007 # Top anchor now in skin
4011 if ( !empty( $head[$i] ) ) {
4016 if ( $this->mForceTocPosition
) {
4017 return str_replace( '<!--MWTOC-->', $toc, $full );
4024 * Transform wiki markup when saving a page by doing \r\n -> \n
4025 * conversion, substitting signatures, {{subst:}} templates, etc.
4027 * @param $text String: the text to transform
4028 * @param $title Title: the Title object for the current article
4029 * @param $user User: the User object describing the current user
4030 * @param $options ParserOptions: parsing options
4031 * @param $clearState Boolean: whether to clear the parser state first
4032 * @return String: the altered wiki markup
4034 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4035 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4036 $this->setUser( $user );
4041 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4042 if( $options->getPreSaveTransform() ) {
4043 $text = $this->pstPass2( $text, $user );
4045 $text = $this->mStripState
->unstripBoth( $text );
4047 $this->setUser( null ); #Reset
4053 * Pre-save transform helper function
4056 function pstPass2( $text, $user ) {
4057 global $wgContLang, $wgLocaltimezone;
4059 # Note: This is the timestamp saved as hardcoded wikitext to
4060 # the database, we use $wgContLang here in order to give
4061 # everyone the same signature and use the default one rather
4062 # than the one selected in each user's preferences.
4063 # (see also bug 12815)
4064 $ts = $this->mOptions
->getTimestamp();
4065 if ( isset( $wgLocaltimezone ) ) {
4066 $tz = $wgLocaltimezone;
4068 $tz = date_default_timezone_get();
4071 $unixts = wfTimestamp( TS_UNIX
, $ts );
4072 $oldtz = date_default_timezone_get();
4073 date_default_timezone_set( $tz );
4074 $ts = date( 'YmdHis', $unixts );
4075 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4077 # Allow translation of timezones through wiki. date() can return
4078 # whatever crap the system uses, localised or not, so we cannot
4079 # ship premade translations.
4080 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4081 $msg = wfMessage( $key )->inContentLanguage();
4082 if ( $msg->exists() ) {
4083 $tzMsg = $msg->text();
4086 date_default_timezone_set( $oldtz );
4088 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4090 # Variable replacement
4091 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4092 $text = $this->replaceVariables( $text );
4094 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4095 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4098 $sigText = $this->getUserSig( $user );
4099 $text = strtr( $text, array(
4101 '~~~~' => "$sigText $d",
4105 # Context links: [[|name]] and [[name (context)|]]
4106 global $wgLegalTitleChars;
4107 $tc = "[$wgLegalTitleChars]";
4108 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4110 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4111 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4112 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4113 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4115 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4116 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4117 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4118 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4120 $t = $this->mTitle
->getText();
4122 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4123 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4124 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4125 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4127 # if there's no context, don't bother duplicating the title
4128 $text = preg_replace( $p2, '[[\\1]]', $text );
4131 # Trim trailing whitespace
4132 $text = rtrim( $text );
4138 * Fetch the user's signature text, if any, and normalize to
4139 * validated, ready-to-insert wikitext.
4140 * If you have pre-fetched the nickname or the fancySig option, you can
4141 * specify them here to save a database query.
4142 * Do not reuse this parser instance after calling getUserSig(),
4143 * as it may have changed if it's the $wgParser.
4146 * @param $nickname String: nickname to use or false to use user's default nickname
4147 * @param $fancySig Boolean: whether the nicknname is the complete signature
4148 * or null to use default value
4151 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4152 global $wgMaxSigChars;
4154 $username = $user->getName();
4156 # If not given, retrieve from the user object.
4157 if ( $nickname === false )
4158 $nickname = $user->getOption( 'nickname' );
4160 if ( is_null( $fancySig ) ) {
4161 $fancySig = $user->getBoolOption( 'fancysig' );
4164 $nickname = $nickname == null ?
$username : $nickname;
4166 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4167 $nickname = $username;
4168 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4169 } elseif ( $fancySig !== false ) {
4170 # Sig. might contain markup; validate this
4171 if ( $this->validateSig( $nickname ) !== false ) {
4172 # Validated; clean up (if needed) and return it
4173 return $this->cleanSig( $nickname, true );
4175 # Failed to validate; fall back to the default
4176 $nickname = $username;
4177 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4181 # Make sure nickname doesnt get a sig in a sig
4182 $nickname = $this->cleanSigInSig( $nickname );
4184 # If we're still here, make it a link to the user page
4185 $userText = wfEscapeWikiText( $username );
4186 $nickText = wfEscapeWikiText( $nickname );
4187 if ( $user->isAnon() ) {
4188 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4190 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4195 * Check that the user's signature contains no bad XML
4197 * @param $text String
4198 * @return mixed An expanded string, or false if invalid.
4200 function validateSig( $text ) {
4201 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4205 * Clean up signature text
4207 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4208 * 2) Substitute all transclusions
4210 * @param $text String
4211 * @param $parsing Whether we're cleaning (preferences save) or parsing
4212 * @return String: signature text
4214 function cleanSig( $text, $parsing = false ) {
4217 $this->mOptions
= new ParserOptions
;
4218 $this->clearState();
4219 $this->setTitle( $wgTitle );
4220 $this->setOutputType
= self
::OT_PREPROCESS
;
4223 # Option to disable this feature
4224 if ( !$this->mOptions
->getCleanSignatures() ) {
4228 # FIXME: regex doesn't respect extension tags or nowiki
4229 # => Move this logic to braceSubstitution()
4230 $substWord = MagicWord
::get( 'subst' );
4231 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4232 $substText = '{{' . $substWord->getSynonym( 0 );
4234 $text = preg_replace( $substRegex, $substText, $text );
4235 $text = $this->cleanSigInSig( $text );
4236 $dom = $this->preprocessToDom( $text );
4237 $frame = $this->getPreprocessor()->newFrame();
4238 $text = $frame->expand( $dom );
4241 $text = $this->mStripState
->unstripBoth( $text );
4248 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4250 * @param $text String
4251 * @return String: signature text with /~{3,5}/ removed
4253 function cleanSigInSig( $text ) {
4254 $text = preg_replace( '/~{3,5}/', '', $text );
4259 * Set up some variables which are usually set up in parse()
4260 * so that an external function can call some class members with confidence
4262 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4263 $this->startParse( $title, $options, $outputType, $clearState );
4266 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4267 $this->setTitle( $title );
4268 $this->mOptions
= $options;
4269 $this->setOutputType( $outputType );
4270 if ( $clearState ) {
4271 $this->clearState();
4276 * Wrapper for preprocess()
4278 * @param $text String: the text to preprocess
4279 * @param $options ParserOptions: options
4280 * @param $title Title object or null to use $wgTitle
4283 public function transformMsg( $text, $options, $title = null ) {
4284 static $executing = false;
4286 # Guard against infinite recursion
4292 wfProfileIn( __METHOD__
);
4298 # It's not uncommon having a null $wgTitle in scripts. See r80898
4299 # Create a ghost title in such case
4300 $title = Title
::newFromText( 'Dwimmerlaik' );
4302 $text = $this->preprocess( $text, $title, $options );
4305 wfProfileOut( __METHOD__
);
4310 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4311 * The callback should have the following form:
4312 * function myParserHook( $text, $params, $parser ) { ... }
4314 * Transform and return $text. Use $parser for any required context, e.g. use
4315 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4317 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4318 * @param $callback Mixed: the callback function (and object) to use for the tag
4319 * @return The old value of the mTagHooks array associated with the hook
4321 public function setHook( $tag, $callback ) {
4322 $tag = strtolower( $tag );
4323 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4324 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4325 $this->mTagHooks
[$tag] = $callback;
4326 if ( !in_array( $tag, $this->mStripList
) ) {
4327 $this->mStripList
[] = $tag;
4333 function setTransparentTagHook( $tag, $callback ) {
4334 $tag = strtolower( $tag );
4335 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4336 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4337 $this->mTransparentTagHooks
[$tag] = $callback;
4343 * Remove all tag hooks
4345 function clearTagHooks() {
4346 $this->mTagHooks
= array();
4347 $this->mStripList
= $this->mDefaultStripList
;
4351 * Create a function, e.g. {{sum:1|2|3}}
4352 * The callback function should have the form:
4353 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4355 * Or with SFH_OBJECT_ARGS:
4356 * function myParserFunction( $parser, $frame, $args ) { ... }
4358 * The callback may either return the text result of the function, or an array with the text
4359 * in element 0, and a number of flags in the other elements. The names of the flags are
4360 * specified in the keys. Valid flags are:
4361 * found The text returned is valid, stop processing the template. This
4363 * nowiki Wiki markup in the return value should be escaped
4364 * isHTML The returned text is HTML, armour it against wikitext transformation
4366 * @param $id String: The magic word ID
4367 * @param $callback Mixed: the callback function (and object) to use
4368 * @param $flags Integer: a combination of the following flags:
4369 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4371 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4372 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4373 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4374 * the arguments, and to control the way they are expanded.
4376 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4377 * arguments, for instance:
4378 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4380 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4381 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4382 * working if/when this is changed.
4384 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4387 * Please read the documentation in includes/parser/Preprocessor.php for more information
4388 * about the methods available in PPFrame and PPNode.
4390 * @return The old callback function for this name, if any
4392 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4395 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4396 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4398 # Add to function cache
4399 $mw = MagicWord
::get( $id );
4401 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4403 $synonyms = $mw->getSynonyms();
4404 $sensitive = intval( $mw->isCaseSensitive() );
4406 foreach ( $synonyms as $syn ) {
4408 if ( !$sensitive ) {
4409 $syn = $wgContLang->lc( $syn );
4412 if ( !( $flags & SFH_NO_HASH
) ) {
4415 # Remove trailing colon
4416 if ( substr( $syn, -1, 1 ) === ':' ) {
4417 $syn = substr( $syn, 0, -1 );
4419 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4425 * Get all registered function hook identifiers
4429 function getFunctionHooks() {
4430 return array_keys( $this->mFunctionHooks
);
4434 * Create a tag function, e.g. <test>some stuff</test>.
4435 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4436 * Unlike parser functions, their content is not preprocessed.
4438 function setFunctionTagHook( $tag, $callback, $flags ) {
4439 $tag = strtolower( $tag );
4440 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4441 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4442 $this->mFunctionTagHooks
[$tag] : null;
4443 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4445 if ( !in_array( $tag, $this->mStripList
) ) {
4446 $this->mStripList
[] = $tag;
4453 * FIXME: update documentation. makeLinkObj() is deprecated.
4454 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4455 * Placeholders created in Skin::makeLinkObj()
4456 * Returns an array of link CSS classes, indexed by PDBK.
4458 function replaceLinkHolders( &$text, $options = 0 ) {
4459 return $this->mLinkHolders
->replace( $text );
4463 * Replace <!--LINK--> link placeholders with plain text of links
4464 * (not HTML-formatted).
4466 * @param $text String
4469 function replaceLinkHoldersText( $text ) {
4470 return $this->mLinkHolders
->replaceText( $text );
4474 * Renders an image gallery from a text with one line per image.
4475 * text labels may be given by using |-style alternative text. E.g.
4476 * Image:one.jpg|The number "1"
4477 * Image:tree.jpg|A tree
4478 * given as text will return the HTML of a gallery with two images,
4479 * labeled 'The number "1"' and
4482 function renderImageGallery( $text, $params ) {
4483 $ig = new ImageGallery();
4484 $ig->setContextTitle( $this->mTitle
);
4485 $ig->setShowBytes( false );
4486 $ig->setShowFilename( false );
4487 $ig->setParser( $this );
4488 $ig->setHideBadImages();
4489 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4490 $ig->useSkin( $this->mOptions
->getSkin( $this->mTitle
) );
4491 $ig->mRevisionId
= $this->mRevisionId
;
4493 if ( isset( $params['showfilename'] ) ) {
4494 $ig->setShowFilename( true );
4496 $ig->setShowFilename( false );
4498 if ( isset( $params['caption'] ) ) {
4499 $caption = $params['caption'];
4500 $caption = htmlspecialchars( $caption );
4501 $caption = $this->replaceInternalLinks( $caption );
4502 $ig->setCaptionHtml( $caption );
4504 if ( isset( $params['perrow'] ) ) {
4505 $ig->setPerRow( $params['perrow'] );
4507 if ( isset( $params['widths'] ) ) {
4508 $ig->setWidths( $params['widths'] );
4510 if ( isset( $params['heights'] ) ) {
4511 $ig->setHeights( $params['heights'] );
4514 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4516 $lines = StringUtils
::explode( "\n", $text );
4517 foreach ( $lines as $line ) {
4518 # match lines like these:
4519 # Image:someimage.jpg|This is some image
4521 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4523 if ( count( $matches ) == 0 ) {
4527 if ( strpos( $matches[0], '%' ) !== false ) {
4528 $matches[1] = rawurldecode( $matches[1] );
4530 $tp = Title
::newFromText( $matches[1], NS_FILE
);
4532 if ( is_null( $nt ) ) {
4533 # Bogus title. Ignore these so we don't bomb out later.
4536 if ( isset( $matches[3] ) ) {
4537 $label = $matches[3];
4542 $html = $this->recursiveTagParse( trim( $label ) );
4544 $ig->add( $nt, $html );
4546 # Only add real images (bug #5586)
4547 if ( $nt->getNamespace() == NS_FILE
) {
4548 $this->mOutput
->addImage( $nt->getDBkey() );
4551 return $ig->toHTML();
4554 function getImageParams( $handler ) {
4556 $handlerClass = get_class( $handler );
4560 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4561 # Initialise static lists
4562 static $internalParamNames = array(
4563 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4564 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4565 'bottom', 'text-bottom' ),
4566 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4567 'upright', 'border', 'link', 'alt' ),
4569 static $internalParamMap;
4570 if ( !$internalParamMap ) {
4571 $internalParamMap = array();
4572 foreach ( $internalParamNames as $type => $names ) {
4573 foreach ( $names as $name ) {
4574 $magicName = str_replace( '-', '_', "img_$name" );
4575 $internalParamMap[$magicName] = array( $type, $name );
4580 # Add handler params
4581 $paramMap = $internalParamMap;
4583 $handlerParamMap = $handler->getParamMap();
4584 foreach ( $handlerParamMap as $magic => $paramName ) {
4585 $paramMap[$magic] = array( 'handler', $paramName );
4588 $this->mImageParams
[$handlerClass] = $paramMap;
4589 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4591 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4595 * Parse image options text and use it to make an image
4597 * @param $title Title
4598 * @param $options String
4599 * @param $holders LinkHolderArray
4601 function makeImage( $title, $options, $holders = false ) {
4602 # Check if the options text is of the form "options|alt text"
4604 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4605 # * left no resizing, just left align. label is used for alt= only
4606 # * right same, but right aligned
4607 # * none same, but not aligned
4608 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4609 # * center center the image
4610 # * frame Keep original image size, no magnify-button.
4611 # * framed Same as "frame"
4612 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4613 # * upright reduce width for upright images, rounded to full __0 px
4614 # * border draw a 1px border around the image
4615 # * alt Text for HTML alt attribute (defaults to empty)
4616 # * link Set the target of the image link. Can be external, interwiki, or local
4617 # vertical-align values (no % or length right now):
4627 $parts = StringUtils
::explode( "|", $options );
4628 $sk = $this->mOptions
->getSkin( $this->mTitle
);
4630 # Give extensions a chance to select the file revision for us
4631 $skip = $time = $descQuery = false;
4632 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4635 return $sk->link( $title );
4639 $file = wfFindFile( $title, array( 'time' => $time ) );
4641 $handler = $file ?
$file->getHandler() : false;
4643 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4645 # Process the input parameters
4647 $params = array( 'frame' => array(), 'handler' => array(),
4648 'horizAlign' => array(), 'vertAlign' => array() );
4649 foreach ( $parts as $part ) {
4650 $part = trim( $part );
4651 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4653 if ( isset( $paramMap[$magicName] ) ) {
4654 list( $type, $paramName ) = $paramMap[$magicName];
4656 # Special case; width and height come in one variable together
4657 if ( $type === 'handler' && $paramName === 'width' ) {
4659 # (bug 13500) In both cases (width/height and width only),
4660 # permit trailing "px" for backward compatibility.
4661 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4662 $width = intval( $m[1] );
4663 $height = intval( $m[2] );
4664 if ( $handler->validateParam( 'width', $width ) ) {
4665 $params[$type]['width'] = $width;
4668 if ( $handler->validateParam( 'height', $height ) ) {
4669 $params[$type]['height'] = $height;
4672 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4673 $width = intval( $value );
4674 if ( $handler->validateParam( 'width', $width ) ) {
4675 $params[$type]['width'] = $width;
4678 } # else no validation -- bug 13436
4680 if ( $type === 'handler' ) {
4681 # Validate handler parameter
4682 $validated = $handler->validateParam( $paramName, $value );
4684 # Validate internal parameters
4685 switch( $paramName ) {
4688 # @todo Fixme: possibly check validity here for
4689 # manualthumb? downstream behavior seems odd with
4690 # missing manual thumbs.
4692 $value = $this->stripAltText( $value, $holders );
4695 $chars = self
::EXT_LINK_URL_CLASS
;
4696 $prots = $this->mUrlProtocols
;
4697 if ( $value === '' ) {
4698 $paramName = 'no-link';
4701 } elseif ( preg_match( "/^$prots/", $value ) ) {
4702 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4703 $paramName = 'link-url';
4704 $this->mOutput
->addExternalLink( $value );
4705 if ( $this->mOptions
->getExternalLinkTarget() ) {
4706 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4711 $linkTitle = Title
::newFromText( $value );
4713 $paramName = 'link-title';
4714 $value = $linkTitle;
4715 $this->mOutput
->addLink( $linkTitle );
4721 # Most other things appear to be empty or numeric...
4722 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4727 $params[$type][$paramName] = $value;
4731 if ( !$validated ) {
4736 # Process alignment parameters
4737 if ( $params['horizAlign'] ) {
4738 $params['frame']['align'] = key( $params['horizAlign'] );
4740 if ( $params['vertAlign'] ) {
4741 $params['frame']['valign'] = key( $params['vertAlign'] );
4744 $params['frame']['caption'] = $caption;
4746 # Will the image be presented in a frame, with the caption below?
4747 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4748 isset( $params['frame']['framed'] ) ||
4749 isset( $params['frame']['thumbnail'] ) ||
4750 isset( $params['frame']['manualthumb'] );
4752 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4753 # came to also set the caption, ordinary text after the image -- which
4754 # makes no sense, because that just repeats the text multiple times in
4755 # screen readers. It *also* came to set the title attribute.
4757 # Now that we have an alt attribute, we should not set the alt text to
4758 # equal the caption: that's worse than useless, it just repeats the
4759 # text. This is the framed/thumbnail case. If there's no caption, we
4760 # use the unnamed parameter for alt text as well, just for the time be-
4761 # ing, if the unnamed param is set and the alt param is not.
4763 # For the future, we need to figure out if we want to tweak this more,
4764 # e.g., introducing a title= parameter for the title; ignoring the un-
4765 # named parameter entirely for images without a caption; adding an ex-
4766 # plicit caption= parameter and preserving the old magic unnamed para-
4768 if ( $imageIsFramed ) { # Framed image
4769 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4770 # No caption or alt text, add the filename as the alt text so
4771 # that screen readers at least get some description of the image
4772 $params['frame']['alt'] = $title->getText();
4774 # Do not set $params['frame']['title'] because tooltips don't make sense
4776 } else { # Inline image
4777 if ( !isset( $params['frame']['alt'] ) ) {
4778 # No alt text, use the "caption" for the alt text
4779 if ( $caption !== '') {
4780 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4782 # No caption, fall back to using the filename for the
4784 $params['frame']['alt'] = $title->getText();
4787 # Use the "caption" for the tooltip text
4788 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4791 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4793 # Linker does the rest
4794 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions
->getThumbSize() );
4796 # Give the handler a chance to modify the parser object
4798 $handler->parserTransformHook( $this, $file );
4804 protected function stripAltText( $caption, $holders ) {
4805 # Strip bad stuff out of the title (tooltip). We can't just use
4806 # replaceLinkHoldersText() here, because if this function is called
4807 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4809 $tooltip = $holders->replaceText( $caption );
4811 $tooltip = $this->replaceLinkHoldersText( $caption );
4814 # make sure there are no placeholders in thumbnail attributes
4815 # that are later expanded to html- so expand them now and
4817 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4818 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4824 * Set a flag in the output object indicating that the content is dynamic and
4825 * shouldn't be cached.
4827 function disableCache() {
4828 wfDebug( "Parser output marked as uncacheable.\n" );
4829 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4830 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4834 * Callback from the Sanitizer for expanding items found in HTML attribute
4835 * values, so they can be safely tested and escaped.
4837 * @param $text String
4838 * @param $frame PPFrame
4842 function attributeStripCallback( &$text, $frame = false ) {
4843 $text = $this->replaceVariables( $text, $frame );
4844 $text = $this->mStripState
->unstripBoth( $text );
4851 function getTags() {
4852 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4856 * Replace transparent tags in $text with the values given by the callbacks.
4858 * Transparent tag hooks are like regular XML-style tag hooks, except they
4859 * operate late in the transformation sequence, on HTML instead of wikitext.
4861 function replaceTransparentTags( $text ) {
4863 $elements = array_keys( $this->mTransparentTagHooks
);
4864 $text = $this->extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
4866 foreach ( $matches as $marker => $data ) {
4867 list( $element, $content, $params, $tag ) = $data;
4868 $tagName = strtolower( $element );
4869 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
4870 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
4874 $this->mStripState
->addGeneral( $marker, $output );
4880 * Break wikitext input into sections, and either pull or replace
4881 * some particular section's text.
4883 * External callers should use the getSection and replaceSection methods.
4885 * @param $text String: Page wikitext
4886 * @param $section String: a section identifier string of the form:
4887 * <flag1> - <flag2> - ... - <section number>
4889 * Currently the only recognised flag is "T", which means the target section number
4890 * was derived during a template inclusion parse, in other words this is a template
4891 * section edit link. If no flags are given, it was an ordinary section edit link.
4892 * This flag is required to avoid a section numbering mismatch when a section is
4893 * enclosed by <includeonly> (bug 6563).
4895 * The section number 0 pulls the text before the first heading; other numbers will
4896 * pull the given section along with its lower-level subsections. If the section is
4897 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4899 * @param $mode String: one of "get" or "replace"
4900 * @param $newText String: replacement text for section data.
4901 * @return String: for "get", the extracted section text.
4902 * for "replace", the whole page with the section replaced.
4904 private function extractSections( $text, $section, $mode, $newText='' ) {
4905 global $wgTitle; # not generally used but removes an ugly failure mode
4906 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
4908 $frame = $this->getPreprocessor()->newFrame();
4910 # Process section extraction flags
4912 $sectionParts = explode( '-', $section );
4913 $sectionIndex = array_pop( $sectionParts );
4914 foreach ( $sectionParts as $part ) {
4915 if ( $part === 'T' ) {
4916 $flags |
= self
::PTD_FOR_INCLUSION
;
4919 # Preprocess the text
4920 $root = $this->preprocessToDom( $text, $flags );
4922 # <h> nodes indicate section breaks
4923 # They can only occur at the top level, so we can find them by iterating the root's children
4924 $node = $root->getFirstChild();
4926 # Find the target section
4927 if ( $sectionIndex == 0 ) {
4928 # Section zero doesn't nest, level=big
4929 $targetLevel = 1000;
4932 if ( $node->getName() === 'h' ) {
4933 $bits = $node->splitHeading();
4934 if ( $bits['i'] == $sectionIndex ) {
4935 $targetLevel = $bits['level'];
4939 if ( $mode === 'replace' ) {
4940 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4942 $node = $node->getNextSibling();
4948 if ( $mode === 'get' ) {
4955 # Find the end of the section, including nested sections
4957 if ( $node->getName() === 'h' ) {
4958 $bits = $node->splitHeading();
4959 $curLevel = $bits['level'];
4960 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4964 if ( $mode === 'get' ) {
4965 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4967 $node = $node->getNextSibling();
4970 # Write out the remainder (in replace mode only)
4971 if ( $mode === 'replace' ) {
4972 # Output the replacement text
4973 # Add two newlines on -- trailing whitespace in $newText is conventionally
4974 # stripped by the editor, so we need both newlines to restore the paragraph gap
4975 # Only add trailing whitespace if there is newText
4976 if ( $newText != "" ) {
4977 $outText .= $newText . "\n\n";
4981 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4982 $node = $node->getNextSibling();
4986 if ( is_string( $outText ) ) {
4987 # Re-insert stripped tags
4988 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4995 * This function returns the text of a section, specified by a number ($section).
4996 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4997 * the first section before any such heading (section 0).
4999 * If a section contains subsections, these are also returned.
5001 * @param $text String: text to look in
5002 * @param $section String: section identifier
5003 * @param $deftext String: default to return if section is not found
5004 * @return string text of the requested section
5006 public function getSection( $text, $section, $deftext='' ) {
5007 return $this->extractSections( $text, $section, "get", $deftext );
5011 * This function returns $oldtext after the content of the section
5012 * specified by $section has been replaced with $text.
5014 * @param $text String: former text of the article
5015 * @param $section Numeric: section identifier
5016 * @param $text String: replacing text
5017 * #return String: modified text
5019 public function replaceSection( $oldtext, $section, $text ) {
5020 return $this->extractSections( $oldtext, $section, "replace", $text );
5024 * Get the ID of the revision we are parsing
5026 * @return Mixed: integer or null
5028 function getRevisionId() {
5029 return $this->mRevisionId
;
5033 * Get the revision object for $this->mRevisionId
5035 * @return either a Revision object or null
5037 protected function getRevisionObject() {
5038 if ( !is_null( $this->mRevisionObject
) ) {
5039 return $this->mRevisionObject
;
5041 if ( is_null( $this->mRevisionId
) ) {
5045 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5046 return $this->mRevisionObject
;
5050 * Get the timestamp associated with the current revision, adjusted for
5051 * the default server-local timestamp
5053 function getRevisionTimestamp() {
5054 if ( is_null( $this->mRevisionTimestamp
) ) {
5055 wfProfileIn( __METHOD__
);
5057 $revObject = $this->getRevisionObject();
5058 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5060 if( $timestamp !== false ) {
5063 # The cryptic '' timezone parameter tells to use the site-default
5064 # timezone offset instead of the user settings.
5066 # Since this value will be saved into the parser cache, served
5067 # to other users, and potentially even used inside links and such,
5068 # it needs to be consistent for all visitors.
5069 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5072 wfProfileOut( __METHOD__
);
5074 return $this->mRevisionTimestamp
;
5078 * Get the name of the user that edited the last revision
5080 * @return String: user name
5082 function getRevisionUser() {
5083 if( is_null( $this->mRevisionUser
) ) {
5084 $revObject = $this->getRevisionObject();
5086 # if this template is subst: the revision id will be blank,
5087 # so just use the current user's name
5089 $this->mRevisionUser
= $revObject->getUserText();
5090 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5091 $this->mRevisionUser
= $this->getUser()->getName();
5094 return $this->mRevisionUser
;
5098 * Mutator for $mDefaultSort
5100 * @param $sort New value
5102 public function setDefaultSort( $sort ) {
5103 $this->mDefaultSort
= $sort;
5104 $this->mOutput
->setProperty( 'defaultsort', $sort );
5108 * Accessor for $mDefaultSort
5109 * Will use the empty string if none is set.
5111 * This value is treated as a prefix, so the
5112 * empty string is equivalent to sorting by
5117 public function getDefaultSort() {
5118 if ( $this->mDefaultSort
!== false ) {
5119 return $this->mDefaultSort
;
5126 * Accessor for $mDefaultSort
5127 * Unlike getDefaultSort(), will return false if none is set
5129 * @return string or false
5131 public function getCustomDefaultSort() {
5132 return $this->mDefaultSort
;
5136 * Try to guess the section anchor name based on a wikitext fragment
5137 * presumably extracted from a heading, for example "Header" from
5140 public function guessSectionNameFromWikiText( $text ) {
5141 # Strip out wikitext links(they break the anchor)
5142 $text = $this->stripSectionName( $text );
5143 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5144 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5148 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5149 * instead. For use in redirects, since IE6 interprets Redirect: headers
5150 * as something other than UTF-8 (apparently?), resulting in breakage.
5152 * @param $text String: The section name
5153 * @return string An anchor
5155 public function guessLegacySectionNameFromWikiText( $text ) {
5156 # Strip out wikitext links(they break the anchor)
5157 $text = $this->stripSectionName( $text );
5158 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5159 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5163 * Strips a text string of wikitext for use in a section anchor
5165 * Accepts a text string and then removes all wikitext from the
5166 * string and leaves only the resultant text (i.e. the result of
5167 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5168 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5169 * to create valid section anchors by mimicing the output of the
5170 * parser when headings are parsed.
5172 * @param $text String: text string to be stripped of wikitext
5173 * for use in a Section anchor
5174 * @return Filtered text string
5176 public function stripSectionName( $text ) {
5177 # Strip internal link markup
5178 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5179 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5181 # Strip external link markup (FIXME: Not Tolerant to blank link text
5182 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5183 # on how many empty links there are on the page - need to figure that out.
5184 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5186 # Parse wikitext quotes (italics & bold)
5187 $text = $this->doQuotes( $text );
5190 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5195 * strip/replaceVariables/unstrip for preprocessor regression testing
5197 function testSrvus( $text, $title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5198 if ( !$title instanceof Title
) {
5199 $title = Title
::newFromText( $title );
5201 $this->startParse( $title, $options, $outputType, true );
5203 $text = $this->replaceVariables( $text );
5204 $text = $this->mStripState
->unstripBoth( $text );
5205 $text = Sanitizer
::removeHTMLtags( $text );
5209 function testPst( $text, $title, $options ) {
5211 if ( !$title instanceof Title
) {
5212 $title = Title
::newFromText( $title );
5214 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5217 function testPreprocess( $text, $title, $options ) {
5218 if ( !$title instanceof Title
) {
5219 $title = Title
::newFromText( $title );
5221 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5225 * Call a callback function on all regions of the given text that are not
5226 * inside strip markers, and replace those regions with the return value
5227 * of the callback. For example, with input:
5231 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5232 * two strings will be replaced with the value returned by the callback in
5235 function markerSkipCallback( $s, $callback ) {
5238 while ( $i < strlen( $s ) ) {
5239 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5240 if ( $markerStart === false ) {
5241 $out .= call_user_func( $callback, substr( $s, $i ) );
5244 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5245 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5246 if ( $markerEnd === false ) {
5247 $out .= substr( $s, $markerStart );
5250 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5251 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5260 * Save the parser state required to convert the given half-parsed text to
5261 * HTML. "Half-parsed" in this context means the output of
5262 * recursiveTagParse() or internalParse(). This output has strip markers
5263 * from replaceVariables (extensionSubstitution() etc.), and link
5264 * placeholders from replaceLinkHolders().
5266 * Returns an array which can be serialized and stored persistently. This
5267 * array can later be loaded into another parser instance with
5268 * unserializeHalfParsed(). The text can then be safely incorporated into
5269 * the return value of a parser hook.
5271 function serializeHalfParsedText( $text ) {
5272 wfProfileIn( __METHOD__
);
5275 'version' => self
::HALF_PARSED_VERSION
,
5276 'stripState' => $this->mStripState
->getSubState( $text ),
5277 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5279 wfProfileOut( __METHOD__
);
5284 * Load the parser state given in the $data array, which is assumed to
5285 * have been generated by serializeHalfParsedText(). The text contents is
5286 * extracted from the array, and its markers are transformed into markers
5287 * appropriate for the current Parser instance. This transformed text is
5288 * returned, and can be safely included in the return value of a parser
5291 * If the $data array has been stored persistently, the caller should first
5292 * check whether it is still valid, by calling isValidHalfParsedData().
5294 * @param $data Serialized data
5297 function unserializeHalfParsedText( $data ) {
5298 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5299 throw new MWException( __METHOD__
.': invalid version' );
5302 # First, extract the strip state.
5303 $texts = array( $data['text'] );
5304 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5306 # Now renumber links
5307 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5309 # Should be good to go.
5314 * Returns true if the given array, presumed to be generated by
5315 * serializeHalfParsedText(), is compatible with the current version of the
5318 * @param $data Array.
5320 function isValidHalfParsedData( $data ) {
5321 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;