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 $mRevIdForTs; # The revision ID which was used to fetch the timestamp
195 var $mInputSize = false; # For {{PAGESIZE}} on current page.
203 * @var Array with the language name of each language link (i.e. the
204 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
205 * duplicate language links to the ParserOutput.
207 var $mLangLinkLanguages;
214 public function __construct( $conf = array() ) {
215 $this->mConf
= $conf;
216 $this->mUrlProtocols
= wfUrlProtocols();
217 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
218 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
219 if ( isset( $conf['preprocessorClass'] ) ) {
220 $this->mPreprocessorClass
= $conf['preprocessorClass'];
221 } elseif ( defined( 'HPHP_VERSION' ) ) {
222 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
223 $this->mPreprocessorClass
= 'Preprocessor_Hash';
224 } elseif ( extension_loaded( 'domxml' ) ) {
225 # PECL extension that conflicts with the core DOM extension (bug 13770)
226 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
227 $this->mPreprocessorClass
= 'Preprocessor_Hash';
228 } elseif ( extension_loaded( 'dom' ) ) {
229 $this->mPreprocessorClass
= 'Preprocessor_DOM';
231 $this->mPreprocessorClass
= 'Preprocessor_Hash';
233 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
237 * Reduce memory usage to reduce the impact of circular references
239 function __destruct() {
240 if ( isset( $this->mLinkHolders
) ) {
241 unset( $this->mLinkHolders
);
243 foreach ( $this as $name => $value ) {
244 unset( $this->$name );
249 * Allow extensions to clean up when the parser is cloned
252 wfRunHooks( 'ParserCloned', array( $this ) );
256 * Do various kinds of initialisation on the first call of the parser
258 function firstCallInit() {
259 if ( !$this->mFirstCall
) {
262 $this->mFirstCall
= false;
264 wfProfileIn( __METHOD__
);
266 CoreParserFunctions
::register( $this );
267 CoreTagHooks
::register( $this );
268 $this->initialiseVariables();
270 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
271 wfProfileOut( __METHOD__
);
279 function clearState() {
280 wfProfileIn( __METHOD__
);
281 if ( $this->mFirstCall
) {
282 $this->firstCallInit();
284 $this->mOutput
= new ParserOutput
;
285 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
286 $this->mAutonumber
= 0;
287 $this->mLastSection
= '';
288 $this->mDTopen
= false;
289 $this->mIncludeCount
= array();
290 $this->mArgStack
= false;
291 $this->mInPre
= false;
292 $this->mLinkHolders
= new LinkHolderArray( $this );
294 $this->mRevisionObject
= $this->mRevisionTimestamp
=
295 $this->mRevisionId
= $this->mRevisionUser
= null;
296 $this->mVarCache
= array();
298 $this->mLangLinkLanguages
= array();
301 * Prefix for temporary replacement strings for the multipass parser.
302 * \x07 should never appear in input as it's disallowed in XML.
303 * Using it at the front also gives us a little extra robustness
304 * since it shouldn't match when butted up against identifier-like
307 * Must not consist of all title characters, or else it will change
308 * the behavior of <nowiki> in a link.
310 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
311 $this->mStripState
= new StripState( $this->mUniqPrefix
);
313 # Clear these on every parse, bug 4549
314 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
316 $this->mShowToc
= true;
317 $this->mForceTocPosition
= false;
318 $this->mIncludeSizes
= array(
322 $this->mPPNodeCount
= 0;
323 $this->mGeneratedPPNodeCount
= 0;
324 $this->mHighestExpansionDepth
= 0;
325 $this->mDefaultSort
= false;
326 $this->mHeadings
= array();
327 $this->mDoubleUnderscores
= array();
328 $this->mExpensiveFunctionCount
= 0;
331 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
332 $this->mPreprocessor
= null;
335 wfRunHooks( 'ParserClearState', array( &$this ) );
336 wfProfileOut( __METHOD__
);
340 * Convert wikitext to HTML
341 * Do not call this function recursively.
343 * @param string $text text we want to parse
344 * @param $title Title object
345 * @param $options ParserOptions
346 * @param $linestart boolean
347 * @param $clearState boolean
348 * @param int $revid number to pass in {{REVISIONID}}
349 * @return ParserOutput a ParserOutput
351 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
353 * First pass--just handle <nowiki> sections, pass the rest off
354 * to internalParse() which does all the real work.
357 global $wgUseTidy, $wgAlwaysUseTidy;
358 $fname = __METHOD__
. '-' . wfGetCaller();
359 wfProfileIn( __METHOD__
);
360 wfProfileIn( $fname );
362 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
364 $this->mInputSize
= strlen( $text );
365 if ( $this->mOptions
->getEnableLimitReport() ) {
366 $this->mOutput
->resetParseStartTime();
369 # Remove the strip marker tag prefix from the input, if present.
371 $text = str_replace( $this->mUniqPrefix
, '', $text );
374 $oldRevisionId = $this->mRevisionId
;
375 $oldRevisionObject = $this->mRevisionObject
;
376 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
377 $oldRevisionUser = $this->mRevisionUser
;
378 if ( $revid !== null ) {
379 $this->mRevisionId
= $revid;
380 $this->mRevisionObject
= null;
381 $this->mRevisionTimestamp
= null;
382 $this->mRevisionUser
= null;
385 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
387 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
388 $text = $this->internalParse( $text );
389 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
391 $text = $this->mStripState
->unstripGeneral( $text );
393 # Clean up special characters, only run once, next-to-last before doBlockLevels
395 # french spaces, last one Guillemet-left
396 # only if there is something before the space
397 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
398 # french spaces, Guillemet-right
399 '/(\\302\\253) /' => '\\1 ',
400 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
402 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
404 $text = $this->doBlockLevels( $text, $linestart );
406 $this->replaceLinkHolders( $text );
409 * The input doesn't get language converted if
411 * b) Content isn't converted
412 * c) It's a conversion table
413 * d) it is an interface message (which is in the user language)
415 if ( !( $options->getDisableContentConversion()
416 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
418 if ( !$this->mOptions
->getInterfaceMessage() ) {
419 # The position of the convert() call should not be changed. it
420 # assumes that the links are all replaced and the only thing left
421 # is the <nowiki> mark.
422 $text = $this->getConverterLanguage()->convert( $text );
427 * A converted title will be provided in the output object if title and
428 * content conversion are enabled, the article text does not contain
429 * a conversion-suppressing double-underscore tag, and no
430 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
431 * automatic link conversion.
433 if ( !( $options->getDisableTitleConversion()
434 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
435 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
436 ||
$this->mOutput
->getDisplayTitle() !== false ) )
438 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
439 if ( $convruletitle ) {
440 $this->mOutput
->setTitleText( $convruletitle );
442 $titleText = $this->getConverterLanguage()->convertTitle( $title );
443 $this->mOutput
->setTitleText( $titleText );
447 $text = $this->mStripState
->unstripNoWiki( $text );
449 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
451 $text = $this->replaceTransparentTags( $text );
452 $text = $this->mStripState
->unstripGeneral( $text );
454 $text = Sanitizer
::normalizeCharReferences( $text );
456 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
457 $text = MWTidy
::tidy( $text );
459 # attempt to sanitize at least some nesting problems
460 # (bug #2702 and quite a few others)
462 # ''Something [http://www.cool.com cool''] -->
463 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
464 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
465 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
466 # fix up an anchor inside another anchor, only
467 # at least for a single single nested link (bug 3695)
468 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
469 '\\1\\2</a>\\3</a>\\1\\4</a>',
470 # fix div inside inline elements- doBlockLevels won't wrap a line which
471 # contains a div, so fix it up here; replace
472 # div with escaped text
473 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
474 '\\1\\3<div\\5>\\6</div>\\8\\9',
475 # remove empty italic or bold tag pairs, some
476 # introduced by rules above
477 '/<([bi])><\/\\1>/' => '',
480 $text = preg_replace(
481 array_keys( $tidyregs ),
482 array_values( $tidyregs ),
486 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
487 $this->limitationWarn( 'expensive-parserfunction',
488 $this->mExpensiveFunctionCount
,
489 $this->mOptions
->getExpensiveParserFunctionLimit()
493 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
495 # Information on include size limits, for the benefit of users who try to skirt them
496 if ( $this->mOptions
->getEnableLimitReport() ) {
497 $max = $this->mOptions
->getMaxIncludeSize();
499 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
500 if ( $cpuTime !== null ) {
501 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
502 sprintf( "%.3f", $cpuTime )
506 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
507 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
508 sprintf( "%.3f", $wallTime )
511 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
512 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
514 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
515 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
517 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
518 array( $this->mIncludeSizes
['post-expand'], $max )
520 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
521 array( $this->mIncludeSizes
['arg'], $max )
523 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
524 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
526 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
527 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
529 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
531 $limitReport = "NewPP limit report\n";
532 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
533 if ( wfRunHooks( 'ParserLimitReportFormat',
534 array( $key, $value, &$limitReport, false, false )
536 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
537 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
538 ->inLanguage( 'en' )->useDatabase( false );
539 if ( !$valueMsg->exists() ) {
540 $valueMsg = new RawMessage( '$1' );
542 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
543 $valueMsg->params( $value );
544 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
548 // Since we're not really outputting HTML, decode the entities and
549 // then re-encode the things that need hiding inside HTML comments.
550 $limitReport = htmlspecialchars_decode( $limitReport );
551 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
553 // Sanitize for comment. Note '‐' in the replacement is U+2010,
554 // which looks much like the problematic '-'.
555 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
556 $text .= "\n<!-- \n$limitReport-->\n";
558 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
559 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
560 $this->mTitle
->getPrefixedDBkey() );
563 $this->mOutput
->setText( $text );
565 $this->mRevisionId
= $oldRevisionId;
566 $this->mRevisionObject
= $oldRevisionObject;
567 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
568 $this->mRevisionUser
= $oldRevisionUser;
569 $this->mInputSize
= false;
570 wfProfileOut( $fname );
571 wfProfileOut( __METHOD__
);
573 return $this->mOutput
;
577 * Recursive parser entry point that can be called from an extension tag
580 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
582 * @param string $text text extension wants to have parsed
583 * @param $frame PPFrame: The frame to use for expanding any template variables
587 function recursiveTagParse( $text, $frame = false ) {
588 wfProfileIn( __METHOD__
);
589 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
590 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
591 $text = $this->internalParse( $text, false, $frame );
592 wfProfileOut( __METHOD__
);
597 * Expand templates and variables in the text, producing valid, static wikitext.
598 * Also removes comments.
599 * @return mixed|string
601 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
602 wfProfileIn( __METHOD__
);
603 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
604 if ( $revid !== null ) {
605 $this->mRevisionId
= $revid;
607 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
608 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
609 $text = $this->replaceVariables( $text );
610 $text = $this->mStripState
->unstripBoth( $text );
611 wfProfileOut( __METHOD__
);
616 * Recursive parser entry point that can be called from an extension tag
619 * @param string $text text to be expanded
620 * @param $frame PPFrame: The frame to use for expanding any template variables
624 public function recursivePreprocess( $text, $frame = false ) {
625 wfProfileIn( __METHOD__
);
626 $text = $this->replaceVariables( $text, $frame );
627 $text = $this->mStripState
->unstripBoth( $text );
628 wfProfileOut( __METHOD__
);
633 * Process the wikitext for the "?preload=" feature. (bug 5210)
635 * "<noinclude>", "<includeonly>" etc. are parsed as for template
636 * transclusion, comments, templates, arguments, tags hooks and parser
637 * functions are untouched.
639 * @param $text String
640 * @param $title Title
641 * @param $options ParserOptions
644 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
645 # Parser (re)initialisation
646 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
648 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
649 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
650 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
651 $text = $this->mStripState
->unstripBoth( $text );
656 * Get a random string
660 public static function getRandomString() {
661 return wfRandomString( 16 );
665 * Set the current user.
666 * Should only be used when doing pre-save transform.
668 * @param $user Mixed: User object or null (to reset)
670 function setUser( $user ) {
671 $this->mUser
= $user;
675 * Accessor for mUniqPrefix.
679 public function uniqPrefix() {
680 if ( !isset( $this->mUniqPrefix
) ) {
681 # @todo FIXME: This is probably *horribly wrong*
682 # LanguageConverter seems to want $wgParser's uniqPrefix, however
683 # if this is called for a parser cache hit, the parser may not
684 # have ever been initialized in the first place.
685 # Not really sure what the heck is supposed to be going on here.
687 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
689 return $this->mUniqPrefix
;
693 * Set the context title
697 function setTitle( $t ) {
698 if ( !$t ||
$t instanceof FakeTitle
) {
699 $t = Title
::newFromText( 'NO TITLE' );
702 if ( strval( $t->getFragment() ) !== '' ) {
703 # Strip the fragment to avoid various odd effects
704 $this->mTitle
= clone $t;
705 $this->mTitle
->setFragment( '' );
712 * Accessor for the Title object
714 * @return Title object
716 function getTitle() {
717 return $this->mTitle
;
721 * Accessor/mutator for the Title object
723 * @param $x Title object or null to just get the current one
724 * @return Title object
726 function Title( $x = null ) {
727 return wfSetVar( $this->mTitle
, $x );
731 * Set the output type
733 * @param $ot Integer: new value
735 function setOutputType( $ot ) {
736 $this->mOutputType
= $ot;
739 'html' => $ot == self
::OT_HTML
,
740 'wiki' => $ot == self
::OT_WIKI
,
741 'pre' => $ot == self
::OT_PREPROCESS
,
742 'plain' => $ot == self
::OT_PLAIN
,
747 * Accessor/mutator for the output type
749 * @param int|null $x New value or null to just get the current one
752 function OutputType( $x = null ) {
753 return wfSetVar( $this->mOutputType
, $x );
757 * Get the ParserOutput object
759 * @return ParserOutput object
761 function getOutput() {
762 return $this->mOutput
;
766 * Get the ParserOptions object
768 * @return ParserOptions object
770 function getOptions() {
771 return $this->mOptions
;
775 * Accessor/mutator for the ParserOptions object
777 * @param $x ParserOptions New value or null to just get the current one
778 * @return ParserOptions Current ParserOptions object
780 function Options( $x = null ) {
781 return wfSetVar( $this->mOptions
, $x );
787 function nextLinkID() {
788 return $this->mLinkID++
;
794 function setLinkID( $id ) {
795 $this->mLinkID
= $id;
799 * Get a language object for use in parser functions such as {{FORMATNUM:}}
802 function getFunctionLang() {
803 return $this->getTargetLanguage();
807 * Get the target language for the content being parsed. This is usually the
808 * language that the content is in.
812 * @throws MWException
813 * @return Language|null
815 public function getTargetLanguage() {
816 $target = $this->mOptions
->getTargetLanguage();
818 if ( $target !== null ) {
820 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
821 return $this->mOptions
->getUserLangObj();
822 } elseif ( is_null( $this->mTitle
) ) {
823 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
826 return $this->mTitle
->getPageLanguage();
830 * Get the language object for language conversion
832 function getConverterLanguage() {
833 return $this->getTargetLanguage();
837 * Get a User object either from $this->mUser, if set, or from the
838 * ParserOptions object otherwise
840 * @return User object
843 if ( !is_null( $this->mUser
) ) {
846 return $this->mOptions
->getUser();
850 * Get a preprocessor object
852 * @return Preprocessor instance
854 function getPreprocessor() {
855 if ( !isset( $this->mPreprocessor
) ) {
856 $class = $this->mPreprocessorClass
;
857 $this->mPreprocessor
= new $class( $this );
859 return $this->mPreprocessor
;
863 * Replaces all occurrences of HTML-style comments and the given tags
864 * in the text with a random marker and returns the next text. The output
865 * parameter $matches will be an associative array filled with data in
869 * 'UNIQ-xxxxx' => array(
872 * array( 'param' => 'x' ),
873 * '<element param="x">tag content</element>' ) )
876 * @param array $elements list of element names. Comments are always extracted.
877 * @param string $text Source text string.
878 * @param array $matches Out parameter, Array: extracted tags
879 * @param $uniq_prefix string
880 * @return String: stripped text
882 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
887 $taglist = implode( '|', $elements );
888 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
890 while ( $text != '' ) {
891 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
893 if ( count( $p ) < 5 ) {
896 if ( count( $p ) > 5 ) {
910 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
911 $stripped .= $marker;
913 if ( $close === '/>' ) {
914 # Empty element tag, <tag />
919 if ( $element === '!--' ) {
922 $end = "/(<\\/$element\\s*>)/i";
924 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
926 if ( count( $q ) < 3 ) {
927 # No end tag -- let it run out to the end of the text.
936 $matches[$marker] = array( $element,
938 Sanitizer
::decodeTagAttributes( $attributes ),
939 "<$element$attributes$close$content$tail" );
945 * Get a list of strippable XML-like elements
949 function getStripList() {
950 return $this->mStripList
;
954 * Add an item to the strip state
955 * Returns the unique tag which must be inserted into the stripped text
956 * The tag will be replaced with the original text in unstrip()
958 * @param $text string
962 function insertStripItem( $text ) {
963 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
964 $this->mMarkerIndex++
;
965 $this->mStripState
->addGeneral( $rnd, $text );
970 * parse the wiki syntax used to render tables
975 function doTableStuff( $text ) {
976 wfProfileIn( __METHOD__
);
978 $lines = StringUtils
::explode( "\n", $text );
980 $td_history = array(); # Is currently a td tag open?
981 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
982 $tr_history = array(); # Is currently a tr tag open?
983 $tr_attributes = array(); # history of tr attributes
984 $has_opened_tr = array(); # Did this table open a <tr> element?
985 $indent_level = 0; # indent level of the table
987 foreach ( $lines as $outLine ) {
988 $line = trim( $outLine );
990 if ( $line === '' ) { # empty line, go to next line
991 $out .= $outLine . "\n";
995 $first_character = $line[0];
998 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
999 # First check if we are starting a new table
1000 $indent_level = strlen( $matches[1] );
1002 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1003 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1005 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1006 array_push( $td_history, false );
1007 array_push( $last_tag_history, '' );
1008 array_push( $tr_history, false );
1009 array_push( $tr_attributes, '' );
1010 array_push( $has_opened_tr, false );
1011 } elseif ( count( $td_history ) == 0 ) {
1012 # Don't do any of the following
1013 $out .= $outLine . "\n";
1015 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1016 # We are ending a table
1017 $line = '</table>' . substr( $line, 2 );
1018 $last_tag = array_pop( $last_tag_history );
1020 if ( !array_pop( $has_opened_tr ) ) {
1021 $line = "<tr><td></td></tr>{$line}";
1024 if ( array_pop( $tr_history ) ) {
1025 $line = "</tr>{$line}";
1028 if ( array_pop( $td_history ) ) {
1029 $line = "</{$last_tag}>{$line}";
1031 array_pop( $tr_attributes );
1032 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1033 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1034 # Now we have a table row
1035 $line = preg_replace( '#^\|-+#', '', $line );
1037 # Whats after the tag is now only attributes
1038 $attributes = $this->mStripState
->unstripBoth( $line );
1039 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1040 array_pop( $tr_attributes );
1041 array_push( $tr_attributes, $attributes );
1044 $last_tag = array_pop( $last_tag_history );
1045 array_pop( $has_opened_tr );
1046 array_push( $has_opened_tr, true );
1048 if ( array_pop( $tr_history ) ) {
1052 if ( array_pop( $td_history ) ) {
1053 $line = "</{$last_tag}>{$line}";
1057 array_push( $tr_history, false );
1058 array_push( $td_history, false );
1059 array_push( $last_tag_history, '' );
1060 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1061 # This might be cell elements, td, th or captions
1062 if ( substr( $line, 0, 2 ) === '|+' ) {
1063 $first_character = '+';
1064 $line = substr( $line, 1 );
1067 $line = substr( $line, 1 );
1069 if ( $first_character === '!' ) {
1070 $line = str_replace( '!!', '||', $line );
1073 # Split up multiple cells on the same line.
1074 # FIXME : This can result in improper nesting of tags processed
1075 # by earlier parser steps, but should avoid splitting up eg
1076 # attribute values containing literal "||".
1077 $cells = StringUtils
::explodeMarkup( '||', $line );
1081 # Loop through each table cell
1082 foreach ( $cells as $cell ) {
1084 if ( $first_character !== '+' ) {
1085 $tr_after = array_pop( $tr_attributes );
1086 if ( !array_pop( $tr_history ) ) {
1087 $previous = "<tr{$tr_after}>\n";
1089 array_push( $tr_history, true );
1090 array_push( $tr_attributes, '' );
1091 array_pop( $has_opened_tr );
1092 array_push( $has_opened_tr, true );
1095 $last_tag = array_pop( $last_tag_history );
1097 if ( array_pop( $td_history ) ) {
1098 $previous = "</{$last_tag}>\n{$previous}";
1101 if ( $first_character === '|' ) {
1103 } elseif ( $first_character === '!' ) {
1105 } elseif ( $first_character === '+' ) {
1106 $last_tag = 'caption';
1111 array_push( $last_tag_history, $last_tag );
1113 # A cell could contain both parameters and data
1114 $cell_data = explode( '|', $cell, 2 );
1116 # Bug 553: Note that a '|' inside an invalid link should not
1117 # be mistaken as delimiting cell parameters
1118 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1119 $cell = "{$previous}<{$last_tag}>{$cell}";
1120 } elseif ( count( $cell_data ) == 1 ) {
1121 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1123 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1124 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1125 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1129 array_push( $td_history, true );
1132 $out .= $outLine . "\n";
1135 # Closing open td, tr && table
1136 while ( count( $td_history ) > 0 ) {
1137 if ( array_pop( $td_history ) ) {
1140 if ( array_pop( $tr_history ) ) {
1143 if ( !array_pop( $has_opened_tr ) ) {
1144 $out .= "<tr><td></td></tr>\n";
1147 $out .= "</table>\n";
1150 # Remove trailing line-ending (b/c)
1151 if ( substr( $out, -1 ) === "\n" ) {
1152 $out = substr( $out, 0, -1 );
1155 # special case: don't return empty table
1156 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1160 wfProfileOut( __METHOD__
);
1166 * Helper function for parse() that transforms wiki markup into
1167 * HTML. Only called for $mOutputType == self::OT_HTML.
1171 * @param $text string
1172 * @param $isMain bool
1173 * @param $frame bool
1177 function internalParse( $text, $isMain = true, $frame = false ) {
1178 wfProfileIn( __METHOD__
);
1182 # Hook to suspend the parser in this state
1183 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1184 wfProfileOut( __METHOD__
);
1188 # if $frame is provided, then use $frame for replacing any variables
1190 # use frame depth to infer how include/noinclude tags should be handled
1191 # depth=0 means this is the top-level document; otherwise it's an included document
1192 if ( !$frame->depth
) {
1195 $flag = Parser
::PTD_FOR_INCLUSION
;
1197 $dom = $this->preprocessToDom( $text, $flag );
1198 $text = $frame->expand( $dom );
1200 # if $frame is not provided, then use old-style replaceVariables
1201 $text = $this->replaceVariables( $text );
1204 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1205 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1206 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1208 # Tables need to come after variable replacement for things to work
1209 # properly; putting them before other transformations should keep
1210 # exciting things like link expansions from showing up in surprising
1212 $text = $this->doTableStuff( $text );
1214 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1216 $text = $this->doDoubleUnderscore( $text );
1218 $text = $this->doHeadings( $text );
1219 $text = $this->replaceInternalLinks( $text );
1220 $text = $this->doAllQuotes( $text );
1221 $text = $this->replaceExternalLinks( $text );
1223 # replaceInternalLinks may sometimes leave behind
1224 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1225 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1227 $text = $this->doMagicLinks( $text );
1228 $text = $this->formatHeadings( $text, $origText, $isMain );
1230 wfProfileOut( __METHOD__
);
1235 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1236 * magic external links.
1241 * @param $text string
1245 function doMagicLinks( $text ) {
1246 wfProfileIn( __METHOD__
);
1247 $prots = wfUrlProtocolsWithoutProtRel();
1248 $urlChar = self
::EXT_LINK_URL_CLASS
;
1249 $text = preg_replace_callback(
1251 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1252 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1253 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1254 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1255 ISBN\s+(\b # m[5]: ISBN, capture number
1256 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1257 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1258 [0-9Xx] # check digit
1260 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1261 wfProfileOut( __METHOD__
);
1266 * @throws MWException
1268 * @return HTML|string
1270 function magicLinkCallback( $m ) {
1271 if ( isset( $m[1] ) && $m[1] !== '' ) {
1274 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1277 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1278 # Free external link
1279 return $this->makeFreeExternalLink( $m[0] );
1280 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1282 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1285 $CssClass = 'mw-magiclink-rfc';
1287 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1289 $urlmsg = 'pubmedurl';
1290 $CssClass = 'mw-magiclink-pmid';
1293 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1294 substr( $m[0], 0, 20 ) . '"' );
1296 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1297 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1298 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1301 $num = strtr( $isbn, array(
1306 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1307 return '<a href="' .
1308 htmlspecialchars( $titleObj->getLocalURL() ) .
1309 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1316 * Make a free external link, given a user-supplied URL
1318 * @param $url string
1320 * @return string HTML
1323 function makeFreeExternalLink( $url ) {
1324 wfProfileIn( __METHOD__
);
1328 # The characters '<' and '>' (which were escaped by
1329 # removeHTMLtags()) should not be included in
1330 # URLs, per RFC 2396.
1332 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1333 $trail = substr( $url, $m2[0][1] ) . $trail;
1334 $url = substr( $url, 0, $m2[0][1] );
1337 # Move trailing punctuation to $trail
1339 # If there is no left bracket, then consider right brackets fair game too
1340 if ( strpos( $url, '(' ) === false ) {
1344 $numSepChars = strspn( strrev( $url ), $sep );
1345 if ( $numSepChars ) {
1346 $trail = substr( $url, -$numSepChars ) . $trail;
1347 $url = substr( $url, 0, -$numSepChars );
1350 $url = Sanitizer
::cleanUrl( $url );
1352 # Is this an external image?
1353 $text = $this->maybeMakeExternalImage( $url );
1354 if ( $text === false ) {
1355 # Not an image, make a link
1356 $text = Linker
::makeExternalLink( $url,
1357 $this->getConverterLanguage()->markNoConversion( $url, true ),
1359 $this->getExternalLinkAttribs( $url ) );
1360 # Register it in the output object...
1361 # Replace unnecessary URL escape codes with their equivalent characters
1362 $pasteurized = self
::replaceUnusualEscapes( $url );
1363 $this->mOutput
->addExternalLink( $pasteurized );
1365 wfProfileOut( __METHOD__
);
1366 return $text . $trail;
1370 * Parse headers and return html
1374 * @param $text string
1378 function doHeadings( $text ) {
1379 wfProfileIn( __METHOD__
);
1380 for ( $i = 6; $i >= 1; --$i ) {
1381 $h = str_repeat( '=', $i );
1382 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1384 wfProfileOut( __METHOD__
);
1389 * Replace single quotes with HTML markup
1392 * @param $text string
1394 * @return string the altered text
1396 function doAllQuotes( $text ) {
1397 wfProfileIn( __METHOD__
);
1399 $lines = StringUtils
::explode( "\n", $text );
1400 foreach ( $lines as $line ) {
1401 $outtext .= $this->doQuotes( $line ) . "\n";
1403 $outtext = substr( $outtext, 0, -1 );
1404 wfProfileOut( __METHOD__
);
1409 * Helper function for doAllQuotes()
1411 * @param $text string
1415 public function doQuotes( $text ) {
1416 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1417 $countarr = count( $arr );
1418 if ( $countarr == 1 ) {
1422 // First, do some preliminary work. This may shift some apostrophes from
1423 // being mark-up to being text. It also counts the number of occurrences
1424 // of bold and italics mark-ups.
1427 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1428 $thislen = strlen( $arr[$i] );
1429 // If there are ever four apostrophes, assume the first is supposed to
1430 // be text, and the remaining three constitute mark-up for bold text.
1431 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1432 if ( $thislen == 4 ) {
1433 $arr[$i - 1] .= "'";
1436 } elseif ( $thislen > 5 ) {
1437 // If there are more than 5 apostrophes in a row, assume they're all
1438 // text except for the last 5.
1439 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1440 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1444 // Count the number of occurrences of bold and italics mark-ups.
1445 if ( $thislen == 2 ) {
1447 } elseif ( $thislen == 3 ) {
1449 } elseif ( $thislen == 5 ) {
1455 // If there is an odd number of both bold and italics, it is likely
1456 // that one of the bold ones was meant to be an apostrophe followed
1457 // by italics. Which one we cannot know for certain, but it is more
1458 // likely to be one that has a single-letter word before it.
1459 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1460 $firstsingleletterword = -1;
1461 $firstmultiletterword = -1;
1463 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1464 if ( strlen( $arr[$i] ) == 3 ) {
1465 $x1 = substr( $arr[$i - 1], -1 );
1466 $x2 = substr( $arr[$i - 1], -2, 1 );
1467 if ( $x1 === ' ' ) {
1468 if ( $firstspace == -1 ) {
1471 } elseif ( $x2 === ' ' ) {
1472 if ( $firstsingleletterword == -1 ) {
1473 $firstsingleletterword = $i;
1474 // if $firstsingleletterword is set, we don't
1475 // look at the other options, so we can bail early.
1479 if ( $firstmultiletterword == -1 ) {
1480 $firstmultiletterword = $i;
1486 // If there is a single-letter word, use it!
1487 if ( $firstsingleletterword > -1 ) {
1488 $arr[$firstsingleletterword] = "''";
1489 $arr[$firstsingleletterword - 1] .= "'";
1490 } elseif ( $firstmultiletterword > -1 ) {
1491 // If not, but there's a multi-letter word, use that one.
1492 $arr[$firstmultiletterword] = "''";
1493 $arr[$firstmultiletterword - 1] .= "'";
1494 } elseif ( $firstspace > -1 ) {
1495 // ... otherwise use the first one that has neither.
1496 // (notice that it is possible for all three to be -1 if, for example,
1497 // there is only one pentuple-apostrophe in the line)
1498 $arr[$firstspace] = "''";
1499 $arr[$firstspace - 1] .= "'";
1503 // Now let's actually convert our apostrophic mush to HTML!
1508 foreach ( $arr as $r ) {
1509 if ( ( $i %
2 ) == 0 ) {
1510 if ( $state === 'both' ) {
1516 $thislen = strlen( $r );
1517 if ( $thislen == 2 ) {
1518 if ( $state === 'i' ) {
1521 } elseif ( $state === 'bi' ) {
1524 } elseif ( $state === 'ib' ) {
1525 $output .= '</b></i><b>';
1527 } elseif ( $state === 'both' ) {
1528 $output .= '<b><i>' . $buffer . '</i>';
1530 } else { // $state can be 'b' or ''
1534 } elseif ( $thislen == 3 ) {
1535 if ( $state === 'b' ) {
1538 } elseif ( $state === 'bi' ) {
1539 $output .= '</i></b><i>';
1541 } elseif ( $state === 'ib' ) {
1544 } elseif ( $state === 'both' ) {
1545 $output .= '<i><b>' . $buffer . '</b>';
1547 } else { // $state can be 'i' or ''
1551 } elseif ( $thislen == 5 ) {
1552 if ( $state === 'b' ) {
1553 $output .= '</b><i>';
1555 } elseif ( $state === 'i' ) {
1556 $output .= '</i><b>';
1558 } elseif ( $state === 'bi' ) {
1559 $output .= '</i></b>';
1561 } elseif ( $state === 'ib' ) {
1562 $output .= '</b></i>';
1564 } elseif ( $state === 'both' ) {
1565 $output .= '<i><b>' . $buffer . '</b></i>';
1567 } else { // ($state == '')
1575 // Now close all remaining tags. Notice that the order is important.
1576 if ( $state === 'b' ||
$state === 'ib' ) {
1579 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1582 if ( $state === 'bi' ) {
1585 // There might be lonely ''''', so make sure we have a buffer
1586 if ( $state === 'both' && $buffer ) {
1587 $output .= '<b><i>' . $buffer . '</i></b>';
1593 * Replace external links (REL)
1595 * Note: this is all very hackish and the order of execution matters a lot.
1596 * Make sure to run tests/parserTests.php if you change this code.
1600 * @param $text string
1602 * @throws MWException
1605 function replaceExternalLinks( $text ) {
1606 wfProfileIn( __METHOD__
);
1608 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1609 if ( $bits === false ) {
1610 wfProfileOut( __METHOD__
);
1611 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1613 $s = array_shift( $bits );
1616 while ( $i < count( $bits ) ) {
1619 $text = $bits[$i++
];
1620 $trail = $bits[$i++
];
1622 # The characters '<' and '>' (which were escaped by
1623 # removeHTMLtags()) should not be included in
1624 # URLs, per RFC 2396.
1626 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1627 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1628 $url = substr( $url, 0, $m2[0][1] );
1631 # If the link text is an image URL, replace it with an <img> tag
1632 # This happened by accident in the original parser, but some people used it extensively
1633 $img = $this->maybeMakeExternalImage( $text );
1634 if ( $img !== false ) {
1640 # Set linktype for CSS - if URL==text, link is essentially free
1641 $linktype = ( $text === $url ) ?
'free' : 'text';
1643 # No link text, e.g. [http://domain.tld/some.link]
1644 if ( $text == '' ) {
1646 $langObj = $this->getTargetLanguage();
1647 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1648 $linktype = 'autonumber';
1650 # Have link text, e.g. [http://domain.tld/some.link text]s
1652 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1655 $text = $this->getConverterLanguage()->markNoConversion( $text );
1657 $url = Sanitizer
::cleanUrl( $url );
1659 # Use the encoded URL
1660 # This means that users can paste URLs directly into the text
1661 # Funny characters like ö aren't valid in URLs anyway
1662 # This was changed in August 2004
1663 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1664 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1666 # Register link in the output object.
1667 # Replace unnecessary URL escape codes with the referenced character
1668 # This prevents spammers from hiding links from the filters
1669 $pasteurized = self
::replaceUnusualEscapes( $url );
1670 $this->mOutput
->addExternalLink( $pasteurized );
1673 wfProfileOut( __METHOD__
);
1677 * Get the rel attribute for a particular external link.
1680 * @param string|bool $url optional URL, to extract the domain from for rel =>
1681 * nofollow if appropriate
1682 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1683 * @return string|null rel attribute for $url
1685 public static function getExternalLinkRel( $url = false, $title = null ) {
1686 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1687 $ns = $title ?
$title->getNamespace() : false;
1688 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1689 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1696 * Get an associative array of additional HTML attributes appropriate for a
1697 * particular external link. This currently may include rel => nofollow
1698 * (depending on configuration, namespace, and the URL's domain) and/or a
1699 * target attribute (depending on configuration).
1701 * @param string|bool $url optional URL, to extract the domain from for rel =>
1702 * nofollow if appropriate
1703 * @return Array associative array of HTML attributes
1705 function getExternalLinkAttribs( $url = false ) {
1707 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1709 if ( $this->mOptions
->getExternalLinkTarget() ) {
1710 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1716 * Replace unusual URL escape codes with their equivalent characters
1718 * @param $url String
1721 * @todo This can merge genuinely required bits in the path or query string,
1722 * breaking legit URLs. A proper fix would treat the various parts of
1723 * the URL differently; as a workaround, just use the output for
1724 * statistical records, not for actual linking/output.
1726 static function replaceUnusualEscapes( $url ) {
1727 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1728 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1732 * Callback function used in replaceUnusualEscapes().
1733 * Replaces unusual URL escape codes with their equivalent character
1735 * @param $matches array
1739 private static function replaceUnusualEscapesCallback( $matches ) {
1740 $char = urldecode( $matches[0] );
1741 $ord = ord( $char );
1742 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1743 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1744 # No, shouldn't be escaped
1747 # Yes, leave it escaped
1753 * make an image if it's allowed, either through the global
1754 * option, through the exception, or through the on-wiki whitelist
1757 * $param $url string
1761 function maybeMakeExternalImage( $url ) {
1762 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1763 $imagesexception = !empty( $imagesfrom );
1765 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1766 if ( $imagesexception && is_array( $imagesfrom ) ) {
1767 $imagematch = false;
1768 foreach ( $imagesfrom as $match ) {
1769 if ( strpos( $url, $match ) === 0 ) {
1774 } elseif ( $imagesexception ) {
1775 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1777 $imagematch = false;
1779 if ( $this->mOptions
->getAllowExternalImages()
1780 ||
( $imagesexception && $imagematch ) ) {
1781 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1783 $text = Linker
::makeExternalImage( $url );
1786 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1787 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1788 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1789 foreach ( $whitelist as $entry ) {
1790 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1791 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1794 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1795 # Image matches a whitelist entry
1796 $text = Linker
::makeExternalImage( $url );
1805 * Process [[ ]] wikilinks
1809 * @return String: processed text
1813 function replaceInternalLinks( $s ) {
1814 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1819 * Process [[ ]] wikilinks (RIL)
1821 * @throws MWException
1822 * @return LinkHolderArray
1826 function replaceInternalLinks2( &$s ) {
1827 wfProfileIn( __METHOD__
);
1829 wfProfileIn( __METHOD__
. '-setup' );
1830 static $tc = false, $e1, $e1_img;
1831 # the % is needed to support urlencoded titles as well
1833 $tc = Title
::legalChars() . '#%';
1834 # Match a link having the form [[namespace:link|alternate]]trail
1835 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1836 # Match cases where there is no "]]", which might still be images
1837 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1840 $holders = new LinkHolderArray( $this );
1842 # split the entire text string on occurrences of [[
1843 $a = StringUtils
::explode( '[[', ' ' . $s );
1844 # get the first element (all text up to first [[), and remove the space we added
1847 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1848 $s = substr( $s, 1 );
1850 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1852 if ( $useLinkPrefixExtension ) {
1853 # Match the end of a line for a word that's not followed by whitespace,
1854 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1855 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1858 if ( is_null( $this->mTitle
) ) {
1859 wfProfileOut( __METHOD__
. '-setup' );
1860 wfProfileOut( __METHOD__
);
1861 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1863 $nottalk = !$this->mTitle
->isTalkPage();
1865 if ( $useLinkPrefixExtension ) {
1867 if ( preg_match( $e2, $s, $m ) ) {
1868 $first_prefix = $m[2];
1870 $first_prefix = false;
1876 $useSubpages = $this->areSubpagesAllowed();
1877 wfProfileOut( __METHOD__
. '-setup' );
1879 # Loop for each link
1880 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1881 # Check for excessive memory usage
1882 if ( $holders->isBig() ) {
1884 # Do the existence check, replace the link holders and clear the array
1885 $holders->replace( $s );
1889 if ( $useLinkPrefixExtension ) {
1890 wfProfileIn( __METHOD__
. '-prefixhandling' );
1891 if ( preg_match( $e2, $s, $m ) ) {
1898 if ( $first_prefix ) {
1899 $prefix = $first_prefix;
1900 $first_prefix = false;
1902 wfProfileOut( __METHOD__
. '-prefixhandling' );
1905 $might_be_img = false;
1907 wfProfileIn( __METHOD__
. "-e1" );
1908 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1910 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1911 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1912 # the real problem is with the $e1 regex
1915 # Still some problems for cases where the ] is meant to be outside punctuation,
1916 # and no image is in sight. See bug 2095.
1918 if ( $text !== '' &&
1919 substr( $m[3], 0, 1 ) === ']' &&
1920 strpos( $text, '[' ) !== false
1923 $text .= ']'; # so that replaceExternalLinks($text) works later
1924 $m[3] = substr( $m[3], 1 );
1926 # fix up urlencoded title texts
1927 if ( strpos( $m[1], '%' ) !== false ) {
1928 # Should anchors '#' also be rejected?
1929 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1932 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1933 $might_be_img = true;
1935 if ( strpos( $m[1], '%' ) !== false ) {
1936 $m[1] = rawurldecode( $m[1] );
1939 } else { # Invalid form; output directly
1940 $s .= $prefix . '[[' . $line;
1941 wfProfileOut( __METHOD__
. "-e1" );
1944 wfProfileOut( __METHOD__
. "-e1" );
1945 wfProfileIn( __METHOD__
. "-misc" );
1947 # Don't allow internal links to pages containing
1948 # PROTO: where PROTO is a valid URL protocol; these
1949 # should be external links.
1950 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1951 $s .= $prefix . '[[' . $line;
1952 wfProfileOut( __METHOD__
. "-misc" );
1956 # Make subpage if necessary
1957 if ( $useSubpages ) {
1958 $link = $this->maybeDoSubpageLink( $m[1], $text );
1963 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1965 # Strip off leading ':'
1966 $link = substr( $link, 1 );
1969 wfProfileOut( __METHOD__
. "-misc" );
1970 wfProfileIn( __METHOD__
. "-title" );
1971 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1972 if ( $nt === null ) {
1973 $s .= $prefix . '[[' . $line;
1974 wfProfileOut( __METHOD__
. "-title" );
1978 $ns = $nt->getNamespace();
1979 $iw = $nt->getInterWiki();
1980 wfProfileOut( __METHOD__
. "-title" );
1982 if ( $might_be_img ) { # if this is actually an invalid link
1983 wfProfileIn( __METHOD__
. "-might_be_img" );
1984 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1987 # look at the next 'line' to see if we can close it there
1989 $next_line = $a->current();
1990 if ( $next_line === false ||
$next_line === null ) {
1993 $m = explode( ']]', $next_line, 3 );
1994 if ( count( $m ) == 3 ) {
1995 # the first ]] closes the inner link, the second the image
1997 $text .= "[[{$m[0]}]]{$m[1]}";
2000 } elseif ( count( $m ) == 2 ) {
2001 # if there's exactly one ]] that's fine, we'll keep looking
2002 $text .= "[[{$m[0]}]]{$m[1]}";
2004 # if $next_line is invalid too, we need look no further
2005 $text .= '[[' . $next_line;
2010 # we couldn't find the end of this imageLink, so output it raw
2011 # but don't ignore what might be perfectly normal links in the text we've examined
2012 $holders->merge( $this->replaceInternalLinks2( $text ) );
2013 $s .= "{$prefix}[[$link|$text";
2014 # note: no $trail, because without an end, there *is* no trail
2015 wfProfileOut( __METHOD__
. "-might_be_img" );
2018 } else { # it's not an image, so output it raw
2019 $s .= "{$prefix}[[$link|$text";
2020 # note: no $trail, because without an end, there *is* no trail
2021 wfProfileOut( __METHOD__
. "-might_be_img" );
2024 wfProfileOut( __METHOD__
. "-might_be_img" );
2027 $wasblank = ( $text == '' );
2031 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2032 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2033 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2034 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2035 $text = $this->doQuotes( $text );
2038 # Link not escaped by : , create the various objects
2041 wfProfileIn( __METHOD__
. "-interwiki" );
2042 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
2043 // XXX: the above check prevents links to sites with identifiers that are not language codes
2045 # Bug 24502: filter duplicates
2046 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2047 $this->mLangLinkLanguages
[$iw] = true;
2048 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2051 $s = rtrim( $s . $prefix );
2052 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2053 wfProfileOut( __METHOD__
. "-interwiki" );
2056 wfProfileOut( __METHOD__
. "-interwiki" );
2058 if ( $ns == NS_FILE
) {
2059 wfProfileIn( __METHOD__
. "-image" );
2060 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2062 # if no parameters were passed, $text
2063 # becomes something like "File:Foo.png",
2064 # which we don't want to pass on to the
2068 # recursively parse links inside the image caption
2069 # actually, this will parse them in any other parameters, too,
2070 # but it might be hard to fix that, and it doesn't matter ATM
2071 $text = $this->replaceExternalLinks( $text );
2072 $holders->merge( $this->replaceInternalLinks2( $text ) );
2074 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2075 $s .= $prefix . $this->armorLinks(
2076 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2078 $s .= $prefix . $trail;
2080 wfProfileOut( __METHOD__
. "-image" );
2084 if ( $ns == NS_CATEGORY
) {
2085 wfProfileIn( __METHOD__
. "-category" );
2086 $s = rtrim( $s . "\n" ); # bug 87
2089 $sortkey = $this->getDefaultSort();
2093 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2094 $sortkey = str_replace( "\n", '', $sortkey );
2095 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2096 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2099 * Strip the whitespace Category links produce, see bug 87
2100 * @todo We might want to use trim($tmp, "\n") here.
2102 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2104 wfProfileOut( __METHOD__
. "-category" );
2109 # Self-link checking
2110 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2111 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2112 $this->mTitle
->getPrefixedText(),
2113 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2116 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2121 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2122 # @todo FIXME: Should do batch file existence checks, see comment below
2123 if ( $ns == NS_MEDIA
) {
2124 wfProfileIn( __METHOD__
. "-media" );
2125 # Give extensions a chance to select the file revision for us
2128 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2129 array( $this, $nt, &$options, &$descQuery ) );
2130 # Fetch and register the file (file title may be different via hooks)
2131 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2132 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2133 $s .= $prefix . $this->armorLinks(
2134 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2135 wfProfileOut( __METHOD__
. "-media" );
2139 wfProfileIn( __METHOD__
. "-always_known" );
2140 # Some titles, such as valid special pages or files in foreign repos, should
2141 # be shown as bluelinks even though they're not included in the page table
2143 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2144 # batch file existence checks for NS_FILE and NS_MEDIA
2145 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2146 $this->mOutput
->addLink( $nt );
2147 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2149 # Links will be added to the output link list after checking
2150 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2152 wfProfileOut( __METHOD__
. "-always_known" );
2154 wfProfileOut( __METHOD__
);
2159 * Render a forced-blue link inline; protect against double expansion of
2160 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2161 * Since this little disaster has to split off the trail text to avoid
2162 * breaking URLs in the following text without breaking trails on the
2163 * wiki links, it's been made into a horrible function.
2166 * @param $text String
2167 * @param array $query or String
2168 * @param $trail String
2169 * @param $prefix String
2170 * @return String: HTML-wikitext mix oh yuck
2172 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2173 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2175 if ( is_string( $query ) ) {
2176 $query = wfCgiToArray( $query );
2178 if ( $text == '' ) {
2179 $text = htmlspecialchars( $nt->getPrefixedText() );
2182 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2184 return $this->armorLinks( $link ) . $trail;
2188 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2189 * going to go through further parsing steps before inline URL expansion.
2191 * Not needed quite as much as it used to be since free links are a bit
2192 * more sensible these days. But bracketed links are still an issue.
2194 * @param string $text more-or-less HTML
2195 * @return String: less-or-more HTML with NOPARSE bits
2197 function armorLinks( $text ) {
2198 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2199 "{$this->mUniqPrefix}NOPARSE$1", $text );
2203 * Return true if subpage links should be expanded on this page.
2206 function areSubpagesAllowed() {
2207 # Some namespaces don't allow subpages
2208 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2212 * Handle link to subpage if necessary
2214 * @param string $target the source of the link
2215 * @param &$text String: the link text, modified as necessary
2216 * @return string the full name of the link
2219 function maybeDoSubpageLink( $target, &$text ) {
2220 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2224 * Used by doBlockLevels()
2229 function closeParagraph() {
2231 if ( $this->mLastSection
!= '' ) {
2232 $result = '</' . $this->mLastSection
. ">\n";
2234 $this->mInPre
= false;
2235 $this->mLastSection
= '';
2240 * getCommon() returns the length of the longest common substring
2241 * of both arguments, starting at the beginning of both.
2244 * @param $st1 string
2245 * @param $st2 string
2249 function getCommon( $st1, $st2 ) {
2250 $fl = strlen( $st1 );
2251 $shorter = strlen( $st2 );
2252 if ( $fl < $shorter ) {
2256 for ( $i = 0; $i < $shorter; ++
$i ) {
2257 if ( $st1[$i] != $st2[$i] ) {
2265 * These next three functions open, continue, and close the list
2266 * element appropriate to the prefix character passed into them.
2269 * @param $char string
2273 function openList( $char ) {
2274 $result = $this->closeParagraph();
2276 if ( '*' === $char ) {
2277 $result .= '<ul><li>';
2278 } elseif ( '#' === $char ) {
2279 $result .= '<ol><li>';
2280 } elseif ( ':' === $char ) {
2281 $result .= '<dl><dd>';
2282 } elseif ( ';' === $char ) {
2283 $result .= '<dl><dt>';
2284 $this->mDTopen
= true;
2286 $result = '<!-- ERR 1 -->';
2294 * @param $char String
2299 function nextItem( $char ) {
2300 if ( '*' === $char ||
'#' === $char ) {
2302 } elseif ( ':' === $char ||
';' === $char ) {
2304 if ( $this->mDTopen
) {
2307 if ( ';' === $char ) {
2308 $this->mDTopen
= true;
2309 return $close . '<dt>';
2311 $this->mDTopen
= false;
2312 return $close . '<dd>';
2315 return '<!-- ERR 2 -->';
2320 * @param $char String
2325 function closeList( $char ) {
2326 if ( '*' === $char ) {
2327 $text = '</li></ul>';
2328 } elseif ( '#' === $char ) {
2329 $text = '</li></ol>';
2330 } elseif ( ':' === $char ) {
2331 if ( $this->mDTopen
) {
2332 $this->mDTopen
= false;
2333 $text = '</dt></dl>';
2335 $text = '</dd></dl>';
2338 return '<!-- ERR 3 -->';
2340 return $text . "\n";
2345 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2347 * @param $text String
2348 * @param $linestart Boolean: whether or not this is at the start of a line.
2350 * @return string the lists rendered as HTML
2352 function doBlockLevels( $text, $linestart ) {
2353 wfProfileIn( __METHOD__
);
2355 # Parsing through the text line by line. The main thing
2356 # happening here is handling of block-level elements p, pre,
2357 # and making lists from lines starting with * # : etc.
2359 $textLines = StringUtils
::explode( "\n", $text );
2361 $lastPrefix = $output = '';
2362 $this->mDTopen
= $inBlockElem = false;
2364 $paragraphStack = false;
2365 $inBlockquote = false;
2367 foreach ( $textLines as $oLine ) {
2369 if ( !$linestart ) {
2379 $lastPrefixLength = strlen( $lastPrefix );
2380 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2381 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2382 # If not in a <pre> element, scan for and figure out what prefixes are there.
2383 if ( !$this->mInPre
) {
2384 # Multiple prefixes may abut each other for nested lists.
2385 $prefixLength = strspn( $oLine, '*#:;' );
2386 $prefix = substr( $oLine, 0, $prefixLength );
2389 # ; and : are both from definition-lists, so they're equivalent
2390 # for the purposes of determining whether or not we need to open/close
2392 $prefix2 = str_replace( ';', ':', $prefix );
2393 $t = substr( $oLine, $prefixLength );
2394 $this->mInPre
= (bool)$preOpenMatch;
2396 # Don't interpret any other prefixes in preformatted text
2398 $prefix = $prefix2 = '';
2403 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2404 # Same as the last item, so no need to deal with nesting or opening stuff
2405 $output .= $this->nextItem( substr( $prefix, -1 ) );
2406 $paragraphStack = false;
2408 if ( substr( $prefix, -1 ) === ';' ) {
2409 # The one nasty exception: definition lists work like this:
2410 # ; title : definition text
2411 # So we check for : in the remainder text to split up the
2412 # title and definition, without b0rking links.
2414 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2416 $output .= $term . $this->nextItem( ':' );
2419 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2420 # We need to open or close prefixes, or both.
2422 # Either open or close a level...
2423 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2424 $paragraphStack = false;
2426 # Close all the prefixes which aren't shared.
2427 while ( $commonPrefixLength < $lastPrefixLength ) {
2428 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2429 --$lastPrefixLength;
2432 # Continue the current prefix if appropriate.
2433 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2434 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2437 # Open prefixes where appropriate.
2438 while ( $prefixLength > $commonPrefixLength ) {
2439 $char = substr( $prefix, $commonPrefixLength, 1 );
2440 $output .= $this->openList( $char );
2442 if ( ';' === $char ) {
2443 # @todo FIXME: This is dupe of code above
2444 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2446 $output .= $term . $this->nextItem( ':' );
2449 ++
$commonPrefixLength;
2451 $lastPrefix = $prefix2;
2454 # If we have no prefixes, go to paragraph mode.
2455 if ( 0 == $prefixLength ) {
2456 wfProfileIn( __METHOD__
. "-paragraph" );
2457 # No prefix (not in list)--go to paragraph mode
2458 # XXX: use a stack for nestable elements like span, table and div
2459 $openmatch = preg_match( '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2460 $closematch = preg_match(
2461 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2462 '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2463 if ( $openmatch or $closematch ) {
2464 $paragraphStack = false;
2465 # TODO bug 5718: paragraph closed
2466 $output .= $this->closeParagraph();
2467 if ( $preOpenMatch and !$preCloseMatch ) {
2468 $this->mInPre
= true;
2471 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2472 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2473 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2475 $inBlockElem = !$closematch;
2476 } elseif ( !$inBlockElem && !$this->mInPre
) {
2477 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) and !$inBlockquote ) {
2479 if ( $this->mLastSection
!== 'pre' ) {
2480 $paragraphStack = false;
2481 $output .= $this->closeParagraph() . '<pre>';
2482 $this->mLastSection
= 'pre';
2484 $t = substr( $t, 1 );
2487 if ( trim( $t ) === '' ) {
2488 if ( $paragraphStack ) {
2489 $output .= $paragraphStack . '<br />';
2490 $paragraphStack = false;
2491 $this->mLastSection
= 'p';
2493 if ( $this->mLastSection
!== 'p' ) {
2494 $output .= $this->closeParagraph();
2495 $this->mLastSection
= '';
2496 $paragraphStack = '<p>';
2498 $paragraphStack = '</p><p>';
2502 if ( $paragraphStack ) {
2503 $output .= $paragraphStack;
2504 $paragraphStack = false;
2505 $this->mLastSection
= 'p';
2506 } elseif ( $this->mLastSection
!== 'p' ) {
2507 $output .= $this->closeParagraph() . '<p>';
2508 $this->mLastSection
= 'p';
2513 wfProfileOut( __METHOD__
. "-paragraph" );
2515 # somewhere above we forget to get out of pre block (bug 785)
2516 if ( $preCloseMatch && $this->mInPre
) {
2517 $this->mInPre
= false;
2519 if ( $paragraphStack === false ) {
2520 $output .= $t . "\n";
2523 while ( $prefixLength ) {
2524 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2527 if ( $this->mLastSection
!= '' ) {
2528 $output .= '</' . $this->mLastSection
. '>';
2529 $this->mLastSection
= '';
2532 wfProfileOut( __METHOD__
);
2537 * Split up a string on ':', ignoring any occurrences inside tags
2538 * to prevent illegal overlapping.
2540 * @param string $str the string to split
2541 * @param &$before String set to everything before the ':'
2542 * @param &$after String set to everything after the ':'
2543 * @throws MWException
2544 * @return String the position of the ':', or false if none found
2546 function findColonNoLinks( $str, &$before, &$after ) {
2547 wfProfileIn( __METHOD__
);
2549 $pos = strpos( $str, ':' );
2550 if ( $pos === false ) {
2552 wfProfileOut( __METHOD__
);
2556 $lt = strpos( $str, '<' );
2557 if ( $lt === false ||
$lt > $pos ) {
2558 # Easy; no tag nesting to worry about
2559 $before = substr( $str, 0, $pos );
2560 $after = substr( $str, $pos +
1 );
2561 wfProfileOut( __METHOD__
);
2565 # Ugly state machine to walk through avoiding tags.
2566 $state = self
::COLON_STATE_TEXT
;
2568 $len = strlen( $str );
2569 for ( $i = 0; $i < $len; $i++
) {
2573 # (Using the number is a performance hack for common cases)
2574 case 0: # self::COLON_STATE_TEXT:
2577 # Could be either a <start> tag or an </end> tag
2578 $state = self
::COLON_STATE_TAGSTART
;
2581 if ( $stack == 0 ) {
2583 $before = substr( $str, 0, $i );
2584 $after = substr( $str, $i +
1 );
2585 wfProfileOut( __METHOD__
);
2588 # Embedded in a tag; don't break it.
2591 # Skip ahead looking for something interesting
2592 $colon = strpos( $str, ':', $i );
2593 if ( $colon === false ) {
2594 # Nothing else interesting
2595 wfProfileOut( __METHOD__
);
2598 $lt = strpos( $str, '<', $i );
2599 if ( $stack === 0 ) {
2600 if ( $lt === false ||
$colon < $lt ) {
2602 $before = substr( $str, 0, $colon );
2603 $after = substr( $str, $colon +
1 );
2604 wfProfileOut( __METHOD__
);
2608 if ( $lt === false ) {
2609 # Nothing else interesting to find; abort!
2610 # We're nested, but there's no close tags left. Abort!
2613 # Skip ahead to next tag start
2615 $state = self
::COLON_STATE_TAGSTART
;
2618 case 1: # self::COLON_STATE_TAG:
2623 $state = self
::COLON_STATE_TEXT
;
2626 # Slash may be followed by >?
2627 $state = self
::COLON_STATE_TAGSLASH
;
2633 case 2: # self::COLON_STATE_TAGSTART:
2636 $state = self
::COLON_STATE_CLOSETAG
;
2639 $state = self
::COLON_STATE_COMMENT
;
2642 # Illegal early close? This shouldn't happen D:
2643 $state = self
::COLON_STATE_TEXT
;
2646 $state = self
::COLON_STATE_TAG
;
2649 case 3: # self::COLON_STATE_CLOSETAG:
2654 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2655 wfProfileOut( __METHOD__
);
2658 $state = self
::COLON_STATE_TEXT
;
2661 case self
::COLON_STATE_TAGSLASH
:
2663 # Yes, a self-closed tag <blah/>
2664 $state = self
::COLON_STATE_TEXT
;
2666 # Probably we're jumping the gun, and this is an attribute
2667 $state = self
::COLON_STATE_TAG
;
2670 case 5: # self::COLON_STATE_COMMENT:
2672 $state = self
::COLON_STATE_COMMENTDASH
;
2675 case self
::COLON_STATE_COMMENTDASH
:
2677 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2679 $state = self
::COLON_STATE_COMMENT
;
2682 case self
::COLON_STATE_COMMENTDASHDASH
:
2684 $state = self
::COLON_STATE_TEXT
;
2686 $state = self
::COLON_STATE_COMMENT
;
2690 wfProfileOut( __METHOD__
);
2691 throw new MWException( "State machine error in " . __METHOD__
);
2695 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2696 wfProfileOut( __METHOD__
);
2699 wfProfileOut( __METHOD__
);
2704 * Return value of a magic variable (like PAGENAME)
2708 * @param $index integer
2709 * @param bool|\PPFrame $frame
2711 * @throws MWException
2714 function getVariableValue( $index, $frame = false ) {
2715 global $wgContLang, $wgSitename, $wgServer;
2716 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2718 if ( is_null( $this->mTitle
) ) {
2719 // If no title set, bad things are going to happen
2720 // later. Title should always be set since this
2721 // should only be called in the middle of a parse
2722 // operation (but the unit-tests do funky stuff)
2723 throw new MWException( __METHOD__
. ' Should only be '
2724 . ' called while parsing (no title set)' );
2728 * Some of these require message or data lookups and can be
2729 * expensive to check many times.
2731 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2732 if ( isset( $this->mVarCache
[$index] ) ) {
2733 return $this->mVarCache
[$index];
2737 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2738 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2740 $pageLang = $this->getFunctionLang();
2743 case 'currentmonth':
2744 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2746 case 'currentmonth1':
2747 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2749 case 'currentmonthname':
2750 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2752 case 'currentmonthnamegen':
2753 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2755 case 'currentmonthabbrev':
2756 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2759 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2762 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2765 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2768 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2770 case 'localmonthname':
2771 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2773 case 'localmonthnamegen':
2774 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2776 case 'localmonthabbrev':
2777 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2780 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2783 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2786 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2789 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2791 case 'fullpagename':
2792 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2794 case 'fullpagenamee':
2795 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2798 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2800 case 'subpagenamee':
2801 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2803 case 'rootpagename':
2804 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2806 case 'rootpagenamee':
2807 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2809 case 'basepagename':
2810 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2812 case 'basepagenamee':
2813 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2815 case 'talkpagename':
2816 if ( $this->mTitle
->canTalk() ) {
2817 $talkPage = $this->mTitle
->getTalkPage();
2818 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2823 case 'talkpagenamee':
2824 if ( $this->mTitle
->canTalk() ) {
2825 $talkPage = $this->mTitle
->getTalkPage();
2826 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2831 case 'subjectpagename':
2832 $subjPage = $this->mTitle
->getSubjectPage();
2833 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2835 case 'subjectpagenamee':
2836 $subjPage = $this->mTitle
->getSubjectPage();
2837 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2839 case 'pageid': // requested in bug 23427
2840 $pageid = $this->getTitle()->getArticleID();
2841 if ( $pageid == 0 ) {
2842 # 0 means the page doesn't exist in the database,
2843 # which means the user is previewing a new page.
2844 # The vary-revision flag must be set, because the magic word
2845 # will have a different value once the page is saved.
2846 $this->mOutput
->setFlag( 'vary-revision' );
2847 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2849 $value = $pageid ?
$pageid : null;
2852 # Let the edit saving system know we should parse the page
2853 # *after* a revision ID has been assigned.
2854 $this->mOutput
->setFlag( 'vary-revision' );
2855 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2856 $value = $this->mRevisionId
;
2859 # Let the edit saving system know we should parse the page
2860 # *after* a revision ID has been assigned. This is for null edits.
2861 $this->mOutput
->setFlag( 'vary-revision' );
2862 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2863 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2865 case 'revisionday2':
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__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2870 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2872 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2877 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2879 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2884 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2886 case 'revisionyear':
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__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2891 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2893 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2898 $value = $this->getRevisionTimestamp();
2900 case 'revisionuser':
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__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2905 $value = $this->getRevisionUser();
2908 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2911 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2913 case 'namespacenumber':
2914 $value = $this->mTitle
->getNamespace();
2917 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2920 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2922 case 'subjectspace':
2923 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2925 case 'subjectspacee':
2926 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2928 case 'currentdayname':
2929 $value = $pageLang->getWeekdayName( MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2932 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2935 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2938 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2941 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2942 # int to remove the padding
2943 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2946 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2948 case 'localdayname':
2949 $value = $pageLang->getWeekdayName( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1 );
2952 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2955 $value = $pageLang->time( MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2958 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2961 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2962 # int to remove the padding
2963 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2966 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2968 case 'numberofarticles':
2969 $value = $pageLang->formatNum( SiteStats
::articles() );
2971 case 'numberoffiles':
2972 $value = $pageLang->formatNum( SiteStats
::images() );
2974 case 'numberofusers':
2975 $value = $pageLang->formatNum( SiteStats
::users() );
2977 case 'numberofactiveusers':
2978 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2980 case 'numberofpages':
2981 $value = $pageLang->formatNum( SiteStats
::pages() );
2983 case 'numberofadmins':
2984 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2986 case 'numberofedits':
2987 $value = $pageLang->formatNum( SiteStats
::edits() );
2989 case 'numberofviews':
2990 global $wgDisableCounters;
2991 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2993 case 'currenttimestamp':
2994 $value = wfTimestamp( TS_MW
, $ts );
2996 case 'localtimestamp':
2997 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2999 case 'currentversion':
3000 $value = SpecialVersion
::getVersion();
3003 return $wgArticlePath;
3009 $serverParts = wfParseUrl( $wgServer );
3010 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
3012 return $wgScriptPath;
3014 return $wgStylePath;
3015 case 'directionmark':
3016 return $pageLang->getDirMark();
3017 case 'contentlanguage':
3018 global $wgLanguageCode;
3019 return $wgLanguageCode;
3022 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
3030 $this->mVarCache
[$index] = $value;
3037 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3041 function initialiseVariables() {
3042 wfProfileIn( __METHOD__
);
3043 $variableIDs = MagicWord
::getVariableIDs();
3044 $substIDs = MagicWord
::getSubstIDs();
3046 $this->mVariables
= new MagicWordArray( $variableIDs );
3047 $this->mSubstWords
= new MagicWordArray( $substIDs );
3048 wfProfileOut( __METHOD__
);
3052 * Preprocess some wikitext and return the document tree.
3053 * This is the ghost of replace_variables().
3055 * @param string $text The text to parse
3056 * @param $flags Integer: bitwise combination of:
3057 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3058 * included. Default is to assume a direct page view.
3060 * The generated DOM tree must depend only on the input text and the flags.
3061 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3063 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3064 * change in the DOM tree for a given text, must be passed through the section identifier
3065 * in the section edit link and thus back to extractSections().
3067 * The output of this function is currently only cached in process memory, but a persistent
3068 * cache may be implemented at a later date which takes further advantage of these strict
3069 * dependency requirements.
3075 function preprocessToDom( $text, $flags = 0 ) {
3076 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3081 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3087 public static function splitWhitespace( $s ) {
3088 $ltrimmed = ltrim( $s );
3089 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3090 $trimmed = rtrim( $ltrimmed );
3091 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3093 $w2 = substr( $ltrimmed, -$diff );
3097 return array( $w1, $trimmed, $w2 );
3101 * Replace magic variables, templates, and template arguments
3102 * with the appropriate text. Templates are substituted recursively,
3103 * taking care to avoid infinite loops.
3105 * Note that the substitution depends on value of $mOutputType:
3106 * self::OT_WIKI: only {{subst:}} templates
3107 * self::OT_PREPROCESS: templates but not extension tags
3108 * self::OT_HTML: all templates and extension tags
3110 * @param string $text the text to transform
3111 * @param $frame PPFrame Object describing the arguments passed to the template.
3112 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3113 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3114 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3119 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3120 # Is there any text? Also, Prevent too big inclusions!
3121 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3124 wfProfileIn( __METHOD__
);
3126 if ( $frame === false ) {
3127 $frame = $this->getPreprocessor()->newFrame();
3128 } elseif ( !( $frame instanceof PPFrame
) ) {
3129 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3130 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3133 $dom = $this->preprocessToDom( $text );
3134 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3135 $text = $frame->expand( $dom, $flags );
3137 wfProfileOut( __METHOD__
);
3142 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3144 * @param $args array
3148 static function createAssocArgs( $args ) {
3149 $assocArgs = array();
3151 foreach ( $args as $arg ) {
3152 $eqpos = strpos( $arg, '=' );
3153 if ( $eqpos === false ) {
3154 $assocArgs[$index++
] = $arg;
3156 $name = trim( substr( $arg, 0, $eqpos ) );
3157 $value = trim( substr( $arg, $eqpos +
1 ) );
3158 if ( $value === false ) {
3161 if ( $name !== false ) {
3162 $assocArgs[$name] = $value;
3171 * Warn the user when a parser limitation is reached
3172 * Will warn at most once the user per limitation type
3174 * @param string $limitationType should be one of:
3175 * 'expensive-parserfunction' (corresponding messages:
3176 * 'expensive-parserfunction-warning',
3177 * 'expensive-parserfunction-category')
3178 * 'post-expand-template-argument' (corresponding messages:
3179 * 'post-expand-template-argument-warning',
3180 * 'post-expand-template-argument-category')
3181 * 'post-expand-template-inclusion' (corresponding messages:
3182 * 'post-expand-template-inclusion-warning',
3183 * 'post-expand-template-inclusion-category')
3184 * 'node-count-exceeded' (corresponding messages:
3185 * 'node-count-exceeded-warning',
3186 * 'node-count-exceeded-category')
3187 * 'expansion-depth-exceeded' (corresponding messages:
3188 * 'expansion-depth-exceeded-warning',
3189 * 'expansion-depth-exceeded-category')
3190 * @param int|null $current Current value
3191 * @param int|null $max Maximum allowed, when an explicit limit has been
3192 * exceeded, provide the values (optional)
3194 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3195 # does no harm if $current and $max are present but are unnecessary for the message
3196 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3197 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3198 $this->mOutput
->addWarning( $warning );
3199 $this->addTrackingCategory( "$limitationType-category" );
3203 * Return the text of a template, after recursively
3204 * replacing any variables or templates within the template.
3206 * @param array $piece the parts of the template
3207 * $piece['title']: the title, i.e. the part before the |
3208 * $piece['parts']: the parameter array
3209 * $piece['lineStart']: whether the brace was at the start of a line
3210 * @param $frame PPFrame The current frame, contains template arguments
3211 * @throws MWException
3212 * @return String: the text of the template
3215 function braceSubstitution( $piece, $frame ) {
3216 wfProfileIn( __METHOD__
);
3217 wfProfileIn( __METHOD__
. '-setup' );
3220 $found = false; # $text has been filled
3221 $nowiki = false; # wiki markup in $text should be escaped
3222 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3223 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3224 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3225 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3227 # Title object, where $text came from
3230 # $part1 is the bit before the first |, and must contain only title characters.
3231 # Various prefixes will be stripped from it later.
3232 $titleWithSpaces = $frame->expand( $piece['title'] );
3233 $part1 = trim( $titleWithSpaces );
3236 # Original title text preserved for various purposes
3237 $originalTitle = $part1;
3239 # $args is a list of argument nodes, starting from index 0, not including $part1
3240 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3241 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3242 wfProfileOut( __METHOD__
. '-setup' );
3244 $titleProfileIn = null; // profile templates
3247 wfProfileIn( __METHOD__
. '-modifiers' );
3250 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3252 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3253 # Decide whether to expand template or keep wikitext as-is.
3254 if ( $this->ot
['wiki'] ) {
3255 if ( $substMatch === false ) {
3256 $literal = true; # literal when in PST with no prefix
3258 $literal = false; # expand when in PST with subst: or safesubst:
3261 if ( $substMatch == 'subst' ) {
3262 $literal = true; # literal when not in PST with plain subst:
3264 $literal = false; # expand when not in PST with safesubst: or no prefix
3268 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3275 if ( !$found && $args->getLength() == 0 ) {
3276 $id = $this->mVariables
->matchStartToEnd( $part1 );
3277 if ( $id !== false ) {
3278 $text = $this->getVariableValue( $id, $frame );
3279 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3280 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3286 # MSG, MSGNW and RAW
3289 $mwMsgnw = MagicWord
::get( 'msgnw' );
3290 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3293 # Remove obsolete MSG:
3294 $mwMsg = MagicWord
::get( 'msg' );
3295 $mwMsg->matchStartAndRemove( $part1 );
3299 $mwRaw = MagicWord
::get( 'raw' );
3300 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3301 $forceRawInterwiki = true;
3304 wfProfileOut( __METHOD__
. '-modifiers' );
3308 wfProfileIn( __METHOD__
. '-pfunc' );
3310 $colonPos = strpos( $part1, ':' );
3311 if ( $colonPos !== false ) {
3312 $func = substr( $part1, 0, $colonPos );
3313 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3314 for ( $i = 0; $i < $args->getLength(); $i++
) {
3315 $funcArgs[] = $args->item( $i );
3318 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3319 } catch ( Exception
$ex ) {
3320 wfProfileOut( __METHOD__
. '-pfunc' );
3321 wfProfileOut( __METHOD__
);
3325 # The interface for parser functions allows for extracting
3326 # flags into the local scope. Extract any forwarded flags
3330 wfProfileOut( __METHOD__
. '-pfunc' );
3333 # Finish mangling title and then check for loops.
3334 # Set $title to a Title object and $titleText to the PDBK
3337 # Split the title into page and subpage
3339 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3340 if ( $part1 !== $relative ) {
3342 $ns = $this->mTitle
->getNamespace();
3344 $title = Title
::newFromText( $part1, $ns );
3346 $titleText = $title->getPrefixedText();
3347 # Check for language variants if the template is not found
3348 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3349 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3351 # Do recursion depth check
3352 $limit = $this->mOptions
->getMaxTemplateDepth();
3353 if ( $frame->depth
>= $limit ) {
3355 $text = '<span class="error">'
3356 . wfMessage( 'parser-template-recursion-depth-warning' )
3357 ->numParams( $limit )->inContentLanguage()->text()
3363 # Load from database
3364 if ( !$found && $title ) {
3365 if ( !Profiler
::instance()->isPersistent() ) {
3366 # Too many unique items can kill profiling DBs/collectors
3367 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3368 wfProfileIn( $titleProfileIn ); // template in
3370 wfProfileIn( __METHOD__
. '-loadtpl' );
3371 if ( !$title->isExternal() ) {
3372 if ( $title->isSpecialPage()
3373 && $this->mOptions
->getAllowSpecialInclusion()
3374 && $this->ot
['html'] )
3376 // Pass the template arguments as URL parameters.
3377 // "uselang" will have no effect since the Language object
3378 // is forced to the one defined in ParserOptions.
3379 $pageArgs = array();
3380 for ( $i = 0; $i < $args->getLength(); $i++
) {
3381 $bits = $args->item( $i )->splitArg();
3382 if ( strval( $bits['index'] ) === '' ) {
3383 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3384 $value = trim( $frame->expand( $bits['value'] ) );
3385 $pageArgs[$name] = $value;
3389 // Create a new context to execute the special page
3390 $context = new RequestContext
;
3391 $context->setTitle( $title );
3392 $context->setRequest( new FauxRequest( $pageArgs ) );
3393 $context->setUser( $this->getUser() );
3394 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3395 $ret = SpecialPageFactory
::capturePath( $title, $context );
3397 $text = $context->getOutput()->getHTML();
3398 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3401 $this->disableCache();
3403 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3404 $found = false; # access denied
3405 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3407 list( $text, $title ) = $this->getTemplateDom( $title );
3408 if ( $text !== false ) {
3414 # If the title is valid but undisplayable, make a link to it
3415 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3416 $text = "[[:$titleText]]";
3419 } elseif ( $title->isTrans() ) {
3420 # Interwiki transclusion
3421 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3422 $text = $this->interwikiTransclude( $title, 'render' );
3425 $text = $this->interwikiTransclude( $title, 'raw' );
3426 # Preprocess it like a template
3427 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3433 # Do infinite loop check
3434 # This has to be done after redirect resolution to avoid infinite loops via redirects
3435 if ( !$frame->loopCheck( $title ) ) {
3437 $text = '<span class="error">'
3438 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3440 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3442 wfProfileOut( __METHOD__
. '-loadtpl' );
3445 # If we haven't found text to substitute by now, we're done
3446 # Recover the source wikitext and return it
3448 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3449 if ( $titleProfileIn ) {
3450 wfProfileOut( $titleProfileIn ); // template out
3452 wfProfileOut( __METHOD__
);
3453 return array( 'object' => $text );
3456 # Expand DOM-style return values in a child frame
3457 if ( $isChildObj ) {
3458 # Clean up argument array
3459 $newFrame = $frame->newChild( $args, $title );
3462 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3463 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3464 # Expansion is eligible for the empty-frame cache
3465 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3466 $text = $this->mTplExpandCache
[$titleText];
3468 $text = $newFrame->expand( $text );
3469 $this->mTplExpandCache
[$titleText] = $text;
3472 # Uncached expansion
3473 $text = $newFrame->expand( $text );
3476 if ( $isLocalObj && $nowiki ) {
3477 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3478 $isLocalObj = false;
3481 if ( $titleProfileIn ) {
3482 wfProfileOut( $titleProfileIn ); // template out
3485 # Replace raw HTML by a placeholder
3487 $text = $this->insertStripItem( $text );
3488 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3489 # Escape nowiki-style return values
3490 $text = wfEscapeWikiText( $text );
3491 } elseif ( is_string( $text )
3492 && !$piece['lineStart']
3493 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3495 # Bug 529: if the template begins with a table or block-level
3496 # element, it should be treated as beginning a new line.
3497 # This behavior is somewhat controversial.
3498 $text = "\n" . $text;
3501 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3502 # Error, oversize inclusion
3503 if ( $titleText !== false ) {
3504 # Make a working, properly escaped link if possible (bug 23588)
3505 $text = "[[:$titleText]]";
3507 # This will probably not be a working link, but at least it may
3508 # provide some hint of where the problem is
3509 preg_replace( '/^:/', '', $originalTitle );
3510 $text = "[[:$originalTitle]]";
3512 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3513 $this->limitationWarn( 'post-expand-template-inclusion' );
3516 if ( $isLocalObj ) {
3517 $ret = array( 'object' => $text );
3519 $ret = array( 'text' => $text );
3522 wfProfileOut( __METHOD__
);
3527 * Call a parser function and return an array with text and flags.
3529 * The returned array will always contain a boolean 'found', indicating
3530 * whether the parser function was found or not. It may also contain the
3532 * text: string|object, resulting wikitext or PP DOM object
3533 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3534 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3535 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3536 * nowiki: bool, wiki markup in $text should be escaped
3539 * @param $frame PPFrame The current frame, contains template arguments
3540 * @param $function string Function name
3541 * @param $args array Arguments to the function
3544 public function callParserFunction( $frame, $function, array $args = array() ) {
3547 wfProfileIn( __METHOD__
);
3549 # Case sensitive functions
3550 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3551 $function = $this->mFunctionSynonyms
[1][$function];
3553 # Case insensitive functions
3554 $function = $wgContLang->lc( $function );
3555 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3556 $function = $this->mFunctionSynonyms
[0][$function];
3558 wfProfileOut( __METHOD__
);
3559 return array( 'found' => false );
3563 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3564 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3566 # Workaround for PHP bug 35229 and similar
3567 if ( !is_callable( $callback ) ) {
3568 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3569 wfProfileOut( __METHOD__
);
3570 throw new MWException( "Tag hook for $function is not callable\n" );
3573 $allArgs = array( &$this );
3574 if ( $flags & SFH_OBJECT_ARGS
) {
3575 # Convert arguments to PPNodes and collect for appending to $allArgs
3576 $funcArgs = array();
3577 foreach ( $args as $k => $v ) {
3578 if ( $v instanceof PPNode ||
$k === 0 ) {
3581 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3585 # Add a frame parameter, and pass the arguments as an array
3586 $allArgs[] = $frame;
3587 $allArgs[] = $funcArgs;
3589 # Convert arguments to plain text and append to $allArgs
3590 foreach ( $args as $k => $v ) {
3591 if ( $v instanceof PPNode
) {
3592 $allArgs[] = trim( $frame->expand( $v ) );
3593 } elseif ( is_int( $k ) && $k >= 0 ) {
3594 $allArgs[] = trim( $v );
3596 $allArgs[] = trim( "$k=$v" );
3601 $result = call_user_func_array( $callback, $allArgs );
3603 # The interface for function hooks allows them to return a wikitext
3604 # string or an array containing the string and any flags. This mungs
3605 # things around to match what this method should return.
3606 if ( !is_array( $result ) ) {
3612 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3613 $result['text'] = $result[0];
3615 unset( $result[0] );
3622 $preprocessFlags = 0;
3623 if ( isset( $result['noparse'] ) ) {
3624 $noparse = $result['noparse'];
3626 if ( isset( $result['preprocessFlags'] ) ) {
3627 $preprocessFlags = $result['preprocessFlags'];
3631 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3632 $result['isChildObj'] = true;
3634 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3635 wfProfileOut( __METHOD__
);
3641 * Get the semi-parsed DOM representation of a template with a given title,
3642 * and its redirect destination title. Cached.
3644 * @param $title Title
3648 function getTemplateDom( $title ) {
3649 $cacheTitle = $title;
3650 $titleText = $title->getPrefixedDBkey();
3652 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3653 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3654 $title = Title
::makeTitle( $ns, $dbk );
3655 $titleText = $title->getPrefixedDBkey();
3657 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3658 return array( $this->mTplDomCache
[$titleText], $title );
3661 # Cache miss, go to the database
3662 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3664 if ( $text === false ) {
3665 $this->mTplDomCache
[$titleText] = false;
3666 return array( false, $title );
3669 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3670 $this->mTplDomCache
[$titleText] = $dom;
3672 if ( !$title->equals( $cacheTitle ) ) {
3673 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3674 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3677 return array( $dom, $title );
3681 * Fetch the unparsed text of a template and register a reference to it.
3682 * @param Title $title
3683 * @return Array ( string or false, Title )
3685 function fetchTemplateAndTitle( $title ) {
3686 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3687 $stuff = call_user_func( $templateCb, $title, $this );
3688 $text = $stuff['text'];
3689 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3690 if ( isset( $stuff['deps'] ) ) {
3691 foreach ( $stuff['deps'] as $dep ) {
3692 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3693 if ( $dep['title']->equals( $this->getTitle() ) ) {
3694 // If we transclude ourselves, the final result
3695 // will change based on the new version of the page
3696 $this->mOutput
->setFlag( 'vary-revision' );
3700 return array( $text, $finalTitle );
3704 * Fetch the unparsed text of a template and register a reference to it.
3705 * @param Title $title
3706 * @return mixed string or false
3708 function fetchTemplate( $title ) {
3709 $rv = $this->fetchTemplateAndTitle( $title );
3714 * Static function to get a template
3715 * Can be overridden via ParserOptions::setTemplateCallback().
3717 * @param $title Title
3718 * @param $parser Parser
3722 static function statelessFetchTemplate( $title, $parser = false ) {
3723 $text = $skip = false;
3724 $finalTitle = $title;
3727 # Loop to fetch the article, with up to 1 redirect
3728 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3729 # Give extensions a chance to select the revision instead
3730 $id = false; # Assume current
3731 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3732 array( $parser, $title, &$skip, &$id ) );
3738 'page_id' => $title->getArticleID(),
3745 ? Revision
::newFromId( $id )
3746 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3747 $rev_id = $rev ?
$rev->getId() : 0;
3748 # If there is no current revision, there is no page
3749 if ( $id === false && !$rev ) {
3750 $linkCache = LinkCache
::singleton();
3751 $linkCache->addBadLinkObj( $title );
3756 'page_id' => $title->getArticleID(),
3757 'rev_id' => $rev_id );
3758 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3759 # We fetched a rev from a different title; register it too...
3761 'title' => $rev->getTitle(),
3762 'page_id' => $rev->getPage(),
3763 'rev_id' => $rev_id );
3767 $content = $rev->getContent();
3768 $text = $content ?
$content->getWikitextForTransclusion() : null;
3770 if ( $text === false ||
$text === null ) {
3774 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3776 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3777 if ( !$message->exists() ) {
3781 $content = $message->content();
3782 $text = $message->plain();
3790 $finalTitle = $title;
3791 $title = $content->getRedirectTarget();
3795 'finalTitle' => $finalTitle,
3800 * Fetch a file and its title and register a reference to it.
3801 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3802 * @param Title $title
3803 * @param array $options Array of options to RepoGroup::findFile
3806 function fetchFile( $title, $options = array() ) {
3807 $res = $this->fetchFileAndTitle( $title, $options );
3812 * Fetch a file and its title and register a reference to it.
3813 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3814 * @param Title $title
3815 * @param array $options Array of options to RepoGroup::findFile
3816 * @return Array ( File or false, Title of file )
3818 function fetchFileAndTitle( $title, $options = array() ) {
3819 $file = $this->fetchFileNoRegister( $title, $options );
3821 $time = $file ?
$file->getTimestamp() : false;
3822 $sha1 = $file ?
$file->getSha1() : false;
3823 # Register the file as a dependency...
3824 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3825 if ( $file && !$title->equals( $file->getTitle() ) ) {
3826 # Update fetched file title
3827 $title = $file->getTitle();
3828 if ( is_null( $file->getRedirectedTitle() ) ) {
3829 # This file was not a redirect, but the title does not match.
3830 # Register under the new name because otherwise the link will
3832 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3835 return array( $file, $title );
3839 * Helper function for fetchFileAndTitle.
3841 * Also useful if you need to fetch a file but not use it yet,
3842 * for example to get the file's handler.
3844 * @param Title $title
3845 * @param array $options Array of options to RepoGroup::findFile
3846 * @return File or false
3848 protected function fetchFileNoRegister( $title, $options = array() ) {
3849 if ( isset( $options['broken'] ) ) {
3850 $file = false; // broken thumbnail forced by hook
3851 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3852 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3853 } else { // get by (name,timestamp)
3854 $file = wfFindFile( $title, $options );
3860 * Transclude an interwiki link.
3862 * @param $title Title
3867 function interwikiTransclude( $title, $action ) {
3868 global $wgEnableScaryTranscluding;
3870 if ( !$wgEnableScaryTranscluding ) {
3871 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3874 $url = $title->getFullURL( array( 'action' => $action ) );
3876 if ( strlen( $url ) > 255 ) {
3877 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3879 return $this->fetchScaryTemplateMaybeFromCache( $url );
3883 * @param $url string
3884 * @return Mixed|String
3886 function fetchScaryTemplateMaybeFromCache( $url ) {
3887 global $wgTranscludeCacheExpiry;
3888 $dbr = wfGetDB( DB_SLAVE
);
3889 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3890 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3891 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3893 return $obj->tc_contents
;
3896 $req = MWHttpRequest
::factory( $url );
3897 $status = $req->execute(); // Status object
3898 if ( $status->isOK() ) {
3899 $text = $req->getContent();
3900 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3901 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3903 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3906 $dbw = wfGetDB( DB_MASTER
);
3907 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3909 'tc_time' => $dbw->timestamp( time() ),
3910 'tc_contents' => $text
3916 * Triple brace replacement -- used for template arguments
3919 * @param $piece array
3920 * @param $frame PPFrame
3924 function argSubstitution( $piece, $frame ) {
3925 wfProfileIn( __METHOD__
);
3928 $parts = $piece['parts'];
3929 $nameWithSpaces = $frame->expand( $piece['title'] );
3930 $argName = trim( $nameWithSpaces );
3932 $text = $frame->getArgument( $argName );
3933 if ( $text === false && $parts->getLength() > 0
3937 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3940 # No match in frame, use the supplied default
3941 $object = $parts->item( 0 )->getChildren();
3943 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3944 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3945 $this->limitationWarn( 'post-expand-template-argument' );
3948 if ( $text === false && $object === false ) {
3950 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3952 if ( $error !== false ) {
3955 if ( $object !== false ) {
3956 $ret = array( 'object' => $object );
3958 $ret = array( 'text' => $text );
3961 wfProfileOut( __METHOD__
);
3966 * Return the text to be used for a given extension tag.
3967 * This is the ghost of strip().
3969 * @param array $params Associative array of parameters:
3970 * name PPNode for the tag name
3971 * attr PPNode for unparsed text where tag attributes are thought to be
3972 * attributes Optional associative array of parsed attributes
3973 * inner Contents of extension element
3974 * noClose Original text did not have a close tag
3975 * @param $frame PPFrame
3977 * @throws MWException
3980 function extensionSubstitution( $params, $frame ) {
3981 $name = $frame->expand( $params['name'] );
3982 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3983 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3984 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3986 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3987 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3988 if ( $isFunctionTag ) {
3989 $markerType = 'none';
3991 $markerType = 'general';
3993 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3994 $name = strtolower( $name );
3995 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3996 if ( isset( $params['attributes'] ) ) {
3997 $attributes = $attributes +
$params['attributes'];
4000 if ( isset( $this->mTagHooks
[$name] ) ) {
4001 # Workaround for PHP bug 35229 and similar
4002 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4003 throw new MWException( "Tag hook for $name is not callable\n" );
4005 $output = call_user_func_array( $this->mTagHooks
[$name],
4006 array( $content, $attributes, $this, $frame ) );
4007 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4008 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4009 if ( !is_callable( $callback ) ) {
4010 throw new MWException( "Tag hook for $name is not callable\n" );
4013 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4015 $output = '<span class="error">Invalid tag extension name: ' .
4016 htmlspecialchars( $name ) . '</span>';
4019 if ( is_array( $output ) ) {
4020 # Extract flags to local scope (to override $markerType)
4022 $output = $flags[0];
4027 if ( is_null( $attrText ) ) {
4030 if ( isset( $params['attributes'] ) ) {
4031 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4032 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4033 htmlspecialchars( $attrValue ) . '"';
4036 if ( $content === null ) {
4037 $output = "<$name$attrText/>";
4039 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4040 $output = "<$name$attrText>$content$close";
4044 if ( $markerType === 'none' ) {
4046 } elseif ( $markerType === 'nowiki' ) {
4047 $this->mStripState
->addNoWiki( $marker, $output );
4048 } elseif ( $markerType === 'general' ) {
4049 $this->mStripState
->addGeneral( $marker, $output );
4051 throw new MWException( __METHOD__
. ': invalid marker type' );
4057 * Increment an include size counter
4059 * @param string $type the type of expansion
4060 * @param $size Integer: the size of the text
4061 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4063 function incrementIncludeSize( $type, $size ) {
4064 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4067 $this->mIncludeSizes
[$type] +
= $size;
4073 * Increment the expensive function count
4075 * @return Boolean: false if the limit has been exceeded
4077 function incrementExpensiveFunctionCount() {
4078 $this->mExpensiveFunctionCount++
;
4079 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4083 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4084 * Fills $this->mDoubleUnderscores, returns the modified text
4086 * @param $text string
4090 function doDoubleUnderscore( $text ) {
4091 wfProfileIn( __METHOD__
);
4093 # The position of __TOC__ needs to be recorded
4094 $mw = MagicWord
::get( 'toc' );
4095 if ( $mw->match( $text ) ) {
4096 $this->mShowToc
= true;
4097 $this->mForceTocPosition
= true;
4099 # Set a placeholder. At the end we'll fill it in with the TOC.
4100 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4102 # Only keep the first one.
4103 $text = $mw->replace( '', $text );
4106 # Now match and remove the rest of them
4107 $mwa = MagicWord
::getDoubleUnderscoreArray();
4108 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4110 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4111 $this->mOutput
->mNoGallery
= true;
4113 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4114 $this->mShowToc
= false;
4116 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4117 $this->addTrackingCategory( 'hidden-category-category' );
4119 # (bug 8068) Allow control over whether robots index a page.
4121 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4122 # is not desirable, the last one on the page should win.
4123 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4124 $this->mOutput
->setIndexPolicy( 'noindex' );
4125 $this->addTrackingCategory( 'noindex-category' );
4127 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4128 $this->mOutput
->setIndexPolicy( 'index' );
4129 $this->addTrackingCategory( 'index-category' );
4132 # Cache all double underscores in the database
4133 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4134 $this->mOutput
->setProperty( $key, '' );
4137 wfProfileOut( __METHOD__
);
4142 * Add a tracking category, getting the title from a system message,
4143 * or print a debug message if the title is invalid.
4145 * @param string $msg message key
4146 * @return Boolean: whether the addition was successful
4148 public function addTrackingCategory( $msg ) {
4149 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4150 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4153 // Important to parse with correct title (bug 31469)
4154 $cat = wfMessage( $msg )
4155 ->title( $this->getTitle() )
4156 ->inContentLanguage()
4159 # Allow tracking categories to be disabled by setting them to "-"
4160 if ( $cat === '-' ) {
4164 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4165 if ( $containerCategory ) {
4166 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4169 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4175 * This function accomplishes several tasks:
4176 * 1) Auto-number headings if that option is enabled
4177 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4178 * 3) Add a Table of contents on the top for users who have enabled the option
4179 * 4) Auto-anchor headings
4181 * It loops through all headlines, collects the necessary data, then splits up the
4182 * string and re-inserts the newly formatted headlines.
4184 * @param $text String
4185 * @param string $origText original, untouched wikitext
4186 * @param $isMain Boolean
4187 * @return mixed|string
4190 function formatHeadings( $text, $origText, $isMain = true ) {
4191 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4193 # Inhibit editsection links if requested in the page
4194 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4195 $maybeShowEditLink = $showEditLink = false;
4197 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4198 $showEditLink = $this->mOptions
->getEditSection();
4200 if ( $showEditLink ) {
4201 $this->mOutput
->setEditSectionTokens( true );
4204 # Get all headlines for numbering them and adding funky stuff like [edit]
4205 # links - this is for later, but we need the number of headlines right now
4207 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4209 # if there are fewer than 4 headlines in the article, do not show TOC
4210 # unless it's been explicitly enabled.
4211 $enoughToc = $this->mShowToc
&&
4212 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4214 # Allow user to stipulate that a page should have a "new section"
4215 # link added via __NEWSECTIONLINK__
4216 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4217 $this->mOutput
->setNewSection( true );
4220 # Allow user to remove the "new section"
4221 # link via __NONEWSECTIONLINK__
4222 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4223 $this->mOutput
->hideNewSection( true );
4226 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4227 # override above conditions and always show TOC above first header
4228 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4229 $this->mShowToc
= true;
4237 # Ugh .. the TOC should have neat indentation levels which can be
4238 # passed to the skin functions. These are determined here
4242 $sublevelCount = array();
4243 $levelCount = array();
4248 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4249 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4250 $oldType = $this->mOutputType
;
4251 $this->setOutputType( self
::OT_WIKI
);
4252 $frame = $this->getPreprocessor()->newFrame();
4253 $root = $this->preprocessToDom( $origText );
4254 $node = $root->getFirstChild();
4259 foreach ( $matches[3] as $headline ) {
4260 $isTemplate = false;
4262 $sectionIndex = false;
4264 $markerMatches = array();
4265 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4266 $serial = $markerMatches[1];
4267 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4268 $isTemplate = ( $titleText != $baseTitleText );
4269 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4273 $prevlevel = $level;
4275 $level = $matches[1][$headlineCount];
4277 if ( $level > $prevlevel ) {
4278 # Increase TOC level
4280 $sublevelCount[$toclevel] = 0;
4281 if ( $toclevel < $wgMaxTocLevel ) {
4282 $prevtoclevel = $toclevel;
4283 $toc .= Linker
::tocIndent();
4286 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4287 # Decrease TOC level, find level to jump to
4289 for ( $i = $toclevel; $i > 0; $i-- ) {
4290 if ( $levelCount[$i] == $level ) {
4291 # Found last matching level
4294 } elseif ( $levelCount[$i] < $level ) {
4295 # Found first matching level below current level
4303 if ( $toclevel < $wgMaxTocLevel ) {
4304 if ( $prevtoclevel < $wgMaxTocLevel ) {
4305 # Unindent only if the previous toc level was shown :p
4306 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4307 $prevtoclevel = $toclevel;
4309 $toc .= Linker
::tocLineEnd();
4313 # No change in level, end TOC line
4314 if ( $toclevel < $wgMaxTocLevel ) {
4315 $toc .= Linker
::tocLineEnd();
4319 $levelCount[$toclevel] = $level;
4321 # count number of headlines for each level
4322 $sublevelCount[$toclevel]++
;
4324 for ( $i = 1; $i <= $toclevel; $i++
) {
4325 if ( !empty( $sublevelCount[$i] ) ) {
4329 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4334 # The safe header is a version of the header text safe to use for links
4336 # Remove link placeholders by the link text.
4337 # <!--LINK number-->
4339 # link text with suffix
4340 # Do this before unstrip since link text can contain strip markers
4341 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4343 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4344 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4346 # Strip out HTML (first regex removes any tag not allowed)
4348 # * <sup> and <sub> (bug 8393)
4351 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4353 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4354 # to allow setting directionality in toc items.
4355 $tocline = preg_replace(
4356 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4357 array( '', '<$1>' ),
4360 $tocline = trim( $tocline );
4362 # For the anchor, strip out HTML-y stuff period
4363 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4364 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4366 # Save headline for section edit hint before it's escaped
4367 $headlineHint = $safeHeadline;
4369 if ( $wgExperimentalHtmlIds ) {
4370 # For reverse compatibility, provide an id that's
4371 # HTML4-compatible, like we used to.
4373 # It may be worth noting, academically, that it's possible for
4374 # the legacy anchor to conflict with a non-legacy headline
4375 # anchor on the page. In this case likely the "correct" thing
4376 # would be to either drop the legacy anchors or make sure
4377 # they're numbered first. However, this would require people
4378 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4379 # manually, so let's not bother worrying about it.
4380 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4381 array( 'noninitial', 'legacy' ) );
4382 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4384 if ( $legacyHeadline == $safeHeadline ) {
4385 # No reason to have both (in fact, we can't)
4386 $legacyHeadline = false;
4389 $legacyHeadline = false;
4390 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4394 # HTML names must be case-insensitively unique (bug 10721).
4395 # This does not apply to Unicode characters per
4396 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4397 # @todo FIXME: We may be changing them depending on the current locale.
4398 $arrayKey = strtolower( $safeHeadline );
4399 if ( $legacyHeadline === false ) {
4400 $legacyArrayKey = false;
4402 $legacyArrayKey = strtolower( $legacyHeadline );
4405 # count how many in assoc. array so we can track dupes in anchors
4406 if ( isset( $refers[$arrayKey] ) ) {
4407 $refers[$arrayKey]++
;
4409 $refers[$arrayKey] = 1;
4411 if ( isset( $refers[$legacyArrayKey] ) ) {
4412 $refers[$legacyArrayKey]++
;
4414 $refers[$legacyArrayKey] = 1;
4417 # Don't number the heading if it is the only one (looks silly)
4418 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4419 # the two are different if the line contains a link
4420 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4423 # Create the anchor for linking from the TOC to the section
4424 $anchor = $safeHeadline;
4425 $legacyAnchor = $legacyHeadline;
4426 if ( $refers[$arrayKey] > 1 ) {
4427 $anchor .= '_' . $refers[$arrayKey];
4429 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4430 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4432 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4433 $toc .= Linker
::tocLine( $anchor, $tocline,
4434 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4437 # Add the section to the section tree
4438 # Find the DOM node for this header
4439 while ( $node && !$isTemplate ) {
4440 if ( $node->getName() === 'h' ) {
4441 $bits = $node->splitHeading();
4442 if ( $bits['i'] == $sectionIndex ) {
4446 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4447 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4448 $node = $node->getNextSibling();
4451 'toclevel' => $toclevel,
4454 'number' => $numbering,
4455 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4456 'fromtitle' => $titleText,
4457 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4458 'anchor' => $anchor,
4461 # give headline the correct <h#> tag
4462 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4463 // Output edit section links as markers with styles that can be customized by skins
4464 if ( $isTemplate ) {
4465 # Put a T flag in the section identifier, to indicate to extractSections()
4466 # that sections inside <includeonly> should be counted.
4467 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4469 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4471 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4472 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4473 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4474 // so we don't have to worry about a user trying to input one of these markers directly.
4475 // We use a page and section attribute to stop the language converter from converting these important bits
4476 // of data, but put the headline hint inside a content block because the language converter is supposed to
4477 // be able to convert that piece of data.
4478 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4479 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4480 if ( isset( $editlinkArgs[2] ) ) {
4481 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4488 $head[$headlineCount] = Linker
::makeHeadline( $level,
4489 $matches['attrib'][$headlineCount], $anchor, $headline,
4490 $editlink, $legacyAnchor );
4495 $this->setOutputType( $oldType );
4497 # Never ever show TOC if no headers
4498 if ( $numVisible < 1 ) {
4503 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4504 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4506 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4507 $this->mOutput
->setTOCHTML( $toc );
4511 $this->mOutput
->setSections( $tocraw );
4514 # split up and insert constructed headlines
4515 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4518 // build an array of document sections
4519 $sections = array();
4520 foreach ( $blocks as $block ) {
4521 // $head is zero-based, sections aren't.
4522 if ( empty( $head[$i - 1] ) ) {
4523 $sections[$i] = $block;
4525 $sections[$i] = $head[$i - 1] . $block;
4529 * Send a hook, one per section.
4530 * The idea here is to be able to make section-level DIVs, but to do so in a
4531 * lower-impact, more correct way than r50769
4534 * $section : the section number
4535 * &$sectionContent : ref to the content of the section
4536 * $showEditLinks : boolean describing whether this section has an edit link
4538 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4543 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4544 // append the TOC at the beginning
4545 // Top anchor now in skin
4546 $sections[0] = $sections[0] . $toc . "\n";
4549 $full .= join( '', $sections );
4551 if ( $this->mForceTocPosition
) {
4552 return str_replace( '<!--MWTOC-->', $toc, $full );
4559 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4560 * conversion, substitting signatures, {{subst:}} templates, etc.
4562 * @param string $text the text to transform
4563 * @param $title Title: the Title object for the current article
4564 * @param $user User: the User object describing the current user
4565 * @param $options ParserOptions: parsing options
4566 * @param $clearState Boolean: whether to clear the parser state first
4567 * @return String: the altered wiki markup
4569 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4570 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4571 $this->setUser( $user );
4576 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4577 if ( $options->getPreSaveTransform() ) {
4578 $text = $this->pstPass2( $text, $user );
4580 $text = $this->mStripState
->unstripBoth( $text );
4582 $this->setUser( null ); #Reset
4588 * Pre-save transform helper function
4591 * @param $text string
4596 function pstPass2( $text, $user ) {
4599 # Note: This is the timestamp saved as hardcoded wikitext to
4600 # the database, we use $wgContLang here in order to give
4601 # everyone the same signature and use the default one rather
4602 # than the one selected in each user's preferences.
4603 # (see also bug 12815)
4604 $ts = $this->mOptions
->getTimestamp();
4605 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4606 $ts = $timestamp->format( 'YmdHis' );
4607 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4609 # Allow translation of timezones through wiki. format() can return
4610 # whatever crap the system uses, localised or not, so we cannot
4611 # ship premade translations.
4612 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4613 $msg = wfMessage( $key )->inContentLanguage();
4614 if ( $msg->exists() ) {
4615 $tzMsg = $msg->text();
4618 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4620 # Variable replacement
4621 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4622 $text = $this->replaceVariables( $text );
4624 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4625 # which may corrupt this parser instance via its wfMessage()->text() call-
4628 $sigText = $this->getUserSig( $user );
4629 $text = strtr( $text, array(
4631 '~~~~' => "$sigText $d",
4635 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4636 $tc = '[' . Title
::legalChars() . ']';
4637 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4639 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4640 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4641 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4642 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4644 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4645 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4646 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4647 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4649 $t = $this->mTitle
->getText();
4651 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4652 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4653 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4654 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4656 # if there's no context, don't bother duplicating the title
4657 $text = preg_replace( $p2, '[[\\1]]', $text );
4660 # Trim trailing whitespace
4661 $text = rtrim( $text );
4667 * Fetch the user's signature text, if any, and normalize to
4668 * validated, ready-to-insert wikitext.
4669 * If you have pre-fetched the nickname or the fancySig option, you can
4670 * specify them here to save a database query.
4671 * Do not reuse this parser instance after calling getUserSig(),
4672 * as it may have changed if it's the $wgParser.
4675 * @param string|bool $nickname nickname to use or false to use user's default nickname
4676 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4677 * or null to use default value
4680 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4681 global $wgMaxSigChars;
4683 $username = $user->getName();
4685 # If not given, retrieve from the user object.
4686 if ( $nickname === false ) {
4687 $nickname = $user->getOption( 'nickname' );
4690 if ( is_null( $fancySig ) ) {
4691 $fancySig = $user->getBoolOption( 'fancysig' );
4694 $nickname = $nickname == null ?
$username : $nickname;
4696 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4697 $nickname = $username;
4698 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4699 } elseif ( $fancySig !== false ) {
4700 # Sig. might contain markup; validate this
4701 if ( $this->validateSig( $nickname ) !== false ) {
4702 # Validated; clean up (if needed) and return it
4703 return $this->cleanSig( $nickname, true );
4705 # Failed to validate; fall back to the default
4706 $nickname = $username;
4707 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4711 # Make sure nickname doesnt get a sig in a sig
4712 $nickname = self
::cleanSigInSig( $nickname );
4714 # If we're still here, make it a link to the user page
4715 $userText = wfEscapeWikiText( $username );
4716 $nickText = wfEscapeWikiText( $nickname );
4717 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4719 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4723 * Check that the user's signature contains no bad XML
4725 * @param $text String
4726 * @return mixed An expanded string, or false if invalid.
4728 function validateSig( $text ) {
4729 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4733 * Clean up signature text
4735 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4736 * 2) Substitute all transclusions
4738 * @param $text String
4739 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4740 * @return String: signature text
4742 public function cleanSig( $text, $parsing = false ) {
4745 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4748 # Option to disable this feature
4749 if ( !$this->mOptions
->getCleanSignatures() ) {
4753 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4754 # => Move this logic to braceSubstitution()
4755 $substWord = MagicWord
::get( 'subst' );
4756 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4757 $substText = '{{' . $substWord->getSynonym( 0 );
4759 $text = preg_replace( $substRegex, $substText, $text );
4760 $text = self
::cleanSigInSig( $text );
4761 $dom = $this->preprocessToDom( $text );
4762 $frame = $this->getPreprocessor()->newFrame();
4763 $text = $frame->expand( $dom );
4766 $text = $this->mStripState
->unstripBoth( $text );
4773 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4775 * @param $text String
4776 * @return String: signature text with /~{3,5}/ removed
4778 public static function cleanSigInSig( $text ) {
4779 $text = preg_replace( '/~{3,5}/', '', $text );
4784 * Set up some variables which are usually set up in parse()
4785 * so that an external function can call some class members with confidence
4787 * @param $title Title|null
4788 * @param $options ParserOptions
4789 * @param $outputType
4790 * @param $clearState bool
4792 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4793 $this->startParse( $title, $options, $outputType, $clearState );
4797 * @param $title Title|null
4798 * @param $options ParserOptions
4799 * @param $outputType
4800 * @param $clearState bool
4802 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4803 $this->setTitle( $title );
4804 $this->mOptions
= $options;
4805 $this->setOutputType( $outputType );
4806 if ( $clearState ) {
4807 $this->clearState();
4812 * Wrapper for preprocess()
4814 * @param string $text the text to preprocess
4815 * @param $options ParserOptions: options
4816 * @param $title Title object or null to use $wgTitle
4819 public function transformMsg( $text, $options, $title = null ) {
4820 static $executing = false;
4822 # Guard against infinite recursion
4828 wfProfileIn( __METHOD__
);
4834 $text = $this->preprocess( $text, $title, $options );
4837 wfProfileOut( __METHOD__
);
4842 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4843 * The callback should have the following form:
4844 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4846 * Transform and return $text. Use $parser for any required context, e.g. use
4847 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4849 * Hooks may return extended information by returning an array, of which the
4850 * first numbered element (index 0) must be the return string, and all other
4851 * entries are extracted into local variables within an internal function
4852 * in the Parser class.
4854 * This interface (introduced r61913) appears to be undocumented, but
4855 * 'markerName' is used by some core tag hooks to override which strip
4856 * array their results are placed in. **Use great caution if attempting
4857 * this interface, as it is not documented and injudicious use could smash
4858 * private variables.**
4860 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4861 * @param $callback Mixed: the callback function (and object) to use for the tag
4862 * @throws MWException
4863 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4865 public function setHook( $tag, $callback ) {
4866 $tag = strtolower( $tag );
4867 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4868 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4870 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4871 $this->mTagHooks
[$tag] = $callback;
4872 if ( !in_array( $tag, $this->mStripList
) ) {
4873 $this->mStripList
[] = $tag;
4880 * As setHook(), but letting the contents be parsed.
4882 * Transparent tag hooks are like regular XML-style tag hooks, except they
4883 * operate late in the transformation sequence, on HTML instead of wikitext.
4885 * This is probably obsoleted by things dealing with parser frames?
4886 * The only extension currently using it is geoserver.
4889 * @todo better document or deprecate this
4891 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4892 * @param $callback Mixed: the callback function (and object) to use for the tag
4893 * @throws MWException
4894 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4896 function setTransparentTagHook( $tag, $callback ) {
4897 $tag = strtolower( $tag );
4898 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4899 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4901 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4902 $this->mTransparentTagHooks
[$tag] = $callback;
4908 * Remove all tag hooks
4910 function clearTagHooks() {
4911 $this->mTagHooks
= array();
4912 $this->mFunctionTagHooks
= array();
4913 $this->mStripList
= $this->mDefaultStripList
;
4917 * Create a function, e.g. {{sum:1|2|3}}
4918 * The callback function should have the form:
4919 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4921 * Or with SFH_OBJECT_ARGS:
4922 * function myParserFunction( $parser, $frame, $args ) { ... }
4924 * The callback may either return the text result of the function, or an array with the text
4925 * in element 0, and a number of flags in the other elements. The names of the flags are
4926 * specified in the keys. Valid flags are:
4927 * found The text returned is valid, stop processing the template. This
4929 * nowiki Wiki markup in the return value should be escaped
4930 * isHTML The returned text is HTML, armour it against wikitext transformation
4932 * @param string $id The magic word ID
4933 * @param $callback Mixed: the callback function (and object) to use
4934 * @param $flags Integer: a combination of the following flags:
4935 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4937 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4938 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4939 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4940 * the arguments, and to control the way they are expanded.
4942 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4943 * arguments, for instance:
4944 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4946 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4947 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4948 * working if/when this is changed.
4950 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4953 * Please read the documentation in includes/parser/Preprocessor.php for more information
4954 * about the methods available in PPFrame and PPNode.
4956 * @throws MWException
4957 * @return string|callback The old callback function for this name, if any
4959 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4962 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4963 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4965 # Add to function cache
4966 $mw = MagicWord
::get( $id );
4968 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4971 $synonyms = $mw->getSynonyms();
4972 $sensitive = intval( $mw->isCaseSensitive() );
4974 foreach ( $synonyms as $syn ) {
4976 if ( !$sensitive ) {
4977 $syn = $wgContLang->lc( $syn );
4980 if ( !( $flags & SFH_NO_HASH
) ) {
4983 # Remove trailing colon
4984 if ( substr( $syn, -1, 1 ) === ':' ) {
4985 $syn = substr( $syn, 0, -1 );
4987 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4993 * Get all registered function hook identifiers
4997 function getFunctionHooks() {
4998 return array_keys( $this->mFunctionHooks
);
5002 * Create a tag function, e.g. "<test>some stuff</test>".
5003 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5004 * Unlike parser functions, their content is not preprocessed.
5008 * @throws MWException
5011 function setFunctionTagHook( $tag, $callback, $flags ) {
5012 $tag = strtolower( $tag );
5013 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5014 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5016 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5017 $this->mFunctionTagHooks
[$tag] : null;
5018 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5020 if ( !in_array( $tag, $this->mStripList
) ) {
5021 $this->mStripList
[] = $tag;
5028 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5029 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5030 * Placeholders created in Skin::makeLinkObj()
5032 * @param $text string
5033 * @param $options int
5035 * @return array of link CSS classes, indexed by PDBK.
5037 function replaceLinkHolders( &$text, $options = 0 ) {
5038 return $this->mLinkHolders
->replace( $text );
5042 * Replace "<!--LINK-->" link placeholders with plain text of links
5043 * (not HTML-formatted).
5045 * @param $text String
5048 function replaceLinkHoldersText( $text ) {
5049 return $this->mLinkHolders
->replaceText( $text );
5053 * Renders an image gallery from a text with one line per image.
5054 * text labels may be given by using |-style alternative text. E.g.
5055 * Image:one.jpg|The number "1"
5056 * Image:tree.jpg|A tree
5057 * given as text will return the HTML of a gallery with two images,
5058 * labeled 'The number "1"' and
5061 * @param string $text
5062 * @param array $params
5063 * @return string HTML
5065 function renderImageGallery( $text, $params ) {
5066 wfProfileIn( __METHOD__
);
5069 if ( isset( $params['mode'] ) ) {
5070 $mode = $params['mode'];
5074 $ig = ImageGalleryBase
::factory( $mode );
5075 } catch ( MWException
$e ) {
5076 // If invalid type set, fallback to default.
5077 $ig = ImageGalleryBase
::factory( false );
5080 $ig->setContextTitle( $this->mTitle
);
5081 $ig->setShowBytes( false );
5082 $ig->setShowFilename( false );
5083 $ig->setParser( $this );
5084 $ig->setHideBadImages();
5085 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5087 if ( isset( $params['showfilename'] ) ) {
5088 $ig->setShowFilename( true );
5090 $ig->setShowFilename( false );
5092 if ( isset( $params['caption'] ) ) {
5093 $caption = $params['caption'];
5094 $caption = htmlspecialchars( $caption );
5095 $caption = $this->replaceInternalLinks( $caption );
5096 $ig->setCaptionHtml( $caption );
5098 if ( isset( $params['perrow'] ) ) {
5099 $ig->setPerRow( $params['perrow'] );
5101 if ( isset( $params['widths'] ) ) {
5102 $ig->setWidths( $params['widths'] );
5104 if ( isset( $params['heights'] ) ) {
5105 $ig->setHeights( $params['heights'] );
5107 $ig->setAdditionalOptions( $params );
5109 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5111 $lines = StringUtils
::explode( "\n", $text );
5112 foreach ( $lines as $line ) {
5113 # match lines like these:
5114 # Image:someimage.jpg|This is some image
5116 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5118 if ( count( $matches ) == 0 ) {
5122 if ( strpos( $matches[0], '%' ) !== false ) {
5123 $matches[1] = rawurldecode( $matches[1] );
5125 $title = Title
::newFromText( $matches[1], NS_FILE
);
5126 if ( is_null( $title ) ) {
5127 # Bogus title. Ignore these so we don't bomb out later.
5131 # We need to get what handler the file uses, to figure out parameters.
5132 # Note, a hook can overide the file name, and chose an entirely different
5133 # file (which potentially could be of a different type and have different handler).
5136 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5137 array( $this, $title, &$options, &$descQuery ) );
5138 # Don't register it now, as ImageGallery does that later.
5139 $file = $this->fetchFileNoRegister( $title, $options );
5140 $handler = $file ?
$file->getHandler() : false;
5142 wfProfileIn( __METHOD__
. '-getMagicWord' );
5144 'img_alt' => 'gallery-internal-alt',
5145 'img_link' => 'gallery-internal-link',
5148 $paramMap = $paramMap +
$handler->getParamMap();
5149 // We don't want people to specify per-image widths.
5150 // Additionally the width parameter would need special casing anyhow.
5151 unset( $paramMap['img_width'] );
5154 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5155 wfProfileOut( __METHOD__
. '-getMagicWord' );
5160 $handlerOptions = array();
5161 if ( isset( $matches[3] ) ) {
5162 // look for an |alt= definition while trying not to break existing
5163 // captions with multiple pipes (|) in it, until a more sensible grammar
5164 // is defined for images in galleries
5166 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5167 // splitting on '|' is a bit odd, and different from makeImage.
5168 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5169 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5171 foreach ( $parameterMatches as $parameterMatch ) {
5172 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5174 $paramName = $paramMap[$magicName];
5176 switch ( $paramName ) {
5177 case 'gallery-internal-alt':
5178 $alt = $this->stripAltText( $match, false );
5180 case 'gallery-internal-link':
5181 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5182 $chars = self
::EXT_LINK_URL_CLASS
;
5183 $prots = $this->mUrlProtocols
;
5184 //check to see if link matches an absolute url, if not then it must be a wiki link.
5185 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5188 $localLinkTitle = Title
::newFromText( $linkValue );
5189 if ( $localLinkTitle !== null ) {
5190 $link = $localLinkTitle->getLocalURL();
5195 // Must be a handler specific parameter.
5196 if ( $handler->validateParam( $paramName, $match ) ) {
5197 $handlerOptions[$paramName] = $match;
5199 // Guess not. Append it to the caption.
5200 wfDebug( "$parameterMatch failed parameter validation" );
5201 $label .= '|' . $parameterMatch;
5206 // concatenate all other pipes
5207 $label .= '|' . $parameterMatch;
5210 // remove the first pipe
5211 $label = substr( $label, 1 );
5214 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5216 $html = $ig->toHTML();
5217 wfProfileOut( __METHOD__
);
5225 function getImageParams( $handler ) {
5227 $handlerClass = get_class( $handler );
5231 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5232 # Initialise static lists
5233 static $internalParamNames = array(
5234 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5235 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5236 'bottom', 'text-bottom' ),
5237 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5238 'upright', 'border', 'link', 'alt', 'class' ),
5240 static $internalParamMap;
5241 if ( !$internalParamMap ) {
5242 $internalParamMap = array();
5243 foreach ( $internalParamNames as $type => $names ) {
5244 foreach ( $names as $name ) {
5245 $magicName = str_replace( '-', '_', "img_$name" );
5246 $internalParamMap[$magicName] = array( $type, $name );
5251 # Add handler params
5252 $paramMap = $internalParamMap;
5254 $handlerParamMap = $handler->getParamMap();
5255 foreach ( $handlerParamMap as $magic => $paramName ) {
5256 $paramMap[$magic] = array( 'handler', $paramName );
5259 $this->mImageParams
[$handlerClass] = $paramMap;
5260 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5262 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5266 * Parse image options text and use it to make an image
5268 * @param $title Title
5269 * @param $options String
5270 * @param $holders LinkHolderArray|bool
5271 * @return string HTML
5273 function makeImage( $title, $options, $holders = false ) {
5274 # Check if the options text is of the form "options|alt text"
5276 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5277 # * left no resizing, just left align. label is used for alt= only
5278 # * right same, but right aligned
5279 # * none same, but not aligned
5280 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5281 # * center center the image
5282 # * frame Keep original image size, no magnify-button.
5283 # * framed Same as "frame"
5284 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5285 # * upright reduce width for upright images, rounded to full __0 px
5286 # * border draw a 1px border around the image
5287 # * alt Text for HTML alt attribute (defaults to empty)
5288 # * class Set a class for img node
5289 # * link Set the target of the image link. Can be external, interwiki, or local
5290 # vertical-align values (no % or length right now):
5300 $parts = StringUtils
::explode( "|", $options );
5302 # Give extensions a chance to select the file revision for us
5305 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5306 array( $this, $title, &$options, &$descQuery ) );
5307 # Fetch and register the file (file title may be different via hooks)
5308 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5311 $handler = $file ?
$file->getHandler() : false;
5313 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5316 $this->addTrackingCategory( 'broken-file-category' );
5319 # Process the input parameters
5321 $params = array( 'frame' => array(), 'handler' => array(),
5322 'horizAlign' => array(), 'vertAlign' => array() );
5323 foreach ( $parts as $part ) {
5324 $part = trim( $part );
5325 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5327 if ( isset( $paramMap[$magicName] ) ) {
5328 list( $type, $paramName ) = $paramMap[$magicName];
5330 # Special case; width and height come in one variable together
5331 if ( $type === 'handler' && $paramName === 'width' ) {
5332 $parsedWidthParam = $this->parseWidthParam( $value );
5333 if ( isset( $parsedWidthParam['width'] ) ) {
5334 $width = $parsedWidthParam['width'];
5335 if ( $handler->validateParam( 'width', $width ) ) {
5336 $params[$type]['width'] = $width;
5340 if ( isset( $parsedWidthParam['height'] ) ) {
5341 $height = $parsedWidthParam['height'];
5342 if ( $handler->validateParam( 'height', $height ) ) {
5343 $params[$type]['height'] = $height;
5347 # else no validation -- bug 13436
5349 if ( $type === 'handler' ) {
5350 # Validate handler parameter
5351 $validated = $handler->validateParam( $paramName, $value );
5353 # Validate internal parameters
5354 switch ( $paramName ) {
5358 # @todo FIXME: Possibly check validity here for
5359 # manualthumb? downstream behavior seems odd with
5360 # missing manual thumbs.
5362 $value = $this->stripAltText( $value, $holders );
5365 $chars = self
::EXT_LINK_URL_CLASS
;
5366 $prots = $this->mUrlProtocols
;
5367 if ( $value === '' ) {
5368 $paramName = 'no-link';
5371 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5372 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5373 $paramName = 'link-url';
5374 $this->mOutput
->addExternalLink( $value );
5375 if ( $this->mOptions
->getExternalLinkTarget() ) {
5376 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5381 $linkTitle = Title
::newFromText( $value );
5383 $paramName = 'link-title';
5384 $value = $linkTitle;
5385 $this->mOutput
->addLink( $linkTitle );
5391 # Most other things appear to be empty or numeric...
5392 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5397 $params[$type][$paramName] = $value;
5401 if ( !$validated ) {
5406 # Process alignment parameters
5407 if ( $params['horizAlign'] ) {
5408 $params['frame']['align'] = key( $params['horizAlign'] );
5410 if ( $params['vertAlign'] ) {
5411 $params['frame']['valign'] = key( $params['vertAlign'] );
5414 $params['frame']['caption'] = $caption;
5416 # Will the image be presented in a frame, with the caption below?
5417 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5418 isset( $params['frame']['framed'] ) ||
5419 isset( $params['frame']['thumbnail'] ) ||
5420 isset( $params['frame']['manualthumb'] );
5422 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5423 # came to also set the caption, ordinary text after the image -- which
5424 # makes no sense, because that just repeats the text multiple times in
5425 # screen readers. It *also* came to set the title attribute.
5427 # Now that we have an alt attribute, we should not set the alt text to
5428 # equal the caption: that's worse than useless, it just repeats the
5429 # text. This is the framed/thumbnail case. If there's no caption, we
5430 # use the unnamed parameter for alt text as well, just for the time be-
5431 # ing, if the unnamed param is set and the alt param is not.
5433 # For the future, we need to figure out if we want to tweak this more,
5434 # e.g., introducing a title= parameter for the title; ignoring the un-
5435 # named parameter entirely for images without a caption; adding an ex-
5436 # plicit caption= parameter and preserving the old magic unnamed para-
5438 if ( $imageIsFramed ) { # Framed image
5439 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5440 # No caption or alt text, add the filename as the alt text so
5441 # that screen readers at least get some description of the image
5442 $params['frame']['alt'] = $title->getText();
5444 # Do not set $params['frame']['title'] because tooltips don't make sense
5446 } else { # Inline image
5447 if ( !isset( $params['frame']['alt'] ) ) {
5448 # No alt text, use the "caption" for the alt text
5449 if ( $caption !== '' ) {
5450 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5452 # No caption, fall back to using the filename for the
5454 $params['frame']['alt'] = $title->getText();
5457 # Use the "caption" for the tooltip text
5458 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5461 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5463 # Linker does the rest
5464 $time = isset( $options['time'] ) ?
$options['time'] : false;
5465 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5466 $time, $descQuery, $this->mOptions
->getThumbSize() );
5468 # Give the handler a chance to modify the parser object
5470 $handler->parserTransformHook( $this, $file );
5478 * @param $holders LinkHolderArray
5479 * @return mixed|String
5481 protected function stripAltText( $caption, $holders ) {
5482 # Strip bad stuff out of the title (tooltip). We can't just use
5483 # replaceLinkHoldersText() here, because if this function is called
5484 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5486 $tooltip = $holders->replaceText( $caption );
5488 $tooltip = $this->replaceLinkHoldersText( $caption );
5491 # make sure there are no placeholders in thumbnail attributes
5492 # that are later expanded to html- so expand them now and
5494 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5495 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5501 * Set a flag in the output object indicating that the content is dynamic and
5502 * shouldn't be cached.
5504 function disableCache() {
5505 wfDebug( "Parser output marked as uncacheable.\n" );
5506 if ( !$this->mOutput
) {
5507 throw new MWException( __METHOD__
.
5508 " can only be called when actually parsing something" );
5510 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5511 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5515 * Callback from the Sanitizer for expanding items found in HTML attribute
5516 * values, so they can be safely tested and escaped.
5518 * @param $text String
5519 * @param $frame PPFrame
5522 function attributeStripCallback( &$text, $frame = false ) {
5523 $text = $this->replaceVariables( $text, $frame );
5524 $text = $this->mStripState
->unstripBoth( $text );
5533 function getTags() {
5534 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5538 * Replace transparent tags in $text with the values given by the callbacks.
5540 * Transparent tag hooks are like regular XML-style tag hooks, except they
5541 * operate late in the transformation sequence, on HTML instead of wikitext.
5543 * @param $text string
5547 function replaceTransparentTags( $text ) {
5549 $elements = array_keys( $this->mTransparentTagHooks
);
5550 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5551 $replacements = array();
5553 foreach ( $matches as $marker => $data ) {
5554 list( $element, $content, $params, $tag ) = $data;
5555 $tagName = strtolower( $element );
5556 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5557 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5561 $replacements[$marker] = $output;
5563 return strtr( $text, $replacements );
5567 * Break wikitext input into sections, and either pull or replace
5568 * some particular section's text.
5570 * External callers should use the getSection and replaceSection methods.
5572 * @param string $text Page wikitext
5573 * @param string $section a section identifier string of the form:
5574 * "<flag1> - <flag2> - ... - <section number>"
5576 * Currently the only recognised flag is "T", which means the target section number
5577 * was derived during a template inclusion parse, in other words this is a template
5578 * section edit link. If no flags are given, it was an ordinary section edit link.
5579 * This flag is required to avoid a section numbering mismatch when a section is
5580 * enclosed by "<includeonly>" (bug 6563).
5582 * The section number 0 pulls the text before the first heading; other numbers will
5583 * pull the given section along with its lower-level subsections. If the section is
5584 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5586 * Section 0 is always considered to exist, even if it only contains the empty
5587 * string. If $text is the empty string and section 0 is replaced, $newText is
5590 * @param string $mode one of "get" or "replace"
5591 * @param string $newText replacement text for section data.
5592 * @return String: for "get", the extracted section text.
5593 * for "replace", the whole page with the section replaced.
5595 private function extractSections( $text, $section, $mode, $newText = '' ) {
5596 global $wgTitle; # not generally used but removes an ugly failure mode
5597 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5599 $frame = $this->getPreprocessor()->newFrame();
5601 # Process section extraction flags
5603 $sectionParts = explode( '-', $section );
5604 $sectionIndex = array_pop( $sectionParts );
5605 foreach ( $sectionParts as $part ) {
5606 if ( $part === 'T' ) {
5607 $flags |
= self
::PTD_FOR_INCLUSION
;
5611 # Check for empty input
5612 if ( strval( $text ) === '' ) {
5613 # Only sections 0 and T-0 exist in an empty document
5614 if ( $sectionIndex == 0 ) {
5615 if ( $mode === 'get' ) {
5621 if ( $mode === 'get' ) {
5629 # Preprocess the text
5630 $root = $this->preprocessToDom( $text, $flags );
5632 # <h> nodes indicate section breaks
5633 # They can only occur at the top level, so we can find them by iterating the root's children
5634 $node = $root->getFirstChild();
5636 # Find the target section
5637 if ( $sectionIndex == 0 ) {
5638 # Section zero doesn't nest, level=big
5639 $targetLevel = 1000;
5642 if ( $node->getName() === 'h' ) {
5643 $bits = $node->splitHeading();
5644 if ( $bits['i'] == $sectionIndex ) {
5645 $targetLevel = $bits['level'];
5649 if ( $mode === 'replace' ) {
5650 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5652 $node = $node->getNextSibling();
5658 if ( $mode === 'get' ) {
5665 # Find the end of the section, including nested sections
5667 if ( $node->getName() === 'h' ) {
5668 $bits = $node->splitHeading();
5669 $curLevel = $bits['level'];
5670 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5674 if ( $mode === 'get' ) {
5675 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5677 $node = $node->getNextSibling();
5680 # Write out the remainder (in replace mode only)
5681 if ( $mode === 'replace' ) {
5682 # Output the replacement text
5683 # Add two newlines on -- trailing whitespace in $newText is conventionally
5684 # stripped by the editor, so we need both newlines to restore the paragraph gap
5685 # Only add trailing whitespace if there is newText
5686 if ( $newText != "" ) {
5687 $outText .= $newText . "\n\n";
5691 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5692 $node = $node->getNextSibling();
5696 if ( is_string( $outText ) ) {
5697 # Re-insert stripped tags
5698 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5705 * This function returns the text of a section, specified by a number ($section).
5706 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5707 * the first section before any such heading (section 0).
5709 * If a section contains subsections, these are also returned.
5711 * @param string $text text to look in
5712 * @param string $section section identifier
5713 * @param string $deftext default to return if section is not found
5714 * @return string text of the requested section
5716 public function getSection( $text, $section, $deftext = '' ) {
5717 return $this->extractSections( $text, $section, "get", $deftext );
5721 * This function returns $oldtext after the content of the section
5722 * specified by $section has been replaced with $text. If the target
5723 * section does not exist, $oldtext is returned unchanged.
5725 * @param string $oldtext former text of the article
5726 * @param int $section section identifier
5727 * @param string $text replacing text
5728 * @return String: modified text
5730 public function replaceSection( $oldtext, $section, $text ) {
5731 return $this->extractSections( $oldtext, $section, "replace", $text );
5735 * Get the ID of the revision we are parsing
5737 * @return Mixed: integer or null
5739 function getRevisionId() {
5740 return $this->mRevisionId
;
5744 * Get the revision object for $this->mRevisionId
5746 * @return Revision|null either a Revision object or null
5748 protected function getRevisionObject() {
5749 if ( !is_null( $this->mRevisionObject
) ) {
5750 return $this->mRevisionObject
;
5752 if ( is_null( $this->mRevisionId
) ) {
5756 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5757 return $this->mRevisionObject
;
5761 * Get the timestamp associated with the current revision, adjusted for
5762 * the default server-local timestamp
5764 function getRevisionTimestamp() {
5765 if ( is_null( $this->mRevisionTimestamp
) ) {
5766 wfProfileIn( __METHOD__
);
5770 $revObject = $this->getRevisionObject();
5771 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5773 # The cryptic '' timezone parameter tells to use the site-default
5774 # timezone offset instead of the user settings.
5776 # Since this value will be saved into the parser cache, served
5777 # to other users, and potentially even used inside links and such,
5778 # it needs to be consistent for all visitors.
5779 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5781 wfProfileOut( __METHOD__
);
5783 return $this->mRevisionTimestamp
;
5787 * Get the name of the user that edited the last revision
5789 * @return String: user name
5791 function getRevisionUser() {
5792 if ( is_null( $this->mRevisionUser
) ) {
5793 $revObject = $this->getRevisionObject();
5795 # if this template is subst: the revision id will be blank,
5796 # so just use the current user's name
5798 $this->mRevisionUser
= $revObject->getUserText();
5799 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5800 $this->mRevisionUser
= $this->getUser()->getName();
5803 return $this->mRevisionUser
;
5807 * Mutator for $mDefaultSort
5809 * @param string $sort New value
5811 public function setDefaultSort( $sort ) {
5812 $this->mDefaultSort
= $sort;
5813 $this->mOutput
->setProperty( 'defaultsort', $sort );
5817 * Accessor for $mDefaultSort
5818 * Will use the empty string if none is set.
5820 * This value is treated as a prefix, so the
5821 * empty string is equivalent to sorting by
5826 public function getDefaultSort() {
5827 if ( $this->mDefaultSort
!== false ) {
5828 return $this->mDefaultSort
;
5835 * Accessor for $mDefaultSort
5836 * Unlike getDefaultSort(), will return false if none is set
5838 * @return string or false
5840 public function getCustomDefaultSort() {
5841 return $this->mDefaultSort
;
5845 * Try to guess the section anchor name based on a wikitext fragment
5846 * presumably extracted from a heading, for example "Header" from
5849 * @param $text string
5853 public function guessSectionNameFromWikiText( $text ) {
5854 # Strip out wikitext links(they break the anchor)
5855 $text = $this->stripSectionName( $text );
5856 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5857 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5861 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5862 * instead. For use in redirects, since IE6 interprets Redirect: headers
5863 * as something other than UTF-8 (apparently?), resulting in breakage.
5865 * @param string $text The section name
5866 * @return string An anchor
5868 public function guessLegacySectionNameFromWikiText( $text ) {
5869 # Strip out wikitext links(they break the anchor)
5870 $text = $this->stripSectionName( $text );
5871 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5872 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5876 * Strips a text string of wikitext for use in a section anchor
5878 * Accepts a text string and then removes all wikitext from the
5879 * string and leaves only the resultant text (i.e. the result of
5880 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5881 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5882 * to create valid section anchors by mimicing the output of the
5883 * parser when headings are parsed.
5885 * @param string $text text string to be stripped of wikitext
5886 * for use in a Section anchor
5887 * @return string Filtered text string
5889 public function stripSectionName( $text ) {
5890 # Strip internal link markup
5891 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5892 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5894 # Strip external link markup
5895 # @todo FIXME: Not tolerant to blank link text
5896 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5897 # on how many empty links there are on the page - need to figure that out.
5898 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5900 # Parse wikitext quotes (italics & bold)
5901 $text = $this->doQuotes( $text );
5904 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5909 * strip/replaceVariables/unstrip for preprocessor regression testing
5911 * @param $text string
5912 * @param $title Title
5913 * @param $options ParserOptions
5914 * @param $outputType int
5918 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5919 $this->startParse( $title, $options, $outputType, true );
5921 $text = $this->replaceVariables( $text );
5922 $text = $this->mStripState
->unstripBoth( $text );
5923 $text = Sanitizer
::removeHTMLtags( $text );
5928 * @param $text string
5929 * @param $title Title
5930 * @param $options ParserOptions
5933 function testPst( $text, Title
$title, ParserOptions
$options ) {
5934 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5939 * @param $title Title
5940 * @param $options ParserOptions
5943 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5944 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5948 * Call a callback function on all regions of the given text that are not
5949 * inside strip markers, and replace those regions with the return value
5950 * of the callback. For example, with input:
5954 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5955 * two strings will be replaced with the value returned by the callback in
5963 function markerSkipCallback( $s, $callback ) {
5966 while ( $i < strlen( $s ) ) {
5967 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5968 if ( $markerStart === false ) {
5969 $out .= call_user_func( $callback, substr( $s, $i ) );
5972 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5973 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5974 if ( $markerEnd === false ) {
5975 $out .= substr( $s, $markerStart );
5978 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5979 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5988 * Remove any strip markers found in the given text.
5990 * @param $text Input string
5993 function killMarkers( $text ) {
5994 return $this->mStripState
->killMarkers( $text );
5998 * Save the parser state required to convert the given half-parsed text to
5999 * HTML. "Half-parsed" in this context means the output of
6000 * recursiveTagParse() or internalParse(). This output has strip markers
6001 * from replaceVariables (extensionSubstitution() etc.), and link
6002 * placeholders from replaceLinkHolders().
6004 * Returns an array which can be serialized and stored persistently. This
6005 * array can later be loaded into another parser instance with
6006 * unserializeHalfParsedText(). The text can then be safely incorporated into
6007 * the return value of a parser hook.
6009 * @param $text string
6013 function serializeHalfParsedText( $text ) {
6014 wfProfileIn( __METHOD__
);
6017 'version' => self
::HALF_PARSED_VERSION
,
6018 'stripState' => $this->mStripState
->getSubState( $text ),
6019 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6021 wfProfileOut( __METHOD__
);
6026 * Load the parser state given in the $data array, which is assumed to
6027 * have been generated by serializeHalfParsedText(). The text contents is
6028 * extracted from the array, and its markers are transformed into markers
6029 * appropriate for the current Parser instance. This transformed text is
6030 * returned, and can be safely included in the return value of a parser
6033 * If the $data array has been stored persistently, the caller should first
6034 * check whether it is still valid, by calling isValidHalfParsedText().
6036 * @param array $data Serialized data
6037 * @throws MWException
6040 function unserializeHalfParsedText( $data ) {
6041 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6042 throw new MWException( __METHOD__
. ': invalid version' );
6045 # First, extract the strip state.
6046 $texts = array( $data['text'] );
6047 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6049 # Now renumber links
6050 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6052 # Should be good to go.
6057 * Returns true if the given array, presumed to be generated by
6058 * serializeHalfParsedText(), is compatible with the current version of the
6061 * @param $data Array
6065 function isValidHalfParsedText( $data ) {
6066 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6070 * Parsed a width param of imagelink like 300px or 200x300px
6072 * @param $value String
6077 public function parseWidthParam( $value ) {
6078 $parsedWidthParam = array();
6079 if ( $value === '' ) {
6080 return $parsedWidthParam;
6083 # (bug 13500) In both cases (width/height and width only),
6084 # permit trailing "px" for backward compatibility.
6085 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6086 $width = intval( $m[1] );
6087 $height = intval( $m[2] );
6088 $parsedWidthParam['width'] = $width;
6089 $parsedWidthParam['height'] = $height;
6090 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6091 $width = intval( $value );
6092 $parsedWidthParam['width'] = $width;
6094 return $parsedWidthParam;