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 if ( count( $arr ) == 1 ) {
1421 // First, do some preliminary work. This may shift some apostrophes from
1422 // being mark-up to being text. It also counts the number of occurrences
1423 // of bold and italics mark-ups.
1426 for ( $i = 1; $i < count( $arr ); $i +
= 2 ) {
1427 // If there are ever four apostrophes, assume the first is supposed to
1428 // be text, and the remaining three constitute mark-up for bold text.
1429 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1430 if ( strlen( $arr[$i] ) == 4 ) {
1431 $arr[$i - 1] .= "'";
1433 } elseif ( strlen( $arr[$i] ) > 5 ) {
1434 // If there are more than 5 apostrophes in a row, assume they're all
1435 // text except for the last 5.
1436 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1437 $arr[$i - 1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1440 // Count the number of occurrences of bold and italics mark-ups.
1441 if ( strlen( $arr[$i] ) == 2 ) {
1443 } elseif ( strlen( $arr[$i] ) == 3 ) {
1445 } elseif ( strlen( $arr[$i] ) == 5 ) {
1451 // If there is an odd number of both bold and italics, it is likely
1452 // that one of the bold ones was meant to be an apostrophe followed
1453 // by italics. Which one we cannot know for certain, but it is more
1454 // likely to be one that has a single-letter word before it.
1455 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1456 $firstsingleletterword = -1;
1457 $firstmultiletterword = -1;
1459 for ( $i = 1; $i < count( $arr ); $i +
= 2 ) {
1460 if ( strlen( $arr[$i] ) == 3 ) {
1461 $x1 = substr( $arr[$i - 1], -1 );
1462 $x2 = substr( $arr[$i - 1], -2, 1 );
1463 if ( $x1 === ' ' ) {
1464 if ( $firstspace == -1 ) {
1467 } elseif ( $x2 === ' ' ) {
1468 if ( $firstsingleletterword == -1 ) {
1469 $firstsingleletterword = $i;
1472 if ( $firstmultiletterword == -1 ) {
1473 $firstmultiletterword = $i;
1479 // If there is a single-letter word, use it!
1480 if ( $firstsingleletterword > -1 ) {
1481 $arr[$firstsingleletterword] = "''";
1482 $arr[$firstsingleletterword - 1] .= "'";
1483 } elseif ( $firstmultiletterword > -1 ) {
1484 // If not, but there's a multi-letter word, use that one.
1485 $arr[$firstmultiletterword] = "''";
1486 $arr[$firstmultiletterword - 1] .= "'";
1487 } elseif ( $firstspace > -1 ) {
1488 // ... otherwise use the first one that has neither.
1489 // (notice that it is possible for all three to be -1 if, for example,
1490 // there is only one pentuple-apostrophe in the line)
1491 $arr[$firstspace] = "''";
1492 $arr[$firstspace - 1] .= "'";
1496 // Now let's actually convert our apostrophic mush to HTML!
1501 foreach ( $arr as $r ) {
1502 if ( ( $i %
2 ) == 0 ) {
1503 if ( $state === 'both' ) {
1509 if ( strlen( $r ) == 2 ) {
1510 if ( $state === 'i' ) {
1513 } elseif ( $state === 'bi' ) {
1516 } elseif ( $state === 'ib' ) {
1517 $output .= '</b></i><b>';
1519 } elseif ( $state === 'both' ) {
1520 $output .= '<b><i>' . $buffer . '</i>';
1522 } else { // $state can be 'b' or ''
1526 } elseif ( strlen( $r ) == 3 ) {
1527 if ( $state === 'b' ) {
1530 } elseif ( $state === 'bi' ) {
1531 $output .= '</i></b><i>';
1533 } elseif ( $state === 'ib' ) {
1536 } elseif ( $state === 'both' ) {
1537 $output .= '<i><b>' . $buffer . '</b>';
1539 } else { // $state can be 'i' or ''
1543 } elseif ( strlen( $r ) == 5 ) {
1544 if ( $state === 'b' ) {
1545 $output .= '</b><i>';
1547 } elseif ( $state === 'i' ) {
1548 $output .= '</i><b>';
1550 } elseif ( $state === 'bi' ) {
1551 $output .= '</i></b>';
1553 } elseif ( $state === 'ib' ) {
1554 $output .= '</b></i>';
1556 } elseif ( $state === 'both' ) {
1557 $output .= '<i><b>' . $buffer . '</b></i>';
1559 } else { // ($state == '')
1567 // Now close all remaining tags. Notice that the order is important.
1568 if ( $state === 'b' ||
$state === 'ib' ) {
1571 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1574 if ( $state === 'bi' ) {
1577 // There might be lonely ''''', so make sure we have a buffer
1578 if ( $state === 'both' && $buffer ) {
1579 $output .= '<b><i>' . $buffer . '</i></b>';
1585 * Replace external links (REL)
1587 * Note: this is all very hackish and the order of execution matters a lot.
1588 * Make sure to run tests/parserTests.php if you change this code.
1592 * @param $text string
1594 * @throws MWException
1597 function replaceExternalLinks( $text ) {
1598 wfProfileIn( __METHOD__
);
1600 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1601 if ( $bits === false ) {
1602 wfProfileOut( __METHOD__
);
1603 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1605 $s = array_shift( $bits );
1608 while ( $i < count( $bits ) ) {
1611 $text = $bits[$i++
];
1612 $trail = $bits[$i++
];
1614 # The characters '<' and '>' (which were escaped by
1615 # removeHTMLtags()) should not be included in
1616 # URLs, per RFC 2396.
1618 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1619 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1620 $url = substr( $url, 0, $m2[0][1] );
1623 # If the link text is an image URL, replace it with an <img> tag
1624 # This happened by accident in the original parser, but some people used it extensively
1625 $img = $this->maybeMakeExternalImage( $text );
1626 if ( $img !== false ) {
1632 # Set linktype for CSS - if URL==text, link is essentially free
1633 $linktype = ( $text === $url ) ?
'free' : 'text';
1635 # No link text, e.g. [http://domain.tld/some.link]
1636 if ( $text == '' ) {
1638 $langObj = $this->getTargetLanguage();
1639 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1640 $linktype = 'autonumber';
1642 # Have link text, e.g. [http://domain.tld/some.link text]s
1644 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1647 $text = $this->getConverterLanguage()->markNoConversion( $text );
1649 $url = Sanitizer
::cleanUrl( $url );
1651 # Use the encoded URL
1652 # This means that users can paste URLs directly into the text
1653 # Funny characters like ö aren't valid in URLs anyway
1654 # This was changed in August 2004
1655 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1656 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1658 # Register link in the output object.
1659 # Replace unnecessary URL escape codes with the referenced character
1660 # This prevents spammers from hiding links from the filters
1661 $pasteurized = self
::replaceUnusualEscapes( $url );
1662 $this->mOutput
->addExternalLink( $pasteurized );
1665 wfProfileOut( __METHOD__
);
1669 * Get the rel attribute for a particular external link.
1672 * @param string|bool $url optional URL, to extract the domain from for rel =>
1673 * nofollow if appropriate
1674 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1675 * @return string|null rel attribute for $url
1677 public static function getExternalLinkRel( $url = false, $title = null ) {
1678 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1679 $ns = $title ?
$title->getNamespace() : false;
1680 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1681 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1688 * Get an associative array of additional HTML attributes appropriate for a
1689 * particular external link. This currently may include rel => nofollow
1690 * (depending on configuration, namespace, and the URL's domain) and/or a
1691 * target attribute (depending on configuration).
1693 * @param string|bool $url optional URL, to extract the domain from for rel =>
1694 * nofollow if appropriate
1695 * @return Array associative array of HTML attributes
1697 function getExternalLinkAttribs( $url = false ) {
1699 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1701 if ( $this->mOptions
->getExternalLinkTarget() ) {
1702 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1708 * Replace unusual URL escape codes with their equivalent characters
1710 * @param $url String
1713 * @todo This can merge genuinely required bits in the path or query string,
1714 * breaking legit URLs. A proper fix would treat the various parts of
1715 * the URL differently; as a workaround, just use the output for
1716 * statistical records, not for actual linking/output.
1718 static function replaceUnusualEscapes( $url ) {
1719 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1720 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1724 * Callback function used in replaceUnusualEscapes().
1725 * Replaces unusual URL escape codes with their equivalent character
1727 * @param $matches array
1731 private static function replaceUnusualEscapesCallback( $matches ) {
1732 $char = urldecode( $matches[0] );
1733 $ord = ord( $char );
1734 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1735 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1736 # No, shouldn't be escaped
1739 # Yes, leave it escaped
1745 * make an image if it's allowed, either through the global
1746 * option, through the exception, or through the on-wiki whitelist
1749 * $param $url string
1753 function maybeMakeExternalImage( $url ) {
1754 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1755 $imagesexception = !empty( $imagesfrom );
1757 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1758 if ( $imagesexception && is_array( $imagesfrom ) ) {
1759 $imagematch = false;
1760 foreach ( $imagesfrom as $match ) {
1761 if ( strpos( $url, $match ) === 0 ) {
1766 } elseif ( $imagesexception ) {
1767 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1769 $imagematch = false;
1771 if ( $this->mOptions
->getAllowExternalImages()
1772 ||
( $imagesexception && $imagematch ) ) {
1773 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1775 $text = Linker
::makeExternalImage( $url );
1778 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1779 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1780 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1781 foreach ( $whitelist as $entry ) {
1782 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1783 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1786 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1787 # Image matches a whitelist entry
1788 $text = Linker
::makeExternalImage( $url );
1797 * Process [[ ]] wikilinks
1801 * @return String: processed text
1805 function replaceInternalLinks( $s ) {
1806 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1811 * Process [[ ]] wikilinks (RIL)
1813 * @throws MWException
1814 * @return LinkHolderArray
1818 function replaceInternalLinks2( &$s ) {
1819 wfProfileIn( __METHOD__
);
1821 wfProfileIn( __METHOD__
. '-setup' );
1822 static $tc = false, $e1, $e1_img;
1823 # the % is needed to support urlencoded titles as well
1825 $tc = Title
::legalChars() . '#%';
1826 # Match a link having the form [[namespace:link|alternate]]trail
1827 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1828 # Match cases where there is no "]]", which might still be images
1829 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1832 $holders = new LinkHolderArray( $this );
1834 # split the entire text string on occurrences of [[
1835 $a = StringUtils
::explode( '[[', ' ' . $s );
1836 # get the first element (all text up to first [[), and remove the space we added
1839 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1840 $s = substr( $s, 1 );
1842 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1844 if ( $useLinkPrefixExtension ) {
1845 # Match the end of a line for a word that's not followed by whitespace,
1846 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1847 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1850 if ( is_null( $this->mTitle
) ) {
1851 wfProfileOut( __METHOD__
. '-setup' );
1852 wfProfileOut( __METHOD__
);
1853 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1855 $nottalk = !$this->mTitle
->isTalkPage();
1857 if ( $useLinkPrefixExtension ) {
1859 if ( preg_match( $e2, $s, $m ) ) {
1860 $first_prefix = $m[2];
1862 $first_prefix = false;
1868 $useSubpages = $this->areSubpagesAllowed();
1869 wfProfileOut( __METHOD__
. '-setup' );
1871 # Loop for each link
1872 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1873 # Check for excessive memory usage
1874 if ( $holders->isBig() ) {
1876 # Do the existence check, replace the link holders and clear the array
1877 $holders->replace( $s );
1881 if ( $useLinkPrefixExtension ) {
1882 wfProfileIn( __METHOD__
. '-prefixhandling' );
1883 if ( preg_match( $e2, $s, $m ) ) {
1890 if ( $first_prefix ) {
1891 $prefix = $first_prefix;
1892 $first_prefix = false;
1894 wfProfileOut( __METHOD__
. '-prefixhandling' );
1897 $might_be_img = false;
1899 wfProfileIn( __METHOD__
. "-e1" );
1900 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1902 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1903 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1904 # the real problem is with the $e1 regex
1907 # Still some problems for cases where the ] is meant to be outside punctuation,
1908 # and no image is in sight. See bug 2095.
1910 if ( $text !== '' &&
1911 substr( $m[3], 0, 1 ) === ']' &&
1912 strpos( $text, '[' ) !== false
1915 $text .= ']'; # so that replaceExternalLinks($text) works later
1916 $m[3] = substr( $m[3], 1 );
1918 # fix up urlencoded title texts
1919 if ( strpos( $m[1], '%' ) !== false ) {
1920 # Should anchors '#' also be rejected?
1921 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1924 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1925 $might_be_img = true;
1927 if ( strpos( $m[1], '%' ) !== false ) {
1928 $m[1] = rawurldecode( $m[1] );
1931 } else { # Invalid form; output directly
1932 $s .= $prefix . '[[' . $line;
1933 wfProfileOut( __METHOD__
. "-e1" );
1936 wfProfileOut( __METHOD__
. "-e1" );
1937 wfProfileIn( __METHOD__
. "-misc" );
1939 # Don't allow internal links to pages containing
1940 # PROTO: where PROTO is a valid URL protocol; these
1941 # should be external links.
1942 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1943 $s .= $prefix . '[[' . $line;
1944 wfProfileOut( __METHOD__
. "-misc" );
1948 # Make subpage if necessary
1949 if ( $useSubpages ) {
1950 $link = $this->maybeDoSubpageLink( $m[1], $text );
1955 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1957 # Strip off leading ':'
1958 $link = substr( $link, 1 );
1961 wfProfileOut( __METHOD__
. "-misc" );
1962 wfProfileIn( __METHOD__
. "-title" );
1963 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1964 if ( $nt === null ) {
1965 $s .= $prefix . '[[' . $line;
1966 wfProfileOut( __METHOD__
. "-title" );
1970 $ns = $nt->getNamespace();
1971 $iw = $nt->getInterWiki();
1972 wfProfileOut( __METHOD__
. "-title" );
1974 if ( $might_be_img ) { # if this is actually an invalid link
1975 wfProfileIn( __METHOD__
. "-might_be_img" );
1976 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1979 # look at the next 'line' to see if we can close it there
1981 $next_line = $a->current();
1982 if ( $next_line === false ||
$next_line === null ) {
1985 $m = explode( ']]', $next_line, 3 );
1986 if ( count( $m ) == 3 ) {
1987 # the first ]] closes the inner link, the second the image
1989 $text .= "[[{$m[0]}]]{$m[1]}";
1992 } elseif ( count( $m ) == 2 ) {
1993 # if there's exactly one ]] that's fine, we'll keep looking
1994 $text .= "[[{$m[0]}]]{$m[1]}";
1996 # if $next_line is invalid too, we need look no further
1997 $text .= '[[' . $next_line;
2002 # we couldn't find the end of this imageLink, so output it raw
2003 # but don't ignore what might be perfectly normal links in the text we've examined
2004 $holders->merge( $this->replaceInternalLinks2( $text ) );
2005 $s .= "{$prefix}[[$link|$text";
2006 # note: no $trail, because without an end, there *is* no trail
2007 wfProfileOut( __METHOD__
. "-might_be_img" );
2010 } else { # it's not an image, so output it raw
2011 $s .= "{$prefix}[[$link|$text";
2012 # note: no $trail, because without an end, there *is* no trail
2013 wfProfileOut( __METHOD__
. "-might_be_img" );
2016 wfProfileOut( __METHOD__
. "-might_be_img" );
2019 $wasblank = ( $text == '' );
2023 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2024 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2025 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2026 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2027 $text = $this->doQuotes( $text );
2030 # Link not escaped by : , create the various objects
2033 wfProfileIn( __METHOD__
. "-interwiki" );
2034 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
2035 // XXX: the above check prevents links to sites with identifiers that are not language codes
2037 # Bug 24502: filter duplicates
2038 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2039 $this->mLangLinkLanguages
[$iw] = true;
2040 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2043 $s = rtrim( $s . $prefix );
2044 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2045 wfProfileOut( __METHOD__
. "-interwiki" );
2048 wfProfileOut( __METHOD__
. "-interwiki" );
2050 if ( $ns == NS_FILE
) {
2051 wfProfileIn( __METHOD__
. "-image" );
2052 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2054 # if no parameters were passed, $text
2055 # becomes something like "File:Foo.png",
2056 # which we don't want to pass on to the
2060 # recursively parse links inside the image caption
2061 # actually, this will parse them in any other parameters, too,
2062 # but it might be hard to fix that, and it doesn't matter ATM
2063 $text = $this->replaceExternalLinks( $text );
2064 $holders->merge( $this->replaceInternalLinks2( $text ) );
2066 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2067 $s .= $prefix . $this->armorLinks(
2068 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2070 $s .= $prefix . $trail;
2072 wfProfileOut( __METHOD__
. "-image" );
2076 if ( $ns == NS_CATEGORY
) {
2077 wfProfileIn( __METHOD__
. "-category" );
2078 $s = rtrim( $s . "\n" ); # bug 87
2081 $sortkey = $this->getDefaultSort();
2085 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2086 $sortkey = str_replace( "\n", '', $sortkey );
2087 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2088 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2091 * Strip the whitespace Category links produce, see bug 87
2092 * @todo We might want to use trim($tmp, "\n") here.
2094 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2096 wfProfileOut( __METHOD__
. "-category" );
2101 # Self-link checking
2102 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2103 if ( $nt->equals( $this->mTitle
) ||
( !$nt->isKnown() && in_array(
2104 $this->mTitle
->getPrefixedText(),
2105 $this->getConverterLanguage()->autoConvertToAllVariants( $nt->getPrefixedText() ),
2108 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2113 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2114 # @todo FIXME: Should do batch file existence checks, see comment below
2115 if ( $ns == NS_MEDIA
) {
2116 wfProfileIn( __METHOD__
. "-media" );
2117 # Give extensions a chance to select the file revision for us
2120 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2121 array( $this, $nt, &$options, &$descQuery ) );
2122 # Fetch and register the file (file title may be different via hooks)
2123 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2124 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2125 $s .= $prefix . $this->armorLinks(
2126 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2127 wfProfileOut( __METHOD__
. "-media" );
2131 wfProfileIn( __METHOD__
. "-always_known" );
2132 # Some titles, such as valid special pages or files in foreign repos, should
2133 # be shown as bluelinks even though they're not included in the page table
2135 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2136 # batch file existence checks for NS_FILE and NS_MEDIA
2137 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2138 $this->mOutput
->addLink( $nt );
2139 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2141 # Links will be added to the output link list after checking
2142 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2144 wfProfileOut( __METHOD__
. "-always_known" );
2146 wfProfileOut( __METHOD__
);
2151 * Render a forced-blue link inline; protect against double expansion of
2152 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2153 * Since this little disaster has to split off the trail text to avoid
2154 * breaking URLs in the following text without breaking trails on the
2155 * wiki links, it's been made into a horrible function.
2158 * @param $text String
2159 * @param array $query or String
2160 * @param $trail String
2161 * @param $prefix String
2162 * @return String: HTML-wikitext mix oh yuck
2164 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2165 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2167 if ( is_string( $query ) ) {
2168 $query = wfCgiToArray( $query );
2170 if ( $text == '' ) {
2171 $text = htmlspecialchars( $nt->getPrefixedText() );
2174 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2176 return $this->armorLinks( $link ) . $trail;
2180 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2181 * going to go through further parsing steps before inline URL expansion.
2183 * Not needed quite as much as it used to be since free links are a bit
2184 * more sensible these days. But bracketed links are still an issue.
2186 * @param string $text more-or-less HTML
2187 * @return String: less-or-more HTML with NOPARSE bits
2189 function armorLinks( $text ) {
2190 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2191 "{$this->mUniqPrefix}NOPARSE$1", $text );
2195 * Return true if subpage links should be expanded on this page.
2198 function areSubpagesAllowed() {
2199 # Some namespaces don't allow subpages
2200 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2204 * Handle link to subpage if necessary
2206 * @param string $target the source of the link
2207 * @param &$text String: the link text, modified as necessary
2208 * @return string the full name of the link
2211 function maybeDoSubpageLink( $target, &$text ) {
2212 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2216 * Used by doBlockLevels()
2221 function closeParagraph() {
2223 if ( $this->mLastSection
!= '' ) {
2224 $result = '</' . $this->mLastSection
. ">\n";
2226 $this->mInPre
= false;
2227 $this->mLastSection
= '';
2232 * getCommon() returns the length of the longest common substring
2233 * of both arguments, starting at the beginning of both.
2236 * @param $st1 string
2237 * @param $st2 string
2241 function getCommon( $st1, $st2 ) {
2242 $fl = strlen( $st1 );
2243 $shorter = strlen( $st2 );
2244 if ( $fl < $shorter ) {
2248 for ( $i = 0; $i < $shorter; ++
$i ) {
2249 if ( $st1[$i] != $st2[$i] ) {
2257 * These next three functions open, continue, and close the list
2258 * element appropriate to the prefix character passed into them.
2261 * @param $char string
2265 function openList( $char ) {
2266 $result = $this->closeParagraph();
2268 if ( '*' === $char ) {
2269 $result .= '<ul><li>';
2270 } elseif ( '#' === $char ) {
2271 $result .= '<ol><li>';
2272 } elseif ( ':' === $char ) {
2273 $result .= '<dl><dd>';
2274 } elseif ( ';' === $char ) {
2275 $result .= '<dl><dt>';
2276 $this->mDTopen
= true;
2278 $result = '<!-- ERR 1 -->';
2286 * @param $char String
2291 function nextItem( $char ) {
2292 if ( '*' === $char ||
'#' === $char ) {
2294 } elseif ( ':' === $char ||
';' === $char ) {
2296 if ( $this->mDTopen
) {
2299 if ( ';' === $char ) {
2300 $this->mDTopen
= true;
2301 return $close . '<dt>';
2303 $this->mDTopen
= false;
2304 return $close . '<dd>';
2307 return '<!-- ERR 2 -->';
2312 * @param $char String
2317 function closeList( $char ) {
2318 if ( '*' === $char ) {
2319 $text = '</li></ul>';
2320 } elseif ( '#' === $char ) {
2321 $text = '</li></ol>';
2322 } elseif ( ':' === $char ) {
2323 if ( $this->mDTopen
) {
2324 $this->mDTopen
= false;
2325 $text = '</dt></dl>';
2327 $text = '</dd></dl>';
2330 return '<!-- ERR 3 -->';
2332 return $text . "\n";
2337 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2339 * @param $text String
2340 * @param $linestart Boolean: whether or not this is at the start of a line.
2342 * @return string the lists rendered as HTML
2344 function doBlockLevels( $text, $linestart ) {
2345 wfProfileIn( __METHOD__
);
2347 # Parsing through the text line by line. The main thing
2348 # happening here is handling of block-level elements p, pre,
2349 # and making lists from lines starting with * # : etc.
2351 $textLines = StringUtils
::explode( "\n", $text );
2353 $lastPrefix = $output = '';
2354 $this->mDTopen
= $inBlockElem = false;
2356 $paragraphStack = false;
2358 foreach ( $textLines as $oLine ) {
2360 if ( !$linestart ) {
2370 $lastPrefixLength = strlen( $lastPrefix );
2371 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2372 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2373 # If not in a <pre> element, scan for and figure out what prefixes are there.
2374 if ( !$this->mInPre
) {
2375 # Multiple prefixes may abut each other for nested lists.
2376 $prefixLength = strspn( $oLine, '*#:;' );
2377 $prefix = substr( $oLine, 0, $prefixLength );
2380 # ; and : are both from definition-lists, so they're equivalent
2381 # for the purposes of determining whether or not we need to open/close
2383 $prefix2 = str_replace( ';', ':', $prefix );
2384 $t = substr( $oLine, $prefixLength );
2385 $this->mInPre
= (bool)$preOpenMatch;
2387 # Don't interpret any other prefixes in preformatted text
2389 $prefix = $prefix2 = '';
2394 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2395 # Same as the last item, so no need to deal with nesting or opening stuff
2396 $output .= $this->nextItem( substr( $prefix, -1 ) );
2397 $paragraphStack = false;
2399 if ( substr( $prefix, -1 ) === ';' ) {
2400 # The one nasty exception: definition lists work like this:
2401 # ; title : definition text
2402 # So we check for : in the remainder text to split up the
2403 # title and definition, without b0rking links.
2405 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2407 $output .= $term . $this->nextItem( ':' );
2410 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2411 # We need to open or close prefixes, or both.
2413 # Either open or close a level...
2414 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2415 $paragraphStack = false;
2417 # Close all the prefixes which aren't shared.
2418 while ( $commonPrefixLength < $lastPrefixLength ) {
2419 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2420 --$lastPrefixLength;
2423 # Continue the current prefix if appropriate.
2424 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2425 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2428 # Open prefixes where appropriate.
2429 while ( $prefixLength > $commonPrefixLength ) {
2430 $char = substr( $prefix, $commonPrefixLength, 1 );
2431 $output .= $this->openList( $char );
2433 if ( ';' === $char ) {
2434 # @todo FIXME: This is dupe of code above
2435 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2437 $output .= $term . $this->nextItem( ':' );
2440 ++
$commonPrefixLength;
2442 $lastPrefix = $prefix2;
2445 # If we have no prefixes, go to paragraph mode.
2446 if ( 0 == $prefixLength ) {
2447 wfProfileIn( __METHOD__
. "-paragraph" );
2448 # No prefix (not in list)--go to paragraph mode
2449 # XXX: use a stack for nestable elements like span, table and div
2450 $openmatch = preg_match( '/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2451 $closematch = preg_match(
2452 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2453 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2454 if ( $openmatch or $closematch ) {
2455 $paragraphStack = false;
2456 # TODO bug 5718: paragraph closed
2457 $output .= $this->closeParagraph();
2458 if ( $preOpenMatch and !$preCloseMatch ) {
2459 $this->mInPre
= true;
2461 $inBlockElem = !$closematch;
2462 } elseif ( !$inBlockElem && !$this->mInPre
) {
2463 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2465 if ( $this->mLastSection
!== 'pre' ) {
2466 $paragraphStack = false;
2467 $output .= $this->closeParagraph() . '<pre>';
2468 $this->mLastSection
= 'pre';
2470 $t = substr( $t, 1 );
2473 if ( trim( $t ) === '' ) {
2474 if ( $paragraphStack ) {
2475 $output .= $paragraphStack . '<br />';
2476 $paragraphStack = false;
2477 $this->mLastSection
= 'p';
2479 if ( $this->mLastSection
!== 'p' ) {
2480 $output .= $this->closeParagraph();
2481 $this->mLastSection
= '';
2482 $paragraphStack = '<p>';
2484 $paragraphStack = '</p><p>';
2488 if ( $paragraphStack ) {
2489 $output .= $paragraphStack;
2490 $paragraphStack = false;
2491 $this->mLastSection
= 'p';
2492 } elseif ( $this->mLastSection
!== 'p' ) {
2493 $output .= $this->closeParagraph() . '<p>';
2494 $this->mLastSection
= 'p';
2499 wfProfileOut( __METHOD__
. "-paragraph" );
2501 # somewhere above we forget to get out of pre block (bug 785)
2502 if ( $preCloseMatch && $this->mInPre
) {
2503 $this->mInPre
= false;
2505 if ( $paragraphStack === false ) {
2506 $output .= $t . "\n";
2509 while ( $prefixLength ) {
2510 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2513 if ( $this->mLastSection
!= '' ) {
2514 $output .= '</' . $this->mLastSection
. '>';
2515 $this->mLastSection
= '';
2518 wfProfileOut( __METHOD__
);
2523 * Split up a string on ':', ignoring any occurrences inside tags
2524 * to prevent illegal overlapping.
2526 * @param string $str the string to split
2527 * @param &$before String set to everything before the ':'
2528 * @param &$after String set to everything after the ':'
2529 * @throws MWException
2530 * @return String the position of the ':', or false if none found
2532 function findColonNoLinks( $str, &$before, &$after ) {
2533 wfProfileIn( __METHOD__
);
2535 $pos = strpos( $str, ':' );
2536 if ( $pos === false ) {
2538 wfProfileOut( __METHOD__
);
2542 $lt = strpos( $str, '<' );
2543 if ( $lt === false ||
$lt > $pos ) {
2544 # Easy; no tag nesting to worry about
2545 $before = substr( $str, 0, $pos );
2546 $after = substr( $str, $pos +
1 );
2547 wfProfileOut( __METHOD__
);
2551 # Ugly state machine to walk through avoiding tags.
2552 $state = self
::COLON_STATE_TEXT
;
2554 $len = strlen( $str );
2555 for ( $i = 0; $i < $len; $i++
) {
2559 # (Using the number is a performance hack for common cases)
2560 case 0: # self::COLON_STATE_TEXT:
2563 # Could be either a <start> tag or an </end> tag
2564 $state = self
::COLON_STATE_TAGSTART
;
2567 if ( $stack == 0 ) {
2569 $before = substr( $str, 0, $i );
2570 $after = substr( $str, $i +
1 );
2571 wfProfileOut( __METHOD__
);
2574 # Embedded in a tag; don't break it.
2577 # Skip ahead looking for something interesting
2578 $colon = strpos( $str, ':', $i );
2579 if ( $colon === false ) {
2580 # Nothing else interesting
2581 wfProfileOut( __METHOD__
);
2584 $lt = strpos( $str, '<', $i );
2585 if ( $stack === 0 ) {
2586 if ( $lt === false ||
$colon < $lt ) {
2588 $before = substr( $str, 0, $colon );
2589 $after = substr( $str, $colon +
1 );
2590 wfProfileOut( __METHOD__
);
2594 if ( $lt === false ) {
2595 # Nothing else interesting to find; abort!
2596 # We're nested, but there's no close tags left. Abort!
2599 # Skip ahead to next tag start
2601 $state = self
::COLON_STATE_TAGSTART
;
2604 case 1: # self::COLON_STATE_TAG:
2609 $state = self
::COLON_STATE_TEXT
;
2612 # Slash may be followed by >?
2613 $state = self
::COLON_STATE_TAGSLASH
;
2619 case 2: # self::COLON_STATE_TAGSTART:
2622 $state = self
::COLON_STATE_CLOSETAG
;
2625 $state = self
::COLON_STATE_COMMENT
;
2628 # Illegal early close? This shouldn't happen D:
2629 $state = self
::COLON_STATE_TEXT
;
2632 $state = self
::COLON_STATE_TAG
;
2635 case 3: # self::COLON_STATE_CLOSETAG:
2640 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2641 wfProfileOut( __METHOD__
);
2644 $state = self
::COLON_STATE_TEXT
;
2647 case self
::COLON_STATE_TAGSLASH
:
2649 # Yes, a self-closed tag <blah/>
2650 $state = self
::COLON_STATE_TEXT
;
2652 # Probably we're jumping the gun, and this is an attribute
2653 $state = self
::COLON_STATE_TAG
;
2656 case 5: # self::COLON_STATE_COMMENT:
2658 $state = self
::COLON_STATE_COMMENTDASH
;
2661 case self
::COLON_STATE_COMMENTDASH
:
2663 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2665 $state = self
::COLON_STATE_COMMENT
;
2668 case self
::COLON_STATE_COMMENTDASHDASH
:
2670 $state = self
::COLON_STATE_TEXT
;
2672 $state = self
::COLON_STATE_COMMENT
;
2676 wfProfileOut( __METHOD__
);
2677 throw new MWException( "State machine error in " . __METHOD__
);
2681 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2682 wfProfileOut( __METHOD__
);
2685 wfProfileOut( __METHOD__
);
2690 * Return value of a magic variable (like PAGENAME)
2694 * @param $index integer
2695 * @param bool|\PPFrame $frame
2697 * @throws MWException
2700 function getVariableValue( $index, $frame = false ) {
2701 global $wgContLang, $wgSitename, $wgServer;
2702 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2704 if ( is_null( $this->mTitle
) ) {
2705 // If no title set, bad things are going to happen
2706 // later. Title should always be set since this
2707 // should only be called in the middle of a parse
2708 // operation (but the unit-tests do funky stuff)
2709 throw new MWException( __METHOD__
. ' Should only be '
2710 . ' called while parsing (no title set)' );
2714 * Some of these require message or data lookups and can be
2715 * expensive to check many times.
2717 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2718 if ( isset( $this->mVarCache
[$index] ) ) {
2719 return $this->mVarCache
[$index];
2723 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2724 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2726 $pageLang = $this->getFunctionLang();
2729 case 'currentmonth':
2730 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2732 case 'currentmonth1':
2733 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2735 case 'currentmonthname':
2736 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2738 case 'currentmonthnamegen':
2739 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2741 case 'currentmonthabbrev':
2742 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2745 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2748 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2751 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2754 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2756 case 'localmonthname':
2757 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2759 case 'localmonthnamegen':
2760 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2762 case 'localmonthabbrev':
2763 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2766 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2769 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2772 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2775 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2777 case 'fullpagename':
2778 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2780 case 'fullpagenamee':
2781 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2784 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2786 case 'subpagenamee':
2787 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2789 case 'rootpagename':
2790 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2792 case 'rootpagenamee':
2793 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2795 case 'basepagename':
2796 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2798 case 'basepagenamee':
2799 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2801 case 'talkpagename':
2802 if ( $this->mTitle
->canTalk() ) {
2803 $talkPage = $this->mTitle
->getTalkPage();
2804 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2809 case 'talkpagenamee':
2810 if ( $this->mTitle
->canTalk() ) {
2811 $talkPage = $this->mTitle
->getTalkPage();
2812 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2817 case 'subjectpagename':
2818 $subjPage = $this->mTitle
->getSubjectPage();
2819 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2821 case 'subjectpagenamee':
2822 $subjPage = $this->mTitle
->getSubjectPage();
2823 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2825 case 'pageid': // requested in bug 23427
2826 $pageid = $this->getTitle()->getArticleID();
2827 if ( $pageid == 0 ) {
2828 # 0 means the page doesn't exist in the database,
2829 # which means the user is previewing a new page.
2830 # The vary-revision flag must be set, because the magic word
2831 # will have a different value once the page is saved.
2832 $this->mOutput
->setFlag( 'vary-revision' );
2833 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2835 $value = $pageid ?
$pageid : null;
2838 # Let the edit saving system know we should parse the page
2839 # *after* a revision ID has been assigned.
2840 $this->mOutput
->setFlag( 'vary-revision' );
2841 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2842 $value = $this->mRevisionId
;
2845 # Let the edit saving system know we should parse the page
2846 # *after* a revision ID has been assigned. This is for null edits.
2847 $this->mOutput
->setFlag( 'vary-revision' );
2848 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2849 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2851 case 'revisionday2':
2852 # Let the edit saving system know we should parse the page
2853 # *after* a revision ID has been assigned. This is for null edits.
2854 $this->mOutput
->setFlag( 'vary-revision' );
2855 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2856 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2858 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2863 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2865 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2870 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2872 case 'revisionyear':
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__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2877 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2879 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2884 $value = $this->getRevisionTimestamp();
2886 case 'revisionuser':
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__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2891 $value = $this->getRevisionUser();
2894 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2897 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2899 case 'namespacenumber':
2900 $value = $this->mTitle
->getNamespace();
2903 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2906 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2908 case 'subjectspace':
2909 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2911 case 'subjectspacee':
2912 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2914 case 'currentdayname':
2915 $value = $pageLang->getWeekdayName( MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2918 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2921 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2924 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2927 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2928 # int to remove the padding
2929 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2932 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2934 case 'localdayname':
2935 $value = $pageLang->getWeekdayName( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1 );
2938 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2941 $value = $pageLang->time( MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2944 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
2947 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2948 # int to remove the padding
2949 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
2952 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
2954 case 'numberofarticles':
2955 $value = $pageLang->formatNum( SiteStats
::articles() );
2957 case 'numberoffiles':
2958 $value = $pageLang->formatNum( SiteStats
::images() );
2960 case 'numberofusers':
2961 $value = $pageLang->formatNum( SiteStats
::users() );
2963 case 'numberofactiveusers':
2964 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2966 case 'numberofpages':
2967 $value = $pageLang->formatNum( SiteStats
::pages() );
2969 case 'numberofadmins':
2970 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2972 case 'numberofedits':
2973 $value = $pageLang->formatNum( SiteStats
::edits() );
2975 case 'numberofviews':
2976 global $wgDisableCounters;
2977 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2979 case 'currenttimestamp':
2980 $value = wfTimestamp( TS_MW
, $ts );
2982 case 'localtimestamp':
2983 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
2985 case 'currentversion':
2986 $value = SpecialVersion
::getVersion();
2989 return $wgArticlePath;
2995 $serverParts = wfParseUrl( $wgServer );
2996 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2998 return $wgScriptPath;
3000 return $wgStylePath;
3001 case 'directionmark':
3002 return $pageLang->getDirMark();
3003 case 'contentlanguage':
3004 global $wgLanguageCode;
3005 return $wgLanguageCode;
3008 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
3016 $this->mVarCache
[$index] = $value;
3023 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3027 function initialiseVariables() {
3028 wfProfileIn( __METHOD__
);
3029 $variableIDs = MagicWord
::getVariableIDs();
3030 $substIDs = MagicWord
::getSubstIDs();
3032 $this->mVariables
= new MagicWordArray( $variableIDs );
3033 $this->mSubstWords
= new MagicWordArray( $substIDs );
3034 wfProfileOut( __METHOD__
);
3038 * Preprocess some wikitext and return the document tree.
3039 * This is the ghost of replace_variables().
3041 * @param string $text The text to parse
3042 * @param $flags Integer: bitwise combination of:
3043 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3044 * included. Default is to assume a direct page view.
3046 * The generated DOM tree must depend only on the input text and the flags.
3047 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3049 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3050 * change in the DOM tree for a given text, must be passed through the section identifier
3051 * in the section edit link and thus back to extractSections().
3053 * The output of this function is currently only cached in process memory, but a persistent
3054 * cache may be implemented at a later date which takes further advantage of these strict
3055 * dependency requirements.
3061 function preprocessToDom( $text, $flags = 0 ) {
3062 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3067 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3073 public static function splitWhitespace( $s ) {
3074 $ltrimmed = ltrim( $s );
3075 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3076 $trimmed = rtrim( $ltrimmed );
3077 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3079 $w2 = substr( $ltrimmed, -$diff );
3083 return array( $w1, $trimmed, $w2 );
3087 * Replace magic variables, templates, and template arguments
3088 * with the appropriate text. Templates are substituted recursively,
3089 * taking care to avoid infinite loops.
3091 * Note that the substitution depends on value of $mOutputType:
3092 * self::OT_WIKI: only {{subst:}} templates
3093 * self::OT_PREPROCESS: templates but not extension tags
3094 * self::OT_HTML: all templates and extension tags
3096 * @param string $text the text to transform
3097 * @param $frame PPFrame Object describing the arguments passed to the template.
3098 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3099 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3100 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3105 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3106 # Is there any text? Also, Prevent too big inclusions!
3107 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3110 wfProfileIn( __METHOD__
);
3112 if ( $frame === false ) {
3113 $frame = $this->getPreprocessor()->newFrame();
3114 } elseif ( !( $frame instanceof PPFrame
) ) {
3115 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3116 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3119 $dom = $this->preprocessToDom( $text );
3120 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3121 $text = $frame->expand( $dom, $flags );
3123 wfProfileOut( __METHOD__
);
3128 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3130 * @param $args array
3134 static function createAssocArgs( $args ) {
3135 $assocArgs = array();
3137 foreach ( $args as $arg ) {
3138 $eqpos = strpos( $arg, '=' );
3139 if ( $eqpos === false ) {
3140 $assocArgs[$index++
] = $arg;
3142 $name = trim( substr( $arg, 0, $eqpos ) );
3143 $value = trim( substr( $arg, $eqpos +
1 ) );
3144 if ( $value === false ) {
3147 if ( $name !== false ) {
3148 $assocArgs[$name] = $value;
3157 * Warn the user when a parser limitation is reached
3158 * Will warn at most once the user per limitation type
3160 * @param string $limitationType should be one of:
3161 * 'expensive-parserfunction' (corresponding messages:
3162 * 'expensive-parserfunction-warning',
3163 * 'expensive-parserfunction-category')
3164 * 'post-expand-template-argument' (corresponding messages:
3165 * 'post-expand-template-argument-warning',
3166 * 'post-expand-template-argument-category')
3167 * 'post-expand-template-inclusion' (corresponding messages:
3168 * 'post-expand-template-inclusion-warning',
3169 * 'post-expand-template-inclusion-category')
3170 * 'node-count-exceeded' (corresponding messages:
3171 * 'node-count-exceeded-warning',
3172 * 'node-count-exceeded-category')
3173 * 'expansion-depth-exceeded' (corresponding messages:
3174 * 'expansion-depth-exceeded-warning',
3175 * 'expansion-depth-exceeded-category')
3176 * @param int|null $current Current value
3177 * @param int|null $max Maximum allowed, when an explicit limit has been
3178 * exceeded, provide the values (optional)
3180 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3181 # does no harm if $current and $max are present but are unnecessary for the message
3182 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3183 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3184 $this->mOutput
->addWarning( $warning );
3185 $this->addTrackingCategory( "$limitationType-category" );
3189 * Return the text of a template, after recursively
3190 * replacing any variables or templates within the template.
3192 * @param array $piece the parts of the template
3193 * $piece['title']: the title, i.e. the part before the |
3194 * $piece['parts']: the parameter array
3195 * $piece['lineStart']: whether the brace was at the start of a line
3196 * @param $frame PPFrame The current frame, contains template arguments
3197 * @throws MWException
3198 * @return String: the text of the template
3201 function braceSubstitution( $piece, $frame ) {
3202 wfProfileIn( __METHOD__
);
3203 wfProfileIn( __METHOD__
. '-setup' );
3206 $found = false; # $text has been filled
3207 $nowiki = false; # wiki markup in $text should be escaped
3208 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3209 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3210 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3211 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3213 # Title object, where $text came from
3216 # $part1 is the bit before the first |, and must contain only title characters.
3217 # Various prefixes will be stripped from it later.
3218 $titleWithSpaces = $frame->expand( $piece['title'] );
3219 $part1 = trim( $titleWithSpaces );
3222 # Original title text preserved for various purposes
3223 $originalTitle = $part1;
3225 # $args is a list of argument nodes, starting from index 0, not including $part1
3226 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3227 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3228 wfProfileOut( __METHOD__
. '-setup' );
3230 $titleProfileIn = null; // profile templates
3233 wfProfileIn( __METHOD__
. '-modifiers' );
3236 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3238 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3239 # Decide whether to expand template or keep wikitext as-is.
3240 if ( $this->ot
['wiki'] ) {
3241 if ( $substMatch === false ) {
3242 $literal = true; # literal when in PST with no prefix
3244 $literal = false; # expand when in PST with subst: or safesubst:
3247 if ( $substMatch == 'subst' ) {
3248 $literal = true; # literal when not in PST with plain subst:
3250 $literal = false; # expand when not in PST with safesubst: or no prefix
3254 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3261 if ( !$found && $args->getLength() == 0 ) {
3262 $id = $this->mVariables
->matchStartToEnd( $part1 );
3263 if ( $id !== false ) {
3264 $text = $this->getVariableValue( $id, $frame );
3265 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3266 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3272 # MSG, MSGNW and RAW
3275 $mwMsgnw = MagicWord
::get( 'msgnw' );
3276 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3279 # Remove obsolete MSG:
3280 $mwMsg = MagicWord
::get( 'msg' );
3281 $mwMsg->matchStartAndRemove( $part1 );
3285 $mwRaw = MagicWord
::get( 'raw' );
3286 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3287 $forceRawInterwiki = true;
3290 wfProfileOut( __METHOD__
. '-modifiers' );
3294 wfProfileIn( __METHOD__
. '-pfunc' );
3296 $colonPos = strpos( $part1, ':' );
3297 if ( $colonPos !== false ) {
3298 $func = substr( $part1, 0, $colonPos );
3299 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3300 for ( $i = 0; $i < $args->getLength(); $i++
) {
3301 $funcArgs[] = $args->item( $i );
3304 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3305 } catch ( Exception
$ex ) {
3306 wfProfileOut( __METHOD__
. '-pfunc' );
3307 wfProfileOut( __METHOD__
);
3311 # The interface for parser functions allows for extracting
3312 # flags into the local scope. Extract any forwarded flags
3316 wfProfileOut( __METHOD__
. '-pfunc' );
3319 # Finish mangling title and then check for loops.
3320 # Set $title to a Title object and $titleText to the PDBK
3323 # Split the title into page and subpage
3325 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3326 if ( $part1 !== $relative ) {
3328 $ns = $this->mTitle
->getNamespace();
3330 $title = Title
::newFromText( $part1, $ns );
3332 $titleText = $title->getPrefixedText();
3333 # Check for language variants if the template is not found
3334 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3335 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3337 # Do recursion depth check
3338 $limit = $this->mOptions
->getMaxTemplateDepth();
3339 if ( $frame->depth
>= $limit ) {
3341 $text = '<span class="error">'
3342 . wfMessage( 'parser-template-recursion-depth-warning' )
3343 ->numParams( $limit )->inContentLanguage()->text()
3349 # Load from database
3350 if ( !$found && $title ) {
3351 if ( !Profiler
::instance()->isPersistent() ) {
3352 # Too many unique items can kill profiling DBs/collectors
3353 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3354 wfProfileIn( $titleProfileIn ); // template in
3356 wfProfileIn( __METHOD__
. '-loadtpl' );
3357 if ( !$title->isExternal() ) {
3358 if ( $title->isSpecialPage()
3359 && $this->mOptions
->getAllowSpecialInclusion()
3360 && $this->ot
['html'] )
3362 // Pass the template arguments as URL parameters.
3363 // "uselang" will have no effect since the Language object
3364 // is forced to the one defined in ParserOptions.
3365 $pageArgs = array();
3366 for ( $i = 0; $i < $args->getLength(); $i++
) {
3367 $bits = $args->item( $i )->splitArg();
3368 if ( strval( $bits['index'] ) === '' ) {
3369 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3370 $value = trim( $frame->expand( $bits['value'] ) );
3371 $pageArgs[$name] = $value;
3375 // Create a new context to execute the special page
3376 $context = new RequestContext
;
3377 $context->setTitle( $title );
3378 $context->setRequest( new FauxRequest( $pageArgs ) );
3379 $context->setUser( $this->getUser() );
3380 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3381 $ret = SpecialPageFactory
::capturePath( $title, $context );
3383 $text = $context->getOutput()->getHTML();
3384 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3387 $this->disableCache();
3389 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3390 $found = false; # access denied
3391 wfDebug( __METHOD__
. ": template inclusion denied for " . $title->getPrefixedDBkey() );
3393 list( $text, $title ) = $this->getTemplateDom( $title );
3394 if ( $text !== false ) {
3400 # If the title is valid but undisplayable, make a link to it
3401 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3402 $text = "[[:$titleText]]";
3405 } elseif ( $title->isTrans() ) {
3406 # Interwiki transclusion
3407 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3408 $text = $this->interwikiTransclude( $title, 'render' );
3411 $text = $this->interwikiTransclude( $title, 'raw' );
3412 # Preprocess it like a template
3413 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3419 # Do infinite loop check
3420 # This has to be done after redirect resolution to avoid infinite loops via redirects
3421 if ( !$frame->loopCheck( $title ) ) {
3423 $text = '<span class="error">'
3424 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3426 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3428 wfProfileOut( __METHOD__
. '-loadtpl' );
3431 # If we haven't found text to substitute by now, we're done
3432 # Recover the source wikitext and return it
3434 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3435 if ( $titleProfileIn ) {
3436 wfProfileOut( $titleProfileIn ); // template out
3438 wfProfileOut( __METHOD__
);
3439 return array( 'object' => $text );
3442 # Expand DOM-style return values in a child frame
3443 if ( $isChildObj ) {
3444 # Clean up argument array
3445 $newFrame = $frame->newChild( $args, $title );
3448 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3449 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3450 # Expansion is eligible for the empty-frame cache
3451 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3452 $text = $this->mTplExpandCache
[$titleText];
3454 $text = $newFrame->expand( $text );
3455 $this->mTplExpandCache
[$titleText] = $text;
3458 # Uncached expansion
3459 $text = $newFrame->expand( $text );
3462 if ( $isLocalObj && $nowiki ) {
3463 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3464 $isLocalObj = false;
3467 if ( $titleProfileIn ) {
3468 wfProfileOut( $titleProfileIn ); // template out
3471 # Replace raw HTML by a placeholder
3473 $text = $this->insertStripItem( $text );
3474 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3475 # Escape nowiki-style return values
3476 $text = wfEscapeWikiText( $text );
3477 } elseif ( is_string( $text )
3478 && !$piece['lineStart']
3479 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3481 # Bug 529: if the template begins with a table or block-level
3482 # element, it should be treated as beginning a new line.
3483 # This behavior is somewhat controversial.
3484 $text = "\n" . $text;
3487 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3488 # Error, oversize inclusion
3489 if ( $titleText !== false ) {
3490 # Make a working, properly escaped link if possible (bug 23588)
3491 $text = "[[:$titleText]]";
3493 # This will probably not be a working link, but at least it may
3494 # provide some hint of where the problem is
3495 preg_replace( '/^:/', '', $originalTitle );
3496 $text = "[[:$originalTitle]]";
3498 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3499 $this->limitationWarn( 'post-expand-template-inclusion' );
3502 if ( $isLocalObj ) {
3503 $ret = array( 'object' => $text );
3505 $ret = array( 'text' => $text );
3508 wfProfileOut( __METHOD__
);
3513 * Call a parser function and return an array with text and flags.
3515 * The returned array will always contain a boolean 'found', indicating
3516 * whether the parser function was found or not. It may also contain the
3518 * text: string|object, resulting wikitext or PP DOM object
3519 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3520 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3521 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3522 * nowiki: bool, wiki markup in $text should be escaped
3525 * @param $frame PPFrame The current frame, contains template arguments
3526 * @param $function string Function name
3527 * @param $args array Arguments to the function
3530 public function callParserFunction( $frame, $function, array $args = array() ) {
3533 wfProfileIn( __METHOD__
);
3535 # Case sensitive functions
3536 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3537 $function = $this->mFunctionSynonyms
[1][$function];
3539 # Case insensitive functions
3540 $function = $wgContLang->lc( $function );
3541 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3542 $function = $this->mFunctionSynonyms
[0][$function];
3544 wfProfileOut( __METHOD__
);
3545 return array( 'found' => false );
3549 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3550 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3552 # Workaround for PHP bug 35229 and similar
3553 if ( !is_callable( $callback ) ) {
3554 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3555 wfProfileOut( __METHOD__
);
3556 throw new MWException( "Tag hook for $function is not callable\n" );
3559 $allArgs = array( &$this );
3560 if ( $flags & SFH_OBJECT_ARGS
) {
3561 # Convert arguments to PPNodes and collect for appending to $allArgs
3562 $funcArgs = array();
3563 foreach ( $args as $k => $v ) {
3564 if ( $v instanceof PPNode ||
$k === 0 ) {
3567 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3571 # Add a frame parameter, and pass the arguments as an array
3572 $allArgs[] = $frame;
3573 $allArgs[] = $funcArgs;
3575 # Convert arguments to plain text and append to $allArgs
3576 foreach ( $args as $k => $v ) {
3577 if ( $v instanceof PPNode
) {
3578 $allArgs[] = trim( $frame->expand( $v ) );
3579 } elseif ( is_int( $k ) && $k >= 0 ) {
3580 $allArgs[] = trim( $v );
3582 $allArgs[] = trim( "$k=$v" );
3587 $result = call_user_func_array( $callback, $allArgs );
3589 # The interface for function hooks allows them to return a wikitext
3590 # string or an array containing the string and any flags. This mungs
3591 # things around to match what this method should return.
3592 if ( !is_array( $result ) ) {
3598 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3599 $result['text'] = $result[0];
3601 unset( $result[0] );
3608 $preprocessFlags = 0;
3609 if ( isset( $result['noparse'] ) ) {
3610 $noparse = $result['noparse'];
3612 if ( isset( $result['preprocessFlags'] ) ) {
3613 $preprocessFlags = $result['preprocessFlags'];
3617 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3618 $result['isChildObj'] = true;
3620 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3621 wfProfileOut( __METHOD__
);
3627 * Get the semi-parsed DOM representation of a template with a given title,
3628 * and its redirect destination title. Cached.
3630 * @param $title Title
3634 function getTemplateDom( $title ) {
3635 $cacheTitle = $title;
3636 $titleText = $title->getPrefixedDBkey();
3638 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3639 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3640 $title = Title
::makeTitle( $ns, $dbk );
3641 $titleText = $title->getPrefixedDBkey();
3643 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3644 return array( $this->mTplDomCache
[$titleText], $title );
3647 # Cache miss, go to the database
3648 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3650 if ( $text === false ) {
3651 $this->mTplDomCache
[$titleText] = false;
3652 return array( false, $title );
3655 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3656 $this->mTplDomCache
[$titleText] = $dom;
3658 if ( !$title->equals( $cacheTitle ) ) {
3659 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3660 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3663 return array( $dom, $title );
3667 * Fetch the unparsed text of a template and register a reference to it.
3668 * @param Title $title
3669 * @return Array ( string or false, Title )
3671 function fetchTemplateAndTitle( $title ) {
3672 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3673 $stuff = call_user_func( $templateCb, $title, $this );
3674 $text = $stuff['text'];
3675 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3676 if ( isset( $stuff['deps'] ) ) {
3677 foreach ( $stuff['deps'] as $dep ) {
3678 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3679 if ( $dep['title']->equals( $this->getTitle() ) ) {
3680 // If we transclude ourselves, the final result
3681 // will change based on the new version of the page
3682 $this->mOutput
->setFlag( 'vary-revision' );
3686 return array( $text, $finalTitle );
3690 * Fetch the unparsed text of a template and register a reference to it.
3691 * @param Title $title
3692 * @return mixed string or false
3694 function fetchTemplate( $title ) {
3695 $rv = $this->fetchTemplateAndTitle( $title );
3700 * Static function to get a template
3701 * Can be overridden via ParserOptions::setTemplateCallback().
3703 * @param $title Title
3704 * @param $parser Parser
3708 static function statelessFetchTemplate( $title, $parser = false ) {
3709 $text = $skip = false;
3710 $finalTitle = $title;
3713 # Loop to fetch the article, with up to 1 redirect
3714 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3715 # Give extensions a chance to select the revision instead
3716 $id = false; # Assume current
3717 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3718 array( $parser, $title, &$skip, &$id ) );
3724 'page_id' => $title->getArticleID(),
3731 ? Revision
::newFromId( $id )
3732 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3733 $rev_id = $rev ?
$rev->getId() : 0;
3734 # If there is no current revision, there is no page
3735 if ( $id === false && !$rev ) {
3736 $linkCache = LinkCache
::singleton();
3737 $linkCache->addBadLinkObj( $title );
3742 'page_id' => $title->getArticleID(),
3743 'rev_id' => $rev_id );
3744 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3745 # We fetched a rev from a different title; register it too...
3747 'title' => $rev->getTitle(),
3748 'page_id' => $rev->getPage(),
3749 'rev_id' => $rev_id );
3753 $content = $rev->getContent();
3754 $text = $content ?
$content->getWikitextForTransclusion() : null;
3756 if ( $text === false ||
$text === null ) {
3760 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3762 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3763 if ( !$message->exists() ) {
3767 $content = $message->content();
3768 $text = $message->plain();
3776 $finalTitle = $title;
3777 $title = $content->getRedirectTarget();
3781 'finalTitle' => $finalTitle,
3786 * Fetch a file and its title and register a reference to it.
3787 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3788 * @param Title $title
3789 * @param array $options Array of options to RepoGroup::findFile
3792 function fetchFile( $title, $options = array() ) {
3793 $res = $this->fetchFileAndTitle( $title, $options );
3798 * Fetch a file and its title and register a reference to it.
3799 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3800 * @param Title $title
3801 * @param array $options Array of options to RepoGroup::findFile
3802 * @return Array ( File or false, Title of file )
3804 function fetchFileAndTitle( $title, $options = array() ) {
3805 $file = $this->fetchFileNoRegister( $title, $options );
3807 $time = $file ?
$file->getTimestamp() : false;
3808 $sha1 = $file ?
$file->getSha1() : false;
3809 # Register the file as a dependency...
3810 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3811 if ( $file && !$title->equals( $file->getTitle() ) ) {
3812 # Update fetched file title
3813 $title = $file->getTitle();
3814 if ( is_null( $file->getRedirectedTitle() ) ) {
3815 # This file was not a redirect, but the title does not match.
3816 # Register under the new name because otherwise the link will
3818 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3821 return array( $file, $title );
3825 * Helper function for fetchFileAndTitle.
3827 * Also useful if you need to fetch a file but not use it yet,
3828 * for example to get the file's handler.
3830 * @param Title $title
3831 * @param array $options Array of options to RepoGroup::findFile
3832 * @return File or false
3834 protected function fetchFileNoRegister( $title, $options = array() ) {
3835 if ( isset( $options['broken'] ) ) {
3836 $file = false; // broken thumbnail forced by hook
3837 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3838 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3839 } else { // get by (name,timestamp)
3840 $file = wfFindFile( $title, $options );
3846 * Transclude an interwiki link.
3848 * @param $title Title
3853 function interwikiTransclude( $title, $action ) {
3854 global $wgEnableScaryTranscluding;
3856 if ( !$wgEnableScaryTranscluding ) {
3857 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3860 $url = $title->getFullURL( array( 'action' => $action ) );
3862 if ( strlen( $url ) > 255 ) {
3863 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3865 return $this->fetchScaryTemplateMaybeFromCache( $url );
3869 * @param $url string
3870 * @return Mixed|String
3872 function fetchScaryTemplateMaybeFromCache( $url ) {
3873 global $wgTranscludeCacheExpiry;
3874 $dbr = wfGetDB( DB_SLAVE
);
3875 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3876 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3877 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3879 return $obj->tc_contents
;
3882 $req = MWHttpRequest
::factory( $url );
3883 $status = $req->execute(); // Status object
3884 if ( $status->isOK() ) {
3885 $text = $req->getContent();
3886 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3887 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3889 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3892 $dbw = wfGetDB( DB_MASTER
);
3893 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3895 'tc_time' => $dbw->timestamp( time() ),
3896 'tc_contents' => $text
3902 * Triple brace replacement -- used for template arguments
3905 * @param $piece array
3906 * @param $frame PPFrame
3910 function argSubstitution( $piece, $frame ) {
3911 wfProfileIn( __METHOD__
);
3914 $parts = $piece['parts'];
3915 $nameWithSpaces = $frame->expand( $piece['title'] );
3916 $argName = trim( $nameWithSpaces );
3918 $text = $frame->getArgument( $argName );
3919 if ( $text === false && $parts->getLength() > 0
3923 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3926 # No match in frame, use the supplied default
3927 $object = $parts->item( 0 )->getChildren();
3929 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3930 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3931 $this->limitationWarn( 'post-expand-template-argument' );
3934 if ( $text === false && $object === false ) {
3936 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3938 if ( $error !== false ) {
3941 if ( $object !== false ) {
3942 $ret = array( 'object' => $object );
3944 $ret = array( 'text' => $text );
3947 wfProfileOut( __METHOD__
);
3952 * Return the text to be used for a given extension tag.
3953 * This is the ghost of strip().
3955 * @param array $params Associative array of parameters:
3956 * name PPNode for the tag name
3957 * attr PPNode for unparsed text where tag attributes are thought to be
3958 * attributes Optional associative array of parsed attributes
3959 * inner Contents of extension element
3960 * noClose Original text did not have a close tag
3961 * @param $frame PPFrame
3963 * @throws MWException
3966 function extensionSubstitution( $params, $frame ) {
3967 $name = $frame->expand( $params['name'] );
3968 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3969 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3970 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3972 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
3973 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3974 if ( $isFunctionTag ) {
3975 $markerType = 'none';
3977 $markerType = 'general';
3979 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3980 $name = strtolower( $name );
3981 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3982 if ( isset( $params['attributes'] ) ) {
3983 $attributes = $attributes +
$params['attributes'];
3986 if ( isset( $this->mTagHooks
[$name] ) ) {
3987 # Workaround for PHP bug 35229 and similar
3988 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3989 throw new MWException( "Tag hook for $name is not callable\n" );
3991 $output = call_user_func_array( $this->mTagHooks
[$name],
3992 array( $content, $attributes, $this, $frame ) );
3993 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3994 list( $callback, ) = $this->mFunctionTagHooks
[$name];
3995 if ( !is_callable( $callback ) ) {
3996 throw new MWException( "Tag hook for $name is not callable\n" );
3999 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4001 $output = '<span class="error">Invalid tag extension name: ' .
4002 htmlspecialchars( $name ) . '</span>';
4005 if ( is_array( $output ) ) {
4006 # Extract flags to local scope (to override $markerType)
4008 $output = $flags[0];
4013 if ( is_null( $attrText ) ) {
4016 if ( isset( $params['attributes'] ) ) {
4017 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4018 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4019 htmlspecialchars( $attrValue ) . '"';
4022 if ( $content === null ) {
4023 $output = "<$name$attrText/>";
4025 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4026 $output = "<$name$attrText>$content$close";
4030 if ( $markerType === 'none' ) {
4032 } elseif ( $markerType === 'nowiki' ) {
4033 $this->mStripState
->addNoWiki( $marker, $output );
4034 } elseif ( $markerType === 'general' ) {
4035 $this->mStripState
->addGeneral( $marker, $output );
4037 throw new MWException( __METHOD__
. ': invalid marker type' );
4043 * Increment an include size counter
4045 * @param string $type the type of expansion
4046 * @param $size Integer: the size of the text
4047 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
4049 function incrementIncludeSize( $type, $size ) {
4050 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4053 $this->mIncludeSizes
[$type] +
= $size;
4059 * Increment the expensive function count
4061 * @return Boolean: false if the limit has been exceeded
4063 function incrementExpensiveFunctionCount() {
4064 $this->mExpensiveFunctionCount++
;
4065 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4069 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4070 * Fills $this->mDoubleUnderscores, returns the modified text
4072 * @param $text string
4076 function doDoubleUnderscore( $text ) {
4077 wfProfileIn( __METHOD__
);
4079 # The position of __TOC__ needs to be recorded
4080 $mw = MagicWord
::get( 'toc' );
4081 if ( $mw->match( $text ) ) {
4082 $this->mShowToc
= true;
4083 $this->mForceTocPosition
= true;
4085 # Set a placeholder. At the end we'll fill it in with the TOC.
4086 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4088 # Only keep the first one.
4089 $text = $mw->replace( '', $text );
4092 # Now match and remove the rest of them
4093 $mwa = MagicWord
::getDoubleUnderscoreArray();
4094 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4096 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4097 $this->mOutput
->mNoGallery
= true;
4099 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4100 $this->mShowToc
= false;
4102 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4103 $this->addTrackingCategory( 'hidden-category-category' );
4105 # (bug 8068) Allow control over whether robots index a page.
4107 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4108 # is not desirable, the last one on the page should win.
4109 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4110 $this->mOutput
->setIndexPolicy( 'noindex' );
4111 $this->addTrackingCategory( 'noindex-category' );
4113 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4114 $this->mOutput
->setIndexPolicy( 'index' );
4115 $this->addTrackingCategory( 'index-category' );
4118 # Cache all double underscores in the database
4119 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4120 $this->mOutput
->setProperty( $key, '' );
4123 wfProfileOut( __METHOD__
);
4128 * Add a tracking category, getting the title from a system message,
4129 * or print a debug message if the title is invalid.
4131 * @param string $msg message key
4132 * @return Boolean: whether the addition was successful
4134 public function addTrackingCategory( $msg ) {
4135 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4136 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4139 // Important to parse with correct title (bug 31469)
4140 $cat = wfMessage( $msg )
4141 ->title( $this->getTitle() )
4142 ->inContentLanguage()
4145 # Allow tracking categories to be disabled by setting them to "-"
4146 if ( $cat === '-' ) {
4150 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4151 if ( $containerCategory ) {
4152 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4155 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4161 * This function accomplishes several tasks:
4162 * 1) Auto-number headings if that option is enabled
4163 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4164 * 3) Add a Table of contents on the top for users who have enabled the option
4165 * 4) Auto-anchor headings
4167 * It loops through all headlines, collects the necessary data, then splits up the
4168 * string and re-inserts the newly formatted headlines.
4170 * @param $text String
4171 * @param string $origText original, untouched wikitext
4172 * @param $isMain Boolean
4173 * @return mixed|string
4176 function formatHeadings( $text, $origText, $isMain = true ) {
4177 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4179 # Inhibit editsection links if requested in the page
4180 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4181 $maybeShowEditLink = $showEditLink = false;
4183 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4184 $showEditLink = $this->mOptions
->getEditSection();
4186 if ( $showEditLink ) {
4187 $this->mOutput
->setEditSectionTokens( true );
4190 # Get all headlines for numbering them and adding funky stuff like [edit]
4191 # links - this is for later, but we need the number of headlines right now
4193 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4195 # if there are fewer than 4 headlines in the article, do not show TOC
4196 # unless it's been explicitly enabled.
4197 $enoughToc = $this->mShowToc
&&
4198 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4200 # Allow user to stipulate that a page should have a "new section"
4201 # link added via __NEWSECTIONLINK__
4202 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4203 $this->mOutput
->setNewSection( true );
4206 # Allow user to remove the "new section"
4207 # link via __NONEWSECTIONLINK__
4208 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4209 $this->mOutput
->hideNewSection( true );
4212 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4213 # override above conditions and always show TOC above first header
4214 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4215 $this->mShowToc
= true;
4223 # Ugh .. the TOC should have neat indentation levels which can be
4224 # passed to the skin functions. These are determined here
4228 $sublevelCount = array();
4229 $levelCount = array();
4234 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4235 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4236 $oldType = $this->mOutputType
;
4237 $this->setOutputType( self
::OT_WIKI
);
4238 $frame = $this->getPreprocessor()->newFrame();
4239 $root = $this->preprocessToDom( $origText );
4240 $node = $root->getFirstChild();
4245 foreach ( $matches[3] as $headline ) {
4246 $isTemplate = false;
4248 $sectionIndex = false;
4250 $markerMatches = array();
4251 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4252 $serial = $markerMatches[1];
4253 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4254 $isTemplate = ( $titleText != $baseTitleText );
4255 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4259 $prevlevel = $level;
4261 $level = $matches[1][$headlineCount];
4263 if ( $level > $prevlevel ) {
4264 # Increase TOC level
4266 $sublevelCount[$toclevel] = 0;
4267 if ( $toclevel < $wgMaxTocLevel ) {
4268 $prevtoclevel = $toclevel;
4269 $toc .= Linker
::tocIndent();
4272 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4273 # Decrease TOC level, find level to jump to
4275 for ( $i = $toclevel; $i > 0; $i-- ) {
4276 if ( $levelCount[$i] == $level ) {
4277 # Found last matching level
4280 } elseif ( $levelCount[$i] < $level ) {
4281 # Found first matching level below current level
4289 if ( $toclevel < $wgMaxTocLevel ) {
4290 if ( $prevtoclevel < $wgMaxTocLevel ) {
4291 # Unindent only if the previous toc level was shown :p
4292 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4293 $prevtoclevel = $toclevel;
4295 $toc .= Linker
::tocLineEnd();
4299 # No change in level, end TOC line
4300 if ( $toclevel < $wgMaxTocLevel ) {
4301 $toc .= Linker
::tocLineEnd();
4305 $levelCount[$toclevel] = $level;
4307 # count number of headlines for each level
4308 $sublevelCount[$toclevel]++
;
4310 for ( $i = 1; $i <= $toclevel; $i++
) {
4311 if ( !empty( $sublevelCount[$i] ) ) {
4315 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4320 # The safe header is a version of the header text safe to use for links
4322 # Remove link placeholders by the link text.
4323 # <!--LINK number-->
4325 # link text with suffix
4326 # Do this before unstrip since link text can contain strip markers
4327 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4329 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4330 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4332 # Strip out HTML (first regex removes any tag not allowed)
4334 # * <sup> and <sub> (bug 8393)
4337 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4339 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4340 # to allow setting directionality in toc items.
4341 $tocline = preg_replace(
4342 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4343 array( '', '<$1>' ),
4346 $tocline = trim( $tocline );
4348 # For the anchor, strip out HTML-y stuff period
4349 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4350 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4352 # Save headline for section edit hint before it's escaped
4353 $headlineHint = $safeHeadline;
4355 if ( $wgExperimentalHtmlIds ) {
4356 # For reverse compatibility, provide an id that's
4357 # HTML4-compatible, like we used to.
4359 # It may be worth noting, academically, that it's possible for
4360 # the legacy anchor to conflict with a non-legacy headline
4361 # anchor on the page. In this case likely the "correct" thing
4362 # would be to either drop the legacy anchors or make sure
4363 # they're numbered first. However, this would require people
4364 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4365 # manually, so let's not bother worrying about it.
4366 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4367 array( 'noninitial', 'legacy' ) );
4368 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4370 if ( $legacyHeadline == $safeHeadline ) {
4371 # No reason to have both (in fact, we can't)
4372 $legacyHeadline = false;
4375 $legacyHeadline = false;
4376 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4380 # HTML names must be case-insensitively unique (bug 10721).
4381 # This does not apply to Unicode characters per
4382 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4383 # @todo FIXME: We may be changing them depending on the current locale.
4384 $arrayKey = strtolower( $safeHeadline );
4385 if ( $legacyHeadline === false ) {
4386 $legacyArrayKey = false;
4388 $legacyArrayKey = strtolower( $legacyHeadline );
4391 # count how many in assoc. array so we can track dupes in anchors
4392 if ( isset( $refers[$arrayKey] ) ) {
4393 $refers[$arrayKey]++
;
4395 $refers[$arrayKey] = 1;
4397 if ( isset( $refers[$legacyArrayKey] ) ) {
4398 $refers[$legacyArrayKey]++
;
4400 $refers[$legacyArrayKey] = 1;
4403 # Don't number the heading if it is the only one (looks silly)
4404 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4405 # the two are different if the line contains a link
4406 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4409 # Create the anchor for linking from the TOC to the section
4410 $anchor = $safeHeadline;
4411 $legacyAnchor = $legacyHeadline;
4412 if ( $refers[$arrayKey] > 1 ) {
4413 $anchor .= '_' . $refers[$arrayKey];
4415 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4416 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4418 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4419 $toc .= Linker
::tocLine( $anchor, $tocline,
4420 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4423 # Add the section to the section tree
4424 # Find the DOM node for this header
4425 while ( $node && !$isTemplate ) {
4426 if ( $node->getName() === 'h' ) {
4427 $bits = $node->splitHeading();
4428 if ( $bits['i'] == $sectionIndex ) {
4432 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4433 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4434 $node = $node->getNextSibling();
4437 'toclevel' => $toclevel,
4440 'number' => $numbering,
4441 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4442 'fromtitle' => $titleText,
4443 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4444 'anchor' => $anchor,
4447 # give headline the correct <h#> tag
4448 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4449 // Output edit section links as markers with styles that can be customized by skins
4450 if ( $isTemplate ) {
4451 # Put a T flag in the section identifier, to indicate to extractSections()
4452 # that sections inside <includeonly> should be counted.
4453 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4455 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4457 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4458 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4459 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4460 // so we don't have to worry about a user trying to input one of these markers directly.
4461 // We use a page and section attribute to stop the language converter from converting these important bits
4462 // of data, but put the headline hint inside a content block because the language converter is supposed to
4463 // be able to convert that piece of data.
4464 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4465 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4466 if ( isset( $editlinkArgs[2] ) ) {
4467 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4474 $head[$headlineCount] = Linker
::makeHeadline( $level,
4475 $matches['attrib'][$headlineCount], $anchor, $headline,
4476 $editlink, $legacyAnchor );
4481 $this->setOutputType( $oldType );
4483 # Never ever show TOC if no headers
4484 if ( $numVisible < 1 ) {
4489 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4490 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4492 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4493 $this->mOutput
->setTOCHTML( $toc );
4497 $this->mOutput
->setSections( $tocraw );
4500 # split up and insert constructed headlines
4501 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4504 // build an array of document sections
4505 $sections = array();
4506 foreach ( $blocks as $block ) {
4507 // $head is zero-based, sections aren't.
4508 if ( empty( $head[$i - 1] ) ) {
4509 $sections[$i] = $block;
4511 $sections[$i] = $head[$i - 1] . $block;
4515 * Send a hook, one per section.
4516 * The idea here is to be able to make section-level DIVs, but to do so in a
4517 * lower-impact, more correct way than r50769
4520 * $section : the section number
4521 * &$sectionContent : ref to the content of the section
4522 * $showEditLinks : boolean describing whether this section has an edit link
4524 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4529 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4530 // append the TOC at the beginning
4531 // Top anchor now in skin
4532 $sections[0] = $sections[0] . $toc . "\n";
4535 $full .= join( '', $sections );
4537 if ( $this->mForceTocPosition
) {
4538 return str_replace( '<!--MWTOC-->', $toc, $full );
4545 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4546 * conversion, substitting signatures, {{subst:}} templates, etc.
4548 * @param string $text the text to transform
4549 * @param $title Title: the Title object for the current article
4550 * @param $user User: the User object describing the current user
4551 * @param $options ParserOptions: parsing options
4552 * @param $clearState Boolean: whether to clear the parser state first
4553 * @return String: the altered wiki markup
4555 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4556 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4557 $this->setUser( $user );
4562 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4563 if ( $options->getPreSaveTransform() ) {
4564 $text = $this->pstPass2( $text, $user );
4566 $text = $this->mStripState
->unstripBoth( $text );
4568 $this->setUser( null ); #Reset
4574 * Pre-save transform helper function
4577 * @param $text string
4582 function pstPass2( $text, $user ) {
4585 # Note: This is the timestamp saved as hardcoded wikitext to
4586 # the database, we use $wgContLang here in order to give
4587 # everyone the same signature and use the default one rather
4588 # than the one selected in each user's preferences.
4589 # (see also bug 12815)
4590 $ts = $this->mOptions
->getTimestamp();
4591 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4592 $ts = $timestamp->format( 'YmdHis' );
4593 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4595 # Allow translation of timezones through wiki. format() can return
4596 # whatever crap the system uses, localised or not, so we cannot
4597 # ship premade translations.
4598 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4599 $msg = wfMessage( $key )->inContentLanguage();
4600 if ( $msg->exists() ) {
4601 $tzMsg = $msg->text();
4604 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4606 # Variable replacement
4607 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4608 $text = $this->replaceVariables( $text );
4610 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4611 # which may corrupt this parser instance via its wfMessage()->text() call-
4614 $sigText = $this->getUserSig( $user );
4615 $text = strtr( $text, array(
4617 '~~~~' => "$sigText $d",
4621 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4622 $tc = '[' . Title
::legalChars() . ']';
4623 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4625 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4626 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4627 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4628 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4630 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4631 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4632 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4633 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4635 $t = $this->mTitle
->getText();
4637 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4638 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4639 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4640 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4642 # if there's no context, don't bother duplicating the title
4643 $text = preg_replace( $p2, '[[\\1]]', $text );
4646 # Trim trailing whitespace
4647 $text = rtrim( $text );
4653 * Fetch the user's signature text, if any, and normalize to
4654 * validated, ready-to-insert wikitext.
4655 * If you have pre-fetched the nickname or the fancySig option, you can
4656 * specify them here to save a database query.
4657 * Do not reuse this parser instance after calling getUserSig(),
4658 * as it may have changed if it's the $wgParser.
4661 * @param string|bool $nickname nickname to use or false to use user's default nickname
4662 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4663 * or null to use default value
4666 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4667 global $wgMaxSigChars;
4669 $username = $user->getName();
4671 # If not given, retrieve from the user object.
4672 if ( $nickname === false ) {
4673 $nickname = $user->getOption( 'nickname' );
4676 if ( is_null( $fancySig ) ) {
4677 $fancySig = $user->getBoolOption( 'fancysig' );
4680 $nickname = $nickname == null ?
$username : $nickname;
4682 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4683 $nickname = $username;
4684 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4685 } elseif ( $fancySig !== false ) {
4686 # Sig. might contain markup; validate this
4687 if ( $this->validateSig( $nickname ) !== false ) {
4688 # Validated; clean up (if needed) and return it
4689 return $this->cleanSig( $nickname, true );
4691 # Failed to validate; fall back to the default
4692 $nickname = $username;
4693 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4697 # Make sure nickname doesnt get a sig in a sig
4698 $nickname = self
::cleanSigInSig( $nickname );
4700 # If we're still here, make it a link to the user page
4701 $userText = wfEscapeWikiText( $username );
4702 $nickText = wfEscapeWikiText( $nickname );
4703 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4705 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4709 * Check that the user's signature contains no bad XML
4711 * @param $text String
4712 * @return mixed An expanded string, or false if invalid.
4714 function validateSig( $text ) {
4715 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4719 * Clean up signature text
4721 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4722 * 2) Substitute all transclusions
4724 * @param $text String
4725 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4726 * @return String: signature text
4728 public function cleanSig( $text, $parsing = false ) {
4731 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4734 # Option to disable this feature
4735 if ( !$this->mOptions
->getCleanSignatures() ) {
4739 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4740 # => Move this logic to braceSubstitution()
4741 $substWord = MagicWord
::get( 'subst' );
4742 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4743 $substText = '{{' . $substWord->getSynonym( 0 );
4745 $text = preg_replace( $substRegex, $substText, $text );
4746 $text = self
::cleanSigInSig( $text );
4747 $dom = $this->preprocessToDom( $text );
4748 $frame = $this->getPreprocessor()->newFrame();
4749 $text = $frame->expand( $dom );
4752 $text = $this->mStripState
->unstripBoth( $text );
4759 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4761 * @param $text String
4762 * @return String: signature text with /~{3,5}/ removed
4764 public static function cleanSigInSig( $text ) {
4765 $text = preg_replace( '/~{3,5}/', '', $text );
4770 * Set up some variables which are usually set up in parse()
4771 * so that an external function can call some class members with confidence
4773 * @param $title Title|null
4774 * @param $options ParserOptions
4775 * @param $outputType
4776 * @param $clearState bool
4778 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4779 $this->startParse( $title, $options, $outputType, $clearState );
4783 * @param $title Title|null
4784 * @param $options ParserOptions
4785 * @param $outputType
4786 * @param $clearState bool
4788 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4789 $this->setTitle( $title );
4790 $this->mOptions
= $options;
4791 $this->setOutputType( $outputType );
4792 if ( $clearState ) {
4793 $this->clearState();
4798 * Wrapper for preprocess()
4800 * @param string $text the text to preprocess
4801 * @param $options ParserOptions: options
4802 * @param $title Title object or null to use $wgTitle
4805 public function transformMsg( $text, $options, $title = null ) {
4806 static $executing = false;
4808 # Guard against infinite recursion
4814 wfProfileIn( __METHOD__
);
4820 $text = $this->preprocess( $text, $title, $options );
4823 wfProfileOut( __METHOD__
);
4828 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4829 * The callback should have the following form:
4830 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4832 * Transform and return $text. Use $parser for any required context, e.g. use
4833 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4835 * Hooks may return extended information by returning an array, of which the
4836 * first numbered element (index 0) must be the return string, and all other
4837 * entries are extracted into local variables within an internal function
4838 * in the Parser class.
4840 * This interface (introduced r61913) appears to be undocumented, but
4841 * 'markerName' is used by some core tag hooks to override which strip
4842 * array their results are placed in. **Use great caution if attempting
4843 * this interface, as it is not documented and injudicious use could smash
4844 * private variables.**
4846 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4847 * @param $callback Mixed: the callback function (and object) to use for the tag
4848 * @throws MWException
4849 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4851 public function setHook( $tag, $callback ) {
4852 $tag = strtolower( $tag );
4853 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4854 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4856 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4857 $this->mTagHooks
[$tag] = $callback;
4858 if ( !in_array( $tag, $this->mStripList
) ) {
4859 $this->mStripList
[] = $tag;
4866 * As setHook(), but letting the contents be parsed.
4868 * Transparent tag hooks are like regular XML-style tag hooks, except they
4869 * operate late in the transformation sequence, on HTML instead of wikitext.
4871 * This is probably obsoleted by things dealing with parser frames?
4872 * The only extension currently using it is geoserver.
4875 * @todo better document or deprecate this
4877 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4878 * @param $callback Mixed: the callback function (and object) to use for the tag
4879 * @throws MWException
4880 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4882 function setTransparentTagHook( $tag, $callback ) {
4883 $tag = strtolower( $tag );
4884 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4885 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4887 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4888 $this->mTransparentTagHooks
[$tag] = $callback;
4894 * Remove all tag hooks
4896 function clearTagHooks() {
4897 $this->mTagHooks
= array();
4898 $this->mFunctionTagHooks
= array();
4899 $this->mStripList
= $this->mDefaultStripList
;
4903 * Create a function, e.g. {{sum:1|2|3}}
4904 * The callback function should have the form:
4905 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4907 * Or with SFH_OBJECT_ARGS:
4908 * function myParserFunction( $parser, $frame, $args ) { ... }
4910 * The callback may either return the text result of the function, or an array with the text
4911 * in element 0, and a number of flags in the other elements. The names of the flags are
4912 * specified in the keys. Valid flags are:
4913 * found The text returned is valid, stop processing the template. This
4915 * nowiki Wiki markup in the return value should be escaped
4916 * isHTML The returned text is HTML, armour it against wikitext transformation
4918 * @param string $id The magic word ID
4919 * @param $callback Mixed: the callback function (and object) to use
4920 * @param $flags Integer: a combination of the following flags:
4921 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4923 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4924 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4925 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4926 * the arguments, and to control the way they are expanded.
4928 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4929 * arguments, for instance:
4930 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4932 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4933 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4934 * working if/when this is changed.
4936 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4939 * Please read the documentation in includes/parser/Preprocessor.php for more information
4940 * about the methods available in PPFrame and PPNode.
4942 * @throws MWException
4943 * @return string|callback The old callback function for this name, if any
4945 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4948 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4949 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4951 # Add to function cache
4952 $mw = MagicWord
::get( $id );
4954 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
4957 $synonyms = $mw->getSynonyms();
4958 $sensitive = intval( $mw->isCaseSensitive() );
4960 foreach ( $synonyms as $syn ) {
4962 if ( !$sensitive ) {
4963 $syn = $wgContLang->lc( $syn );
4966 if ( !( $flags & SFH_NO_HASH
) ) {
4969 # Remove trailing colon
4970 if ( substr( $syn, -1, 1 ) === ':' ) {
4971 $syn = substr( $syn, 0, -1 );
4973 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4979 * Get all registered function hook identifiers
4983 function getFunctionHooks() {
4984 return array_keys( $this->mFunctionHooks
);
4988 * Create a tag function, e.g. "<test>some stuff</test>".
4989 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4990 * Unlike parser functions, their content is not preprocessed.
4994 * @throws MWException
4997 function setFunctionTagHook( $tag, $callback, $flags ) {
4998 $tag = strtolower( $tag );
4999 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5000 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5002 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5003 $this->mFunctionTagHooks
[$tag] : null;
5004 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5006 if ( !in_array( $tag, $this->mStripList
) ) {
5007 $this->mStripList
[] = $tag;
5014 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5015 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5016 * Placeholders created in Skin::makeLinkObj()
5018 * @param $text string
5019 * @param $options int
5021 * @return array of link CSS classes, indexed by PDBK.
5023 function replaceLinkHolders( &$text, $options = 0 ) {
5024 return $this->mLinkHolders
->replace( $text );
5028 * Replace "<!--LINK-->" link placeholders with plain text of links
5029 * (not HTML-formatted).
5031 * @param $text String
5034 function replaceLinkHoldersText( $text ) {
5035 return $this->mLinkHolders
->replaceText( $text );
5039 * Renders an image gallery from a text with one line per image.
5040 * text labels may be given by using |-style alternative text. E.g.
5041 * Image:one.jpg|The number "1"
5042 * Image:tree.jpg|A tree
5043 * given as text will return the HTML of a gallery with two images,
5044 * labeled 'The number "1"' and
5047 * @param string $text
5048 * @param array $params
5049 * @return string HTML
5051 function renderImageGallery( $text, $params ) {
5052 wfProfileIn( __METHOD__
);
5055 if ( isset( $params['mode'] ) ) {
5056 $mode = $params['mode'];
5060 $ig = ImageGalleryBase
::factory( $mode );
5061 } catch ( MWException
$e ) {
5062 // If invalid type set, fallback to default.
5063 $ig = ImageGalleryBase
::factory( false );
5066 $ig->setContextTitle( $this->mTitle
);
5067 $ig->setShowBytes( false );
5068 $ig->setShowFilename( false );
5069 $ig->setParser( $this );
5070 $ig->setHideBadImages();
5071 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5073 if ( isset( $params['showfilename'] ) ) {
5074 $ig->setShowFilename( true );
5076 $ig->setShowFilename( false );
5078 if ( isset( $params['caption'] ) ) {
5079 $caption = $params['caption'];
5080 $caption = htmlspecialchars( $caption );
5081 $caption = $this->replaceInternalLinks( $caption );
5082 $ig->setCaptionHtml( $caption );
5084 if ( isset( $params['perrow'] ) ) {
5085 $ig->setPerRow( $params['perrow'] );
5087 if ( isset( $params['widths'] ) ) {
5088 $ig->setWidths( $params['widths'] );
5090 if ( isset( $params['heights'] ) ) {
5091 $ig->setHeights( $params['heights'] );
5093 $ig->setAdditionalOptions( $params );
5095 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5097 $lines = StringUtils
::explode( "\n", $text );
5098 foreach ( $lines as $line ) {
5099 # match lines like these:
5100 # Image:someimage.jpg|This is some image
5102 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5104 if ( count( $matches ) == 0 ) {
5108 if ( strpos( $matches[0], '%' ) !== false ) {
5109 $matches[1] = rawurldecode( $matches[1] );
5111 $title = Title
::newFromText( $matches[1], NS_FILE
);
5112 if ( is_null( $title ) ) {
5113 # Bogus title. Ignore these so we don't bomb out later.
5117 # We need to get what handler the file uses, to figure out parameters.
5118 # Note, a hook can overide the file name, and chose an entirely different
5119 # file (which potentially could be of a different type and have different handler).
5122 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5123 array( $this, $title, &$options, &$descQuery ) );
5124 # Don't register it now, as ImageGallery does that later.
5125 $file = $this->fetchFileNoRegister( $title, $options );
5126 $handler = $file ?
$file->getHandler() : false;
5128 wfProfileIn( __METHOD__
. '-getMagicWord' );
5130 'img_alt' => 'gallery-internal-alt',
5131 'img_link' => 'gallery-internal-link',
5134 $paramMap = $paramMap +
$handler->getParamMap();
5135 // We don't want people to specify per-image widths.
5136 // Additionally the width parameter would need special casing anyhow.
5137 unset( $paramMap['img_width'] );
5140 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5141 wfProfileOut( __METHOD__
. '-getMagicWord' );
5146 $handlerOptions = array();
5147 if ( isset( $matches[3] ) ) {
5148 // look for an |alt= definition while trying not to break existing
5149 // captions with multiple pipes (|) in it, until a more sensible grammar
5150 // is defined for images in galleries
5152 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5153 // splitting on '|' is a bit odd, and different from makeImage.
5154 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5155 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5157 foreach ( $parameterMatches as $parameterMatch ) {
5158 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5160 $paramName = $paramMap[$magicName];
5162 switch ( $paramName ) {
5163 case 'gallery-internal-alt':
5164 $alt = $this->stripAltText( $match, false );
5166 case 'gallery-internal-link':
5167 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5168 $chars = self
::EXT_LINK_URL_CLASS
;
5169 $prots = $this->mUrlProtocols
;
5170 //check to see if link matches an absolute url, if not then it must be a wiki link.
5171 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5174 $localLinkTitle = Title
::newFromText( $linkValue );
5175 if ( $localLinkTitle !== null ) {
5176 $link = $localLinkTitle->getLocalURL();
5181 // Must be a handler specific parameter.
5182 if ( $handler->validateParam( $paramName, $match ) ) {
5183 $handlerOptions[$paramName] = $match;
5185 // Guess not. Append it to the caption.
5186 wfDebug( "$parameterMatch failed parameter validation" );
5187 $label .= '|' . $parameterMatch;
5192 // concatenate all other pipes
5193 $label .= '|' . $parameterMatch;
5196 // remove the first pipe
5197 $label = substr( $label, 1 );
5200 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5202 $html = $ig->toHTML();
5203 wfProfileOut( __METHOD__
);
5211 function getImageParams( $handler ) {
5213 $handlerClass = get_class( $handler );
5217 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5218 # Initialise static lists
5219 static $internalParamNames = array(
5220 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5221 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5222 'bottom', 'text-bottom' ),
5223 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5224 'upright', 'border', 'link', 'alt', 'class' ),
5226 static $internalParamMap;
5227 if ( !$internalParamMap ) {
5228 $internalParamMap = array();
5229 foreach ( $internalParamNames as $type => $names ) {
5230 foreach ( $names as $name ) {
5231 $magicName = str_replace( '-', '_', "img_$name" );
5232 $internalParamMap[$magicName] = array( $type, $name );
5237 # Add handler params
5238 $paramMap = $internalParamMap;
5240 $handlerParamMap = $handler->getParamMap();
5241 foreach ( $handlerParamMap as $magic => $paramName ) {
5242 $paramMap[$magic] = array( 'handler', $paramName );
5245 $this->mImageParams
[$handlerClass] = $paramMap;
5246 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5248 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5252 * Parse image options text and use it to make an image
5254 * @param $title Title
5255 * @param $options String
5256 * @param $holders LinkHolderArray|bool
5257 * @return string HTML
5259 function makeImage( $title, $options, $holders = false ) {
5260 # Check if the options text is of the form "options|alt text"
5262 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5263 # * left no resizing, just left align. label is used for alt= only
5264 # * right same, but right aligned
5265 # * none same, but not aligned
5266 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5267 # * center center the image
5268 # * frame Keep original image size, no magnify-button.
5269 # * framed Same as "frame"
5270 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5271 # * upright reduce width for upright images, rounded to full __0 px
5272 # * border draw a 1px border around the image
5273 # * alt Text for HTML alt attribute (defaults to empty)
5274 # * class Set a class for img node
5275 # * link Set the target of the image link. Can be external, interwiki, or local
5276 # vertical-align values (no % or length right now):
5286 $parts = StringUtils
::explode( "|", $options );
5288 # Give extensions a chance to select the file revision for us
5291 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5292 array( $this, $title, &$options, &$descQuery ) );
5293 # Fetch and register the file (file title may be different via hooks)
5294 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5297 $handler = $file ?
$file->getHandler() : false;
5299 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5302 $this->addTrackingCategory( 'broken-file-category' );
5305 # Process the input parameters
5307 $params = array( 'frame' => array(), 'handler' => array(),
5308 'horizAlign' => array(), 'vertAlign' => array() );
5309 foreach ( $parts as $part ) {
5310 $part = trim( $part );
5311 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5313 if ( isset( $paramMap[$magicName] ) ) {
5314 list( $type, $paramName ) = $paramMap[$magicName];
5316 # Special case; width and height come in one variable together
5317 if ( $type === 'handler' && $paramName === 'width' ) {
5318 $parsedWidthParam = $this->parseWidthParam( $value );
5319 if ( isset( $parsedWidthParam['width'] ) ) {
5320 $width = $parsedWidthParam['width'];
5321 if ( $handler->validateParam( 'width', $width ) ) {
5322 $params[$type]['width'] = $width;
5326 if ( isset( $parsedWidthParam['height'] ) ) {
5327 $height = $parsedWidthParam['height'];
5328 if ( $handler->validateParam( 'height', $height ) ) {
5329 $params[$type]['height'] = $height;
5333 # else no validation -- bug 13436
5335 if ( $type === 'handler' ) {
5336 # Validate handler parameter
5337 $validated = $handler->validateParam( $paramName, $value );
5339 # Validate internal parameters
5340 switch ( $paramName ) {
5344 # @todo FIXME: Possibly check validity here for
5345 # manualthumb? downstream behavior seems odd with
5346 # missing manual thumbs.
5348 $value = $this->stripAltText( $value, $holders );
5351 $chars = self
::EXT_LINK_URL_CLASS
;
5352 $prots = $this->mUrlProtocols
;
5353 if ( $value === '' ) {
5354 $paramName = 'no-link';
5357 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5358 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5359 $paramName = 'link-url';
5360 $this->mOutput
->addExternalLink( $value );
5361 if ( $this->mOptions
->getExternalLinkTarget() ) {
5362 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5367 $linkTitle = Title
::newFromText( $value );
5369 $paramName = 'link-title';
5370 $value = $linkTitle;
5371 $this->mOutput
->addLink( $linkTitle );
5377 # Most other things appear to be empty or numeric...
5378 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5383 $params[$type][$paramName] = $value;
5387 if ( !$validated ) {
5392 # Process alignment parameters
5393 if ( $params['horizAlign'] ) {
5394 $params['frame']['align'] = key( $params['horizAlign'] );
5396 if ( $params['vertAlign'] ) {
5397 $params['frame']['valign'] = key( $params['vertAlign'] );
5400 $params['frame']['caption'] = $caption;
5402 # Will the image be presented in a frame, with the caption below?
5403 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5404 isset( $params['frame']['framed'] ) ||
5405 isset( $params['frame']['thumbnail'] ) ||
5406 isset( $params['frame']['manualthumb'] );
5408 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5409 # came to also set the caption, ordinary text after the image -- which
5410 # makes no sense, because that just repeats the text multiple times in
5411 # screen readers. It *also* came to set the title attribute.
5413 # Now that we have an alt attribute, we should not set the alt text to
5414 # equal the caption: that's worse than useless, it just repeats the
5415 # text. This is the framed/thumbnail case. If there's no caption, we
5416 # use the unnamed parameter for alt text as well, just for the time be-
5417 # ing, if the unnamed param is set and the alt param is not.
5419 # For the future, we need to figure out if we want to tweak this more,
5420 # e.g., introducing a title= parameter for the title; ignoring the un-
5421 # named parameter entirely for images without a caption; adding an ex-
5422 # plicit caption= parameter and preserving the old magic unnamed para-
5424 if ( $imageIsFramed ) { # Framed image
5425 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5426 # No caption or alt text, add the filename as the alt text so
5427 # that screen readers at least get some description of the image
5428 $params['frame']['alt'] = $title->getText();
5430 # Do not set $params['frame']['title'] because tooltips don't make sense
5432 } else { # Inline image
5433 if ( !isset( $params['frame']['alt'] ) ) {
5434 # No alt text, use the "caption" for the alt text
5435 if ( $caption !== '' ) {
5436 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5438 # No caption, fall back to using the filename for the
5440 $params['frame']['alt'] = $title->getText();
5443 # Use the "caption" for the tooltip text
5444 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5447 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5449 # Linker does the rest
5450 $time = isset( $options['time'] ) ?
$options['time'] : false;
5451 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5452 $time, $descQuery, $this->mOptions
->getThumbSize() );
5454 # Give the handler a chance to modify the parser object
5456 $handler->parserTransformHook( $this, $file );
5464 * @param $holders LinkHolderArray
5465 * @return mixed|String
5467 protected function stripAltText( $caption, $holders ) {
5468 # Strip bad stuff out of the title (tooltip). We can't just use
5469 # replaceLinkHoldersText() here, because if this function is called
5470 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5472 $tooltip = $holders->replaceText( $caption );
5474 $tooltip = $this->replaceLinkHoldersText( $caption );
5477 # make sure there are no placeholders in thumbnail attributes
5478 # that are later expanded to html- so expand them now and
5480 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5481 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5487 * Set a flag in the output object indicating that the content is dynamic and
5488 * shouldn't be cached.
5490 function disableCache() {
5491 wfDebug( "Parser output marked as uncacheable.\n" );
5492 if ( !$this->mOutput
) {
5493 throw new MWException( __METHOD__
.
5494 " can only be called when actually parsing something" );
5496 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5497 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5501 * Callback from the Sanitizer for expanding items found in HTML attribute
5502 * values, so they can be safely tested and escaped.
5504 * @param $text String
5505 * @param $frame PPFrame
5508 function attributeStripCallback( &$text, $frame = false ) {
5509 $text = $this->replaceVariables( $text, $frame );
5510 $text = $this->mStripState
->unstripBoth( $text );
5519 function getTags() {
5520 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5524 * Replace transparent tags in $text with the values given by the callbacks.
5526 * Transparent tag hooks are like regular XML-style tag hooks, except they
5527 * operate late in the transformation sequence, on HTML instead of wikitext.
5529 * @param $text string
5533 function replaceTransparentTags( $text ) {
5535 $elements = array_keys( $this->mTransparentTagHooks
);
5536 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5537 $replacements = array();
5539 foreach ( $matches as $marker => $data ) {
5540 list( $element, $content, $params, $tag ) = $data;
5541 $tagName = strtolower( $element );
5542 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5543 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5547 $replacements[$marker] = $output;
5549 return strtr( $text, $replacements );
5553 * Break wikitext input into sections, and either pull or replace
5554 * some particular section's text.
5556 * External callers should use the getSection and replaceSection methods.
5558 * @param string $text Page wikitext
5559 * @param string $section a section identifier string of the form:
5560 * "<flag1> - <flag2> - ... - <section number>"
5562 * Currently the only recognised flag is "T", which means the target section number
5563 * was derived during a template inclusion parse, in other words this is a template
5564 * section edit link. If no flags are given, it was an ordinary section edit link.
5565 * This flag is required to avoid a section numbering mismatch when a section is
5566 * enclosed by "<includeonly>" (bug 6563).
5568 * The section number 0 pulls the text before the first heading; other numbers will
5569 * pull the given section along with its lower-level subsections. If the section is
5570 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5572 * Section 0 is always considered to exist, even if it only contains the empty
5573 * string. If $text is the empty string and section 0 is replaced, $newText is
5576 * @param string $mode one of "get" or "replace"
5577 * @param string $newText replacement text for section data.
5578 * @return String: for "get", the extracted section text.
5579 * for "replace", the whole page with the section replaced.
5581 private function extractSections( $text, $section, $mode, $newText = '' ) {
5582 global $wgTitle; # not generally used but removes an ugly failure mode
5583 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5585 $frame = $this->getPreprocessor()->newFrame();
5587 # Process section extraction flags
5589 $sectionParts = explode( '-', $section );
5590 $sectionIndex = array_pop( $sectionParts );
5591 foreach ( $sectionParts as $part ) {
5592 if ( $part === 'T' ) {
5593 $flags |
= self
::PTD_FOR_INCLUSION
;
5597 # Check for empty input
5598 if ( strval( $text ) === '' ) {
5599 # Only sections 0 and T-0 exist in an empty document
5600 if ( $sectionIndex == 0 ) {
5601 if ( $mode === 'get' ) {
5607 if ( $mode === 'get' ) {
5615 # Preprocess the text
5616 $root = $this->preprocessToDom( $text, $flags );
5618 # <h> nodes indicate section breaks
5619 # They can only occur at the top level, so we can find them by iterating the root's children
5620 $node = $root->getFirstChild();
5622 # Find the target section
5623 if ( $sectionIndex == 0 ) {
5624 # Section zero doesn't nest, level=big
5625 $targetLevel = 1000;
5628 if ( $node->getName() === 'h' ) {
5629 $bits = $node->splitHeading();
5630 if ( $bits['i'] == $sectionIndex ) {
5631 $targetLevel = $bits['level'];
5635 if ( $mode === 'replace' ) {
5636 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5638 $node = $node->getNextSibling();
5644 if ( $mode === 'get' ) {
5651 # Find the end of the section, including nested sections
5653 if ( $node->getName() === 'h' ) {
5654 $bits = $node->splitHeading();
5655 $curLevel = $bits['level'];
5656 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5660 if ( $mode === 'get' ) {
5661 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5663 $node = $node->getNextSibling();
5666 # Write out the remainder (in replace mode only)
5667 if ( $mode === 'replace' ) {
5668 # Output the replacement text
5669 # Add two newlines on -- trailing whitespace in $newText is conventionally
5670 # stripped by the editor, so we need both newlines to restore the paragraph gap
5671 # Only add trailing whitespace if there is newText
5672 if ( $newText != "" ) {
5673 $outText .= $newText . "\n\n";
5677 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5678 $node = $node->getNextSibling();
5682 if ( is_string( $outText ) ) {
5683 # Re-insert stripped tags
5684 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5691 * This function returns the text of a section, specified by a number ($section).
5692 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5693 * the first section before any such heading (section 0).
5695 * If a section contains subsections, these are also returned.
5697 * @param string $text text to look in
5698 * @param string $section section identifier
5699 * @param string $deftext default to return if section is not found
5700 * @return string text of the requested section
5702 public function getSection( $text, $section, $deftext = '' ) {
5703 return $this->extractSections( $text, $section, "get", $deftext );
5707 * This function returns $oldtext after the content of the section
5708 * specified by $section has been replaced with $text. If the target
5709 * section does not exist, $oldtext is returned unchanged.
5711 * @param string $oldtext former text of the article
5712 * @param int $section section identifier
5713 * @param string $text replacing text
5714 * @return String: modified text
5716 public function replaceSection( $oldtext, $section, $text ) {
5717 return $this->extractSections( $oldtext, $section, "replace", $text );
5721 * Get the ID of the revision we are parsing
5723 * @return Mixed: integer or null
5725 function getRevisionId() {
5726 return $this->mRevisionId
;
5730 * Get the revision object for $this->mRevisionId
5732 * @return Revision|null either a Revision object or null
5734 protected function getRevisionObject() {
5735 if ( !is_null( $this->mRevisionObject
) ) {
5736 return $this->mRevisionObject
;
5738 if ( is_null( $this->mRevisionId
) ) {
5742 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5743 return $this->mRevisionObject
;
5747 * Get the timestamp associated with the current revision, adjusted for
5748 * the default server-local timestamp
5750 function getRevisionTimestamp() {
5751 if ( is_null( $this->mRevisionTimestamp
) ) {
5752 wfProfileIn( __METHOD__
);
5756 $revObject = $this->getRevisionObject();
5757 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5759 # The cryptic '' timezone parameter tells to use the site-default
5760 # timezone offset instead of the user settings.
5762 # Since this value will be saved into the parser cache, served
5763 # to other users, and potentially even used inside links and such,
5764 # it needs to be consistent for all visitors.
5765 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5767 wfProfileOut( __METHOD__
);
5769 return $this->mRevisionTimestamp
;
5773 * Get the name of the user that edited the last revision
5775 * @return String: user name
5777 function getRevisionUser() {
5778 if ( is_null( $this->mRevisionUser
) ) {
5779 $revObject = $this->getRevisionObject();
5781 # if this template is subst: the revision id will be blank,
5782 # so just use the current user's name
5784 $this->mRevisionUser
= $revObject->getUserText();
5785 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5786 $this->mRevisionUser
= $this->getUser()->getName();
5789 return $this->mRevisionUser
;
5793 * Mutator for $mDefaultSort
5795 * @param string $sort New value
5797 public function setDefaultSort( $sort ) {
5798 $this->mDefaultSort
= $sort;
5799 $this->mOutput
->setProperty( 'defaultsort', $sort );
5803 * Accessor for $mDefaultSort
5804 * Will use the empty string if none is set.
5806 * This value is treated as a prefix, so the
5807 * empty string is equivalent to sorting by
5812 public function getDefaultSort() {
5813 if ( $this->mDefaultSort
!== false ) {
5814 return $this->mDefaultSort
;
5821 * Accessor for $mDefaultSort
5822 * Unlike getDefaultSort(), will return false if none is set
5824 * @return string or false
5826 public function getCustomDefaultSort() {
5827 return $this->mDefaultSort
;
5831 * Try to guess the section anchor name based on a wikitext fragment
5832 * presumably extracted from a heading, for example "Header" from
5835 * @param $text string
5839 public function guessSectionNameFromWikiText( $text ) {
5840 # Strip out wikitext links(they break the anchor)
5841 $text = $this->stripSectionName( $text );
5842 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5843 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5847 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5848 * instead. For use in redirects, since IE6 interprets Redirect: headers
5849 * as something other than UTF-8 (apparently?), resulting in breakage.
5851 * @param string $text The section name
5852 * @return string An anchor
5854 public function guessLegacySectionNameFromWikiText( $text ) {
5855 # Strip out wikitext links(they break the anchor)
5856 $text = $this->stripSectionName( $text );
5857 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5858 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5862 * Strips a text string of wikitext for use in a section anchor
5864 * Accepts a text string and then removes all wikitext from the
5865 * string and leaves only the resultant text (i.e. the result of
5866 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5867 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5868 * to create valid section anchors by mimicing the output of the
5869 * parser when headings are parsed.
5871 * @param string $text text string to be stripped of wikitext
5872 * for use in a Section anchor
5873 * @return string Filtered text string
5875 public function stripSectionName( $text ) {
5876 # Strip internal link markup
5877 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5878 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5880 # Strip external link markup
5881 # @todo FIXME: Not tolerant to blank link text
5882 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5883 # on how many empty links there are on the page - need to figure that out.
5884 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5886 # Parse wikitext quotes (italics & bold)
5887 $text = $this->doQuotes( $text );
5890 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5895 * strip/replaceVariables/unstrip for preprocessor regression testing
5897 * @param $text string
5898 * @param $title Title
5899 * @param $options ParserOptions
5900 * @param $outputType int
5904 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5905 $this->startParse( $title, $options, $outputType, true );
5907 $text = $this->replaceVariables( $text );
5908 $text = $this->mStripState
->unstripBoth( $text );
5909 $text = Sanitizer
::removeHTMLtags( $text );
5914 * @param $text string
5915 * @param $title Title
5916 * @param $options ParserOptions
5919 function testPst( $text, Title
$title, ParserOptions
$options ) {
5920 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5925 * @param $title Title
5926 * @param $options ParserOptions
5929 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5930 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5934 * Call a callback function on all regions of the given text that are not
5935 * inside strip markers, and replace those regions with the return value
5936 * of the callback. For example, with input:
5940 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5941 * two strings will be replaced with the value returned by the callback in
5949 function markerSkipCallback( $s, $callback ) {
5952 while ( $i < strlen( $s ) ) {
5953 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5954 if ( $markerStart === false ) {
5955 $out .= call_user_func( $callback, substr( $s, $i ) );
5958 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5959 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5960 if ( $markerEnd === false ) {
5961 $out .= substr( $s, $markerStart );
5964 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5965 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5974 * Remove any strip markers found in the given text.
5976 * @param $text Input string
5979 function killMarkers( $text ) {
5980 return $this->mStripState
->killMarkers( $text );
5984 * Save the parser state required to convert the given half-parsed text to
5985 * HTML. "Half-parsed" in this context means the output of
5986 * recursiveTagParse() or internalParse(). This output has strip markers
5987 * from replaceVariables (extensionSubstitution() etc.), and link
5988 * placeholders from replaceLinkHolders().
5990 * Returns an array which can be serialized and stored persistently. This
5991 * array can later be loaded into another parser instance with
5992 * unserializeHalfParsedText(). The text can then be safely incorporated into
5993 * the return value of a parser hook.
5995 * @param $text string
5999 function serializeHalfParsedText( $text ) {
6000 wfProfileIn( __METHOD__
);
6003 'version' => self
::HALF_PARSED_VERSION
,
6004 'stripState' => $this->mStripState
->getSubState( $text ),
6005 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6007 wfProfileOut( __METHOD__
);
6012 * Load the parser state given in the $data array, which is assumed to
6013 * have been generated by serializeHalfParsedText(). The text contents is
6014 * extracted from the array, and its markers are transformed into markers
6015 * appropriate for the current Parser instance. This transformed text is
6016 * returned, and can be safely included in the return value of a parser
6019 * If the $data array has been stored persistently, the caller should first
6020 * check whether it is still valid, by calling isValidHalfParsedText().
6022 * @param array $data Serialized data
6023 * @throws MWException
6026 function unserializeHalfParsedText( $data ) {
6027 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6028 throw new MWException( __METHOD__
. ': invalid version' );
6031 # First, extract the strip state.
6032 $texts = array( $data['text'] );
6033 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6035 # Now renumber links
6036 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6038 # Should be good to go.
6043 * Returns true if the given array, presumed to be generated by
6044 * serializeHalfParsedText(), is compatible with the current version of the
6047 * @param $data Array
6051 function isValidHalfParsedText( $data ) {
6052 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6056 * Parsed a width param of imagelink like 300px or 200x300px
6058 * @param $value String
6063 public function parseWidthParam( $value ) {
6064 $parsedWidthParam = array();
6065 if ( $value === '' ) {
6066 return $parsedWidthParam;
6069 # (bug 13500) In both cases (width/height and width only),
6070 # permit trailing "px" for backward compatibility.
6071 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6072 $width = intval( $m[1] );
6073 $height = intval( $m[2] );
6074 $parsedWidthParam['width'] = $width;
6075 $parsedWidthParam['height'] = $height;
6076 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6077 $width = intval( $value );
6078 $parsedWidthParam['width'] = $width;
6080 return $parsedWidthParam;