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, $wgShowHostnames;
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 if ( $wgShowHostnames ) {
536 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
538 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
539 if ( wfRunHooks( 'ParserLimitReportFormat',
540 array( $key, $value, &$limitReport, false, false )
542 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
543 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
544 ->inLanguage( 'en' )->useDatabase( false );
545 if ( !$valueMsg->exists() ) {
546 $valueMsg = new RawMessage( '$1' );
548 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
549 $valueMsg->params( $value );
550 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
554 // Since we're not really outputting HTML, decode the entities and
555 // then re-encode the things that need hiding inside HTML comments.
556 $limitReport = htmlspecialchars_decode( $limitReport );
557 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
559 // Sanitize for comment. Note '‐' in the replacement is U+2010,
560 // which looks much like the problematic '-'.
561 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
562 $text .= "\n<!-- \n$limitReport-->\n";
564 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
565 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
566 $this->mTitle
->getPrefixedDBkey() );
569 $this->mOutput
->setText( $text );
571 $this->mRevisionId
= $oldRevisionId;
572 $this->mRevisionObject
= $oldRevisionObject;
573 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
574 $this->mRevisionUser
= $oldRevisionUser;
575 $this->mRevisionSize
= $oldRevisionSize;
576 $this->mInputSize
= false;
577 wfProfileOut( $fname );
578 wfProfileOut( __METHOD__
);
580 return $this->mOutput
;
584 * Recursive parser entry point that can be called from an extension tag
587 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
589 * @param string $text text extension wants to have parsed
590 * @param $frame PPFrame: The frame to use for expanding any template variables
594 function recursiveTagParse( $text, $frame = false ) {
595 wfProfileIn( __METHOD__
);
596 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
597 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
598 $text = $this->internalParse( $text, false, $frame );
599 wfProfileOut( __METHOD__
);
604 * Expand templates and variables in the text, producing valid, static wikitext.
605 * Also removes comments.
606 * @return mixed|string
608 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
609 wfProfileIn( __METHOD__
);
610 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
611 if ( $revid !== null ) {
612 $this->mRevisionId
= $revid;
614 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
615 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
616 $text = $this->replaceVariables( $text );
617 $text = $this->mStripState
->unstripBoth( $text );
618 wfProfileOut( __METHOD__
);
623 * Recursive parser entry point that can be called from an extension tag
626 * @param string $text text to be expanded
627 * @param $frame PPFrame: The frame to use for expanding any template variables
631 public function recursivePreprocess( $text, $frame = false ) {
632 wfProfileIn( __METHOD__
);
633 $text = $this->replaceVariables( $text, $frame );
634 $text = $this->mStripState
->unstripBoth( $text );
635 wfProfileOut( __METHOD__
);
640 * Process the wikitext for the "?preload=" feature. (bug 5210)
642 * "<noinclude>", "<includeonly>" etc. are parsed as for template
643 * transclusion, comments, templates, arguments, tags hooks and parser
644 * functions are untouched.
646 * @param $text String
647 * @param $title Title
648 * @param $options ParserOptions
651 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
652 # Parser (re)initialisation
653 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
655 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
656 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
657 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
658 $text = $this->mStripState
->unstripBoth( $text );
663 * Get a random string
667 public static function getRandomString() {
668 return wfRandomString( 16 );
672 * Set the current user.
673 * Should only be used when doing pre-save transform.
675 * @param $user Mixed: User object or null (to reset)
677 function setUser( $user ) {
678 $this->mUser
= $user;
682 * Accessor for mUniqPrefix.
686 public function uniqPrefix() {
687 if ( !isset( $this->mUniqPrefix
) ) {
688 # @todo FIXME: This is probably *horribly wrong*
689 # LanguageConverter seems to want $wgParser's uniqPrefix, however
690 # if this is called for a parser cache hit, the parser may not
691 # have ever been initialized in the first place.
692 # Not really sure what the heck is supposed to be going on here.
694 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
696 return $this->mUniqPrefix
;
700 * Set the context title
704 function setTitle( $t ) {
705 if ( !$t ||
$t instanceof FakeTitle
) {
706 $t = Title
::newFromText( 'NO TITLE' );
709 if ( strval( $t->getFragment() ) !== '' ) {
710 # Strip the fragment to avoid various odd effects
711 $this->mTitle
= clone $t;
712 $this->mTitle
->setFragment( '' );
719 * Accessor for the Title object
721 * @return Title object
723 function getTitle() {
724 return $this->mTitle
;
728 * Accessor/mutator for the Title object
730 * @param $x Title object or null to just get the current one
731 * @return Title object
733 function Title( $x = null ) {
734 return wfSetVar( $this->mTitle
, $x );
738 * Set the output type
740 * @param $ot Integer: new value
742 function setOutputType( $ot ) {
743 $this->mOutputType
= $ot;
746 'html' => $ot == self
::OT_HTML
,
747 'wiki' => $ot == self
::OT_WIKI
,
748 'pre' => $ot == self
::OT_PREPROCESS
,
749 'plain' => $ot == self
::OT_PLAIN
,
754 * Accessor/mutator for the output type
756 * @param int|null $x New value or null to just get the current one
759 function OutputType( $x = null ) {
760 return wfSetVar( $this->mOutputType
, $x );
764 * Get the ParserOutput object
766 * @return ParserOutput object
768 function getOutput() {
769 return $this->mOutput
;
773 * Get the ParserOptions object
775 * @return ParserOptions object
777 function getOptions() {
778 return $this->mOptions
;
782 * Accessor/mutator for the ParserOptions object
784 * @param $x ParserOptions New value or null to just get the current one
785 * @return ParserOptions Current ParserOptions object
787 function Options( $x = null ) {
788 return wfSetVar( $this->mOptions
, $x );
794 function nextLinkID() {
795 return $this->mLinkID++
;
801 function setLinkID( $id ) {
802 $this->mLinkID
= $id;
806 * Get a language object for use in parser functions such as {{FORMATNUM:}}
809 function getFunctionLang() {
810 return $this->getTargetLanguage();
814 * Get the target language for the content being parsed. This is usually the
815 * language that the content is in.
819 * @throws MWException
820 * @return Language|null
822 public function getTargetLanguage() {
823 $target = $this->mOptions
->getTargetLanguage();
825 if ( $target !== null ) {
827 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
828 return $this->mOptions
->getUserLangObj();
829 } elseif ( is_null( $this->mTitle
) ) {
830 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
833 return $this->mTitle
->getPageLanguage();
837 * Get the language object for language conversion
839 function getConverterLanguage() {
840 return $this->getTargetLanguage();
844 * Get a User object either from $this->mUser, if set, or from the
845 * ParserOptions object otherwise
847 * @return User object
850 if ( !is_null( $this->mUser
) ) {
853 return $this->mOptions
->getUser();
857 * Get a preprocessor object
859 * @return Preprocessor instance
861 function getPreprocessor() {
862 if ( !isset( $this->mPreprocessor
) ) {
863 $class = $this->mPreprocessorClass
;
864 $this->mPreprocessor
= new $class( $this );
866 return $this->mPreprocessor
;
870 * Replaces all occurrences of HTML-style comments and the given tags
871 * in the text with a random marker and returns the next text. The output
872 * parameter $matches will be an associative array filled with data in
876 * 'UNIQ-xxxxx' => array(
879 * array( 'param' => 'x' ),
880 * '<element param="x">tag content</element>' ) )
883 * @param array $elements list of element names. Comments are always extracted.
884 * @param string $text Source text string.
885 * @param array $matches Out parameter, Array: extracted tags
886 * @param $uniq_prefix string
887 * @return String: stripped text
889 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
894 $taglist = implode( '|', $elements );
895 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
897 while ( $text != '' ) {
898 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
900 if ( count( $p ) < 5 ) {
903 if ( count( $p ) > 5 ) {
917 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
918 $stripped .= $marker;
920 if ( $close === '/>' ) {
921 # Empty element tag, <tag />
926 if ( $element === '!--' ) {
929 $end = "/(<\\/$element\\s*>)/i";
931 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
933 if ( count( $q ) < 3 ) {
934 # No end tag -- let it run out to the end of the text.
943 $matches[$marker] = array( $element,
945 Sanitizer
::decodeTagAttributes( $attributes ),
946 "<$element$attributes$close$content$tail" );
952 * Get a list of strippable XML-like elements
956 function getStripList() {
957 return $this->mStripList
;
961 * Add an item to the strip state
962 * Returns the unique tag which must be inserted into the stripped text
963 * The tag will be replaced with the original text in unstrip()
965 * @param $text string
969 function insertStripItem( $text ) {
970 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
971 $this->mMarkerIndex++
;
972 $this->mStripState
->addGeneral( $rnd, $text );
977 * parse the wiki syntax used to render tables
982 function doTableStuff( $text ) {
983 wfProfileIn( __METHOD__
);
985 $lines = StringUtils
::explode( "\n", $text );
987 $td_history = array(); # Is currently a td tag open?
988 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
989 $tr_history = array(); # Is currently a tr tag open?
990 $tr_attributes = array(); # history of tr attributes
991 $has_opened_tr = array(); # Did this table open a <tr> element?
992 $indent_level = 0; # indent level of the table
994 foreach ( $lines as $outLine ) {
995 $line = trim( $outLine );
997 if ( $line === '' ) { # empty line, go to next line
998 $out .= $outLine . "\n";
1002 $first_character = $line[0];
1005 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1006 # First check if we are starting a new table
1007 $indent_level = strlen( $matches[1] );
1009 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1010 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1012 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1013 array_push( $td_history, false );
1014 array_push( $last_tag_history, '' );
1015 array_push( $tr_history, false );
1016 array_push( $tr_attributes, '' );
1017 array_push( $has_opened_tr, false );
1018 } elseif ( count( $td_history ) == 0 ) {
1019 # Don't do any of the following
1020 $out .= $outLine . "\n";
1022 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1023 # We are ending a table
1024 $line = '</table>' . substr( $line, 2 );
1025 $last_tag = array_pop( $last_tag_history );
1027 if ( !array_pop( $has_opened_tr ) ) {
1028 $line = "<tr><td></td></tr>{$line}";
1031 if ( array_pop( $tr_history ) ) {
1032 $line = "</tr>{$line}";
1035 if ( array_pop( $td_history ) ) {
1036 $line = "</{$last_tag}>{$line}";
1038 array_pop( $tr_attributes );
1039 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1040 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1041 # Now we have a table row
1042 $line = preg_replace( '#^\|-+#', '', $line );
1044 # Whats after the tag is now only attributes
1045 $attributes = $this->mStripState
->unstripBoth( $line );
1046 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1047 array_pop( $tr_attributes );
1048 array_push( $tr_attributes, $attributes );
1051 $last_tag = array_pop( $last_tag_history );
1052 array_pop( $has_opened_tr );
1053 array_push( $has_opened_tr, true );
1055 if ( array_pop( $tr_history ) ) {
1059 if ( array_pop( $td_history ) ) {
1060 $line = "</{$last_tag}>{$line}";
1064 array_push( $tr_history, false );
1065 array_push( $td_history, false );
1066 array_push( $last_tag_history, '' );
1067 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1068 # This might be cell elements, td, th or captions
1069 if ( substr( $line, 0, 2 ) === '|+' ) {
1070 $first_character = '+';
1071 $line = substr( $line, 1 );
1074 $line = substr( $line, 1 );
1076 if ( $first_character === '!' ) {
1077 $line = str_replace( '!!', '||', $line );
1080 # Split up multiple cells on the same line.
1081 # FIXME : This can result in improper nesting of tags processed
1082 # by earlier parser steps, but should avoid splitting up eg
1083 # attribute values containing literal "||".
1084 $cells = StringUtils
::explodeMarkup( '||', $line );
1088 # Loop through each table cell
1089 foreach ( $cells as $cell ) {
1091 if ( $first_character !== '+' ) {
1092 $tr_after = array_pop( $tr_attributes );
1093 if ( !array_pop( $tr_history ) ) {
1094 $previous = "<tr{$tr_after}>\n";
1096 array_push( $tr_history, true );
1097 array_push( $tr_attributes, '' );
1098 array_pop( $has_opened_tr );
1099 array_push( $has_opened_tr, true );
1102 $last_tag = array_pop( $last_tag_history );
1104 if ( array_pop( $td_history ) ) {
1105 $previous = "</{$last_tag}>\n{$previous}";
1108 if ( $first_character === '|' ) {
1110 } elseif ( $first_character === '!' ) {
1112 } elseif ( $first_character === '+' ) {
1113 $last_tag = 'caption';
1118 array_push( $last_tag_history, $last_tag );
1120 # A cell could contain both parameters and data
1121 $cell_data = explode( '|', $cell, 2 );
1123 # Bug 553: Note that a '|' inside an invalid link should not
1124 # be mistaken as delimiting cell parameters
1125 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1126 $cell = "{$previous}<{$last_tag}>{$cell}";
1127 } elseif ( count( $cell_data ) == 1 ) {
1128 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1130 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1131 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1132 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1136 array_push( $td_history, true );
1139 $out .= $outLine . "\n";
1142 # Closing open td, tr && table
1143 while ( count( $td_history ) > 0 ) {
1144 if ( array_pop( $td_history ) ) {
1147 if ( array_pop( $tr_history ) ) {
1150 if ( !array_pop( $has_opened_tr ) ) {
1151 $out .= "<tr><td></td></tr>\n";
1154 $out .= "</table>\n";
1157 # Remove trailing line-ending (b/c)
1158 if ( substr( $out, -1 ) === "\n" ) {
1159 $out = substr( $out, 0, -1 );
1162 # special case: don't return empty table
1163 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1167 wfProfileOut( __METHOD__
);
1173 * Helper function for parse() that transforms wiki markup into
1174 * HTML. Only called for $mOutputType == self::OT_HTML.
1178 * @param $text string
1179 * @param $isMain bool
1180 * @param $frame bool
1184 function internalParse( $text, $isMain = true, $frame = false ) {
1185 wfProfileIn( __METHOD__
);
1189 # Hook to suspend the parser in this state
1190 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1191 wfProfileOut( __METHOD__
);
1195 # if $frame is provided, then use $frame for replacing any variables
1197 # use frame depth to infer how include/noinclude tags should be handled
1198 # depth=0 means this is the top-level document; otherwise it's an included document
1199 if ( !$frame->depth
) {
1202 $flag = Parser
::PTD_FOR_INCLUSION
;
1204 $dom = $this->preprocessToDom( $text, $flag );
1205 $text = $frame->expand( $dom );
1207 # if $frame is not provided, then use old-style replaceVariables
1208 $text = $this->replaceVariables( $text );
1211 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1212 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1213 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1215 # Tables need to come after variable replacement for things to work
1216 # properly; putting them before other transformations should keep
1217 # exciting things like link expansions from showing up in surprising
1219 $text = $this->doTableStuff( $text );
1221 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1223 $text = $this->doDoubleUnderscore( $text );
1225 $text = $this->doHeadings( $text );
1226 $text = $this->replaceInternalLinks( $text );
1227 $text = $this->doAllQuotes( $text );
1228 $text = $this->replaceExternalLinks( $text );
1230 # replaceInternalLinks may sometimes leave behind
1231 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1232 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1234 $text = $this->doMagicLinks( $text );
1235 $text = $this->formatHeadings( $text, $origText, $isMain );
1237 wfProfileOut( __METHOD__
);
1242 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1243 * magic external links.
1248 * @param $text string
1252 function doMagicLinks( $text ) {
1253 wfProfileIn( __METHOD__
);
1254 $prots = wfUrlProtocolsWithoutProtRel();
1255 $urlChar = self
::EXT_LINK_URL_CLASS
;
1256 $text = preg_replace_callback(
1258 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1259 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1260 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1261 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1262 ISBN\s+(\b # m[5]: ISBN, capture number
1263 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1264 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1265 [0-9Xx] # check digit
1267 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1268 wfProfileOut( __METHOD__
);
1273 * @throws MWException
1275 * @return HTML|string
1277 function magicLinkCallback( $m ) {
1278 if ( isset( $m[1] ) && $m[1] !== '' ) {
1281 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1284 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1285 # Free external link
1286 return $this->makeFreeExternalLink( $m[0] );
1287 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1289 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1292 $CssClass = 'mw-magiclink-rfc';
1294 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1296 $urlmsg = 'pubmedurl';
1297 $CssClass = 'mw-magiclink-pmid';
1300 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1301 substr( $m[0], 0, 20 ) . '"' );
1303 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1304 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1305 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1308 $num = strtr( $isbn, array(
1313 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1314 return '<a href="' .
1315 htmlspecialchars( $titleObj->getLocalURL() ) .
1316 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1323 * Make a free external link, given a user-supplied URL
1325 * @param $url string
1327 * @return string HTML
1330 function makeFreeExternalLink( $url ) {
1331 wfProfileIn( __METHOD__
);
1335 # The characters '<' and '>' (which were escaped by
1336 # removeHTMLtags()) should not be included in
1337 # URLs, per RFC 2396.
1339 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1340 $trail = substr( $url, $m2[0][1] ) . $trail;
1341 $url = substr( $url, 0, $m2[0][1] );
1344 # Move trailing punctuation to $trail
1346 # If there is no left bracket, then consider right brackets fair game too
1347 if ( strpos( $url, '(' ) === false ) {
1351 $numSepChars = strspn( strrev( $url ), $sep );
1352 if ( $numSepChars ) {
1353 $trail = substr( $url, -$numSepChars ) . $trail;
1354 $url = substr( $url, 0, -$numSepChars );
1357 $url = Sanitizer
::cleanUrl( $url );
1359 # Is this an external image?
1360 $text = $this->maybeMakeExternalImage( $url );
1361 if ( $text === false ) {
1362 # Not an image, make a link
1363 $text = Linker
::makeExternalLink( $url,
1364 $this->getConverterLanguage()->markNoConversion( $url, true ),
1366 $this->getExternalLinkAttribs( $url ) );
1367 # Register it in the output object...
1368 # Replace unnecessary URL escape codes with their equivalent characters
1369 $pasteurized = self
::replaceUnusualEscapes( $url );
1370 $this->mOutput
->addExternalLink( $pasteurized );
1372 wfProfileOut( __METHOD__
);
1373 return $text . $trail;
1377 * Parse headers and return html
1381 * @param $text string
1385 function doHeadings( $text ) {
1386 wfProfileIn( __METHOD__
);
1387 for ( $i = 6; $i >= 1; --$i ) {
1388 $h = str_repeat( '=', $i );
1389 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1391 wfProfileOut( __METHOD__
);
1396 * Replace single quotes with HTML markup
1399 * @param $text string
1401 * @return string the altered text
1403 function doAllQuotes( $text ) {
1404 wfProfileIn( __METHOD__
);
1406 $lines = StringUtils
::explode( "\n", $text );
1407 foreach ( $lines as $line ) {
1408 $outtext .= $this->doQuotes( $line ) . "\n";
1410 $outtext = substr( $outtext, 0, -1 );
1411 wfProfileOut( __METHOD__
);
1416 * Helper function for doAllQuotes()
1418 * @param $text string
1422 public function doQuotes( $text ) {
1423 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1424 $countarr = count( $arr );
1425 if ( $countarr == 1 ) {
1429 // First, do some preliminary work. This may shift some apostrophes from
1430 // being mark-up to being text. It also counts the number of occurrences
1431 // of bold and italics mark-ups.
1434 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1435 $thislen = strlen( $arr[$i] );
1436 // If there are ever four apostrophes, assume the first is supposed to
1437 // be text, and the remaining three constitute mark-up for bold text.
1438 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1439 if ( $thislen == 4 ) {
1440 $arr[$i - 1] .= "'";
1443 } elseif ( $thislen > 5 ) {
1444 // If there are more than 5 apostrophes in a row, assume they're all
1445 // text except for the last 5.
1446 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1447 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1451 // Count the number of occurrences of bold and italics mark-ups.
1452 if ( $thislen == 2 ) {
1454 } elseif ( $thislen == 3 ) {
1456 } elseif ( $thislen == 5 ) {
1462 // If there is an odd number of both bold and italics, it is likely
1463 // that one of the bold ones was meant to be an apostrophe followed
1464 // by italics. Which one we cannot know for certain, but it is more
1465 // likely to be one that has a single-letter word before it.
1466 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1467 $firstsingleletterword = -1;
1468 $firstmultiletterword = -1;
1470 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1471 if ( strlen( $arr[$i] ) == 3 ) {
1472 $x1 = substr( $arr[$i - 1], -1 );
1473 $x2 = substr( $arr[$i - 1], -2, 1 );
1474 if ( $x1 === ' ' ) {
1475 if ( $firstspace == -1 ) {
1478 } elseif ( $x2 === ' ' ) {
1479 if ( $firstsingleletterword == -1 ) {
1480 $firstsingleletterword = $i;
1481 // if $firstsingleletterword is set, we don't
1482 // look at the other options, so we can bail early.
1486 if ( $firstmultiletterword == -1 ) {
1487 $firstmultiletterword = $i;
1493 // If there is a single-letter word, use it!
1494 if ( $firstsingleletterword > -1 ) {
1495 $arr[$firstsingleletterword] = "''";
1496 $arr[$firstsingleletterword - 1] .= "'";
1497 } elseif ( $firstmultiletterword > -1 ) {
1498 // If not, but there's a multi-letter word, use that one.
1499 $arr[$firstmultiletterword] = "''";
1500 $arr[$firstmultiletterword - 1] .= "'";
1501 } elseif ( $firstspace > -1 ) {
1502 // ... otherwise use the first one that has neither.
1503 // (notice that it is possible for all three to be -1 if, for example,
1504 // there is only one pentuple-apostrophe in the line)
1505 $arr[$firstspace] = "''";
1506 $arr[$firstspace - 1] .= "'";
1510 // Now let's actually convert our apostrophic mush to HTML!
1515 foreach ( $arr as $r ) {
1516 if ( ( $i %
2 ) == 0 ) {
1517 if ( $state === 'both' ) {
1523 $thislen = strlen( $r );
1524 if ( $thislen == 2 ) {
1525 if ( $state === 'i' ) {
1528 } elseif ( $state === 'bi' ) {
1531 } elseif ( $state === 'ib' ) {
1532 $output .= '</b></i><b>';
1534 } elseif ( $state === 'both' ) {
1535 $output .= '<b><i>' . $buffer . '</i>';
1537 } else { // $state can be 'b' or ''
1541 } elseif ( $thislen == 3 ) {
1542 if ( $state === 'b' ) {
1545 } elseif ( $state === 'bi' ) {
1546 $output .= '</i></b><i>';
1548 } elseif ( $state === 'ib' ) {
1551 } elseif ( $state === 'both' ) {
1552 $output .= '<i><b>' . $buffer . '</b>';
1554 } else { // $state can be 'i' or ''
1558 } elseif ( $thislen == 5 ) {
1559 if ( $state === 'b' ) {
1560 $output .= '</b><i>';
1562 } elseif ( $state === 'i' ) {
1563 $output .= '</i><b>';
1565 } elseif ( $state === 'bi' ) {
1566 $output .= '</i></b>';
1568 } elseif ( $state === 'ib' ) {
1569 $output .= '</b></i>';
1571 } elseif ( $state === 'both' ) {
1572 $output .= '<i><b>' . $buffer . '</b></i>';
1574 } else { // ($state == '')
1582 // Now close all remaining tags. Notice that the order is important.
1583 if ( $state === 'b' ||
$state === 'ib' ) {
1586 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1589 if ( $state === 'bi' ) {
1592 // There might be lonely ''''', so make sure we have a buffer
1593 if ( $state === 'both' && $buffer ) {
1594 $output .= '<b><i>' . $buffer . '</i></b>';
1600 * Replace external links (REL)
1602 * Note: this is all very hackish and the order of execution matters a lot.
1603 * Make sure to run tests/parserTests.php if you change this code.
1607 * @param $text string
1609 * @throws MWException
1612 function replaceExternalLinks( $text ) {
1613 wfProfileIn( __METHOD__
);
1615 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1616 if ( $bits === false ) {
1617 wfProfileOut( __METHOD__
);
1618 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1620 $s = array_shift( $bits );
1623 while ( $i < count( $bits ) ) {
1626 $text = $bits[$i++
];
1627 $trail = $bits[$i++
];
1629 # The characters '<' and '>' (which were escaped by
1630 # removeHTMLtags()) should not be included in
1631 # URLs, per RFC 2396.
1633 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1634 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1635 $url = substr( $url, 0, $m2[0][1] );
1638 # If the link text is an image URL, replace it with an <img> tag
1639 # This happened by accident in the original parser, but some people used it extensively
1640 $img = $this->maybeMakeExternalImage( $text );
1641 if ( $img !== false ) {
1647 # Set linktype for CSS - if URL==text, link is essentially free
1648 $linktype = ( $text === $url ) ?
'free' : 'text';
1650 # No link text, e.g. [http://domain.tld/some.link]
1651 if ( $text == '' ) {
1653 $langObj = $this->getTargetLanguage();
1654 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1655 $linktype = 'autonumber';
1657 # Have link text, e.g. [http://domain.tld/some.link text]s
1659 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1662 $text = $this->getConverterLanguage()->markNoConversion( $text );
1664 $url = Sanitizer
::cleanUrl( $url );
1666 # Use the encoded URL
1667 # This means that users can paste URLs directly into the text
1668 # Funny characters like ö aren't valid in URLs anyway
1669 # This was changed in August 2004
1670 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1671 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1673 # Register link in the output object.
1674 # Replace unnecessary URL escape codes with the referenced character
1675 # This prevents spammers from hiding links from the filters
1676 $pasteurized = self
::replaceUnusualEscapes( $url );
1677 $this->mOutput
->addExternalLink( $pasteurized );
1680 wfProfileOut( __METHOD__
);
1684 * Get the rel attribute for a particular external link.
1687 * @param string|bool $url optional URL, to extract the domain from for rel =>
1688 * nofollow if appropriate
1689 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1690 * @return string|null rel attribute for $url
1692 public static function getExternalLinkRel( $url = false, $title = null ) {
1693 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1694 $ns = $title ?
$title->getNamespace() : false;
1695 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1696 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1703 * Get an associative array of additional HTML attributes appropriate for a
1704 * particular external link. This currently may include rel => nofollow
1705 * (depending on configuration, namespace, and the URL's domain) and/or a
1706 * target attribute (depending on configuration).
1708 * @param string|bool $url optional URL, to extract the domain from for rel =>
1709 * nofollow if appropriate
1710 * @return Array associative array of HTML attributes
1712 function getExternalLinkAttribs( $url = false ) {
1714 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1716 if ( $this->mOptions
->getExternalLinkTarget() ) {
1717 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1723 * Replace unusual URL escape codes with their equivalent characters
1725 * @param $url String
1728 * @todo This can merge genuinely required bits in the path or query string,
1729 * breaking legit URLs. A proper fix would treat the various parts of
1730 * the URL differently; as a workaround, just use the output for
1731 * statistical records, not for actual linking/output.
1733 static function replaceUnusualEscapes( $url ) {
1734 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1735 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1739 * Callback function used in replaceUnusualEscapes().
1740 * Replaces unusual URL escape codes with their equivalent character
1742 * @param $matches array
1746 private static function replaceUnusualEscapesCallback( $matches ) {
1747 $char = urldecode( $matches[0] );
1748 $ord = ord( $char );
1749 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1750 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1751 # No, shouldn't be escaped
1754 # Yes, leave it escaped
1760 * make an image if it's allowed, either through the global
1761 * option, through the exception, or through the on-wiki whitelist
1764 * $param $url string
1768 function maybeMakeExternalImage( $url ) {
1769 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1770 $imagesexception = !empty( $imagesfrom );
1772 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1773 if ( $imagesexception && is_array( $imagesfrom ) ) {
1774 $imagematch = false;
1775 foreach ( $imagesfrom as $match ) {
1776 if ( strpos( $url, $match ) === 0 ) {
1781 } elseif ( $imagesexception ) {
1782 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1784 $imagematch = false;
1786 if ( $this->mOptions
->getAllowExternalImages()
1787 ||
( $imagesexception && $imagematch ) ) {
1788 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1790 $text = Linker
::makeExternalImage( $url );
1793 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1794 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1795 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1796 foreach ( $whitelist as $entry ) {
1797 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1798 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1801 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1802 # Image matches a whitelist entry
1803 $text = Linker
::makeExternalImage( $url );
1812 * Process [[ ]] wikilinks
1816 * @return String: processed text
1820 function replaceInternalLinks( $s ) {
1821 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1826 * Process [[ ]] wikilinks (RIL)
1828 * @throws MWException
1829 * @return LinkHolderArray
1833 function replaceInternalLinks2( &$s ) {
1834 wfProfileIn( __METHOD__
);
1836 wfProfileIn( __METHOD__
. '-setup' );
1837 static $tc = false, $e1, $e1_img;
1838 # the % is needed to support urlencoded titles as well
1840 $tc = Title
::legalChars() . '#%';
1841 # Match a link having the form [[namespace:link|alternate]]trail
1842 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1843 # Match cases where there is no "]]", which might still be images
1844 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1847 $holders = new LinkHolderArray( $this );
1849 # split the entire text string on occurrences of [[
1850 $a = StringUtils
::explode( '[[', ' ' . $s );
1851 # get the first element (all text up to first [[), and remove the space we added
1854 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1855 $s = substr( $s, 1 );
1857 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1859 if ( $useLinkPrefixExtension ) {
1860 # Match the end of a line for a word that's not followed by whitespace,
1861 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1862 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1865 if ( is_null( $this->mTitle
) ) {
1866 wfProfileOut( __METHOD__
. '-setup' );
1867 wfProfileOut( __METHOD__
);
1868 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1870 $nottalk = !$this->mTitle
->isTalkPage();
1872 if ( $useLinkPrefixExtension ) {
1874 if ( preg_match( $e2, $s, $m ) ) {
1875 $first_prefix = $m[2];
1877 $first_prefix = false;
1883 $useSubpages = $this->areSubpagesAllowed();
1884 wfProfileOut( __METHOD__
. '-setup' );
1886 # Loop for each link
1887 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1888 # Check for excessive memory usage
1889 if ( $holders->isBig() ) {
1891 # Do the existence check, replace the link holders and clear the array
1892 $holders->replace( $s );
1896 if ( $useLinkPrefixExtension ) {
1897 wfProfileIn( __METHOD__
. '-prefixhandling' );
1898 if ( preg_match( $e2, $s, $m ) ) {
1905 if ( $first_prefix ) {
1906 $prefix = $first_prefix;
1907 $first_prefix = false;
1909 wfProfileOut( __METHOD__
. '-prefixhandling' );
1912 $might_be_img = false;
1914 wfProfileIn( __METHOD__
. "-e1" );
1915 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1917 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1918 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1919 # the real problem is with the $e1 regex
1922 # Still some problems for cases where the ] is meant to be outside punctuation,
1923 # and no image is in sight. See bug 2095.
1925 if ( $text !== '' &&
1926 substr( $m[3], 0, 1 ) === ']' &&
1927 strpos( $text, '[' ) !== false
1930 $text .= ']'; # so that replaceExternalLinks($text) works later
1931 $m[3] = substr( $m[3], 1 );
1933 # fix up urlencoded title texts
1934 if ( strpos( $m[1], '%' ) !== false ) {
1935 # Should anchors '#' also be rejected?
1936 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1939 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1940 $might_be_img = true;
1942 if ( strpos( $m[1], '%' ) !== false ) {
1943 $m[1] = rawurldecode( $m[1] );
1946 } else { # Invalid form; output directly
1947 $s .= $prefix . '[[' . $line;
1948 wfProfileOut( __METHOD__
. "-e1" );
1951 wfProfileOut( __METHOD__
. "-e1" );
1952 wfProfileIn( __METHOD__
. "-misc" );
1954 # Don't allow internal links to pages containing
1955 # PROTO: where PROTO is a valid URL protocol; these
1956 # should be external links.
1957 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1958 $s .= $prefix . '[[' . $line;
1959 wfProfileOut( __METHOD__
. "-misc" );
1963 # Make subpage if necessary
1964 if ( $useSubpages ) {
1965 $link = $this->maybeDoSubpageLink( $m[1], $text );
1970 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1972 # Strip off leading ':'
1973 $link = substr( $link, 1 );
1976 wfProfileOut( __METHOD__
. "-misc" );
1977 wfProfileIn( __METHOD__
. "-title" );
1978 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1979 if ( $nt === null ) {
1980 $s .= $prefix . '[[' . $line;
1981 wfProfileOut( __METHOD__
. "-title" );
1985 $ns = $nt->getNamespace();
1986 $iw = $nt->getInterWiki();
1987 wfProfileOut( __METHOD__
. "-title" );
1989 if ( $might_be_img ) { # if this is actually an invalid link
1990 wfProfileIn( __METHOD__
. "-might_be_img" );
1991 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1994 # look at the next 'line' to see if we can close it there
1996 $next_line = $a->current();
1997 if ( $next_line === false ||
$next_line === null ) {
2000 $m = explode( ']]', $next_line, 3 );
2001 if ( count( $m ) == 3 ) {
2002 # the first ]] closes the inner link, the second the image
2004 $text .= "[[{$m[0]}]]{$m[1]}";
2007 } elseif ( count( $m ) == 2 ) {
2008 # if there's exactly one ]] that's fine, we'll keep looking
2009 $text .= "[[{$m[0]}]]{$m[1]}";
2011 # if $next_line is invalid too, we need look no further
2012 $text .= '[[' . $next_line;
2017 # we couldn't find the end of this imageLink, so output it raw
2018 # but don't ignore what might be perfectly normal links in the text we've examined
2019 $holders->merge( $this->replaceInternalLinks2( $text ) );
2020 $s .= "{$prefix}[[$link|$text";
2021 # note: no $trail, because without an end, there *is* no trail
2022 wfProfileOut( __METHOD__
. "-might_be_img" );
2025 } else { # it's not an image, so output it raw
2026 $s .= "{$prefix}[[$link|$text";
2027 # note: no $trail, because without an end, there *is* no trail
2028 wfProfileOut( __METHOD__
. "-might_be_img" );
2031 wfProfileOut( __METHOD__
. "-might_be_img" );
2034 $wasblank = ( $text == '' );
2038 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2039 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2040 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2041 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2042 $text = $this->doQuotes( $text );
2045 # Link not escaped by : , create the various objects
2048 wfProfileIn( __METHOD__
. "-interwiki" );
2049 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
2050 // XXX: the above check prevents links to sites with identifiers that are not language codes
2052 # Bug 24502: filter duplicates
2053 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2054 $this->mLangLinkLanguages
[$iw] = true;
2055 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2058 $s = rtrim( $s . $prefix );
2059 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2060 wfProfileOut( __METHOD__
. "-interwiki" );
2063 wfProfileOut( __METHOD__
. "-interwiki" );
2065 if ( $ns == NS_FILE
) {
2066 wfProfileIn( __METHOD__
. "-image" );
2067 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2069 # if no parameters were passed, $text
2070 # becomes something like "File:Foo.png",
2071 # which we don't want to pass on to the
2075 # recursively parse links inside the image caption
2076 # actually, this will parse them in any other parameters, too,
2077 # but it might be hard to fix that, and it doesn't matter ATM
2078 $text = $this->replaceExternalLinks( $text );
2079 $holders->merge( $this->replaceInternalLinks2( $text ) );
2081 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2082 $s .= $prefix . $this->armorLinks(
2083 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2085 $s .= $prefix . $trail;
2087 wfProfileOut( __METHOD__
. "-image" );
2091 if ( $ns == NS_CATEGORY
) {
2092 wfProfileIn( __METHOD__
. "-category" );
2093 $s = rtrim( $s . "\n" ); # bug 87
2096 $sortkey = $this->getDefaultSort();
2100 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2101 $sortkey = str_replace( "\n", '', $sortkey );
2102 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2103 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2106 * Strip the whitespace Category links produce, see bug 87
2107 * @todo We might want to use trim($tmp, "\n") here.
2109 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2111 wfProfileOut( __METHOD__
. "-category" );
2116 # Self-link checking
2117 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2118 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2119 $this->mTitle
->getPrefixedText(),
2120 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2123 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2128 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2129 # @todo FIXME: Should do batch file existence checks, see comment below
2130 if ( $ns == NS_MEDIA
) {
2131 wfProfileIn( __METHOD__
. "-media" );
2132 # Give extensions a chance to select the file revision for us
2135 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2136 array( $this, $nt, &$options, &$descQuery ) );
2137 # Fetch and register the file (file title may be different via hooks)
2138 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2139 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2140 $s .= $prefix . $this->armorLinks(
2141 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2142 wfProfileOut( __METHOD__
. "-media" );
2146 wfProfileIn( __METHOD__
. "-always_known" );
2147 # Some titles, such as valid special pages or files in foreign repos, should
2148 # be shown as bluelinks even though they're not included in the page table
2150 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2151 # batch file existence checks for NS_FILE and NS_MEDIA
2152 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2153 $this->mOutput
->addLink( $nt );
2154 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2156 # Links will be added to the output link list after checking
2157 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2159 wfProfileOut( __METHOD__
. "-always_known" );
2161 wfProfileOut( __METHOD__
);
2166 * Render a forced-blue link inline; protect against double expansion of
2167 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2168 * Since this little disaster has to split off the trail text to avoid
2169 * breaking URLs in the following text without breaking trails on the
2170 * wiki links, it's been made into a horrible function.
2173 * @param $text String
2174 * @param array $query or String
2175 * @param $trail String
2176 * @param $prefix String
2177 * @return String: HTML-wikitext mix oh yuck
2179 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2180 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2182 if ( is_string( $query ) ) {
2183 $query = wfCgiToArray( $query );
2185 if ( $text == '' ) {
2186 $text = htmlspecialchars( $nt->getPrefixedText() );
2189 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2191 return $this->armorLinks( $link ) . $trail;
2195 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2196 * going to go through further parsing steps before inline URL expansion.
2198 * Not needed quite as much as it used to be since free links are a bit
2199 * more sensible these days. But bracketed links are still an issue.
2201 * @param string $text more-or-less HTML
2202 * @return String: less-or-more HTML with NOPARSE bits
2204 function armorLinks( $text ) {
2205 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2206 "{$this->mUniqPrefix}NOPARSE$1", $text );
2210 * Return true if subpage links should be expanded on this page.
2213 function areSubpagesAllowed() {
2214 # Some namespaces don't allow subpages
2215 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2219 * Handle link to subpage if necessary
2221 * @param string $target the source of the link
2222 * @param &$text String: the link text, modified as necessary
2223 * @return string the full name of the link
2226 function maybeDoSubpageLink( $target, &$text ) {
2227 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2231 * Used by doBlockLevels()
2236 function closeParagraph() {
2238 if ( $this->mLastSection
!= '' ) {
2239 $result = '</' . $this->mLastSection
. ">\n";
2241 $this->mInPre
= false;
2242 $this->mLastSection
= '';
2247 * getCommon() returns the length of the longest common substring
2248 * of both arguments, starting at the beginning of both.
2251 * @param $st1 string
2252 * @param $st2 string
2256 function getCommon( $st1, $st2 ) {
2257 $fl = strlen( $st1 );
2258 $shorter = strlen( $st2 );
2259 if ( $fl < $shorter ) {
2263 for ( $i = 0; $i < $shorter; ++
$i ) {
2264 if ( $st1[$i] != $st2[$i] ) {
2272 * These next three functions open, continue, and close the list
2273 * element appropriate to the prefix character passed into them.
2276 * @param $char string
2280 function openList( $char ) {
2281 $result = $this->closeParagraph();
2283 if ( '*' === $char ) {
2284 $result .= '<ul><li>';
2285 } elseif ( '#' === $char ) {
2286 $result .= '<ol><li>';
2287 } elseif ( ':' === $char ) {
2288 $result .= '<dl><dd>';
2289 } elseif ( ';' === $char ) {
2290 $result .= '<dl><dt>';
2291 $this->mDTopen
= true;
2293 $result = '<!-- ERR 1 -->';
2301 * @param $char String
2306 function nextItem( $char ) {
2307 if ( '*' === $char ||
'#' === $char ) {
2309 } elseif ( ':' === $char ||
';' === $char ) {
2311 if ( $this->mDTopen
) {
2314 if ( ';' === $char ) {
2315 $this->mDTopen
= true;
2316 return $close . '<dt>';
2318 $this->mDTopen
= false;
2319 return $close . '<dd>';
2322 return '<!-- ERR 2 -->';
2327 * @param $char String
2332 function closeList( $char ) {
2333 if ( '*' === $char ) {
2334 $text = '</li></ul>';
2335 } elseif ( '#' === $char ) {
2336 $text = '</li></ol>';
2337 } elseif ( ':' === $char ) {
2338 if ( $this->mDTopen
) {
2339 $this->mDTopen
= false;
2340 $text = '</dt></dl>';
2342 $text = '</dd></dl>';
2345 return '<!-- ERR 3 -->';
2347 return $text . "\n";
2352 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2354 * @param $text String
2355 * @param $linestart Boolean: whether or not this is at the start of a line.
2357 * @return string the lists rendered as HTML
2359 function doBlockLevels( $text, $linestart ) {
2360 wfProfileIn( __METHOD__
);
2362 # Parsing through the text line by line. The main thing
2363 # happening here is handling of block-level elements p, pre,
2364 # and making lists from lines starting with * # : etc.
2366 $textLines = StringUtils
::explode( "\n", $text );
2368 $lastPrefix = $output = '';
2369 $this->mDTopen
= $inBlockElem = false;
2371 $paragraphStack = false;
2372 $inBlockquote = false;
2374 foreach ( $textLines as $oLine ) {
2376 if ( !$linestart ) {
2386 $lastPrefixLength = strlen( $lastPrefix );
2387 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2388 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2389 # If not in a <pre> element, scan for and figure out what prefixes are there.
2390 if ( !$this->mInPre
) {
2391 # Multiple prefixes may abut each other for nested lists.
2392 $prefixLength = strspn( $oLine, '*#:;' );
2393 $prefix = substr( $oLine, 0, $prefixLength );
2396 # ; and : are both from definition-lists, so they're equivalent
2397 # for the purposes of determining whether or not we need to open/close
2399 $prefix2 = str_replace( ';', ':', $prefix );
2400 $t = substr( $oLine, $prefixLength );
2401 $this->mInPre
= (bool)$preOpenMatch;
2403 # Don't interpret any other prefixes in preformatted text
2405 $prefix = $prefix2 = '';
2410 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2411 # Same as the last item, so no need to deal with nesting or opening stuff
2412 $output .= $this->nextItem( substr( $prefix, -1 ) );
2413 $paragraphStack = false;
2415 if ( substr( $prefix, -1 ) === ';' ) {
2416 # The one nasty exception: definition lists work like this:
2417 # ; title : definition text
2418 # So we check for : in the remainder text to split up the
2419 # title and definition, without b0rking links.
2421 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2423 $output .= $term . $this->nextItem( ':' );
2426 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2427 # We need to open or close prefixes, or both.
2429 # Either open or close a level...
2430 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2431 $paragraphStack = false;
2433 # Close all the prefixes which aren't shared.
2434 while ( $commonPrefixLength < $lastPrefixLength ) {
2435 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2436 --$lastPrefixLength;
2439 # Continue the current prefix if appropriate.
2440 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2441 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2444 # Open prefixes where appropriate.
2445 while ( $prefixLength > $commonPrefixLength ) {
2446 $char = substr( $prefix, $commonPrefixLength, 1 );
2447 $output .= $this->openList( $char );
2449 if ( ';' === $char ) {
2450 # @todo FIXME: This is dupe of code above
2451 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2453 $output .= $term . $this->nextItem( ':' );
2456 ++
$commonPrefixLength;
2458 $lastPrefix = $prefix2;
2461 # If we have no prefixes, go to paragraph mode.
2462 if ( 0 == $prefixLength ) {
2463 wfProfileIn( __METHOD__
. "-paragraph" );
2464 # No prefix (not in list)--go to paragraph mode
2465 # XXX: use a stack for nestable elements like span, table and div
2466 $openmatch = preg_match( '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2467 $closematch = preg_match(
2468 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2469 '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2470 if ( $openmatch or $closematch ) {
2471 $paragraphStack = false;
2472 # TODO bug 5718: paragraph closed
2473 $output .= $this->closeParagraph();
2474 if ( $preOpenMatch and !$preCloseMatch ) {
2475 $this->mInPre
= true;
2478 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2479 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2480 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2482 $inBlockElem = !$closematch;
2483 } elseif ( !$inBlockElem && !$this->mInPre
) {
2484 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) and !$inBlockquote ) {
2486 if ( $this->mLastSection
!== 'pre' ) {
2487 $paragraphStack = false;
2488 $output .= $this->closeParagraph() . '<pre>';
2489 $this->mLastSection
= 'pre';
2491 $t = substr( $t, 1 );
2494 if ( trim( $t ) === '' ) {
2495 if ( $paragraphStack ) {
2496 $output .= $paragraphStack . '<br />';
2497 $paragraphStack = false;
2498 $this->mLastSection
= 'p';
2500 if ( $this->mLastSection
!== 'p' ) {
2501 $output .= $this->closeParagraph();
2502 $this->mLastSection
= '';
2503 $paragraphStack = '<p>';
2505 $paragraphStack = '</p><p>';
2509 if ( $paragraphStack ) {
2510 $output .= $paragraphStack;
2511 $paragraphStack = false;
2512 $this->mLastSection
= 'p';
2513 } elseif ( $this->mLastSection
!== 'p' ) {
2514 $output .= $this->closeParagraph() . '<p>';
2515 $this->mLastSection
= 'p';
2520 wfProfileOut( __METHOD__
. "-paragraph" );
2522 # somewhere above we forget to get out of pre block (bug 785)
2523 if ( $preCloseMatch && $this->mInPre
) {
2524 $this->mInPre
= false;
2526 if ( $paragraphStack === false ) {
2527 $output .= $t . "\n";
2530 while ( $prefixLength ) {
2531 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2534 if ( $this->mLastSection
!= '' ) {
2535 $output .= '</' . $this->mLastSection
. '>';
2536 $this->mLastSection
= '';
2539 wfProfileOut( __METHOD__
);
2544 * Split up a string on ':', ignoring any occurrences inside tags
2545 * to prevent illegal overlapping.
2547 * @param string $str the string to split
2548 * @param &$before String set to everything before the ':'
2549 * @param &$after String set to everything after the ':'
2550 * @throws MWException
2551 * @return String the position of the ':', or false if none found
2553 function findColonNoLinks( $str, &$before, &$after ) {
2554 wfProfileIn( __METHOD__
);
2556 $pos = strpos( $str, ':' );
2557 if ( $pos === false ) {
2559 wfProfileOut( __METHOD__
);
2563 $lt = strpos( $str, '<' );
2564 if ( $lt === false ||
$lt > $pos ) {
2565 # Easy; no tag nesting to worry about
2566 $before = substr( $str, 0, $pos );
2567 $after = substr( $str, $pos +
1 );
2568 wfProfileOut( __METHOD__
);
2572 # Ugly state machine to walk through avoiding tags.
2573 $state = self
::COLON_STATE_TEXT
;
2575 $len = strlen( $str );
2576 for ( $i = 0; $i < $len; $i++
) {
2580 # (Using the number is a performance hack for common cases)
2581 case 0: # self::COLON_STATE_TEXT:
2584 # Could be either a <start> tag or an </end> tag
2585 $state = self
::COLON_STATE_TAGSTART
;
2588 if ( $stack == 0 ) {
2590 $before = substr( $str, 0, $i );
2591 $after = substr( $str, $i +
1 );
2592 wfProfileOut( __METHOD__
);
2595 # Embedded in a tag; don't break it.
2598 # Skip ahead looking for something interesting
2599 $colon = strpos( $str, ':', $i );
2600 if ( $colon === false ) {
2601 # Nothing else interesting
2602 wfProfileOut( __METHOD__
);
2605 $lt = strpos( $str, '<', $i );
2606 if ( $stack === 0 ) {
2607 if ( $lt === false ||
$colon < $lt ) {
2609 $before = substr( $str, 0, $colon );
2610 $after = substr( $str, $colon +
1 );
2611 wfProfileOut( __METHOD__
);
2615 if ( $lt === false ) {
2616 # Nothing else interesting to find; abort!
2617 # We're nested, but there's no close tags left. Abort!
2620 # Skip ahead to next tag start
2622 $state = self
::COLON_STATE_TAGSTART
;
2625 case 1: # self::COLON_STATE_TAG:
2630 $state = self
::COLON_STATE_TEXT
;
2633 # Slash may be followed by >?
2634 $state = self
::COLON_STATE_TAGSLASH
;
2640 case 2: # self::COLON_STATE_TAGSTART:
2643 $state = self
::COLON_STATE_CLOSETAG
;
2646 $state = self
::COLON_STATE_COMMENT
;
2649 # Illegal early close? This shouldn't happen D:
2650 $state = self
::COLON_STATE_TEXT
;
2653 $state = self
::COLON_STATE_TAG
;
2656 case 3: # self::COLON_STATE_CLOSETAG:
2661 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2662 wfProfileOut( __METHOD__
);
2665 $state = self
::COLON_STATE_TEXT
;
2668 case self
::COLON_STATE_TAGSLASH
:
2670 # Yes, a self-closed tag <blah/>
2671 $state = self
::COLON_STATE_TEXT
;
2673 # Probably we're jumping the gun, and this is an attribute
2674 $state = self
::COLON_STATE_TAG
;
2677 case 5: # self::COLON_STATE_COMMENT:
2679 $state = self
::COLON_STATE_COMMENTDASH
;
2682 case self
::COLON_STATE_COMMENTDASH
:
2684 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2686 $state = self
::COLON_STATE_COMMENT
;
2689 case self
::COLON_STATE_COMMENTDASHDASH
:
2691 $state = self
::COLON_STATE_TEXT
;
2693 $state = self
::COLON_STATE_COMMENT
;
2697 wfProfileOut( __METHOD__
);
2698 throw new MWException( "State machine error in " . __METHOD__
);
2702 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2703 wfProfileOut( __METHOD__
);
2706 wfProfileOut( __METHOD__
);
2711 * Return value of a magic variable (like PAGENAME)
2715 * @param $index integer
2716 * @param bool|\PPFrame $frame
2718 * @throws MWException
2721 function getVariableValue( $index, $frame = false ) {
2722 global $wgContLang, $wgSitename, $wgServer;
2723 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2725 if ( is_null( $this->mTitle
) ) {
2726 // If no title set, bad things are going to happen
2727 // later. Title should always be set since this
2728 // should only be called in the middle of a parse
2729 // operation (but the unit-tests do funky stuff)
2730 throw new MWException( __METHOD__
. ' Should only be '
2731 . ' called while parsing (no title set)' );
2735 * Some of these require message or data lookups and can be
2736 * expensive to check many times.
2738 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2739 if ( isset( $this->mVarCache
[$index] ) ) {
2740 return $this->mVarCache
[$index];
2744 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2745 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2747 $pageLang = $this->getFunctionLang();
2750 case 'currentmonth':
2751 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2753 case 'currentmonth1':
2754 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2756 case 'currentmonthname':
2757 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2759 case 'currentmonthnamegen':
2760 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2762 case 'currentmonthabbrev':
2763 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2766 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2769 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2772 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2775 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2777 case 'localmonthname':
2778 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2780 case 'localmonthnamegen':
2781 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2783 case 'localmonthabbrev':
2784 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2787 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2790 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2793 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2796 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2798 case 'fullpagename':
2799 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2801 case 'fullpagenamee':
2802 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2805 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2807 case 'subpagenamee':
2808 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2810 case 'rootpagename':
2811 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2813 case 'rootpagenamee':
2814 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2816 case 'basepagename':
2817 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2819 case 'basepagenamee':
2820 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2822 case 'talkpagename':
2823 if ( $this->mTitle
->canTalk() ) {
2824 $talkPage = $this->mTitle
->getTalkPage();
2825 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2830 case 'talkpagenamee':
2831 if ( $this->mTitle
->canTalk() ) {
2832 $talkPage = $this->mTitle
->getTalkPage();
2833 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2838 case 'subjectpagename':
2839 $subjPage = $this->mTitle
->getSubjectPage();
2840 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2842 case 'subjectpagenamee':
2843 $subjPage = $this->mTitle
->getSubjectPage();
2844 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2846 case 'pageid': // requested in bug 23427
2847 $pageid = $this->getTitle()->getArticleID();
2848 if ( $pageid == 0 ) {
2849 # 0 means the page doesn't exist in the database,
2850 # which means the user is previewing a new page.
2851 # The vary-revision flag must be set, because the magic word
2852 # will have a different value once the page is saved.
2853 $this->mOutput
->setFlag( 'vary-revision' );
2854 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2856 $value = $pageid ?
$pageid : null;
2859 # Let the edit saving system know we should parse the page
2860 # *after* a revision ID has been assigned.
2861 $this->mOutput
->setFlag( 'vary-revision' );
2862 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2863 $value = $this->mRevisionId
;
2866 # Let the edit saving system know we should parse the page
2867 # *after* a revision ID has been assigned. This is for null edits.
2868 $this->mOutput
->setFlag( 'vary-revision' );
2869 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2870 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2872 case 'revisionday2':
2873 # Let the edit saving system know we should parse the page
2874 # *after* a revision ID has been assigned. This is for null edits.
2875 $this->mOutput
->setFlag( 'vary-revision' );
2876 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2877 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2879 case 'revisionmonth':
2880 # Let the edit saving system know we should parse the page
2881 # *after* a revision ID has been assigned. This is for null edits.
2882 $this->mOutput
->setFlag( 'vary-revision' );
2883 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2884 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2886 case 'revisionmonth1':
2887 # Let the edit saving system know we should parse the page
2888 # *after* a revision ID has been assigned. This is for null edits.
2889 $this->mOutput
->setFlag( 'vary-revision' );
2890 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2891 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2893 case 'revisionyear':
2894 # Let the edit saving system know we should parse the page
2895 # *after* a revision ID has been assigned. This is for null edits.
2896 $this->mOutput
->setFlag( 'vary-revision' );
2897 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2898 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2900 case 'revisiontimestamp':
2901 # Let the edit saving system know we should parse the page
2902 # *after* a revision ID has been assigned. This is for null edits.
2903 $this->mOutput
->setFlag( 'vary-revision' );
2904 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2905 $value = $this->getRevisionTimestamp();
2907 case 'revisionuser':
2908 # Let the edit saving system know we should parse the page
2909 # *after* a revision ID has been assigned. This is for null edits.
2910 $this->mOutput
->setFlag( 'vary-revision' );
2911 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2912 $value = $this->getRevisionUser();
2914 case 'revisionsize':
2915 # Let the edit saving system know we should parse the page
2916 # *after* a revision ID has been assigned. This is for null edits.
2917 $this->mOutput
->setFlag( 'vary-revision' );
2918 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
2919 $value = $this->getRevisionSize();
2922 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2925 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2927 case 'namespacenumber':
2928 $value = $this->mTitle
->getNamespace();
2931 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2934 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2936 case 'subjectspace':
2937 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2939 case 'subjectspacee':
2940 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2942 case 'currentdayname':
2943 $value = $pageLang->getWeekdayName( MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2946 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2949 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2952 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2955 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2956 # int to remove the padding
2957 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2960 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2962 case 'localdayname':
2963 $value = $pageLang->getWeekdayName( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1 );
2966 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2969 $value = $pageLang->time( MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2972 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2975 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2976 # int to remove the padding
2977 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2980 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2982 case 'numberofarticles':
2983 $value = $pageLang->formatNum( SiteStats
::articles() );
2985 case 'numberoffiles':
2986 $value = $pageLang->formatNum( SiteStats
::images() );
2988 case 'numberofusers':
2989 $value = $pageLang->formatNum( SiteStats
::users() );
2991 case 'numberofactiveusers':
2992 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2994 case 'numberofpages':
2995 $value = $pageLang->formatNum( SiteStats
::pages() );
2997 case 'numberofadmins':
2998 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3000 case 'numberofedits':
3001 $value = $pageLang->formatNum( SiteStats
::edits() );
3003 case 'numberofviews':
3004 global $wgDisableCounters;
3005 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3007 case 'currenttimestamp':
3008 $value = wfTimestamp( TS_MW
, $ts );
3010 case 'localtimestamp':
3011 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3013 case 'currentversion':
3014 $value = SpecialVersion
::getVersion();
3017 return $wgArticlePath;
3023 $serverParts = wfParseUrl( $wgServer );
3024 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
3026 return $wgScriptPath;
3028 return $wgStylePath;
3029 case 'directionmark':
3030 return $pageLang->getDirMark();
3031 case 'contentlanguage':
3032 global $wgLanguageCode;
3033 return $wgLanguageCode;
3036 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
3044 $this->mVarCache
[$index] = $value;
3051 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3055 function initialiseVariables() {
3056 wfProfileIn( __METHOD__
);
3057 $variableIDs = MagicWord
::getVariableIDs();
3058 $substIDs = MagicWord
::getSubstIDs();
3060 $this->mVariables
= new MagicWordArray( $variableIDs );
3061 $this->mSubstWords
= new MagicWordArray( $substIDs );
3062 wfProfileOut( __METHOD__
);
3066 * Preprocess some wikitext and return the document tree.
3067 * This is the ghost of replace_variables().
3069 * @param string $text The text to parse
3070 * @param $flags Integer: bitwise combination of:
3071 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3072 * included. Default is to assume a direct page view.
3074 * The generated DOM tree must depend only on the input text and the flags.
3075 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3077 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3078 * change in the DOM tree for a given text, must be passed through the section identifier
3079 * in the section edit link and thus back to extractSections().
3081 * The output of this function is currently only cached in process memory, but a persistent
3082 * cache may be implemented at a later date which takes further advantage of these strict
3083 * dependency requirements.
3089 function preprocessToDom( $text, $flags = 0 ) {
3090 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3095 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3101 public static function splitWhitespace( $s ) {
3102 $ltrimmed = ltrim( $s );
3103 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3104 $trimmed = rtrim( $ltrimmed );
3105 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3107 $w2 = substr( $ltrimmed, -$diff );
3111 return array( $w1, $trimmed, $w2 );
3115 * Replace magic variables, templates, and template arguments
3116 * with the appropriate text. Templates are substituted recursively,
3117 * taking care to avoid infinite loops.
3119 * Note that the substitution depends on value of $mOutputType:
3120 * self::OT_WIKI: only {{subst:}} templates
3121 * self::OT_PREPROCESS: templates but not extension tags
3122 * self::OT_HTML: all templates and extension tags
3124 * @param string $text the text to transform
3125 * @param $frame PPFrame Object describing the arguments passed to the template.
3126 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3127 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3128 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3133 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3134 # Is there any text? Also, Prevent too big inclusions!
3135 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3138 wfProfileIn( __METHOD__
);
3140 if ( $frame === false ) {
3141 $frame = $this->getPreprocessor()->newFrame();
3142 } elseif ( !( $frame instanceof PPFrame
) ) {
3143 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3144 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3147 $dom = $this->preprocessToDom( $text );
3148 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3149 $text = $frame->expand( $dom, $flags );
3151 wfProfileOut( __METHOD__
);
3156 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3158 * @param $args array
3162 static function createAssocArgs( $args ) {
3163 $assocArgs = array();
3165 foreach ( $args as $arg ) {
3166 $eqpos = strpos( $arg, '=' );
3167 if ( $eqpos === false ) {
3168 $assocArgs[$index++
] = $arg;
3170 $name = trim( substr( $arg, 0, $eqpos ) );
3171 $value = trim( substr( $arg, $eqpos +
1 ) );
3172 if ( $value === false ) {
3175 if ( $name !== false ) {
3176 $assocArgs[$name] = $value;
3185 * Warn the user when a parser limitation is reached
3186 * Will warn at most once the user per limitation type
3188 * @param string $limitationType should be one of:
3189 * 'expensive-parserfunction' (corresponding messages:
3190 * 'expensive-parserfunction-warning',
3191 * 'expensive-parserfunction-category')
3192 * 'post-expand-template-argument' (corresponding messages:
3193 * 'post-expand-template-argument-warning',
3194 * 'post-expand-template-argument-category')
3195 * 'post-expand-template-inclusion' (corresponding messages:
3196 * 'post-expand-template-inclusion-warning',
3197 * 'post-expand-template-inclusion-category')
3198 * 'node-count-exceeded' (corresponding messages:
3199 * 'node-count-exceeded-warning',
3200 * 'node-count-exceeded-category')
3201 * 'expansion-depth-exceeded' (corresponding messages:
3202 * 'expansion-depth-exceeded-warning',
3203 * 'expansion-depth-exceeded-category')
3204 * @param int|null $current Current value
3205 * @param int|null $max Maximum allowed, when an explicit limit has been
3206 * exceeded, provide the values (optional)
3208 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3209 # does no harm if $current and $max are present but are unnecessary for the message
3210 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3211 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3212 $this->mOutput
->addWarning( $warning );
3213 $this->addTrackingCategory( "$limitationType-category" );
3217 * Return the text of a template, after recursively
3218 * replacing any variables or templates within the template.
3220 * @param array $piece the parts of the template
3221 * $piece['title']: the title, i.e. the part before the |
3222 * $piece['parts']: the parameter array
3223 * $piece['lineStart']: whether the brace was at the start of a line
3224 * @param $frame PPFrame The current frame, contains template arguments
3225 * @throws MWException
3226 * @return String: the text of the template
3229 function braceSubstitution( $piece, $frame ) {
3230 wfProfileIn( __METHOD__
);
3231 wfProfileIn( __METHOD__
. '-setup' );
3234 $found = false; # $text has been filled
3235 $nowiki = false; # wiki markup in $text should be escaped
3236 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3237 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3238 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3239 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3241 # Title object, where $text came from
3244 # $part1 is the bit before the first |, and must contain only title characters.
3245 # Various prefixes will be stripped from it later.
3246 $titleWithSpaces = $frame->expand( $piece['title'] );
3247 $part1 = trim( $titleWithSpaces );
3250 # Original title text preserved for various purposes
3251 $originalTitle = $part1;
3253 # $args is a list of argument nodes, starting from index 0, not including $part1
3254 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3255 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3256 wfProfileOut( __METHOD__
. '-setup' );
3258 $titleProfileIn = null; // profile templates
3261 wfProfileIn( __METHOD__
. '-modifiers' );
3264 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3266 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3267 # Decide whether to expand template or keep wikitext as-is.
3268 if ( $this->ot
['wiki'] ) {
3269 if ( $substMatch === false ) {
3270 $literal = true; # literal when in PST with no prefix
3272 $literal = false; # expand when in PST with subst: or safesubst:
3275 if ( $substMatch == 'subst' ) {
3276 $literal = true; # literal when not in PST with plain subst:
3278 $literal = false; # expand when not in PST with safesubst: or no prefix
3282 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3289 if ( !$found && $args->getLength() == 0 ) {
3290 $id = $this->mVariables
->matchStartToEnd( $part1 );
3291 if ( $id !== false ) {
3292 $text = $this->getVariableValue( $id, $frame );
3293 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3294 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3300 # MSG, MSGNW and RAW
3303 $mwMsgnw = MagicWord
::get( 'msgnw' );
3304 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3307 # Remove obsolete MSG:
3308 $mwMsg = MagicWord
::get( 'msg' );
3309 $mwMsg->matchStartAndRemove( $part1 );
3313 $mwRaw = MagicWord
::get( 'raw' );
3314 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3315 $forceRawInterwiki = true;
3318 wfProfileOut( __METHOD__
. '-modifiers' );
3322 wfProfileIn( __METHOD__
. '-pfunc' );
3324 $colonPos = strpos( $part1, ':' );
3325 if ( $colonPos !== false ) {
3326 $func = substr( $part1, 0, $colonPos );
3327 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3328 for ( $i = 0; $i < $args->getLength(); $i++
) {
3329 $funcArgs[] = $args->item( $i );
3332 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3333 } catch ( Exception
$ex ) {
3334 wfProfileOut( __METHOD__
. '-pfunc' );
3335 wfProfileOut( __METHOD__
);
3339 # The interface for parser functions allows for extracting
3340 # flags into the local scope. Extract any forwarded flags
3344 wfProfileOut( __METHOD__
. '-pfunc' );
3347 # Finish mangling title and then check for loops.
3348 # Set $title to a Title object and $titleText to the PDBK
3351 # Split the title into page and subpage
3353 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3354 if ( $part1 !== $relative ) {
3356 $ns = $this->mTitle
->getNamespace();
3358 $title = Title
::newFromText( $part1, $ns );
3360 $titleText = $title->getPrefixedText();
3361 # Check for language variants if the template is not found
3362 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3363 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3365 # Do recursion depth check
3366 $limit = $this->mOptions
->getMaxTemplateDepth();
3367 if ( $frame->depth
>= $limit ) {
3369 $text = '<span class="error">'
3370 . wfMessage( 'parser-template-recursion-depth-warning' )
3371 ->numParams( $limit )->inContentLanguage()->text()
3377 # Load from database
3378 if ( !$found && $title ) {
3379 if ( !Profiler
::instance()->isPersistent() ) {
3380 # Too many unique items can kill profiling DBs/collectors
3381 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3382 wfProfileIn( $titleProfileIn ); // template in
3384 wfProfileIn( __METHOD__
. '-loadtpl' );
3385 if ( !$title->isExternal() ) {
3386 if ( $title->isSpecialPage()
3387 && $this->mOptions
->getAllowSpecialInclusion()
3388 && $this->ot
['html'] )
3390 // Pass the template arguments as URL parameters.
3391 // "uselang" will have no effect since the Language object
3392 // is forced to the one defined in ParserOptions.
3393 $pageArgs = array();
3394 for ( $i = 0; $i < $args->getLength(); $i++
) {
3395 $bits = $args->item( $i )->splitArg();
3396 if ( strval( $bits['index'] ) === '' ) {
3397 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3398 $value = trim( $frame->expand( $bits['value'] ) );
3399 $pageArgs[$name] = $value;
3403 // Create a new context to execute the special page
3404 $context = new RequestContext
;
3405 $context->setTitle( $title );
3406 $context->setRequest( new FauxRequest( $pageArgs ) );
3407 $context->setUser( $this->getUser() );
3408 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3409 $ret = SpecialPageFactory
::capturePath( $title, $context );
3411 $text = $context->getOutput()->getHTML();
3412 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3415 $this->disableCache();
3417 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3418 $found = false; # access denied
3419 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3421 list( $text, $title ) = $this->getTemplateDom( $title );
3422 if ( $text !== false ) {
3428 # If the title is valid but undisplayable, make a link to it
3429 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3430 $text = "[[:$titleText]]";
3433 } elseif ( $title->isTrans() ) {
3434 # Interwiki transclusion
3435 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3436 $text = $this->interwikiTransclude( $title, 'render' );
3439 $text = $this->interwikiTransclude( $title, 'raw' );
3440 # Preprocess it like a template
3441 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3447 # Do infinite loop check
3448 # This has to be done after redirect resolution to avoid infinite loops via redirects
3449 if ( !$frame->loopCheck( $title ) ) {
3451 $text = '<span class="error">'
3452 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3454 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3456 wfProfileOut( __METHOD__
. '-loadtpl' );
3459 # If we haven't found text to substitute by now, we're done
3460 # Recover the source wikitext and return it
3462 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3463 if ( $titleProfileIn ) {
3464 wfProfileOut( $titleProfileIn ); // template out
3466 wfProfileOut( __METHOD__
);
3467 return array( 'object' => $text );
3470 # Expand DOM-style return values in a child frame
3471 if ( $isChildObj ) {
3472 # Clean up argument array
3473 $newFrame = $frame->newChild( $args, $title );
3476 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3477 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3478 # Expansion is eligible for the empty-frame cache
3479 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3480 $text = $this->mTplExpandCache
[$titleText];
3482 $text = $newFrame->expand( $text );
3483 $this->mTplExpandCache
[$titleText] = $text;
3486 # Uncached expansion
3487 $text = $newFrame->expand( $text );
3490 if ( $isLocalObj && $nowiki ) {
3491 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3492 $isLocalObj = false;
3495 if ( $titleProfileIn ) {
3496 wfProfileOut( $titleProfileIn ); // template out
3499 # Replace raw HTML by a placeholder
3501 $text = $this->insertStripItem( $text );
3502 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3503 # Escape nowiki-style return values
3504 $text = wfEscapeWikiText( $text );
3505 } elseif ( is_string( $text )
3506 && !$piece['lineStart']
3507 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3509 # Bug 529: if the template begins with a table or block-level
3510 # element, it should be treated as beginning a new line.
3511 # This behavior is somewhat controversial.
3512 $text = "\n" . $text;
3515 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3516 # Error, oversize inclusion
3517 if ( $titleText !== false ) {
3518 # Make a working, properly escaped link if possible (bug 23588)
3519 $text = "[[:$titleText]]";
3521 # This will probably not be a working link, but at least it may
3522 # provide some hint of where the problem is
3523 preg_replace( '/^:/', '', $originalTitle );
3524 $text = "[[:$originalTitle]]";
3526 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3527 $this->limitationWarn( 'post-expand-template-inclusion' );
3530 if ( $isLocalObj ) {
3531 $ret = array( 'object' => $text );
3533 $ret = array( 'text' => $text );
3536 wfProfileOut( __METHOD__
);
3541 * Call a parser function and return an array with text and flags.
3543 * The returned array will always contain a boolean 'found', indicating
3544 * whether the parser function was found or not. It may also contain the
3546 * text: string|object, resulting wikitext or PP DOM object
3547 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3548 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3549 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3550 * nowiki: bool, wiki markup in $text should be escaped
3553 * @param $frame PPFrame The current frame, contains template arguments
3554 * @param $function string Function name
3555 * @param $args array Arguments to the function
3558 public function callParserFunction( $frame, $function, array $args = array() ) {
3561 wfProfileIn( __METHOD__
);
3563 # Case sensitive functions
3564 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3565 $function = $this->mFunctionSynonyms
[1][$function];
3567 # Case insensitive functions
3568 $function = $wgContLang->lc( $function );
3569 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3570 $function = $this->mFunctionSynonyms
[0][$function];
3572 wfProfileOut( __METHOD__
);
3573 return array( 'found' => false );
3577 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3578 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3580 # Workaround for PHP bug 35229 and similar
3581 if ( !is_callable( $callback ) ) {
3582 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3583 wfProfileOut( __METHOD__
);
3584 throw new MWException( "Tag hook for $function is not callable\n" );
3587 $allArgs = array( &$this );
3588 if ( $flags & SFH_OBJECT_ARGS
) {
3589 # Convert arguments to PPNodes and collect for appending to $allArgs
3590 $funcArgs = array();
3591 foreach ( $args as $k => $v ) {
3592 if ( $v instanceof PPNode ||
$k === 0 ) {
3595 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3599 # Add a frame parameter, and pass the arguments as an array
3600 $allArgs[] = $frame;
3601 $allArgs[] = $funcArgs;
3603 # Convert arguments to plain text and append to $allArgs
3604 foreach ( $args as $k => $v ) {
3605 if ( $v instanceof PPNode
) {
3606 $allArgs[] = trim( $frame->expand( $v ) );
3607 } elseif ( is_int( $k ) && $k >= 0 ) {
3608 $allArgs[] = trim( $v );
3610 $allArgs[] = trim( "$k=$v" );
3615 $result = call_user_func_array( $callback, $allArgs );
3617 # The interface for function hooks allows them to return a wikitext
3618 # string or an array containing the string and any flags. This mungs
3619 # things around to match what this method should return.
3620 if ( !is_array( $result ) ) {
3626 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3627 $result['text'] = $result[0];
3629 unset( $result[0] );
3636 $preprocessFlags = 0;
3637 if ( isset( $result['noparse'] ) ) {
3638 $noparse = $result['noparse'];
3640 if ( isset( $result['preprocessFlags'] ) ) {
3641 $preprocessFlags = $result['preprocessFlags'];
3645 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3646 $result['isChildObj'] = true;
3648 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3649 wfProfileOut( __METHOD__
);
3655 * Get the semi-parsed DOM representation of a template with a given title,
3656 * and its redirect destination title. Cached.
3658 * @param $title Title
3662 function getTemplateDom( $title ) {
3663 $cacheTitle = $title;
3664 $titleText = $title->getPrefixedDBkey();
3666 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3667 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3668 $title = Title
::makeTitle( $ns, $dbk );
3669 $titleText = $title->getPrefixedDBkey();
3671 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3672 return array( $this->mTplDomCache
[$titleText], $title );
3675 # Cache miss, go to the database
3676 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3678 if ( $text === false ) {
3679 $this->mTplDomCache
[$titleText] = false;
3680 return array( false, $title );
3683 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3684 $this->mTplDomCache
[$titleText] = $dom;
3686 if ( !$title->equals( $cacheTitle ) ) {
3687 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3688 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3691 return array( $dom, $title );
3695 * Fetch the unparsed text of a template and register a reference to it.
3696 * @param Title $title
3697 * @return Array ( string or false, Title )
3699 function fetchTemplateAndTitle( $title ) {
3700 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3701 $stuff = call_user_func( $templateCb, $title, $this );
3702 $text = $stuff['text'];
3703 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3704 if ( isset( $stuff['deps'] ) ) {
3705 foreach ( $stuff['deps'] as $dep ) {
3706 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3707 if ( $dep['title']->equals( $this->getTitle() ) ) {
3708 // If we transclude ourselves, the final result
3709 // will change based on the new version of the page
3710 $this->mOutput
->setFlag( 'vary-revision' );
3714 return array( $text, $finalTitle );
3718 * Fetch the unparsed text of a template and register a reference to it.
3719 * @param Title $title
3720 * @return mixed string or false
3722 function fetchTemplate( $title ) {
3723 $rv = $this->fetchTemplateAndTitle( $title );
3728 * Static function to get a template
3729 * Can be overridden via ParserOptions::setTemplateCallback().
3731 * @param $title Title
3732 * @param $parser Parser
3736 static function statelessFetchTemplate( $title, $parser = false ) {
3737 $text = $skip = false;
3738 $finalTitle = $title;
3741 # Loop to fetch the article, with up to 1 redirect
3742 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3743 # Give extensions a chance to select the revision instead
3744 $id = false; # Assume current
3745 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3746 array( $parser, $title, &$skip, &$id ) );
3752 'page_id' => $title->getArticleID(),
3759 ? Revision
::newFromId( $id )
3760 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3761 $rev_id = $rev ?
$rev->getId() : 0;
3762 # If there is no current revision, there is no page
3763 if ( $id === false && !$rev ) {
3764 $linkCache = LinkCache
::singleton();
3765 $linkCache->addBadLinkObj( $title );
3770 'page_id' => $title->getArticleID(),
3771 'rev_id' => $rev_id );
3772 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3773 # We fetched a rev from a different title; register it too...
3775 'title' => $rev->getTitle(),
3776 'page_id' => $rev->getPage(),
3777 'rev_id' => $rev_id );
3781 $content = $rev->getContent();
3782 $text = $content ?
$content->getWikitextForTransclusion() : null;
3784 if ( $text === false ||
$text === null ) {
3788 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3790 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3791 if ( !$message->exists() ) {
3795 $content = $message->content();
3796 $text = $message->plain();
3804 $finalTitle = $title;
3805 $title = $content->getRedirectTarget();
3809 'finalTitle' => $finalTitle,
3814 * Fetch a file and its title and register a reference to it.
3815 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3816 * @param Title $title
3817 * @param array $options Array of options to RepoGroup::findFile
3820 function fetchFile( $title, $options = array() ) {
3821 $res = $this->fetchFileAndTitle( $title, $options );
3826 * Fetch a file and its title and register a reference to it.
3827 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3828 * @param Title $title
3829 * @param array $options Array of options to RepoGroup::findFile
3830 * @return Array ( File or false, Title of file )
3832 function fetchFileAndTitle( $title, $options = array() ) {
3833 $file = $this->fetchFileNoRegister( $title, $options );
3835 $time = $file ?
$file->getTimestamp() : false;
3836 $sha1 = $file ?
$file->getSha1() : false;
3837 # Register the file as a dependency...
3838 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3839 if ( $file && !$title->equals( $file->getTitle() ) ) {
3840 # Update fetched file title
3841 $title = $file->getTitle();
3842 if ( is_null( $file->getRedirectedTitle() ) ) {
3843 # This file was not a redirect, but the title does not match.
3844 # Register under the new name because otherwise the link will
3846 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3849 return array( $file, $title );
3853 * Helper function for fetchFileAndTitle.
3855 * Also useful if you need to fetch a file but not use it yet,
3856 * for example to get the file's handler.
3858 * @param Title $title
3859 * @param array $options Array of options to RepoGroup::findFile
3860 * @return File or false
3862 protected function fetchFileNoRegister( $title, $options = array() ) {
3863 if ( isset( $options['broken'] ) ) {
3864 $file = false; // broken thumbnail forced by hook
3865 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3866 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3867 } else { // get by (name,timestamp)
3868 $file = wfFindFile( $title, $options );
3874 * Transclude an interwiki link.
3876 * @param $title Title
3881 function interwikiTransclude( $title, $action ) {
3882 global $wgEnableScaryTranscluding;
3884 if ( !$wgEnableScaryTranscluding ) {
3885 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3888 $url = $title->getFullURL( array( 'action' => $action ) );
3890 if ( strlen( $url ) > 255 ) {
3891 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3893 return $this->fetchScaryTemplateMaybeFromCache( $url );
3897 * @param $url string
3898 * @return Mixed|String
3900 function fetchScaryTemplateMaybeFromCache( $url ) {
3901 global $wgTranscludeCacheExpiry;
3902 $dbr = wfGetDB( DB_SLAVE
);
3903 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3904 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3905 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3907 return $obj->tc_contents
;
3910 $req = MWHttpRequest
::factory( $url );
3911 $status = $req->execute(); // Status object
3912 if ( $status->isOK() ) {
3913 $text = $req->getContent();
3914 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3915 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3917 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3920 $dbw = wfGetDB( DB_MASTER
);
3921 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3923 'tc_time' => $dbw->timestamp( time() ),
3924 'tc_contents' => $text
3930 * Triple brace replacement -- used for template arguments
3933 * @param $piece array
3934 * @param $frame PPFrame
3938 function argSubstitution( $piece, $frame ) {
3939 wfProfileIn( __METHOD__
);
3942 $parts = $piece['parts'];
3943 $nameWithSpaces = $frame->expand( $piece['title'] );
3944 $argName = trim( $nameWithSpaces );
3946 $text = $frame->getArgument( $argName );
3947 if ( $text === false && $parts->getLength() > 0
3951 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3954 # No match in frame, use the supplied default
3955 $object = $parts->item( 0 )->getChildren();
3957 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3958 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3959 $this->limitationWarn( 'post-expand-template-argument' );
3962 if ( $text === false && $object === false ) {
3964 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3966 if ( $error !== false ) {
3969 if ( $object !== false ) {
3970 $ret = array( 'object' => $object );
3972 $ret = array( 'text' => $text );
3975 wfProfileOut( __METHOD__
);
3980 * Return the text to be used for a given extension tag.
3981 * This is the ghost of strip().
3983 * @param array $params Associative array of parameters:
3984 * name PPNode for the tag name
3985 * attr PPNode for unparsed text where tag attributes are thought to be
3986 * attributes Optional associative array of parsed attributes
3987 * inner Contents of extension element
3988 * noClose Original text did not have a close tag
3989 * @param $frame PPFrame
3991 * @throws MWException
3994 function extensionSubstitution( $params, $frame ) {
3995 $name = $frame->expand( $params['name'] );
3996 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3997 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3998 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4000 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4001 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4002 if ( $isFunctionTag ) {
4003 $markerType = 'none';
4005 $markerType = 'general';
4007 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4008 $name = strtolower( $name );
4009 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4010 if ( isset( $params['attributes'] ) ) {
4011 $attributes = $attributes +
$params['attributes'];
4014 if ( isset( $this->mTagHooks
[$name] ) ) {
4015 # Workaround for PHP bug 35229 and similar
4016 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4017 throw new MWException( "Tag hook for $name is not callable\n" );
4019 $output = call_user_func_array( $this->mTagHooks
[$name],
4020 array( $content, $attributes, $this, $frame ) );
4021 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4022 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4023 if ( !is_callable( $callback ) ) {
4024 throw new MWException( "Tag hook for $name is not callable\n" );
4027 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4029 $output = '<span class="error">Invalid tag extension name: ' .
4030 htmlspecialchars( $name ) . '</span>';
4033 if ( is_array( $output ) ) {
4034 # Extract flags to local scope (to override $markerType)
4036 $output = $flags[0];
4041 if ( is_null( $attrText ) ) {
4044 if ( isset( $params['attributes'] ) ) {
4045 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4046 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4047 htmlspecialchars( $attrValue ) . '"';
4050 if ( $content === null ) {
4051 $output = "<$name$attrText/>";
4053 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4054 $output = "<$name$attrText>$content$close";
4058 if ( $markerType === 'none' ) {
4060 } elseif ( $markerType === 'nowiki' ) {
4061 $this->mStripState
->addNoWiki( $marker, $output );
4062 } elseif ( $markerType === 'general' ) {
4063 $this->mStripState
->addGeneral( $marker, $output );
4065 throw new MWException( __METHOD__
. ': invalid marker type' );
4071 * Increment an include size counter
4073 * @param string $type the type of expansion
4074 * @param $size Integer: the size of the text
4075 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4077 function incrementIncludeSize( $type, $size ) {
4078 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4081 $this->mIncludeSizes
[$type] +
= $size;
4087 * Increment the expensive function count
4089 * @return Boolean: false if the limit has been exceeded
4091 function incrementExpensiveFunctionCount() {
4092 $this->mExpensiveFunctionCount++
;
4093 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4097 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4098 * Fills $this->mDoubleUnderscores, returns the modified text
4100 * @param $text string
4104 function doDoubleUnderscore( $text ) {
4105 wfProfileIn( __METHOD__
);
4107 # The position of __TOC__ needs to be recorded
4108 $mw = MagicWord
::get( 'toc' );
4109 if ( $mw->match( $text ) ) {
4110 $this->mShowToc
= true;
4111 $this->mForceTocPosition
= true;
4113 # Set a placeholder. At the end we'll fill it in with the TOC.
4114 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4116 # Only keep the first one.
4117 $text = $mw->replace( '', $text );
4120 # Now match and remove the rest of them
4121 $mwa = MagicWord
::getDoubleUnderscoreArray();
4122 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4124 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4125 $this->mOutput
->mNoGallery
= true;
4127 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4128 $this->mShowToc
= false;
4130 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4131 $this->addTrackingCategory( 'hidden-category-category' );
4133 # (bug 8068) Allow control over whether robots index a page.
4135 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4136 # is not desirable, the last one on the page should win.
4137 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4138 $this->mOutput
->setIndexPolicy( 'noindex' );
4139 $this->addTrackingCategory( 'noindex-category' );
4141 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4142 $this->mOutput
->setIndexPolicy( 'index' );
4143 $this->addTrackingCategory( 'index-category' );
4146 # Cache all double underscores in the database
4147 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4148 $this->mOutput
->setProperty( $key, '' );
4151 wfProfileOut( __METHOD__
);
4156 * Add a tracking category, getting the title from a system message,
4157 * or print a debug message if the title is invalid.
4159 * @param string $msg message key
4160 * @return Boolean: whether the addition was successful
4162 public function addTrackingCategory( $msg ) {
4163 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4164 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4167 // Important to parse with correct title (bug 31469)
4168 $cat = wfMessage( $msg )
4169 ->title( $this->getTitle() )
4170 ->inContentLanguage()
4173 # Allow tracking categories to be disabled by setting them to "-"
4174 if ( $cat === '-' ) {
4178 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4179 if ( $containerCategory ) {
4180 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4183 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4189 * This function accomplishes several tasks:
4190 * 1) Auto-number headings if that option is enabled
4191 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4192 * 3) Add a Table of contents on the top for users who have enabled the option
4193 * 4) Auto-anchor headings
4195 * It loops through all headlines, collects the necessary data, then splits up the
4196 * string and re-inserts the newly formatted headlines.
4198 * @param $text String
4199 * @param string $origText original, untouched wikitext
4200 * @param $isMain Boolean
4201 * @return mixed|string
4204 function formatHeadings( $text, $origText, $isMain = true ) {
4205 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4207 # Inhibit editsection links if requested in the page
4208 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4209 $maybeShowEditLink = $showEditLink = false;
4211 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4212 $showEditLink = $this->mOptions
->getEditSection();
4214 if ( $showEditLink ) {
4215 $this->mOutput
->setEditSectionTokens( true );
4218 # Get all headlines for numbering them and adding funky stuff like [edit]
4219 # links - this is for later, but we need the number of headlines right now
4221 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4223 # if there are fewer than 4 headlines in the article, do not show TOC
4224 # unless it's been explicitly enabled.
4225 $enoughToc = $this->mShowToc
&&
4226 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4228 # Allow user to stipulate that a page should have a "new section"
4229 # link added via __NEWSECTIONLINK__
4230 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4231 $this->mOutput
->setNewSection( true );
4234 # Allow user to remove the "new section"
4235 # link via __NONEWSECTIONLINK__
4236 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4237 $this->mOutput
->hideNewSection( true );
4240 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4241 # override above conditions and always show TOC above first header
4242 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4243 $this->mShowToc
= true;
4251 # Ugh .. the TOC should have neat indentation levels which can be
4252 # passed to the skin functions. These are determined here
4256 $sublevelCount = array();
4257 $levelCount = array();
4262 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4263 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4264 $oldType = $this->mOutputType
;
4265 $this->setOutputType( self
::OT_WIKI
);
4266 $frame = $this->getPreprocessor()->newFrame();
4267 $root = $this->preprocessToDom( $origText );
4268 $node = $root->getFirstChild();
4273 foreach ( $matches[3] as $headline ) {
4274 $isTemplate = false;
4276 $sectionIndex = false;
4278 $markerMatches = array();
4279 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4280 $serial = $markerMatches[1];
4281 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4282 $isTemplate = ( $titleText != $baseTitleText );
4283 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4287 $prevlevel = $level;
4289 $level = $matches[1][$headlineCount];
4291 if ( $level > $prevlevel ) {
4292 # Increase TOC level
4294 $sublevelCount[$toclevel] = 0;
4295 if ( $toclevel < $wgMaxTocLevel ) {
4296 $prevtoclevel = $toclevel;
4297 $toc .= Linker
::tocIndent();
4300 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4301 # Decrease TOC level, find level to jump to
4303 for ( $i = $toclevel; $i > 0; $i-- ) {
4304 if ( $levelCount[$i] == $level ) {
4305 # Found last matching level
4308 } elseif ( $levelCount[$i] < $level ) {
4309 # Found first matching level below current level
4317 if ( $toclevel < $wgMaxTocLevel ) {
4318 if ( $prevtoclevel < $wgMaxTocLevel ) {
4319 # Unindent only if the previous toc level was shown :p
4320 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4321 $prevtoclevel = $toclevel;
4323 $toc .= Linker
::tocLineEnd();
4327 # No change in level, end TOC line
4328 if ( $toclevel < $wgMaxTocLevel ) {
4329 $toc .= Linker
::tocLineEnd();
4333 $levelCount[$toclevel] = $level;
4335 # count number of headlines for each level
4336 $sublevelCount[$toclevel]++
;
4338 for ( $i = 1; $i <= $toclevel; $i++
) {
4339 if ( !empty( $sublevelCount[$i] ) ) {
4343 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4348 # The safe header is a version of the header text safe to use for links
4350 # Remove link placeholders by the link text.
4351 # <!--LINK number-->
4353 # link text with suffix
4354 # Do this before unstrip since link text can contain strip markers
4355 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4357 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4358 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4360 # Strip out HTML (first regex removes any tag not allowed)
4362 # * <sup> and <sub> (bug 8393)
4365 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4367 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4368 # to allow setting directionality in toc items.
4369 $tocline = preg_replace(
4370 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4371 array( '', '<$1>' ),
4374 $tocline = trim( $tocline );
4376 # For the anchor, strip out HTML-y stuff period
4377 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4378 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4380 # Save headline for section edit hint before it's escaped
4381 $headlineHint = $safeHeadline;
4383 if ( $wgExperimentalHtmlIds ) {
4384 # For reverse compatibility, provide an id that's
4385 # HTML4-compatible, like we used to.
4387 # It may be worth noting, academically, that it's possible for
4388 # the legacy anchor to conflict with a non-legacy headline
4389 # anchor on the page. In this case likely the "correct" thing
4390 # would be to either drop the legacy anchors or make sure
4391 # they're numbered first. However, this would require people
4392 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4393 # manually, so let's not bother worrying about it.
4394 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4395 array( 'noninitial', 'legacy' ) );
4396 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4398 if ( $legacyHeadline == $safeHeadline ) {
4399 # No reason to have both (in fact, we can't)
4400 $legacyHeadline = false;
4403 $legacyHeadline = false;
4404 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4408 # HTML names must be case-insensitively unique (bug 10721).
4409 # This does not apply to Unicode characters per
4410 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4411 # @todo FIXME: We may be changing them depending on the current locale.
4412 $arrayKey = strtolower( $safeHeadline );
4413 if ( $legacyHeadline === false ) {
4414 $legacyArrayKey = false;
4416 $legacyArrayKey = strtolower( $legacyHeadline );
4419 # count how many in assoc. array so we can track dupes in anchors
4420 if ( isset( $refers[$arrayKey] ) ) {
4421 $refers[$arrayKey]++
;
4423 $refers[$arrayKey] = 1;
4425 if ( isset( $refers[$legacyArrayKey] ) ) {
4426 $refers[$legacyArrayKey]++
;
4428 $refers[$legacyArrayKey] = 1;
4431 # Don't number the heading if it is the only one (looks silly)
4432 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4433 # the two are different if the line contains a link
4434 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4437 # Create the anchor for linking from the TOC to the section
4438 $anchor = $safeHeadline;
4439 $legacyAnchor = $legacyHeadline;
4440 if ( $refers[$arrayKey] > 1 ) {
4441 $anchor .= '_' . $refers[$arrayKey];
4443 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4444 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4446 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4447 $toc .= Linker
::tocLine( $anchor, $tocline,
4448 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4451 # Add the section to the section tree
4452 # Find the DOM node for this header
4453 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4454 while ( $node && !$noOffset ) {
4455 if ( $node->getName() === 'h' ) {
4456 $bits = $node->splitHeading();
4457 if ( $bits['i'] == $sectionIndex ) {
4461 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4462 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4463 $node = $node->getNextSibling();
4466 'toclevel' => $toclevel,
4469 'number' => $numbering,
4470 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4471 'fromtitle' => $titleText,
4472 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4473 'anchor' => $anchor,
4476 # give headline the correct <h#> tag
4477 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4478 // Output edit section links as markers with styles that can be customized by skins
4479 if ( $isTemplate ) {
4480 # Put a T flag in the section identifier, to indicate to extractSections()
4481 # that sections inside <includeonly> should be counted.
4482 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4484 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4486 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4487 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4488 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4489 // so we don't have to worry about a user trying to input one of these markers directly.
4490 // We use a page and section attribute to stop the language converter from converting these important bits
4491 // of data, but put the headline hint inside a content block because the language converter is supposed to
4492 // be able to convert that piece of data.
4493 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4494 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4495 if ( isset( $editlinkArgs[2] ) ) {
4496 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4503 $head[$headlineCount] = Linker
::makeHeadline( $level,
4504 $matches['attrib'][$headlineCount], $anchor, $headline,
4505 $editlink, $legacyAnchor );
4510 $this->setOutputType( $oldType );
4512 # Never ever show TOC if no headers
4513 if ( $numVisible < 1 ) {
4518 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4519 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4521 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4522 $this->mOutput
->setTOCHTML( $toc );
4526 $this->mOutput
->setSections( $tocraw );
4529 # split up and insert constructed headlines
4530 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4533 // build an array of document sections
4534 $sections = array();
4535 foreach ( $blocks as $block ) {
4536 // $head is zero-based, sections aren't.
4537 if ( empty( $head[$i - 1] ) ) {
4538 $sections[$i] = $block;
4540 $sections[$i] = $head[$i - 1] . $block;
4544 * Send a hook, one per section.
4545 * The idea here is to be able to make section-level DIVs, but to do so in a
4546 * lower-impact, more correct way than r50769
4549 * $section : the section number
4550 * &$sectionContent : ref to the content of the section
4551 * $showEditLinks : boolean describing whether this section has an edit link
4553 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4558 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4559 // append the TOC at the beginning
4560 // Top anchor now in skin
4561 $sections[0] = $sections[0] . $toc . "\n";
4564 $full .= join( '', $sections );
4566 if ( $this->mForceTocPosition
) {
4567 return str_replace( '<!--MWTOC-->', $toc, $full );
4574 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4575 * conversion, substitting signatures, {{subst:}} templates, etc.
4577 * @param string $text the text to transform
4578 * @param $title Title: the Title object for the current article
4579 * @param $user User: the User object describing the current user
4580 * @param $options ParserOptions: parsing options
4581 * @param $clearState Boolean: whether to clear the parser state first
4582 * @return String: the altered wiki markup
4584 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4585 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4586 $this->setUser( $user );
4591 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4592 if ( $options->getPreSaveTransform() ) {
4593 $text = $this->pstPass2( $text, $user );
4595 $text = $this->mStripState
->unstripBoth( $text );
4597 $this->setUser( null ); #Reset
4603 * Pre-save transform helper function
4606 * @param $text string
4611 function pstPass2( $text, $user ) {
4614 # Note: This is the timestamp saved as hardcoded wikitext to
4615 # the database, we use $wgContLang here in order to give
4616 # everyone the same signature and use the default one rather
4617 # than the one selected in each user's preferences.
4618 # (see also bug 12815)
4619 $ts = $this->mOptions
->getTimestamp();
4620 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4621 $ts = $timestamp->format( 'YmdHis' );
4622 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4624 # Allow translation of timezones through wiki. format() can return
4625 # whatever crap the system uses, localised or not, so we cannot
4626 # ship premade translations.
4627 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4628 $msg = wfMessage( $key )->inContentLanguage();
4629 if ( $msg->exists() ) {
4630 $tzMsg = $msg->text();
4633 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4635 # Variable replacement
4636 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4637 $text = $this->replaceVariables( $text );
4639 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4640 # which may corrupt this parser instance via its wfMessage()->text() call-
4643 $sigText = $this->getUserSig( $user );
4644 $text = strtr( $text, array(
4646 '~~~~' => "$sigText $d",
4650 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4651 $tc = '[' . Title
::legalChars() . ']';
4652 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4654 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4655 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4656 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4657 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4659 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4660 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4661 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4662 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4664 $t = $this->mTitle
->getText();
4666 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4667 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4668 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4669 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4671 # if there's no context, don't bother duplicating the title
4672 $text = preg_replace( $p2, '[[\\1]]', $text );
4675 # Trim trailing whitespace
4676 $text = rtrim( $text );
4682 * Fetch the user's signature text, if any, and normalize to
4683 * validated, ready-to-insert wikitext.
4684 * If you have pre-fetched the nickname or the fancySig option, you can
4685 * specify them here to save a database query.
4686 * Do not reuse this parser instance after calling getUserSig(),
4687 * as it may have changed if it's the $wgParser.
4690 * @param string|bool $nickname nickname to use or false to use user's default nickname
4691 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4692 * or null to use default value
4695 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4696 global $wgMaxSigChars;
4698 $username = $user->getName();
4700 # If not given, retrieve from the user object.
4701 if ( $nickname === false ) {
4702 $nickname = $user->getOption( 'nickname' );
4705 if ( is_null( $fancySig ) ) {
4706 $fancySig = $user->getBoolOption( 'fancysig' );
4709 $nickname = $nickname == null ?
$username : $nickname;
4711 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4712 $nickname = $username;
4713 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4714 } elseif ( $fancySig !== false ) {
4715 # Sig. might contain markup; validate this
4716 if ( $this->validateSig( $nickname ) !== false ) {
4717 # Validated; clean up (if needed) and return it
4718 return $this->cleanSig( $nickname, true );
4720 # Failed to validate; fall back to the default
4721 $nickname = $username;
4722 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4726 # Make sure nickname doesnt get a sig in a sig
4727 $nickname = self
::cleanSigInSig( $nickname );
4729 # If we're still here, make it a link to the user page
4730 $userText = wfEscapeWikiText( $username );
4731 $nickText = wfEscapeWikiText( $nickname );
4732 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4734 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4738 * Check that the user's signature contains no bad XML
4740 * @param $text String
4741 * @return mixed An expanded string, or false if invalid.
4743 function validateSig( $text ) {
4744 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4748 * Clean up signature text
4750 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4751 * 2) Substitute all transclusions
4753 * @param $text String
4754 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4755 * @return String: signature text
4757 public function cleanSig( $text, $parsing = false ) {
4760 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4763 # Option to disable this feature
4764 if ( !$this->mOptions
->getCleanSignatures() ) {
4768 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4769 # => Move this logic to braceSubstitution()
4770 $substWord = MagicWord
::get( 'subst' );
4771 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4772 $substText = '{{' . $substWord->getSynonym( 0 );
4774 $text = preg_replace( $substRegex, $substText, $text );
4775 $text = self
::cleanSigInSig( $text );
4776 $dom = $this->preprocessToDom( $text );
4777 $frame = $this->getPreprocessor()->newFrame();
4778 $text = $frame->expand( $dom );
4781 $text = $this->mStripState
->unstripBoth( $text );
4788 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4790 * @param $text String
4791 * @return String: signature text with /~{3,5}/ removed
4793 public static function cleanSigInSig( $text ) {
4794 $text = preg_replace( '/~{3,5}/', '', $text );
4799 * Set up some variables which are usually set up in parse()
4800 * so that an external function can call some class members with confidence
4802 * @param $title Title|null
4803 * @param $options ParserOptions
4804 * @param $outputType
4805 * @param $clearState bool
4807 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4808 $this->startParse( $title, $options, $outputType, $clearState );
4812 * @param $title Title|null
4813 * @param $options ParserOptions
4814 * @param $outputType
4815 * @param $clearState bool
4817 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4818 $this->setTitle( $title );
4819 $this->mOptions
= $options;
4820 $this->setOutputType( $outputType );
4821 if ( $clearState ) {
4822 $this->clearState();
4827 * Wrapper for preprocess()
4829 * @param string $text the text to preprocess
4830 * @param $options ParserOptions: options
4831 * @param $title Title object or null to use $wgTitle
4834 public function transformMsg( $text, $options, $title = null ) {
4835 static $executing = false;
4837 # Guard against infinite recursion
4843 wfProfileIn( __METHOD__
);
4849 $text = $this->preprocess( $text, $title, $options );
4852 wfProfileOut( __METHOD__
);
4857 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4858 * The callback should have the following form:
4859 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4861 * Transform and return $text. Use $parser for any required context, e.g. use
4862 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4864 * Hooks may return extended information by returning an array, of which the
4865 * first numbered element (index 0) must be the return string, and all other
4866 * entries are extracted into local variables within an internal function
4867 * in the Parser class.
4869 * This interface (introduced r61913) appears to be undocumented, but
4870 * 'markerName' is used by some core tag hooks to override which strip
4871 * array their results are placed in. **Use great caution if attempting
4872 * this interface, as it is not documented and injudicious use could smash
4873 * private variables.**
4875 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4876 * @param $callback Mixed: the callback function (and object) to use for the tag
4877 * @throws MWException
4878 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4880 public function setHook( $tag, $callback ) {
4881 $tag = strtolower( $tag );
4882 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4883 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4885 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4886 $this->mTagHooks
[$tag] = $callback;
4887 if ( !in_array( $tag, $this->mStripList
) ) {
4888 $this->mStripList
[] = $tag;
4895 * As setHook(), but letting the contents be parsed.
4897 * Transparent tag hooks are like regular XML-style tag hooks, except they
4898 * operate late in the transformation sequence, on HTML instead of wikitext.
4900 * This is probably obsoleted by things dealing with parser frames?
4901 * The only extension currently using it is geoserver.
4904 * @todo better document or deprecate this
4906 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4907 * @param $callback Mixed: the callback function (and object) to use for the tag
4908 * @throws MWException
4909 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4911 function setTransparentTagHook( $tag, $callback ) {
4912 $tag = strtolower( $tag );
4913 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4914 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4916 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4917 $this->mTransparentTagHooks
[$tag] = $callback;
4923 * Remove all tag hooks
4925 function clearTagHooks() {
4926 $this->mTagHooks
= array();
4927 $this->mFunctionTagHooks
= array();
4928 $this->mStripList
= $this->mDefaultStripList
;
4932 * Create a function, e.g. {{sum:1|2|3}}
4933 * The callback function should have the form:
4934 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4936 * Or with SFH_OBJECT_ARGS:
4937 * function myParserFunction( $parser, $frame, $args ) { ... }
4939 * The callback may either return the text result of the function, or an array with the text
4940 * in element 0, and a number of flags in the other elements. The names of the flags are
4941 * specified in the keys. Valid flags are:
4942 * found The text returned is valid, stop processing the template. This
4944 * nowiki Wiki markup in the return value should be escaped
4945 * isHTML The returned text is HTML, armour it against wikitext transformation
4947 * @param string $id The magic word ID
4948 * @param $callback Mixed: the callback function (and object) to use
4949 * @param $flags Integer: a combination of the following flags:
4950 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4952 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4953 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4954 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4955 * the arguments, and to control the way they are expanded.
4957 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4958 * arguments, for instance:
4959 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4961 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4962 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4963 * working if/when this is changed.
4965 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4968 * Please read the documentation in includes/parser/Preprocessor.php for more information
4969 * about the methods available in PPFrame and PPNode.
4971 * @throws MWException
4972 * @return string|callback The old callback function for this name, if any
4974 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4977 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4978 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4980 # Add to function cache
4981 $mw = MagicWord
::get( $id );
4983 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4986 $synonyms = $mw->getSynonyms();
4987 $sensitive = intval( $mw->isCaseSensitive() );
4989 foreach ( $synonyms as $syn ) {
4991 if ( !$sensitive ) {
4992 $syn = $wgContLang->lc( $syn );
4995 if ( !( $flags & SFH_NO_HASH
) ) {
4998 # Remove trailing colon
4999 if ( substr( $syn, -1, 1 ) === ':' ) {
5000 $syn = substr( $syn, 0, -1 );
5002 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5008 * Get all registered function hook identifiers
5012 function getFunctionHooks() {
5013 return array_keys( $this->mFunctionHooks
);
5017 * Create a tag function, e.g. "<test>some stuff</test>".
5018 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5019 * Unlike parser functions, their content is not preprocessed.
5023 * @throws MWException
5026 function setFunctionTagHook( $tag, $callback, $flags ) {
5027 $tag = strtolower( $tag );
5028 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5029 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5031 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5032 $this->mFunctionTagHooks
[$tag] : null;
5033 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5035 if ( !in_array( $tag, $this->mStripList
) ) {
5036 $this->mStripList
[] = $tag;
5043 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5044 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5045 * Placeholders created in Skin::makeLinkObj()
5047 * @param $text string
5048 * @param $options int
5050 * @return array of link CSS classes, indexed by PDBK.
5052 function replaceLinkHolders( &$text, $options = 0 ) {
5053 return $this->mLinkHolders
->replace( $text );
5057 * Replace "<!--LINK-->" link placeholders with plain text of links
5058 * (not HTML-formatted).
5060 * @param $text String
5063 function replaceLinkHoldersText( $text ) {
5064 return $this->mLinkHolders
->replaceText( $text );
5068 * Renders an image gallery from a text with one line per image.
5069 * text labels may be given by using |-style alternative text. E.g.
5070 * Image:one.jpg|The number "1"
5071 * Image:tree.jpg|A tree
5072 * given as text will return the HTML of a gallery with two images,
5073 * labeled 'The number "1"' and
5076 * @param string $text
5077 * @param array $params
5078 * @return string HTML
5080 function renderImageGallery( $text, $params ) {
5081 wfProfileIn( __METHOD__
);
5084 if ( isset( $params['mode'] ) ) {
5085 $mode = $params['mode'];
5089 $ig = ImageGalleryBase
::factory( $mode );
5090 } catch ( MWException
$e ) {
5091 // If invalid type set, fallback to default.
5092 $ig = ImageGalleryBase
::factory( false );
5095 $ig->setContextTitle( $this->mTitle
);
5096 $ig->setShowBytes( false );
5097 $ig->setShowFilename( false );
5098 $ig->setParser( $this );
5099 $ig->setHideBadImages();
5100 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5102 if ( isset( $params['showfilename'] ) ) {
5103 $ig->setShowFilename( true );
5105 $ig->setShowFilename( false );
5107 if ( isset( $params['caption'] ) ) {
5108 $caption = $params['caption'];
5109 $caption = htmlspecialchars( $caption );
5110 $caption = $this->replaceInternalLinks( $caption );
5111 $ig->setCaptionHtml( $caption );
5113 if ( isset( $params['perrow'] ) ) {
5114 $ig->setPerRow( $params['perrow'] );
5116 if ( isset( $params['widths'] ) ) {
5117 $ig->setWidths( $params['widths'] );
5119 if ( isset( $params['heights'] ) ) {
5120 $ig->setHeights( $params['heights'] );
5122 $ig->setAdditionalOptions( $params );
5124 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5126 $lines = StringUtils
::explode( "\n", $text );
5127 foreach ( $lines as $line ) {
5128 # match lines like these:
5129 # Image:someimage.jpg|This is some image
5131 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5133 if ( count( $matches ) == 0 ) {
5137 if ( strpos( $matches[0], '%' ) !== false ) {
5138 $matches[1] = rawurldecode( $matches[1] );
5140 $title = Title
::newFromText( $matches[1], NS_FILE
);
5141 if ( is_null( $title ) ) {
5142 # Bogus title. Ignore these so we don't bomb out later.
5146 # We need to get what handler the file uses, to figure out parameters.
5147 # Note, a hook can overide the file name, and chose an entirely different
5148 # file (which potentially could be of a different type and have different handler).
5151 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5152 array( $this, $title, &$options, &$descQuery ) );
5153 # Don't register it now, as ImageGallery does that later.
5154 $file = $this->fetchFileNoRegister( $title, $options );
5155 $handler = $file ?
$file->getHandler() : false;
5157 wfProfileIn( __METHOD__
. '-getMagicWord' );
5159 'img_alt' => 'gallery-internal-alt',
5160 'img_link' => 'gallery-internal-link',
5163 $paramMap = $paramMap +
$handler->getParamMap();
5164 // We don't want people to specify per-image widths.
5165 // Additionally the width parameter would need special casing anyhow.
5166 unset( $paramMap['img_width'] );
5169 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5170 wfProfileOut( __METHOD__
. '-getMagicWord' );
5175 $handlerOptions = array();
5176 if ( isset( $matches[3] ) ) {
5177 // look for an |alt= definition while trying not to break existing
5178 // captions with multiple pipes (|) in it, until a more sensible grammar
5179 // is defined for images in galleries
5181 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5182 // splitting on '|' is a bit odd, and different from makeImage.
5183 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5184 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5186 foreach ( $parameterMatches as $parameterMatch ) {
5187 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5189 $paramName = $paramMap[$magicName];
5191 switch ( $paramName ) {
5192 case 'gallery-internal-alt':
5193 $alt = $this->stripAltText( $match, false );
5195 case 'gallery-internal-link':
5196 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5197 $chars = self
::EXT_LINK_URL_CLASS
;
5198 $prots = $this->mUrlProtocols
;
5199 //check to see if link matches an absolute url, if not then it must be a wiki link.
5200 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5203 $localLinkTitle = Title
::newFromText( $linkValue );
5204 if ( $localLinkTitle !== null ) {
5205 $link = $localLinkTitle->getLocalURL();
5210 // Must be a handler specific parameter.
5211 if ( $handler->validateParam( $paramName, $match ) ) {
5212 $handlerOptions[$paramName] = $match;
5214 // Guess not. Append it to the caption.
5215 wfDebug( "$parameterMatch failed parameter validation" );
5216 $label .= '|' . $parameterMatch;
5221 // concatenate all other pipes
5222 $label .= '|' . $parameterMatch;
5225 // remove the first pipe
5226 $label = substr( $label, 1 );
5229 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5231 $html = $ig->toHTML();
5232 wfProfileOut( __METHOD__
);
5240 function getImageParams( $handler ) {
5242 $handlerClass = get_class( $handler );
5246 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5247 # Initialise static lists
5248 static $internalParamNames = array(
5249 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5250 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5251 'bottom', 'text-bottom' ),
5252 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5253 'upright', 'border', 'link', 'alt', 'class' ),
5255 static $internalParamMap;
5256 if ( !$internalParamMap ) {
5257 $internalParamMap = array();
5258 foreach ( $internalParamNames as $type => $names ) {
5259 foreach ( $names as $name ) {
5260 $magicName = str_replace( '-', '_', "img_$name" );
5261 $internalParamMap[$magicName] = array( $type, $name );
5266 # Add handler params
5267 $paramMap = $internalParamMap;
5269 $handlerParamMap = $handler->getParamMap();
5270 foreach ( $handlerParamMap as $magic => $paramName ) {
5271 $paramMap[$magic] = array( 'handler', $paramName );
5274 $this->mImageParams
[$handlerClass] = $paramMap;
5275 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5277 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5281 * Parse image options text and use it to make an image
5283 * @param $title Title
5284 * @param $options String
5285 * @param $holders LinkHolderArray|bool
5286 * @return string HTML
5288 function makeImage( $title, $options, $holders = false ) {
5289 # Check if the options text is of the form "options|alt text"
5291 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5292 # * left no resizing, just left align. label is used for alt= only
5293 # * right same, but right aligned
5294 # * none same, but not aligned
5295 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5296 # * center center the image
5297 # * frame Keep original image size, no magnify-button.
5298 # * framed Same as "frame"
5299 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5300 # * upright reduce width for upright images, rounded to full __0 px
5301 # * border draw a 1px border around the image
5302 # * alt Text for HTML alt attribute (defaults to empty)
5303 # * class Set a class for img node
5304 # * link Set the target of the image link. Can be external, interwiki, or local
5305 # vertical-align values (no % or length right now):
5315 $parts = StringUtils
::explode( "|", $options );
5317 # Give extensions a chance to select the file revision for us
5320 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5321 array( $this, $title, &$options, &$descQuery ) );
5322 # Fetch and register the file (file title may be different via hooks)
5323 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5326 $handler = $file ?
$file->getHandler() : false;
5328 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5331 $this->addTrackingCategory( 'broken-file-category' );
5334 # Process the input parameters
5336 $params = array( 'frame' => array(), 'handler' => array(),
5337 'horizAlign' => array(), 'vertAlign' => array() );
5338 foreach ( $parts as $part ) {
5339 $part = trim( $part );
5340 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5342 if ( isset( $paramMap[$magicName] ) ) {
5343 list( $type, $paramName ) = $paramMap[$magicName];
5345 # Special case; width and height come in one variable together
5346 if ( $type === 'handler' && $paramName === 'width' ) {
5347 $parsedWidthParam = $this->parseWidthParam( $value );
5348 if ( isset( $parsedWidthParam['width'] ) ) {
5349 $width = $parsedWidthParam['width'];
5350 if ( $handler->validateParam( 'width', $width ) ) {
5351 $params[$type]['width'] = $width;
5355 if ( isset( $parsedWidthParam['height'] ) ) {
5356 $height = $parsedWidthParam['height'];
5357 if ( $handler->validateParam( 'height', $height ) ) {
5358 $params[$type]['height'] = $height;
5362 # else no validation -- bug 13436
5364 if ( $type === 'handler' ) {
5365 # Validate handler parameter
5366 $validated = $handler->validateParam( $paramName, $value );
5368 # Validate internal parameters
5369 switch ( $paramName ) {
5373 # @todo FIXME: Possibly check validity here for
5374 # manualthumb? downstream behavior seems odd with
5375 # missing manual thumbs.
5377 $value = $this->stripAltText( $value, $holders );
5380 $chars = self
::EXT_LINK_URL_CLASS
;
5381 $prots = $this->mUrlProtocols
;
5382 if ( $value === '' ) {
5383 $paramName = 'no-link';
5386 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5387 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5388 $paramName = 'link-url';
5389 $this->mOutput
->addExternalLink( $value );
5390 if ( $this->mOptions
->getExternalLinkTarget() ) {
5391 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5396 $linkTitle = Title
::newFromText( $value );
5398 $paramName = 'link-title';
5399 $value = $linkTitle;
5400 $this->mOutput
->addLink( $linkTitle );
5406 # Most other things appear to be empty or numeric...
5407 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5412 $params[$type][$paramName] = $value;
5416 if ( !$validated ) {
5421 # Process alignment parameters
5422 if ( $params['horizAlign'] ) {
5423 $params['frame']['align'] = key( $params['horizAlign'] );
5425 if ( $params['vertAlign'] ) {
5426 $params['frame']['valign'] = key( $params['vertAlign'] );
5429 $params['frame']['caption'] = $caption;
5431 # Will the image be presented in a frame, with the caption below?
5432 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5433 isset( $params['frame']['framed'] ) ||
5434 isset( $params['frame']['thumbnail'] ) ||
5435 isset( $params['frame']['manualthumb'] );
5437 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5438 # came to also set the caption, ordinary text after the image -- which
5439 # makes no sense, because that just repeats the text multiple times in
5440 # screen readers. It *also* came to set the title attribute.
5442 # Now that we have an alt attribute, we should not set the alt text to
5443 # equal the caption: that's worse than useless, it just repeats the
5444 # text. This is the framed/thumbnail case. If there's no caption, we
5445 # use the unnamed parameter for alt text as well, just for the time be-
5446 # ing, if the unnamed param is set and the alt param is not.
5448 # For the future, we need to figure out if we want to tweak this more,
5449 # e.g., introducing a title= parameter for the title; ignoring the un-
5450 # named parameter entirely for images without a caption; adding an ex-
5451 # plicit caption= parameter and preserving the old magic unnamed para-
5453 if ( $imageIsFramed ) { # Framed image
5454 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5455 # No caption or alt text, add the filename as the alt text so
5456 # that screen readers at least get some description of the image
5457 $params['frame']['alt'] = $title->getText();
5459 # Do not set $params['frame']['title'] because tooltips don't make sense
5461 } else { # Inline image
5462 if ( !isset( $params['frame']['alt'] ) ) {
5463 # No alt text, use the "caption" for the alt text
5464 if ( $caption !== '' ) {
5465 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5467 # No caption, fall back to using the filename for the
5469 $params['frame']['alt'] = $title->getText();
5472 # Use the "caption" for the tooltip text
5473 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5476 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5478 # Linker does the rest
5479 $time = isset( $options['time'] ) ?
$options['time'] : false;
5480 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5481 $time, $descQuery, $this->mOptions
->getThumbSize() );
5483 # Give the handler a chance to modify the parser object
5485 $handler->parserTransformHook( $this, $file );
5493 * @param $holders LinkHolderArray
5494 * @return mixed|String
5496 protected function stripAltText( $caption, $holders ) {
5497 # Strip bad stuff out of the title (tooltip). We can't just use
5498 # replaceLinkHoldersText() here, because if this function is called
5499 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5501 $tooltip = $holders->replaceText( $caption );
5503 $tooltip = $this->replaceLinkHoldersText( $caption );
5506 # make sure there are no placeholders in thumbnail attributes
5507 # that are later expanded to html- so expand them now and
5509 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5510 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5516 * Set a flag in the output object indicating that the content is dynamic and
5517 * shouldn't be cached.
5519 function disableCache() {
5520 wfDebug( "Parser output marked as uncacheable.\n" );
5521 if ( !$this->mOutput
) {
5522 throw new MWException( __METHOD__
.
5523 " can only be called when actually parsing something" );
5525 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5526 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5530 * Callback from the Sanitizer for expanding items found in HTML attribute
5531 * values, so they can be safely tested and escaped.
5533 * @param $text String
5534 * @param $frame PPFrame
5537 function attributeStripCallback( &$text, $frame = false ) {
5538 $text = $this->replaceVariables( $text, $frame );
5539 $text = $this->mStripState
->unstripBoth( $text );
5548 function getTags() {
5549 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5553 * Replace transparent tags in $text with the values given by the callbacks.
5555 * Transparent tag hooks are like regular XML-style tag hooks, except they
5556 * operate late in the transformation sequence, on HTML instead of wikitext.
5558 * @param $text string
5562 function replaceTransparentTags( $text ) {
5564 $elements = array_keys( $this->mTransparentTagHooks
);
5565 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5566 $replacements = array();
5568 foreach ( $matches as $marker => $data ) {
5569 list( $element, $content, $params, $tag ) = $data;
5570 $tagName = strtolower( $element );
5571 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5572 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5576 $replacements[$marker] = $output;
5578 return strtr( $text, $replacements );
5582 * Break wikitext input into sections, and either pull or replace
5583 * some particular section's text.
5585 * External callers should use the getSection and replaceSection methods.
5587 * @param string $text Page wikitext
5588 * @param string $section a section identifier string of the form:
5589 * "<flag1> - <flag2> - ... - <section number>"
5591 * Currently the only recognised flag is "T", which means the target section number
5592 * was derived during a template inclusion parse, in other words this is a template
5593 * section edit link. If no flags are given, it was an ordinary section edit link.
5594 * This flag is required to avoid a section numbering mismatch when a section is
5595 * enclosed by "<includeonly>" (bug 6563).
5597 * The section number 0 pulls the text before the first heading; other numbers will
5598 * pull the given section along with its lower-level subsections. If the section is
5599 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5601 * Section 0 is always considered to exist, even if it only contains the empty
5602 * string. If $text is the empty string and section 0 is replaced, $newText is
5605 * @param string $mode one of "get" or "replace"
5606 * @param string $newText replacement text for section data.
5607 * @return String: for "get", the extracted section text.
5608 * for "replace", the whole page with the section replaced.
5610 private function extractSections( $text, $section, $mode, $newText = '' ) {
5611 global $wgTitle; # not generally used but removes an ugly failure mode
5612 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5614 $frame = $this->getPreprocessor()->newFrame();
5616 # Process section extraction flags
5618 $sectionParts = explode( '-', $section );
5619 $sectionIndex = array_pop( $sectionParts );
5620 foreach ( $sectionParts as $part ) {
5621 if ( $part === 'T' ) {
5622 $flags |
= self
::PTD_FOR_INCLUSION
;
5626 # Check for empty input
5627 if ( strval( $text ) === '' ) {
5628 # Only sections 0 and T-0 exist in an empty document
5629 if ( $sectionIndex == 0 ) {
5630 if ( $mode === 'get' ) {
5636 if ( $mode === 'get' ) {
5644 # Preprocess the text
5645 $root = $this->preprocessToDom( $text, $flags );
5647 # <h> nodes indicate section breaks
5648 # They can only occur at the top level, so we can find them by iterating the root's children
5649 $node = $root->getFirstChild();
5651 # Find the target section
5652 if ( $sectionIndex == 0 ) {
5653 # Section zero doesn't nest, level=big
5654 $targetLevel = 1000;
5657 if ( $node->getName() === 'h' ) {
5658 $bits = $node->splitHeading();
5659 if ( $bits['i'] == $sectionIndex ) {
5660 $targetLevel = $bits['level'];
5664 if ( $mode === 'replace' ) {
5665 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5667 $node = $node->getNextSibling();
5673 if ( $mode === 'get' ) {
5680 # Find the end of the section, including nested sections
5682 if ( $node->getName() === 'h' ) {
5683 $bits = $node->splitHeading();
5684 $curLevel = $bits['level'];
5685 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5689 if ( $mode === 'get' ) {
5690 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5692 $node = $node->getNextSibling();
5695 # Write out the remainder (in replace mode only)
5696 if ( $mode === 'replace' ) {
5697 # Output the replacement text
5698 # Add two newlines on -- trailing whitespace in $newText is conventionally
5699 # stripped by the editor, so we need both newlines to restore the paragraph gap
5700 # Only add trailing whitespace if there is newText
5701 if ( $newText != "" ) {
5702 $outText .= $newText . "\n\n";
5706 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5707 $node = $node->getNextSibling();
5711 if ( is_string( $outText ) ) {
5712 # Re-insert stripped tags
5713 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5720 * This function returns the text of a section, specified by a number ($section).
5721 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5722 * the first section before any such heading (section 0).
5724 * If a section contains subsections, these are also returned.
5726 * @param string $text text to look in
5727 * @param string $section section identifier
5728 * @param string $deftext default to return if section is not found
5729 * @return string text of the requested section
5731 public function getSection( $text, $section, $deftext = '' ) {
5732 return $this->extractSections( $text, $section, "get", $deftext );
5736 * This function returns $oldtext after the content of the section
5737 * specified by $section has been replaced with $text. If the target
5738 * section does not exist, $oldtext is returned unchanged.
5740 * @param string $oldtext former text of the article
5741 * @param int $section section identifier
5742 * @param string $text replacing text
5743 * @return String: modified text
5745 public function replaceSection( $oldtext, $section, $text ) {
5746 return $this->extractSections( $oldtext, $section, "replace", $text );
5750 * Get the ID of the revision we are parsing
5752 * @return Mixed: integer or null
5754 function getRevisionId() {
5755 return $this->mRevisionId
;
5759 * Get the revision object for $this->mRevisionId
5761 * @return Revision|null either a Revision object or null
5763 protected function getRevisionObject() {
5764 if ( !is_null( $this->mRevisionObject
) ) {
5765 return $this->mRevisionObject
;
5767 if ( is_null( $this->mRevisionId
) ) {
5771 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5772 return $this->mRevisionObject
;
5776 * Get the timestamp associated with the current revision, adjusted for
5777 * the default server-local timestamp
5779 function getRevisionTimestamp() {
5780 if ( is_null( $this->mRevisionTimestamp
) ) {
5781 wfProfileIn( __METHOD__
);
5785 $revObject = $this->getRevisionObject();
5786 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5788 # The cryptic '' timezone parameter tells to use the site-default
5789 # timezone offset instead of the user settings.
5791 # Since this value will be saved into the parser cache, served
5792 # to other users, and potentially even used inside links and such,
5793 # it needs to be consistent for all visitors.
5794 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5796 wfProfileOut( __METHOD__
);
5798 return $this->mRevisionTimestamp
;
5802 * Get the name of the user that edited the last revision
5804 * @return String: user name
5806 function getRevisionUser() {
5807 if ( is_null( $this->mRevisionUser
) ) {
5808 $revObject = $this->getRevisionObject();
5810 # if this template is subst: the revision id will be blank,
5811 # so just use the current user's name
5813 $this->mRevisionUser
= $revObject->getUserText();
5814 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5815 $this->mRevisionUser
= $this->getUser()->getName();
5818 return $this->mRevisionUser
;
5822 * Get the size of the revision
5824 * @return int|null revision size
5826 function getRevisionSize() {
5827 if ( is_null( $this->mRevisionSize
) ) {
5828 $revObject = $this->getRevisionObject();
5830 # if this variable is subst: the revision id will be blank,
5831 # so just use the parser input size, because the own substituation
5832 # will change the size.
5834 $this->mRevisionSize
= $revObject->getSize();
5835 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5836 $this->mRevisionSize
= $this->mInputSize
;
5839 return $this->mRevisionSize
;
5843 * Mutator for $mDefaultSort
5845 * @param string $sort New value
5847 public function setDefaultSort( $sort ) {
5848 $this->mDefaultSort
= $sort;
5849 $this->mOutput
->setProperty( 'defaultsort', $sort );
5853 * Accessor for $mDefaultSort
5854 * Will use the empty string if none is set.
5856 * This value is treated as a prefix, so the
5857 * empty string is equivalent to sorting by
5862 public function getDefaultSort() {
5863 if ( $this->mDefaultSort
!== false ) {
5864 return $this->mDefaultSort
;
5871 * Accessor for $mDefaultSort
5872 * Unlike getDefaultSort(), will return false if none is set
5874 * @return string or false
5876 public function getCustomDefaultSort() {
5877 return $this->mDefaultSort
;
5881 * Try to guess the section anchor name based on a wikitext fragment
5882 * presumably extracted from a heading, for example "Header" from
5885 * @param $text string
5889 public function guessSectionNameFromWikiText( $text ) {
5890 # Strip out wikitext links(they break the anchor)
5891 $text = $this->stripSectionName( $text );
5892 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5893 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5897 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5898 * instead. For use in redirects, since IE6 interprets Redirect: headers
5899 * as something other than UTF-8 (apparently?), resulting in breakage.
5901 * @param string $text The section name
5902 * @return string An anchor
5904 public function guessLegacySectionNameFromWikiText( $text ) {
5905 # Strip out wikitext links(they break the anchor)
5906 $text = $this->stripSectionName( $text );
5907 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5908 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5912 * Strips a text string of wikitext for use in a section anchor
5914 * Accepts a text string and then removes all wikitext from the
5915 * string and leaves only the resultant text (i.e. the result of
5916 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5917 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5918 * to create valid section anchors by mimicing the output of the
5919 * parser when headings are parsed.
5921 * @param string $text text string to be stripped of wikitext
5922 * for use in a Section anchor
5923 * @return string Filtered text string
5925 public function stripSectionName( $text ) {
5926 # Strip internal link markup
5927 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5928 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5930 # Strip external link markup
5931 # @todo FIXME: Not tolerant to blank link text
5932 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5933 # on how many empty links there are on the page - need to figure that out.
5934 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5936 # Parse wikitext quotes (italics & bold)
5937 $text = $this->doQuotes( $text );
5940 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5945 * strip/replaceVariables/unstrip for preprocessor regression testing
5947 * @param $text string
5948 * @param $title Title
5949 * @param $options ParserOptions
5950 * @param $outputType int
5954 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5955 $this->startParse( $title, $options, $outputType, true );
5957 $text = $this->replaceVariables( $text );
5958 $text = $this->mStripState
->unstripBoth( $text );
5959 $text = Sanitizer
::removeHTMLtags( $text );
5964 * @param $text string
5965 * @param $title Title
5966 * @param $options ParserOptions
5969 function testPst( $text, Title
$title, ParserOptions
$options ) {
5970 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5975 * @param $title Title
5976 * @param $options ParserOptions
5979 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5980 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5984 * Call a callback function on all regions of the given text that are not
5985 * inside strip markers, and replace those regions with the return value
5986 * of the callback. For example, with input:
5990 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5991 * two strings will be replaced with the value returned by the callback in
5999 function markerSkipCallback( $s, $callback ) {
6002 while ( $i < strlen( $s ) ) {
6003 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6004 if ( $markerStart === false ) {
6005 $out .= call_user_func( $callback, substr( $s, $i ) );
6008 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6009 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6010 if ( $markerEnd === false ) {
6011 $out .= substr( $s, $markerStart );
6014 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6015 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6024 * Remove any strip markers found in the given text.
6026 * @param $text Input string
6029 function killMarkers( $text ) {
6030 return $this->mStripState
->killMarkers( $text );
6034 * Save the parser state required to convert the given half-parsed text to
6035 * HTML. "Half-parsed" in this context means the output of
6036 * recursiveTagParse() or internalParse(). This output has strip markers
6037 * from replaceVariables (extensionSubstitution() etc.), and link
6038 * placeholders from replaceLinkHolders().
6040 * Returns an array which can be serialized and stored persistently. This
6041 * array can later be loaded into another parser instance with
6042 * unserializeHalfParsedText(). The text can then be safely incorporated into
6043 * the return value of a parser hook.
6045 * @param $text string
6049 function serializeHalfParsedText( $text ) {
6050 wfProfileIn( __METHOD__
);
6053 'version' => self
::HALF_PARSED_VERSION
,
6054 'stripState' => $this->mStripState
->getSubState( $text ),
6055 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6057 wfProfileOut( __METHOD__
);
6062 * Load the parser state given in the $data array, which is assumed to
6063 * have been generated by serializeHalfParsedText(). The text contents is
6064 * extracted from the array, and its markers are transformed into markers
6065 * appropriate for the current Parser instance. This transformed text is
6066 * returned, and can be safely included in the return value of a parser
6069 * If the $data array has been stored persistently, the caller should first
6070 * check whether it is still valid, by calling isValidHalfParsedText().
6072 * @param array $data Serialized data
6073 * @throws MWException
6076 function unserializeHalfParsedText( $data ) {
6077 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6078 throw new MWException( __METHOD__
. ': invalid version' );
6081 # First, extract the strip state.
6082 $texts = array( $data['text'] );
6083 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6085 # Now renumber links
6086 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6088 # Should be good to go.
6093 * Returns true if the given array, presumed to be generated by
6094 * serializeHalfParsedText(), is compatible with the current version of the
6097 * @param $data Array
6101 function isValidHalfParsedText( $data ) {
6102 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6106 * Parsed a width param of imagelink like 300px or 200x300px
6108 * @param $value String
6113 public function parseWidthParam( $value ) {
6114 $parsedWidthParam = array();
6115 if ( $value === '' ) {
6116 return $parsedWidthParam;
6119 # (bug 13500) In both cases (width/height and width only),
6120 # permit trailing "px" for backward compatibility.
6121 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6122 $width = intval( $m[1] );
6123 $height = intval( $m[2] );
6124 $parsedWidthParam['width'] = $width;
6125 $parsedWidthParam['height'] = $height;
6126 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6127 $width = intval( $value );
6128 $parsedWidthParam['width'] = $width;
6130 return $parsedWidthParam;