3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
119 var $mTagHooks = array();
120 var $mTransparentTagHooks = array();
121 var $mFunctionHooks = array();
122 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
123 var $mFunctionTagHooks = array();
124 var $mStripList = array();
125 var $mDefaultStripList = array();
126 var $mVarCache = array();
127 var $mImageParams = array();
128 var $mImageParamsMagicArray = array();
129 var $mMarkerIndex = 0;
130 var $mFirstCall = true;
132 # Initialised by initialiseVariables()
135 * @var MagicWordArray
140 * @var MagicWordArray
143 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
145 # Cleared with clearState():
150 var $mAutonumber, $mDTopen;
157 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
159 * @var LinkHolderArray
164 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
166 var $mTplExpandCache; # empty-frame expansion cache
167 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
168 var $mExpensiveFunctionCount; # number of expensive parser function calls
169 var $mShowToc, $mForceTocPosition;
174 var $mUser; # User object; only used when doing pre-save transform
177 # These are variables reset at least once per parse regardless of $clearState
187 var $mTitle; # Title context, used for self-link rendering and similar things
188 var $mOutputType; # Output type, one of the OT_xxx constants
189 var $ot; # Shortcut alias, see setOutputType()
190 var $mRevisionObject; # The revision object of the specified revision ID
191 var $mRevisionId; # ID to display in {{REVISIONID}} tags
192 var $mRevisionTimestamp; # The timestamp of the specified revision ID
193 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
194 var $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
195 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
196 var $mInputSize = false; # For {{PAGESIZE}} on current page.
204 * @var Array with the language name of each language link (i.e. the
205 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
206 * duplicate language links to the ParserOutput.
208 var $mLangLinkLanguages;
215 public function __construct( $conf = array() ) {
216 $this->mConf
= $conf;
217 $this->mUrlProtocols
= wfUrlProtocols();
218 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
219 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
220 if ( isset( $conf['preprocessorClass'] ) ) {
221 $this->mPreprocessorClass
= $conf['preprocessorClass'];
222 } elseif ( defined( 'HPHP_VERSION' ) ) {
223 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
224 $this->mPreprocessorClass
= 'Preprocessor_Hash';
225 } elseif ( extension_loaded( 'domxml' ) ) {
226 # PECL extension that conflicts with the core DOM extension (bug 13770)
227 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
228 $this->mPreprocessorClass
= 'Preprocessor_Hash';
229 } elseif ( extension_loaded( 'dom' ) ) {
230 $this->mPreprocessorClass
= 'Preprocessor_DOM';
232 $this->mPreprocessorClass
= 'Preprocessor_Hash';
234 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
238 * Reduce memory usage to reduce the impact of circular references
240 function __destruct() {
241 if ( isset( $this->mLinkHolders
) ) {
242 unset( $this->mLinkHolders
);
244 foreach ( $this as $name => $value ) {
245 unset( $this->$name );
250 * Allow extensions to clean up when the parser is cloned
253 wfRunHooks( 'ParserCloned', array( $this ) );
257 * Do various kinds of initialisation on the first call of the parser
259 function firstCallInit() {
260 if ( !$this->mFirstCall
) {
263 $this->mFirstCall
= false;
265 wfProfileIn( __METHOD__
);
267 CoreParserFunctions
::register( $this );
268 CoreTagHooks
::register( $this );
269 $this->initialiseVariables();
271 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
272 wfProfileOut( __METHOD__
);
280 function clearState() {
281 wfProfileIn( __METHOD__
);
282 if ( $this->mFirstCall
) {
283 $this->firstCallInit();
285 $this->mOutput
= new ParserOutput
;
286 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
287 $this->mAutonumber
= 0;
288 $this->mLastSection
= '';
289 $this->mDTopen
= false;
290 $this->mIncludeCount
= array();
291 $this->mArgStack
= false;
292 $this->mInPre
= false;
293 $this->mLinkHolders
= new LinkHolderArray( $this );
295 $this->mRevisionObject
= $this->mRevisionTimestamp
=
296 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
297 $this->mVarCache
= array();
299 $this->mLangLinkLanguages
= array();
302 * Prefix for temporary replacement strings for the multipass parser.
303 * \x07 should never appear in input as it's disallowed in XML.
304 * Using it at the front also gives us a little extra robustness
305 * since it shouldn't match when butted up against identifier-like
308 * Must not consist of all title characters, or else it will change
309 * the behavior of <nowiki> in a link.
311 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
312 $this->mStripState
= new StripState( $this->mUniqPrefix
);
314 # Clear these on every parse, bug 4549
315 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
317 $this->mShowToc
= true;
318 $this->mForceTocPosition
= false;
319 $this->mIncludeSizes
= array(
323 $this->mPPNodeCount
= 0;
324 $this->mGeneratedPPNodeCount
= 0;
325 $this->mHighestExpansionDepth
= 0;
326 $this->mDefaultSort
= false;
327 $this->mHeadings
= array();
328 $this->mDoubleUnderscores
= array();
329 $this->mExpensiveFunctionCount
= 0;
332 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
333 $this->mPreprocessor
= null;
336 wfRunHooks( 'ParserClearState', array( &$this ) );
337 wfProfileOut( __METHOD__
);
341 * Convert wikitext to HTML
342 * Do not call this function recursively.
344 * @param string $text text we want to parse
345 * @param $title Title object
346 * @param $options ParserOptions
347 * @param $linestart boolean
348 * @param $clearState boolean
349 * @param int $revid number to pass in {{REVISIONID}}
350 * @return ParserOutput a ParserOutput
352 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
354 * First pass--just handle <nowiki> sections, pass the rest off
355 * to internalParse() which does all the real work.
358 global $wgUseTidy, $wgAlwaysUseTidy;
359 $fname = __METHOD__
. '-' . wfGetCaller();
360 wfProfileIn( __METHOD__
);
361 wfProfileIn( $fname );
363 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
365 $this->mInputSize
= strlen( $text );
366 if ( $this->mOptions
->getEnableLimitReport() ) {
367 $this->mOutput
->resetParseStartTime();
370 # Remove the strip marker tag prefix from the input, if present.
372 $text = str_replace( $this->mUniqPrefix
, '', $text );
375 $oldRevisionId = $this->mRevisionId
;
376 $oldRevisionObject = $this->mRevisionObject
;
377 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
378 $oldRevisionUser = $this->mRevisionUser
;
379 $oldRevisionSize = $this->mRevisionSize
;
380 if ( $revid !== null ) {
381 $this->mRevisionId
= $revid;
382 $this->mRevisionObject
= null;
383 $this->mRevisionTimestamp
= null;
384 $this->mRevisionUser
= null;
385 $this->mRevisionSize
= null;
388 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
390 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
391 $text = $this->internalParse( $text );
392 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
394 $text = $this->mStripState
->unstripGeneral( $text );
396 # Clean up special characters, only run once, next-to-last before doBlockLevels
398 # french spaces, last one Guillemet-left
399 # only if there is something before the space
400 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
401 # french spaces, Guillemet-right
402 '/(\\302\\253) /' => '\\1 ',
403 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
405 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
407 $text = $this->doBlockLevels( $text, $linestart );
409 $this->replaceLinkHolders( $text );
412 * The input doesn't get language converted if
414 * b) Content isn't converted
415 * c) It's a conversion table
416 * d) it is an interface message (which is in the user language)
418 if ( !( $options->getDisableContentConversion()
419 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
421 if ( !$this->mOptions
->getInterfaceMessage() ) {
422 # The position of the convert() call should not be changed. it
423 # assumes that the links are all replaced and the only thing left
424 # is the <nowiki> mark.
425 $text = $this->getConverterLanguage()->convert( $text );
430 * A converted title will be provided in the output object if title and
431 * content conversion are enabled, the article text does not contain
432 * a conversion-suppressing double-underscore tag, and no
433 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
434 * automatic link conversion.
436 if ( !( $options->getDisableTitleConversion()
437 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
438 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
439 ||
$this->mOutput
->getDisplayTitle() !== false ) )
441 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
442 if ( $convruletitle ) {
443 $this->mOutput
->setTitleText( $convruletitle );
445 $titleText = $this->getConverterLanguage()->convertTitle( $title );
446 $this->mOutput
->setTitleText( $titleText );
450 $text = $this->mStripState
->unstripNoWiki( $text );
452 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
454 $text = $this->replaceTransparentTags( $text );
455 $text = $this->mStripState
->unstripGeneral( $text );
457 $text = Sanitizer
::normalizeCharReferences( $text );
459 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
460 $text = MWTidy
::tidy( $text );
462 # attempt to sanitize at least some nesting problems
463 # (bug #2702 and quite a few others)
465 # ''Something [http://www.cool.com cool''] -->
466 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
467 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
468 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
469 # fix up an anchor inside another anchor, only
470 # at least for a single single nested link (bug 3695)
471 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
472 '\\1\\2</a>\\3</a>\\1\\4</a>',
473 # fix div inside inline elements- doBlockLevels won't wrap a line which
474 # contains a div, so fix it up here; replace
475 # div with escaped text
476 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
477 '\\1\\3<div\\5>\\6</div>\\8\\9',
478 # remove empty italic or bold tag pairs, some
479 # introduced by rules above
480 '/<([bi])><\/\\1>/' => '',
483 $text = preg_replace(
484 array_keys( $tidyregs ),
485 array_values( $tidyregs ),
489 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
490 $this->limitationWarn( 'expensive-parserfunction',
491 $this->mExpensiveFunctionCount
,
492 $this->mOptions
->getExpensiveParserFunctionLimit()
496 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
498 # Information on include size limits, for the benefit of users who try to skirt them
499 if ( $this->mOptions
->getEnableLimitReport() ) {
500 $max = $this->mOptions
->getMaxIncludeSize();
502 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
503 if ( $cpuTime !== null ) {
504 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
505 sprintf( "%.3f", $cpuTime )
509 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
510 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
511 sprintf( "%.3f", $wallTime )
514 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
515 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
517 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
518 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
520 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
521 array( $this->mIncludeSizes
['post-expand'], $max )
523 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
524 array( $this->mIncludeSizes
['arg'], $max )
526 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
527 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
529 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
530 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
532 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
534 $limitReport = "NewPP limit report\n";
535 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
536 if ( wfRunHooks( 'ParserLimitReportFormat',
537 array( $key, $value, &$limitReport, false, false )
539 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
540 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
541 ->inLanguage( 'en' )->useDatabase( false );
542 if ( !$valueMsg->exists() ) {
543 $valueMsg = new RawMessage( '$1' );
545 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
546 $valueMsg->params( $value );
547 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
551 // Since we're not really outputting HTML, decode the entities and
552 // then re-encode the things that need hiding inside HTML comments.
553 $limitReport = htmlspecialchars_decode( $limitReport );
554 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
556 // Sanitize for comment. Note '‐' in the replacement is U+2010,
557 // which looks much like the problematic '-'.
558 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
559 $text .= "\n<!-- \n$limitReport-->\n";
561 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
562 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
563 $this->mTitle
->getPrefixedDBkey() );
566 $this->mOutput
->setText( $text );
568 $this->mRevisionId
= $oldRevisionId;
569 $this->mRevisionObject
= $oldRevisionObject;
570 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
571 $this->mRevisionUser
= $oldRevisionUser;
572 $this->mRevisionSize
= $oldRevisionSize;
573 $this->mInputSize
= false;
574 wfProfileOut( $fname );
575 wfProfileOut( __METHOD__
);
577 return $this->mOutput
;
581 * Recursive parser entry point that can be called from an extension tag
584 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
586 * @param string $text text extension wants to have parsed
587 * @param $frame PPFrame: The frame to use for expanding any template variables
591 function recursiveTagParse( $text, $frame = false ) {
592 wfProfileIn( __METHOD__
);
593 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
594 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
595 $text = $this->internalParse( $text, false, $frame );
596 wfProfileOut( __METHOD__
);
601 * Expand templates and variables in the text, producing valid, static wikitext.
602 * Also removes comments.
603 * @return mixed|string
605 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
606 wfProfileIn( __METHOD__
);
607 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
608 if ( $revid !== null ) {
609 $this->mRevisionId
= $revid;
611 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
612 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
613 $text = $this->replaceVariables( $text );
614 $text = $this->mStripState
->unstripBoth( $text );
615 wfProfileOut( __METHOD__
);
620 * Recursive parser entry point that can be called from an extension tag
623 * @param string $text text to be expanded
624 * @param $frame PPFrame: The frame to use for expanding any template variables
628 public function recursivePreprocess( $text, $frame = false ) {
629 wfProfileIn( __METHOD__
);
630 $text = $this->replaceVariables( $text, $frame );
631 $text = $this->mStripState
->unstripBoth( $text );
632 wfProfileOut( __METHOD__
);
637 * Process the wikitext for the "?preload=" feature. (bug 5210)
639 * "<noinclude>", "<includeonly>" etc. are parsed as for template
640 * transclusion, comments, templates, arguments, tags hooks and parser
641 * functions are untouched.
643 * @param $text String
644 * @param $title Title
645 * @param $options ParserOptions
648 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
649 # Parser (re)initialisation
650 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
652 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
653 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
654 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
655 $text = $this->mStripState
->unstripBoth( $text );
660 * Get a random string
664 public static function getRandomString() {
665 return wfRandomString( 16 );
669 * Set the current user.
670 * Should only be used when doing pre-save transform.
672 * @param $user Mixed: User object or null (to reset)
674 function setUser( $user ) {
675 $this->mUser
= $user;
679 * Accessor for mUniqPrefix.
683 public function uniqPrefix() {
684 if ( !isset( $this->mUniqPrefix
) ) {
685 # @todo FIXME: This is probably *horribly wrong*
686 # LanguageConverter seems to want $wgParser's uniqPrefix, however
687 # if this is called for a parser cache hit, the parser may not
688 # have ever been initialized in the first place.
689 # Not really sure what the heck is supposed to be going on here.
691 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
693 return $this->mUniqPrefix
;
697 * Set the context title
701 function setTitle( $t ) {
702 if ( !$t ||
$t instanceof FakeTitle
) {
703 $t = Title
::newFromText( 'NO TITLE' );
706 if ( strval( $t->getFragment() ) !== '' ) {
707 # Strip the fragment to avoid various odd effects
708 $this->mTitle
= clone $t;
709 $this->mTitle
->setFragment( '' );
716 * Accessor for the Title object
718 * @return Title object
720 function getTitle() {
721 return $this->mTitle
;
725 * Accessor/mutator for the Title object
727 * @param $x Title object or null to just get the current one
728 * @return Title object
730 function Title( $x = null ) {
731 return wfSetVar( $this->mTitle
, $x );
735 * Set the output type
737 * @param $ot Integer: new value
739 function setOutputType( $ot ) {
740 $this->mOutputType
= $ot;
743 'html' => $ot == self
::OT_HTML
,
744 'wiki' => $ot == self
::OT_WIKI
,
745 'pre' => $ot == self
::OT_PREPROCESS
,
746 'plain' => $ot == self
::OT_PLAIN
,
751 * Accessor/mutator for the output type
753 * @param int|null $x New value or null to just get the current one
756 function OutputType( $x = null ) {
757 return wfSetVar( $this->mOutputType
, $x );
761 * Get the ParserOutput object
763 * @return ParserOutput object
765 function getOutput() {
766 return $this->mOutput
;
770 * Get the ParserOptions object
772 * @return ParserOptions object
774 function getOptions() {
775 return $this->mOptions
;
779 * Accessor/mutator for the ParserOptions object
781 * @param $x ParserOptions New value or null to just get the current one
782 * @return ParserOptions Current ParserOptions object
784 function Options( $x = null ) {
785 return wfSetVar( $this->mOptions
, $x );
791 function nextLinkID() {
792 return $this->mLinkID++
;
798 function setLinkID( $id ) {
799 $this->mLinkID
= $id;
803 * Get a language object for use in parser functions such as {{FORMATNUM:}}
806 function getFunctionLang() {
807 return $this->getTargetLanguage();
811 * Get the target language for the content being parsed. This is usually the
812 * language that the content is in.
816 * @throws MWException
817 * @return Language|null
819 public function getTargetLanguage() {
820 $target = $this->mOptions
->getTargetLanguage();
822 if ( $target !== null ) {
824 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
825 return $this->mOptions
->getUserLangObj();
826 } elseif ( is_null( $this->mTitle
) ) {
827 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
830 return $this->mTitle
->getPageLanguage();
834 * Get the language object for language conversion
836 function getConverterLanguage() {
837 return $this->getTargetLanguage();
841 * Get a User object either from $this->mUser, if set, or from the
842 * ParserOptions object otherwise
844 * @return User object
847 if ( !is_null( $this->mUser
) ) {
850 return $this->mOptions
->getUser();
854 * Get a preprocessor object
856 * @return Preprocessor instance
858 function getPreprocessor() {
859 if ( !isset( $this->mPreprocessor
) ) {
860 $class = $this->mPreprocessorClass
;
861 $this->mPreprocessor
= new $class( $this );
863 return $this->mPreprocessor
;
867 * Replaces all occurrences of HTML-style comments and the given tags
868 * in the text with a random marker and returns the next text. The output
869 * parameter $matches will be an associative array filled with data in
873 * 'UNIQ-xxxxx' => array(
876 * array( 'param' => 'x' ),
877 * '<element param="x">tag content</element>' ) )
880 * @param array $elements list of element names. Comments are always extracted.
881 * @param string $text Source text string.
882 * @param array $matches Out parameter, Array: extracted tags
883 * @param $uniq_prefix string
884 * @return String: stripped text
886 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
891 $taglist = implode( '|', $elements );
892 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
894 while ( $text != '' ) {
895 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
897 if ( count( $p ) < 5 ) {
900 if ( count( $p ) > 5 ) {
914 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
915 $stripped .= $marker;
917 if ( $close === '/>' ) {
918 # Empty element tag, <tag />
923 if ( $element === '!--' ) {
926 $end = "/(<\\/$element\\s*>)/i";
928 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
930 if ( count( $q ) < 3 ) {
931 # No end tag -- let it run out to the end of the text.
940 $matches[$marker] = array( $element,
942 Sanitizer
::decodeTagAttributes( $attributes ),
943 "<$element$attributes$close$content$tail" );
949 * Get a list of strippable XML-like elements
953 function getStripList() {
954 return $this->mStripList
;
958 * Add an item to the strip state
959 * Returns the unique tag which must be inserted into the stripped text
960 * The tag will be replaced with the original text in unstrip()
962 * @param $text string
966 function insertStripItem( $text ) {
967 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
968 $this->mMarkerIndex++
;
969 $this->mStripState
->addGeneral( $rnd, $text );
974 * parse the wiki syntax used to render tables
979 function doTableStuff( $text ) {
980 wfProfileIn( __METHOD__
);
982 $lines = StringUtils
::explode( "\n", $text );
984 $td_history = array(); # Is currently a td tag open?
985 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
986 $tr_history = array(); # Is currently a tr tag open?
987 $tr_attributes = array(); # history of tr attributes
988 $has_opened_tr = array(); # Did this table open a <tr> element?
989 $indent_level = 0; # indent level of the table
991 foreach ( $lines as $outLine ) {
992 $line = trim( $outLine );
994 if ( $line === '' ) { # empty line, go to next line
995 $out .= $outLine . "\n";
999 $first_character = $line[0];
1002 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1003 # First check if we are starting a new table
1004 $indent_level = strlen( $matches[1] );
1006 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1007 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1009 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1010 array_push( $td_history, false );
1011 array_push( $last_tag_history, '' );
1012 array_push( $tr_history, false );
1013 array_push( $tr_attributes, '' );
1014 array_push( $has_opened_tr, false );
1015 } elseif ( count( $td_history ) == 0 ) {
1016 # Don't do any of the following
1017 $out .= $outLine . "\n";
1019 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1020 # We are ending a table
1021 $line = '</table>' . substr( $line, 2 );
1022 $last_tag = array_pop( $last_tag_history );
1024 if ( !array_pop( $has_opened_tr ) ) {
1025 $line = "<tr><td></td></tr>{$line}";
1028 if ( array_pop( $tr_history ) ) {
1029 $line = "</tr>{$line}";
1032 if ( array_pop( $td_history ) ) {
1033 $line = "</{$last_tag}>{$line}";
1035 array_pop( $tr_attributes );
1036 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1037 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1038 # Now we have a table row
1039 $line = preg_replace( '#^\|-+#', '', $line );
1041 # Whats after the tag is now only attributes
1042 $attributes = $this->mStripState
->unstripBoth( $line );
1043 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1044 array_pop( $tr_attributes );
1045 array_push( $tr_attributes, $attributes );
1048 $last_tag = array_pop( $last_tag_history );
1049 array_pop( $has_opened_tr );
1050 array_push( $has_opened_tr, true );
1052 if ( array_pop( $tr_history ) ) {
1056 if ( array_pop( $td_history ) ) {
1057 $line = "</{$last_tag}>{$line}";
1061 array_push( $tr_history, false );
1062 array_push( $td_history, false );
1063 array_push( $last_tag_history, '' );
1064 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1065 # This might be cell elements, td, th or captions
1066 if ( substr( $line, 0, 2 ) === '|+' ) {
1067 $first_character = '+';
1068 $line = substr( $line, 1 );
1071 $line = substr( $line, 1 );
1073 if ( $first_character === '!' ) {
1074 $line = str_replace( '!!', '||', $line );
1077 # Split up multiple cells on the same line.
1078 # FIXME : This can result in improper nesting of tags processed
1079 # by earlier parser steps, but should avoid splitting up eg
1080 # attribute values containing literal "||".
1081 $cells = StringUtils
::explodeMarkup( '||', $line );
1085 # Loop through each table cell
1086 foreach ( $cells as $cell ) {
1088 if ( $first_character !== '+' ) {
1089 $tr_after = array_pop( $tr_attributes );
1090 if ( !array_pop( $tr_history ) ) {
1091 $previous = "<tr{$tr_after}>\n";
1093 array_push( $tr_history, true );
1094 array_push( $tr_attributes, '' );
1095 array_pop( $has_opened_tr );
1096 array_push( $has_opened_tr, true );
1099 $last_tag = array_pop( $last_tag_history );
1101 if ( array_pop( $td_history ) ) {
1102 $previous = "</{$last_tag}>\n{$previous}";
1105 if ( $first_character === '|' ) {
1107 } elseif ( $first_character === '!' ) {
1109 } elseif ( $first_character === '+' ) {
1110 $last_tag = 'caption';
1115 array_push( $last_tag_history, $last_tag );
1117 # A cell could contain both parameters and data
1118 $cell_data = explode( '|', $cell, 2 );
1120 # Bug 553: Note that a '|' inside an invalid link should not
1121 # be mistaken as delimiting cell parameters
1122 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1123 $cell = "{$previous}<{$last_tag}>{$cell}";
1124 } elseif ( count( $cell_data ) == 1 ) {
1125 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1127 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1128 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1129 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1133 array_push( $td_history, true );
1136 $out .= $outLine . "\n";
1139 # Closing open td, tr && table
1140 while ( count( $td_history ) > 0 ) {
1141 if ( array_pop( $td_history ) ) {
1144 if ( array_pop( $tr_history ) ) {
1147 if ( !array_pop( $has_opened_tr ) ) {
1148 $out .= "<tr><td></td></tr>\n";
1151 $out .= "</table>\n";
1154 # Remove trailing line-ending (b/c)
1155 if ( substr( $out, -1 ) === "\n" ) {
1156 $out = substr( $out, 0, -1 );
1159 # special case: don't return empty table
1160 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1164 wfProfileOut( __METHOD__
);
1170 * Helper function for parse() that transforms wiki markup into
1171 * HTML. Only called for $mOutputType == self::OT_HTML.
1175 * @param $text string
1176 * @param $isMain bool
1177 * @param $frame bool
1181 function internalParse( $text, $isMain = true, $frame = false ) {
1182 wfProfileIn( __METHOD__
);
1186 # Hook to suspend the parser in this state
1187 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1188 wfProfileOut( __METHOD__
);
1192 # if $frame is provided, then use $frame for replacing any variables
1194 # use frame depth to infer how include/noinclude tags should be handled
1195 # depth=0 means this is the top-level document; otherwise it's an included document
1196 if ( !$frame->depth
) {
1199 $flag = Parser
::PTD_FOR_INCLUSION
;
1201 $dom = $this->preprocessToDom( $text, $flag );
1202 $text = $frame->expand( $dom );
1204 # if $frame is not provided, then use old-style replaceVariables
1205 $text = $this->replaceVariables( $text );
1208 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1209 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1210 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1212 # Tables need to come after variable replacement for things to work
1213 # properly; putting them before other transformations should keep
1214 # exciting things like link expansions from showing up in surprising
1216 $text = $this->doTableStuff( $text );
1218 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1220 $text = $this->doDoubleUnderscore( $text );
1222 $text = $this->doHeadings( $text );
1223 $text = $this->replaceInternalLinks( $text );
1224 $text = $this->doAllQuotes( $text );
1225 $text = $this->replaceExternalLinks( $text );
1227 # replaceInternalLinks may sometimes leave behind
1228 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1229 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1231 $text = $this->doMagicLinks( $text );
1232 $text = $this->formatHeadings( $text, $origText, $isMain );
1234 wfProfileOut( __METHOD__
);
1239 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1240 * magic external links.
1245 * @param $text string
1249 function doMagicLinks( $text ) {
1250 wfProfileIn( __METHOD__
);
1251 $prots = wfUrlProtocolsWithoutProtRel();
1252 $urlChar = self
::EXT_LINK_URL_CLASS
;
1253 $text = preg_replace_callback(
1255 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1256 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1257 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1258 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1259 ISBN\s+(\b # m[5]: ISBN, capture number
1260 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1261 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1262 [0-9Xx] # check digit
1264 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1265 wfProfileOut( __METHOD__
);
1270 * @throws MWException
1272 * @return HTML|string
1274 function magicLinkCallback( $m ) {
1275 if ( isset( $m[1] ) && $m[1] !== '' ) {
1278 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1281 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1282 # Free external link
1283 return $this->makeFreeExternalLink( $m[0] );
1284 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1286 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1289 $CssClass = 'mw-magiclink-rfc';
1291 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1293 $urlmsg = 'pubmedurl';
1294 $CssClass = 'mw-magiclink-pmid';
1297 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1298 substr( $m[0], 0, 20 ) . '"' );
1300 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1301 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1302 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1305 $num = strtr( $isbn, array(
1310 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1311 return '<a href="' .
1312 htmlspecialchars( $titleObj->getLocalURL() ) .
1313 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1320 * Make a free external link, given a user-supplied URL
1322 * @param $url string
1324 * @return string HTML
1327 function makeFreeExternalLink( $url ) {
1328 wfProfileIn( __METHOD__
);
1332 # The characters '<' and '>' (which were escaped by
1333 # removeHTMLtags()) should not be included in
1334 # URLs, per RFC 2396.
1336 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1337 $trail = substr( $url, $m2[0][1] ) . $trail;
1338 $url = substr( $url, 0, $m2[0][1] );
1341 # Move trailing punctuation to $trail
1343 # If there is no left bracket, then consider right brackets fair game too
1344 if ( strpos( $url, '(' ) === false ) {
1348 $numSepChars = strspn( strrev( $url ), $sep );
1349 if ( $numSepChars ) {
1350 $trail = substr( $url, -$numSepChars ) . $trail;
1351 $url = substr( $url, 0, -$numSepChars );
1354 $url = Sanitizer
::cleanUrl( $url );
1356 # Is this an external image?
1357 $text = $this->maybeMakeExternalImage( $url );
1358 if ( $text === false ) {
1359 # Not an image, make a link
1360 $text = Linker
::makeExternalLink( $url,
1361 $this->getConverterLanguage()->markNoConversion( $url, true ),
1363 $this->getExternalLinkAttribs( $url ) );
1364 # Register it in the output object...
1365 # Replace unnecessary URL escape codes with their equivalent characters
1366 $pasteurized = self
::replaceUnusualEscapes( $url );
1367 $this->mOutput
->addExternalLink( $pasteurized );
1369 wfProfileOut( __METHOD__
);
1370 return $text . $trail;
1374 * Parse headers and return html
1378 * @param $text string
1382 function doHeadings( $text ) {
1383 wfProfileIn( __METHOD__
);
1384 for ( $i = 6; $i >= 1; --$i ) {
1385 $h = str_repeat( '=', $i );
1386 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1388 wfProfileOut( __METHOD__
);
1393 * Replace single quotes with HTML markup
1396 * @param $text string
1398 * @return string the altered text
1400 function doAllQuotes( $text ) {
1401 wfProfileIn( __METHOD__
);
1403 $lines = StringUtils
::explode( "\n", $text );
1404 foreach ( $lines as $line ) {
1405 $outtext .= $this->doQuotes( $line ) . "\n";
1407 $outtext = substr( $outtext, 0, -1 );
1408 wfProfileOut( __METHOD__
);
1413 * Helper function for doAllQuotes()
1415 * @param $text string
1419 public function doQuotes( $text ) {
1420 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1421 $countarr = count( $arr );
1422 if ( $countarr == 1 ) {
1426 // First, do some preliminary work. This may shift some apostrophes from
1427 // being mark-up to being text. It also counts the number of occurrences
1428 // of bold and italics mark-ups.
1431 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1432 $thislen = strlen( $arr[$i] );
1433 // If there are ever four apostrophes, assume the first is supposed to
1434 // be text, and the remaining three constitute mark-up for bold text.
1435 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1436 if ( $thislen == 4 ) {
1437 $arr[$i - 1] .= "'";
1440 } elseif ( $thislen > 5 ) {
1441 // If there are more than 5 apostrophes in a row, assume they're all
1442 // text except for the last 5.
1443 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1444 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1448 // Count the number of occurrences of bold and italics mark-ups.
1449 if ( $thislen == 2 ) {
1451 } elseif ( $thislen == 3 ) {
1453 } elseif ( $thislen == 5 ) {
1459 // If there is an odd number of both bold and italics, it is likely
1460 // that one of the bold ones was meant to be an apostrophe followed
1461 // by italics. Which one we cannot know for certain, but it is more
1462 // likely to be one that has a single-letter word before it.
1463 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1464 $firstsingleletterword = -1;
1465 $firstmultiletterword = -1;
1467 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1468 if ( strlen( $arr[$i] ) == 3 ) {
1469 $x1 = substr( $arr[$i - 1], -1 );
1470 $x2 = substr( $arr[$i - 1], -2, 1 );
1471 if ( $x1 === ' ' ) {
1472 if ( $firstspace == -1 ) {
1475 } elseif ( $x2 === ' ' ) {
1476 if ( $firstsingleletterword == -1 ) {
1477 $firstsingleletterword = $i;
1478 // if $firstsingleletterword is set, we don't
1479 // look at the other options, so we can bail early.
1483 if ( $firstmultiletterword == -1 ) {
1484 $firstmultiletterword = $i;
1490 // If there is a single-letter word, use it!
1491 if ( $firstsingleletterword > -1 ) {
1492 $arr[$firstsingleletterword] = "''";
1493 $arr[$firstsingleletterword - 1] .= "'";
1494 } elseif ( $firstmultiletterword > -1 ) {
1495 // If not, but there's a multi-letter word, use that one.
1496 $arr[$firstmultiletterword] = "''";
1497 $arr[$firstmultiletterword - 1] .= "'";
1498 } elseif ( $firstspace > -1 ) {
1499 // ... otherwise use the first one that has neither.
1500 // (notice that it is possible for all three to be -1 if, for example,
1501 // there is only one pentuple-apostrophe in the line)
1502 $arr[$firstspace] = "''";
1503 $arr[$firstspace - 1] .= "'";
1507 // Now let's actually convert our apostrophic mush to HTML!
1512 foreach ( $arr as $r ) {
1513 if ( ( $i %
2 ) == 0 ) {
1514 if ( $state === 'both' ) {
1520 $thislen = strlen( $r );
1521 if ( $thislen == 2 ) {
1522 if ( $state === 'i' ) {
1525 } elseif ( $state === 'bi' ) {
1528 } elseif ( $state === 'ib' ) {
1529 $output .= '</b></i><b>';
1531 } elseif ( $state === 'both' ) {
1532 $output .= '<b><i>' . $buffer . '</i>';
1534 } else { // $state can be 'b' or ''
1538 } elseif ( $thislen == 3 ) {
1539 if ( $state === 'b' ) {
1542 } elseif ( $state === 'bi' ) {
1543 $output .= '</i></b><i>';
1545 } elseif ( $state === 'ib' ) {
1548 } elseif ( $state === 'both' ) {
1549 $output .= '<i><b>' . $buffer . '</b>';
1551 } else { // $state can be 'i' or ''
1555 } elseif ( $thislen == 5 ) {
1556 if ( $state === 'b' ) {
1557 $output .= '</b><i>';
1559 } elseif ( $state === 'i' ) {
1560 $output .= '</i><b>';
1562 } elseif ( $state === 'bi' ) {
1563 $output .= '</i></b>';
1565 } elseif ( $state === 'ib' ) {
1566 $output .= '</b></i>';
1568 } elseif ( $state === 'both' ) {
1569 $output .= '<i><b>' . $buffer . '</b></i>';
1571 } else { // ($state == '')
1579 // Now close all remaining tags. Notice that the order is important.
1580 if ( $state === 'b' ||
$state === 'ib' ) {
1583 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1586 if ( $state === 'bi' ) {
1589 // There might be lonely ''''', so make sure we have a buffer
1590 if ( $state === 'both' && $buffer ) {
1591 $output .= '<b><i>' . $buffer . '</i></b>';
1597 * Replace external links (REL)
1599 * Note: this is all very hackish and the order of execution matters a lot.
1600 * Make sure to run tests/parserTests.php if you change this code.
1604 * @param $text string
1606 * @throws MWException
1609 function replaceExternalLinks( $text ) {
1610 wfProfileIn( __METHOD__
);
1612 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1613 if ( $bits === false ) {
1614 wfProfileOut( __METHOD__
);
1615 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1617 $s = array_shift( $bits );
1620 while ( $i < count( $bits ) ) {
1623 $text = $bits[$i++
];
1624 $trail = $bits[$i++
];
1626 # The characters '<' and '>' (which were escaped by
1627 # removeHTMLtags()) should not be included in
1628 # URLs, per RFC 2396.
1630 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1631 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1632 $url = substr( $url, 0, $m2[0][1] );
1635 # If the link text is an image URL, replace it with an <img> tag
1636 # This happened by accident in the original parser, but some people used it extensively
1637 $img = $this->maybeMakeExternalImage( $text );
1638 if ( $img !== false ) {
1644 # Set linktype for CSS - if URL==text, link is essentially free
1645 $linktype = ( $text === $url ) ?
'free' : 'text';
1647 # No link text, e.g. [http://domain.tld/some.link]
1648 if ( $text == '' ) {
1650 $langObj = $this->getTargetLanguage();
1651 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1652 $linktype = 'autonumber';
1654 # Have link text, e.g. [http://domain.tld/some.link text]s
1656 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1659 $text = $this->getConverterLanguage()->markNoConversion( $text );
1661 $url = Sanitizer
::cleanUrl( $url );
1663 # Use the encoded URL
1664 # This means that users can paste URLs directly into the text
1665 # Funny characters like ö aren't valid in URLs anyway
1666 # This was changed in August 2004
1667 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1668 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1670 # Register link in the output object.
1671 # Replace unnecessary URL escape codes with the referenced character
1672 # This prevents spammers from hiding links from the filters
1673 $pasteurized = self
::replaceUnusualEscapes( $url );
1674 $this->mOutput
->addExternalLink( $pasteurized );
1677 wfProfileOut( __METHOD__
);
1681 * Get the rel attribute for a particular external link.
1684 * @param string|bool $url optional URL, to extract the domain from for rel =>
1685 * nofollow if appropriate
1686 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1687 * @return string|null rel attribute for $url
1689 public static function getExternalLinkRel( $url = false, $title = null ) {
1690 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1691 $ns = $title ?
$title->getNamespace() : false;
1692 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1693 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1700 * Get an associative array of additional HTML attributes appropriate for a
1701 * particular external link. This currently may include rel => nofollow
1702 * (depending on configuration, namespace, and the URL's domain) and/or a
1703 * target attribute (depending on configuration).
1705 * @param string|bool $url optional URL, to extract the domain from for rel =>
1706 * nofollow if appropriate
1707 * @return Array associative array of HTML attributes
1709 function getExternalLinkAttribs( $url = false ) {
1711 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1713 if ( $this->mOptions
->getExternalLinkTarget() ) {
1714 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1720 * Replace unusual URL escape codes with their equivalent characters
1722 * @param $url String
1725 * @todo This can merge genuinely required bits in the path or query string,
1726 * breaking legit URLs. A proper fix would treat the various parts of
1727 * the URL differently; as a workaround, just use the output for
1728 * statistical records, not for actual linking/output.
1730 static function replaceUnusualEscapes( $url ) {
1731 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1732 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1736 * Callback function used in replaceUnusualEscapes().
1737 * Replaces unusual URL escape codes with their equivalent character
1739 * @param $matches array
1743 private static function replaceUnusualEscapesCallback( $matches ) {
1744 $char = urldecode( $matches[0] );
1745 $ord = ord( $char );
1746 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1747 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1748 # No, shouldn't be escaped
1751 # Yes, leave it escaped
1757 * make an image if it's allowed, either through the global
1758 * option, through the exception, or through the on-wiki whitelist
1761 * $param $url string
1765 function maybeMakeExternalImage( $url ) {
1766 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1767 $imagesexception = !empty( $imagesfrom );
1769 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1770 if ( $imagesexception && is_array( $imagesfrom ) ) {
1771 $imagematch = false;
1772 foreach ( $imagesfrom as $match ) {
1773 if ( strpos( $url, $match ) === 0 ) {
1778 } elseif ( $imagesexception ) {
1779 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1781 $imagematch = false;
1783 if ( $this->mOptions
->getAllowExternalImages()
1784 ||
( $imagesexception && $imagematch ) ) {
1785 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1787 $text = Linker
::makeExternalImage( $url );
1790 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1791 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1792 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1793 foreach ( $whitelist as $entry ) {
1794 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1795 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1798 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1799 # Image matches a whitelist entry
1800 $text = Linker
::makeExternalImage( $url );
1809 * Process [[ ]] wikilinks
1813 * @return String: processed text
1817 function replaceInternalLinks( $s ) {
1818 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1823 * Process [[ ]] wikilinks (RIL)
1825 * @throws MWException
1826 * @return LinkHolderArray
1830 function replaceInternalLinks2( &$s ) {
1831 wfProfileIn( __METHOD__
);
1833 wfProfileIn( __METHOD__
. '-setup' );
1834 static $tc = false, $e1, $e1_img;
1835 # the % is needed to support urlencoded titles as well
1837 $tc = Title
::legalChars() . '#%';
1838 # Match a link having the form [[namespace:link|alternate]]trail
1839 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1840 # Match cases where there is no "]]", which might still be images
1841 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1844 $holders = new LinkHolderArray( $this );
1846 # split the entire text string on occurrences of [[
1847 $a = StringUtils
::explode( '[[', ' ' . $s );
1848 # get the first element (all text up to first [[), and remove the space we added
1851 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1852 $s = substr( $s, 1 );
1854 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1856 if ( $useLinkPrefixExtension ) {
1857 # Match the end of a line for a word that's not followed by whitespace,
1858 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1859 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1862 if ( is_null( $this->mTitle
) ) {
1863 wfProfileOut( __METHOD__
. '-setup' );
1864 wfProfileOut( __METHOD__
);
1865 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1867 $nottalk = !$this->mTitle
->isTalkPage();
1869 if ( $useLinkPrefixExtension ) {
1871 if ( preg_match( $e2, $s, $m ) ) {
1872 $first_prefix = $m[2];
1874 $first_prefix = false;
1880 $useSubpages = $this->areSubpagesAllowed();
1881 wfProfileOut( __METHOD__
. '-setup' );
1883 # Loop for each link
1884 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1885 # Check for excessive memory usage
1886 if ( $holders->isBig() ) {
1888 # Do the existence check, replace the link holders and clear the array
1889 $holders->replace( $s );
1893 if ( $useLinkPrefixExtension ) {
1894 wfProfileIn( __METHOD__
. '-prefixhandling' );
1895 if ( preg_match( $e2, $s, $m ) ) {
1902 if ( $first_prefix ) {
1903 $prefix = $first_prefix;
1904 $first_prefix = false;
1906 wfProfileOut( __METHOD__
. '-prefixhandling' );
1909 $might_be_img = false;
1911 wfProfileIn( __METHOD__
. "-e1" );
1912 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1914 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1915 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1916 # the real problem is with the $e1 regex
1919 # Still some problems for cases where the ] is meant to be outside punctuation,
1920 # and no image is in sight. See bug 2095.
1922 if ( $text !== '' &&
1923 substr( $m[3], 0, 1 ) === ']' &&
1924 strpos( $text, '[' ) !== false
1927 $text .= ']'; # so that replaceExternalLinks($text) works later
1928 $m[3] = substr( $m[3], 1 );
1930 # fix up urlencoded title texts
1931 if ( strpos( $m[1], '%' ) !== false ) {
1932 # Should anchors '#' also be rejected?
1933 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1936 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1937 $might_be_img = true;
1939 if ( strpos( $m[1], '%' ) !== false ) {
1940 $m[1] = rawurldecode( $m[1] );
1943 } else { # Invalid form; output directly
1944 $s .= $prefix . '[[' . $line;
1945 wfProfileOut( __METHOD__
. "-e1" );
1948 wfProfileOut( __METHOD__
. "-e1" );
1949 wfProfileIn( __METHOD__
. "-misc" );
1951 # Don't allow internal links to pages containing
1952 # PROTO: where PROTO is a valid URL protocol; these
1953 # should be external links.
1954 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1955 $s .= $prefix . '[[' . $line;
1956 wfProfileOut( __METHOD__
. "-misc" );
1960 # Make subpage if necessary
1961 if ( $useSubpages ) {
1962 $link = $this->maybeDoSubpageLink( $m[1], $text );
1967 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1969 # Strip off leading ':'
1970 $link = substr( $link, 1 );
1973 wfProfileOut( __METHOD__
. "-misc" );
1974 wfProfileIn( __METHOD__
. "-title" );
1975 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1976 if ( $nt === null ) {
1977 $s .= $prefix . '[[' . $line;
1978 wfProfileOut( __METHOD__
. "-title" );
1982 $ns = $nt->getNamespace();
1983 $iw = $nt->getInterWiki();
1984 wfProfileOut( __METHOD__
. "-title" );
1986 if ( $might_be_img ) { # if this is actually an invalid link
1987 wfProfileIn( __METHOD__
. "-might_be_img" );
1988 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1991 # look at the next 'line' to see if we can close it there
1993 $next_line = $a->current();
1994 if ( $next_line === false ||
$next_line === null ) {
1997 $m = explode( ']]', $next_line, 3 );
1998 if ( count( $m ) == 3 ) {
1999 # the first ]] closes the inner link, the second the image
2001 $text .= "[[{$m[0]}]]{$m[1]}";
2004 } elseif ( count( $m ) == 2 ) {
2005 # if there's exactly one ]] that's fine, we'll keep looking
2006 $text .= "[[{$m[0]}]]{$m[1]}";
2008 # if $next_line is invalid too, we need look no further
2009 $text .= '[[' . $next_line;
2014 # we couldn't find the end of this imageLink, so output it raw
2015 # but don't ignore what might be perfectly normal links in the text we've examined
2016 $holders->merge( $this->replaceInternalLinks2( $text ) );
2017 $s .= "{$prefix}[[$link|$text";
2018 # note: no $trail, because without an end, there *is* no trail
2019 wfProfileOut( __METHOD__
. "-might_be_img" );
2022 } else { # it's not an image, so output it raw
2023 $s .= "{$prefix}[[$link|$text";
2024 # note: no $trail, because without an end, there *is* no trail
2025 wfProfileOut( __METHOD__
. "-might_be_img" );
2028 wfProfileOut( __METHOD__
. "-might_be_img" );
2031 $wasblank = ( $text == '' );
2035 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2036 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2037 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2038 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2039 $text = $this->doQuotes( $text );
2042 # Link not escaped by : , create the various objects
2045 wfProfileIn( __METHOD__
. "-interwiki" );
2046 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
2047 // XXX: the above check prevents links to sites with identifiers that are not language codes
2049 # Bug 24502: filter duplicates
2050 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2051 $this->mLangLinkLanguages
[$iw] = true;
2052 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2055 $s = rtrim( $s . $prefix );
2056 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2057 wfProfileOut( __METHOD__
. "-interwiki" );
2060 wfProfileOut( __METHOD__
. "-interwiki" );
2062 if ( $ns == NS_FILE
) {
2063 wfProfileIn( __METHOD__
. "-image" );
2064 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2066 # if no parameters were passed, $text
2067 # becomes something like "File:Foo.png",
2068 # which we don't want to pass on to the
2072 # recursively parse links inside the image caption
2073 # actually, this will parse them in any other parameters, too,
2074 # but it might be hard to fix that, and it doesn't matter ATM
2075 $text = $this->replaceExternalLinks( $text );
2076 $holders->merge( $this->replaceInternalLinks2( $text ) );
2078 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2079 $s .= $prefix . $this->armorLinks(
2080 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2082 $s .= $prefix . $trail;
2084 wfProfileOut( __METHOD__
. "-image" );
2088 if ( $ns == NS_CATEGORY
) {
2089 wfProfileIn( __METHOD__
. "-category" );
2090 $s = rtrim( $s . "\n" ); # bug 87
2093 $sortkey = $this->getDefaultSort();
2097 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2098 $sortkey = str_replace( "\n", '', $sortkey );
2099 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2100 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2103 * Strip the whitespace Category links produce, see bug 87
2104 * @todo We might want to use trim($tmp, "\n") here.
2106 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2108 wfProfileOut( __METHOD__
. "-category" );
2113 # Self-link checking
2114 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2115 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2116 $this->mTitle
->getPrefixedText(),
2117 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2120 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2125 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2126 # @todo FIXME: Should do batch file existence checks, see comment below
2127 if ( $ns == NS_MEDIA
) {
2128 wfProfileIn( __METHOD__
. "-media" );
2129 # Give extensions a chance to select the file revision for us
2132 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2133 array( $this, $nt, &$options, &$descQuery ) );
2134 # Fetch and register the file (file title may be different via hooks)
2135 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2136 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2137 $s .= $prefix . $this->armorLinks(
2138 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2139 wfProfileOut( __METHOD__
. "-media" );
2143 wfProfileIn( __METHOD__
. "-always_known" );
2144 # Some titles, such as valid special pages or files in foreign repos, should
2145 # be shown as bluelinks even though they're not included in the page table
2147 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2148 # batch file existence checks for NS_FILE and NS_MEDIA
2149 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2150 $this->mOutput
->addLink( $nt );
2151 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2153 # Links will be added to the output link list after checking
2154 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2156 wfProfileOut( __METHOD__
. "-always_known" );
2158 wfProfileOut( __METHOD__
);
2163 * Render a forced-blue link inline; protect against double expansion of
2164 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2165 * Since this little disaster has to split off the trail text to avoid
2166 * breaking URLs in the following text without breaking trails on the
2167 * wiki links, it's been made into a horrible function.
2170 * @param $text String
2171 * @param array $query or String
2172 * @param $trail String
2173 * @param $prefix String
2174 * @return String: HTML-wikitext mix oh yuck
2176 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2177 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2179 if ( is_string( $query ) ) {
2180 $query = wfCgiToArray( $query );
2182 if ( $text == '' ) {
2183 $text = htmlspecialchars( $nt->getPrefixedText() );
2186 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2188 return $this->armorLinks( $link ) . $trail;
2192 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2193 * going to go through further parsing steps before inline URL expansion.
2195 * Not needed quite as much as it used to be since free links are a bit
2196 * more sensible these days. But bracketed links are still an issue.
2198 * @param string $text more-or-less HTML
2199 * @return String: less-or-more HTML with NOPARSE bits
2201 function armorLinks( $text ) {
2202 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2203 "{$this->mUniqPrefix}NOPARSE$1", $text );
2207 * Return true if subpage links should be expanded on this page.
2210 function areSubpagesAllowed() {
2211 # Some namespaces don't allow subpages
2212 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2216 * Handle link to subpage if necessary
2218 * @param string $target the source of the link
2219 * @param &$text String: the link text, modified as necessary
2220 * @return string the full name of the link
2223 function maybeDoSubpageLink( $target, &$text ) {
2224 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2228 * Used by doBlockLevels()
2233 function closeParagraph() {
2235 if ( $this->mLastSection
!= '' ) {
2236 $result = '</' . $this->mLastSection
. ">\n";
2238 $this->mInPre
= false;
2239 $this->mLastSection
= '';
2244 * getCommon() returns the length of the longest common substring
2245 * of both arguments, starting at the beginning of both.
2248 * @param $st1 string
2249 * @param $st2 string
2253 function getCommon( $st1, $st2 ) {
2254 $fl = strlen( $st1 );
2255 $shorter = strlen( $st2 );
2256 if ( $fl < $shorter ) {
2260 for ( $i = 0; $i < $shorter; ++
$i ) {
2261 if ( $st1[$i] != $st2[$i] ) {
2269 * These next three functions open, continue, and close the list
2270 * element appropriate to the prefix character passed into them.
2273 * @param $char string
2277 function openList( $char ) {
2278 $result = $this->closeParagraph();
2280 if ( '*' === $char ) {
2281 $result .= '<ul><li>';
2282 } elseif ( '#' === $char ) {
2283 $result .= '<ol><li>';
2284 } elseif ( ':' === $char ) {
2285 $result .= '<dl><dd>';
2286 } elseif ( ';' === $char ) {
2287 $result .= '<dl><dt>';
2288 $this->mDTopen
= true;
2290 $result = '<!-- ERR 1 -->';
2298 * @param $char String
2303 function nextItem( $char ) {
2304 if ( '*' === $char ||
'#' === $char ) {
2306 } elseif ( ':' === $char ||
';' === $char ) {
2308 if ( $this->mDTopen
) {
2311 if ( ';' === $char ) {
2312 $this->mDTopen
= true;
2313 return $close . '<dt>';
2315 $this->mDTopen
= false;
2316 return $close . '<dd>';
2319 return '<!-- ERR 2 -->';
2324 * @param $char String
2329 function closeList( $char ) {
2330 if ( '*' === $char ) {
2331 $text = '</li></ul>';
2332 } elseif ( '#' === $char ) {
2333 $text = '</li></ol>';
2334 } elseif ( ':' === $char ) {
2335 if ( $this->mDTopen
) {
2336 $this->mDTopen
= false;
2337 $text = '</dt></dl>';
2339 $text = '</dd></dl>';
2342 return '<!-- ERR 3 -->';
2344 return $text . "\n";
2349 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2351 * @param $text String
2352 * @param $linestart Boolean: whether or not this is at the start of a line.
2354 * @return string the lists rendered as HTML
2356 function doBlockLevels( $text, $linestart ) {
2357 wfProfileIn( __METHOD__
);
2359 # Parsing through the text line by line. The main thing
2360 # happening here is handling of block-level elements p, pre,
2361 # and making lists from lines starting with * # : etc.
2363 $textLines = StringUtils
::explode( "\n", $text );
2365 $lastPrefix = $output = '';
2366 $this->mDTopen
= $inBlockElem = false;
2368 $paragraphStack = false;
2369 $inBlockquote = false;
2371 foreach ( $textLines as $oLine ) {
2373 if ( !$linestart ) {
2383 $lastPrefixLength = strlen( $lastPrefix );
2384 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2385 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2386 # If not in a <pre> element, scan for and figure out what prefixes are there.
2387 if ( !$this->mInPre
) {
2388 # Multiple prefixes may abut each other for nested lists.
2389 $prefixLength = strspn( $oLine, '*#:;' );
2390 $prefix = substr( $oLine, 0, $prefixLength );
2393 # ; and : are both from definition-lists, so they're equivalent
2394 # for the purposes of determining whether or not we need to open/close
2396 $prefix2 = str_replace( ';', ':', $prefix );
2397 $t = substr( $oLine, $prefixLength );
2398 $this->mInPre
= (bool)$preOpenMatch;
2400 # Don't interpret any other prefixes in preformatted text
2402 $prefix = $prefix2 = '';
2407 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2408 # Same as the last item, so no need to deal with nesting or opening stuff
2409 $output .= $this->nextItem( substr( $prefix, -1 ) );
2410 $paragraphStack = false;
2412 if ( substr( $prefix, -1 ) === ';' ) {
2413 # The one nasty exception: definition lists work like this:
2414 # ; title : definition text
2415 # So we check for : in the remainder text to split up the
2416 # title and definition, without b0rking links.
2418 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2420 $output .= $term . $this->nextItem( ':' );
2423 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2424 # We need to open or close prefixes, or both.
2426 # Either open or close a level...
2427 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2428 $paragraphStack = false;
2430 # Close all the prefixes which aren't shared.
2431 while ( $commonPrefixLength < $lastPrefixLength ) {
2432 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2433 --$lastPrefixLength;
2436 # Continue the current prefix if appropriate.
2437 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2438 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2441 # Open prefixes where appropriate.
2442 while ( $prefixLength > $commonPrefixLength ) {
2443 $char = substr( $prefix, $commonPrefixLength, 1 );
2444 $output .= $this->openList( $char );
2446 if ( ';' === $char ) {
2447 # @todo FIXME: This is dupe of code above
2448 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2450 $output .= $term . $this->nextItem( ':' );
2453 ++
$commonPrefixLength;
2455 $lastPrefix = $prefix2;
2458 # If we have no prefixes, go to paragraph mode.
2459 if ( 0 == $prefixLength ) {
2460 wfProfileIn( __METHOD__
. "-paragraph" );
2461 # No prefix (not in list)--go to paragraph mode
2462 # XXX: use a stack for nestable elements like span, table and div
2463 $openmatch = preg_match( '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2464 $closematch = preg_match(
2465 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2466 '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2467 if ( $openmatch or $closematch ) {
2468 $paragraphStack = false;
2469 # TODO bug 5718: paragraph closed
2470 $output .= $this->closeParagraph();
2471 if ( $preOpenMatch and !$preCloseMatch ) {
2472 $this->mInPre
= true;
2475 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2476 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2477 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2479 $inBlockElem = !$closematch;
2480 } elseif ( !$inBlockElem && !$this->mInPre
) {
2481 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) and !$inBlockquote ) {
2483 if ( $this->mLastSection
!== 'pre' ) {
2484 $paragraphStack = false;
2485 $output .= $this->closeParagraph() . '<pre>';
2486 $this->mLastSection
= 'pre';
2488 $t = substr( $t, 1 );
2491 if ( trim( $t ) === '' ) {
2492 if ( $paragraphStack ) {
2493 $output .= $paragraphStack . '<br />';
2494 $paragraphStack = false;
2495 $this->mLastSection
= 'p';
2497 if ( $this->mLastSection
!== 'p' ) {
2498 $output .= $this->closeParagraph();
2499 $this->mLastSection
= '';
2500 $paragraphStack = '<p>';
2502 $paragraphStack = '</p><p>';
2506 if ( $paragraphStack ) {
2507 $output .= $paragraphStack;
2508 $paragraphStack = false;
2509 $this->mLastSection
= 'p';
2510 } elseif ( $this->mLastSection
!== 'p' ) {
2511 $output .= $this->closeParagraph() . '<p>';
2512 $this->mLastSection
= 'p';
2517 wfProfileOut( __METHOD__
. "-paragraph" );
2519 # somewhere above we forget to get out of pre block (bug 785)
2520 if ( $preCloseMatch && $this->mInPre
) {
2521 $this->mInPre
= false;
2523 if ( $paragraphStack === false ) {
2524 $output .= $t . "\n";
2527 while ( $prefixLength ) {
2528 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2531 if ( $this->mLastSection
!= '' ) {
2532 $output .= '</' . $this->mLastSection
. '>';
2533 $this->mLastSection
= '';
2536 wfProfileOut( __METHOD__
);
2541 * Split up a string on ':', ignoring any occurrences inside tags
2542 * to prevent illegal overlapping.
2544 * @param string $str the string to split
2545 * @param &$before String set to everything before the ':'
2546 * @param &$after String set to everything after the ':'
2547 * @throws MWException
2548 * @return String the position of the ':', or false if none found
2550 function findColonNoLinks( $str, &$before, &$after ) {
2551 wfProfileIn( __METHOD__
);
2553 $pos = strpos( $str, ':' );
2554 if ( $pos === false ) {
2556 wfProfileOut( __METHOD__
);
2560 $lt = strpos( $str, '<' );
2561 if ( $lt === false ||
$lt > $pos ) {
2562 # Easy; no tag nesting to worry about
2563 $before = substr( $str, 0, $pos );
2564 $after = substr( $str, $pos +
1 );
2565 wfProfileOut( __METHOD__
);
2569 # Ugly state machine to walk through avoiding tags.
2570 $state = self
::COLON_STATE_TEXT
;
2572 $len = strlen( $str );
2573 for ( $i = 0; $i < $len; $i++
) {
2577 # (Using the number is a performance hack for common cases)
2578 case 0: # self::COLON_STATE_TEXT:
2581 # Could be either a <start> tag or an </end> tag
2582 $state = self
::COLON_STATE_TAGSTART
;
2585 if ( $stack == 0 ) {
2587 $before = substr( $str, 0, $i );
2588 $after = substr( $str, $i +
1 );
2589 wfProfileOut( __METHOD__
);
2592 # Embedded in a tag; don't break it.
2595 # Skip ahead looking for something interesting
2596 $colon = strpos( $str, ':', $i );
2597 if ( $colon === false ) {
2598 # Nothing else interesting
2599 wfProfileOut( __METHOD__
);
2602 $lt = strpos( $str, '<', $i );
2603 if ( $stack === 0 ) {
2604 if ( $lt === false ||
$colon < $lt ) {
2606 $before = substr( $str, 0, $colon );
2607 $after = substr( $str, $colon +
1 );
2608 wfProfileOut( __METHOD__
);
2612 if ( $lt === false ) {
2613 # Nothing else interesting to find; abort!
2614 # We're nested, but there's no close tags left. Abort!
2617 # Skip ahead to next tag start
2619 $state = self
::COLON_STATE_TAGSTART
;
2622 case 1: # self::COLON_STATE_TAG:
2627 $state = self
::COLON_STATE_TEXT
;
2630 # Slash may be followed by >?
2631 $state = self
::COLON_STATE_TAGSLASH
;
2637 case 2: # self::COLON_STATE_TAGSTART:
2640 $state = self
::COLON_STATE_CLOSETAG
;
2643 $state = self
::COLON_STATE_COMMENT
;
2646 # Illegal early close? This shouldn't happen D:
2647 $state = self
::COLON_STATE_TEXT
;
2650 $state = self
::COLON_STATE_TAG
;
2653 case 3: # self::COLON_STATE_CLOSETAG:
2658 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2659 wfProfileOut( __METHOD__
);
2662 $state = self
::COLON_STATE_TEXT
;
2665 case self
::COLON_STATE_TAGSLASH
:
2667 # Yes, a self-closed tag <blah/>
2668 $state = self
::COLON_STATE_TEXT
;
2670 # Probably we're jumping the gun, and this is an attribute
2671 $state = self
::COLON_STATE_TAG
;
2674 case 5: # self::COLON_STATE_COMMENT:
2676 $state = self
::COLON_STATE_COMMENTDASH
;
2679 case self
::COLON_STATE_COMMENTDASH
:
2681 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2683 $state = self
::COLON_STATE_COMMENT
;
2686 case self
::COLON_STATE_COMMENTDASHDASH
:
2688 $state = self
::COLON_STATE_TEXT
;
2690 $state = self
::COLON_STATE_COMMENT
;
2694 wfProfileOut( __METHOD__
);
2695 throw new MWException( "State machine error in " . __METHOD__
);
2699 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2700 wfProfileOut( __METHOD__
);
2703 wfProfileOut( __METHOD__
);
2708 * Return value of a magic variable (like PAGENAME)
2712 * @param $index integer
2713 * @param bool|\PPFrame $frame
2715 * @throws MWException
2718 function getVariableValue( $index, $frame = false ) {
2719 global $wgContLang, $wgSitename, $wgServer;
2720 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2722 if ( is_null( $this->mTitle
) ) {
2723 // If no title set, bad things are going to happen
2724 // later. Title should always be set since this
2725 // should only be called in the middle of a parse
2726 // operation (but the unit-tests do funky stuff)
2727 throw new MWException( __METHOD__
. ' Should only be '
2728 . ' called while parsing (no title set)' );
2732 * Some of these require message or data lookups and can be
2733 * expensive to check many times.
2735 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2736 if ( isset( $this->mVarCache
[$index] ) ) {
2737 return $this->mVarCache
[$index];
2741 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2742 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2744 $pageLang = $this->getFunctionLang();
2747 case 'currentmonth':
2748 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2750 case 'currentmonth1':
2751 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2753 case 'currentmonthname':
2754 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2756 case 'currentmonthnamegen':
2757 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2759 case 'currentmonthabbrev':
2760 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2763 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2766 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2769 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2772 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2774 case 'localmonthname':
2775 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2777 case 'localmonthnamegen':
2778 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2780 case 'localmonthabbrev':
2781 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2784 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2787 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2790 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2793 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2795 case 'fullpagename':
2796 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2798 case 'fullpagenamee':
2799 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2802 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2804 case 'subpagenamee':
2805 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2807 case 'rootpagename':
2808 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2810 case 'rootpagenamee':
2811 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2813 case 'basepagename':
2814 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2816 case 'basepagenamee':
2817 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2819 case 'talkpagename':
2820 if ( $this->mTitle
->canTalk() ) {
2821 $talkPage = $this->mTitle
->getTalkPage();
2822 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2827 case 'talkpagenamee':
2828 if ( $this->mTitle
->canTalk() ) {
2829 $talkPage = $this->mTitle
->getTalkPage();
2830 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2835 case 'subjectpagename':
2836 $subjPage = $this->mTitle
->getSubjectPage();
2837 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2839 case 'subjectpagenamee':
2840 $subjPage = $this->mTitle
->getSubjectPage();
2841 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2843 case 'pageid': // requested in bug 23427
2844 $pageid = $this->getTitle()->getArticleID();
2845 if ( $pageid == 0 ) {
2846 # 0 means the page doesn't exist in the database,
2847 # which means the user is previewing a new page.
2848 # The vary-revision flag must be set, because the magic word
2849 # will have a different value once the page is saved.
2850 $this->mOutput
->setFlag( 'vary-revision' );
2851 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2853 $value = $pageid ?
$pageid : null;
2856 # Let the edit saving system know we should parse the page
2857 # *after* a revision ID has been assigned.
2858 $this->mOutput
->setFlag( 'vary-revision' );
2859 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2860 $value = $this->mRevisionId
;
2863 # Let the edit saving system know we should parse the page
2864 # *after* a revision ID has been assigned. This is for null edits.
2865 $this->mOutput
->setFlag( 'vary-revision' );
2866 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2867 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2869 case 'revisionday2':
2870 # Let the edit saving system know we should parse the page
2871 # *after* a revision ID has been assigned. This is for null edits.
2872 $this->mOutput
->setFlag( 'vary-revision' );
2873 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2874 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2876 case 'revisionmonth':
2877 # Let the edit saving system know we should parse the page
2878 # *after* a revision ID has been assigned. This is for null edits.
2879 $this->mOutput
->setFlag( 'vary-revision' );
2880 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2881 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2883 case 'revisionmonth1':
2884 # Let the edit saving system know we should parse the page
2885 # *after* a revision ID has been assigned. This is for null edits.
2886 $this->mOutput
->setFlag( 'vary-revision' );
2887 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2888 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2890 case 'revisionyear':
2891 # Let the edit saving system know we should parse the page
2892 # *after* a revision ID has been assigned. This is for null edits.
2893 $this->mOutput
->setFlag( 'vary-revision' );
2894 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2895 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2897 case 'revisiontimestamp':
2898 # Let the edit saving system know we should parse the page
2899 # *after* a revision ID has been assigned. This is for null edits.
2900 $this->mOutput
->setFlag( 'vary-revision' );
2901 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2902 $value = $this->getRevisionTimestamp();
2904 case 'revisionuser':
2905 # Let the edit saving system know we should parse the page
2906 # *after* a revision ID has been assigned. This is for null edits.
2907 $this->mOutput
->setFlag( 'vary-revision' );
2908 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2909 $value = $this->getRevisionUser();
2911 case 'revisionsize':
2912 # Let the edit saving system know we should parse the page
2913 # *after* a revision ID has been assigned. This is for null edits.
2914 $this->mOutput
->setFlag( 'vary-revision' );
2915 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
2916 $value = $this->getRevisionSize();
2919 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2922 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2924 case 'namespacenumber':
2925 $value = $this->mTitle
->getNamespace();
2928 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2931 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2933 case 'subjectspace':
2934 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2936 case 'subjectspacee':
2937 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2939 case 'currentdayname':
2940 $value = $pageLang->getWeekdayName( MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2943 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2946 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2949 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2952 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2953 # int to remove the padding
2954 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2957 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2959 case 'localdayname':
2960 $value = $pageLang->getWeekdayName( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1 );
2963 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2966 $value = $pageLang->time( MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2969 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2972 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2973 # int to remove the padding
2974 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2977 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2979 case 'numberofarticles':
2980 $value = $pageLang->formatNum( SiteStats
::articles() );
2982 case 'numberoffiles':
2983 $value = $pageLang->formatNum( SiteStats
::images() );
2985 case 'numberofusers':
2986 $value = $pageLang->formatNum( SiteStats
::users() );
2988 case 'numberofactiveusers':
2989 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2991 case 'numberofpages':
2992 $value = $pageLang->formatNum( SiteStats
::pages() );
2994 case 'numberofadmins':
2995 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2997 case 'numberofedits':
2998 $value = $pageLang->formatNum( SiteStats
::edits() );
3000 case 'numberofviews':
3001 global $wgDisableCounters;
3002 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3004 case 'currenttimestamp':
3005 $value = wfTimestamp( TS_MW
, $ts );
3007 case 'localtimestamp':
3008 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3010 case 'currentversion':
3011 $value = SpecialVersion
::getVersion();
3014 return $wgArticlePath;
3020 $serverParts = wfParseUrl( $wgServer );
3021 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
3023 return $wgScriptPath;
3025 return $wgStylePath;
3026 case 'directionmark':
3027 return $pageLang->getDirMark();
3028 case 'contentlanguage':
3029 global $wgLanguageCode;
3030 return $wgLanguageCode;
3033 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
3041 $this->mVarCache
[$index] = $value;
3048 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3052 function initialiseVariables() {
3053 wfProfileIn( __METHOD__
);
3054 $variableIDs = MagicWord
::getVariableIDs();
3055 $substIDs = MagicWord
::getSubstIDs();
3057 $this->mVariables
= new MagicWordArray( $variableIDs );
3058 $this->mSubstWords
= new MagicWordArray( $substIDs );
3059 wfProfileOut( __METHOD__
);
3063 * Preprocess some wikitext and return the document tree.
3064 * This is the ghost of replace_variables().
3066 * @param string $text The text to parse
3067 * @param $flags Integer: bitwise combination of:
3068 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3069 * included. Default is to assume a direct page view.
3071 * The generated DOM tree must depend only on the input text and the flags.
3072 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3074 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3075 * change in the DOM tree for a given text, must be passed through the section identifier
3076 * in the section edit link and thus back to extractSections().
3078 * The output of this function is currently only cached in process memory, but a persistent
3079 * cache may be implemented at a later date which takes further advantage of these strict
3080 * dependency requirements.
3086 function preprocessToDom( $text, $flags = 0 ) {
3087 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3092 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3098 public static function splitWhitespace( $s ) {
3099 $ltrimmed = ltrim( $s );
3100 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3101 $trimmed = rtrim( $ltrimmed );
3102 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3104 $w2 = substr( $ltrimmed, -$diff );
3108 return array( $w1, $trimmed, $w2 );
3112 * Replace magic variables, templates, and template arguments
3113 * with the appropriate text. Templates are substituted recursively,
3114 * taking care to avoid infinite loops.
3116 * Note that the substitution depends on value of $mOutputType:
3117 * self::OT_WIKI: only {{subst:}} templates
3118 * self::OT_PREPROCESS: templates but not extension tags
3119 * self::OT_HTML: all templates and extension tags
3121 * @param string $text the text to transform
3122 * @param $frame PPFrame Object describing the arguments passed to the template.
3123 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3124 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3125 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3130 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3131 # Is there any text? Also, Prevent too big inclusions!
3132 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3135 wfProfileIn( __METHOD__
);
3137 if ( $frame === false ) {
3138 $frame = $this->getPreprocessor()->newFrame();
3139 } elseif ( !( $frame instanceof PPFrame
) ) {
3140 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3141 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3144 $dom = $this->preprocessToDom( $text );
3145 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3146 $text = $frame->expand( $dom, $flags );
3148 wfProfileOut( __METHOD__
);
3153 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3155 * @param $args array
3159 static function createAssocArgs( $args ) {
3160 $assocArgs = array();
3162 foreach ( $args as $arg ) {
3163 $eqpos = strpos( $arg, '=' );
3164 if ( $eqpos === false ) {
3165 $assocArgs[$index++
] = $arg;
3167 $name = trim( substr( $arg, 0, $eqpos ) );
3168 $value = trim( substr( $arg, $eqpos +
1 ) );
3169 if ( $value === false ) {
3172 if ( $name !== false ) {
3173 $assocArgs[$name] = $value;
3182 * Warn the user when a parser limitation is reached
3183 * Will warn at most once the user per limitation type
3185 * @param string $limitationType should be one of:
3186 * 'expensive-parserfunction' (corresponding messages:
3187 * 'expensive-parserfunction-warning',
3188 * 'expensive-parserfunction-category')
3189 * 'post-expand-template-argument' (corresponding messages:
3190 * 'post-expand-template-argument-warning',
3191 * 'post-expand-template-argument-category')
3192 * 'post-expand-template-inclusion' (corresponding messages:
3193 * 'post-expand-template-inclusion-warning',
3194 * 'post-expand-template-inclusion-category')
3195 * 'node-count-exceeded' (corresponding messages:
3196 * 'node-count-exceeded-warning',
3197 * 'node-count-exceeded-category')
3198 * 'expansion-depth-exceeded' (corresponding messages:
3199 * 'expansion-depth-exceeded-warning',
3200 * 'expansion-depth-exceeded-category')
3201 * @param int|null $current Current value
3202 * @param int|null $max Maximum allowed, when an explicit limit has been
3203 * exceeded, provide the values (optional)
3205 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3206 # does no harm if $current and $max are present but are unnecessary for the message
3207 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3208 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3209 $this->mOutput
->addWarning( $warning );
3210 $this->addTrackingCategory( "$limitationType-category" );
3214 * Return the text of a template, after recursively
3215 * replacing any variables or templates within the template.
3217 * @param array $piece the parts of the template
3218 * $piece['title']: the title, i.e. the part before the |
3219 * $piece['parts']: the parameter array
3220 * $piece['lineStart']: whether the brace was at the start of a line
3221 * @param $frame PPFrame The current frame, contains template arguments
3222 * @throws MWException
3223 * @return String: the text of the template
3226 function braceSubstitution( $piece, $frame ) {
3227 wfProfileIn( __METHOD__
);
3228 wfProfileIn( __METHOD__
. '-setup' );
3231 $found = false; # $text has been filled
3232 $nowiki = false; # wiki markup in $text should be escaped
3233 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3234 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3235 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3236 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3238 # Title object, where $text came from
3241 # $part1 is the bit before the first |, and must contain only title characters.
3242 # Various prefixes will be stripped from it later.
3243 $titleWithSpaces = $frame->expand( $piece['title'] );
3244 $part1 = trim( $titleWithSpaces );
3247 # Original title text preserved for various purposes
3248 $originalTitle = $part1;
3250 # $args is a list of argument nodes, starting from index 0, not including $part1
3251 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3252 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3253 wfProfileOut( __METHOD__
. '-setup' );
3255 $titleProfileIn = null; // profile templates
3258 wfProfileIn( __METHOD__
. '-modifiers' );
3261 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3263 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3264 # Decide whether to expand template or keep wikitext as-is.
3265 if ( $this->ot
['wiki'] ) {
3266 if ( $substMatch === false ) {
3267 $literal = true; # literal when in PST with no prefix
3269 $literal = false; # expand when in PST with subst: or safesubst:
3272 if ( $substMatch == 'subst' ) {
3273 $literal = true; # literal when not in PST with plain subst:
3275 $literal = false; # expand when not in PST with safesubst: or no prefix
3279 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3286 if ( !$found && $args->getLength() == 0 ) {
3287 $id = $this->mVariables
->matchStartToEnd( $part1 );
3288 if ( $id !== false ) {
3289 $text = $this->getVariableValue( $id, $frame );
3290 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3291 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3297 # MSG, MSGNW and RAW
3300 $mwMsgnw = MagicWord
::get( 'msgnw' );
3301 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3304 # Remove obsolete MSG:
3305 $mwMsg = MagicWord
::get( 'msg' );
3306 $mwMsg->matchStartAndRemove( $part1 );
3310 $mwRaw = MagicWord
::get( 'raw' );
3311 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3312 $forceRawInterwiki = true;
3315 wfProfileOut( __METHOD__
. '-modifiers' );
3319 wfProfileIn( __METHOD__
. '-pfunc' );
3321 $colonPos = strpos( $part1, ':' );
3322 if ( $colonPos !== false ) {
3323 $func = substr( $part1, 0, $colonPos );
3324 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3325 for ( $i = 0; $i < $args->getLength(); $i++
) {
3326 $funcArgs[] = $args->item( $i );
3329 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3330 } catch ( Exception
$ex ) {
3331 wfProfileOut( __METHOD__
. '-pfunc' );
3332 wfProfileOut( __METHOD__
);
3336 # The interface for parser functions allows for extracting
3337 # flags into the local scope. Extract any forwarded flags
3341 wfProfileOut( __METHOD__
. '-pfunc' );
3344 # Finish mangling title and then check for loops.
3345 # Set $title to a Title object and $titleText to the PDBK
3348 # Split the title into page and subpage
3350 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3351 if ( $part1 !== $relative ) {
3353 $ns = $this->mTitle
->getNamespace();
3355 $title = Title
::newFromText( $part1, $ns );
3357 $titleText = $title->getPrefixedText();
3358 # Check for language variants if the template is not found
3359 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3360 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3362 # Do recursion depth check
3363 $limit = $this->mOptions
->getMaxTemplateDepth();
3364 if ( $frame->depth
>= $limit ) {
3366 $text = '<span class="error">'
3367 . wfMessage( 'parser-template-recursion-depth-warning' )
3368 ->numParams( $limit )->inContentLanguage()->text()
3374 # Load from database
3375 if ( !$found && $title ) {
3376 if ( !Profiler
::instance()->isPersistent() ) {
3377 # Too many unique items can kill profiling DBs/collectors
3378 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3379 wfProfileIn( $titleProfileIn ); // template in
3381 wfProfileIn( __METHOD__
. '-loadtpl' );
3382 if ( !$title->isExternal() ) {
3383 if ( $title->isSpecialPage()
3384 && $this->mOptions
->getAllowSpecialInclusion()
3385 && $this->ot
['html'] )
3387 // Pass the template arguments as URL parameters.
3388 // "uselang" will have no effect since the Language object
3389 // is forced to the one defined in ParserOptions.
3390 $pageArgs = array();
3391 for ( $i = 0; $i < $args->getLength(); $i++
) {
3392 $bits = $args->item( $i )->splitArg();
3393 if ( strval( $bits['index'] ) === '' ) {
3394 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3395 $value = trim( $frame->expand( $bits['value'] ) );
3396 $pageArgs[$name] = $value;
3400 // Create a new context to execute the special page
3401 $context = new RequestContext
;
3402 $context->setTitle( $title );
3403 $context->setRequest( new FauxRequest( $pageArgs ) );
3404 $context->setUser( $this->getUser() );
3405 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3406 $ret = SpecialPageFactory
::capturePath( $title, $context );
3408 $text = $context->getOutput()->getHTML();
3409 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3412 $this->disableCache();
3414 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3415 $found = false; # access denied
3416 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3418 list( $text, $title ) = $this->getTemplateDom( $title );
3419 if ( $text !== false ) {
3425 # If the title is valid but undisplayable, make a link to it
3426 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3427 $text = "[[:$titleText]]";
3430 } elseif ( $title->isTrans() ) {
3431 # Interwiki transclusion
3432 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3433 $text = $this->interwikiTransclude( $title, 'render' );
3436 $text = $this->interwikiTransclude( $title, 'raw' );
3437 # Preprocess it like a template
3438 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3444 # Do infinite loop check
3445 # This has to be done after redirect resolution to avoid infinite loops via redirects
3446 if ( !$frame->loopCheck( $title ) ) {
3448 $text = '<span class="error">'
3449 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3451 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3453 wfProfileOut( __METHOD__
. '-loadtpl' );
3456 # If we haven't found text to substitute by now, we're done
3457 # Recover the source wikitext and return it
3459 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3460 if ( $titleProfileIn ) {
3461 wfProfileOut( $titleProfileIn ); // template out
3463 wfProfileOut( __METHOD__
);
3464 return array( 'object' => $text );
3467 # Expand DOM-style return values in a child frame
3468 if ( $isChildObj ) {
3469 # Clean up argument array
3470 $newFrame = $frame->newChild( $args, $title );
3473 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3474 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3475 # Expansion is eligible for the empty-frame cache
3476 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3477 $text = $this->mTplExpandCache
[$titleText];
3479 $text = $newFrame->expand( $text );
3480 $this->mTplExpandCache
[$titleText] = $text;
3483 # Uncached expansion
3484 $text = $newFrame->expand( $text );
3487 if ( $isLocalObj && $nowiki ) {
3488 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3489 $isLocalObj = false;
3492 if ( $titleProfileIn ) {
3493 wfProfileOut( $titleProfileIn ); // template out
3496 # Replace raw HTML by a placeholder
3498 $text = $this->insertStripItem( $text );
3499 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3500 # Escape nowiki-style return values
3501 $text = wfEscapeWikiText( $text );
3502 } elseif ( is_string( $text )
3503 && !$piece['lineStart']
3504 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3506 # Bug 529: if the template begins with a table or block-level
3507 # element, it should be treated as beginning a new line.
3508 # This behavior is somewhat controversial.
3509 $text = "\n" . $text;
3512 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3513 # Error, oversize inclusion
3514 if ( $titleText !== false ) {
3515 # Make a working, properly escaped link if possible (bug 23588)
3516 $text = "[[:$titleText]]";
3518 # This will probably not be a working link, but at least it may
3519 # provide some hint of where the problem is
3520 preg_replace( '/^:/', '', $originalTitle );
3521 $text = "[[:$originalTitle]]";
3523 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3524 $this->limitationWarn( 'post-expand-template-inclusion' );
3527 if ( $isLocalObj ) {
3528 $ret = array( 'object' => $text );
3530 $ret = array( 'text' => $text );
3533 wfProfileOut( __METHOD__
);
3538 * Call a parser function and return an array with text and flags.
3540 * The returned array will always contain a boolean 'found', indicating
3541 * whether the parser function was found or not. It may also contain the
3543 * text: string|object, resulting wikitext or PP DOM object
3544 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3545 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3546 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3547 * nowiki: bool, wiki markup in $text should be escaped
3550 * @param $frame PPFrame The current frame, contains template arguments
3551 * @param $function string Function name
3552 * @param $args array Arguments to the function
3555 public function callParserFunction( $frame, $function, array $args = array() ) {
3558 wfProfileIn( __METHOD__
);
3560 # Case sensitive functions
3561 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3562 $function = $this->mFunctionSynonyms
[1][$function];
3564 # Case insensitive functions
3565 $function = $wgContLang->lc( $function );
3566 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3567 $function = $this->mFunctionSynonyms
[0][$function];
3569 wfProfileOut( __METHOD__
);
3570 return array( 'found' => false );
3574 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3575 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3577 # Workaround for PHP bug 35229 and similar
3578 if ( !is_callable( $callback ) ) {
3579 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3580 wfProfileOut( __METHOD__
);
3581 throw new MWException( "Tag hook for $function is not callable\n" );
3584 $allArgs = array( &$this );
3585 if ( $flags & SFH_OBJECT_ARGS
) {
3586 # Convert arguments to PPNodes and collect for appending to $allArgs
3587 $funcArgs = array();
3588 foreach ( $args as $k => $v ) {
3589 if ( $v instanceof PPNode ||
$k === 0 ) {
3592 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3596 # Add a frame parameter, and pass the arguments as an array
3597 $allArgs[] = $frame;
3598 $allArgs[] = $funcArgs;
3600 # Convert arguments to plain text and append to $allArgs
3601 foreach ( $args as $k => $v ) {
3602 if ( $v instanceof PPNode
) {
3603 $allArgs[] = trim( $frame->expand( $v ) );
3604 } elseif ( is_int( $k ) && $k >= 0 ) {
3605 $allArgs[] = trim( $v );
3607 $allArgs[] = trim( "$k=$v" );
3612 $result = call_user_func_array( $callback, $allArgs );
3614 # The interface for function hooks allows them to return a wikitext
3615 # string or an array containing the string and any flags. This mungs
3616 # things around to match what this method should return.
3617 if ( !is_array( $result ) ) {
3623 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3624 $result['text'] = $result[0];
3626 unset( $result[0] );
3633 $preprocessFlags = 0;
3634 if ( isset( $result['noparse'] ) ) {
3635 $noparse = $result['noparse'];
3637 if ( isset( $result['preprocessFlags'] ) ) {
3638 $preprocessFlags = $result['preprocessFlags'];
3642 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3643 $result['isChildObj'] = true;
3645 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3646 wfProfileOut( __METHOD__
);
3652 * Get the semi-parsed DOM representation of a template with a given title,
3653 * and its redirect destination title. Cached.
3655 * @param $title Title
3659 function getTemplateDom( $title ) {
3660 $cacheTitle = $title;
3661 $titleText = $title->getPrefixedDBkey();
3663 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3664 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3665 $title = Title
::makeTitle( $ns, $dbk );
3666 $titleText = $title->getPrefixedDBkey();
3668 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3669 return array( $this->mTplDomCache
[$titleText], $title );
3672 # Cache miss, go to the database
3673 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3675 if ( $text === false ) {
3676 $this->mTplDomCache
[$titleText] = false;
3677 return array( false, $title );
3680 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3681 $this->mTplDomCache
[$titleText] = $dom;
3683 if ( !$title->equals( $cacheTitle ) ) {
3684 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3685 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3688 return array( $dom, $title );
3692 * Fetch the unparsed text of a template and register a reference to it.
3693 * @param Title $title
3694 * @return Array ( string or false, Title )
3696 function fetchTemplateAndTitle( $title ) {
3697 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3698 $stuff = call_user_func( $templateCb, $title, $this );
3699 $text = $stuff['text'];
3700 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3701 if ( isset( $stuff['deps'] ) ) {
3702 foreach ( $stuff['deps'] as $dep ) {
3703 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3704 if ( $dep['title']->equals( $this->getTitle() ) ) {
3705 // If we transclude ourselves, the final result
3706 // will change based on the new version of the page
3707 $this->mOutput
->setFlag( 'vary-revision' );
3711 return array( $text, $finalTitle );
3715 * Fetch the unparsed text of a template and register a reference to it.
3716 * @param Title $title
3717 * @return mixed string or false
3719 function fetchTemplate( $title ) {
3720 $rv = $this->fetchTemplateAndTitle( $title );
3725 * Static function to get a template
3726 * Can be overridden via ParserOptions::setTemplateCallback().
3728 * @param $title Title
3729 * @param $parser Parser
3733 static function statelessFetchTemplate( $title, $parser = false ) {
3734 $text = $skip = false;
3735 $finalTitle = $title;
3738 # Loop to fetch the article, with up to 1 redirect
3739 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3740 # Give extensions a chance to select the revision instead
3741 $id = false; # Assume current
3742 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3743 array( $parser, $title, &$skip, &$id ) );
3749 'page_id' => $title->getArticleID(),
3756 ? Revision
::newFromId( $id )
3757 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3758 $rev_id = $rev ?
$rev->getId() : 0;
3759 # If there is no current revision, there is no page
3760 if ( $id === false && !$rev ) {
3761 $linkCache = LinkCache
::singleton();
3762 $linkCache->addBadLinkObj( $title );
3767 'page_id' => $title->getArticleID(),
3768 'rev_id' => $rev_id );
3769 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3770 # We fetched a rev from a different title; register it too...
3772 'title' => $rev->getTitle(),
3773 'page_id' => $rev->getPage(),
3774 'rev_id' => $rev_id );
3778 $content = $rev->getContent();
3779 $text = $content ?
$content->getWikitextForTransclusion() : null;
3781 if ( $text === false ||
$text === null ) {
3785 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3787 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3788 if ( !$message->exists() ) {
3792 $content = $message->content();
3793 $text = $message->plain();
3801 $finalTitle = $title;
3802 $title = $content->getRedirectTarget();
3806 'finalTitle' => $finalTitle,
3811 * Fetch a file and its title and register a reference to it.
3812 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3813 * @param Title $title
3814 * @param array $options Array of options to RepoGroup::findFile
3817 function fetchFile( $title, $options = array() ) {
3818 $res = $this->fetchFileAndTitle( $title, $options );
3823 * Fetch a file and its title and register a reference to it.
3824 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3825 * @param Title $title
3826 * @param array $options Array of options to RepoGroup::findFile
3827 * @return Array ( File or false, Title of file )
3829 function fetchFileAndTitle( $title, $options = array() ) {
3830 $file = $this->fetchFileNoRegister( $title, $options );
3832 $time = $file ?
$file->getTimestamp() : false;
3833 $sha1 = $file ?
$file->getSha1() : false;
3834 # Register the file as a dependency...
3835 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3836 if ( $file && !$title->equals( $file->getTitle() ) ) {
3837 # Update fetched file title
3838 $title = $file->getTitle();
3839 if ( is_null( $file->getRedirectedTitle() ) ) {
3840 # This file was not a redirect, but the title does not match.
3841 # Register under the new name because otherwise the link will
3843 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3846 return array( $file, $title );
3850 * Helper function for fetchFileAndTitle.
3852 * Also useful if you need to fetch a file but not use it yet,
3853 * for example to get the file's handler.
3855 * @param Title $title
3856 * @param array $options Array of options to RepoGroup::findFile
3857 * @return File or false
3859 protected function fetchFileNoRegister( $title, $options = array() ) {
3860 if ( isset( $options['broken'] ) ) {
3861 $file = false; // broken thumbnail forced by hook
3862 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3863 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3864 } else { // get by (name,timestamp)
3865 $file = wfFindFile( $title, $options );
3871 * Transclude an interwiki link.
3873 * @param $title Title
3878 function interwikiTransclude( $title, $action ) {
3879 global $wgEnableScaryTranscluding;
3881 if ( !$wgEnableScaryTranscluding ) {
3882 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3885 $url = $title->getFullURL( array( 'action' => $action ) );
3887 if ( strlen( $url ) > 255 ) {
3888 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3890 return $this->fetchScaryTemplateMaybeFromCache( $url );
3894 * @param $url string
3895 * @return Mixed|String
3897 function fetchScaryTemplateMaybeFromCache( $url ) {
3898 global $wgTranscludeCacheExpiry;
3899 $dbr = wfGetDB( DB_SLAVE
);
3900 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3901 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3902 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3904 return $obj->tc_contents
;
3907 $req = MWHttpRequest
::factory( $url );
3908 $status = $req->execute(); // Status object
3909 if ( $status->isOK() ) {
3910 $text = $req->getContent();
3911 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3912 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3914 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3917 $dbw = wfGetDB( DB_MASTER
);
3918 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3920 'tc_time' => $dbw->timestamp( time() ),
3921 'tc_contents' => $text
3927 * Triple brace replacement -- used for template arguments
3930 * @param $piece array
3931 * @param $frame PPFrame
3935 function argSubstitution( $piece, $frame ) {
3936 wfProfileIn( __METHOD__
);
3939 $parts = $piece['parts'];
3940 $nameWithSpaces = $frame->expand( $piece['title'] );
3941 $argName = trim( $nameWithSpaces );
3943 $text = $frame->getArgument( $argName );
3944 if ( $text === false && $parts->getLength() > 0
3948 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3951 # No match in frame, use the supplied default
3952 $object = $parts->item( 0 )->getChildren();
3954 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3955 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3956 $this->limitationWarn( 'post-expand-template-argument' );
3959 if ( $text === false && $object === false ) {
3961 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3963 if ( $error !== false ) {
3966 if ( $object !== false ) {
3967 $ret = array( 'object' => $object );
3969 $ret = array( 'text' => $text );
3972 wfProfileOut( __METHOD__
);
3977 * Return the text to be used for a given extension tag.
3978 * This is the ghost of strip().
3980 * @param array $params Associative array of parameters:
3981 * name PPNode for the tag name
3982 * attr PPNode for unparsed text where tag attributes are thought to be
3983 * attributes Optional associative array of parsed attributes
3984 * inner Contents of extension element
3985 * noClose Original text did not have a close tag
3986 * @param $frame PPFrame
3988 * @throws MWException
3991 function extensionSubstitution( $params, $frame ) {
3992 $name = $frame->expand( $params['name'] );
3993 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3994 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3995 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3997 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3998 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3999 if ( $isFunctionTag ) {
4000 $markerType = 'none';
4002 $markerType = 'general';
4004 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4005 $name = strtolower( $name );
4006 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4007 if ( isset( $params['attributes'] ) ) {
4008 $attributes = $attributes +
$params['attributes'];
4011 if ( isset( $this->mTagHooks
[$name] ) ) {
4012 # Workaround for PHP bug 35229 and similar
4013 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4014 throw new MWException( "Tag hook for $name is not callable\n" );
4016 $output = call_user_func_array( $this->mTagHooks
[$name],
4017 array( $content, $attributes, $this, $frame ) );
4018 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4019 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4020 if ( !is_callable( $callback ) ) {
4021 throw new MWException( "Tag hook for $name is not callable\n" );
4024 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4026 $output = '<span class="error">Invalid tag extension name: ' .
4027 htmlspecialchars( $name ) . '</span>';
4030 if ( is_array( $output ) ) {
4031 # Extract flags to local scope (to override $markerType)
4033 $output = $flags[0];
4038 if ( is_null( $attrText ) ) {
4041 if ( isset( $params['attributes'] ) ) {
4042 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4043 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4044 htmlspecialchars( $attrValue ) . '"';
4047 if ( $content === null ) {
4048 $output = "<$name$attrText/>";
4050 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4051 $output = "<$name$attrText>$content$close";
4055 if ( $markerType === 'none' ) {
4057 } elseif ( $markerType === 'nowiki' ) {
4058 $this->mStripState
->addNoWiki( $marker, $output );
4059 } elseif ( $markerType === 'general' ) {
4060 $this->mStripState
->addGeneral( $marker, $output );
4062 throw new MWException( __METHOD__
. ': invalid marker type' );
4068 * Increment an include size counter
4070 * @param string $type the type of expansion
4071 * @param $size Integer: the size of the text
4072 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4074 function incrementIncludeSize( $type, $size ) {
4075 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4078 $this->mIncludeSizes
[$type] +
= $size;
4084 * Increment the expensive function count
4086 * @return Boolean: false if the limit has been exceeded
4088 function incrementExpensiveFunctionCount() {
4089 $this->mExpensiveFunctionCount++
;
4090 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4094 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4095 * Fills $this->mDoubleUnderscores, returns the modified text
4097 * @param $text string
4101 function doDoubleUnderscore( $text ) {
4102 wfProfileIn( __METHOD__
);
4104 # The position of __TOC__ needs to be recorded
4105 $mw = MagicWord
::get( 'toc' );
4106 if ( $mw->match( $text ) ) {
4107 $this->mShowToc
= true;
4108 $this->mForceTocPosition
= true;
4110 # Set a placeholder. At the end we'll fill it in with the TOC.
4111 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4113 # Only keep the first one.
4114 $text = $mw->replace( '', $text );
4117 # Now match and remove the rest of them
4118 $mwa = MagicWord
::getDoubleUnderscoreArray();
4119 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4121 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4122 $this->mOutput
->mNoGallery
= true;
4124 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4125 $this->mShowToc
= false;
4127 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4128 $this->addTrackingCategory( 'hidden-category-category' );
4130 # (bug 8068) Allow control over whether robots index a page.
4132 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4133 # is not desirable, the last one on the page should win.
4134 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4135 $this->mOutput
->setIndexPolicy( 'noindex' );
4136 $this->addTrackingCategory( 'noindex-category' );
4138 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4139 $this->mOutput
->setIndexPolicy( 'index' );
4140 $this->addTrackingCategory( 'index-category' );
4143 # Cache all double underscores in the database
4144 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4145 $this->mOutput
->setProperty( $key, '' );
4148 wfProfileOut( __METHOD__
);
4153 * Add a tracking category, getting the title from a system message,
4154 * or print a debug message if the title is invalid.
4156 * @param string $msg message key
4157 * @return Boolean: whether the addition was successful
4159 public function addTrackingCategory( $msg ) {
4160 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4161 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4164 // Important to parse with correct title (bug 31469)
4165 $cat = wfMessage( $msg )
4166 ->title( $this->getTitle() )
4167 ->inContentLanguage()
4170 # Allow tracking categories to be disabled by setting them to "-"
4171 if ( $cat === '-' ) {
4175 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4176 if ( $containerCategory ) {
4177 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4180 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4186 * This function accomplishes several tasks:
4187 * 1) Auto-number headings if that option is enabled
4188 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4189 * 3) Add a Table of contents on the top for users who have enabled the option
4190 * 4) Auto-anchor headings
4192 * It loops through all headlines, collects the necessary data, then splits up the
4193 * string and re-inserts the newly formatted headlines.
4195 * @param $text String
4196 * @param string $origText original, untouched wikitext
4197 * @param $isMain Boolean
4198 * @return mixed|string
4201 function formatHeadings( $text, $origText, $isMain = true ) {
4202 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4204 # Inhibit editsection links if requested in the page
4205 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4206 $maybeShowEditLink = $showEditLink = false;
4208 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4209 $showEditLink = $this->mOptions
->getEditSection();
4211 if ( $showEditLink ) {
4212 $this->mOutput
->setEditSectionTokens( true );
4215 # Get all headlines for numbering them and adding funky stuff like [edit]
4216 # links - this is for later, but we need the number of headlines right now
4218 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4220 # if there are fewer than 4 headlines in the article, do not show TOC
4221 # unless it's been explicitly enabled.
4222 $enoughToc = $this->mShowToc
&&
4223 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4225 # Allow user to stipulate that a page should have a "new section"
4226 # link added via __NEWSECTIONLINK__
4227 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4228 $this->mOutput
->setNewSection( true );
4231 # Allow user to remove the "new section"
4232 # link via __NONEWSECTIONLINK__
4233 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4234 $this->mOutput
->hideNewSection( true );
4237 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4238 # override above conditions and always show TOC above first header
4239 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4240 $this->mShowToc
= true;
4248 # Ugh .. the TOC should have neat indentation levels which can be
4249 # passed to the skin functions. These are determined here
4253 $sublevelCount = array();
4254 $levelCount = array();
4259 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4260 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4261 $oldType = $this->mOutputType
;
4262 $this->setOutputType( self
::OT_WIKI
);
4263 $frame = $this->getPreprocessor()->newFrame();
4264 $root = $this->preprocessToDom( $origText );
4265 $node = $root->getFirstChild();
4270 foreach ( $matches[3] as $headline ) {
4271 $isTemplate = false;
4273 $sectionIndex = false;
4275 $markerMatches = array();
4276 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4277 $serial = $markerMatches[1];
4278 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4279 $isTemplate = ( $titleText != $baseTitleText );
4280 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4284 $prevlevel = $level;
4286 $level = $matches[1][$headlineCount];
4288 if ( $level > $prevlevel ) {
4289 # Increase TOC level
4291 $sublevelCount[$toclevel] = 0;
4292 if ( $toclevel < $wgMaxTocLevel ) {
4293 $prevtoclevel = $toclevel;
4294 $toc .= Linker
::tocIndent();
4297 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4298 # Decrease TOC level, find level to jump to
4300 for ( $i = $toclevel; $i > 0; $i-- ) {
4301 if ( $levelCount[$i] == $level ) {
4302 # Found last matching level
4305 } elseif ( $levelCount[$i] < $level ) {
4306 # Found first matching level below current level
4314 if ( $toclevel < $wgMaxTocLevel ) {
4315 if ( $prevtoclevel < $wgMaxTocLevel ) {
4316 # Unindent only if the previous toc level was shown :p
4317 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4318 $prevtoclevel = $toclevel;
4320 $toc .= Linker
::tocLineEnd();
4324 # No change in level, end TOC line
4325 if ( $toclevel < $wgMaxTocLevel ) {
4326 $toc .= Linker
::tocLineEnd();
4330 $levelCount[$toclevel] = $level;
4332 # count number of headlines for each level
4333 $sublevelCount[$toclevel]++
;
4335 for ( $i = 1; $i <= $toclevel; $i++
) {
4336 if ( !empty( $sublevelCount[$i] ) ) {
4340 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4345 # The safe header is a version of the header text safe to use for links
4347 # Remove link placeholders by the link text.
4348 # <!--LINK number-->
4350 # link text with suffix
4351 # Do this before unstrip since link text can contain strip markers
4352 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4354 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4355 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4357 # Strip out HTML (first regex removes any tag not allowed)
4359 # * <sup> and <sub> (bug 8393)
4362 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4364 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4365 # to allow setting directionality in toc items.
4366 $tocline = preg_replace(
4367 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4368 array( '', '<$1>' ),
4371 $tocline = trim( $tocline );
4373 # For the anchor, strip out HTML-y stuff period
4374 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4375 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4377 # Save headline for section edit hint before it's escaped
4378 $headlineHint = $safeHeadline;
4380 if ( $wgExperimentalHtmlIds ) {
4381 # For reverse compatibility, provide an id that's
4382 # HTML4-compatible, like we used to.
4384 # It may be worth noting, academically, that it's possible for
4385 # the legacy anchor to conflict with a non-legacy headline
4386 # anchor on the page. In this case likely the "correct" thing
4387 # would be to either drop the legacy anchors or make sure
4388 # they're numbered first. However, this would require people
4389 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4390 # manually, so let's not bother worrying about it.
4391 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4392 array( 'noninitial', 'legacy' ) );
4393 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4395 if ( $legacyHeadline == $safeHeadline ) {
4396 # No reason to have both (in fact, we can't)
4397 $legacyHeadline = false;
4400 $legacyHeadline = false;
4401 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4405 # HTML names must be case-insensitively unique (bug 10721).
4406 # This does not apply to Unicode characters per
4407 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4408 # @todo FIXME: We may be changing them depending on the current locale.
4409 $arrayKey = strtolower( $safeHeadline );
4410 if ( $legacyHeadline === false ) {
4411 $legacyArrayKey = false;
4413 $legacyArrayKey = strtolower( $legacyHeadline );
4416 # count how many in assoc. array so we can track dupes in anchors
4417 if ( isset( $refers[$arrayKey] ) ) {
4418 $refers[$arrayKey]++
;
4420 $refers[$arrayKey] = 1;
4422 if ( isset( $refers[$legacyArrayKey] ) ) {
4423 $refers[$legacyArrayKey]++
;
4425 $refers[$legacyArrayKey] = 1;
4428 # Don't number the heading if it is the only one (looks silly)
4429 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4430 # the two are different if the line contains a link
4431 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4434 # Create the anchor for linking from the TOC to the section
4435 $anchor = $safeHeadline;
4436 $legacyAnchor = $legacyHeadline;
4437 if ( $refers[$arrayKey] > 1 ) {
4438 $anchor .= '_' . $refers[$arrayKey];
4440 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4441 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4443 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4444 $toc .= Linker
::tocLine( $anchor, $tocline,
4445 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4448 # Add the section to the section tree
4449 # Find the DOM node for this header
4450 while ( $node && !$isTemplate ) {
4451 if ( $node->getName() === 'h' ) {
4452 $bits = $node->splitHeading();
4453 if ( $bits['i'] == $sectionIndex ) {
4457 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4458 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4459 $node = $node->getNextSibling();
4462 'toclevel' => $toclevel,
4465 'number' => $numbering,
4466 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4467 'fromtitle' => $titleText,
4468 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4469 'anchor' => $anchor,
4472 # give headline the correct <h#> tag
4473 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4474 // Output edit section links as markers with styles that can be customized by skins
4475 if ( $isTemplate ) {
4476 # Put a T flag in the section identifier, to indicate to extractSections()
4477 # that sections inside <includeonly> should be counted.
4478 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4480 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4482 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4483 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4484 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4485 // so we don't have to worry about a user trying to input one of these markers directly.
4486 // We use a page and section attribute to stop the language converter from converting these important bits
4487 // of data, but put the headline hint inside a content block because the language converter is supposed to
4488 // be able to convert that piece of data.
4489 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4490 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4491 if ( isset( $editlinkArgs[2] ) ) {
4492 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4499 $head[$headlineCount] = Linker
::makeHeadline( $level,
4500 $matches['attrib'][$headlineCount], $anchor, $headline,
4501 $editlink, $legacyAnchor );
4506 $this->setOutputType( $oldType );
4508 # Never ever show TOC if no headers
4509 if ( $numVisible < 1 ) {
4514 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4515 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4517 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4518 $this->mOutput
->setTOCHTML( $toc );
4522 $this->mOutput
->setSections( $tocraw );
4525 # split up and insert constructed headlines
4526 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4529 // build an array of document sections
4530 $sections = array();
4531 foreach ( $blocks as $block ) {
4532 // $head is zero-based, sections aren't.
4533 if ( empty( $head[$i - 1] ) ) {
4534 $sections[$i] = $block;
4536 $sections[$i] = $head[$i - 1] . $block;
4540 * Send a hook, one per section.
4541 * The idea here is to be able to make section-level DIVs, but to do so in a
4542 * lower-impact, more correct way than r50769
4545 * $section : the section number
4546 * &$sectionContent : ref to the content of the section
4547 * $showEditLinks : boolean describing whether this section has an edit link
4549 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4554 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4555 // append the TOC at the beginning
4556 // Top anchor now in skin
4557 $sections[0] = $sections[0] . $toc . "\n";
4560 $full .= join( '', $sections );
4562 if ( $this->mForceTocPosition
) {
4563 return str_replace( '<!--MWTOC-->', $toc, $full );
4570 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4571 * conversion, substitting signatures, {{subst:}} templates, etc.
4573 * @param string $text the text to transform
4574 * @param $title Title: the Title object for the current article
4575 * @param $user User: the User object describing the current user
4576 * @param $options ParserOptions: parsing options
4577 * @param $clearState Boolean: whether to clear the parser state first
4578 * @return String: the altered wiki markup
4580 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4581 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4582 $this->setUser( $user );
4587 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4588 if ( $options->getPreSaveTransform() ) {
4589 $text = $this->pstPass2( $text, $user );
4591 $text = $this->mStripState
->unstripBoth( $text );
4593 $this->setUser( null ); #Reset
4599 * Pre-save transform helper function
4602 * @param $text string
4607 function pstPass2( $text, $user ) {
4610 # Note: This is the timestamp saved as hardcoded wikitext to
4611 # the database, we use $wgContLang here in order to give
4612 # everyone the same signature and use the default one rather
4613 # than the one selected in each user's preferences.
4614 # (see also bug 12815)
4615 $ts = $this->mOptions
->getTimestamp();
4616 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4617 $ts = $timestamp->format( 'YmdHis' );
4618 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4620 # Allow translation of timezones through wiki. format() can return
4621 # whatever crap the system uses, localised or not, so we cannot
4622 # ship premade translations.
4623 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4624 $msg = wfMessage( $key )->inContentLanguage();
4625 if ( $msg->exists() ) {
4626 $tzMsg = $msg->text();
4629 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4631 # Variable replacement
4632 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4633 $text = $this->replaceVariables( $text );
4635 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4636 # which may corrupt this parser instance via its wfMessage()->text() call-
4639 $sigText = $this->getUserSig( $user );
4640 $text = strtr( $text, array(
4642 '~~~~' => "$sigText $d",
4646 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4647 $tc = '[' . Title
::legalChars() . ']';
4648 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4650 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4651 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4652 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4653 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4655 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4656 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4657 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4658 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4660 $t = $this->mTitle
->getText();
4662 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4663 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4664 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4665 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4667 # if there's no context, don't bother duplicating the title
4668 $text = preg_replace( $p2, '[[\\1]]', $text );
4671 # Trim trailing whitespace
4672 $text = rtrim( $text );
4678 * Fetch the user's signature text, if any, and normalize to
4679 * validated, ready-to-insert wikitext.
4680 * If you have pre-fetched the nickname or the fancySig option, you can
4681 * specify them here to save a database query.
4682 * Do not reuse this parser instance after calling getUserSig(),
4683 * as it may have changed if it's the $wgParser.
4686 * @param string|bool $nickname nickname to use or false to use user's default nickname
4687 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4688 * or null to use default value
4691 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4692 global $wgMaxSigChars;
4694 $username = $user->getName();
4696 # If not given, retrieve from the user object.
4697 if ( $nickname === false ) {
4698 $nickname = $user->getOption( 'nickname' );
4701 if ( is_null( $fancySig ) ) {
4702 $fancySig = $user->getBoolOption( 'fancysig' );
4705 $nickname = $nickname == null ?
$username : $nickname;
4707 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4708 $nickname = $username;
4709 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4710 } elseif ( $fancySig !== false ) {
4711 # Sig. might contain markup; validate this
4712 if ( $this->validateSig( $nickname ) !== false ) {
4713 # Validated; clean up (if needed) and return it
4714 return $this->cleanSig( $nickname, true );
4716 # Failed to validate; fall back to the default
4717 $nickname = $username;
4718 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4722 # Make sure nickname doesnt get a sig in a sig
4723 $nickname = self
::cleanSigInSig( $nickname );
4725 # If we're still here, make it a link to the user page
4726 $userText = wfEscapeWikiText( $username );
4727 $nickText = wfEscapeWikiText( $nickname );
4728 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4730 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4734 * Check that the user's signature contains no bad XML
4736 * @param $text String
4737 * @return mixed An expanded string, or false if invalid.
4739 function validateSig( $text ) {
4740 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4744 * Clean up signature text
4746 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4747 * 2) Substitute all transclusions
4749 * @param $text String
4750 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4751 * @return String: signature text
4753 public function cleanSig( $text, $parsing = false ) {
4756 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4759 # Option to disable this feature
4760 if ( !$this->mOptions
->getCleanSignatures() ) {
4764 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4765 # => Move this logic to braceSubstitution()
4766 $substWord = MagicWord
::get( 'subst' );
4767 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4768 $substText = '{{' . $substWord->getSynonym( 0 );
4770 $text = preg_replace( $substRegex, $substText, $text );
4771 $text = self
::cleanSigInSig( $text );
4772 $dom = $this->preprocessToDom( $text );
4773 $frame = $this->getPreprocessor()->newFrame();
4774 $text = $frame->expand( $dom );
4777 $text = $this->mStripState
->unstripBoth( $text );
4784 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4786 * @param $text String
4787 * @return String: signature text with /~{3,5}/ removed
4789 public static function cleanSigInSig( $text ) {
4790 $text = preg_replace( '/~{3,5}/', '', $text );
4795 * Set up some variables which are usually set up in parse()
4796 * so that an external function can call some class members with confidence
4798 * @param $title Title|null
4799 * @param $options ParserOptions
4800 * @param $outputType
4801 * @param $clearState bool
4803 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4804 $this->startParse( $title, $options, $outputType, $clearState );
4808 * @param $title Title|null
4809 * @param $options ParserOptions
4810 * @param $outputType
4811 * @param $clearState bool
4813 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4814 $this->setTitle( $title );
4815 $this->mOptions
= $options;
4816 $this->setOutputType( $outputType );
4817 if ( $clearState ) {
4818 $this->clearState();
4823 * Wrapper for preprocess()
4825 * @param string $text the text to preprocess
4826 * @param $options ParserOptions: options
4827 * @param $title Title object or null to use $wgTitle
4830 public function transformMsg( $text, $options, $title = null ) {
4831 static $executing = false;
4833 # Guard against infinite recursion
4839 wfProfileIn( __METHOD__
);
4845 $text = $this->preprocess( $text, $title, $options );
4848 wfProfileOut( __METHOD__
);
4853 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4854 * The callback should have the following form:
4855 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4857 * Transform and return $text. Use $parser for any required context, e.g. use
4858 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4860 * Hooks may return extended information by returning an array, of which the
4861 * first numbered element (index 0) must be the return string, and all other
4862 * entries are extracted into local variables within an internal function
4863 * in the Parser class.
4865 * This interface (introduced r61913) appears to be undocumented, but
4866 * 'markerName' is used by some core tag hooks to override which strip
4867 * array their results are placed in. **Use great caution if attempting
4868 * this interface, as it is not documented and injudicious use could smash
4869 * private variables.**
4871 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4872 * @param $callback Mixed: the callback function (and object) to use for the tag
4873 * @throws MWException
4874 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4876 public function setHook( $tag, $callback ) {
4877 $tag = strtolower( $tag );
4878 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4879 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4881 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4882 $this->mTagHooks
[$tag] = $callback;
4883 if ( !in_array( $tag, $this->mStripList
) ) {
4884 $this->mStripList
[] = $tag;
4891 * As setHook(), but letting the contents be parsed.
4893 * Transparent tag hooks are like regular XML-style tag hooks, except they
4894 * operate late in the transformation sequence, on HTML instead of wikitext.
4896 * This is probably obsoleted by things dealing with parser frames?
4897 * The only extension currently using it is geoserver.
4900 * @todo better document or deprecate this
4902 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4903 * @param $callback Mixed: the callback function (and object) to use for the tag
4904 * @throws MWException
4905 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4907 function setTransparentTagHook( $tag, $callback ) {
4908 $tag = strtolower( $tag );
4909 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4910 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4912 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4913 $this->mTransparentTagHooks
[$tag] = $callback;
4919 * Remove all tag hooks
4921 function clearTagHooks() {
4922 $this->mTagHooks
= array();
4923 $this->mFunctionTagHooks
= array();
4924 $this->mStripList
= $this->mDefaultStripList
;
4928 * Create a function, e.g. {{sum:1|2|3}}
4929 * The callback function should have the form:
4930 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4932 * Or with SFH_OBJECT_ARGS:
4933 * function myParserFunction( $parser, $frame, $args ) { ... }
4935 * The callback may either return the text result of the function, or an array with the text
4936 * in element 0, and a number of flags in the other elements. The names of the flags are
4937 * specified in the keys. Valid flags are:
4938 * found The text returned is valid, stop processing the template. This
4940 * nowiki Wiki markup in the return value should be escaped
4941 * isHTML The returned text is HTML, armour it against wikitext transformation
4943 * @param string $id The magic word ID
4944 * @param $callback Mixed: the callback function (and object) to use
4945 * @param $flags Integer: a combination of the following flags:
4946 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4948 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4949 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4950 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4951 * the arguments, and to control the way they are expanded.
4953 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4954 * arguments, for instance:
4955 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4957 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4958 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4959 * working if/when this is changed.
4961 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4964 * Please read the documentation in includes/parser/Preprocessor.php for more information
4965 * about the methods available in PPFrame and PPNode.
4967 * @throws MWException
4968 * @return string|callback The old callback function for this name, if any
4970 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4973 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4974 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4976 # Add to function cache
4977 $mw = MagicWord
::get( $id );
4979 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4982 $synonyms = $mw->getSynonyms();
4983 $sensitive = intval( $mw->isCaseSensitive() );
4985 foreach ( $synonyms as $syn ) {
4987 if ( !$sensitive ) {
4988 $syn = $wgContLang->lc( $syn );
4991 if ( !( $flags & SFH_NO_HASH
) ) {
4994 # Remove trailing colon
4995 if ( substr( $syn, -1, 1 ) === ':' ) {
4996 $syn = substr( $syn, 0, -1 );
4998 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5004 * Get all registered function hook identifiers
5008 function getFunctionHooks() {
5009 return array_keys( $this->mFunctionHooks
);
5013 * Create a tag function, e.g. "<test>some stuff</test>".
5014 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5015 * Unlike parser functions, their content is not preprocessed.
5019 * @throws MWException
5022 function setFunctionTagHook( $tag, $callback, $flags ) {
5023 $tag = strtolower( $tag );
5024 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5025 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5027 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5028 $this->mFunctionTagHooks
[$tag] : null;
5029 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5031 if ( !in_array( $tag, $this->mStripList
) ) {
5032 $this->mStripList
[] = $tag;
5039 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5040 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5041 * Placeholders created in Skin::makeLinkObj()
5043 * @param $text string
5044 * @param $options int
5046 * @return array of link CSS classes, indexed by PDBK.
5048 function replaceLinkHolders( &$text, $options = 0 ) {
5049 return $this->mLinkHolders
->replace( $text );
5053 * Replace "<!--LINK-->" link placeholders with plain text of links
5054 * (not HTML-formatted).
5056 * @param $text String
5059 function replaceLinkHoldersText( $text ) {
5060 return $this->mLinkHolders
->replaceText( $text );
5064 * Renders an image gallery from a text with one line per image.
5065 * text labels may be given by using |-style alternative text. E.g.
5066 * Image:one.jpg|The number "1"
5067 * Image:tree.jpg|A tree
5068 * given as text will return the HTML of a gallery with two images,
5069 * labeled 'The number "1"' and
5072 * @param string $text
5073 * @param array $params
5074 * @return string HTML
5076 function renderImageGallery( $text, $params ) {
5077 wfProfileIn( __METHOD__
);
5080 if ( isset( $params['mode'] ) ) {
5081 $mode = $params['mode'];
5085 $ig = ImageGalleryBase
::factory( $mode );
5086 } catch ( MWException
$e ) {
5087 // If invalid type set, fallback to default.
5088 $ig = ImageGalleryBase
::factory( false );
5091 $ig->setContextTitle( $this->mTitle
);
5092 $ig->setShowBytes( false );
5093 $ig->setShowFilename( false );
5094 $ig->setParser( $this );
5095 $ig->setHideBadImages();
5096 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5098 if ( isset( $params['showfilename'] ) ) {
5099 $ig->setShowFilename( true );
5101 $ig->setShowFilename( false );
5103 if ( isset( $params['caption'] ) ) {
5104 $caption = $params['caption'];
5105 $caption = htmlspecialchars( $caption );
5106 $caption = $this->replaceInternalLinks( $caption );
5107 $ig->setCaptionHtml( $caption );
5109 if ( isset( $params['perrow'] ) ) {
5110 $ig->setPerRow( $params['perrow'] );
5112 if ( isset( $params['widths'] ) ) {
5113 $ig->setWidths( $params['widths'] );
5115 if ( isset( $params['heights'] ) ) {
5116 $ig->setHeights( $params['heights'] );
5118 $ig->setAdditionalOptions( $params );
5120 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5122 $lines = StringUtils
::explode( "\n", $text );
5123 foreach ( $lines as $line ) {
5124 # match lines like these:
5125 # Image:someimage.jpg|This is some image
5127 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5129 if ( count( $matches ) == 0 ) {
5133 if ( strpos( $matches[0], '%' ) !== false ) {
5134 $matches[1] = rawurldecode( $matches[1] );
5136 $title = Title
::newFromText( $matches[1], NS_FILE
);
5137 if ( is_null( $title ) ) {
5138 # Bogus title. Ignore these so we don't bomb out later.
5142 # We need to get what handler the file uses, to figure out parameters.
5143 # Note, a hook can overide the file name, and chose an entirely different
5144 # file (which potentially could be of a different type and have different handler).
5147 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5148 array( $this, $title, &$options, &$descQuery ) );
5149 # Don't register it now, as ImageGallery does that later.
5150 $file = $this->fetchFileNoRegister( $title, $options );
5151 $handler = $file ?
$file->getHandler() : false;
5153 wfProfileIn( __METHOD__
. '-getMagicWord' );
5155 'img_alt' => 'gallery-internal-alt',
5156 'img_link' => 'gallery-internal-link',
5159 $paramMap = $paramMap +
$handler->getParamMap();
5160 // We don't want people to specify per-image widths.
5161 // Additionally the width parameter would need special casing anyhow.
5162 unset( $paramMap['img_width'] );
5165 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5166 wfProfileOut( __METHOD__
. '-getMagicWord' );
5171 $handlerOptions = array();
5172 if ( isset( $matches[3] ) ) {
5173 // look for an |alt= definition while trying not to break existing
5174 // captions with multiple pipes (|) in it, until a more sensible grammar
5175 // is defined for images in galleries
5177 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5178 // splitting on '|' is a bit odd, and different from makeImage.
5179 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5180 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5182 foreach ( $parameterMatches as $parameterMatch ) {
5183 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5185 $paramName = $paramMap[$magicName];
5187 switch ( $paramName ) {
5188 case 'gallery-internal-alt':
5189 $alt = $this->stripAltText( $match, false );
5191 case 'gallery-internal-link':
5192 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5193 $chars = self
::EXT_LINK_URL_CLASS
;
5194 $prots = $this->mUrlProtocols
;
5195 //check to see if link matches an absolute url, if not then it must be a wiki link.
5196 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5199 $localLinkTitle = Title
::newFromText( $linkValue );
5200 if ( $localLinkTitle !== null ) {
5201 $link = $localLinkTitle->getLocalURL();
5206 // Must be a handler specific parameter.
5207 if ( $handler->validateParam( $paramName, $match ) ) {
5208 $handlerOptions[$paramName] = $match;
5210 // Guess not. Append it to the caption.
5211 wfDebug( "$parameterMatch failed parameter validation" );
5212 $label .= '|' . $parameterMatch;
5217 // concatenate all other pipes
5218 $label .= '|' . $parameterMatch;
5221 // remove the first pipe
5222 $label = substr( $label, 1 );
5225 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5227 $html = $ig->toHTML();
5228 wfProfileOut( __METHOD__
);
5236 function getImageParams( $handler ) {
5238 $handlerClass = get_class( $handler );
5242 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5243 # Initialise static lists
5244 static $internalParamNames = array(
5245 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5246 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5247 'bottom', 'text-bottom' ),
5248 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5249 'upright', 'border', 'link', 'alt', 'class' ),
5251 static $internalParamMap;
5252 if ( !$internalParamMap ) {
5253 $internalParamMap = array();
5254 foreach ( $internalParamNames as $type => $names ) {
5255 foreach ( $names as $name ) {
5256 $magicName = str_replace( '-', '_', "img_$name" );
5257 $internalParamMap[$magicName] = array( $type, $name );
5262 # Add handler params
5263 $paramMap = $internalParamMap;
5265 $handlerParamMap = $handler->getParamMap();
5266 foreach ( $handlerParamMap as $magic => $paramName ) {
5267 $paramMap[$magic] = array( 'handler', $paramName );
5270 $this->mImageParams
[$handlerClass] = $paramMap;
5271 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5273 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5277 * Parse image options text and use it to make an image
5279 * @param $title Title
5280 * @param $options String
5281 * @param $holders LinkHolderArray|bool
5282 * @return string HTML
5284 function makeImage( $title, $options, $holders = false ) {
5285 # Check if the options text is of the form "options|alt text"
5287 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5288 # * left no resizing, just left align. label is used for alt= only
5289 # * right same, but right aligned
5290 # * none same, but not aligned
5291 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5292 # * center center the image
5293 # * frame Keep original image size, no magnify-button.
5294 # * framed Same as "frame"
5295 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5296 # * upright reduce width for upright images, rounded to full __0 px
5297 # * border draw a 1px border around the image
5298 # * alt Text for HTML alt attribute (defaults to empty)
5299 # * class Set a class for img node
5300 # * link Set the target of the image link. Can be external, interwiki, or local
5301 # vertical-align values (no % or length right now):
5311 $parts = StringUtils
::explode( "|", $options );
5313 # Give extensions a chance to select the file revision for us
5316 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5317 array( $this, $title, &$options, &$descQuery ) );
5318 # Fetch and register the file (file title may be different via hooks)
5319 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5322 $handler = $file ?
$file->getHandler() : false;
5324 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5327 $this->addTrackingCategory( 'broken-file-category' );
5330 # Process the input parameters
5332 $params = array( 'frame' => array(), 'handler' => array(),
5333 'horizAlign' => array(), 'vertAlign' => array() );
5334 foreach ( $parts as $part ) {
5335 $part = trim( $part );
5336 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5338 if ( isset( $paramMap[$magicName] ) ) {
5339 list( $type, $paramName ) = $paramMap[$magicName];
5341 # Special case; width and height come in one variable together
5342 if ( $type === 'handler' && $paramName === 'width' ) {
5343 $parsedWidthParam = $this->parseWidthParam( $value );
5344 if ( isset( $parsedWidthParam['width'] ) ) {
5345 $width = $parsedWidthParam['width'];
5346 if ( $handler->validateParam( 'width', $width ) ) {
5347 $params[$type]['width'] = $width;
5351 if ( isset( $parsedWidthParam['height'] ) ) {
5352 $height = $parsedWidthParam['height'];
5353 if ( $handler->validateParam( 'height', $height ) ) {
5354 $params[$type]['height'] = $height;
5358 # else no validation -- bug 13436
5360 if ( $type === 'handler' ) {
5361 # Validate handler parameter
5362 $validated = $handler->validateParam( $paramName, $value );
5364 # Validate internal parameters
5365 switch ( $paramName ) {
5369 # @todo FIXME: Possibly check validity here for
5370 # manualthumb? downstream behavior seems odd with
5371 # missing manual thumbs.
5373 $value = $this->stripAltText( $value, $holders );
5376 $chars = self
::EXT_LINK_URL_CLASS
;
5377 $prots = $this->mUrlProtocols
;
5378 if ( $value === '' ) {
5379 $paramName = 'no-link';
5382 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5383 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5384 $paramName = 'link-url';
5385 $this->mOutput
->addExternalLink( $value );
5386 if ( $this->mOptions
->getExternalLinkTarget() ) {
5387 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5392 $linkTitle = Title
::newFromText( $value );
5394 $paramName = 'link-title';
5395 $value = $linkTitle;
5396 $this->mOutput
->addLink( $linkTitle );
5402 # Most other things appear to be empty or numeric...
5403 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5408 $params[$type][$paramName] = $value;
5412 if ( !$validated ) {
5417 # Process alignment parameters
5418 if ( $params['horizAlign'] ) {
5419 $params['frame']['align'] = key( $params['horizAlign'] );
5421 if ( $params['vertAlign'] ) {
5422 $params['frame']['valign'] = key( $params['vertAlign'] );
5425 $params['frame']['caption'] = $caption;
5427 # Will the image be presented in a frame, with the caption below?
5428 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5429 isset( $params['frame']['framed'] ) ||
5430 isset( $params['frame']['thumbnail'] ) ||
5431 isset( $params['frame']['manualthumb'] );
5433 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5434 # came to also set the caption, ordinary text after the image -- which
5435 # makes no sense, because that just repeats the text multiple times in
5436 # screen readers. It *also* came to set the title attribute.
5438 # Now that we have an alt attribute, we should not set the alt text to
5439 # equal the caption: that's worse than useless, it just repeats the
5440 # text. This is the framed/thumbnail case. If there's no caption, we
5441 # use the unnamed parameter for alt text as well, just for the time be-
5442 # ing, if the unnamed param is set and the alt param is not.
5444 # For the future, we need to figure out if we want to tweak this more,
5445 # e.g., introducing a title= parameter for the title; ignoring the un-
5446 # named parameter entirely for images without a caption; adding an ex-
5447 # plicit caption= parameter and preserving the old magic unnamed para-
5449 if ( $imageIsFramed ) { # Framed image
5450 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5451 # No caption or alt text, add the filename as the alt text so
5452 # that screen readers at least get some description of the image
5453 $params['frame']['alt'] = $title->getText();
5455 # Do not set $params['frame']['title'] because tooltips don't make sense
5457 } else { # Inline image
5458 if ( !isset( $params['frame']['alt'] ) ) {
5459 # No alt text, use the "caption" for the alt text
5460 if ( $caption !== '' ) {
5461 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5463 # No caption, fall back to using the filename for the
5465 $params['frame']['alt'] = $title->getText();
5468 # Use the "caption" for the tooltip text
5469 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5472 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5474 # Linker does the rest
5475 $time = isset( $options['time'] ) ?
$options['time'] : false;
5476 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5477 $time, $descQuery, $this->mOptions
->getThumbSize() );
5479 # Give the handler a chance to modify the parser object
5481 $handler->parserTransformHook( $this, $file );
5489 * @param $holders LinkHolderArray
5490 * @return mixed|String
5492 protected function stripAltText( $caption, $holders ) {
5493 # Strip bad stuff out of the title (tooltip). We can't just use
5494 # replaceLinkHoldersText() here, because if this function is called
5495 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5497 $tooltip = $holders->replaceText( $caption );
5499 $tooltip = $this->replaceLinkHoldersText( $caption );
5502 # make sure there are no placeholders in thumbnail attributes
5503 # that are later expanded to html- so expand them now and
5505 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5506 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5512 * Set a flag in the output object indicating that the content is dynamic and
5513 * shouldn't be cached.
5515 function disableCache() {
5516 wfDebug( "Parser output marked as uncacheable.\n" );
5517 if ( !$this->mOutput
) {
5518 throw new MWException( __METHOD__
.
5519 " can only be called when actually parsing something" );
5521 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5522 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5526 * Callback from the Sanitizer for expanding items found in HTML attribute
5527 * values, so they can be safely tested and escaped.
5529 * @param $text String
5530 * @param $frame PPFrame
5533 function attributeStripCallback( &$text, $frame = false ) {
5534 $text = $this->replaceVariables( $text, $frame );
5535 $text = $this->mStripState
->unstripBoth( $text );
5544 function getTags() {
5545 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5549 * Replace transparent tags in $text with the values given by the callbacks.
5551 * Transparent tag hooks are like regular XML-style tag hooks, except they
5552 * operate late in the transformation sequence, on HTML instead of wikitext.
5554 * @param $text string
5558 function replaceTransparentTags( $text ) {
5560 $elements = array_keys( $this->mTransparentTagHooks
);
5561 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5562 $replacements = array();
5564 foreach ( $matches as $marker => $data ) {
5565 list( $element, $content, $params, $tag ) = $data;
5566 $tagName = strtolower( $element );
5567 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5568 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5572 $replacements[$marker] = $output;
5574 return strtr( $text, $replacements );
5578 * Break wikitext input into sections, and either pull or replace
5579 * some particular section's text.
5581 * External callers should use the getSection and replaceSection methods.
5583 * @param string $text Page wikitext
5584 * @param string $section a section identifier string of the form:
5585 * "<flag1> - <flag2> - ... - <section number>"
5587 * Currently the only recognised flag is "T", which means the target section number
5588 * was derived during a template inclusion parse, in other words this is a template
5589 * section edit link. If no flags are given, it was an ordinary section edit link.
5590 * This flag is required to avoid a section numbering mismatch when a section is
5591 * enclosed by "<includeonly>" (bug 6563).
5593 * The section number 0 pulls the text before the first heading; other numbers will
5594 * pull the given section along with its lower-level subsections. If the section is
5595 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5597 * Section 0 is always considered to exist, even if it only contains the empty
5598 * string. If $text is the empty string and section 0 is replaced, $newText is
5601 * @param string $mode one of "get" or "replace"
5602 * @param string $newText replacement text for section data.
5603 * @return String: for "get", the extracted section text.
5604 * for "replace", the whole page with the section replaced.
5606 private function extractSections( $text, $section, $mode, $newText = '' ) {
5607 global $wgTitle; # not generally used but removes an ugly failure mode
5608 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5610 $frame = $this->getPreprocessor()->newFrame();
5612 # Process section extraction flags
5614 $sectionParts = explode( '-', $section );
5615 $sectionIndex = array_pop( $sectionParts );
5616 foreach ( $sectionParts as $part ) {
5617 if ( $part === 'T' ) {
5618 $flags |
= self
::PTD_FOR_INCLUSION
;
5622 # Check for empty input
5623 if ( strval( $text ) === '' ) {
5624 # Only sections 0 and T-0 exist in an empty document
5625 if ( $sectionIndex == 0 ) {
5626 if ( $mode === 'get' ) {
5632 if ( $mode === 'get' ) {
5640 # Preprocess the text
5641 $root = $this->preprocessToDom( $text, $flags );
5643 # <h> nodes indicate section breaks
5644 # They can only occur at the top level, so we can find them by iterating the root's children
5645 $node = $root->getFirstChild();
5647 # Find the target section
5648 if ( $sectionIndex == 0 ) {
5649 # Section zero doesn't nest, level=big
5650 $targetLevel = 1000;
5653 if ( $node->getName() === 'h' ) {
5654 $bits = $node->splitHeading();
5655 if ( $bits['i'] == $sectionIndex ) {
5656 $targetLevel = $bits['level'];
5660 if ( $mode === 'replace' ) {
5661 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5663 $node = $node->getNextSibling();
5669 if ( $mode === 'get' ) {
5676 # Find the end of the section, including nested sections
5678 if ( $node->getName() === 'h' ) {
5679 $bits = $node->splitHeading();
5680 $curLevel = $bits['level'];
5681 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5685 if ( $mode === 'get' ) {
5686 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5688 $node = $node->getNextSibling();
5691 # Write out the remainder (in replace mode only)
5692 if ( $mode === 'replace' ) {
5693 # Output the replacement text
5694 # Add two newlines on -- trailing whitespace in $newText is conventionally
5695 # stripped by the editor, so we need both newlines to restore the paragraph gap
5696 # Only add trailing whitespace if there is newText
5697 if ( $newText != "" ) {
5698 $outText .= $newText . "\n\n";
5702 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5703 $node = $node->getNextSibling();
5707 if ( is_string( $outText ) ) {
5708 # Re-insert stripped tags
5709 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5716 * This function returns the text of a section, specified by a number ($section).
5717 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5718 * the first section before any such heading (section 0).
5720 * If a section contains subsections, these are also returned.
5722 * @param string $text text to look in
5723 * @param string $section section identifier
5724 * @param string $deftext default to return if section is not found
5725 * @return string text of the requested section
5727 public function getSection( $text, $section, $deftext = '' ) {
5728 return $this->extractSections( $text, $section, "get", $deftext );
5732 * This function returns $oldtext after the content of the section
5733 * specified by $section has been replaced with $text. If the target
5734 * section does not exist, $oldtext is returned unchanged.
5736 * @param string $oldtext former text of the article
5737 * @param int $section section identifier
5738 * @param string $text replacing text
5739 * @return String: modified text
5741 public function replaceSection( $oldtext, $section, $text ) {
5742 return $this->extractSections( $oldtext, $section, "replace", $text );
5746 * Get the ID of the revision we are parsing
5748 * @return Mixed: integer or null
5750 function getRevisionId() {
5751 return $this->mRevisionId
;
5755 * Get the revision object for $this->mRevisionId
5757 * @return Revision|null either a Revision object or null
5759 protected function getRevisionObject() {
5760 if ( !is_null( $this->mRevisionObject
) ) {
5761 return $this->mRevisionObject
;
5763 if ( is_null( $this->mRevisionId
) ) {
5767 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5768 return $this->mRevisionObject
;
5772 * Get the timestamp associated with the current revision, adjusted for
5773 * the default server-local timestamp
5775 function getRevisionTimestamp() {
5776 if ( is_null( $this->mRevisionTimestamp
) ) {
5777 wfProfileIn( __METHOD__
);
5781 $revObject = $this->getRevisionObject();
5782 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5784 # The cryptic '' timezone parameter tells to use the site-default
5785 # timezone offset instead of the user settings.
5787 # Since this value will be saved into the parser cache, served
5788 # to other users, and potentially even used inside links and such,
5789 # it needs to be consistent for all visitors.
5790 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5792 wfProfileOut( __METHOD__
);
5794 return $this->mRevisionTimestamp
;
5798 * Get the name of the user that edited the last revision
5800 * @return String: user name
5802 function getRevisionUser() {
5803 if ( is_null( $this->mRevisionUser
) ) {
5804 $revObject = $this->getRevisionObject();
5806 # if this template is subst: the revision id will be blank,
5807 # so just use the current user's name
5809 $this->mRevisionUser
= $revObject->getUserText();
5810 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5811 $this->mRevisionUser
= $this->getUser()->getName();
5814 return $this->mRevisionUser
;
5818 * Get the size of the revision
5820 * @return int|null revision size
5822 function getRevisionSize() {
5823 if ( is_null( $this->mRevisionSize
) ) {
5824 $revObject = $this->getRevisionObject();
5826 # if this variable is subst: the revision id will be blank,
5827 # so just use the parser input size, because the own substituation
5828 # will change the size.
5830 $this->mRevisionSize
= $revObject->getSize();
5831 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5832 $this->mRevisionSize
= $this->mInputSize
;
5835 return $this->mRevisionSize
;
5839 * Mutator for $mDefaultSort
5841 * @param string $sort New value
5843 public function setDefaultSort( $sort ) {
5844 $this->mDefaultSort
= $sort;
5845 $this->mOutput
->setProperty( 'defaultsort', $sort );
5849 * Accessor for $mDefaultSort
5850 * Will use the empty string if none is set.
5852 * This value is treated as a prefix, so the
5853 * empty string is equivalent to sorting by
5858 public function getDefaultSort() {
5859 if ( $this->mDefaultSort
!== false ) {
5860 return $this->mDefaultSort
;
5867 * Accessor for $mDefaultSort
5868 * Unlike getDefaultSort(), will return false if none is set
5870 * @return string or false
5872 public function getCustomDefaultSort() {
5873 return $this->mDefaultSort
;
5877 * Try to guess the section anchor name based on a wikitext fragment
5878 * presumably extracted from a heading, for example "Header" from
5881 * @param $text string
5885 public function guessSectionNameFromWikiText( $text ) {
5886 # Strip out wikitext links(they break the anchor)
5887 $text = $this->stripSectionName( $text );
5888 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5889 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5893 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5894 * instead. For use in redirects, since IE6 interprets Redirect: headers
5895 * as something other than UTF-8 (apparently?), resulting in breakage.
5897 * @param string $text The section name
5898 * @return string An anchor
5900 public function guessLegacySectionNameFromWikiText( $text ) {
5901 # Strip out wikitext links(they break the anchor)
5902 $text = $this->stripSectionName( $text );
5903 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5904 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5908 * Strips a text string of wikitext for use in a section anchor
5910 * Accepts a text string and then removes all wikitext from the
5911 * string and leaves only the resultant text (i.e. the result of
5912 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5913 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5914 * to create valid section anchors by mimicing the output of the
5915 * parser when headings are parsed.
5917 * @param string $text text string to be stripped of wikitext
5918 * for use in a Section anchor
5919 * @return string Filtered text string
5921 public function stripSectionName( $text ) {
5922 # Strip internal link markup
5923 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5924 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5926 # Strip external link markup
5927 # @todo FIXME: Not tolerant to blank link text
5928 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5929 # on how many empty links there are on the page - need to figure that out.
5930 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5932 # Parse wikitext quotes (italics & bold)
5933 $text = $this->doQuotes( $text );
5936 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5941 * strip/replaceVariables/unstrip for preprocessor regression testing
5943 * @param $text string
5944 * @param $title Title
5945 * @param $options ParserOptions
5946 * @param $outputType int
5950 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5951 $this->startParse( $title, $options, $outputType, true );
5953 $text = $this->replaceVariables( $text );
5954 $text = $this->mStripState
->unstripBoth( $text );
5955 $text = Sanitizer
::removeHTMLtags( $text );
5960 * @param $text string
5961 * @param $title Title
5962 * @param $options ParserOptions
5965 function testPst( $text, Title
$title, ParserOptions
$options ) {
5966 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5971 * @param $title Title
5972 * @param $options ParserOptions
5975 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5976 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5980 * Call a callback function on all regions of the given text that are not
5981 * inside strip markers, and replace those regions with the return value
5982 * of the callback. For example, with input:
5986 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5987 * two strings will be replaced with the value returned by the callback in
5995 function markerSkipCallback( $s, $callback ) {
5998 while ( $i < strlen( $s ) ) {
5999 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6000 if ( $markerStart === false ) {
6001 $out .= call_user_func( $callback, substr( $s, $i ) );
6004 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6005 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6006 if ( $markerEnd === false ) {
6007 $out .= substr( $s, $markerStart );
6010 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6011 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6020 * Remove any strip markers found in the given text.
6022 * @param $text Input string
6025 function killMarkers( $text ) {
6026 return $this->mStripState
->killMarkers( $text );
6030 * Save the parser state required to convert the given half-parsed text to
6031 * HTML. "Half-parsed" in this context means the output of
6032 * recursiveTagParse() or internalParse(). This output has strip markers
6033 * from replaceVariables (extensionSubstitution() etc.), and link
6034 * placeholders from replaceLinkHolders().
6036 * Returns an array which can be serialized and stored persistently. This
6037 * array can later be loaded into another parser instance with
6038 * unserializeHalfParsedText(). The text can then be safely incorporated into
6039 * the return value of a parser hook.
6041 * @param $text string
6045 function serializeHalfParsedText( $text ) {
6046 wfProfileIn( __METHOD__
);
6049 'version' => self
::HALF_PARSED_VERSION
,
6050 'stripState' => $this->mStripState
->getSubState( $text ),
6051 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6053 wfProfileOut( __METHOD__
);
6058 * Load the parser state given in the $data array, which is assumed to
6059 * have been generated by serializeHalfParsedText(). The text contents is
6060 * extracted from the array, and its markers are transformed into markers
6061 * appropriate for the current Parser instance. This transformed text is
6062 * returned, and can be safely included in the return value of a parser
6065 * If the $data array has been stored persistently, the caller should first
6066 * check whether it is still valid, by calling isValidHalfParsedText().
6068 * @param array $data Serialized data
6069 * @throws MWException
6072 function unserializeHalfParsedText( $data ) {
6073 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6074 throw new MWException( __METHOD__
. ': invalid version' );
6077 # First, extract the strip state.
6078 $texts = array( $data['text'] );
6079 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6081 # Now renumber links
6082 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6084 # Should be good to go.
6089 * Returns true if the given array, presumed to be generated by
6090 * serializeHalfParsedText(), is compatible with the current version of the
6093 * @param $data Array
6097 function isValidHalfParsedText( $data ) {
6098 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6102 * Parsed a width param of imagelink like 300px or 200x300px
6104 * @param $value String
6109 public function parseWidthParam( $value ) {
6110 $parsedWidthParam = array();
6111 if ( $value === '' ) {
6112 return $parsedWidthParam;
6115 # (bug 13500) In both cases (width/height and width only),
6116 # permit trailing "px" for backward compatibility.
6117 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6118 $width = intval( $m[1] );
6119 $height = intval( $m[2] );
6120 $parsedWidthParam['width'] = $width;
6121 $parsedWidthParam['height'] = $height;
6122 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6123 $width = intval( $value );
6124 $parsedWidthParam['width'] = $width;
6126 return $parsedWidthParam;