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 XHTML 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!
58 * $wgNamespacesWithSubpages
60 * @par Settings only within ParserOptions:
61 * $wgAllowExternalImages
62 * $wgAllowSpecialInclusion
71 * Update this version number when the ParserOutput format
72 * changes in an incompatible way, so the parser cache
73 * can automatically discard old data.
75 const VERSION
= '1.6.4';
78 * Update this version number when the output of serialiseHalfParsedText()
79 * changes in an incompatible way
81 const HALF_PARSED_VERSION
= 2;
83 # Flags for Parser::setFunctionHook
84 # Also available as global constants from Defines.php
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
92 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
93 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
94 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT
= 0;
98 const COLON_STATE_TAG
= 1;
99 const COLON_STATE_TAGSTART
= 2;
100 const COLON_STATE_CLOSETAG
= 3;
101 const COLON_STATE_TAGSLASH
= 4;
102 const COLON_STATE_COMMENT
= 5;
103 const COLON_STATE_COMMENTDASH
= 6;
104 const COLON_STATE_COMMENTDASHDASH
= 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX
= "-QINU\x7f";
121 var $mTagHooks = array();
122 var $mTransparentTagHooks = array();
123 var $mFunctionHooks = array();
124 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
125 var $mFunctionTagHooks = array();
126 var $mStripList = array();
127 var $mDefaultStripList = array();
128 var $mVarCache = array();
129 var $mImageParams = array();
130 var $mImageParamsMagicArray = array();
131 var $mMarkerIndex = 0;
132 var $mFirstCall = true;
134 # Initialised by initialiseVariables()
137 * @var MagicWordArray
142 * @var MagicWordArray
145 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
147 # Cleared with clearState():
152 var $mAutonumber, $mDTopen;
159 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
161 * @var LinkHolderArray
166 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
168 var $mTplExpandCache; # empty-frame expansion cache
169 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
170 var $mExpensiveFunctionCount; # number of expensive parser function calls
171 var $mShowToc, $mForceTocPosition;
176 var $mUser; # User object; only used when doing pre-save transform
179 # These are variables reset at least once per parse regardless of $clearState
189 var $mTitle; # Title context, used for self-link rendering and similar things
190 var $mOutputType; # Output type, one of the OT_xxx constants
191 var $ot; # Shortcut alias, see setOutputType()
192 var $mRevisionObject; # The revision object of the specified revision ID
193 var $mRevisionId; # ID to display in {{REVISIONID}} tags
194 var $mRevisionTimestamp; # The timestamp of the specified revision ID
195 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
196 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
204 * @var Array with the language name of each language link (i.e. the
205 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
206 * duplicate language links to the ParserOutput.
208 var $mLangLinkLanguages;
215 public function __construct( $conf = array() ) {
216 $this->mConf
= $conf;
217 $this->mUrlProtocols
= wfUrlProtocols();
218 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')'.
219 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
220 if ( isset( $conf['preprocessorClass'] ) ) {
221 $this->mPreprocessorClass
= $conf['preprocessorClass'];
222 } elseif ( defined( 'MW_COMPILED' ) ) {
223 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
224 $this->mPreprocessorClass
= 'Preprocessor_Hash';
225 } elseif ( extension_loaded( 'domxml' ) ) {
226 # PECL extension that conflicts with the core DOM extension (bug 13770)
227 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
228 $this->mPreprocessorClass
= 'Preprocessor_Hash';
229 } elseif ( extension_loaded( 'dom' ) ) {
230 $this->mPreprocessorClass
= 'Preprocessor_DOM';
232 $this->mPreprocessorClass
= 'Preprocessor_Hash';
234 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
238 * Reduce memory usage to reduce the impact of circular references
240 function __destruct() {
241 if ( isset( $this->mLinkHolders
) ) {
242 unset( $this->mLinkHolders
);
244 foreach ( $this as $name => $value ) {
245 unset( $this->$name );
250 * Allow extensions to clean up when the parser is cloned
253 wfRunHooks( 'ParserCloned', array( $this ) );
257 * Do various kinds of initialisation on the first call of the parser
259 function firstCallInit() {
260 if ( !$this->mFirstCall
) {
263 $this->mFirstCall
= false;
265 wfProfileIn( __METHOD__
);
267 CoreParserFunctions
::register( $this );
268 CoreTagHooks
::register( $this );
269 $this->initialiseVariables();
271 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
272 wfProfileOut( __METHOD__
);
280 function clearState() {
281 wfProfileIn( __METHOD__
);
282 if ( $this->mFirstCall
) {
283 $this->firstCallInit();
285 $this->mOutput
= new ParserOutput
;
286 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
287 $this->mAutonumber
= 0;
288 $this->mLastSection
= '';
289 $this->mDTopen
= false;
290 $this->mIncludeCount
= array();
291 $this->mArgStack
= false;
292 $this->mInPre
= false;
293 $this->mLinkHolders
= new LinkHolderArray( $this );
295 $this->mRevisionObject
= $this->mRevisionTimestamp
=
296 $this->mRevisionId
= $this->mRevisionUser
= null;
297 $this->mVarCache
= array();
299 $this->mLangLinkLanguages
= array();
302 * Prefix for temporary replacement strings for the multipass parser.
303 * \x07 should never appear in input as it's disallowed in XML.
304 * Using it at the front also gives us a little extra robustness
305 * since it shouldn't match when butted up against identifier-like
308 * Must not consist of all title characters, or else it will change
309 * the behaviour of <nowiki> in a link.
311 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
312 $this->mStripState
= new StripState( $this->mUniqPrefix
);
315 # Clear these on every parse, bug 4549
316 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
318 $this->mShowToc
= true;
319 $this->mForceTocPosition
= false;
320 $this->mIncludeSizes
= array(
324 $this->mPPNodeCount
= 0;
325 $this->mGeneratedPPNodeCount
= 0;
326 $this->mHighestExpansionDepth
= 0;
327 $this->mDefaultSort
= false;
328 $this->mHeadings
= array();
329 $this->mDoubleUnderscores
= array();
330 $this->mExpensiveFunctionCount
= 0;
333 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
334 $this->mPreprocessor
= null;
337 wfRunHooks( 'ParserClearState', array( &$this ) );
338 wfProfileOut( __METHOD__
);
342 * Convert wikitext to HTML
343 * Do not call this function recursively.
345 * @param $text String: text we want to parse
346 * @param $title Title object
347 * @param $options ParserOptions
348 * @param $linestart boolean
349 * @param $clearState boolean
350 * @param $revid Int: number to pass in {{REVISIONID}}
351 * @return ParserOutput a ParserOutput
353 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
355 * First pass--just handle <nowiki> sections, pass the rest off
356 * to internalParse() which does all the real work.
359 global $wgUseTidy, $wgAlwaysUseTidy;
360 $fname = __METHOD__
.'-' . wfGetCaller();
361 wfProfileIn( __METHOD__
);
362 wfProfileIn( $fname );
364 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
366 # Remove the strip marker tag prefix from the input, if present.
368 $text = str_replace( $this->mUniqPrefix
, '', $text );
371 $oldRevisionId = $this->mRevisionId
;
372 $oldRevisionObject = $this->mRevisionObject
;
373 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
374 $oldRevisionUser = $this->mRevisionUser
;
375 if ( $revid !== null ) {
376 $this->mRevisionId
= $revid;
377 $this->mRevisionObject
= null;
378 $this->mRevisionTimestamp
= null;
379 $this->mRevisionUser
= null;
382 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
384 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
385 $text = $this->internalParse( $text );
386 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
388 $text = $this->mStripState
->unstripGeneral( $text );
390 # Clean up special characters, only run once, next-to-last before doBlockLevels
392 # french spaces, last one Guillemet-left
393 # only if there is something before the space
394 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
395 # french spaces, Guillemet-right
396 '/(\\302\\253) /' => '\\1 ',
397 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
399 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
401 $text = $this->doBlockLevels( $text, $linestart );
403 $this->replaceLinkHolders( $text );
406 * The input doesn't get language converted if
408 * b) Content isn't converted
409 * c) It's a conversion table
410 * d) it is an interface message (which is in the user language)
412 if ( !( $options->getDisableContentConversion()
413 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
415 # Run convert unconditionally in 1.18-compatible mode
416 global $wgBug34832TransitionalRollback;
417 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
418 # The position of the convert() call should not be changed. it
419 # assumes that the links are all replaced and the only thing left
420 # is the <nowiki> mark.
421 $text = $this->getConverterLanguage()->convert( $text );
426 * A converted title will be provided in the output object if title and
427 * content conversion are enabled, the article text does not contain
428 * a conversion-suppressing double-underscore tag, and no
429 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
430 * automatic link conversion.
432 if ( !( $options->getDisableTitleConversion()
433 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
434 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
435 ||
$this->mOutput
->getDisplayTitle() !== false ) )
437 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
438 if ( $convruletitle ) {
439 $this->mOutput
->setTitleText( $convruletitle );
441 $titleText = $this->getConverterLanguage()->convertTitle( $title );
442 $this->mOutput
->setTitleText( $titleText );
446 $text = $this->mStripState
->unstripNoWiki( $text );
448 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
450 $text = $this->replaceTransparentTags( $text );
451 $text = $this->mStripState
->unstripGeneral( $text );
453 $text = Sanitizer
::normalizeCharReferences( $text );
455 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
456 $text = MWTidy
::tidy( $text );
458 # attempt to sanitize at least some nesting problems
459 # (bug #2702 and quite a few others)
461 # ''Something [http://www.cool.com cool''] -->
462 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
463 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
464 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
465 # fix up an anchor inside another anchor, only
466 # at least for a single single nested link (bug 3695)
467 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
468 '\\1\\2</a>\\3</a>\\1\\4</a>',
469 # fix div inside inline elements- doBlockLevels won't wrap a line which
470 # contains a div, so fix it up here; replace
471 # div with escaped text
472 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
473 '\\1\\3<div\\5>\\6</div>\\8\\9',
474 # remove empty italic or bold tag pairs, some
475 # introduced by rules above
476 '/<([bi])><\/\\1>/' => '',
479 $text = preg_replace(
480 array_keys( $tidyregs ),
481 array_values( $tidyregs ),
485 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
486 $this->limitationWarn( 'expensive-parserfunction',
487 $this->mExpensiveFunctionCount
,
488 $this->mOptions
->getExpensiveParserFunctionLimit()
492 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
494 # Information on include size limits, for the benefit of users who try to skirt them
495 if ( $this->mOptions
->getEnableLimitReport() ) {
496 $max = $this->mOptions
->getMaxIncludeSize();
497 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
499 "NewPP limit report\n" .
500 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
501 "Preprocessor generated node count: " .
502 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
503 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
504 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
505 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
507 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
508 $text .= "\n<!-- \n$limitReport-->\n";
510 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
511 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
512 $this->mTitle
->getPrefixedDBkey() );
515 $this->mOutput
->setText( $text );
517 $this->mRevisionId
= $oldRevisionId;
518 $this->mRevisionObject
= $oldRevisionObject;
519 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
520 $this->mRevisionUser
= $oldRevisionUser;
521 wfProfileOut( $fname );
522 wfProfileOut( __METHOD__
);
524 return $this->mOutput
;
528 * Recursive parser entry point that can be called from an extension tag
531 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
533 * @param $text String: text extension wants to have parsed
534 * @param $frame PPFrame: The frame to use for expanding any template variables
538 function recursiveTagParse( $text, $frame=false ) {
539 wfProfileIn( __METHOD__
);
540 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
541 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
542 $text = $this->internalParse( $text, false, $frame );
543 wfProfileOut( __METHOD__
);
548 * Expand templates and variables in the text, producing valid, static wikitext.
549 * Also removes comments.
550 * @return mixed|string
552 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
553 wfProfileIn( __METHOD__
);
554 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
555 if ( $revid !== null ) {
556 $this->mRevisionId
= $revid;
558 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
559 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
560 $text = $this->replaceVariables( $text );
561 $text = $this->mStripState
->unstripBoth( $text );
562 wfProfileOut( __METHOD__
);
567 * Recursive parser entry point that can be called from an extension tag
570 * @param $text String: text to be expanded
571 * @param $frame PPFrame: The frame to use for expanding any template variables
575 public function recursivePreprocess( $text, $frame = false ) {
576 wfProfileIn( __METHOD__
);
577 $text = $this->replaceVariables( $text, $frame );
578 $text = $this->mStripState
->unstripBoth( $text );
579 wfProfileOut( __METHOD__
);
584 * Process the wikitext for the "?preload=" feature. (bug 5210)
586 * "<noinclude>", "<includeonly>" etc. are parsed as for template
587 * transclusion, comments, templates, arguments, tags hooks and parser
588 * functions are untouched.
590 * @param $text String
591 * @param $title Title
592 * @param $options ParserOptions
595 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
596 # Parser (re)initialisation
597 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
599 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
600 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
601 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
602 $text = $this->mStripState
->unstripBoth( $text );
607 * Get a random string
611 static public function getRandomString() {
612 return wfRandomString( 16 );
616 * Set the current user.
617 * Should only be used when doing pre-save transform.
619 * @param $user Mixed: User object or null (to reset)
621 function setUser( $user ) {
622 $this->mUser
= $user;
626 * Accessor for mUniqPrefix.
630 public function uniqPrefix() {
631 if ( !isset( $this->mUniqPrefix
) ) {
632 # @todo FIXME: This is probably *horribly wrong*
633 # LanguageConverter seems to want $wgParser's uniqPrefix, however
634 # if this is called for a parser cache hit, the parser may not
635 # have ever been initialized in the first place.
636 # Not really sure what the heck is supposed to be going on here.
638 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
640 return $this->mUniqPrefix
;
644 * Set the context title
648 function setTitle( $t ) {
649 if ( !$t ||
$t instanceof FakeTitle
) {
650 $t = Title
::newFromText( 'NO TITLE' );
653 if ( strval( $t->getFragment() ) !== '' ) {
654 # Strip the fragment to avoid various odd effects
655 $this->mTitle
= clone $t;
656 $this->mTitle
->setFragment( '' );
663 * Accessor for the Title object
665 * @return Title object
667 function getTitle() {
668 return $this->mTitle
;
672 * Accessor/mutator for the Title object
674 * @param $x Title object or null to just get the current one
675 * @return Title object
677 function Title( $x = null ) {
678 return wfSetVar( $this->mTitle
, $x );
682 * Set the output type
684 * @param $ot Integer: new value
686 function setOutputType( $ot ) {
687 $this->mOutputType
= $ot;
690 'html' => $ot == self
::OT_HTML
,
691 'wiki' => $ot == self
::OT_WIKI
,
692 'pre' => $ot == self
::OT_PREPROCESS
,
693 'plain' => $ot == self
::OT_PLAIN
,
698 * Accessor/mutator for the output type
700 * @param $x int|null New value or null to just get the current one
703 function OutputType( $x = null ) {
704 return wfSetVar( $this->mOutputType
, $x );
708 * Get the ParserOutput object
710 * @return ParserOutput object
712 function getOutput() {
713 return $this->mOutput
;
717 * Get the ParserOptions object
719 * @return ParserOptions object
721 function getOptions() {
722 return $this->mOptions
;
726 * Accessor/mutator for the ParserOptions object
728 * @param $x ParserOptions New value or null to just get the current one
729 * @return ParserOptions Current ParserOptions object
731 function Options( $x = null ) {
732 return wfSetVar( $this->mOptions
, $x );
738 function nextLinkID() {
739 return $this->mLinkID++
;
745 function setLinkID( $id ) {
746 $this->mLinkID
= $id;
750 * Get a language object for use in parser functions such as {{FORMATNUM:}}
753 function getFunctionLang() {
754 return $this->getTargetLanguage();
758 * Get the target language for the content being parsed. This is usually the
759 * language that the content is in.
763 * @throws MWException
764 * @return Language|null
766 public function getTargetLanguage() {
767 $target = $this->mOptions
->getTargetLanguage();
769 if ( $target !== null ) {
771 } elseif( $this->mOptions
->getInterfaceMessage() ) {
772 return $this->mOptions
->getUserLangObj();
773 } elseif( is_null( $this->mTitle
) ) {
774 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
777 return $this->mTitle
->getPageLanguage();
781 * Get the language object for language conversion
783 function getConverterLanguage() {
784 global $wgBug34832TransitionalRollback, $wgContLang;
785 if ( $wgBug34832TransitionalRollback ) {
788 return $this->getTargetLanguage();
793 * Get a User object either from $this->mUser, if set, or from the
794 * ParserOptions object otherwise
796 * @return User object
799 if ( !is_null( $this->mUser
) ) {
802 return $this->mOptions
->getUser();
806 * Get a preprocessor object
808 * @return Preprocessor instance
810 function getPreprocessor() {
811 if ( !isset( $this->mPreprocessor
) ) {
812 $class = $this->mPreprocessorClass
;
813 $this->mPreprocessor
= new $class( $this );
815 return $this->mPreprocessor
;
819 * Replaces all occurrences of HTML-style comments and the given tags
820 * in the text with a random marker and returns the next text. The output
821 * parameter $matches will be an associative array filled with data in
825 * 'UNIQ-xxxxx' => array(
828 * array( 'param' => 'x' ),
829 * '<element param="x">tag content</element>' ) )
832 * @param $elements array list of element names. Comments are always extracted.
833 * @param $text string Source text string.
834 * @param $matches array Out parameter, Array: extracted tags
835 * @param $uniq_prefix string
836 * @return String: stripped text
838 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
843 $taglist = implode( '|', $elements );
844 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
846 while ( $text != '' ) {
847 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
849 if ( count( $p ) < 5 ) {
852 if ( count( $p ) > 5 ) {
866 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
867 $stripped .= $marker;
869 if ( $close === '/>' ) {
870 # Empty element tag, <tag />
875 if ( $element === '!--' ) {
878 $end = "/(<\\/$element\\s*>)/i";
880 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
882 if ( count( $q ) < 3 ) {
883 # No end tag -- let it run out to the end of the text.
892 $matches[$marker] = array( $element,
894 Sanitizer
::decodeTagAttributes( $attributes ),
895 "<$element$attributes$close$content$tail" );
901 * Get a list of strippable XML-like elements
905 function getStripList() {
906 return $this->mStripList
;
910 * Add an item to the strip state
911 * Returns the unique tag which must be inserted into the stripped text
912 * The tag will be replaced with the original text in unstrip()
914 * @param $text string
918 function insertStripItem( $text ) {
919 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
920 $this->mMarkerIndex++
;
921 $this->mStripState
->addGeneral( $rnd, $text );
926 * parse the wiki syntax used to render tables
931 function doTableStuff( $text ) {
932 wfProfileIn( __METHOD__
);
934 $lines = StringUtils
::explode( "\n", $text );
936 $td_history = array(); # Is currently a td tag open?
937 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
938 $tr_history = array(); # Is currently a tr tag open?
939 $tr_attributes = array(); # history of tr attributes
940 $has_opened_tr = array(); # Did this table open a <tr> element?
941 $indent_level = 0; # indent level of the table
943 foreach ( $lines as $outLine ) {
944 $line = trim( $outLine );
946 if ( $line === '' ) { # empty line, go to next line
947 $out .= $outLine."\n";
951 $first_character = $line[0];
954 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
955 # First check if we are starting a new table
956 $indent_level = strlen( $matches[1] );
958 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
959 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
961 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
962 array_push( $td_history , false );
963 array_push( $last_tag_history , '' );
964 array_push( $tr_history , false );
965 array_push( $tr_attributes , '' );
966 array_push( $has_opened_tr , false );
967 } elseif ( count( $td_history ) == 0 ) {
968 # Don't do any of the following
969 $out .= $outLine."\n";
971 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
972 # We are ending a table
973 $line = '</table>' . substr( $line , 2 );
974 $last_tag = array_pop( $last_tag_history );
976 if ( !array_pop( $has_opened_tr ) ) {
977 $line = "<tr><td></td></tr>{$line}";
980 if ( array_pop( $tr_history ) ) {
981 $line = "</tr>{$line}";
984 if ( array_pop( $td_history ) ) {
985 $line = "</{$last_tag}>{$line}";
987 array_pop( $tr_attributes );
988 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
989 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
990 # Now we have a table row
991 $line = preg_replace( '#^\|-+#', '', $line );
993 # Whats after the tag is now only attributes
994 $attributes = $this->mStripState
->unstripBoth( $line );
995 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
996 array_pop( $tr_attributes );
997 array_push( $tr_attributes, $attributes );
1000 $last_tag = array_pop( $last_tag_history );
1001 array_pop( $has_opened_tr );
1002 array_push( $has_opened_tr , true );
1004 if ( array_pop( $tr_history ) ) {
1008 if ( array_pop( $td_history ) ) {
1009 $line = "</{$last_tag}>{$line}";
1013 array_push( $tr_history , false );
1014 array_push( $td_history , false );
1015 array_push( $last_tag_history , '' );
1016 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
1017 # This might be cell elements, td, th or captions
1018 if ( substr( $line , 0 , 2 ) === '|+' ) {
1019 $first_character = '+';
1020 $line = substr( $line , 1 );
1023 $line = substr( $line , 1 );
1025 if ( $first_character === '!' ) {
1026 $line = str_replace( '!!' , '||' , $line );
1029 # Split up multiple cells on the same line.
1030 # FIXME : This can result in improper nesting of tags processed
1031 # by earlier parser steps, but should avoid splitting up eg
1032 # attribute values containing literal "||".
1033 $cells = StringUtils
::explodeMarkup( '||' , $line );
1037 # Loop through each table cell
1038 foreach ( $cells as $cell ) {
1040 if ( $first_character !== '+' ) {
1041 $tr_after = array_pop( $tr_attributes );
1042 if ( !array_pop( $tr_history ) ) {
1043 $previous = "<tr{$tr_after}>\n";
1045 array_push( $tr_history , true );
1046 array_push( $tr_attributes , '' );
1047 array_pop( $has_opened_tr );
1048 array_push( $has_opened_tr , true );
1051 $last_tag = array_pop( $last_tag_history );
1053 if ( array_pop( $td_history ) ) {
1054 $previous = "</{$last_tag}>\n{$previous}";
1057 if ( $first_character === '|' ) {
1059 } elseif ( $first_character === '!' ) {
1061 } elseif ( $first_character === '+' ) {
1062 $last_tag = 'caption';
1067 array_push( $last_tag_history , $last_tag );
1069 # A cell could contain both parameters and data
1070 $cell_data = explode( '|' , $cell , 2 );
1072 # Bug 553: Note that a '|' inside an invalid link should not
1073 # be mistaken as delimiting cell parameters
1074 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1075 $cell = "{$previous}<{$last_tag}>{$cell}";
1076 } elseif ( count( $cell_data ) == 1 ) {
1077 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1079 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1080 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1081 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1085 array_push( $td_history , true );
1088 $out .= $outLine . "\n";
1091 # Closing open td, tr && table
1092 while ( count( $td_history ) > 0 ) {
1093 if ( array_pop( $td_history ) ) {
1096 if ( array_pop( $tr_history ) ) {
1099 if ( !array_pop( $has_opened_tr ) ) {
1100 $out .= "<tr><td></td></tr>\n" ;
1103 $out .= "</table>\n";
1106 # Remove trailing line-ending (b/c)
1107 if ( substr( $out, -1 ) === "\n" ) {
1108 $out = substr( $out, 0, -1 );
1111 # special case: don't return empty table
1112 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1116 wfProfileOut( __METHOD__
);
1122 * Helper function for parse() that transforms wiki markup into
1123 * HTML. Only called for $mOutputType == self::OT_HTML.
1127 * @param $text string
1128 * @param $isMain bool
1129 * @param $frame bool
1133 function internalParse( $text, $isMain = true, $frame = false ) {
1134 wfProfileIn( __METHOD__
);
1138 # Hook to suspend the parser in this state
1139 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1140 wfProfileOut( __METHOD__
);
1144 # if $frame is provided, then use $frame for replacing any variables
1146 # use frame depth to infer how include/noinclude tags should be handled
1147 # depth=0 means this is the top-level document; otherwise it's an included document
1148 if ( !$frame->depth
) {
1151 $flag = Parser
::PTD_FOR_INCLUSION
;
1153 $dom = $this->preprocessToDom( $text, $flag );
1154 $text = $frame->expand( $dom );
1156 # if $frame is not provided, then use old-style replaceVariables
1157 $text = $this->replaceVariables( $text );
1160 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1161 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1162 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1164 # Tables need to come after variable replacement for things to work
1165 # properly; putting them before other transformations should keep
1166 # exciting things like link expansions from showing up in surprising
1168 $text = $this->doTableStuff( $text );
1170 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1172 $text = $this->doDoubleUnderscore( $text );
1174 $text = $this->doHeadings( $text );
1175 if ( $this->mOptions
->getUseDynamicDates() ) {
1176 $df = DateFormatter
::getInstance();
1177 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1179 $text = $this->replaceInternalLinks( $text );
1180 $text = $this->doAllQuotes( $text );
1181 $text = $this->replaceExternalLinks( $text );
1183 # replaceInternalLinks may sometimes leave behind
1184 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1185 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1187 $text = $this->doMagicLinks( $text );
1188 $text = $this->formatHeadings( $text, $origText, $isMain );
1190 wfProfileOut( __METHOD__
);
1195 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1196 * magic external links.
1201 * @param $text string
1205 function doMagicLinks( $text ) {
1206 wfProfileIn( __METHOD__
);
1207 $prots = wfUrlProtocolsWithoutProtRel();
1208 $urlChar = self
::EXT_LINK_URL_CLASS
;
1209 $text = preg_replace_callback(
1211 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1212 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1213 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1214 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1215 ISBN\s+(\b # m[5]: ISBN, capture number
1216 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1217 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1218 [0-9Xx] # check digit
1220 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1221 wfProfileOut( __METHOD__
);
1226 * @throws MWException
1228 * @return HTML|string
1230 function magicLinkCallback( $m ) {
1231 if ( isset( $m[1] ) && $m[1] !== '' ) {
1234 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1237 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1238 # Free external link
1239 return $this->makeFreeExternalLink( $m[0] );
1240 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1242 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1245 $CssClass = 'mw-magiclink-rfc';
1247 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1249 $urlmsg = 'pubmedurl';
1250 $CssClass = 'mw-magiclink-pmid';
1253 throw new MWException( __METHOD__
.': unrecognised match type "' .
1254 substr( $m[0], 0, 20 ) . '"' );
1256 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1257 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1258 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1261 $num = strtr( $isbn, array(
1266 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1268 htmlspecialchars( $titleObj->getLocalUrl() ) .
1269 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1276 * Make a free external link, given a user-supplied URL
1278 * @param $url string
1280 * @return string HTML
1283 function makeFreeExternalLink( $url ) {
1284 wfProfileIn( __METHOD__
);
1288 # The characters '<' and '>' (which were escaped by
1289 # removeHTMLtags()) should not be included in
1290 # URLs, per RFC 2396.
1292 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1293 $trail = substr( $url, $m2[0][1] ) . $trail;
1294 $url = substr( $url, 0, $m2[0][1] );
1297 # Move trailing punctuation to $trail
1299 # If there is no left bracket, then consider right brackets fair game too
1300 if ( strpos( $url, '(' ) === false ) {
1304 $numSepChars = strspn( strrev( $url ), $sep );
1305 if ( $numSepChars ) {
1306 $trail = substr( $url, -$numSepChars ) . $trail;
1307 $url = substr( $url, 0, -$numSepChars );
1310 $url = Sanitizer
::cleanUrl( $url );
1312 # Is this an external image?
1313 $text = $this->maybeMakeExternalImage( $url );
1314 if ( $text === false ) {
1315 # Not an image, make a link
1316 $text = Linker
::makeExternalLink( $url,
1317 $this->getConverterLanguage()->markNoConversion( $url, true ),
1319 $this->getExternalLinkAttribs( $url ) );
1320 # Register it in the output object...
1321 # Replace unnecessary URL escape codes with their equivalent characters
1322 $pasteurized = self
::replaceUnusualEscapes( $url );
1323 $this->mOutput
->addExternalLink( $pasteurized );
1325 wfProfileOut( __METHOD__
);
1326 return $text . $trail;
1331 * Parse headers and return html
1335 * @param $text string
1339 function doHeadings( $text ) {
1340 wfProfileIn( __METHOD__
);
1341 for ( $i = 6; $i >= 1; --$i ) {
1342 $h = str_repeat( '=', $i );
1343 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1344 "<h$i>\\1</h$i>", $text );
1346 wfProfileOut( __METHOD__
);
1351 * Replace single quotes with HTML markup
1354 * @param $text string
1356 * @return string the altered text
1358 function doAllQuotes( $text ) {
1359 wfProfileIn( __METHOD__
);
1361 $lines = StringUtils
::explode( "\n", $text );
1362 foreach ( $lines as $line ) {
1363 $outtext .= $this->doQuotes( $line ) . "\n";
1365 $outtext = substr( $outtext, 0,-1 );
1366 wfProfileOut( __METHOD__
);
1371 * Helper function for doAllQuotes()
1373 * @param $text string
1377 public function doQuotes( $text ) {
1378 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1379 if ( count( $arr ) == 1 ) {
1382 # First, do some preliminary work. This may shift some apostrophes from
1383 # being mark-up to being text. It also counts the number of occurrences
1384 # of bold and italics mark-ups.
1387 for ( $i = 0; $i < count( $arr ); $i++
) {
1388 if ( ( $i %
2 ) == 1 ) {
1389 # If there are ever four apostrophes, assume the first is supposed to
1390 # be text, and the remaining three constitute mark-up for bold text.
1391 if ( strlen( $arr[$i] ) == 4 ) {
1394 } elseif ( strlen( $arr[$i] ) > 5 ) {
1395 # If there are more than 5 apostrophes in a row, assume they're all
1396 # text except for the last 5.
1397 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1400 # Count the number of occurrences of bold and italics mark-ups.
1401 # We are not counting sequences of five apostrophes.
1402 if ( strlen( $arr[$i] ) == 2 ) {
1404 } elseif ( strlen( $arr[$i] ) == 3 ) {
1406 } elseif ( strlen( $arr[$i] ) == 5 ) {
1413 # If there is an odd number of both bold and italics, it is likely
1414 # that one of the bold ones was meant to be an apostrophe followed
1415 # by italics. Which one we cannot know for certain, but it is more
1416 # likely to be one that has a single-letter word before it.
1417 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1419 $firstsingleletterword = -1;
1420 $firstmultiletterword = -1;
1422 foreach ( $arr as $r ) {
1423 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1424 $x1 = substr( $arr[$i-1], -1 );
1425 $x2 = substr( $arr[$i-1], -2, 1 );
1426 if ( $x1 === ' ' ) {
1427 if ( $firstspace == -1 ) {
1430 } elseif ( $x2 === ' ') {
1431 if ( $firstsingleletterword == -1 ) {
1432 $firstsingleletterword = $i;
1435 if ( $firstmultiletterword == -1 ) {
1436 $firstmultiletterword = $i;
1443 # If there is a single-letter word, use it!
1444 if ( $firstsingleletterword > -1 ) {
1445 $arr[$firstsingleletterword] = "''";
1446 $arr[$firstsingleletterword-1] .= "'";
1447 } elseif ( $firstmultiletterword > -1 ) {
1448 # If not, but there's a multi-letter word, use that one.
1449 $arr[$firstmultiletterword] = "''";
1450 $arr[$firstmultiletterword-1] .= "'";
1451 } elseif ( $firstspace > -1 ) {
1452 # ... otherwise use the first one that has neither.
1453 # (notice that it is possible for all three to be -1 if, for example,
1454 # there is only one pentuple-apostrophe in the line)
1455 $arr[$firstspace] = "''";
1456 $arr[$firstspace-1] .= "'";
1460 # Now let's actually convert our apostrophic mush to HTML!
1465 foreach ( $arr as $r ) {
1466 if ( ( $i %
2 ) == 0 ) {
1467 if ( $state === 'both' ) {
1473 if ( strlen( $r ) == 2 ) {
1474 if ( $state === 'i' ) {
1475 $output .= '</i>'; $state = '';
1476 } elseif ( $state === 'bi' ) {
1477 $output .= '</i>'; $state = 'b';
1478 } elseif ( $state === 'ib' ) {
1479 $output .= '</b></i><b>'; $state = 'b';
1480 } elseif ( $state === 'both' ) {
1481 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1482 } else { # $state can be 'b' or ''
1483 $output .= '<i>'; $state .= 'i';
1485 } elseif ( strlen( $r ) == 3 ) {
1486 if ( $state === 'b' ) {
1487 $output .= '</b>'; $state = '';
1488 } elseif ( $state === 'bi' ) {
1489 $output .= '</i></b><i>'; $state = 'i';
1490 } elseif ( $state === 'ib' ) {
1491 $output .= '</b>'; $state = 'i';
1492 } elseif ( $state === 'both' ) {
1493 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1494 } else { # $state can be 'i' or ''
1495 $output .= '<b>'; $state .= 'b';
1497 } elseif ( strlen( $r ) == 5 ) {
1498 if ( $state === 'b' ) {
1499 $output .= '</b><i>'; $state = 'i';
1500 } elseif ( $state === 'i' ) {
1501 $output .= '</i><b>'; $state = 'b';
1502 } elseif ( $state === 'bi' ) {
1503 $output .= '</i></b>'; $state = '';
1504 } elseif ( $state === 'ib' ) {
1505 $output .= '</b></i>'; $state = '';
1506 } elseif ( $state === 'both' ) {
1507 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1508 } else { # ($state == '')
1509 $buffer = ''; $state = 'both';
1515 # Now close all remaining tags. Notice that the order is important.
1516 if ( $state === 'b' ||
$state === 'ib' ) {
1519 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1522 if ( $state === 'bi' ) {
1525 # There might be lonely ''''', so make sure we have a buffer
1526 if ( $state === 'both' && $buffer ) {
1527 $output .= '<b><i>'.$buffer.'</i></b>';
1534 * Replace external links (REL)
1536 * Note: this is all very hackish and the order of execution matters a lot.
1537 * Make sure to run maintenance/parserTests.php if you change this code.
1541 * @param $text string
1543 * @throws MWException
1546 function replaceExternalLinks( $text ) {
1547 wfProfileIn( __METHOD__
);
1549 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1550 if ( $bits === false ) {
1551 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1553 $s = array_shift( $bits );
1556 while ( $i<count( $bits ) ) {
1558 // @todo FIXME: Unused variable.
1559 $protocol = $bits[$i++
];
1560 $text = $bits[$i++
];
1561 $trail = $bits[$i++
];
1563 # The characters '<' and '>' (which were escaped by
1564 # removeHTMLtags()) should not be included in
1565 # URLs, per RFC 2396.
1567 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1568 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1569 $url = substr( $url, 0, $m2[0][1] );
1572 # If the link text is an image URL, replace it with an <img> tag
1573 # This happened by accident in the original parser, but some people used it extensively
1574 $img = $this->maybeMakeExternalImage( $text );
1575 if ( $img !== false ) {
1581 # Set linktype for CSS - if URL==text, link is essentially free
1582 $linktype = ( $text === $url ) ?
'free' : 'text';
1584 # No link text, e.g. [http://domain.tld/some.link]
1585 if ( $text == '' ) {
1587 $langObj = $this->getTargetLanguage();
1588 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1589 $linktype = 'autonumber';
1591 # Have link text, e.g. [http://domain.tld/some.link text]s
1593 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1596 $text = $this->getConverterLanguage()->markNoConversion( $text );
1598 $url = Sanitizer
::cleanUrl( $url );
1600 # Use the encoded URL
1601 # This means that users can paste URLs directly into the text
1602 # Funny characters like ö aren't valid in URLs anyway
1603 # This was changed in August 2004
1604 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1605 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1607 # Register link in the output object.
1608 # Replace unnecessary URL escape codes with the referenced character
1609 # This prevents spammers from hiding links from the filters
1610 $pasteurized = self
::replaceUnusualEscapes( $url );
1611 $this->mOutput
->addExternalLink( $pasteurized );
1614 wfProfileOut( __METHOD__
);
1618 * Get the rel attribute for a particular external link.
1621 * @param $url String|bool optional URL, to extract the domain from for rel =>
1622 * nofollow if appropriate
1623 * @param $title Title optional Title, for wgNoFollowNsExceptions lookups
1624 * @return string|null rel attribute for $url
1626 public static function getExternalLinkRel( $url = false, $title = null ) {
1627 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1628 $ns = $title ?
$title->getNamespace() : false;
1629 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1630 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1637 * Get an associative array of additional HTML attributes appropriate for a
1638 * particular external link. This currently may include rel => nofollow
1639 * (depending on configuration, namespace, and the URL's domain) and/or a
1640 * target attribute (depending on configuration).
1642 * @param $url String|bool optional URL, to extract the domain from for rel =>
1643 * nofollow if appropriate
1644 * @return Array associative array of HTML attributes
1646 function getExternalLinkAttribs( $url = false ) {
1648 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1650 if ( $this->mOptions
->getExternalLinkTarget() ) {
1651 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1657 * Replace unusual URL escape codes with their equivalent characters
1659 * @param $url String
1662 * @todo This can merge genuinely required bits in the path or query string,
1663 * breaking legit URLs. A proper fix would treat the various parts of
1664 * the URL differently; as a workaround, just use the output for
1665 * statistical records, not for actual linking/output.
1667 static function replaceUnusualEscapes( $url ) {
1668 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1669 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1673 * Callback function used in replaceUnusualEscapes().
1674 * Replaces unusual URL escape codes with their equivalent character
1676 * @param $matches array
1680 private static function replaceUnusualEscapesCallback( $matches ) {
1681 $char = urldecode( $matches[0] );
1682 $ord = ord( $char );
1683 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1684 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1685 # No, shouldn't be escaped
1688 # Yes, leave it escaped
1694 * make an image if it's allowed, either through the global
1695 * option, through the exception, or through the on-wiki whitelist
1698 * $param $url string
1702 function maybeMakeExternalImage( $url ) {
1703 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1704 $imagesexception = !empty( $imagesfrom );
1706 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1707 if ( $imagesexception && is_array( $imagesfrom ) ) {
1708 $imagematch = false;
1709 foreach ( $imagesfrom as $match ) {
1710 if ( strpos( $url, $match ) === 0 ) {
1715 } elseif ( $imagesexception ) {
1716 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1718 $imagematch = false;
1720 if ( $this->mOptions
->getAllowExternalImages()
1721 ||
( $imagesexception && $imagematch ) ) {
1722 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1724 $text = Linker
::makeExternalImage( $url );
1727 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1728 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1729 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1730 foreach ( $whitelist as $entry ) {
1731 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1732 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1735 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1736 # Image matches a whitelist entry
1737 $text = Linker
::makeExternalImage( $url );
1746 * Process [[ ]] wikilinks
1750 * @return String: processed text
1754 function replaceInternalLinks( $s ) {
1755 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1760 * Process [[ ]] wikilinks (RIL)
1762 * @throws MWException
1763 * @return LinkHolderArray
1767 function replaceInternalLinks2( &$s ) {
1768 wfProfileIn( __METHOD__
);
1770 wfProfileIn( __METHOD__
.'-setup' );
1771 static $tc = FALSE, $e1, $e1_img;
1772 # the % is needed to support urlencoded titles as well
1774 $tc = Title
::legalChars() . '#%';
1775 # Match a link having the form [[namespace:link|alternate]]trail
1776 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1777 # Match cases where there is no "]]", which might still be images
1778 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1781 $holders = new LinkHolderArray( $this );
1783 # split the entire text string on occurrences of [[
1784 $a = StringUtils
::explode( '[[', ' ' . $s );
1785 # get the first element (all text up to first [[), and remove the space we added
1788 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1789 $s = substr( $s, 1 );
1791 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1793 if ( $useLinkPrefixExtension ) {
1794 # Match the end of a line for a word that's not followed by whitespace,
1795 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1796 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1799 if ( is_null( $this->mTitle
) ) {
1800 wfProfileOut( __METHOD__
.'-setup' );
1801 wfProfileOut( __METHOD__
);
1802 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1804 $nottalk = !$this->mTitle
->isTalkPage();
1806 if ( $useLinkPrefixExtension ) {
1808 if ( preg_match( $e2, $s, $m ) ) {
1809 $first_prefix = $m[2];
1811 $first_prefix = false;
1817 if ( $this->getConverterLanguage()->hasVariants() ) {
1818 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1819 $this->mTitle
->getPrefixedText() );
1821 $selflink = array( $this->mTitle
->getPrefixedText() );
1823 $useSubpages = $this->areSubpagesAllowed();
1824 wfProfileOut( __METHOD__
.'-setup' );
1826 # Loop for each link
1827 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1828 # Check for excessive memory usage
1829 if ( $holders->isBig() ) {
1831 # Do the existence check, replace the link holders and clear the array
1832 $holders->replace( $s );
1836 if ( $useLinkPrefixExtension ) {
1837 wfProfileIn( __METHOD__
.'-prefixhandling' );
1838 if ( preg_match( $e2, $s, $m ) ) {
1845 if ( $first_prefix ) {
1846 $prefix = $first_prefix;
1847 $first_prefix = false;
1849 wfProfileOut( __METHOD__
.'-prefixhandling' );
1852 $might_be_img = false;
1854 wfProfileIn( __METHOD__
."-e1" );
1855 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1857 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1858 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1859 # the real problem is with the $e1 regex
1862 # Still some problems for cases where the ] is meant to be outside punctuation,
1863 # and no image is in sight. See bug 2095.
1865 if ( $text !== '' &&
1866 substr( $m[3], 0, 1 ) === ']' &&
1867 strpos( $text, '[' ) !== false
1870 $text .= ']'; # so that replaceExternalLinks($text) works later
1871 $m[3] = substr( $m[3], 1 );
1873 # fix up urlencoded title texts
1874 if ( strpos( $m[1], '%' ) !== false ) {
1875 # Should anchors '#' also be rejected?
1876 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1879 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1880 $might_be_img = true;
1882 if ( strpos( $m[1], '%' ) !== false ) {
1883 $m[1] = rawurldecode( $m[1] );
1886 } else { # Invalid form; output directly
1887 $s .= $prefix . '[[' . $line ;
1888 wfProfileOut( __METHOD__
."-e1" );
1891 wfProfileOut( __METHOD__
."-e1" );
1892 wfProfileIn( __METHOD__
."-misc" );
1894 # Don't allow internal links to pages containing
1895 # PROTO: where PROTO is a valid URL protocol; these
1896 # should be external links.
1897 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1898 $s .= $prefix . '[[' . $line ;
1899 wfProfileOut( __METHOD__
."-misc" );
1903 # Make subpage if necessary
1904 if ( $useSubpages ) {
1905 $link = $this->maybeDoSubpageLink( $m[1], $text );
1910 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1912 # Strip off leading ':'
1913 $link = substr( $link, 1 );
1916 wfProfileOut( __METHOD__
."-misc" );
1917 wfProfileIn( __METHOD__
."-title" );
1918 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1919 if ( $nt === null ) {
1920 $s .= $prefix . '[[' . $line;
1921 wfProfileOut( __METHOD__
."-title" );
1925 $ns = $nt->getNamespace();
1926 $iw = $nt->getInterWiki();
1927 wfProfileOut( __METHOD__
."-title" );
1929 if ( $might_be_img ) { # if this is actually an invalid link
1930 wfProfileIn( __METHOD__
."-might_be_img" );
1931 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1934 # look at the next 'line' to see if we can close it there
1936 $next_line = $a->current();
1937 if ( $next_line === false ||
$next_line === null ) {
1940 $m = explode( ']]', $next_line, 3 );
1941 if ( count( $m ) == 3 ) {
1942 # the first ]] closes the inner link, the second the image
1944 $text .= "[[{$m[0]}]]{$m[1]}";
1947 } elseif ( count( $m ) == 2 ) {
1948 # if there's exactly one ]] that's fine, we'll keep looking
1949 $text .= "[[{$m[0]}]]{$m[1]}";
1951 # if $next_line is invalid too, we need look no further
1952 $text .= '[[' . $next_line;
1957 # we couldn't find the end of this imageLink, so output it raw
1958 # but don't ignore what might be perfectly normal links in the text we've examined
1959 $holders->merge( $this->replaceInternalLinks2( $text ) );
1960 $s .= "{$prefix}[[$link|$text";
1961 # note: no $trail, because without an end, there *is* no trail
1962 wfProfileOut( __METHOD__
."-might_be_img" );
1965 } else { # it's not an image, so output it raw
1966 $s .= "{$prefix}[[$link|$text";
1967 # note: no $trail, because without an end, there *is* no trail
1968 wfProfileOut( __METHOD__
."-might_be_img" );
1971 wfProfileOut( __METHOD__
."-might_be_img" );
1974 $wasblank = ( $text == '' );
1978 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1979 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1980 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1981 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1982 $text = $this->doQuotes( $text );
1985 # Link not escaped by : , create the various objects
1988 wfProfileIn( __METHOD__
."-interwiki" );
1989 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1990 // XXX: the above check prevents links to sites with identifiers that are not language codes
1992 # Bug 24502: filter duplicates
1993 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1994 $this->mLangLinkLanguages
[$iw] = true;
1995 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1998 $s = rtrim( $s . $prefix );
1999 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2000 wfProfileOut( __METHOD__
."-interwiki" );
2003 wfProfileOut( __METHOD__
."-interwiki" );
2005 if ( $ns == NS_FILE
) {
2006 wfProfileIn( __METHOD__
."-image" );
2007 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2009 # if no parameters were passed, $text
2010 # becomes something like "File:Foo.png",
2011 # which we don't want to pass on to the
2015 # recursively parse links inside the image caption
2016 # actually, this will parse them in any other parameters, too,
2017 # but it might be hard to fix that, and it doesn't matter ATM
2018 $text = $this->replaceExternalLinks( $text );
2019 $holders->merge( $this->replaceInternalLinks2( $text ) );
2021 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2022 $s .= $prefix . $this->armorLinks(
2023 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2025 $s .= $prefix . $trail;
2027 wfProfileOut( __METHOD__
."-image" );
2031 if ( $ns == NS_CATEGORY
) {
2032 wfProfileIn( __METHOD__
."-category" );
2033 $s = rtrim( $s . "\n" ); # bug 87
2036 $sortkey = $this->getDefaultSort();
2040 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2041 $sortkey = str_replace( "\n", '', $sortkey );
2042 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2043 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2046 * Strip the whitespace Category links produce, see bug 87
2047 * @todo We might want to use trim($tmp, "\n") here.
2049 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2051 wfProfileOut( __METHOD__
."-category" );
2056 # Self-link checking
2057 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2058 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2059 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2064 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2065 # @todo FIXME: Should do batch file existence checks, see comment below
2066 if ( $ns == NS_MEDIA
) {
2067 wfProfileIn( __METHOD__
."-media" );
2068 # Give extensions a chance to select the file revision for us
2071 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2072 array( $this, $nt, &$options, &$descQuery ) );
2073 # Fetch and register the file (file title may be different via hooks)
2074 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2075 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2076 $s .= $prefix . $this->armorLinks(
2077 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2078 wfProfileOut( __METHOD__
."-media" );
2082 wfProfileIn( __METHOD__
."-always_known" );
2083 # Some titles, such as valid special pages or files in foreign repos, should
2084 # be shown as bluelinks even though they're not included in the page table
2086 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2087 # batch file existence checks for NS_FILE and NS_MEDIA
2088 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2089 $this->mOutput
->addLink( $nt );
2090 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2092 # Links will be added to the output link list after checking
2093 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2095 wfProfileOut( __METHOD__
."-always_known" );
2097 wfProfileOut( __METHOD__
);
2102 * Render a forced-blue link inline; protect against double expansion of
2103 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2104 * Since this little disaster has to split off the trail text to avoid
2105 * breaking URLs in the following text without breaking trails on the
2106 * wiki links, it's been made into a horrible function.
2109 * @param $text String
2110 * @param $query Array or String
2111 * @param $trail String
2112 * @param $prefix String
2113 * @return String: HTML-wikitext mix oh yuck
2115 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2116 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2118 if ( is_string( $query ) ) {
2119 $query = wfCgiToArray( $query );
2121 if ( $text == '' ) {
2122 $text = htmlspecialchars( $nt->getPrefixedText() );
2125 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2127 return $this->armorLinks( $link ) . $trail;
2131 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2132 * going to go through further parsing steps before inline URL expansion.
2134 * Not needed quite as much as it used to be since free links are a bit
2135 * more sensible these days. But bracketed links are still an issue.
2137 * @param $text String: more-or-less HTML
2138 * @return String: less-or-more HTML with NOPARSE bits
2140 function armorLinks( $text ) {
2141 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2142 "{$this->mUniqPrefix}NOPARSE$1", $text );
2146 * Return true if subpage links should be expanded on this page.
2149 function areSubpagesAllowed() {
2150 # Some namespaces don't allow subpages
2151 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2155 * Handle link to subpage if necessary
2157 * @param $target String: the source of the link
2158 * @param &$text String: the link text, modified as necessary
2159 * @return string the full name of the link
2162 function maybeDoSubpageLink( $target, &$text ) {
2163 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2167 * Used by doBlockLevels()
2172 function closeParagraph() {
2174 if ( $this->mLastSection
!= '' ) {
2175 $result = '</' . $this->mLastSection
. ">\n";
2177 $this->mInPre
= false;
2178 $this->mLastSection
= '';
2183 * getCommon() returns the length of the longest common substring
2184 * of both arguments, starting at the beginning of both.
2187 * @param $st1 string
2188 * @param $st2 string
2192 function getCommon( $st1, $st2 ) {
2193 $fl = strlen( $st1 );
2194 $shorter = strlen( $st2 );
2195 if ( $fl < $shorter ) {
2199 for ( $i = 0; $i < $shorter; ++
$i ) {
2200 if ( $st1[$i] != $st2[$i] ) {
2208 * These next three functions open, continue, and close the list
2209 * element appropriate to the prefix character passed into them.
2212 * @param $char string
2216 function openList( $char ) {
2217 $result = $this->closeParagraph();
2219 if ( '*' === $char ) {
2220 $result .= '<ul><li>';
2221 } elseif ( '#' === $char ) {
2222 $result .= '<ol><li>';
2223 } elseif ( ':' === $char ) {
2224 $result .= '<dl><dd>';
2225 } elseif ( ';' === $char ) {
2226 $result .= '<dl><dt>';
2227 $this->mDTopen
= true;
2229 $result = '<!-- ERR 1 -->';
2237 * @param $char String
2242 function nextItem( $char ) {
2243 if ( '*' === $char ||
'#' === $char ) {
2245 } elseif ( ':' === $char ||
';' === $char ) {
2247 if ( $this->mDTopen
) {
2250 if ( ';' === $char ) {
2251 $this->mDTopen
= true;
2252 return $close . '<dt>';
2254 $this->mDTopen
= false;
2255 return $close . '<dd>';
2258 return '<!-- ERR 2 -->';
2263 * @param $char String
2268 function closeList( $char ) {
2269 if ( '*' === $char ) {
2270 $text = '</li></ul>';
2271 } elseif ( '#' === $char ) {
2272 $text = '</li></ol>';
2273 } elseif ( ':' === $char ) {
2274 if ( $this->mDTopen
) {
2275 $this->mDTopen
= false;
2276 $text = '</dt></dl>';
2278 $text = '</dd></dl>';
2281 return '<!-- ERR 3 -->';
2288 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2290 * @param $text String
2291 * @param $linestart Boolean: whether or not this is at the start of a line.
2293 * @return string the lists rendered as HTML
2295 function doBlockLevels( $text, $linestart ) {
2296 wfProfileIn( __METHOD__
);
2298 # Parsing through the text line by line. The main thing
2299 # happening here is handling of block-level elements p, pre,
2300 # and making lists from lines starting with * # : etc.
2302 $textLines = StringUtils
::explode( "\n", $text );
2304 $lastPrefix = $output = '';
2305 $this->mDTopen
= $inBlockElem = false;
2307 $paragraphStack = false;
2309 foreach ( $textLines as $oLine ) {
2311 if ( !$linestart ) {
2321 $lastPrefixLength = strlen( $lastPrefix );
2322 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2323 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2324 # If not in a <pre> element, scan for and figure out what prefixes are there.
2325 if ( !$this->mInPre
) {
2326 # Multiple prefixes may abut each other for nested lists.
2327 $prefixLength = strspn( $oLine, '*#:;' );
2328 $prefix = substr( $oLine, 0, $prefixLength );
2331 # ; and : are both from definition-lists, so they're equivalent
2332 # for the purposes of determining whether or not we need to open/close
2334 $prefix2 = str_replace( ';', ':', $prefix );
2335 $t = substr( $oLine, $prefixLength );
2336 $this->mInPre
= (bool)$preOpenMatch;
2338 # Don't interpret any other prefixes in preformatted text
2340 $prefix = $prefix2 = '';
2345 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2346 # Same as the last item, so no need to deal with nesting or opening stuff
2347 $output .= $this->nextItem( substr( $prefix, -1 ) );
2348 $paragraphStack = false;
2350 if ( substr( $prefix, -1 ) === ';') {
2351 # The one nasty exception: definition lists work like this:
2352 # ; title : definition text
2353 # So we check for : in the remainder text to split up the
2354 # title and definition, without b0rking links.
2356 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2358 $output .= $term . $this->nextItem( ':' );
2361 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2362 # We need to open or close prefixes, or both.
2364 # Either open or close a level...
2365 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2366 $paragraphStack = false;
2368 # Close all the prefixes which aren't shared.
2369 while ( $commonPrefixLength < $lastPrefixLength ) {
2370 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2371 --$lastPrefixLength;
2374 # Continue the current prefix if appropriate.
2375 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2376 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2379 # Open prefixes where appropriate.
2380 while ( $prefixLength > $commonPrefixLength ) {
2381 $char = substr( $prefix, $commonPrefixLength, 1 );
2382 $output .= $this->openList( $char );
2384 if ( ';' === $char ) {
2385 # @todo FIXME: This is dupe of code above
2386 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2388 $output .= $term . $this->nextItem( ':' );
2391 ++
$commonPrefixLength;
2393 $lastPrefix = $prefix2;
2396 # If we have no prefixes, go to paragraph mode.
2397 if ( 0 == $prefixLength ) {
2398 wfProfileIn( __METHOD__
."-paragraph" );
2399 # No prefix (not in list)--go to paragraph mode
2400 # XXX: use a stack for nestable elements like span, table and div
2401 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2402 $closematch = preg_match(
2403 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2404 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2405 if ( $openmatch or $closematch ) {
2406 $paragraphStack = false;
2407 # TODO bug 5718: paragraph closed
2408 $output .= $this->closeParagraph();
2409 if ( $preOpenMatch and !$preCloseMatch ) {
2410 $this->mInPre
= true;
2412 $inBlockElem = !$closematch;
2413 } elseif ( !$inBlockElem && !$this->mInPre
) {
2414 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2416 if ( $this->mLastSection
!== 'pre' ) {
2417 $paragraphStack = false;
2418 $output .= $this->closeParagraph().'<pre>';
2419 $this->mLastSection
= 'pre';
2421 $t = substr( $t, 1 );
2424 if ( trim( $t ) === '' ) {
2425 if ( $paragraphStack ) {
2426 $output .= $paragraphStack.'<br />';
2427 $paragraphStack = false;
2428 $this->mLastSection
= 'p';
2430 if ( $this->mLastSection
!== 'p' ) {
2431 $output .= $this->closeParagraph();
2432 $this->mLastSection
= '';
2433 $paragraphStack = '<p>';
2435 $paragraphStack = '</p><p>';
2439 if ( $paragraphStack ) {
2440 $output .= $paragraphStack;
2441 $paragraphStack = false;
2442 $this->mLastSection
= 'p';
2443 } elseif ( $this->mLastSection
!== 'p' ) {
2444 $output .= $this->closeParagraph().'<p>';
2445 $this->mLastSection
= 'p';
2450 wfProfileOut( __METHOD__
."-paragraph" );
2452 # somewhere above we forget to get out of pre block (bug 785)
2453 if ( $preCloseMatch && $this->mInPre
) {
2454 $this->mInPre
= false;
2456 if ( $paragraphStack === false ) {
2460 while ( $prefixLength ) {
2461 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2464 if ( $this->mLastSection
!= '' ) {
2465 $output .= '</' . $this->mLastSection
. '>';
2466 $this->mLastSection
= '';
2469 wfProfileOut( __METHOD__
);
2474 * Split up a string on ':', ignoring any occurrences inside tags
2475 * to prevent illegal overlapping.
2477 * @param $str String the string to split
2478 * @param &$before String set to everything before the ':'
2479 * @param &$after String set to everything after the ':'
2480 * @throws MWException
2481 * @return String the position of the ':', or false if none found
2483 function findColonNoLinks( $str, &$before, &$after ) {
2484 wfProfileIn( __METHOD__
);
2486 $pos = strpos( $str, ':' );
2487 if ( $pos === false ) {
2489 wfProfileOut( __METHOD__
);
2493 $lt = strpos( $str, '<' );
2494 if ( $lt === false ||
$lt > $pos ) {
2495 # Easy; no tag nesting to worry about
2496 $before = substr( $str, 0, $pos );
2497 $after = substr( $str, $pos+
1 );
2498 wfProfileOut( __METHOD__
);
2502 # Ugly state machine to walk through avoiding tags.
2503 $state = self
::COLON_STATE_TEXT
;
2505 $len = strlen( $str );
2506 for( $i = 0; $i < $len; $i++
) {
2510 # (Using the number is a performance hack for common cases)
2511 case 0: # self::COLON_STATE_TEXT:
2514 # Could be either a <start> tag or an </end> tag
2515 $state = self
::COLON_STATE_TAGSTART
;
2518 if ( $stack == 0 ) {
2520 $before = substr( $str, 0, $i );
2521 $after = substr( $str, $i +
1 );
2522 wfProfileOut( __METHOD__
);
2525 # Embedded in a tag; don't break it.
2528 # Skip ahead looking for something interesting
2529 $colon = strpos( $str, ':', $i );
2530 if ( $colon === false ) {
2531 # Nothing else interesting
2532 wfProfileOut( __METHOD__
);
2535 $lt = strpos( $str, '<', $i );
2536 if ( $stack === 0 ) {
2537 if ( $lt === false ||
$colon < $lt ) {
2539 $before = substr( $str, 0, $colon );
2540 $after = substr( $str, $colon +
1 );
2541 wfProfileOut( __METHOD__
);
2545 if ( $lt === false ) {
2546 # Nothing else interesting to find; abort!
2547 # We're nested, but there's no close tags left. Abort!
2550 # Skip ahead to next tag start
2552 $state = self
::COLON_STATE_TAGSTART
;
2555 case 1: # self::COLON_STATE_TAG:
2560 $state = self
::COLON_STATE_TEXT
;
2563 # Slash may be followed by >?
2564 $state = self
::COLON_STATE_TAGSLASH
;
2570 case 2: # self::COLON_STATE_TAGSTART:
2573 $state = self
::COLON_STATE_CLOSETAG
;
2576 $state = self
::COLON_STATE_COMMENT
;
2579 # Illegal early close? This shouldn't happen D:
2580 $state = self
::COLON_STATE_TEXT
;
2583 $state = self
::COLON_STATE_TAG
;
2586 case 3: # self::COLON_STATE_CLOSETAG:
2591 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2592 wfProfileOut( __METHOD__
);
2595 $state = self
::COLON_STATE_TEXT
;
2598 case self
::COLON_STATE_TAGSLASH
:
2600 # Yes, a self-closed tag <blah/>
2601 $state = self
::COLON_STATE_TEXT
;
2603 # Probably we're jumping the gun, and this is an attribute
2604 $state = self
::COLON_STATE_TAG
;
2607 case 5: # self::COLON_STATE_COMMENT:
2609 $state = self
::COLON_STATE_COMMENTDASH
;
2612 case self
::COLON_STATE_COMMENTDASH
:
2614 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2616 $state = self
::COLON_STATE_COMMENT
;
2619 case self
::COLON_STATE_COMMENTDASHDASH
:
2621 $state = self
::COLON_STATE_TEXT
;
2623 $state = self
::COLON_STATE_COMMENT
;
2627 throw new MWException( "State machine error in " . __METHOD__
);
2631 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2632 wfProfileOut( __METHOD__
);
2635 wfProfileOut( __METHOD__
);
2640 * Return value of a magic variable (like PAGENAME)
2644 * @param $index integer
2645 * @param bool|\PPFrame $frame
2647 * @throws MWException
2650 function getVariableValue( $index, $frame = false ) {
2651 global $wgContLang, $wgSitename, $wgServer;
2652 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2654 if ( is_null( $this->mTitle
) ) {
2655 // If no title set, bad things are going to happen
2656 // later. Title should always be set since this
2657 // should only be called in the middle of a parse
2658 // operation (but the unit-tests do funky stuff)
2659 throw new MWException( __METHOD__
. ' Should only be '
2660 . ' called while parsing (no title set)' );
2664 * Some of these require message or data lookups and can be
2665 * expensive to check many times.
2667 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2668 if ( isset( $this->mVarCache
[$index] ) ) {
2669 return $this->mVarCache
[$index];
2673 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2674 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2677 global $wgLocaltimezone;
2678 if ( isset( $wgLocaltimezone ) ) {
2679 $oldtz = date_default_timezone_get();
2680 date_default_timezone_set( $wgLocaltimezone );
2683 $localTimestamp = date( 'YmdHis', $ts );
2684 $localMonth = date( 'm', $ts );
2685 $localMonth1 = date( 'n', $ts );
2686 $localMonthName = date( 'n', $ts );
2687 $localDay = date( 'j', $ts );
2688 $localDay2 = date( 'd', $ts );
2689 $localDayOfWeek = date( 'w', $ts );
2690 $localWeek = date( 'W', $ts );
2691 $localYear = date( 'Y', $ts );
2692 $localHour = date( 'H', $ts );
2693 if ( isset( $wgLocaltimezone ) ) {
2694 date_default_timezone_set( $oldtz );
2697 $pageLang = $this->getFunctionLang();
2700 case 'currentmonth':
2701 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2703 case 'currentmonth1':
2704 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2706 case 'currentmonthname':
2707 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2709 case 'currentmonthnamegen':
2710 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2712 case 'currentmonthabbrev':
2713 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2716 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2719 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2722 $value = $pageLang->formatNum( $localMonth );
2725 $value = $pageLang->formatNum( $localMonth1 );
2727 case 'localmonthname':
2728 $value = $pageLang->getMonthName( $localMonthName );
2730 case 'localmonthnamegen':
2731 $value = $pageLang->getMonthNameGen( $localMonthName );
2733 case 'localmonthabbrev':
2734 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2737 $value = $pageLang->formatNum( $localDay );
2740 $value = $pageLang->formatNum( $localDay2 );
2743 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2746 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2748 case 'fullpagename':
2749 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2751 case 'fullpagenamee':
2752 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2755 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2757 case 'subpagenamee':
2758 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2760 case 'basepagename':
2761 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2763 case 'basepagenamee':
2764 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2766 case 'talkpagename':
2767 if ( $this->mTitle
->canTalk() ) {
2768 $talkPage = $this->mTitle
->getTalkPage();
2769 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2774 case 'talkpagenamee':
2775 if ( $this->mTitle
->canTalk() ) {
2776 $talkPage = $this->mTitle
->getTalkPage();
2777 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2782 case 'subjectpagename':
2783 $subjPage = $this->mTitle
->getSubjectPage();
2784 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2786 case 'subjectpagenamee':
2787 $subjPage = $this->mTitle
->getSubjectPage();
2788 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2790 case 'pageid': // requested in bug 23427
2791 $pageid = $this->getTitle()->getArticleId();
2792 if( $pageid == 0 ) {
2793 # 0 means the page doesn't exist in the database,
2794 # which means the user is previewing a new page.
2795 # The vary-revision flag must be set, because the magic word
2796 # will have a different value once the page is saved.
2797 $this->mOutput
->setFlag( 'vary-revision' );
2798 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2800 $value = $pageid ?
$pageid : null;
2803 # Let the edit saving system know we should parse the page
2804 # *after* a revision ID has been assigned.
2805 $this->mOutput
->setFlag( 'vary-revision' );
2806 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2807 $value = $this->mRevisionId
;
2810 # Let the edit saving system know we should parse the page
2811 # *after* a revision ID has been assigned. This is for null edits.
2812 $this->mOutput
->setFlag( 'vary-revision' );
2813 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2814 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2816 case 'revisionday2':
2817 # Let the edit saving system know we should parse the page
2818 # *after* a revision ID has been assigned. This is for null edits.
2819 $this->mOutput
->setFlag( 'vary-revision' );
2820 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2821 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2823 case 'revisionmonth':
2824 # Let the edit saving system know we should parse the page
2825 # *after* a revision ID has been assigned. This is for null edits.
2826 $this->mOutput
->setFlag( 'vary-revision' );
2827 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2828 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2830 case 'revisionmonth1':
2831 # Let the edit saving system know we should parse the page
2832 # *after* a revision ID has been assigned. This is for null edits.
2833 $this->mOutput
->setFlag( 'vary-revision' );
2834 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2835 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2837 case 'revisionyear':
2838 # Let the edit saving system know we should parse the page
2839 # *after* a revision ID has been assigned. This is for null edits.
2840 $this->mOutput
->setFlag( 'vary-revision' );
2841 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2842 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2844 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2849 $value = $this->getRevisionTimestamp();
2851 case 'revisionuser':
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__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2856 $value = $this->getRevisionUser();
2859 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2862 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2864 case 'namespacenumber':
2865 $value = $this->mTitle
->getNamespace();
2868 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2871 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2873 case 'subjectspace':
2874 $value = $this->mTitle
->getSubjectNsText();
2876 case 'subjectspacee':
2877 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2879 case 'currentdayname':
2880 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2883 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2886 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2889 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2892 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2893 # int to remove the padding
2894 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2897 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2899 case 'localdayname':
2900 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2903 $value = $pageLang->formatNum( $localYear, true );
2906 $value = $pageLang->time( $localTimestamp, false, false );
2909 $value = $pageLang->formatNum( $localHour, true );
2912 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2913 # int to remove the padding
2914 $value = $pageLang->formatNum( (int)$localWeek );
2917 $value = $pageLang->formatNum( $localDayOfWeek );
2919 case 'numberofarticles':
2920 $value = $pageLang->formatNum( SiteStats
::articles() );
2922 case 'numberoffiles':
2923 $value = $pageLang->formatNum( SiteStats
::images() );
2925 case 'numberofusers':
2926 $value = $pageLang->formatNum( SiteStats
::users() );
2928 case 'numberofactiveusers':
2929 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2931 case 'numberofpages':
2932 $value = $pageLang->formatNum( SiteStats
::pages() );
2934 case 'numberofadmins':
2935 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2937 case 'numberofedits':
2938 $value = $pageLang->formatNum( SiteStats
::edits() );
2940 case 'numberofviews':
2941 global $wgDisableCounters;
2942 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2944 case 'currenttimestamp':
2945 $value = wfTimestamp( TS_MW
, $ts );
2947 case 'localtimestamp':
2948 $value = $localTimestamp;
2950 case 'currentversion':
2951 $value = SpecialVersion
::getVersion();
2954 return $wgArticlePath;
2960 $serverParts = wfParseUrl( $wgServer );
2961 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2963 return $wgScriptPath;
2965 return $wgStylePath;
2966 case 'directionmark':
2967 return $pageLang->getDirMark();
2968 case 'contentlanguage':
2969 global $wgLanguageCode;
2970 return $wgLanguageCode;
2973 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2981 $this->mVarCache
[$index] = $value;
2988 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2992 function initialiseVariables() {
2993 wfProfileIn( __METHOD__
);
2994 $variableIDs = MagicWord
::getVariableIDs();
2995 $substIDs = MagicWord
::getSubstIDs();
2997 $this->mVariables
= new MagicWordArray( $variableIDs );
2998 $this->mSubstWords
= new MagicWordArray( $substIDs );
2999 wfProfileOut( __METHOD__
);
3003 * Preprocess some wikitext and return the document tree.
3004 * This is the ghost of replace_variables().
3006 * @param $text String: The text to parse
3007 * @param $flags Integer: bitwise combination of:
3008 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
3009 * included. Default is to assume a direct page view.
3011 * The generated DOM tree must depend only on the input text and the flags.
3012 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3014 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3015 * change in the DOM tree for a given text, must be passed through the section identifier
3016 * in the section edit link and thus back to extractSections().
3018 * The output of this function is currently only cached in process memory, but a persistent
3019 * cache may be implemented at a later date which takes further advantage of these strict
3020 * dependency requirements.
3026 function preprocessToDom( $text, $flags = 0 ) {
3027 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3032 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3038 public static function splitWhitespace( $s ) {
3039 $ltrimmed = ltrim( $s );
3040 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3041 $trimmed = rtrim( $ltrimmed );
3042 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3044 $w2 = substr( $ltrimmed, -$diff );
3048 return array( $w1, $trimmed, $w2 );
3052 * Replace magic variables, templates, and template arguments
3053 * with the appropriate text. Templates are substituted recursively,
3054 * taking care to avoid infinite loops.
3056 * Note that the substitution depends on value of $mOutputType:
3057 * self::OT_WIKI: only {{subst:}} templates
3058 * self::OT_PREPROCESS: templates but not extension tags
3059 * self::OT_HTML: all templates and extension tags
3061 * @param $text String the text to transform
3062 * @param $frame PPFrame Object describing the arguments passed to the template.
3063 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3064 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3065 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3070 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3071 # Is there any text? Also, Prevent too big inclusions!
3072 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3075 wfProfileIn( __METHOD__
);
3077 if ( $frame === false ) {
3078 $frame = $this->getPreprocessor()->newFrame();
3079 } elseif ( !( $frame instanceof PPFrame
) ) {
3080 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3081 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3084 $dom = $this->preprocessToDom( $text );
3085 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3086 $text = $frame->expand( $dom, $flags );
3088 wfProfileOut( __METHOD__
);
3093 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3095 * @param $args array
3099 static function createAssocArgs( $args ) {
3100 $assocArgs = array();
3102 foreach ( $args as $arg ) {
3103 $eqpos = strpos( $arg, '=' );
3104 if ( $eqpos === false ) {
3105 $assocArgs[$index++
] = $arg;
3107 $name = trim( substr( $arg, 0, $eqpos ) );
3108 $value = trim( substr( $arg, $eqpos+
1 ) );
3109 if ( $value === false ) {
3112 if ( $name !== false ) {
3113 $assocArgs[$name] = $value;
3122 * Warn the user when a parser limitation is reached
3123 * Will warn at most once the user per limitation type
3125 * @param $limitationType String: should be one of:
3126 * 'expensive-parserfunction' (corresponding messages:
3127 * 'expensive-parserfunction-warning',
3128 * 'expensive-parserfunction-category')
3129 * 'post-expand-template-argument' (corresponding messages:
3130 * 'post-expand-template-argument-warning',
3131 * 'post-expand-template-argument-category')
3132 * 'post-expand-template-inclusion' (corresponding messages:
3133 * 'post-expand-template-inclusion-warning',
3134 * 'post-expand-template-inclusion-category')
3135 * @param $current int|null Current value
3136 * @param $max int|null Maximum allowed, when an explicit limit has been
3137 * exceeded, provide the values (optional)
3139 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3140 # does no harm if $current and $max are present but are unnecessary for the message
3141 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3142 ->inContentLanguage()->escaped();
3143 $this->mOutput
->addWarning( $warning );
3144 $this->addTrackingCategory( "$limitationType-category" );
3148 * Return the text of a template, after recursively
3149 * replacing any variables or templates within the template.
3151 * @param $piece Array: the parts of the template
3152 * $piece['title']: the title, i.e. the part before the |
3153 * $piece['parts']: the parameter array
3154 * $piece['lineStart']: whether the brace was at the start of a line
3155 * @param $frame PPFrame The current frame, contains template arguments
3156 * @throws MWException
3157 * @return String: the text of the template
3160 function braceSubstitution( $piece, $frame ) {
3162 wfProfileIn( __METHOD__
);
3163 wfProfileIn( __METHOD__
.'-setup' );
3166 $found = false; # $text has been filled
3167 $nowiki = false; # wiki markup in $text should be escaped
3168 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3169 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3170 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3171 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3173 # Title object, where $text came from
3176 # $part1 is the bit before the first |, and must contain only title characters.
3177 # Various prefixes will be stripped from it later.
3178 $titleWithSpaces = $frame->expand( $piece['title'] );
3179 $part1 = trim( $titleWithSpaces );
3182 # Original title text preserved for various purposes
3183 $originalTitle = $part1;
3185 # $args is a list of argument nodes, starting from index 0, not including $part1
3186 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3187 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3188 wfProfileOut( __METHOD__
.'-setup' );
3190 $titleProfileIn = null; // profile templates
3193 wfProfileIn( __METHOD__
.'-modifiers' );
3196 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3198 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3199 # Decide whether to expand template or keep wikitext as-is.
3200 if ( $this->ot
['wiki'] ) {
3201 if ( $substMatch === false ) {
3202 $literal = true; # literal when in PST with no prefix
3204 $literal = false; # expand when in PST with subst: or safesubst:
3207 if ( $substMatch == 'subst' ) {
3208 $literal = true; # literal when not in PST with plain subst:
3210 $literal = false; # expand when not in PST with safesubst: or no prefix
3214 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3221 if ( !$found && $args->getLength() == 0 ) {
3222 $id = $this->mVariables
->matchStartToEnd( $part1 );
3223 if ( $id !== false ) {
3224 $text = $this->getVariableValue( $id, $frame );
3225 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3226 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3232 # MSG, MSGNW and RAW
3235 $mwMsgnw = MagicWord
::get( 'msgnw' );
3236 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3239 # Remove obsolete MSG:
3240 $mwMsg = MagicWord
::get( 'msg' );
3241 $mwMsg->matchStartAndRemove( $part1 );
3245 $mwRaw = MagicWord
::get( 'raw' );
3246 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3247 $forceRawInterwiki = true;
3250 wfProfileOut( __METHOD__
.'-modifiers' );
3254 wfProfileIn( __METHOD__
. '-pfunc' );
3256 $colonPos = strpos( $part1, ':' );
3257 if ( $colonPos !== false ) {
3258 # Case sensitive functions
3259 $function = substr( $part1, 0, $colonPos );
3260 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3261 $function = $this->mFunctionSynonyms
[1][$function];
3263 # Case insensitive functions
3264 $function = $wgContLang->lc( $function );
3265 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3266 $function = $this->mFunctionSynonyms
[0][$function];
3272 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3273 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3274 $initialArgs = array( &$this );
3275 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3276 if ( $flags & SFH_OBJECT_ARGS
) {
3277 # Add a frame parameter, and pass the arguments as an array
3278 $allArgs = $initialArgs;
3279 $allArgs[] = $frame;
3280 for ( $i = 0; $i < $args->getLength(); $i++
) {
3281 $funcArgs[] = $args->item( $i );
3283 $allArgs[] = $funcArgs;
3285 # Convert arguments to plain text
3286 for ( $i = 0; $i < $args->getLength(); $i++
) {
3287 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3289 $allArgs = array_merge( $initialArgs, $funcArgs );
3292 # Workaround for PHP bug 35229 and similar
3293 if ( !is_callable( $callback ) ) {
3294 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3295 wfProfileOut( __METHOD__
. '-pfunc' );
3296 wfProfileOut( __METHOD__
);
3297 throw new MWException( "Tag hook for $function is not callable\n" );
3299 $result = call_user_func_array( $callback, $allArgs );
3302 $preprocessFlags = 0;
3304 if ( is_array( $result ) ) {
3305 if ( isset( $result[0] ) ) {
3307 unset( $result[0] );
3310 # Extract flags into the local scope
3311 # This allows callers to set flags such as nowiki, found, etc.
3317 $text = $this->preprocessToDom( $text, $preprocessFlags );
3320 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3323 wfProfileOut( __METHOD__
. '-pfunc' );
3326 # Finish mangling title and then check for loops.
3327 # Set $title to a Title object and $titleText to the PDBK
3330 # Split the title into page and subpage
3332 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3333 if ( $subpage !== '' ) {
3334 $ns = $this->mTitle
->getNamespace();
3336 $title = Title
::newFromText( $part1, $ns );
3338 $titleText = $title->getPrefixedText();
3339 # Check for language variants if the template is not found
3340 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3341 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3343 # Do recursion depth check
3344 $limit = $this->mOptions
->getMaxTemplateDepth();
3345 if ( $frame->depth
>= $limit ) {
3347 $text = '<span class="error">'
3348 . wfMessage( 'parser-template-recursion-depth-warning' )
3349 ->numParams( $limit )->inContentLanguage()->text()
3355 # Load from database
3356 if ( !$found && $title ) {
3357 if ( !Profiler
::instance()->isPersistent() ) {
3358 # Too many unique items can kill profiling DBs/collectors
3359 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3360 wfProfileIn( $titleProfileIn ); // template in
3362 wfProfileIn( __METHOD__
. '-loadtpl' );
3363 if ( !$title->isExternal() ) {
3364 if ( $title->isSpecialPage()
3365 && $this->mOptions
->getAllowSpecialInclusion()
3366 && $this->ot
['html'] )
3368 // Pass the template arguments as URL parameters.
3369 // "uselang" will have no effect since the Language object
3370 // is forced to the one defined in ParserOptions.
3371 $pageArgs = array();
3372 for ( $i = 0; $i < $args->getLength(); $i++
) {
3373 $bits = $args->item( $i )->splitArg();
3374 if ( strval( $bits['index'] ) === '' ) {
3375 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3376 $value = trim( $frame->expand( $bits['value'] ) );
3377 $pageArgs[$name] = $value;
3381 // Create a new context to execute the special page
3382 $context = new RequestContext
;
3383 $context->setTitle( $title );
3384 $context->setRequest( new FauxRequest( $pageArgs ) );
3385 $context->setUser( $this->getUser() );
3386 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3387 $ret = SpecialPageFactory
::capturePath( $title, $context );
3389 $text = $context->getOutput()->getHTML();
3390 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3393 $this->disableCache();
3395 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3396 $found = false; # access denied
3397 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3399 list( $text, $title ) = $this->getTemplateDom( $title );
3400 if ( $text !== false ) {
3406 # If the title is valid but undisplayable, make a link to it
3407 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3408 $text = "[[:$titleText]]";
3411 } elseif ( $title->isTrans() ) {
3412 # Interwiki transclusion
3413 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3414 $text = $this->interwikiTransclude( $title, 'render' );
3417 $text = $this->interwikiTransclude( $title, 'raw' );
3418 # Preprocess it like a template
3419 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3425 # Do infinite loop check
3426 # This has to be done after redirect resolution to avoid infinite loops via redirects
3427 if ( !$frame->loopCheck( $title ) ) {
3429 $text = '<span class="error">'
3430 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3432 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3434 wfProfileOut( __METHOD__
. '-loadtpl' );
3437 # If we haven't found text to substitute by now, we're done
3438 # Recover the source wikitext and return it
3440 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3441 if ( $titleProfileIn ) {
3442 wfProfileOut( $titleProfileIn ); // template out
3444 wfProfileOut( __METHOD__
);
3445 return array( 'object' => $text );
3448 # Expand DOM-style return values in a child frame
3449 if ( $isChildObj ) {
3450 # Clean up argument array
3451 $newFrame = $frame->newChild( $args, $title );
3454 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3455 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3456 # Expansion is eligible for the empty-frame cache
3457 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3458 $text = $this->mTplExpandCache
[$titleText];
3460 $text = $newFrame->expand( $text );
3461 $this->mTplExpandCache
[$titleText] = $text;
3464 # Uncached expansion
3465 $text = $newFrame->expand( $text );
3468 if ( $isLocalObj && $nowiki ) {
3469 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3470 $isLocalObj = false;
3473 if ( $titleProfileIn ) {
3474 wfProfileOut( $titleProfileIn ); // template out
3477 # Replace raw HTML by a placeholder
3479 $text = $this->insertStripItem( $text );
3480 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3481 # Escape nowiki-style return values
3482 $text = wfEscapeWikiText( $text );
3483 } elseif ( is_string( $text )
3484 && !$piece['lineStart']
3485 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3487 # Bug 529: if the template begins with a table or block-level
3488 # element, it should be treated as beginning a new line.
3489 # This behaviour is somewhat controversial.
3490 $text = "\n" . $text;
3493 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3494 # Error, oversize inclusion
3495 if ( $titleText !== false ) {
3496 # Make a working, properly escaped link if possible (bug 23588)
3497 $text = "[[:$titleText]]";
3499 # This will probably not be a working link, but at least it may
3500 # provide some hint of where the problem is
3501 preg_replace( '/^:/', '', $originalTitle );
3502 $text = "[[:$originalTitle]]";
3504 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3505 $this->limitationWarn( 'post-expand-template-inclusion' );
3508 if ( $isLocalObj ) {
3509 $ret = array( 'object' => $text );
3511 $ret = array( 'text' => $text );
3514 wfProfileOut( __METHOD__
);
3519 * Get the semi-parsed DOM representation of a template with a given title,
3520 * and its redirect destination title. Cached.
3522 * @param $title Title
3526 function getTemplateDom( $title ) {
3527 $cacheTitle = $title;
3528 $titleText = $title->getPrefixedDBkey();
3530 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3531 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3532 $title = Title
::makeTitle( $ns, $dbk );
3533 $titleText = $title->getPrefixedDBkey();
3535 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3536 return array( $this->mTplDomCache
[$titleText], $title );
3539 # Cache miss, go to the database
3540 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3542 if ( $text === false ) {
3543 $this->mTplDomCache
[$titleText] = false;
3544 return array( false, $title );
3547 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3548 $this->mTplDomCache
[ $titleText ] = $dom;
3550 if ( !$title->equals( $cacheTitle ) ) {
3551 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3552 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3555 return array( $dom, $title );
3559 * Fetch the unparsed text of a template and register a reference to it.
3560 * @param Title $title
3561 * @return Array ( string or false, Title )
3563 function fetchTemplateAndTitle( $title ) {
3564 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3565 $stuff = call_user_func( $templateCb, $title, $this );
3566 $text = $stuff['text'];
3567 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3568 if ( isset( $stuff['deps'] ) ) {
3569 foreach ( $stuff['deps'] as $dep ) {
3570 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3573 return array( $text, $finalTitle );
3577 * Fetch the unparsed text of a template and register a reference to it.
3578 * @param Title $title
3579 * @return mixed string or false
3581 function fetchTemplate( $title ) {
3582 $rv = $this->fetchTemplateAndTitle( $title );
3587 * Static function to get a template
3588 * Can be overridden via ParserOptions::setTemplateCallback().
3590 * @param $title Title
3591 * @param $parser Parser
3595 static function statelessFetchTemplate( $title, $parser = false ) {
3596 $text = $skip = false;
3597 $finalTitle = $title;
3600 # Loop to fetch the article, with up to 1 redirect
3601 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3602 # Give extensions a chance to select the revision instead
3603 $id = false; # Assume current
3604 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3605 array( $parser, $title, &$skip, &$id ) );
3611 'page_id' => $title->getArticleID(),
3618 ? Revision
::newFromId( $id )
3619 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3620 $rev_id = $rev ?
$rev->getId() : 0;
3621 # If there is no current revision, there is no page
3622 if ( $id === false && !$rev ) {
3623 $linkCache = LinkCache
::singleton();
3624 $linkCache->addBadLinkObj( $title );
3629 'page_id' => $title->getArticleID(),
3630 'rev_id' => $rev_id );
3631 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3632 # We fetched a rev from a different title; register it too...
3634 'title' => $rev->getTitle(),
3635 'page_id' => $rev->getPage(),
3636 'rev_id' => $rev_id );
3640 $content = $rev->getContent();
3641 $text = $content ?
$content->getWikitextForTransclusion() : null;
3643 if ( $text === false ||
$text === null ) {
3647 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3649 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3650 if ( !$message->exists() ) {
3654 $content = $message->content();
3655 $text = $message->plain();
3663 $finalTitle = $title;
3664 $title = $content->getRedirectTarget();
3668 'finalTitle' => $finalTitle,
3673 * Fetch a file and its title and register a reference to it.
3674 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3675 * @param Title $title
3676 * @param Array $options Array of options to RepoGroup::findFile
3679 function fetchFile( $title, $options = array() ) {
3680 $res = $this->fetchFileAndTitle( $title, $options );
3685 * Fetch a file and its title and register a reference to it.
3686 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3687 * @param Title $title
3688 * @param Array $options Array of options to RepoGroup::findFile
3689 * @return Array ( File or false, Title of file )
3691 function fetchFileAndTitle( $title, $options = array() ) {
3692 if ( isset( $options['broken'] ) ) {
3693 $file = false; // broken thumbnail forced by hook
3694 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3695 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3696 } else { // get by (name,timestamp)
3697 $file = wfFindFile( $title, $options );
3699 $time = $file ?
$file->getTimestamp() : false;
3700 $sha1 = $file ?
$file->getSha1() : false;
3701 # Register the file as a dependency...
3702 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3703 if ( $file && !$title->equals( $file->getTitle() ) ) {
3704 # Update fetched file title
3705 $title = $file->getTitle();
3706 if ( is_null( $file->getRedirectedTitle() ) ) {
3707 # This file was not a redirect, but the title does not match.
3708 # Register under the new name because otherwise the link will
3710 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3713 return array( $file, $title );
3717 * Transclude an interwiki link.
3719 * @param $title Title
3724 function interwikiTransclude( $title, $action ) {
3725 global $wgEnableScaryTranscluding;
3727 if ( !$wgEnableScaryTranscluding ) {
3728 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
3731 $url = $title->getFullUrl( "action=$action" );
3733 if ( strlen( $url ) > 255 ) {
3734 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3736 return $this->fetchScaryTemplateMaybeFromCache( $url );
3740 * @param $url string
3741 * @return Mixed|String
3743 function fetchScaryTemplateMaybeFromCache( $url ) {
3744 global $wgTranscludeCacheExpiry;
3745 $dbr = wfGetDB( DB_SLAVE
);
3746 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3747 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3748 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3750 return $obj->tc_contents
;
3753 $req = MWHttpRequest
::factory( $url );
3754 $status = $req->execute(); // Status object
3755 if ( $status->isOK() ) {
3756 $text = $req->getContent();
3757 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3758 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3760 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3763 $dbw = wfGetDB( DB_MASTER
);
3764 $dbw->replace( 'transcache', array('tc_url'), array(
3766 'tc_time' => $dbw->timestamp( time() ),
3767 'tc_contents' => $text)
3773 * Triple brace replacement -- used for template arguments
3776 * @param $piece array
3777 * @param $frame PPFrame
3781 function argSubstitution( $piece, $frame ) {
3782 wfProfileIn( __METHOD__
);
3785 $parts = $piece['parts'];
3786 $nameWithSpaces = $frame->expand( $piece['title'] );
3787 $argName = trim( $nameWithSpaces );
3789 $text = $frame->getArgument( $argName );
3790 if ( $text === false && $parts->getLength() > 0
3794 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3797 # No match in frame, use the supplied default
3798 $object = $parts->item( 0 )->getChildren();
3800 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3801 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3802 $this->limitationWarn( 'post-expand-template-argument' );
3805 if ( $text === false && $object === false ) {
3807 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3809 if ( $error !== false ) {
3812 if ( $object !== false ) {
3813 $ret = array( 'object' => $object );
3815 $ret = array( 'text' => $text );
3818 wfProfileOut( __METHOD__
);
3823 * Return the text to be used for a given extension tag.
3824 * This is the ghost of strip().
3826 * @param $params array Associative array of parameters:
3827 * name PPNode for the tag name
3828 * attr PPNode for unparsed text where tag attributes are thought to be
3829 * attributes Optional associative array of parsed attributes
3830 * inner Contents of extension element
3831 * noClose Original text did not have a close tag
3832 * @param $frame PPFrame
3834 * @throws MWException
3837 function extensionSubstitution( $params, $frame ) {
3838 $name = $frame->expand( $params['name'] );
3839 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3840 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3841 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3843 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3844 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3845 if ( $isFunctionTag ) {
3846 $markerType = 'none';
3848 $markerType = 'general';
3850 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3851 $name = strtolower( $name );
3852 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3853 if ( isset( $params['attributes'] ) ) {
3854 $attributes = $attributes +
$params['attributes'];
3857 if ( isset( $this->mTagHooks
[$name] ) ) {
3858 # Workaround for PHP bug 35229 and similar
3859 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3860 throw new MWException( "Tag hook for $name is not callable\n" );
3862 $output = call_user_func_array( $this->mTagHooks
[$name],
3863 array( $content, $attributes, $this, $frame ) );
3864 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3865 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3866 if ( !is_callable( $callback ) ) {
3867 throw new MWException( "Tag hook for $name is not callable\n" );
3870 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3872 $output = '<span class="error">Invalid tag extension name: ' .
3873 htmlspecialchars( $name ) . '</span>';
3876 if ( is_array( $output ) ) {
3877 # Extract flags to local scope (to override $markerType)
3879 $output = $flags[0];
3884 if ( is_null( $attrText ) ) {
3887 if ( isset( $params['attributes'] ) ) {
3888 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3889 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3890 htmlspecialchars( $attrValue ) . '"';
3893 if ( $content === null ) {
3894 $output = "<$name$attrText/>";
3896 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3897 $output = "<$name$attrText>$content$close";
3901 if ( $markerType === 'none' ) {
3903 } elseif ( $markerType === 'nowiki' ) {
3904 $this->mStripState
->addNoWiki( $marker, $output );
3905 } elseif ( $markerType === 'general' ) {
3906 $this->mStripState
->addGeneral( $marker, $output );
3908 throw new MWException( __METHOD__
.': invalid marker type' );
3914 * Increment an include size counter
3916 * @param $type String: the type of expansion
3917 * @param $size Integer: the size of the text
3918 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3920 function incrementIncludeSize( $type, $size ) {
3921 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3924 $this->mIncludeSizes
[$type] +
= $size;
3930 * Increment the expensive function count
3932 * @return Boolean: false if the limit has been exceeded
3934 function incrementExpensiveFunctionCount() {
3935 $this->mExpensiveFunctionCount++
;
3936 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3940 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3941 * Fills $this->mDoubleUnderscores, returns the modified text
3943 * @param $text string
3947 function doDoubleUnderscore( $text ) {
3948 wfProfileIn( __METHOD__
);
3950 # The position of __TOC__ needs to be recorded
3951 $mw = MagicWord
::get( 'toc' );
3952 if ( $mw->match( $text ) ) {
3953 $this->mShowToc
= true;
3954 $this->mForceTocPosition
= true;
3956 # Set a placeholder. At the end we'll fill it in with the TOC.
3957 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3959 # Only keep the first one.
3960 $text = $mw->replace( '', $text );
3963 # Now match and remove the rest of them
3964 $mwa = MagicWord
::getDoubleUnderscoreArray();
3965 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3967 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3968 $this->mOutput
->mNoGallery
= true;
3970 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3971 $this->mShowToc
= false;
3973 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3974 $this->addTrackingCategory( 'hidden-category-category' );
3976 # (bug 8068) Allow control over whether robots index a page.
3978 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3979 # is not desirable, the last one on the page should win.
3980 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3981 $this->mOutput
->setIndexPolicy( 'noindex' );
3982 $this->addTrackingCategory( 'noindex-category' );
3984 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3985 $this->mOutput
->setIndexPolicy( 'index' );
3986 $this->addTrackingCategory( 'index-category' );
3989 # Cache all double underscores in the database
3990 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3991 $this->mOutput
->setProperty( $key, '' );
3994 wfProfileOut( __METHOD__
);
3999 * Add a tracking category, getting the title from a system message,
4000 * or print a debug message if the title is invalid.
4002 * @param $msg String: message key
4003 * @return Boolean: whether the addition was successful
4005 public function addTrackingCategory( $msg ) {
4006 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4007 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
4010 // Important to parse with correct title (bug 31469)
4011 $cat = wfMessage( $msg )
4012 ->title( $this->getTitle() )
4013 ->inContentLanguage()
4016 # Allow tracking categories to be disabled by setting them to "-"
4017 if ( $cat === '-' ) {
4021 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4022 if ( $containerCategory ) {
4023 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4026 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
4032 * This function accomplishes several tasks:
4033 * 1) Auto-number headings if that option is enabled
4034 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4035 * 3) Add a Table of contents on the top for users who have enabled the option
4036 * 4) Auto-anchor headings
4038 * It loops through all headlines, collects the necessary data, then splits up the
4039 * string and re-inserts the newly formatted headlines.
4041 * @param $text String
4042 * @param $origText String: original, untouched wikitext
4043 * @param $isMain Boolean
4044 * @return mixed|string
4047 function formatHeadings( $text, $origText, $isMain=true ) {
4048 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4050 # Inhibit editsection links if requested in the page
4051 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4052 $maybeShowEditLink = $showEditLink = false;
4054 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4055 $showEditLink = $this->mOptions
->getEditSection();
4057 if ( $showEditLink ) {
4058 $this->mOutput
->setEditSectionTokens( true );
4061 # Get all headlines for numbering them and adding funky stuff like [edit]
4062 # links - this is for later, but we need the number of headlines right now
4064 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4066 # if there are fewer than 4 headlines in the article, do not show TOC
4067 # unless it's been explicitly enabled.
4068 $enoughToc = $this->mShowToc
&&
4069 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4071 # Allow user to stipulate that a page should have a "new section"
4072 # link added via __NEWSECTIONLINK__
4073 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4074 $this->mOutput
->setNewSection( true );
4077 # Allow user to remove the "new section"
4078 # link via __NONEWSECTIONLINK__
4079 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4080 $this->mOutput
->hideNewSection( true );
4083 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4084 # override above conditions and always show TOC above first header
4085 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4086 $this->mShowToc
= true;
4094 # Ugh .. the TOC should have neat indentation levels which can be
4095 # passed to the skin functions. These are determined here
4099 $sublevelCount = array();
4100 $levelCount = array();
4105 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4106 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4107 $oldType = $this->mOutputType
;
4108 $this->setOutputType( self
::OT_WIKI
);
4109 $frame = $this->getPreprocessor()->newFrame();
4110 $root = $this->preprocessToDom( $origText );
4111 $node = $root->getFirstChild();
4116 foreach ( $matches[3] as $headline ) {
4117 $isTemplate = false;
4119 $sectionIndex = false;
4121 $markerMatches = array();
4122 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4123 $serial = $markerMatches[1];
4124 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4125 $isTemplate = ( $titleText != $baseTitleText );
4126 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4130 $prevlevel = $level;
4132 $level = $matches[1][$headlineCount];
4134 if ( $level > $prevlevel ) {
4135 # Increase TOC level
4137 $sublevelCount[$toclevel] = 0;
4138 if ( $toclevel<$wgMaxTocLevel ) {
4139 $prevtoclevel = $toclevel;
4140 $toc .= Linker
::tocIndent();
4143 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4144 # Decrease TOC level, find level to jump to
4146 for ( $i = $toclevel; $i > 0; $i-- ) {
4147 if ( $levelCount[$i] == $level ) {
4148 # Found last matching level
4151 } elseif ( $levelCount[$i] < $level ) {
4152 # Found first matching level below current level
4160 if ( $toclevel<$wgMaxTocLevel ) {
4161 if ( $prevtoclevel < $wgMaxTocLevel ) {
4162 # Unindent only if the previous toc level was shown :p
4163 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4164 $prevtoclevel = $toclevel;
4166 $toc .= Linker
::tocLineEnd();
4170 # No change in level, end TOC line
4171 if ( $toclevel<$wgMaxTocLevel ) {
4172 $toc .= Linker
::tocLineEnd();
4176 $levelCount[$toclevel] = $level;
4178 # count number of headlines for each level
4179 @$sublevelCount[$toclevel]++
;
4181 for( $i = 1; $i <= $toclevel; $i++
) {
4182 if ( !empty( $sublevelCount[$i] ) ) {
4186 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4191 # The safe header is a version of the header text safe to use for links
4193 # Remove link placeholders by the link text.
4194 # <!--LINK number-->
4196 # link text with suffix
4197 # Do this before unstrip since link text can contain strip markers
4198 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4200 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4201 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4203 # Strip out HTML (first regex removes any tag not allowed)
4205 # * <sup> and <sub> (bug 8393)
4208 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4210 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4211 # to allow setting directionality in toc items.
4212 $tocline = preg_replace(
4213 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
4214 array( '', '<$1>' ),
4217 $tocline = trim( $tocline );
4219 # For the anchor, strip out HTML-y stuff period
4220 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4221 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4223 # Save headline for section edit hint before it's escaped
4224 $headlineHint = $safeHeadline;
4226 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4227 # For reverse compatibility, provide an id that's
4228 # HTML4-compatible, like we used to.
4230 # It may be worth noting, academically, that it's possible for
4231 # the legacy anchor to conflict with a non-legacy headline
4232 # anchor on the page. In this case likely the "correct" thing
4233 # would be to either drop the legacy anchors or make sure
4234 # they're numbered first. However, this would require people
4235 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4236 # manually, so let's not bother worrying about it.
4237 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4238 array( 'noninitial', 'legacy' ) );
4239 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4241 if ( $legacyHeadline == $safeHeadline ) {
4242 # No reason to have both (in fact, we can't)
4243 $legacyHeadline = false;
4246 $legacyHeadline = false;
4247 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4251 # HTML names must be case-insensitively unique (bug 10721).
4252 # This does not apply to Unicode characters per
4253 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4254 # @todo FIXME: We may be changing them depending on the current locale.
4255 $arrayKey = strtolower( $safeHeadline );
4256 if ( $legacyHeadline === false ) {
4257 $legacyArrayKey = false;
4259 $legacyArrayKey = strtolower( $legacyHeadline );
4262 # count how many in assoc. array so we can track dupes in anchors
4263 if ( isset( $refers[$arrayKey] ) ) {
4264 $refers[$arrayKey]++
;
4266 $refers[$arrayKey] = 1;
4268 if ( isset( $refers[$legacyArrayKey] ) ) {
4269 $refers[$legacyArrayKey]++
;
4271 $refers[$legacyArrayKey] = 1;
4274 # Don't number the heading if it is the only one (looks silly)
4275 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4276 # the two are different if the line contains a link
4277 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4280 # Create the anchor for linking from the TOC to the section
4281 $anchor = $safeHeadline;
4282 $legacyAnchor = $legacyHeadline;
4283 if ( $refers[$arrayKey] > 1 ) {
4284 $anchor .= '_' . $refers[$arrayKey];
4286 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4287 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4289 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4290 $toc .= Linker
::tocLine( $anchor, $tocline,
4291 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4294 # Add the section to the section tree
4295 # Find the DOM node for this header
4296 while ( $node && !$isTemplate ) {
4297 if ( $node->getName() === 'h' ) {
4298 $bits = $node->splitHeading();
4299 if ( $bits['i'] == $sectionIndex ) {
4303 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4304 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4305 $node = $node->getNextSibling();
4308 'toclevel' => $toclevel,
4311 'number' => $numbering,
4312 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4313 'fromtitle' => $titleText,
4314 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4315 'anchor' => $anchor,
4318 # give headline the correct <h#> tag
4319 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4320 // Output edit section links as markers with styles that can be customized by skins
4321 if ( $isTemplate ) {
4322 # Put a T flag in the section identifier, to indicate to extractSections()
4323 # that sections inside <includeonly> should be counted.
4324 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4326 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4328 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4329 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4330 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4331 // so we don't have to worry about a user trying to input one of these markers directly.
4332 // We use a page and section attribute to stop the language converter from converting these important bits
4333 // of data, but put the headline hint inside a content block because the language converter is supposed to
4334 // be able to convert that piece of data.
4335 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4336 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4337 if ( isset($editlinkArgs[2]) ) {
4338 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4345 $head[$headlineCount] = Linker
::makeHeadline( $level,
4346 $matches['attrib'][$headlineCount], $anchor, $headline,
4347 $editlink, $legacyAnchor );
4352 $this->setOutputType( $oldType );
4354 # Never ever show TOC if no headers
4355 if ( $numVisible < 1 ) {
4360 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4361 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4363 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4364 $this->mOutput
->setTOCHTML( $toc );
4368 $this->mOutput
->setSections( $tocraw );
4371 # split up and insert constructed headlines
4372 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4375 // build an array of document sections
4376 $sections = array();
4377 foreach ( $blocks as $block ) {
4378 // $head is zero-based, sections aren't.
4379 if ( empty( $head[$i - 1] ) ) {
4380 $sections[$i] = $block;
4382 $sections[$i] = $head[$i - 1] . $block;
4386 * Send a hook, one per section.
4387 * The idea here is to be able to make section-level DIVs, but to do so in a
4388 * lower-impact, more correct way than r50769
4391 * $section : the section number
4392 * &$sectionContent : ref to the content of the section
4393 * $showEditLinks : boolean describing whether this section has an edit link
4395 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4400 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4401 // append the TOC at the beginning
4402 // Top anchor now in skin
4403 $sections[0] = $sections[0] . $toc . "\n";
4406 $full .= join( '', $sections );
4408 if ( $this->mForceTocPosition
) {
4409 return str_replace( '<!--MWTOC-->', $toc, $full );
4416 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4417 * conversion, substitting signatures, {{subst:}} templates, etc.
4419 * @param $text String: the text to transform
4420 * @param $title Title: the Title object for the current article
4421 * @param $user User: the User object describing the current user
4422 * @param $options ParserOptions: parsing options
4423 * @param $clearState Boolean: whether to clear the parser state first
4424 * @return String: the altered wiki markup
4426 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4427 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4428 $this->setUser( $user );
4433 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4434 if( $options->getPreSaveTransform() ) {
4435 $text = $this->pstPass2( $text, $user );
4437 $text = $this->mStripState
->unstripBoth( $text );
4439 $this->setUser( null ); #Reset
4445 * Pre-save transform helper function
4448 * @param $text string
4453 function pstPass2( $text, $user ) {
4454 global $wgContLang, $wgLocaltimezone;
4456 # Note: This is the timestamp saved as hardcoded wikitext to
4457 # the database, we use $wgContLang here in order to give
4458 # everyone the same signature and use the default one rather
4459 # than the one selected in each user's preferences.
4460 # (see also bug 12815)
4461 $ts = $this->mOptions
->getTimestamp();
4462 if ( isset( $wgLocaltimezone ) ) {
4463 $tz = $wgLocaltimezone;
4465 $tz = date_default_timezone_get();
4468 $unixts = wfTimestamp( TS_UNIX
, $ts );
4469 $oldtz = date_default_timezone_get();
4470 date_default_timezone_set( $tz );
4471 $ts = date( 'YmdHis', $unixts );
4472 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4474 # Allow translation of timezones through wiki. date() can return
4475 # whatever crap the system uses, localised or not, so we cannot
4476 # ship premade translations.
4477 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4478 $msg = wfMessage( $key )->inContentLanguage();
4479 if ( $msg->exists() ) {
4480 $tzMsg = $msg->text();
4483 date_default_timezone_set( $oldtz );
4485 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4487 # Variable replacement
4488 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4489 $text = $this->replaceVariables( $text );
4491 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4492 # which may corrupt this parser instance via its wfMessage()->text() call-
4495 $sigText = $this->getUserSig( $user );
4496 $text = strtr( $text, array(
4498 '~~~~' => "$sigText $d",
4502 # Context links ("pipe trick"): [[|name]] and [[name (context)|]]
4503 $tc = '[' . Title
::legalChars() . ']';
4504 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4506 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4507 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4508 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4509 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4511 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4512 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4513 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4514 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4516 $t = $this->mTitle
->getText();
4518 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4519 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4520 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4521 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4523 # if there's no context, don't bother duplicating the title
4524 $text = preg_replace( $p2, '[[\\1]]', $text );
4527 # Trim trailing whitespace
4528 $text = rtrim( $text );
4534 * Fetch the user's signature text, if any, and normalize to
4535 * validated, ready-to-insert wikitext.
4536 * If you have pre-fetched the nickname or the fancySig option, you can
4537 * specify them here to save a database query.
4538 * Do not reuse this parser instance after calling getUserSig(),
4539 * as it may have changed if it's the $wgParser.
4542 * @param $nickname String|bool nickname to use or false to use user's default nickname
4543 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4544 * or null to use default value
4547 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4548 global $wgMaxSigChars;
4550 $username = $user->getName();
4552 # If not given, retrieve from the user object.
4553 if ( $nickname === false )
4554 $nickname = $user->getOption( 'nickname' );
4556 if ( is_null( $fancySig ) ) {
4557 $fancySig = $user->getBoolOption( 'fancysig' );
4560 $nickname = $nickname == null ?
$username : $nickname;
4562 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4563 $nickname = $username;
4564 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4565 } elseif ( $fancySig !== false ) {
4566 # Sig. might contain markup; validate this
4567 if ( $this->validateSig( $nickname ) !== false ) {
4568 # Validated; clean up (if needed) and return it
4569 return $this->cleanSig( $nickname, true );
4571 # Failed to validate; fall back to the default
4572 $nickname = $username;
4573 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4577 # Make sure nickname doesnt get a sig in a sig
4578 $nickname = self
::cleanSigInSig( $nickname );
4580 # If we're still here, make it a link to the user page
4581 $userText = wfEscapeWikiText( $username );
4582 $nickText = wfEscapeWikiText( $nickname );
4583 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4585 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4589 * Check that the user's signature contains no bad XML
4591 * @param $text String
4592 * @return mixed An expanded string, or false if invalid.
4594 function validateSig( $text ) {
4595 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4599 * Clean up signature text
4601 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4602 * 2) Substitute all transclusions
4604 * @param $text String
4605 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4606 * @return String: signature text
4608 public function cleanSig( $text, $parsing = false ) {
4611 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4614 # Option to disable this feature
4615 if ( !$this->mOptions
->getCleanSignatures() ) {
4619 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4620 # => Move this logic to braceSubstitution()
4621 $substWord = MagicWord
::get( 'subst' );
4622 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4623 $substText = '{{' . $substWord->getSynonym( 0 );
4625 $text = preg_replace( $substRegex, $substText, $text );
4626 $text = self
::cleanSigInSig( $text );
4627 $dom = $this->preprocessToDom( $text );
4628 $frame = $this->getPreprocessor()->newFrame();
4629 $text = $frame->expand( $dom );
4632 $text = $this->mStripState
->unstripBoth( $text );
4639 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4641 * @param $text String
4642 * @return String: signature text with /~{3,5}/ removed
4644 public static function cleanSigInSig( $text ) {
4645 $text = preg_replace( '/~{3,5}/', '', $text );
4650 * Set up some variables which are usually set up in parse()
4651 * so that an external function can call some class members with confidence
4653 * @param $title Title|null
4654 * @param $options ParserOptions
4655 * @param $outputType
4656 * @param $clearState bool
4658 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4659 $this->startParse( $title, $options, $outputType, $clearState );
4663 * @param $title Title|null
4664 * @param $options ParserOptions
4665 * @param $outputType
4666 * @param $clearState bool
4668 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4669 $this->setTitle( $title );
4670 $this->mOptions
= $options;
4671 $this->setOutputType( $outputType );
4672 if ( $clearState ) {
4673 $this->clearState();
4678 * Wrapper for preprocess()
4680 * @param $text String: the text to preprocess
4681 * @param $options ParserOptions: options
4682 * @param $title Title object or null to use $wgTitle
4685 public function transformMsg( $text, $options, $title = null ) {
4686 static $executing = false;
4688 # Guard against infinite recursion
4694 wfProfileIn( __METHOD__
);
4700 $text = $this->preprocess( $text, $title, $options );
4703 wfProfileOut( __METHOD__
);
4708 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4709 * The callback should have the following form:
4710 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4712 * Transform and return $text. Use $parser for any required context, e.g. use
4713 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4715 * Hooks may return extended information by returning an array, of which the
4716 * first numbered element (index 0) must be the return string, and all other
4717 * entries are extracted into local variables within an internal function
4718 * in the Parser class.
4720 * This interface (introduced r61913) appears to be undocumented, but
4721 * 'markerName' is used by some core tag hooks to override which strip
4722 * array their results are placed in. **Use great caution if attempting
4723 * this interface, as it is not documented and injudicious use could smash
4724 * private variables.**
4726 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4727 * @param $callback Mixed: the callback function (and object) to use for the tag
4728 * @throws MWException
4729 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4731 public function setHook( $tag, $callback ) {
4732 $tag = strtolower( $tag );
4733 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4734 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4736 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4737 $this->mTagHooks
[$tag] = $callback;
4738 if ( !in_array( $tag, $this->mStripList
) ) {
4739 $this->mStripList
[] = $tag;
4746 * As setHook(), but letting the contents be parsed.
4748 * Transparent tag hooks are like regular XML-style tag hooks, except they
4749 * operate late in the transformation sequence, on HTML instead of wikitext.
4751 * This is probably obsoleted by things dealing with parser frames?
4752 * The only extension currently using it is geoserver.
4755 * @todo better document or deprecate this
4757 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4758 * @param $callback Mixed: the callback function (and object) to use for the tag
4759 * @throws MWException
4760 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4762 function setTransparentTagHook( $tag, $callback ) {
4763 $tag = strtolower( $tag );
4764 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4765 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4767 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4768 $this->mTransparentTagHooks
[$tag] = $callback;
4774 * Remove all tag hooks
4776 function clearTagHooks() {
4777 $this->mTagHooks
= array();
4778 $this->mFunctionTagHooks
= array();
4779 $this->mStripList
= $this->mDefaultStripList
;
4783 * Create a function, e.g. {{sum:1|2|3}}
4784 * The callback function should have the form:
4785 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4787 * Or with SFH_OBJECT_ARGS:
4788 * function myParserFunction( $parser, $frame, $args ) { ... }
4790 * The callback may either return the text result of the function, or an array with the text
4791 * in element 0, and a number of flags in the other elements. The names of the flags are
4792 * specified in the keys. Valid flags are:
4793 * found The text returned is valid, stop processing the template. This
4795 * nowiki Wiki markup in the return value should be escaped
4796 * isHTML The returned text is HTML, armour it against wikitext transformation
4798 * @param $id String: The magic word ID
4799 * @param $callback Mixed: the callback function (and object) to use
4800 * @param $flags Integer: a combination of the following flags:
4801 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4803 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4804 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4805 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4806 * the arguments, and to control the way they are expanded.
4808 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4809 * arguments, for instance:
4810 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4812 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4813 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4814 * working if/when this is changed.
4816 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4819 * Please read the documentation in includes/parser/Preprocessor.php for more information
4820 * about the methods available in PPFrame and PPNode.
4822 * @throws MWException
4823 * @return string|callback The old callback function for this name, if any
4825 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4828 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4829 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4831 # Add to function cache
4832 $mw = MagicWord
::get( $id );
4834 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4836 $synonyms = $mw->getSynonyms();
4837 $sensitive = intval( $mw->isCaseSensitive() );
4839 foreach ( $synonyms as $syn ) {
4841 if ( !$sensitive ) {
4842 $syn = $wgContLang->lc( $syn );
4845 if ( !( $flags & SFH_NO_HASH
) ) {
4848 # Remove trailing colon
4849 if ( substr( $syn, -1, 1 ) === ':' ) {
4850 $syn = substr( $syn, 0, -1 );
4852 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4858 * Get all registered function hook identifiers
4862 function getFunctionHooks() {
4863 return array_keys( $this->mFunctionHooks
);
4867 * Create a tag function, e.g. "<test>some stuff</test>".
4868 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4869 * Unlike parser functions, their content is not preprocessed.
4873 * @throws MWException
4876 function setFunctionTagHook( $tag, $callback, $flags ) {
4877 $tag = strtolower( $tag );
4878 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4879 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4880 $this->mFunctionTagHooks
[$tag] : null;
4881 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4883 if ( !in_array( $tag, $this->mStripList
) ) {
4884 $this->mStripList
[] = $tag;
4891 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4892 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4893 * Placeholders created in Skin::makeLinkObj()
4895 * @param $text string
4896 * @param $options int
4898 * @return array of link CSS classes, indexed by PDBK.
4900 function replaceLinkHolders( &$text, $options = 0 ) {
4901 return $this->mLinkHolders
->replace( $text );
4905 * Replace "<!--LINK-->" link placeholders with plain text of links
4906 * (not HTML-formatted).
4908 * @param $text String
4911 function replaceLinkHoldersText( $text ) {
4912 return $this->mLinkHolders
->replaceText( $text );
4916 * Renders an image gallery from a text with one line per image.
4917 * text labels may be given by using |-style alternative text. E.g.
4918 * Image:one.jpg|The number "1"
4919 * Image:tree.jpg|A tree
4920 * given as text will return the HTML of a gallery with two images,
4921 * labeled 'The number "1"' and
4924 * @param string $text
4925 * @param array $params
4926 * @return string HTML
4928 function renderImageGallery( $text, $params ) {
4929 $ig = new ImageGallery();
4930 $ig->setContextTitle( $this->mTitle
);
4931 $ig->setShowBytes( false );
4932 $ig->setShowFilename( false );
4933 $ig->setParser( $this );
4934 $ig->setHideBadImages();
4935 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4937 if ( isset( $params['showfilename'] ) ) {
4938 $ig->setShowFilename( true );
4940 $ig->setShowFilename( false );
4942 if ( isset( $params['caption'] ) ) {
4943 $caption = $params['caption'];
4944 $caption = htmlspecialchars( $caption );
4945 $caption = $this->replaceInternalLinks( $caption );
4946 $ig->setCaptionHtml( $caption );
4948 if ( isset( $params['perrow'] ) ) {
4949 $ig->setPerRow( $params['perrow'] );
4951 if ( isset( $params['widths'] ) ) {
4952 $ig->setWidths( $params['widths'] );
4954 if ( isset( $params['heights'] ) ) {
4955 $ig->setHeights( $params['heights'] );
4958 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4960 $lines = StringUtils
::explode( "\n", $text );
4961 foreach ( $lines as $line ) {
4962 # match lines like these:
4963 # Image:someimage.jpg|This is some image
4965 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4967 if ( count( $matches ) == 0 ) {
4971 if ( strpos( $matches[0], '%' ) !== false ) {
4972 $matches[1] = rawurldecode( $matches[1] );
4974 $title = Title
::newFromText( $matches[1], NS_FILE
);
4975 if ( is_null( $title ) ) {
4976 # Bogus title. Ignore these so we don't bomb out later.
4983 if ( isset( $matches[3] ) ) {
4984 // look for an |alt= definition while trying not to break existing
4985 // captions with multiple pipes (|) in it, until a more sensible grammar
4986 // is defined for images in galleries
4988 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4989 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4990 $magicWordAlt = MagicWord
::get( 'img_alt' );
4991 $magicWordLink = MagicWord
::get( 'img_link' );
4993 foreach ( $parameterMatches as $parameterMatch ) {
4994 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4995 $alt = $this->stripAltText( $match, false );
4997 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4998 $link = strip_tags($this->replaceLinkHoldersText($match));
4999 $chars = self
::EXT_LINK_URL_CLASS
;
5000 $prots = $this->mUrlProtocols
;
5001 //check to see if link matches an absolute url, if not then it must be a wiki link.
5002 if(!preg_match( "/^($prots)$chars+$/u", $link)){
5003 $localLinkTitle = Title
::newFromText($link);
5004 $link = $localLinkTitle->getLocalURL();
5008 // concatenate all other pipes
5009 $label .= '|' . $parameterMatch;
5012 // remove the first pipe
5013 $label = substr( $label, 1 );
5016 $ig->add( $title, $label, $alt ,$link);
5018 return $ig->toHTML();
5025 function getImageParams( $handler ) {
5027 $handlerClass = get_class( $handler );
5031 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5032 # Initialise static lists
5033 static $internalParamNames = array(
5034 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5035 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5036 'bottom', 'text-bottom' ),
5037 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5038 'upright', 'border', 'link', 'alt', 'class' ),
5040 static $internalParamMap;
5041 if ( !$internalParamMap ) {
5042 $internalParamMap = array();
5043 foreach ( $internalParamNames as $type => $names ) {
5044 foreach ( $names as $name ) {
5045 $magicName = str_replace( '-', '_', "img_$name" );
5046 $internalParamMap[$magicName] = array( $type, $name );
5051 # Add handler params
5052 $paramMap = $internalParamMap;
5054 $handlerParamMap = $handler->getParamMap();
5055 foreach ( $handlerParamMap as $magic => $paramName ) {
5056 $paramMap[$magic] = array( 'handler', $paramName );
5059 $this->mImageParams
[$handlerClass] = $paramMap;
5060 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5062 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5066 * Parse image options text and use it to make an image
5068 * @param $title Title
5069 * @param $options String
5070 * @param $holders LinkHolderArray|bool
5071 * @return string HTML
5073 function makeImage( $title, $options, $holders = false ) {
5074 # Check if the options text is of the form "options|alt text"
5076 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5077 # * left no resizing, just left align. label is used for alt= only
5078 # * right same, but right aligned
5079 # * none same, but not aligned
5080 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5081 # * center center the image
5082 # * frame Keep original image size, no magnify-button.
5083 # * framed Same as "frame"
5084 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5085 # * upright reduce width for upright images, rounded to full __0 px
5086 # * border draw a 1px border around the image
5087 # * alt Text for HTML alt attribute (defaults to empty)
5088 # * class Set a class for img node
5089 # * link Set the target of the image link. Can be external, interwiki, or local
5090 # vertical-align values (no % or length right now):
5100 $parts = StringUtils
::explode( "|", $options );
5102 # Give extensions a chance to select the file revision for us
5105 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5106 array( $this, $title, &$options, &$descQuery ) );
5107 # Fetch and register the file (file title may be different via hooks)
5108 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5111 $handler = $file ?
$file->getHandler() : false;
5113 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5116 $this->addTrackingCategory( 'broken-file-category' );
5119 # Process the input parameters
5121 $params = array( 'frame' => array(), 'handler' => array(),
5122 'horizAlign' => array(), 'vertAlign' => array() );
5123 foreach ( $parts as $part ) {
5124 $part = trim( $part );
5125 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5127 if ( isset( $paramMap[$magicName] ) ) {
5128 list( $type, $paramName ) = $paramMap[$magicName];
5130 # Special case; width and height come in one variable together
5131 if ( $type === 'handler' && $paramName === 'width' ) {
5132 $parsedWidthParam = $this->parseWidthParam( $value );
5133 if( isset( $parsedWidthParam['width'] ) ) {
5134 $width = $parsedWidthParam['width'];
5135 if ( $handler->validateParam( 'width', $width ) ) {
5136 $params[$type]['width'] = $width;
5140 if( isset( $parsedWidthParam['height'] ) ) {
5141 $height = $parsedWidthParam['height'];
5142 if ( $handler->validateParam( 'height', $height ) ) {
5143 $params[$type]['height'] = $height;
5147 # else no validation -- bug 13436
5149 if ( $type === 'handler' ) {
5150 # Validate handler parameter
5151 $validated = $handler->validateParam( $paramName, $value );
5153 # Validate internal parameters
5154 switch( $paramName ) {
5158 # @todo FIXME: Possibly check validity here for
5159 # manualthumb? downstream behavior seems odd with
5160 # missing manual thumbs.
5162 $value = $this->stripAltText( $value, $holders );
5165 $chars = self
::EXT_LINK_URL_CLASS
;
5166 $prots = $this->mUrlProtocols
;
5167 if ( $value === '' ) {
5168 $paramName = 'no-link';
5171 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5172 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5173 $paramName = 'link-url';
5174 $this->mOutput
->addExternalLink( $value );
5175 if ( $this->mOptions
->getExternalLinkTarget() ) {
5176 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5181 $linkTitle = Title
::newFromText( $value );
5183 $paramName = 'link-title';
5184 $value = $linkTitle;
5185 $this->mOutput
->addLink( $linkTitle );
5191 # Most other things appear to be empty or numeric...
5192 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5197 $params[$type][$paramName] = $value;
5201 if ( !$validated ) {
5206 # Process alignment parameters
5207 if ( $params['horizAlign'] ) {
5208 $params['frame']['align'] = key( $params['horizAlign'] );
5210 if ( $params['vertAlign'] ) {
5211 $params['frame']['valign'] = key( $params['vertAlign'] );
5214 $params['frame']['caption'] = $caption;
5216 # Will the image be presented in a frame, with the caption below?
5217 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5218 isset( $params['frame']['framed'] ) ||
5219 isset( $params['frame']['thumbnail'] ) ||
5220 isset( $params['frame']['manualthumb'] );
5222 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5223 # came to also set the caption, ordinary text after the image -- which
5224 # makes no sense, because that just repeats the text multiple times in
5225 # screen readers. It *also* came to set the title attribute.
5227 # Now that we have an alt attribute, we should not set the alt text to
5228 # equal the caption: that's worse than useless, it just repeats the
5229 # text. This is the framed/thumbnail case. If there's no caption, we
5230 # use the unnamed parameter for alt text as well, just for the time be-
5231 # ing, if the unnamed param is set and the alt param is not.
5233 # For the future, we need to figure out if we want to tweak this more,
5234 # e.g., introducing a title= parameter for the title; ignoring the un-
5235 # named parameter entirely for images without a caption; adding an ex-
5236 # plicit caption= parameter and preserving the old magic unnamed para-
5238 if ( $imageIsFramed ) { # Framed image
5239 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5240 # No caption or alt text, add the filename as the alt text so
5241 # that screen readers at least get some description of the image
5242 $params['frame']['alt'] = $title->getText();
5244 # Do not set $params['frame']['title'] because tooltips don't make sense
5246 } else { # Inline image
5247 if ( !isset( $params['frame']['alt'] ) ) {
5248 # No alt text, use the "caption" for the alt text
5249 if ( $caption !== '') {
5250 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5252 # No caption, fall back to using the filename for the
5254 $params['frame']['alt'] = $title->getText();
5257 # Use the "caption" for the tooltip text
5258 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5261 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5263 # Linker does the rest
5264 $time = isset( $options['time'] ) ?
$options['time'] : false;
5265 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5266 $time, $descQuery, $this->mOptions
->getThumbSize() );
5268 # Give the handler a chance to modify the parser object
5270 $handler->parserTransformHook( $this, $file );
5278 * @param $holders LinkHolderArray
5279 * @return mixed|String
5281 protected function stripAltText( $caption, $holders ) {
5282 # Strip bad stuff out of the title (tooltip). We can't just use
5283 # replaceLinkHoldersText() here, because if this function is called
5284 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5286 $tooltip = $holders->replaceText( $caption );
5288 $tooltip = $this->replaceLinkHoldersText( $caption );
5291 # make sure there are no placeholders in thumbnail attributes
5292 # that are later expanded to html- so expand them now and
5294 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5295 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5301 * Set a flag in the output object indicating that the content is dynamic and
5302 * shouldn't be cached.
5304 function disableCache() {
5305 wfDebug( "Parser output marked as uncacheable.\n" );
5306 if ( !$this->mOutput
) {
5307 throw new MWException( __METHOD__
.
5308 " can only be called when actually parsing something" );
5310 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5311 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5315 * Callback from the Sanitizer for expanding items found in HTML attribute
5316 * values, so they can be safely tested and escaped.
5318 * @param $text String
5319 * @param $frame PPFrame
5322 function attributeStripCallback( &$text, $frame = false ) {
5323 $text = $this->replaceVariables( $text, $frame );
5324 $text = $this->mStripState
->unstripBoth( $text );
5333 function getTags() {
5334 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5338 * Replace transparent tags in $text with the values given by the callbacks.
5340 * Transparent tag hooks are like regular XML-style tag hooks, except they
5341 * operate late in the transformation sequence, on HTML instead of wikitext.
5343 * @param $text string
5347 function replaceTransparentTags( $text ) {
5349 $elements = array_keys( $this->mTransparentTagHooks
);
5350 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5351 $replacements = array();
5353 foreach ( $matches as $marker => $data ) {
5354 list( $element, $content, $params, $tag ) = $data;
5355 $tagName = strtolower( $element );
5356 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5357 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5361 $replacements[$marker] = $output;
5363 return strtr( $text, $replacements );
5367 * Break wikitext input into sections, and either pull or replace
5368 * some particular section's text.
5370 * External callers should use the getSection and replaceSection methods.
5372 * @param $text String: Page wikitext
5373 * @param $section String: a section identifier string of the form:
5374 * "<flag1> - <flag2> - ... - <section number>"
5376 * Currently the only recognised flag is "T", which means the target section number
5377 * was derived during a template inclusion parse, in other words this is a template
5378 * section edit link. If no flags are given, it was an ordinary section edit link.
5379 * This flag is required to avoid a section numbering mismatch when a section is
5380 * enclosed by "<includeonly>" (bug 6563).
5382 * The section number 0 pulls the text before the first heading; other numbers will
5383 * pull the given section along with its lower-level subsections. If the section is
5384 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5386 * Section 0 is always considered to exist, even if it only contains the empty
5387 * string. If $text is the empty string and section 0 is replaced, $newText is
5390 * @param $mode String: one of "get" or "replace"
5391 * @param $newText String: replacement text for section data.
5392 * @return String: for "get", the extracted section text.
5393 * for "replace", the whole page with the section replaced.
5395 private function extractSections( $text, $section, $mode, $newText='' ) {
5396 global $wgTitle; # not generally used but removes an ugly failure mode
5397 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5399 $frame = $this->getPreprocessor()->newFrame();
5401 # Process section extraction flags
5403 $sectionParts = explode( '-', $section );
5404 $sectionIndex = array_pop( $sectionParts );
5405 foreach ( $sectionParts as $part ) {
5406 if ( $part === 'T' ) {
5407 $flags |
= self
::PTD_FOR_INCLUSION
;
5411 # Check for empty input
5412 if ( strval( $text ) === '' ) {
5413 # Only sections 0 and T-0 exist in an empty document
5414 if ( $sectionIndex == 0 ) {
5415 if ( $mode === 'get' ) {
5421 if ( $mode === 'get' ) {
5429 # Preprocess the text
5430 $root = $this->preprocessToDom( $text, $flags );
5432 # <h> nodes indicate section breaks
5433 # They can only occur at the top level, so we can find them by iterating the root's children
5434 $node = $root->getFirstChild();
5436 # Find the target section
5437 if ( $sectionIndex == 0 ) {
5438 # Section zero doesn't nest, level=big
5439 $targetLevel = 1000;
5442 if ( $node->getName() === 'h' ) {
5443 $bits = $node->splitHeading();
5444 if ( $bits['i'] == $sectionIndex ) {
5445 $targetLevel = $bits['level'];
5449 if ( $mode === 'replace' ) {
5450 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5452 $node = $node->getNextSibling();
5458 if ( $mode === 'get' ) {
5465 # Find the end of the section, including nested sections
5467 if ( $node->getName() === 'h' ) {
5468 $bits = $node->splitHeading();
5469 $curLevel = $bits['level'];
5470 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5474 if ( $mode === 'get' ) {
5475 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5477 $node = $node->getNextSibling();
5480 # Write out the remainder (in replace mode only)
5481 if ( $mode === 'replace' ) {
5482 # Output the replacement text
5483 # Add two newlines on -- trailing whitespace in $newText is conventionally
5484 # stripped by the editor, so we need both newlines to restore the paragraph gap
5485 # Only add trailing whitespace if there is newText
5486 if ( $newText != "" ) {
5487 $outText .= $newText . "\n\n";
5491 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5492 $node = $node->getNextSibling();
5496 if ( is_string( $outText ) ) {
5497 # Re-insert stripped tags
5498 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5505 * This function returns the text of a section, specified by a number ($section).
5506 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5507 * the first section before any such heading (section 0).
5509 * If a section contains subsections, these are also returned.
5511 * @param $text String: text to look in
5512 * @param $section String: section identifier
5513 * @param $deftext String: default to return if section is not found
5514 * @return string text of the requested section
5516 public function getSection( $text, $section, $deftext='' ) {
5517 return $this->extractSections( $text, $section, "get", $deftext );
5521 * This function returns $oldtext after the content of the section
5522 * specified by $section has been replaced with $text. If the target
5523 * section does not exist, $oldtext is returned unchanged.
5525 * @param $oldtext String: former text of the article
5526 * @param $section int section identifier
5527 * @param $text String: replacing text
5528 * @return String: modified text
5530 public function replaceSection( $oldtext, $section, $text ) {
5531 return $this->extractSections( $oldtext, $section, "replace", $text );
5535 * Get the ID of the revision we are parsing
5537 * @return Mixed: integer or null
5539 function getRevisionId() {
5540 return $this->mRevisionId
;
5544 * Get the revision object for $this->mRevisionId
5546 * @return Revision|null either a Revision object or null
5548 protected function getRevisionObject() {
5549 if ( !is_null( $this->mRevisionObject
) ) {
5550 return $this->mRevisionObject
;
5552 if ( is_null( $this->mRevisionId
) ) {
5556 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5557 return $this->mRevisionObject
;
5561 * Get the timestamp associated with the current revision, adjusted for
5562 * the default server-local timestamp
5564 function getRevisionTimestamp() {
5565 if ( is_null( $this->mRevisionTimestamp
) ) {
5566 wfProfileIn( __METHOD__
);
5570 $revObject = $this->getRevisionObject();
5571 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5573 # The cryptic '' timezone parameter tells to use the site-default
5574 # timezone offset instead of the user settings.
5576 # Since this value will be saved into the parser cache, served
5577 # to other users, and potentially even used inside links and such,
5578 # it needs to be consistent for all visitors.
5579 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5581 wfProfileOut( __METHOD__
);
5583 return $this->mRevisionTimestamp
;
5587 * Get the name of the user that edited the last revision
5589 * @return String: user name
5591 function getRevisionUser() {
5592 if( is_null( $this->mRevisionUser
) ) {
5593 $revObject = $this->getRevisionObject();
5595 # if this template is subst: the revision id will be blank,
5596 # so just use the current user's name
5598 $this->mRevisionUser
= $revObject->getUserText();
5599 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5600 $this->mRevisionUser
= $this->getUser()->getName();
5603 return $this->mRevisionUser
;
5607 * Mutator for $mDefaultSort
5609 * @param $sort string New value
5611 public function setDefaultSort( $sort ) {
5612 $this->mDefaultSort
= $sort;
5613 $this->mOutput
->setProperty( 'defaultsort', $sort );
5617 * Accessor for $mDefaultSort
5618 * Will use the empty string if none is set.
5620 * This value is treated as a prefix, so the
5621 * empty string is equivalent to sorting by
5626 public function getDefaultSort() {
5627 if ( $this->mDefaultSort
!== false ) {
5628 return $this->mDefaultSort
;
5635 * Accessor for $mDefaultSort
5636 * Unlike getDefaultSort(), will return false if none is set
5638 * @return string or false
5640 public function getCustomDefaultSort() {
5641 return $this->mDefaultSort
;
5645 * Try to guess the section anchor name based on a wikitext fragment
5646 * presumably extracted from a heading, for example "Header" from
5649 * @param $text string
5653 public function guessSectionNameFromWikiText( $text ) {
5654 # Strip out wikitext links(they break the anchor)
5655 $text = $this->stripSectionName( $text );
5656 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5657 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5661 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5662 * instead. For use in redirects, since IE6 interprets Redirect: headers
5663 * as something other than UTF-8 (apparently?), resulting in breakage.
5665 * @param $text String: The section name
5666 * @return string An anchor
5668 public function guessLegacySectionNameFromWikiText( $text ) {
5669 # Strip out wikitext links(they break the anchor)
5670 $text = $this->stripSectionName( $text );
5671 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5672 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5676 * Strips a text string of wikitext for use in a section anchor
5678 * Accepts a text string and then removes all wikitext from the
5679 * string and leaves only the resultant text (i.e. the result of
5680 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5681 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5682 * to create valid section anchors by mimicing the output of the
5683 * parser when headings are parsed.
5685 * @param $text String: text string to be stripped of wikitext
5686 * for use in a Section anchor
5687 * @return string Filtered text string
5689 public function stripSectionName( $text ) {
5690 # Strip internal link markup
5691 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5692 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5694 # Strip external link markup
5695 # @todo FIXME: Not tolerant to blank link text
5696 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5697 # on how many empty links there are on the page - need to figure that out.
5698 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5700 # Parse wikitext quotes (italics & bold)
5701 $text = $this->doQuotes( $text );
5704 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5709 * strip/replaceVariables/unstrip for preprocessor regression testing
5711 * @param $text string
5712 * @param $title Title
5713 * @param $options ParserOptions
5714 * @param $outputType int
5718 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5719 $this->startParse( $title, $options, $outputType, true );
5721 $text = $this->replaceVariables( $text );
5722 $text = $this->mStripState
->unstripBoth( $text );
5723 $text = Sanitizer
::removeHTMLtags( $text );
5728 * @param $text string
5729 * @param $title Title
5730 * @param $options ParserOptions
5733 function testPst( $text, Title
$title, ParserOptions
$options ) {
5734 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5739 * @param $title Title
5740 * @param $options ParserOptions
5743 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5744 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5748 * Call a callback function on all regions of the given text that are not
5749 * inside strip markers, and replace those regions with the return value
5750 * of the callback. For example, with input:
5754 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5755 * two strings will be replaced with the value returned by the callback in
5763 function markerSkipCallback( $s, $callback ) {
5766 while ( $i < strlen( $s ) ) {
5767 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5768 if ( $markerStart === false ) {
5769 $out .= call_user_func( $callback, substr( $s, $i ) );
5772 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5773 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5774 if ( $markerEnd === false ) {
5775 $out .= substr( $s, $markerStart );
5778 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5779 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5788 * Remove any strip markers found in the given text.
5790 * @param $text Input string
5793 function killMarkers( $text ) {
5794 return $this->mStripState
->killMarkers( $text );
5798 * Save the parser state required to convert the given half-parsed text to
5799 * HTML. "Half-parsed" in this context means the output of
5800 * recursiveTagParse() or internalParse(). This output has strip markers
5801 * from replaceVariables (extensionSubstitution() etc.), and link
5802 * placeholders from replaceLinkHolders().
5804 * Returns an array which can be serialized and stored persistently. This
5805 * array can later be loaded into another parser instance with
5806 * unserializeHalfParsedText(). The text can then be safely incorporated into
5807 * the return value of a parser hook.
5809 * @param $text string
5813 function serializeHalfParsedText( $text ) {
5814 wfProfileIn( __METHOD__
);
5817 'version' => self
::HALF_PARSED_VERSION
,
5818 'stripState' => $this->mStripState
->getSubState( $text ),
5819 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5821 wfProfileOut( __METHOD__
);
5826 * Load the parser state given in the $data array, which is assumed to
5827 * have been generated by serializeHalfParsedText(). The text contents is
5828 * extracted from the array, and its markers are transformed into markers
5829 * appropriate for the current Parser instance. This transformed text is
5830 * returned, and can be safely included in the return value of a parser
5833 * If the $data array has been stored persistently, the caller should first
5834 * check whether it is still valid, by calling isValidHalfParsedText().
5836 * @param $data array Serialized data
5837 * @throws MWException
5840 function unserializeHalfParsedText( $data ) {
5841 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5842 throw new MWException( __METHOD__
.': invalid version' );
5845 # First, extract the strip state.
5846 $texts = array( $data['text'] );
5847 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5849 # Now renumber links
5850 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5852 # Should be good to go.
5857 * Returns true if the given array, presumed to be generated by
5858 * serializeHalfParsedText(), is compatible with the current version of the
5861 * @param $data Array
5865 function isValidHalfParsedText( $data ) {
5866 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5870 * Parsed a width param of imagelink like 300px or 200x300px
5872 * @param $value String
5877 public function parseWidthParam( $value ) {
5878 $parsedWidthParam = array();
5879 if( $value === '' ) {
5880 return $parsedWidthParam;
5883 # (bug 13500) In both cases (width/height and width only),
5884 # permit trailing "px" for backward compatibility.
5885 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5886 $width = intval( $m[1] );
5887 $height = intval( $m[2] );
5888 $parsedWidthParam['width'] = $width;
5889 $parsedWidthParam['height'] = $height;
5890 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5891 $width = intval( $value );
5892 $parsedWidthParam['width'] = $width;
5894 return $parsedWidthParam;