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).
35 * There are five main entry points into the Parser class:
37 * produces HTML output
39 * produces altered wiki markup.
41 * removes HTML comments and expands templates
42 * cleanSig() / cleanSigInSig()
43 * Cleans a signature before saving it to preferences
45 * Return the content of a section from an article for section editing
47 * Replaces a section by number inside an article
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * NOT $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgUseDynamicDates*, $wgInterwikiMagic*,
58 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
59 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
62 * * only within ParserOptions
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
119 var $mTagHooks = array();
120 var $mTransparentTagHooks = array();
121 var $mFunctionHooks = array();
122 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
123 var $mFunctionTagHooks = array();
124 var $mStripList = array();
125 var $mDefaultStripList = array();
126 var $mVarCache = array();
127 var $mImageParams = array();
128 var $mImageParamsMagicArray = array();
129 var $mMarkerIndex = 0;
130 var $mFirstCall = true;
132 # Initialised by initialiseVariables()
135 * @var MagicWordArray
140 * @var MagicWordArray
143 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
145 # Cleared with clearState():
150 var $mAutonumber, $mDTopen;
157 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
159 * @var LinkHolderArray
164 var $mIncludeSizes, $mPPNodeCount, $mHighestExpansionDepth, $mDefaultSort;
165 var $mTplExpandCache; # empty-frame expansion cache
166 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
167 var $mExpensiveFunctionCount; # number of expensive parser function calls
168 var $mShowToc, $mForceTocPosition;
173 var $mUser; # User object; only used when doing pre-save transform
176 # These are variables reset at least once per parse regardless of $clearState
186 var $mTitle; # Title context, used for self-link rendering and similar things
187 var $mOutputType; # Output type, one of the OT_xxx constants
188 var $ot; # Shortcut alias, see setOutputType()
189 var $mRevisionObject; # The revision object of the specified revision ID
190 var $mRevisionId; # ID to display in {{REVISIONID}} tags
191 var $mRevisionTimestamp; # The timestamp of the specified revision ID
192 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
193 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
205 public function __construct( $conf = array() ) {
206 $this->mConf
= $conf;
207 $this->mUrlProtocols
= wfUrlProtocols();
208 $this->mExtLinkBracketedRegex
= '/\[((' . $this->mUrlProtocols
. ')'.
209 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
210 if ( isset( $conf['preprocessorClass'] ) ) {
211 $this->mPreprocessorClass
= $conf['preprocessorClass'];
212 } elseif ( defined( 'MW_COMPILED' ) ) {
213 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
214 $this->mPreprocessorClass
= 'Preprocessor_Hash';
215 } elseif ( extension_loaded( 'domxml' ) ) {
216 # PECL extension that conflicts with the core DOM extension (bug 13770)
217 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
218 $this->mPreprocessorClass
= 'Preprocessor_Hash';
219 } elseif ( extension_loaded( 'dom' ) ) {
220 $this->mPreprocessorClass
= 'Preprocessor_DOM';
222 $this->mPreprocessorClass
= 'Preprocessor_Hash';
224 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
228 * Reduce memory usage to reduce the impact of circular references
230 function __destruct() {
231 if ( isset( $this->mLinkHolders
) ) {
232 unset( $this->mLinkHolders
);
234 foreach ( $this as $name => $value ) {
235 unset( $this->$name );
240 * Do various kinds of initialisation on the first call of the parser
242 function firstCallInit() {
243 if ( !$this->mFirstCall
) {
246 $this->mFirstCall
= false;
248 wfProfileIn( __METHOD__
);
250 CoreParserFunctions
::register( $this );
251 CoreTagHooks
::register( $this );
252 $this->initialiseVariables();
254 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
255 wfProfileOut( __METHOD__
);
263 function clearState() {
264 wfProfileIn( __METHOD__
);
265 if ( $this->mFirstCall
) {
266 $this->firstCallInit();
268 $this->mOutput
= new ParserOutput
;
269 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
270 $this->mAutonumber
= 0;
271 $this->mLastSection
= '';
272 $this->mDTopen
= false;
273 $this->mIncludeCount
= array();
274 $this->mArgStack
= false;
275 $this->mInPre
= false;
276 $this->mLinkHolders
= new LinkHolderArray( $this );
278 $this->mRevisionObject
= $this->mRevisionTimestamp
=
279 $this->mRevisionId
= $this->mRevisionUser
= null;
280 $this->mVarCache
= array();
284 * Prefix for temporary replacement strings for the multipass parser.
285 * \x07 should never appear in input as it's disallowed in XML.
286 * Using it at the front also gives us a little extra robustness
287 * since it shouldn't match when butted up against identifier-like
290 * Must not consist of all title characters, or else it will change
291 * the behaviour of <nowiki> in a link.
293 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
294 $this->mStripState
= new StripState( $this->mUniqPrefix
);
297 # Clear these on every parse, bug 4549
298 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
300 $this->mShowToc
= true;
301 $this->mForceTocPosition
= false;
302 $this->mIncludeSizes
= array(
306 $this->mPPNodeCount
= 0;
307 $this->mHighestExpansionDepth
= 0;
308 $this->mDefaultSort
= false;
309 $this->mHeadings
= array();
310 $this->mDoubleUnderscores
= array();
311 $this->mExpensiveFunctionCount
= 0;
314 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
315 $this->mPreprocessor
= null;
318 wfRunHooks( 'ParserClearState', array( &$this ) );
319 wfProfileOut( __METHOD__
);
323 * Convert wikitext to HTML
324 * Do not call this function recursively.
326 * @param $text String: text we want to parse
327 * @param $title Title object
328 * @param $options ParserOptions
329 * @param $linestart boolean
330 * @param $clearState boolean
331 * @param $revid Int: number to pass in {{REVISIONID}}
332 * @return ParserOutput a ParserOutput
334 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
336 * First pass--just handle <nowiki> sections, pass the rest off
337 * to internalParse() which does all the real work.
340 global $wgUseTidy, $wgAlwaysUseTidy, $wgDisableLangConversion, $wgDisableTitleConversion;
341 $fname = __METHOD__
.'-' . wfGetCaller();
342 wfProfileIn( __METHOD__
);
343 wfProfileIn( $fname );
345 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
347 # Remove the strip marker tag prefix from the input, if present.
349 $text = str_replace( $this->mUniqPrefix
, '', $text );
352 $oldRevisionId = $this->mRevisionId
;
353 $oldRevisionObject = $this->mRevisionObject
;
354 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
355 $oldRevisionUser = $this->mRevisionUser
;
356 if ( $revid !== null ) {
357 $this->mRevisionId
= $revid;
358 $this->mRevisionObject
= null;
359 $this->mRevisionTimestamp
= null;
360 $this->mRevisionUser
= null;
363 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
365 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
366 $text = $this->internalParse( $text );
367 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
369 $text = $this->mStripState
->unstripGeneral( $text );
371 # Clean up special characters, only run once, next-to-last before doBlockLevels
373 # french spaces, last one Guillemet-left
374 # only if there is something before the space
375 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
376 # french spaces, Guillemet-right
377 '/(\\302\\253) /' => '\\1 ',
378 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
380 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
382 $text = $this->doBlockLevels( $text, $linestart );
384 $this->replaceLinkHolders( $text );
387 * The input doesn't get language converted if
389 * b) Content isn't converted
390 * c) It's a conversion table
391 * d) it is an interface message (which is in the user language)
393 if ( !( $wgDisableLangConversion
394 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
395 ||
$this->mTitle
->isConversionTable() ) )
397 # Run convert unconditionally in 1.18-compatible mode
398 global $wgBug34832TransitionalRollback;
399 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
400 # The position of the convert() call should not be changed. it
401 # assumes that the links are all replaced and the only thing left
402 # is the <nowiki> mark.
403 $text = $this->getConverterLanguage()->convert( $text );
408 * A converted title will be provided in the output object if title and
409 * content conversion are enabled, the article text does not contain
410 * a conversion-suppressing double-underscore tag, and no
411 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
412 * automatic link conversion.
414 if ( !( $wgDisableLangConversion
415 ||
$wgDisableTitleConversion
416 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
417 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
418 ||
$this->mOutput
->getDisplayTitle() !== false ) )
420 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
421 if ( $convruletitle ) {
422 $this->mOutput
->setTitleText( $convruletitle );
424 $titleText = $this->getConverterLanguage()->convertTitle( $title );
425 $this->mOutput
->setTitleText( $titleText );
429 $text = $this->mStripState
->unstripNoWiki( $text );
431 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
433 $text = $this->replaceTransparentTags( $text );
434 $text = $this->mStripState
->unstripGeneral( $text );
436 $text = Sanitizer
::normalizeCharReferences( $text );
438 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
439 $text = MWTidy
::tidy( $text );
441 # attempt to sanitize at least some nesting problems
442 # (bug #2702 and quite a few others)
444 # ''Something [http://www.cool.com cool''] -->
445 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
446 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
447 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
448 # fix up an anchor inside another anchor, only
449 # at least for a single single nested link (bug 3695)
450 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
451 '\\1\\2</a>\\3</a>\\1\\4</a>',
452 # fix div inside inline elements- doBlockLevels won't wrap a line which
453 # contains a div, so fix it up here; replace
454 # div with escaped text
455 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
456 '\\1\\3<div\\5>\\6</div>\\8\\9',
457 # remove empty italic or bold tag pairs, some
458 # introduced by rules above
459 '/<([bi])><\/\\1>/' => '',
462 $text = preg_replace(
463 array_keys( $tidyregs ),
464 array_values( $tidyregs ),
468 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
469 $this->limitationWarn( 'expensive-parserfunction',
470 $this->mExpensiveFunctionCount
,
471 $this->mOptions
->getExpensiveParserFunctionLimit()
475 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
477 # Information on include size limits, for the benefit of users who try to skirt them
478 if ( $this->mOptions
->getEnableLimitReport() ) {
479 $max = $this->mOptions
->getMaxIncludeSize();
480 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
482 "NewPP limit report\n" .
483 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
484 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
485 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
486 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
488 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
489 $text .= "\n<!-- \n$limitReport-->\n";
491 $this->mOutput
->setText( $text );
493 $this->mRevisionId
= $oldRevisionId;
494 $this->mRevisionObject
= $oldRevisionObject;
495 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
496 $this->mRevisionUser
= $oldRevisionUser;
497 wfProfileOut( $fname );
498 wfProfileOut( __METHOD__
);
500 return $this->mOutput
;
504 * Recursive parser entry point that can be called from an extension tag
507 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
509 * @param $text String: text extension wants to have parsed
510 * @param $frame PPFrame: The frame to use for expanding any template variables
514 function recursiveTagParse( $text, $frame=false ) {
515 wfProfileIn( __METHOD__
);
516 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
517 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
518 $text = $this->internalParse( $text, false, $frame );
519 wfProfileOut( __METHOD__
);
524 * Expand templates and variables in the text, producing valid, static wikitext.
525 * Also removes comments.
526 * @return mixed|string
528 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
529 wfProfileIn( __METHOD__
);
530 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
531 if ( $revid !== null ) {
532 $this->mRevisionId
= $revid;
534 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
535 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
536 $text = $this->replaceVariables( $text );
537 $text = $this->mStripState
->unstripBoth( $text );
538 wfProfileOut( __METHOD__
);
543 * Recursive parser entry point that can be called from an extension tag
546 * @param $text String: text to be expanded
547 * @param $frame PPFrame: The frame to use for expanding any template variables
551 public function recursivePreprocess( $text, $frame = false ) {
552 wfProfileIn( __METHOD__
);
553 $text = $this->replaceVariables( $text, $frame );
554 $text = $this->mStripState
->unstripBoth( $text );
555 wfProfileOut( __METHOD__
);
560 * Process the wikitext for the "?preload=" feature. (bug 5210)
562 * "<noinclude>", "<includeonly>" etc. are parsed as for template
563 * transclusion, comments, templates, arguments, tags hooks and parser
564 * functions are untouched.
566 * @param $text String
567 * @param $title Title
568 * @param $options ParserOptions
571 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
572 # Parser (re)initialisation
573 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
575 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
576 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
577 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
578 $text = $this->mStripState
->unstripBoth( $text );
583 * Get a random string
587 static public function getRandomString() {
588 return wfRandomString( 16 );
592 * Set the current user.
593 * Should only be used when doing pre-save transform.
595 * @param $user Mixed: User object or null (to reset)
597 function setUser( $user ) {
598 $this->mUser
= $user;
602 * Accessor for mUniqPrefix.
606 public function uniqPrefix() {
607 if ( !isset( $this->mUniqPrefix
) ) {
608 # @todo FIXME: This is probably *horribly wrong*
609 # LanguageConverter seems to want $wgParser's uniqPrefix, however
610 # if this is called for a parser cache hit, the parser may not
611 # have ever been initialized in the first place.
612 # Not really sure what the heck is supposed to be going on here.
614 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
616 return $this->mUniqPrefix
;
620 * Set the context title
624 function setTitle( $t ) {
625 if ( !$t ||
$t instanceof FakeTitle
) {
626 $t = Title
::newFromText( 'NO TITLE' );
629 if ( strval( $t->getFragment() ) !== '' ) {
630 # Strip the fragment to avoid various odd effects
631 $this->mTitle
= clone $t;
632 $this->mTitle
->setFragment( '' );
639 * Accessor for the Title object
641 * @return Title object
643 function getTitle() {
644 return $this->mTitle
;
648 * Accessor/mutator for the Title object
650 * @param $x Title object or null to just get the current one
651 * @return Title object
653 function Title( $x = null ) {
654 return wfSetVar( $this->mTitle
, $x );
658 * Set the output type
660 * @param $ot Integer: new value
662 function setOutputType( $ot ) {
663 $this->mOutputType
= $ot;
666 'html' => $ot == self
::OT_HTML
,
667 'wiki' => $ot == self
::OT_WIKI
,
668 'pre' => $ot == self
::OT_PREPROCESS
,
669 'plain' => $ot == self
::OT_PLAIN
,
674 * Accessor/mutator for the output type
676 * @param $x int|null New value or null to just get the current one
679 function OutputType( $x = null ) {
680 return wfSetVar( $this->mOutputType
, $x );
684 * Get the ParserOutput object
686 * @return ParserOutput object
688 function getOutput() {
689 return $this->mOutput
;
693 * Get the ParserOptions object
695 * @return ParserOptions object
697 function getOptions() {
698 return $this->mOptions
;
702 * Accessor/mutator for the ParserOptions object
704 * @param $x ParserOptions New value or null to just get the current one
705 * @return ParserOptions Current ParserOptions object
707 function Options( $x = null ) {
708 return wfSetVar( $this->mOptions
, $x );
714 function nextLinkID() {
715 return $this->mLinkID++
;
721 function setLinkID( $id ) {
722 $this->mLinkID
= $id;
726 * Get a language object for use in parser functions such as {{FORMATNUM:}}
729 function getFunctionLang() {
730 return $this->getTargetLanguage();
734 * Get the target language for the content being parsed. This is usually the
735 * language that the content is in.
737 function getTargetLanguage() {
738 $target = $this->mOptions
->getTargetLanguage();
739 if ( $target !== null ) {
741 } elseif( $this->mOptions
->getInterfaceMessage() ) {
742 return $this->mOptions
->getUserLangObj();
743 } elseif( is_null( $this->mTitle
) ) {
744 throw new MWException( __METHOD__
.': $this->mTitle is null' );
746 return $this->mTitle
->getPageLanguage();
750 * Get the language object for language conversion
752 function getConverterLanguage() {
753 global $wgBug34832TransitionalRollback, $wgContLang;
754 if ( $wgBug34832TransitionalRollback ) {
757 return $this->getTargetLanguage();
762 * Get a User object either from $this->mUser, if set, or from the
763 * ParserOptions object otherwise
765 * @return User object
768 if ( !is_null( $this->mUser
) ) {
771 return $this->mOptions
->getUser();
775 * Get a preprocessor object
777 * @return Preprocessor instance
779 function getPreprocessor() {
780 if ( !isset( $this->mPreprocessor
) ) {
781 $class = $this->mPreprocessorClass
;
782 $this->mPreprocessor
= new $class( $this );
784 return $this->mPreprocessor
;
788 * Replaces all occurrences of HTML-style comments and the given tags
789 * in the text with a random marker and returns the next text. The output
790 * parameter $matches will be an associative array filled with data in
794 * 'UNIQ-xxxxx' => array(
797 * array( 'param' => 'x' ),
798 * '<element param="x">tag content</element>' ) )
801 * @param $elements array list of element names. Comments are always extracted.
802 * @param $text string Source text string.
803 * @param $matches array Out parameter, Array: extracted tags
804 * @param $uniq_prefix string
805 * @return String: stripped text
807 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
812 $taglist = implode( '|', $elements );
813 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
815 while ( $text != '' ) {
816 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
818 if ( count( $p ) < 5 ) {
821 if ( count( $p ) > 5 ) {
835 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
836 $stripped .= $marker;
838 if ( $close === '/>' ) {
839 # Empty element tag, <tag />
844 if ( $element === '!--' ) {
847 $end = "/(<\\/$element\\s*>)/i";
849 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
851 if ( count( $q ) < 3 ) {
852 # No end tag -- let it run out to the end of the text.
861 $matches[$marker] = array( $element,
863 Sanitizer
::decodeTagAttributes( $attributes ),
864 "<$element$attributes$close$content$tail" );
870 * Get a list of strippable XML-like elements
874 function getStripList() {
875 return $this->mStripList
;
879 * Add an item to the strip state
880 * Returns the unique tag which must be inserted into the stripped text
881 * The tag will be replaced with the original text in unstrip()
883 * @param $text string
887 function insertStripItem( $text ) {
888 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
889 $this->mMarkerIndex++
;
890 $this->mStripState
->addGeneral( $rnd, $text );
895 * parse the wiki syntax used to render tables
900 function doTableStuff( $text ) {
901 wfProfileIn( __METHOD__
);
903 $lines = StringUtils
::explode( "\n", $text );
905 $td_history = array(); # Is currently a td tag open?
906 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
907 $tr_history = array(); # Is currently a tr tag open?
908 $tr_attributes = array(); # history of tr attributes
909 $has_opened_tr = array(); # Did this table open a <tr> element?
910 $indent_level = 0; # indent level of the table
912 foreach ( $lines as $outLine ) {
913 $line = trim( $outLine );
915 if ( $line === '' ) { # empty line, go to next line
916 $out .= $outLine."\n";
920 $first_character = $line[0];
923 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
924 # First check if we are starting a new table
925 $indent_level = strlen( $matches[1] );
927 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
928 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
930 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
931 array_push( $td_history , false );
932 array_push( $last_tag_history , '' );
933 array_push( $tr_history , false );
934 array_push( $tr_attributes , '' );
935 array_push( $has_opened_tr , false );
936 } elseif ( count( $td_history ) == 0 ) {
937 # Don't do any of the following
938 $out .= $outLine."\n";
940 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
941 # We are ending a table
942 $line = '</table>' . substr( $line , 2 );
943 $last_tag = array_pop( $last_tag_history );
945 if ( !array_pop( $has_opened_tr ) ) {
946 $line = "<tr><td></td></tr>{$line}";
949 if ( array_pop( $tr_history ) ) {
950 $line = "</tr>{$line}";
953 if ( array_pop( $td_history ) ) {
954 $line = "</{$last_tag}>{$line}";
956 array_pop( $tr_attributes );
957 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
958 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
959 # Now we have a table row
960 $line = preg_replace( '#^\|-+#', '', $line );
962 # Whats after the tag is now only attributes
963 $attributes = $this->mStripState
->unstripBoth( $line );
964 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
965 array_pop( $tr_attributes );
966 array_push( $tr_attributes, $attributes );
969 $last_tag = array_pop( $last_tag_history );
970 array_pop( $has_opened_tr );
971 array_push( $has_opened_tr , true );
973 if ( array_pop( $tr_history ) ) {
977 if ( array_pop( $td_history ) ) {
978 $line = "</{$last_tag}>{$line}";
982 array_push( $tr_history , false );
983 array_push( $td_history , false );
984 array_push( $last_tag_history , '' );
985 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
986 # This might be cell elements, td, th or captions
987 if ( substr( $line , 0 , 2 ) === '|+' ) {
988 $first_character = '+';
989 $line = substr( $line , 1 );
992 $line = substr( $line , 1 );
994 if ( $first_character === '!' ) {
995 $line = str_replace( '!!' , '||' , $line );
998 # Split up multiple cells on the same line.
999 # FIXME : This can result in improper nesting of tags processed
1000 # by earlier parser steps, but should avoid splitting up eg
1001 # attribute values containing literal "||".
1002 $cells = StringUtils
::explodeMarkup( '||' , $line );
1006 # Loop through each table cell
1007 foreach ( $cells as $cell ) {
1009 if ( $first_character !== '+' ) {
1010 $tr_after = array_pop( $tr_attributes );
1011 if ( !array_pop( $tr_history ) ) {
1012 $previous = "<tr{$tr_after}>\n";
1014 array_push( $tr_history , true );
1015 array_push( $tr_attributes , '' );
1016 array_pop( $has_opened_tr );
1017 array_push( $has_opened_tr , true );
1020 $last_tag = array_pop( $last_tag_history );
1022 if ( array_pop( $td_history ) ) {
1023 $previous = "</{$last_tag}>\n{$previous}";
1026 if ( $first_character === '|' ) {
1028 } elseif ( $first_character === '!' ) {
1030 } elseif ( $first_character === '+' ) {
1031 $last_tag = 'caption';
1036 array_push( $last_tag_history , $last_tag );
1038 # A cell could contain both parameters and data
1039 $cell_data = explode( '|' , $cell , 2 );
1041 # Bug 553: Note that a '|' inside an invalid link should not
1042 # be mistaken as delimiting cell parameters
1043 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1044 $cell = "{$previous}<{$last_tag}>{$cell}";
1045 } elseif ( count( $cell_data ) == 1 ) {
1046 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1048 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1049 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1050 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1054 array_push( $td_history , true );
1057 $out .= $outLine . "\n";
1060 # Closing open td, tr && table
1061 while ( count( $td_history ) > 0 ) {
1062 if ( array_pop( $td_history ) ) {
1065 if ( array_pop( $tr_history ) ) {
1068 if ( !array_pop( $has_opened_tr ) ) {
1069 $out .= "<tr><td></td></tr>\n" ;
1072 $out .= "</table>\n";
1075 # Remove trailing line-ending (b/c)
1076 if ( substr( $out, -1 ) === "\n" ) {
1077 $out = substr( $out, 0, -1 );
1080 # special case: don't return empty table
1081 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1085 wfProfileOut( __METHOD__
);
1091 * Helper function for parse() that transforms wiki markup into
1092 * HTML. Only called for $mOutputType == self::OT_HTML.
1096 * @param $text string
1097 * @param $isMain bool
1098 * @param $frame bool
1102 function internalParse( $text, $isMain = true, $frame = false ) {
1103 wfProfileIn( __METHOD__
);
1107 # Hook to suspend the parser in this state
1108 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1109 wfProfileOut( __METHOD__
);
1113 # if $frame is provided, then use $frame for replacing any variables
1115 # use frame depth to infer how include/noinclude tags should be handled
1116 # depth=0 means this is the top-level document; otherwise it's an included document
1117 if ( !$frame->depth
) {
1120 $flag = Parser
::PTD_FOR_INCLUSION
;
1122 $dom = $this->preprocessToDom( $text, $flag );
1123 $text = $frame->expand( $dom );
1125 # if $frame is not provided, then use old-style replaceVariables
1126 $text = $this->replaceVariables( $text );
1129 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1130 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1131 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1133 # Tables need to come after variable replacement for things to work
1134 # properly; putting them before other transformations should keep
1135 # exciting things like link expansions from showing up in surprising
1137 $text = $this->doTableStuff( $text );
1139 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1141 $text = $this->doDoubleUnderscore( $text );
1143 $text = $this->doHeadings( $text );
1144 if ( $this->mOptions
->getUseDynamicDates() ) {
1145 $df = DateFormatter
::getInstance();
1146 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1148 $text = $this->replaceInternalLinks( $text );
1149 $text = $this->doAllQuotes( $text );
1150 $text = $this->replaceExternalLinks( $text );
1152 # replaceInternalLinks may sometimes leave behind
1153 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1154 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1156 $text = $this->doMagicLinks( $text );
1157 $text = $this->formatHeadings( $text, $origText, $isMain );
1159 wfProfileOut( __METHOD__
);
1164 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1165 * magic external links.
1170 * @param $text string
1174 function doMagicLinks( $text ) {
1175 wfProfileIn( __METHOD__
);
1176 $prots = wfUrlProtocolsWithoutProtRel();
1177 $urlChar = self
::EXT_LINK_URL_CLASS
;
1178 $text = preg_replace_callback(
1180 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1181 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1182 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1183 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1184 ISBN\s+(\b # m[5]: ISBN, capture number
1185 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1186 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1187 [0-9Xx] # check digit
1189 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1190 wfProfileOut( __METHOD__
);
1195 * @throws MWException
1197 * @return HTML|string
1199 function magicLinkCallback( $m ) {
1200 if ( isset( $m[1] ) && $m[1] !== '' ) {
1203 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1206 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1207 # Free external link
1208 return $this->makeFreeExternalLink( $m[0] );
1209 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1211 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1214 $CssClass = 'mw-magiclink-rfc';
1216 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1218 $urlmsg = 'pubmedurl';
1219 $CssClass = 'mw-magiclink-pmid';
1222 throw new MWException( __METHOD__
.': unrecognised match type "' .
1223 substr( $m[0], 0, 20 ) . '"' );
1225 $url = wfMsgForContent( $urlmsg, $id );
1226 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1227 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1230 $num = strtr( $isbn, array(
1235 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1237 htmlspecialchars( $titleObj->getLocalUrl() ) .
1238 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1245 * Make a free external link, given a user-supplied URL
1247 * @param $url string
1249 * @return string HTML
1252 function makeFreeExternalLink( $url ) {
1253 wfProfileIn( __METHOD__
);
1257 # The characters '<' and '>' (which were escaped by
1258 # removeHTMLtags()) should not be included in
1259 # URLs, per RFC 2396.
1261 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1262 $trail = substr( $url, $m2[0][1] ) . $trail;
1263 $url = substr( $url, 0, $m2[0][1] );
1266 # Move trailing punctuation to $trail
1268 # If there is no left bracket, then consider right brackets fair game too
1269 if ( strpos( $url, '(' ) === false ) {
1273 $numSepChars = strspn( strrev( $url ), $sep );
1274 if ( $numSepChars ) {
1275 $trail = substr( $url, -$numSepChars ) . $trail;
1276 $url = substr( $url, 0, -$numSepChars );
1279 $url = Sanitizer
::cleanUrl( $url );
1281 # Is this an external image?
1282 $text = $this->maybeMakeExternalImage( $url );
1283 if ( $text === false ) {
1284 # Not an image, make a link
1285 $text = Linker
::makeExternalLink( $url,
1286 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1287 $this->getExternalLinkAttribs( $url ) );
1288 # Register it in the output object...
1289 # Replace unnecessary URL escape codes with their equivalent characters
1290 $pasteurized = self
::replaceUnusualEscapes( $url );
1291 $this->mOutput
->addExternalLink( $pasteurized );
1293 wfProfileOut( __METHOD__
);
1294 return $text . $trail;
1299 * Parse headers and return html
1303 * @param $text string
1307 function doHeadings( $text ) {
1308 wfProfileIn( __METHOD__
);
1309 for ( $i = 6; $i >= 1; --$i ) {
1310 $h = str_repeat( '=', $i );
1311 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1312 "<h$i>\\1</h$i>", $text );
1314 wfProfileOut( __METHOD__
);
1319 * Replace single quotes with HTML markup
1322 * @param $text string
1324 * @return string the altered text
1326 function doAllQuotes( $text ) {
1327 wfProfileIn( __METHOD__
);
1329 $lines = StringUtils
::explode( "\n", $text );
1330 foreach ( $lines as $line ) {
1331 $outtext .= $this->doQuotes( $line ) . "\n";
1333 $outtext = substr( $outtext, 0,-1 );
1334 wfProfileOut( __METHOD__
);
1339 * Helper function for doAllQuotes()
1341 * @param $text string
1345 public function doQuotes( $text ) {
1346 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1347 if ( count( $arr ) == 1 ) {
1350 # First, do some preliminary work. This may shift some apostrophes from
1351 # being mark-up to being text. It also counts the number of occurrences
1352 # of bold and italics mark-ups.
1355 for ( $i = 0; $i < count( $arr ); $i++
) {
1356 if ( ( $i %
2 ) == 1 ) {
1357 # If there are ever four apostrophes, assume the first is supposed to
1358 # be text, and the remaining three constitute mark-up for bold text.
1359 if ( strlen( $arr[$i] ) == 4 ) {
1362 } elseif ( strlen( $arr[$i] ) > 5 ) {
1363 # If there are more than 5 apostrophes in a row, assume they're all
1364 # text except for the last 5.
1365 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1368 # Count the number of occurrences of bold and italics mark-ups.
1369 # We are not counting sequences of five apostrophes.
1370 if ( strlen( $arr[$i] ) == 2 ) {
1372 } elseif ( strlen( $arr[$i] ) == 3 ) {
1374 } elseif ( strlen( $arr[$i] ) == 5 ) {
1381 # If there is an odd number of both bold and italics, it is likely
1382 # that one of the bold ones was meant to be an apostrophe followed
1383 # by italics. Which one we cannot know for certain, but it is more
1384 # likely to be one that has a single-letter word before it.
1385 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1387 $firstsingleletterword = -1;
1388 $firstmultiletterword = -1;
1390 foreach ( $arr as $r ) {
1391 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1392 $x1 = substr( $arr[$i-1], -1 );
1393 $x2 = substr( $arr[$i-1], -2, 1 );
1394 if ( $x1 === ' ' ) {
1395 if ( $firstspace == -1 ) {
1398 } elseif ( $x2 === ' ') {
1399 if ( $firstsingleletterword == -1 ) {
1400 $firstsingleletterword = $i;
1403 if ( $firstmultiletterword == -1 ) {
1404 $firstmultiletterword = $i;
1411 # If there is a single-letter word, use it!
1412 if ( $firstsingleletterword > -1 ) {
1413 $arr[$firstsingleletterword] = "''";
1414 $arr[$firstsingleletterword-1] .= "'";
1415 } elseif ( $firstmultiletterword > -1 ) {
1416 # If not, but there's a multi-letter word, use that one.
1417 $arr[$firstmultiletterword] = "''";
1418 $arr[$firstmultiletterword-1] .= "'";
1419 } elseif ( $firstspace > -1 ) {
1420 # ... otherwise use the first one that has neither.
1421 # (notice that it is possible for all three to be -1 if, for example,
1422 # there is only one pentuple-apostrophe in the line)
1423 $arr[$firstspace] = "''";
1424 $arr[$firstspace-1] .= "'";
1428 # Now let's actually convert our apostrophic mush to HTML!
1433 foreach ( $arr as $r ) {
1434 if ( ( $i %
2 ) == 0 ) {
1435 if ( $state === 'both' ) {
1441 if ( strlen( $r ) == 2 ) {
1442 if ( $state === 'i' ) {
1443 $output .= '</i>'; $state = '';
1444 } elseif ( $state === 'bi' ) {
1445 $output .= '</i>'; $state = 'b';
1446 } elseif ( $state === 'ib' ) {
1447 $output .= '</b></i><b>'; $state = 'b';
1448 } elseif ( $state === 'both' ) {
1449 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1450 } else { # $state can be 'b' or ''
1451 $output .= '<i>'; $state .= 'i';
1453 } elseif ( strlen( $r ) == 3 ) {
1454 if ( $state === 'b' ) {
1455 $output .= '</b>'; $state = '';
1456 } elseif ( $state === 'bi' ) {
1457 $output .= '</i></b><i>'; $state = 'i';
1458 } elseif ( $state === 'ib' ) {
1459 $output .= '</b>'; $state = 'i';
1460 } elseif ( $state === 'both' ) {
1461 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1462 } else { # $state can be 'i' or ''
1463 $output .= '<b>'; $state .= 'b';
1465 } elseif ( strlen( $r ) == 5 ) {
1466 if ( $state === 'b' ) {
1467 $output .= '</b><i>'; $state = 'i';
1468 } elseif ( $state === 'i' ) {
1469 $output .= '</i><b>'; $state = 'b';
1470 } elseif ( $state === 'bi' ) {
1471 $output .= '</i></b>'; $state = '';
1472 } elseif ( $state === 'ib' ) {
1473 $output .= '</b></i>'; $state = '';
1474 } elseif ( $state === 'both' ) {
1475 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1476 } else { # ($state == '')
1477 $buffer = ''; $state = 'both';
1483 # Now close all remaining tags. Notice that the order is important.
1484 if ( $state === 'b' ||
$state === 'ib' ) {
1487 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1490 if ( $state === 'bi' ) {
1493 # There might be lonely ''''', so make sure we have a buffer
1494 if ( $state === 'both' && $buffer ) {
1495 $output .= '<b><i>'.$buffer.'</i></b>';
1502 * Replace external links (REL)
1504 * Note: this is all very hackish and the order of execution matters a lot.
1505 * Make sure to run maintenance/parserTests.php if you change this code.
1509 * @param $text string
1513 function replaceExternalLinks( $text ) {
1514 wfProfileIn( __METHOD__
);
1516 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1517 $s = array_shift( $bits );
1520 while ( $i<count( $bits ) ) {
1522 $protocol = $bits[$i++
];
1523 $text = $bits[$i++
];
1524 $trail = $bits[$i++
];
1526 # The characters '<' and '>' (which were escaped by
1527 # removeHTMLtags()) should not be included in
1528 # URLs, per RFC 2396.
1530 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1531 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1532 $url = substr( $url, 0, $m2[0][1] );
1535 # If the link text is an image URL, replace it with an <img> tag
1536 # This happened by accident in the original parser, but some people used it extensively
1537 $img = $this->maybeMakeExternalImage( $text );
1538 if ( $img !== false ) {
1544 # Set linktype for CSS - if URL==text, link is essentially free
1545 $linktype = ( $text === $url ) ?
'free' : 'text';
1547 # No link text, e.g. [http://domain.tld/some.link]
1548 if ( $text == '' ) {
1550 $langObj = $this->getTargetLanguage();
1551 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1552 $linktype = 'autonumber';
1554 # Have link text, e.g. [http://domain.tld/some.link text]s
1556 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1559 $text = $this->getConverterLanguage()->markNoConversion( $text );
1561 $url = Sanitizer
::cleanUrl( $url );
1563 # Use the encoded URL
1564 # This means that users can paste URLs directly into the text
1565 # Funny characters like ö aren't valid in URLs anyway
1566 # This was changed in August 2004
1567 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1568 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1570 # Register link in the output object.
1571 # Replace unnecessary URL escape codes with the referenced character
1572 # This prevents spammers from hiding links from the filters
1573 $pasteurized = self
::replaceUnusualEscapes( $url );
1574 $this->mOutput
->addExternalLink( $pasteurized );
1577 wfProfileOut( __METHOD__
);
1582 * Get an associative array of additional HTML attributes appropriate for a
1583 * particular external link. This currently may include rel => nofollow
1584 * (depending on configuration, namespace, and the URL's domain) and/or a
1585 * target attribute (depending on configuration).
1587 * @param $url String|bool optional URL, to extract the domain from for rel =>
1588 * nofollow if appropriate
1589 * @return Array associative array of HTML attributes
1591 function getExternalLinkAttribs( $url = false ) {
1593 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1594 $ns = $this->mTitle
->getNamespace();
1595 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1596 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1598 $attribs['rel'] = 'nofollow';
1600 if ( $this->mOptions
->getExternalLinkTarget() ) {
1601 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1607 * Replace unusual URL escape codes with their equivalent characters
1609 * @param $url String
1612 * @todo This can merge genuinely required bits in the path or query string,
1613 * breaking legit URLs. A proper fix would treat the various parts of
1614 * the URL differently; as a workaround, just use the output for
1615 * statistical records, not for actual linking/output.
1617 static function replaceUnusualEscapes( $url ) {
1618 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1619 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1623 * Callback function used in replaceUnusualEscapes().
1624 * Replaces unusual URL escape codes with their equivalent character
1626 * @param $matches array
1630 private static function replaceUnusualEscapesCallback( $matches ) {
1631 $char = urldecode( $matches[0] );
1632 $ord = ord( $char );
1633 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1634 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1635 # No, shouldn't be escaped
1638 # Yes, leave it escaped
1644 * make an image if it's allowed, either through the global
1645 * option, through the exception, or through the on-wiki whitelist
1648 * $param $url string
1652 function maybeMakeExternalImage( $url ) {
1653 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1654 $imagesexception = !empty( $imagesfrom );
1656 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1657 if ( $imagesexception && is_array( $imagesfrom ) ) {
1658 $imagematch = false;
1659 foreach ( $imagesfrom as $match ) {
1660 if ( strpos( $url, $match ) === 0 ) {
1665 } elseif ( $imagesexception ) {
1666 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1668 $imagematch = false;
1670 if ( $this->mOptions
->getAllowExternalImages()
1671 ||
( $imagesexception && $imagematch ) ) {
1672 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1674 $text = Linker
::makeExternalImage( $url );
1677 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1678 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1679 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1680 foreach ( $whitelist as $entry ) {
1681 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1682 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1685 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1686 # Image matches a whitelist entry
1687 $text = Linker
::makeExternalImage( $url );
1696 * Process [[ ]] wikilinks
1700 * @return String: processed text
1704 function replaceInternalLinks( $s ) {
1705 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1710 * Process [[ ]] wikilinks (RIL)
1711 * @return LinkHolderArray
1715 function replaceInternalLinks2( &$s ) {
1716 wfProfileIn( __METHOD__
);
1718 wfProfileIn( __METHOD__
.'-setup' );
1719 static $tc = FALSE, $e1, $e1_img;
1720 # the % is needed to support urlencoded titles as well
1722 $tc = Title
::legalChars() . '#%';
1723 # Match a link having the form [[namespace:link|alternate]]trail
1724 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1725 # Match cases where there is no "]]", which might still be images
1726 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1729 $holders = new LinkHolderArray( $this );
1731 # split the entire text string on occurrences of [[
1732 $a = StringUtils
::explode( '[[', ' ' . $s );
1733 # get the first element (all text up to first [[), and remove the space we added
1736 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1737 $s = substr( $s, 1 );
1739 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1741 if ( $useLinkPrefixExtension ) {
1742 # Match the end of a line for a word that's not followed by whitespace,
1743 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1744 $e2 = wfMsgForContent( 'linkprefix' );
1747 if ( is_null( $this->mTitle
) ) {
1748 wfProfileOut( __METHOD__
.'-setup' );
1749 wfProfileOut( __METHOD__
);
1750 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1752 $nottalk = !$this->mTitle
->isTalkPage();
1754 if ( $useLinkPrefixExtension ) {
1756 if ( preg_match( $e2, $s, $m ) ) {
1757 $first_prefix = $m[2];
1759 $first_prefix = false;
1765 if ( $this->getConverterLanguage()->hasVariants() ) {
1766 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1767 $this->mTitle
->getPrefixedText() );
1769 $selflink = array( $this->mTitle
->getPrefixedText() );
1771 $useSubpages = $this->areSubpagesAllowed();
1772 wfProfileOut( __METHOD__
.'-setup' );
1774 # Loop for each link
1775 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1776 # Check for excessive memory usage
1777 if ( $holders->isBig() ) {
1779 # Do the existence check, replace the link holders and clear the array
1780 $holders->replace( $s );
1784 if ( $useLinkPrefixExtension ) {
1785 wfProfileIn( __METHOD__
.'-prefixhandling' );
1786 if ( preg_match( $e2, $s, $m ) ) {
1793 if ( $first_prefix ) {
1794 $prefix = $first_prefix;
1795 $first_prefix = false;
1797 wfProfileOut( __METHOD__
.'-prefixhandling' );
1800 $might_be_img = false;
1802 wfProfileIn( __METHOD__
."-e1" );
1803 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1805 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1806 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1807 # the real problem is with the $e1 regex
1810 # Still some problems for cases where the ] is meant to be outside punctuation,
1811 # and no image is in sight. See bug 2095.
1813 if ( $text !== '' &&
1814 substr( $m[3], 0, 1 ) === ']' &&
1815 strpos( $text, '[' ) !== false
1818 $text .= ']'; # so that replaceExternalLinks($text) works later
1819 $m[3] = substr( $m[3], 1 );
1821 # fix up urlencoded title texts
1822 if ( strpos( $m[1], '%' ) !== false ) {
1823 # Should anchors '#' also be rejected?
1824 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1827 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1828 $might_be_img = true;
1830 if ( strpos( $m[1], '%' ) !== false ) {
1831 $m[1] = rawurldecode( $m[1] );
1834 } else { # Invalid form; output directly
1835 $s .= $prefix . '[[' . $line ;
1836 wfProfileOut( __METHOD__
."-e1" );
1839 wfProfileOut( __METHOD__
."-e1" );
1840 wfProfileIn( __METHOD__
."-misc" );
1842 # Don't allow internal links to pages containing
1843 # PROTO: where PROTO is a valid URL protocol; these
1844 # should be external links.
1845 if ( preg_match( '/^(?:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1846 $s .= $prefix . '[[' . $line ;
1847 wfProfileOut( __METHOD__
."-misc" );
1851 # Make subpage if necessary
1852 if ( $useSubpages ) {
1853 $link = $this->maybeDoSubpageLink( $m[1], $text );
1858 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1860 # Strip off leading ':'
1861 $link = substr( $link, 1 );
1864 wfProfileOut( __METHOD__
."-misc" );
1865 wfProfileIn( __METHOD__
."-title" );
1866 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1867 if ( $nt === null ) {
1868 $s .= $prefix . '[[' . $line;
1869 wfProfileOut( __METHOD__
."-title" );
1873 $ns = $nt->getNamespace();
1874 $iw = $nt->getInterWiki();
1875 wfProfileOut( __METHOD__
."-title" );
1877 if ( $might_be_img ) { # if this is actually an invalid link
1878 wfProfileIn( __METHOD__
."-might_be_img" );
1879 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1882 # look at the next 'line' to see if we can close it there
1884 $next_line = $a->current();
1885 if ( $next_line === false ||
$next_line === null ) {
1888 $m = explode( ']]', $next_line, 3 );
1889 if ( count( $m ) == 3 ) {
1890 # the first ]] closes the inner link, the second the image
1892 $text .= "[[{$m[0]}]]{$m[1]}";
1895 } elseif ( count( $m ) == 2 ) {
1896 # if there's exactly one ]] that's fine, we'll keep looking
1897 $text .= "[[{$m[0]}]]{$m[1]}";
1899 # if $next_line is invalid too, we need look no further
1900 $text .= '[[' . $next_line;
1905 # we couldn't find the end of this imageLink, so output it raw
1906 # but don't ignore what might be perfectly normal links in the text we've examined
1907 $holders->merge( $this->replaceInternalLinks2( $text ) );
1908 $s .= "{$prefix}[[$link|$text";
1909 # note: no $trail, because without an end, there *is* no trail
1910 wfProfileOut( __METHOD__
."-might_be_img" );
1913 } else { # it's not an image, so output it raw
1914 $s .= "{$prefix}[[$link|$text";
1915 # note: no $trail, because without an end, there *is* no trail
1916 wfProfileOut( __METHOD__
."-might_be_img" );
1919 wfProfileOut( __METHOD__
."-might_be_img" );
1922 $wasblank = ( $text == '' );
1926 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1927 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1928 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1929 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1930 $text = $this->doQuotes( $text );
1933 # Link not escaped by : , create the various objects
1936 wfProfileIn( __METHOD__
."-interwiki" );
1937 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1938 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1939 $s = rtrim( $s . $prefix );
1940 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1941 wfProfileOut( __METHOD__
."-interwiki" );
1944 wfProfileOut( __METHOD__
."-interwiki" );
1946 if ( $ns == NS_FILE
) {
1947 wfProfileIn( __METHOD__
."-image" );
1948 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1950 # if no parameters were passed, $text
1951 # becomes something like "File:Foo.png",
1952 # which we don't want to pass on to the
1956 # recursively parse links inside the image caption
1957 # actually, this will parse them in any other parameters, too,
1958 # but it might be hard to fix that, and it doesn't matter ATM
1959 $text = $this->replaceExternalLinks( $text );
1960 $holders->merge( $this->replaceInternalLinks2( $text ) );
1962 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1963 $s .= $prefix . $this->armorLinks(
1964 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1966 $s .= $prefix . $trail;
1968 wfProfileOut( __METHOD__
."-image" );
1972 if ( $ns == NS_CATEGORY
) {
1973 wfProfileIn( __METHOD__
."-category" );
1974 $s = rtrim( $s . "\n" ); # bug 87
1977 $sortkey = $this->getDefaultSort();
1981 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1982 $sortkey = str_replace( "\n", '', $sortkey );
1983 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1984 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1987 * Strip the whitespace Category links produce, see bug 87
1988 * @todo We might want to use trim($tmp, "\n") here.
1990 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1992 wfProfileOut( __METHOD__
."-category" );
1997 # Self-link checking
1998 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1999 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2000 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2005 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2006 # @todo FIXME: Should do batch file existence checks, see comment below
2007 if ( $ns == NS_MEDIA
) {
2008 wfProfileIn( __METHOD__
."-media" );
2009 # Give extensions a chance to select the file revision for us
2012 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2013 array( $this, $nt, &$options, &$descQuery ) );
2014 # Fetch and register the file (file title may be different via hooks)
2015 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2016 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2017 $s .= $prefix . $this->armorLinks(
2018 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2019 wfProfileOut( __METHOD__
."-media" );
2023 wfProfileIn( __METHOD__
."-always_known" );
2024 # Some titles, such as valid special pages or files in foreign repos, should
2025 # be shown as bluelinks even though they're not included in the page table
2027 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2028 # batch file existence checks for NS_FILE and NS_MEDIA
2029 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2030 $this->mOutput
->addLink( $nt );
2031 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2033 # Links will be added to the output link list after checking
2034 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2036 wfProfileOut( __METHOD__
."-always_known" );
2038 wfProfileOut( __METHOD__
);
2043 * Render a forced-blue link inline; protect against double expansion of
2044 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2045 * Since this little disaster has to split off the trail text to avoid
2046 * breaking URLs in the following text without breaking trails on the
2047 * wiki links, it's been made into a horrible function.
2050 * @param $text String
2051 * @param $query Array or String
2052 * @param $trail String
2053 * @param $prefix String
2054 * @return String: HTML-wikitext mix oh yuck
2056 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2057 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2059 if ( is_string( $query ) ) {
2060 $query = wfCgiToArray( $query );
2062 if ( $text == '' ) {
2063 $text = htmlspecialchars( $nt->getPrefixedText() );
2066 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2068 return $this->armorLinks( $link ) . $trail;
2072 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2073 * going to go through further parsing steps before inline URL expansion.
2075 * Not needed quite as much as it used to be since free links are a bit
2076 * more sensible these days. But bracketed links are still an issue.
2078 * @param $text String: more-or-less HTML
2079 * @return String: less-or-more HTML with NOPARSE bits
2081 function armorLinks( $text ) {
2082 return preg_replace( '/\b(' . $this->mUrlProtocols
. ')/',
2083 "{$this->mUniqPrefix}NOPARSE$1", $text );
2087 * Return true if subpage links should be expanded on this page.
2090 function areSubpagesAllowed() {
2091 # Some namespaces don't allow subpages
2092 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2096 * Handle link to subpage if necessary
2098 * @param $target String: the source of the link
2099 * @param &$text String: the link text, modified as necessary
2100 * @return string the full name of the link
2103 function maybeDoSubpageLink( $target, &$text ) {
2104 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2108 * Used by doBlockLevels()
2113 function closeParagraph() {
2115 if ( $this->mLastSection
!= '' ) {
2116 $result = '</' . $this->mLastSection
. ">\n";
2118 $this->mInPre
= false;
2119 $this->mLastSection
= '';
2124 * getCommon() returns the length of the longest common substring
2125 * of both arguments, starting at the beginning of both.
2128 * @param $st1 string
2129 * @param $st2 string
2133 function getCommon( $st1, $st2 ) {
2134 $fl = strlen( $st1 );
2135 $shorter = strlen( $st2 );
2136 if ( $fl < $shorter ) {
2140 for ( $i = 0; $i < $shorter; ++
$i ) {
2141 if ( $st1[$i] != $st2[$i] ) {
2149 * These next three functions open, continue, and close the list
2150 * element appropriate to the prefix character passed into them.
2153 * @param $char string
2157 function openList( $char ) {
2158 $result = $this->closeParagraph();
2160 if ( '*' === $char ) {
2161 $result .= '<ul><li>';
2162 } elseif ( '#' === $char ) {
2163 $result .= '<ol><li>';
2164 } elseif ( ':' === $char ) {
2165 $result .= '<dl><dd>';
2166 } elseif ( ';' === $char ) {
2167 $result .= '<dl><dt>';
2168 $this->mDTopen
= true;
2170 $result = '<!-- ERR 1 -->';
2178 * @param $char String
2183 function nextItem( $char ) {
2184 if ( '*' === $char ||
'#' === $char ) {
2186 } elseif ( ':' === $char ||
';' === $char ) {
2188 if ( $this->mDTopen
) {
2191 if ( ';' === $char ) {
2192 $this->mDTopen
= true;
2193 return $close . '<dt>';
2195 $this->mDTopen
= false;
2196 return $close . '<dd>';
2199 return '<!-- ERR 2 -->';
2204 * @param $char String
2209 function closeList( $char ) {
2210 if ( '*' === $char ) {
2211 $text = '</li></ul>';
2212 } elseif ( '#' === $char ) {
2213 $text = '</li></ol>';
2214 } elseif ( ':' === $char ) {
2215 if ( $this->mDTopen
) {
2216 $this->mDTopen
= false;
2217 $text = '</dt></dl>';
2219 $text = '</dd></dl>';
2222 return '<!-- ERR 3 -->';
2229 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2231 * @param $text String
2232 * @param $linestart Boolean: whether or not this is at the start of a line.
2234 * @return string the lists rendered as HTML
2236 function doBlockLevels( $text, $linestart ) {
2237 wfProfileIn( __METHOD__
);
2239 # Parsing through the text line by line. The main thing
2240 # happening here is handling of block-level elements p, pre,
2241 # and making lists from lines starting with * # : etc.
2243 $textLines = StringUtils
::explode( "\n", $text );
2245 $lastPrefix = $output = '';
2246 $this->mDTopen
= $inBlockElem = false;
2248 $paragraphStack = false;
2250 foreach ( $textLines as $oLine ) {
2252 if ( !$linestart ) {
2262 $lastPrefixLength = strlen( $lastPrefix );
2263 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2264 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2265 # If not in a <pre> element, scan for and figure out what prefixes are there.
2266 if ( !$this->mInPre
) {
2267 # Multiple prefixes may abut each other for nested lists.
2268 $prefixLength = strspn( $oLine, '*#:;' );
2269 $prefix = substr( $oLine, 0, $prefixLength );
2272 # ; and : are both from definition-lists, so they're equivalent
2273 # for the purposes of determining whether or not we need to open/close
2275 $prefix2 = str_replace( ';', ':', $prefix );
2276 $t = substr( $oLine, $prefixLength );
2277 $this->mInPre
= (bool)$preOpenMatch;
2279 # Don't interpret any other prefixes in preformatted text
2281 $prefix = $prefix2 = '';
2286 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2287 # Same as the last item, so no need to deal with nesting or opening stuff
2288 $output .= $this->nextItem( substr( $prefix, -1 ) );
2289 $paragraphStack = false;
2291 if ( substr( $prefix, -1 ) === ';') {
2292 # The one nasty exception: definition lists work like this:
2293 # ; title : definition text
2294 # So we check for : in the remainder text to split up the
2295 # title and definition, without b0rking links.
2297 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2299 $output .= $term . $this->nextItem( ':' );
2302 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2303 # We need to open or close prefixes, or both.
2305 # Either open or close a level...
2306 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2307 $paragraphStack = false;
2309 # Close all the prefixes which aren't shared.
2310 while ( $commonPrefixLength < $lastPrefixLength ) {
2311 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2312 --$lastPrefixLength;
2315 # Continue the current prefix if appropriate.
2316 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2317 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2320 # Open prefixes where appropriate.
2321 while ( $prefixLength > $commonPrefixLength ) {
2322 $char = substr( $prefix, $commonPrefixLength, 1 );
2323 $output .= $this->openList( $char );
2325 if ( ';' === $char ) {
2326 # @todo FIXME: This is dupe of code above
2327 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2329 $output .= $term . $this->nextItem( ':' );
2332 ++
$commonPrefixLength;
2334 $lastPrefix = $prefix2;
2337 # If we have no prefixes, go to paragraph mode.
2338 if ( 0 == $prefixLength ) {
2339 wfProfileIn( __METHOD__
."-paragraph" );
2340 # No prefix (not in list)--go to paragraph mode
2341 # XXX: use a stack for nestable elements like span, table and div
2342 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2343 $closematch = preg_match(
2344 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2345 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2346 if ( $openmatch or $closematch ) {
2347 $paragraphStack = false;
2348 # TODO bug 5718: paragraph closed
2349 $output .= $this->closeParagraph();
2350 if ( $preOpenMatch and !$preCloseMatch ) {
2351 $this->mInPre
= true;
2353 $inBlockElem = !$closematch;
2354 } elseif ( !$inBlockElem && !$this->mInPre
) {
2355 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2357 if ( $this->mLastSection
!== 'pre' ) {
2358 $paragraphStack = false;
2359 $output .= $this->closeParagraph().'<pre>';
2360 $this->mLastSection
= 'pre';
2362 $t = substr( $t, 1 );
2365 if ( trim( $t ) === '' ) {
2366 if ( $paragraphStack ) {
2367 $output .= $paragraphStack.'<br />';
2368 $paragraphStack = false;
2369 $this->mLastSection
= 'p';
2371 if ( $this->mLastSection
!== 'p' ) {
2372 $output .= $this->closeParagraph();
2373 $this->mLastSection
= '';
2374 $paragraphStack = '<p>';
2376 $paragraphStack = '</p><p>';
2380 if ( $paragraphStack ) {
2381 $output .= $paragraphStack;
2382 $paragraphStack = false;
2383 $this->mLastSection
= 'p';
2384 } elseif ( $this->mLastSection
!== 'p' ) {
2385 $output .= $this->closeParagraph().'<p>';
2386 $this->mLastSection
= 'p';
2391 wfProfileOut( __METHOD__
."-paragraph" );
2393 # somewhere above we forget to get out of pre block (bug 785)
2394 if ( $preCloseMatch && $this->mInPre
) {
2395 $this->mInPre
= false;
2397 if ( $paragraphStack === false ) {
2401 while ( $prefixLength ) {
2402 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2405 if ( $this->mLastSection
!= '' ) {
2406 $output .= '</' . $this->mLastSection
. '>';
2407 $this->mLastSection
= '';
2410 wfProfileOut( __METHOD__
);
2415 * Split up a string on ':', ignoring any occurrences inside tags
2416 * to prevent illegal overlapping.
2418 * @param $str String the string to split
2419 * @param &$before String set to everything before the ':'
2420 * @param &$after String set to everything after the ':'
2421 * @return String the position of the ':', or false if none found
2423 function findColonNoLinks( $str, &$before, &$after ) {
2424 wfProfileIn( __METHOD__
);
2426 $pos = strpos( $str, ':' );
2427 if ( $pos === false ) {
2429 wfProfileOut( __METHOD__
);
2433 $lt = strpos( $str, '<' );
2434 if ( $lt === false ||
$lt > $pos ) {
2435 # Easy; no tag nesting to worry about
2436 $before = substr( $str, 0, $pos );
2437 $after = substr( $str, $pos+
1 );
2438 wfProfileOut( __METHOD__
);
2442 # Ugly state machine to walk through avoiding tags.
2443 $state = self
::COLON_STATE_TEXT
;
2445 $len = strlen( $str );
2446 for( $i = 0; $i < $len; $i++
) {
2450 # (Using the number is a performance hack for common cases)
2451 case 0: # self::COLON_STATE_TEXT:
2454 # Could be either a <start> tag or an </end> tag
2455 $state = self
::COLON_STATE_TAGSTART
;
2458 if ( $stack == 0 ) {
2460 $before = substr( $str, 0, $i );
2461 $after = substr( $str, $i +
1 );
2462 wfProfileOut( __METHOD__
);
2465 # Embedded in a tag; don't break it.
2468 # Skip ahead looking for something interesting
2469 $colon = strpos( $str, ':', $i );
2470 if ( $colon === false ) {
2471 # Nothing else interesting
2472 wfProfileOut( __METHOD__
);
2475 $lt = strpos( $str, '<', $i );
2476 if ( $stack === 0 ) {
2477 if ( $lt === false ||
$colon < $lt ) {
2479 $before = substr( $str, 0, $colon );
2480 $after = substr( $str, $colon +
1 );
2481 wfProfileOut( __METHOD__
);
2485 if ( $lt === false ) {
2486 # Nothing else interesting to find; abort!
2487 # We're nested, but there's no close tags left. Abort!
2490 # Skip ahead to next tag start
2492 $state = self
::COLON_STATE_TAGSTART
;
2495 case 1: # self::COLON_STATE_TAG:
2500 $state = self
::COLON_STATE_TEXT
;
2503 # Slash may be followed by >?
2504 $state = self
::COLON_STATE_TAGSLASH
;
2510 case 2: # self::COLON_STATE_TAGSTART:
2513 $state = self
::COLON_STATE_CLOSETAG
;
2516 $state = self
::COLON_STATE_COMMENT
;
2519 # Illegal early close? This shouldn't happen D:
2520 $state = self
::COLON_STATE_TEXT
;
2523 $state = self
::COLON_STATE_TAG
;
2526 case 3: # self::COLON_STATE_CLOSETAG:
2531 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2532 wfProfileOut( __METHOD__
);
2535 $state = self
::COLON_STATE_TEXT
;
2538 case self
::COLON_STATE_TAGSLASH
:
2540 # Yes, a self-closed tag <blah/>
2541 $state = self
::COLON_STATE_TEXT
;
2543 # Probably we're jumping the gun, and this is an attribute
2544 $state = self
::COLON_STATE_TAG
;
2547 case 5: # self::COLON_STATE_COMMENT:
2549 $state = self
::COLON_STATE_COMMENTDASH
;
2552 case self
::COLON_STATE_COMMENTDASH
:
2554 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2556 $state = self
::COLON_STATE_COMMENT
;
2559 case self
::COLON_STATE_COMMENTDASHDASH
:
2561 $state = self
::COLON_STATE_TEXT
;
2563 $state = self
::COLON_STATE_COMMENT
;
2567 throw new MWException( "State machine error in " . __METHOD__
);
2571 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2572 wfProfileOut( __METHOD__
);
2575 wfProfileOut( __METHOD__
);
2580 * Return value of a magic variable (like PAGENAME)
2584 * @param $index integer
2585 * @param $frame PPFrame
2589 function getVariableValue( $index, $frame = false ) {
2590 global $wgContLang, $wgSitename, $wgServer;
2591 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2593 if ( is_null( $this->mTitle
) ) {
2594 // If no title set, bad things are going to happen
2595 // later. Title should always be set since this
2596 // should only be called in the middle of a parse
2597 // operation (but the unit-tests do funky stuff)
2598 throw new MWException( __METHOD__
. ' Should only be '
2599 . ' called while parsing (no title set)' );
2603 * Some of these require message or data lookups and can be
2604 * expensive to check many times.
2606 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2607 if ( isset( $this->mVarCache
[$index] ) ) {
2608 return $this->mVarCache
[$index];
2612 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2613 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2616 global $wgLocaltimezone;
2617 if ( isset( $wgLocaltimezone ) ) {
2618 $oldtz = date_default_timezone_get();
2619 date_default_timezone_set( $wgLocaltimezone );
2622 $localTimestamp = date( 'YmdHis', $ts );
2623 $localMonth = date( 'm', $ts );
2624 $localMonth1 = date( 'n', $ts );
2625 $localMonthName = date( 'n', $ts );
2626 $localDay = date( 'j', $ts );
2627 $localDay2 = date( 'd', $ts );
2628 $localDayOfWeek = date( 'w', $ts );
2629 $localWeek = date( 'W', $ts );
2630 $localYear = date( 'Y', $ts );
2631 $localHour = date( 'H', $ts );
2632 if ( isset( $wgLocaltimezone ) ) {
2633 date_default_timezone_set( $oldtz );
2636 $pageLang = $this->getFunctionLang();
2639 case 'currentmonth':
2640 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2642 case 'currentmonth1':
2643 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2645 case 'currentmonthname':
2646 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2648 case 'currentmonthnamegen':
2649 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2651 case 'currentmonthabbrev':
2652 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2655 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2658 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2661 $value = $pageLang->formatNum( $localMonth );
2664 $value = $pageLang->formatNum( $localMonth1 );
2666 case 'localmonthname':
2667 $value = $pageLang->getMonthName( $localMonthName );
2669 case 'localmonthnamegen':
2670 $value = $pageLang->getMonthNameGen( $localMonthName );
2672 case 'localmonthabbrev':
2673 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2676 $value = $pageLang->formatNum( $localDay );
2679 $value = $pageLang->formatNum( $localDay2 );
2682 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2685 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2687 case 'fullpagename':
2688 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2690 case 'fullpagenamee':
2691 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2694 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2696 case 'subpagenamee':
2697 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2699 case 'basepagename':
2700 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2702 case 'basepagenamee':
2703 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2705 case 'talkpagename':
2706 if ( $this->mTitle
->canTalk() ) {
2707 $talkPage = $this->mTitle
->getTalkPage();
2708 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2713 case 'talkpagenamee':
2714 if ( $this->mTitle
->canTalk() ) {
2715 $talkPage = $this->mTitle
->getTalkPage();
2716 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2721 case 'subjectpagename':
2722 $subjPage = $this->mTitle
->getSubjectPage();
2723 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2725 case 'subjectpagenamee':
2726 $subjPage = $this->mTitle
->getSubjectPage();
2727 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2729 case 'pageid': // requested in bug 23427
2730 $pageid = $this->getTitle()->getArticleId();
2731 if( $pageid == 0 ) {
2732 # 0 means the page doesn't exist in the database,
2733 # which means the user is previewing a new page.
2734 # The vary-revision flag must be set, because the magic word
2735 # will have a different value once the page is saved.
2736 $this->mOutput
->setFlag( 'vary-revision' );
2737 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2739 $value = $pageid ?
$pageid : null;
2742 # Let the edit saving system know we should parse the page
2743 # *after* a revision ID has been assigned.
2744 $this->mOutput
->setFlag( 'vary-revision' );
2745 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2746 $value = $this->mRevisionId
;
2749 # Let the edit saving system know we should parse the page
2750 # *after* a revision ID has been assigned. This is for null edits.
2751 $this->mOutput
->setFlag( 'vary-revision' );
2752 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2753 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2755 case 'revisionday2':
2756 # Let the edit saving system know we should parse the page
2757 # *after* a revision ID has been assigned. This is for null edits.
2758 $this->mOutput
->setFlag( 'vary-revision' );
2759 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2760 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2762 case 'revisionmonth':
2763 # Let the edit saving system know we should parse the page
2764 # *after* a revision ID has been assigned. This is for null edits.
2765 $this->mOutput
->setFlag( 'vary-revision' );
2766 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2767 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2769 case 'revisionmonth1':
2770 # Let the edit saving system know we should parse the page
2771 # *after* a revision ID has been assigned. This is for null edits.
2772 $this->mOutput
->setFlag( 'vary-revision' );
2773 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2774 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2776 case 'revisionyear':
2777 # Let the edit saving system know we should parse the page
2778 # *after* a revision ID has been assigned. This is for null edits.
2779 $this->mOutput
->setFlag( 'vary-revision' );
2780 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2781 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2783 case 'revisiontimestamp':
2784 # Let the edit saving system know we should parse the page
2785 # *after* a revision ID has been assigned. This is for null edits.
2786 $this->mOutput
->setFlag( 'vary-revision' );
2787 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2788 $value = $this->getRevisionTimestamp();
2790 case 'revisionuser':
2791 # Let the edit saving system know we should parse the page
2792 # *after* a revision ID has been assigned. This is for null edits.
2793 $this->mOutput
->setFlag( 'vary-revision' );
2794 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2795 $value = $this->getRevisionUser();
2798 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2801 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2803 case 'namespacenumber':
2804 $value = $this->mTitle
->getNamespace();
2807 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2810 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2812 case 'subjectspace':
2813 $value = $this->mTitle
->getSubjectNsText();
2815 case 'subjectspacee':
2816 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2818 case 'currentdayname':
2819 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2822 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2825 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2828 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2831 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2832 # int to remove the padding
2833 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2836 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2838 case 'localdayname':
2839 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2842 $value = $pageLang->formatNum( $localYear, true );
2845 $value = $pageLang->time( $localTimestamp, false, false );
2848 $value = $pageLang->formatNum( $localHour, true );
2851 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2852 # int to remove the padding
2853 $value = $pageLang->formatNum( (int)$localWeek );
2856 $value = $pageLang->formatNum( $localDayOfWeek );
2858 case 'numberofarticles':
2859 $value = $pageLang->formatNum( SiteStats
::articles() );
2861 case 'numberoffiles':
2862 $value = $pageLang->formatNum( SiteStats
::images() );
2864 case 'numberofusers':
2865 $value = $pageLang->formatNum( SiteStats
::users() );
2867 case 'numberofactiveusers':
2868 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2870 case 'numberofpages':
2871 $value = $pageLang->formatNum( SiteStats
::pages() );
2873 case 'numberofadmins':
2874 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2876 case 'numberofedits':
2877 $value = $pageLang->formatNum( SiteStats
::edits() );
2879 case 'numberofviews':
2880 global $wgDisableCounters;
2881 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2883 case 'currenttimestamp':
2884 $value = wfTimestamp( TS_MW
, $ts );
2886 case 'localtimestamp':
2887 $value = $localTimestamp;
2889 case 'currentversion':
2890 $value = SpecialVersion
::getVersion();
2893 return $wgArticlePath;
2899 $serverParts = wfParseUrl( $wgServer );
2900 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2902 return $wgScriptPath;
2904 return $wgStylePath;
2905 case 'directionmark':
2906 return $pageLang->getDirMark();
2907 case 'contentlanguage':
2908 global $wgLanguageCode;
2909 return $wgLanguageCode;
2912 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2920 $this->mVarCache
[$index] = $value;
2927 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2931 function initialiseVariables() {
2932 wfProfileIn( __METHOD__
);
2933 $variableIDs = MagicWord
::getVariableIDs();
2934 $substIDs = MagicWord
::getSubstIDs();
2936 $this->mVariables
= new MagicWordArray( $variableIDs );
2937 $this->mSubstWords
= new MagicWordArray( $substIDs );
2938 wfProfileOut( __METHOD__
);
2942 * Preprocess some wikitext and return the document tree.
2943 * This is the ghost of replace_variables().
2945 * @param $text String: The text to parse
2946 * @param $flags Integer: bitwise combination of:
2947 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2948 * included. Default is to assume a direct page view.
2950 * The generated DOM tree must depend only on the input text and the flags.
2951 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2953 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2954 * change in the DOM tree for a given text, must be passed through the section identifier
2955 * in the section edit link and thus back to extractSections().
2957 * The output of this function is currently only cached in process memory, but a persistent
2958 * cache may be implemented at a later date which takes further advantage of these strict
2959 * dependency requirements.
2965 function preprocessToDom( $text, $flags = 0 ) {
2966 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2971 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2977 public static function splitWhitespace( $s ) {
2978 $ltrimmed = ltrim( $s );
2979 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2980 $trimmed = rtrim( $ltrimmed );
2981 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2983 $w2 = substr( $ltrimmed, -$diff );
2987 return array( $w1, $trimmed, $w2 );
2991 * Replace magic variables, templates, and template arguments
2992 * with the appropriate text. Templates are substituted recursively,
2993 * taking care to avoid infinite loops.
2995 * Note that the substitution depends on value of $mOutputType:
2996 * self::OT_WIKI: only {{subst:}} templates
2997 * self::OT_PREPROCESS: templates but not extension tags
2998 * self::OT_HTML: all templates and extension tags
3000 * @param $text String the text to transform
3001 * @param $frame PPFrame Object describing the arguments passed to the template.
3002 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3003 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3004 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3009 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3010 # Is there any text? Also, Prevent too big inclusions!
3011 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3014 wfProfileIn( __METHOD__
);
3016 if ( $frame === false ) {
3017 $frame = $this->getPreprocessor()->newFrame();
3018 } elseif ( !( $frame instanceof PPFrame
) ) {
3019 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3020 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3023 $dom = $this->preprocessToDom( $text );
3024 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3025 $text = $frame->expand( $dom, $flags );
3027 wfProfileOut( __METHOD__
);
3032 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3034 * @param $args array
3038 static function createAssocArgs( $args ) {
3039 $assocArgs = array();
3041 foreach ( $args as $arg ) {
3042 $eqpos = strpos( $arg, '=' );
3043 if ( $eqpos === false ) {
3044 $assocArgs[$index++
] = $arg;
3046 $name = trim( substr( $arg, 0, $eqpos ) );
3047 $value = trim( substr( $arg, $eqpos+
1 ) );
3048 if ( $value === false ) {
3051 if ( $name !== false ) {
3052 $assocArgs[$name] = $value;
3061 * Warn the user when a parser limitation is reached
3062 * Will warn at most once the user per limitation type
3064 * @param $limitationType String: should be one of:
3065 * 'expensive-parserfunction' (corresponding messages:
3066 * 'expensive-parserfunction-warning',
3067 * 'expensive-parserfunction-category')
3068 * 'post-expand-template-argument' (corresponding messages:
3069 * 'post-expand-template-argument-warning',
3070 * 'post-expand-template-argument-category')
3071 * 'post-expand-template-inclusion' (corresponding messages:
3072 * 'post-expand-template-inclusion-warning',
3073 * 'post-expand-template-inclusion-category')
3074 * @param $current int|null Current value
3075 * @param $max int|null Maximum allowed, when an explicit limit has been
3076 * exceeded, provide the values (optional)
3078 function limitationWarn( $limitationType, $current = null, $max = null) {
3079 # does no harm if $current and $max are present but are unnecessary for the message
3080 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3081 $this->mOutput
->addWarning( $warning );
3082 $this->addTrackingCategory( "$limitationType-category" );
3086 * Return the text of a template, after recursively
3087 * replacing any variables or templates within the template.
3089 * @param $piece Array: the parts of the template
3090 * $piece['title']: the title, i.e. the part before the |
3091 * $piece['parts']: the parameter array
3092 * $piece['lineStart']: whether the brace was at the start of a line
3093 * @param $frame PPFrame The current frame, contains template arguments
3094 * @return String: the text of the template
3097 function braceSubstitution( $piece, $frame ) {
3099 wfProfileIn( __METHOD__
);
3100 wfProfileIn( __METHOD__
.'-setup' );
3103 $found = false; # $text has been filled
3104 $nowiki = false; # wiki markup in $text should be escaped
3105 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3106 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3107 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3108 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3110 # Title object, where $text came from
3113 # $part1 is the bit before the first |, and must contain only title characters.
3114 # Various prefixes will be stripped from it later.
3115 $titleWithSpaces = $frame->expand( $piece['title'] );
3116 $part1 = trim( $titleWithSpaces );
3119 # Original title text preserved for various purposes
3120 $originalTitle = $part1;
3122 # $args is a list of argument nodes, starting from index 0, not including $part1
3123 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3124 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3125 wfProfileOut( __METHOD__
.'-setup' );
3127 $titleProfileIn = null; // profile templates
3130 wfProfileIn( __METHOD__
.'-modifiers' );
3133 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3135 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3136 # Decide whether to expand template or keep wikitext as-is.
3137 if ( $this->ot
['wiki'] ) {
3138 if ( $substMatch === false ) {
3139 $literal = true; # literal when in PST with no prefix
3141 $literal = false; # expand when in PST with subst: or safesubst:
3144 if ( $substMatch == 'subst' ) {
3145 $literal = true; # literal when not in PST with plain subst:
3147 $literal = false; # expand when not in PST with safesubst: or no prefix
3151 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3158 if ( !$found && $args->getLength() == 0 ) {
3159 $id = $this->mVariables
->matchStartToEnd( $part1 );
3160 if ( $id !== false ) {
3161 $text = $this->getVariableValue( $id, $frame );
3162 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3163 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3169 # MSG, MSGNW and RAW
3172 $mwMsgnw = MagicWord
::get( 'msgnw' );
3173 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3176 # Remove obsolete MSG:
3177 $mwMsg = MagicWord
::get( 'msg' );
3178 $mwMsg->matchStartAndRemove( $part1 );
3182 $mwRaw = MagicWord
::get( 'raw' );
3183 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3184 $forceRawInterwiki = true;
3187 wfProfileOut( __METHOD__
.'-modifiers' );
3191 wfProfileIn( __METHOD__
. '-pfunc' );
3193 $colonPos = strpos( $part1, ':' );
3194 if ( $colonPos !== false ) {
3195 # Case sensitive functions
3196 $function = substr( $part1, 0, $colonPos );
3197 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3198 $function = $this->mFunctionSynonyms
[1][$function];
3200 # Case insensitive functions
3201 $function = $wgContLang->lc( $function );
3202 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3203 $function = $this->mFunctionSynonyms
[0][$function];
3209 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3210 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3211 $initialArgs = array( &$this );
3212 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3213 if ( $flags & SFH_OBJECT_ARGS
) {
3214 # Add a frame parameter, and pass the arguments as an array
3215 $allArgs = $initialArgs;
3216 $allArgs[] = $frame;
3217 for ( $i = 0; $i < $args->getLength(); $i++
) {
3218 $funcArgs[] = $args->item( $i );
3220 $allArgs[] = $funcArgs;
3222 # Convert arguments to plain text
3223 for ( $i = 0; $i < $args->getLength(); $i++
) {
3224 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3226 $allArgs = array_merge( $initialArgs, $funcArgs );
3229 # Workaround for PHP bug 35229 and similar
3230 if ( !is_callable( $callback ) ) {
3231 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3232 wfProfileOut( __METHOD__
. '-pfunc' );
3233 wfProfileOut( __METHOD__
);
3234 throw new MWException( "Tag hook for $function is not callable\n" );
3236 $result = call_user_func_array( $callback, $allArgs );
3239 $preprocessFlags = 0;
3241 if ( is_array( $result ) ) {
3242 if ( isset( $result[0] ) ) {
3244 unset( $result[0] );
3247 # Extract flags into the local scope
3248 # This allows callers to set flags such as nowiki, found, etc.
3254 $text = $this->preprocessToDom( $text, $preprocessFlags );
3257 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3260 wfProfileOut( __METHOD__
. '-pfunc' );
3263 # Finish mangling title and then check for loops.
3264 # Set $title to a Title object and $titleText to the PDBK
3267 # Split the title into page and subpage
3269 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3270 if ( $subpage !== '' ) {
3271 $ns = $this->mTitle
->getNamespace();
3273 $title = Title
::newFromText( $part1, $ns );
3275 $titleText = $title->getPrefixedText();
3276 # Check for language variants if the template is not found
3277 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3278 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3280 # Do recursion depth check
3281 $limit = $this->mOptions
->getMaxTemplateDepth();
3282 if ( $frame->depth
>= $limit ) {
3284 $text = '<span class="error">'
3285 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3291 # Load from database
3292 if ( !$found && $title ) {
3293 if ( !Profiler
::instance()->isPersistent() ) {
3294 # Too many unique items can kill profiling DBs/collectors
3295 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3296 wfProfileIn( $titleProfileIn ); // template in
3298 wfProfileIn( __METHOD__
. '-loadtpl' );
3299 if ( !$title->isExternal() ) {
3300 if ( $title->isSpecialPage()
3301 && $this->mOptions
->getAllowSpecialInclusion()
3302 && $this->ot
['html'] )
3304 // Pass the template arguments as URL parameters.
3305 // "uselang" will have no effect since the Language object
3306 // is forced to the one defined in ParserOptions.
3307 $pageArgs = array();
3308 for ( $i = 0; $i < $args->getLength(); $i++
) {
3309 $bits = $args->item( $i )->splitArg();
3310 if ( strval( $bits['index'] ) === '' ) {
3311 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3312 $value = trim( $frame->expand( $bits['value'] ) );
3313 $pageArgs[$name] = $value;
3317 // Create a new context to execute the special page
3318 $context = new RequestContext
;
3319 $context->setTitle( $title );
3320 $context->setRequest( new FauxRequest( $pageArgs ) );
3321 $context->setUser( $this->getUser() );
3322 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3323 $ret = SpecialPageFactory
::capturePath( $title, $context );
3325 $text = $context->getOutput()->getHTML();
3326 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3329 $this->disableCache();
3331 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3332 $found = false; # access denied
3333 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3335 list( $text, $title ) = $this->getTemplateDom( $title );
3336 if ( $text !== false ) {
3342 # If the title is valid but undisplayable, make a link to it
3343 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3344 $text = "[[:$titleText]]";
3347 } elseif ( $title->isTrans() ) {
3348 # Interwiki transclusion
3349 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3350 $text = $this->interwikiTransclude( $title, 'render' );
3353 $text = $this->interwikiTransclude( $title, 'raw' );
3354 # Preprocess it like a template
3355 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3361 # Do infinite loop check
3362 # This has to be done after redirect resolution to avoid infinite loops via redirects
3363 if ( !$frame->loopCheck( $title ) ) {
3365 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3366 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3368 wfProfileOut( __METHOD__
. '-loadtpl' );
3371 # If we haven't found text to substitute by now, we're done
3372 # Recover the source wikitext and return it
3374 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3375 if ( $titleProfileIn ) {
3376 wfProfileOut( $titleProfileIn ); // template out
3378 wfProfileOut( __METHOD__
);
3379 return array( 'object' => $text );
3382 # Expand DOM-style return values in a child frame
3383 if ( $isChildObj ) {
3384 # Clean up argument array
3385 $newFrame = $frame->newChild( $args, $title );
3388 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3389 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3390 # Expansion is eligible for the empty-frame cache
3391 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3392 $text = $this->mTplExpandCache
[$titleText];
3394 $text = $newFrame->expand( $text );
3395 $this->mTplExpandCache
[$titleText] = $text;
3398 # Uncached expansion
3399 $text = $newFrame->expand( $text );
3402 if ( $isLocalObj && $nowiki ) {
3403 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3404 $isLocalObj = false;
3407 if ( $titleProfileIn ) {
3408 wfProfileOut( $titleProfileIn ); // template out
3411 # Replace raw HTML by a placeholder
3413 $text = $this->insertStripItem( $text );
3414 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3415 # Escape nowiki-style return values
3416 $text = wfEscapeWikiText( $text );
3417 } elseif ( is_string( $text )
3418 && !$piece['lineStart']
3419 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3421 # Bug 529: if the template begins with a table or block-level
3422 # element, it should be treated as beginning a new line.
3423 # This behaviour is somewhat controversial.
3424 $text = "\n" . $text;
3427 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3428 # Error, oversize inclusion
3429 if ( $titleText !== false ) {
3430 # Make a working, properly escaped link if possible (bug 23588)
3431 $text = "[[:$titleText]]";
3433 # This will probably not be a working link, but at least it may
3434 # provide some hint of where the problem is
3435 preg_replace( '/^:/', '', $originalTitle );
3436 $text = "[[:$originalTitle]]";
3438 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3439 $this->limitationWarn( 'post-expand-template-inclusion' );
3442 if ( $isLocalObj ) {
3443 $ret = array( 'object' => $text );
3445 $ret = array( 'text' => $text );
3448 wfProfileOut( __METHOD__
);
3453 * Get the semi-parsed DOM representation of a template with a given title,
3454 * and its redirect destination title. Cached.
3456 * @param $title Title
3460 function getTemplateDom( $title ) {
3461 $cacheTitle = $title;
3462 $titleText = $title->getPrefixedDBkey();
3464 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3465 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3466 $title = Title
::makeTitle( $ns, $dbk );
3467 $titleText = $title->getPrefixedDBkey();
3469 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3470 return array( $this->mTplDomCache
[$titleText], $title );
3473 # Cache miss, go to the database
3474 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3476 if ( $text === false ) {
3477 $this->mTplDomCache
[$titleText] = false;
3478 return array( false, $title );
3481 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3482 $this->mTplDomCache
[ $titleText ] = $dom;
3484 if ( !$title->equals( $cacheTitle ) ) {
3485 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3486 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3489 return array( $dom, $title );
3493 * Fetch the unparsed text of a template and register a reference to it.
3494 * @param Title $title
3495 * @return Array ( string or false, Title )
3497 function fetchTemplateAndTitle( $title ) {
3498 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3499 $stuff = call_user_func( $templateCb, $title, $this );
3500 $text = $stuff['text'];
3501 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3502 if ( isset( $stuff['deps'] ) ) {
3503 foreach ( $stuff['deps'] as $dep ) {
3504 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3507 return array( $text, $finalTitle );
3511 * Fetch the unparsed text of a template and register a reference to it.
3512 * @param Title $title
3513 * @return mixed string or false
3515 function fetchTemplate( $title ) {
3516 $rv = $this->fetchTemplateAndTitle( $title );
3521 * Static function to get a template
3522 * Can be overridden via ParserOptions::setTemplateCallback().
3524 * @parma $title Title
3525 * @param $parser Parser
3529 static function statelessFetchTemplate( $title, $parser = false ) {
3530 $text = $skip = false;
3531 $finalTitle = $title;
3534 # Loop to fetch the article, with up to 1 redirect
3535 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3536 # Give extensions a chance to select the revision instead
3537 $id = false; # Assume current
3538 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3539 array( $parser, $title, &$skip, &$id ) );
3545 'page_id' => $title->getArticleID(),
3552 ? Revision
::newFromId( $id )
3553 : Revision
::newFromTitle( $title );
3554 $rev_id = $rev ?
$rev->getId() : 0;
3555 # If there is no current revision, there is no page
3556 if ( $id === false && !$rev ) {
3557 $linkCache = LinkCache
::singleton();
3558 $linkCache->addBadLinkObj( $title );
3563 'page_id' => $title->getArticleID(),
3564 'rev_id' => $rev_id );
3565 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3566 # We fetched a rev from a different title; register it too...
3568 'title' => $rev->getTitle(),
3569 'page_id' => $rev->getPage(),
3570 'rev_id' => $rev_id );
3574 $text = $rev->getText();
3575 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3577 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3578 if ( !$message->exists() ) {
3582 $text = $message->plain();
3586 if ( $text === false ) {
3590 $finalTitle = $title;
3591 $title = Title
::newFromRedirect( $text );
3595 'finalTitle' => $finalTitle,
3600 * Fetch a file and its title and register a reference to it.
3601 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3602 * @param Title $title
3603 * @param Array $options Array of options to RepoGroup::findFile
3606 function fetchFile( $title, $options = array() ) {
3607 $res = $this->fetchFileAndTitle( $title, $options );
3612 * Fetch a file and its title and register a reference to it.
3613 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3614 * @param Title $title
3615 * @param Array $options Array of options to RepoGroup::findFile
3616 * @return Array ( File or false, Title of file )
3618 function fetchFileAndTitle( $title, $options = array() ) {
3619 if ( isset( $options['broken'] ) ) {
3620 $file = false; // broken thumbnail forced by hook
3621 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3622 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3623 } else { // get by (name,timestamp)
3624 $file = wfFindFile( $title, $options );
3626 $time = $file ?
$file->getTimestamp() : false;
3627 $sha1 = $file ?
$file->getSha1() : false;
3628 # Register the file as a dependency...
3629 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3630 if ( $file && !$title->equals( $file->getTitle() ) ) {
3631 # Update fetched file title
3632 $title = $file->getTitle();
3633 if ( is_null( $file->getRedirectedTitle() ) ) {
3634 # This file was not a redirect, but the title does not match.
3635 # Register under the new name because otherwise the link will
3637 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3640 return array( $file, $title );
3644 * Transclude an interwiki link.
3646 * @param $title Title
3651 function interwikiTransclude( $title, $action ) {
3652 global $wgEnableScaryTranscluding;
3654 if ( !$wgEnableScaryTranscluding ) {
3655 return wfMsgForContent('scarytranscludedisabled');
3658 $url = $title->getFullUrl( "action=$action" );
3660 if ( strlen( $url ) > 255 ) {
3661 return wfMsgForContent( 'scarytranscludetoolong' );
3663 return $this->fetchScaryTemplateMaybeFromCache( $url );
3667 * @param $url string
3668 * @return Mixed|String
3670 function fetchScaryTemplateMaybeFromCache( $url ) {
3671 global $wgTranscludeCacheExpiry;
3672 $dbr = wfGetDB( DB_SLAVE
);
3673 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3674 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3675 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3677 return $obj->tc_contents
;
3680 $text = Http
::get( $url );
3682 return wfMsgForContent( 'scarytranscludefailed', $url );
3685 $dbw = wfGetDB( DB_MASTER
);
3686 $dbw->replace( 'transcache', array('tc_url'), array(
3688 'tc_time' => $dbw->timestamp( time() ),
3689 'tc_contents' => $text)
3695 * Triple brace replacement -- used for template arguments
3698 * @param $peice array
3699 * @param $frame PPFrame
3703 function argSubstitution( $piece, $frame ) {
3704 wfProfileIn( __METHOD__
);
3707 $parts = $piece['parts'];
3708 $nameWithSpaces = $frame->expand( $piece['title'] );
3709 $argName = trim( $nameWithSpaces );
3711 $text = $frame->getArgument( $argName );
3712 if ( $text === false && $parts->getLength() > 0
3716 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3719 # No match in frame, use the supplied default
3720 $object = $parts->item( 0 )->getChildren();
3722 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3723 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3724 $this->limitationWarn( 'post-expand-template-argument' );
3727 if ( $text === false && $object === false ) {
3729 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3731 if ( $error !== false ) {
3734 if ( $object !== false ) {
3735 $ret = array( 'object' => $object );
3737 $ret = array( 'text' => $text );
3740 wfProfileOut( __METHOD__
);
3745 * Return the text to be used for a given extension tag.
3746 * This is the ghost of strip().
3748 * @param $params array Associative array of parameters:
3749 * name PPNode for the tag name
3750 * attr PPNode for unparsed text where tag attributes are thought to be
3751 * attributes Optional associative array of parsed attributes
3752 * inner Contents of extension element
3753 * noClose Original text did not have a close tag
3754 * @param $frame PPFrame
3758 function extensionSubstitution( $params, $frame ) {
3759 $name = $frame->expand( $params['name'] );
3760 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3761 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3762 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3764 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3765 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3766 if ( $isFunctionTag ) {
3767 $markerType = 'none';
3769 $markerType = 'general';
3771 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3772 $name = strtolower( $name );
3773 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3774 if ( isset( $params['attributes'] ) ) {
3775 $attributes = $attributes +
$params['attributes'];
3778 if ( isset( $this->mTagHooks
[$name] ) ) {
3779 # Workaround for PHP bug 35229 and similar
3780 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3781 throw new MWException( "Tag hook for $name is not callable\n" );
3783 $output = call_user_func_array( $this->mTagHooks
[$name],
3784 array( $content, $attributes, $this, $frame ) );
3785 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3786 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3787 if ( !is_callable( $callback ) ) {
3788 throw new MWException( "Tag hook for $name is not callable\n" );
3791 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3793 $output = '<span class="error">Invalid tag extension name: ' .
3794 htmlspecialchars( $name ) . '</span>';
3797 if ( is_array( $output ) ) {
3798 # Extract flags to local scope (to override $markerType)
3800 $output = $flags[0];
3805 if ( is_null( $attrText ) ) {
3808 if ( isset( $params['attributes'] ) ) {
3809 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3810 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3811 htmlspecialchars( $attrValue ) . '"';
3814 if ( $content === null ) {
3815 $output = "<$name$attrText/>";
3817 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3818 $output = "<$name$attrText>$content$close";
3822 if ( $markerType === 'none' ) {
3824 } elseif ( $markerType === 'nowiki' ) {
3825 $this->mStripState
->addNoWiki( $marker, $output );
3826 } elseif ( $markerType === 'general' ) {
3827 $this->mStripState
->addGeneral( $marker, $output );
3829 throw new MWException( __METHOD__
.': invalid marker type' );
3835 * Increment an include size counter
3837 * @param $type String: the type of expansion
3838 * @param $size Integer: the size of the text
3839 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3841 function incrementIncludeSize( $type, $size ) {
3842 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3845 $this->mIncludeSizes
[$type] +
= $size;
3851 * Increment the expensive function count
3853 * @return Boolean: false if the limit has been exceeded
3855 function incrementExpensiveFunctionCount() {
3856 $this->mExpensiveFunctionCount++
;
3857 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3861 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3862 * Fills $this->mDoubleUnderscores, returns the modified text
3864 * @param $text string
3868 function doDoubleUnderscore( $text ) {
3869 wfProfileIn( __METHOD__
);
3871 # The position of __TOC__ needs to be recorded
3872 $mw = MagicWord
::get( 'toc' );
3873 if ( $mw->match( $text ) ) {
3874 $this->mShowToc
= true;
3875 $this->mForceTocPosition
= true;
3877 # Set a placeholder. At the end we'll fill it in with the TOC.
3878 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3880 # Only keep the first one.
3881 $text = $mw->replace( '', $text );
3884 # Now match and remove the rest of them
3885 $mwa = MagicWord
::getDoubleUnderscoreArray();
3886 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3888 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3889 $this->mOutput
->mNoGallery
= true;
3891 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3892 $this->mShowToc
= false;
3894 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3895 $this->addTrackingCategory( 'hidden-category-category' );
3897 # (bug 8068) Allow control over whether robots index a page.
3899 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3900 # is not desirable, the last one on the page should win.
3901 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3902 $this->mOutput
->setIndexPolicy( 'noindex' );
3903 $this->addTrackingCategory( 'noindex-category' );
3905 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3906 $this->mOutput
->setIndexPolicy( 'index' );
3907 $this->addTrackingCategory( 'index-category' );
3910 # Cache all double underscores in the database
3911 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3912 $this->mOutput
->setProperty( $key, '' );
3915 wfProfileOut( __METHOD__
);
3920 * Add a tracking category, getting the title from a system message,
3921 * or print a debug message if the title is invalid.
3923 * @param $msg String: message key
3924 * @return Boolean: whether the addition was successful
3926 public function addTrackingCategory( $msg ) {
3927 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3928 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3931 // Important to parse with correct title (bug 31469)
3932 $cat = wfMessage( $msg )
3933 ->title( $this->getTitle() )
3934 ->inContentLanguage()
3937 # Allow tracking categories to be disabled by setting them to "-"
3938 if ( $cat === '-' ) {
3942 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3943 if ( $containerCategory ) {
3944 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3947 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3953 * This function accomplishes several tasks:
3954 * 1) Auto-number headings if that option is enabled
3955 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3956 * 3) Add a Table of contents on the top for users who have enabled the option
3957 * 4) Auto-anchor headings
3959 * It loops through all headlines, collects the necessary data, then splits up the
3960 * string and re-inserts the newly formatted headlines.
3962 * @param $text String
3963 * @param $origText String: original, untouched wikitext
3964 * @param $isMain Boolean
3965 * @return mixed|string
3968 function formatHeadings( $text, $origText, $isMain=true ) {
3969 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3971 # Inhibit editsection links if requested in the page
3972 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3973 $maybeShowEditLink = $showEditLink = false;
3975 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3976 $showEditLink = $this->mOptions
->getEditSection();
3978 if ( $showEditLink ) {
3979 $this->mOutput
->setEditSectionTokens( true );
3982 # Get all headlines for numbering them and adding funky stuff like [edit]
3983 # links - this is for later, but we need the number of headlines right now
3985 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3987 # if there are fewer than 4 headlines in the article, do not show TOC
3988 # unless it's been explicitly enabled.
3989 $enoughToc = $this->mShowToc
&&
3990 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3992 # Allow user to stipulate that a page should have a "new section"
3993 # link added via __NEWSECTIONLINK__
3994 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3995 $this->mOutput
->setNewSection( true );
3998 # Allow user to remove the "new section"
3999 # link via __NONEWSECTIONLINK__
4000 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4001 $this->mOutput
->hideNewSection( true );
4004 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4005 # override above conditions and always show TOC above first header
4006 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4007 $this->mShowToc
= true;
4015 # Ugh .. the TOC should have neat indentation levels which can be
4016 # passed to the skin functions. These are determined here
4020 $sublevelCount = array();
4021 $levelCount = array();
4026 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4027 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4028 $oldType = $this->mOutputType
;
4029 $this->setOutputType( self
::OT_WIKI
);
4030 $frame = $this->getPreprocessor()->newFrame();
4031 $root = $this->preprocessToDom( $origText );
4032 $node = $root->getFirstChild();
4037 foreach ( $matches[3] as $headline ) {
4038 $isTemplate = false;
4040 $sectionIndex = false;
4042 $markerMatches = array();
4043 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4044 $serial = $markerMatches[1];
4045 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4046 $isTemplate = ( $titleText != $baseTitleText );
4047 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4051 $prevlevel = $level;
4053 $level = $matches[1][$headlineCount];
4055 if ( $level > $prevlevel ) {
4056 # Increase TOC level
4058 $sublevelCount[$toclevel] = 0;
4059 if ( $toclevel<$wgMaxTocLevel ) {
4060 $prevtoclevel = $toclevel;
4061 $toc .= Linker
::tocIndent();
4064 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4065 # Decrease TOC level, find level to jump to
4067 for ( $i = $toclevel; $i > 0; $i-- ) {
4068 if ( $levelCount[$i] == $level ) {
4069 # Found last matching level
4072 } elseif ( $levelCount[$i] < $level ) {
4073 # Found first matching level below current level
4081 if ( $toclevel<$wgMaxTocLevel ) {
4082 if ( $prevtoclevel < $wgMaxTocLevel ) {
4083 # Unindent only if the previous toc level was shown :p
4084 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4085 $prevtoclevel = $toclevel;
4087 $toc .= Linker
::tocLineEnd();
4091 # No change in level, end TOC line
4092 if ( $toclevel<$wgMaxTocLevel ) {
4093 $toc .= Linker
::tocLineEnd();
4097 $levelCount[$toclevel] = $level;
4099 # count number of headlines for each level
4100 @$sublevelCount[$toclevel]++
;
4102 for( $i = 1; $i <= $toclevel; $i++
) {
4103 if ( !empty( $sublevelCount[$i] ) ) {
4107 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4112 # The safe header is a version of the header text safe to use for links
4114 # Remove link placeholders by the link text.
4115 # <!--LINK number-->
4117 # link text with suffix
4118 # Do this before unstrip since link text can contain strip markers
4119 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4121 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4122 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4124 # Strip out HTML (first regex removes any tag not allowed)
4125 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4126 # We strip any parameter from accepted tags (second regex)
4127 $tocline = preg_replace(
4128 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4129 array( '', '<$1>' ),
4132 $tocline = trim( $tocline );
4134 # For the anchor, strip out HTML-y stuff period
4135 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4136 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4138 # Save headline for section edit hint before it's escaped
4139 $headlineHint = $safeHeadline;
4141 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4142 # For reverse compatibility, provide an id that's
4143 # HTML4-compatible, like we used to.
4145 # It may be worth noting, academically, that it's possible for
4146 # the legacy anchor to conflict with a non-legacy headline
4147 # anchor on the page. In this case likely the "correct" thing
4148 # would be to either drop the legacy anchors or make sure
4149 # they're numbered first. However, this would require people
4150 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4151 # manually, so let's not bother worrying about it.
4152 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4153 array( 'noninitial', 'legacy' ) );
4154 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4156 if ( $legacyHeadline == $safeHeadline ) {
4157 # No reason to have both (in fact, we can't)
4158 $legacyHeadline = false;
4161 $legacyHeadline = false;
4162 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4166 # HTML names must be case-insensitively unique (bug 10721).
4167 # This does not apply to Unicode characters per
4168 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4169 # @todo FIXME: We may be changing them depending on the current locale.
4170 $arrayKey = strtolower( $safeHeadline );
4171 if ( $legacyHeadline === false ) {
4172 $legacyArrayKey = false;
4174 $legacyArrayKey = strtolower( $legacyHeadline );
4177 # count how many in assoc. array so we can track dupes in anchors
4178 if ( isset( $refers[$arrayKey] ) ) {
4179 $refers[$arrayKey]++
;
4181 $refers[$arrayKey] = 1;
4183 if ( isset( $refers[$legacyArrayKey] ) ) {
4184 $refers[$legacyArrayKey]++
;
4186 $refers[$legacyArrayKey] = 1;
4189 # Don't number the heading if it is the only one (looks silly)
4190 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4191 # the two are different if the line contains a link
4192 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4195 # Create the anchor for linking from the TOC to the section
4196 $anchor = $safeHeadline;
4197 $legacyAnchor = $legacyHeadline;
4198 if ( $refers[$arrayKey] > 1 ) {
4199 $anchor .= '_' . $refers[$arrayKey];
4201 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4202 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4204 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4205 $toc .= Linker
::tocLine( $anchor, $tocline,
4206 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4209 # Add the section to the section tree
4210 # Find the DOM node for this header
4211 while ( $node && !$isTemplate ) {
4212 if ( $node->getName() === 'h' ) {
4213 $bits = $node->splitHeading();
4214 if ( $bits['i'] == $sectionIndex ) {
4218 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4219 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4220 $node = $node->getNextSibling();
4223 'toclevel' => $toclevel,
4226 'number' => $numbering,
4227 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4228 'fromtitle' => $titleText,
4229 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4230 'anchor' => $anchor,
4233 # give headline the correct <h#> tag
4234 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4235 // Output edit section links as markers with styles that can be customized by skins
4236 if ( $isTemplate ) {
4237 # Put a T flag in the section identifier, to indicate to extractSections()
4238 # that sections inside <includeonly> should be counted.
4239 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4241 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4243 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4244 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4245 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4246 // so we don't have to worry about a user trying to input one of these markers directly.
4247 // We use a page and section attribute to stop the language converter from converting these important bits
4248 // of data, but put the headline hint inside a content block because the language converter is supposed to
4249 // be able to convert that piece of data.
4250 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4251 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4252 if ( isset($editlinkArgs[2]) ) {
4253 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4260 $head[$headlineCount] = Linker
::makeHeadline( $level,
4261 $matches['attrib'][$headlineCount], $anchor, $headline,
4262 $editlink, $legacyAnchor );
4267 $this->setOutputType( $oldType );
4269 # Never ever show TOC if no headers
4270 if ( $numVisible < 1 ) {
4275 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4276 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4278 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4279 $this->mOutput
->setTOCHTML( $toc );
4283 $this->mOutput
->setSections( $tocraw );
4286 # split up and insert constructed headlines
4287 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4290 // build an array of document sections
4291 $sections = array();
4292 foreach ( $blocks as $block ) {
4293 // $head is zero-based, sections aren't.
4294 if ( empty( $head[$i - 1] ) ) {
4295 $sections[$i] = $block;
4297 $sections[$i] = $head[$i - 1] . $block;
4301 * Send a hook, one per section.
4302 * The idea here is to be able to make section-level DIVs, but to do so in a
4303 * lower-impact, more correct way than r50769
4306 * $section : the section number
4307 * &$sectionContent : ref to the content of the section
4308 * $showEditLinks : boolean describing whether this section has an edit link
4310 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4315 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4316 // append the TOC at the beginning
4317 // Top anchor now in skin
4318 $sections[0] = $sections[0] . $toc . "\n";
4321 $full .= join( '', $sections );
4323 if ( $this->mForceTocPosition
) {
4324 return str_replace( '<!--MWTOC-->', $toc, $full );
4331 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4332 * conversion, substitting signatures, {{subst:}} templates, etc.
4334 * @param $text String: the text to transform
4335 * @param $title Title: the Title object for the current article
4336 * @param $user User: the User object describing the current user
4337 * @param $options ParserOptions: parsing options
4338 * @param $clearState Boolean: whether to clear the parser state first
4339 * @return String: the altered wiki markup
4341 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4342 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4343 $this->setUser( $user );
4348 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4349 if( $options->getPreSaveTransform() ) {
4350 $text = $this->pstPass2( $text, $user );
4352 $text = $this->mStripState
->unstripBoth( $text );
4354 $this->setUser( null ); #Reset
4360 * Pre-save transform helper function
4363 * @param $text string
4368 function pstPass2( $text, $user ) {
4369 global $wgContLang, $wgLocaltimezone;
4371 # Note: This is the timestamp saved as hardcoded wikitext to
4372 # the database, we use $wgContLang here in order to give
4373 # everyone the same signature and use the default one rather
4374 # than the one selected in each user's preferences.
4375 # (see also bug 12815)
4376 $ts = $this->mOptions
->getTimestamp();
4377 if ( isset( $wgLocaltimezone ) ) {
4378 $tz = $wgLocaltimezone;
4380 $tz = date_default_timezone_get();
4383 $unixts = wfTimestamp( TS_UNIX
, $ts );
4384 $oldtz = date_default_timezone_get();
4385 date_default_timezone_set( $tz );
4386 $ts = date( 'YmdHis', $unixts );
4387 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4389 # Allow translation of timezones through wiki. date() can return
4390 # whatever crap the system uses, localised or not, so we cannot
4391 # ship premade translations.
4392 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4393 $msg = wfMessage( $key )->inContentLanguage();
4394 if ( $msg->exists() ) {
4395 $tzMsg = $msg->text();
4398 date_default_timezone_set( $oldtz );
4400 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4402 # Variable replacement
4403 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4404 $text = $this->replaceVariables( $text );
4406 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4407 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4410 $sigText = $this->getUserSig( $user );
4411 $text = strtr( $text, array(
4413 '~~~~' => "$sigText $d",
4417 # Context links: [[|name]] and [[name (context)|]]
4418 $tc = '[' . Title
::legalChars() . ']';
4419 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4421 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4422 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4423 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4424 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4426 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4427 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4428 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4429 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4431 $t = $this->mTitle
->getText();
4433 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4434 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4435 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4436 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4438 # if there's no context, don't bother duplicating the title
4439 $text = preg_replace( $p2, '[[\\1]]', $text );
4442 # Trim trailing whitespace
4443 $text = rtrim( $text );
4449 * Fetch the user's signature text, if any, and normalize to
4450 * validated, ready-to-insert wikitext.
4451 * If you have pre-fetched the nickname or the fancySig option, you can
4452 * specify them here to save a database query.
4453 * Do not reuse this parser instance after calling getUserSig(),
4454 * as it may have changed if it's the $wgParser.
4457 * @param $nickname String|bool nickname to use or false to use user's default nickname
4458 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4459 * or null to use default value
4462 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4463 global $wgMaxSigChars;
4465 $username = $user->getName();
4467 # If not given, retrieve from the user object.
4468 if ( $nickname === false )
4469 $nickname = $user->getOption( 'nickname' );
4471 if ( is_null( $fancySig ) ) {
4472 $fancySig = $user->getBoolOption( 'fancysig' );
4475 $nickname = $nickname == null ?
$username : $nickname;
4477 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4478 $nickname = $username;
4479 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4480 } elseif ( $fancySig !== false ) {
4481 # Sig. might contain markup; validate this
4482 if ( $this->validateSig( $nickname ) !== false ) {
4483 # Validated; clean up (if needed) and return it
4484 return $this->cleanSig( $nickname, true );
4486 # Failed to validate; fall back to the default
4487 $nickname = $username;
4488 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4492 # Make sure nickname doesnt get a sig in a sig
4493 $nickname = self
::cleanSigInSig( $nickname );
4495 # If we're still here, make it a link to the user page
4496 $userText = wfEscapeWikiText( $username );
4497 $nickText = wfEscapeWikiText( $nickname );
4498 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4500 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4504 * Check that the user's signature contains no bad XML
4506 * @param $text String
4507 * @return mixed An expanded string, or false if invalid.
4509 function validateSig( $text ) {
4510 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4514 * Clean up signature text
4516 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4517 * 2) Substitute all transclusions
4519 * @param $text String
4520 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4521 * @return String: signature text
4523 public function cleanSig( $text, $parsing = false ) {
4526 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4529 # Option to disable this feature
4530 if ( !$this->mOptions
->getCleanSignatures() ) {
4534 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4535 # => Move this logic to braceSubstitution()
4536 $substWord = MagicWord
::get( 'subst' );
4537 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4538 $substText = '{{' . $substWord->getSynonym( 0 );
4540 $text = preg_replace( $substRegex, $substText, $text );
4541 $text = self
::cleanSigInSig( $text );
4542 $dom = $this->preprocessToDom( $text );
4543 $frame = $this->getPreprocessor()->newFrame();
4544 $text = $frame->expand( $dom );
4547 $text = $this->mStripState
->unstripBoth( $text );
4554 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4556 * @param $text String
4557 * @return String: signature text with /~{3,5}/ removed
4559 public static function cleanSigInSig( $text ) {
4560 $text = preg_replace( '/~{3,5}/', '', $text );
4565 * Set up some variables which are usually set up in parse()
4566 * so that an external function can call some class members with confidence
4568 * @param $title Title|null
4569 * @param $options ParserOptions
4570 * @param $outputType
4571 * @param $clearState bool
4573 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4574 $this->startParse( $title, $options, $outputType, $clearState );
4578 * @param $title Title|null
4579 * @param $options ParserOptions
4580 * @param $outputType
4581 * @param $clearState bool
4583 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4584 $this->setTitle( $title );
4585 $this->mOptions
= $options;
4586 $this->setOutputType( $outputType );
4587 if ( $clearState ) {
4588 $this->clearState();
4593 * Wrapper for preprocess()
4595 * @param $text String: the text to preprocess
4596 * @param $options ParserOptions: options
4597 * @param $title Title object or null to use $wgTitle
4600 public function transformMsg( $text, $options, $title = null ) {
4601 static $executing = false;
4603 # Guard against infinite recursion
4609 wfProfileIn( __METHOD__
);
4615 # It's not uncommon having a null $wgTitle in scripts. See r80898
4616 # Create a ghost title in such case
4617 $title = Title
::newFromText( 'Dwimmerlaik' );
4619 $text = $this->preprocess( $text, $title, $options );
4622 wfProfileOut( __METHOD__
);
4627 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4628 * The callback should have the following form:
4629 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4631 * Transform and return $text. Use $parser for any required context, e.g. use
4632 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4634 * Hooks may return extended information by returning an array, of which the
4635 * first numbered element (index 0) must be the return string, and all other
4636 * entries are extracted into local variables within an internal function
4637 * in the Parser class.
4639 * This interface (introduced r61913) appears to be undocumented, but
4640 * 'markerName' is used by some core tag hooks to override which strip
4641 * array their results are placed in. **Use great caution if attempting
4642 * this interface, as it is not documented and injudicious use could smash
4643 * private variables.**
4645 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4646 * @param $callback Mixed: the callback function (and object) to use for the tag
4647 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4649 public function setHook( $tag, $callback ) {
4650 $tag = strtolower( $tag );
4651 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4652 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4654 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4655 $this->mTagHooks
[$tag] = $callback;
4656 if ( !in_array( $tag, $this->mStripList
) ) {
4657 $this->mStripList
[] = $tag;
4664 * As setHook(), but letting the contents be parsed.
4666 * Transparent tag hooks are like regular XML-style tag hooks, except they
4667 * operate late in the transformation sequence, on HTML instead of wikitext.
4669 * This is probably obsoleted by things dealing with parser frames?
4670 * The only extension currently using it is geoserver.
4673 * @todo better document or deprecate this
4675 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4676 * @param $callback Mixed: the callback function (and object) to use for the tag
4677 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4679 function setTransparentTagHook( $tag, $callback ) {
4680 $tag = strtolower( $tag );
4681 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4682 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4684 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4685 $this->mTransparentTagHooks
[$tag] = $callback;
4691 * Remove all tag hooks
4693 function clearTagHooks() {
4694 $this->mTagHooks
= array();
4695 $this->mFunctionTagHooks
= array();
4696 $this->mStripList
= $this->mDefaultStripList
;
4700 * Create a function, e.g. {{sum:1|2|3}}
4701 * The callback function should have the form:
4702 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4704 * Or with SFH_OBJECT_ARGS:
4705 * function myParserFunction( $parser, $frame, $args ) { ... }
4707 * The callback may either return the text result of the function, or an array with the text
4708 * in element 0, and a number of flags in the other elements. The names of the flags are
4709 * specified in the keys. Valid flags are:
4710 * found The text returned is valid, stop processing the template. This
4712 * nowiki Wiki markup in the return value should be escaped
4713 * isHTML The returned text is HTML, armour it against wikitext transformation
4715 * @param $id String: The magic word ID
4716 * @param $callback Mixed: the callback function (and object) to use
4717 * @param $flags Integer: a combination of the following flags:
4718 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4720 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4721 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4722 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4723 * the arguments, and to control the way they are expanded.
4725 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4726 * arguments, for instance:
4727 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4729 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4730 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4731 * working if/when this is changed.
4733 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4736 * Please read the documentation in includes/parser/Preprocessor.php for more information
4737 * about the methods available in PPFrame and PPNode.
4739 * @return string|callback The old callback function for this name, if any
4741 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4744 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4745 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4747 # Add to function cache
4748 $mw = MagicWord
::get( $id );
4750 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4752 $synonyms = $mw->getSynonyms();
4753 $sensitive = intval( $mw->isCaseSensitive() );
4755 foreach ( $synonyms as $syn ) {
4757 if ( !$sensitive ) {
4758 $syn = $wgContLang->lc( $syn );
4761 if ( !( $flags & SFH_NO_HASH
) ) {
4764 # Remove trailing colon
4765 if ( substr( $syn, -1, 1 ) === ':' ) {
4766 $syn = substr( $syn, 0, -1 );
4768 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4774 * Get all registered function hook identifiers
4778 function getFunctionHooks() {
4779 return array_keys( $this->mFunctionHooks
);
4783 * Create a tag function, e.g. "<test>some stuff</test>".
4784 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4785 * Unlike parser functions, their content is not preprocessed.
4788 function setFunctionTagHook( $tag, $callback, $flags ) {
4789 $tag = strtolower( $tag );
4790 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4791 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4792 $this->mFunctionTagHooks
[$tag] : null;
4793 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4795 if ( !in_array( $tag, $this->mStripList
) ) {
4796 $this->mStripList
[] = $tag;
4803 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4804 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4805 * Placeholders created in Skin::makeLinkObj()
4807 * @param $text string
4808 * @param $options int
4810 * @return array of link CSS classes, indexed by PDBK.
4812 function replaceLinkHolders( &$text, $options = 0 ) {
4813 return $this->mLinkHolders
->replace( $text );
4817 * Replace "<!--LINK-->" link placeholders with plain text of links
4818 * (not HTML-formatted).
4820 * @param $text String
4823 function replaceLinkHoldersText( $text ) {
4824 return $this->mLinkHolders
->replaceText( $text );
4828 * Renders an image gallery from a text with one line per image.
4829 * text labels may be given by using |-style alternative text. E.g.
4830 * Image:one.jpg|The number "1"
4831 * Image:tree.jpg|A tree
4832 * given as text will return the HTML of a gallery with two images,
4833 * labeled 'The number "1"' and
4836 * @param string $text
4837 * @param array $params
4838 * @return string HTML
4840 function renderImageGallery( $text, $params ) {
4841 $ig = new ImageGallery();
4842 $ig->setContextTitle( $this->mTitle
);
4843 $ig->setShowBytes( false );
4844 $ig->setShowFilename( false );
4845 $ig->setParser( $this );
4846 $ig->setHideBadImages();
4847 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4849 if ( isset( $params['showfilename'] ) ) {
4850 $ig->setShowFilename( true );
4852 $ig->setShowFilename( false );
4854 if ( isset( $params['caption'] ) ) {
4855 $caption = $params['caption'];
4856 $caption = htmlspecialchars( $caption );
4857 $caption = $this->replaceInternalLinks( $caption );
4858 $ig->setCaptionHtml( $caption );
4860 if ( isset( $params['perrow'] ) ) {
4861 $ig->setPerRow( $params['perrow'] );
4863 if ( isset( $params['widths'] ) ) {
4864 $ig->setWidths( $params['widths'] );
4866 if ( isset( $params['heights'] ) ) {
4867 $ig->setHeights( $params['heights'] );
4870 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4872 $lines = StringUtils
::explode( "\n", $text );
4873 foreach ( $lines as $line ) {
4874 # match lines like these:
4875 # Image:someimage.jpg|This is some image
4877 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4879 if ( count( $matches ) == 0 ) {
4883 if ( strpos( $matches[0], '%' ) !== false ) {
4884 $matches[1] = rawurldecode( $matches[1] );
4886 $title = Title
::newFromText( $matches[1], NS_FILE
);
4887 if ( is_null( $title ) ) {
4888 # Bogus title. Ignore these so we don't bomb out later.
4895 if ( isset( $matches[3] ) ) {
4896 // look for an |alt= definition while trying not to break existing
4897 // captions with multiple pipes (|) in it, until a more sensible grammar
4898 // is defined for images in galleries
4900 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4901 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4902 $magicWordAlt = MagicWord
::get( 'img_alt' );
4903 $magicWordLink = MagicWord
::get( 'img_link' );
4905 foreach ( $parameterMatches as $parameterMatch ) {
4906 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4907 $alt = $this->stripAltText( $match, false );
4909 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4910 $link = strip_tags($this->replaceLinkHoldersText($match));
4911 $chars = self
::EXT_LINK_URL_CLASS
;
4912 $prots = $this->mUrlProtocols
;
4913 //check to see if link matches an absolute url, if not then it must be a wiki link.
4914 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4915 $localLinkTitle = Title
::newFromText($link);
4916 $link = $localLinkTitle->getLocalURL();
4920 // concatenate all other pipes
4921 $label .= '|' . $parameterMatch;
4924 // remove the first pipe
4925 $label = substr( $label, 1 );
4928 $ig->add( $title, $label, $alt ,$link);
4930 return $ig->toHTML();
4937 function getImageParams( $handler ) {
4939 $handlerClass = get_class( $handler );
4943 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4944 # Initialise static lists
4945 static $internalParamNames = array(
4946 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4947 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4948 'bottom', 'text-bottom' ),
4949 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4950 'upright', 'border', 'link', 'alt' ),
4952 static $internalParamMap;
4953 if ( !$internalParamMap ) {
4954 $internalParamMap = array();
4955 foreach ( $internalParamNames as $type => $names ) {
4956 foreach ( $names as $name ) {
4957 $magicName = str_replace( '-', '_', "img_$name" );
4958 $internalParamMap[$magicName] = array( $type, $name );
4963 # Add handler params
4964 $paramMap = $internalParamMap;
4966 $handlerParamMap = $handler->getParamMap();
4967 foreach ( $handlerParamMap as $magic => $paramName ) {
4968 $paramMap[$magic] = array( 'handler', $paramName );
4971 $this->mImageParams
[$handlerClass] = $paramMap;
4972 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4974 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4978 * Parse image options text and use it to make an image
4980 * @param $title Title
4981 * @param $options String
4982 * @param $holders LinkHolderArray|bool
4983 * @return string HTML
4985 function makeImage( $title, $options, $holders = false ) {
4986 # Check if the options text is of the form "options|alt text"
4988 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4989 # * left no resizing, just left align. label is used for alt= only
4990 # * right same, but right aligned
4991 # * none same, but not aligned
4992 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4993 # * center center the image
4994 # * frame Keep original image size, no magnify-button.
4995 # * framed Same as "frame"
4996 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4997 # * upright reduce width for upright images, rounded to full __0 px
4998 # * border draw a 1px border around the image
4999 # * alt Text for HTML alt attribute (defaults to empty)
5000 # * link Set the target of the image link. Can be external, interwiki, or local
5001 # vertical-align values (no % or length right now):
5011 $parts = StringUtils
::explode( "|", $options );
5013 # Give extensions a chance to select the file revision for us
5016 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5017 array( $this, $title, &$options, &$descQuery ) );
5018 # Fetch and register the file (file title may be different via hooks)
5019 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5022 $handler = $file ?
$file->getHandler() : false;
5024 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5027 $this->addTrackingCategory( 'broken-file-category' );
5030 # Process the input parameters
5032 $params = array( 'frame' => array(), 'handler' => array(),
5033 'horizAlign' => array(), 'vertAlign' => array() );
5034 foreach ( $parts as $part ) {
5035 $part = trim( $part );
5036 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5038 if ( isset( $paramMap[$magicName] ) ) {
5039 list( $type, $paramName ) = $paramMap[$magicName];
5041 # Special case; width and height come in one variable together
5042 if ( $type === 'handler' && $paramName === 'width' ) {
5044 # (bug 13500) In both cases (width/height and width only),
5045 # permit trailing "px" for backward compatibility.
5046 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5047 $width = intval( $m[1] );
5048 $height = intval( $m[2] );
5049 if ( $handler->validateParam( 'width', $width ) ) {
5050 $params[$type]['width'] = $width;
5053 if ( $handler->validateParam( 'height', $height ) ) {
5054 $params[$type]['height'] = $height;
5057 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5058 $width = intval( $value );
5059 if ( $handler->validateParam( 'width', $width ) ) {
5060 $params[$type]['width'] = $width;
5063 } # else no validation -- bug 13436
5065 if ( $type === 'handler' ) {
5066 # Validate handler parameter
5067 $validated = $handler->validateParam( $paramName, $value );
5069 # Validate internal parameters
5070 switch( $paramName ) {
5073 # @todo FIXME: Possibly check validity here for
5074 # manualthumb? downstream behavior seems odd with
5075 # missing manual thumbs.
5077 $value = $this->stripAltText( $value, $holders );
5080 $chars = self
::EXT_LINK_URL_CLASS
;
5081 $prots = $this->mUrlProtocols
;
5082 if ( $value === '' ) {
5083 $paramName = 'no-link';
5086 } elseif ( preg_match( "/^$prots/", $value ) ) {
5087 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5088 $paramName = 'link-url';
5089 $this->mOutput
->addExternalLink( $value );
5090 if ( $this->mOptions
->getExternalLinkTarget() ) {
5091 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5096 $linkTitle = Title
::newFromText( $value );
5098 $paramName = 'link-title';
5099 $value = $linkTitle;
5100 $this->mOutput
->addLink( $linkTitle );
5106 # Most other things appear to be empty or numeric...
5107 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5112 $params[$type][$paramName] = $value;
5116 if ( !$validated ) {
5121 # Process alignment parameters
5122 if ( $params['horizAlign'] ) {
5123 $params['frame']['align'] = key( $params['horizAlign'] );
5125 if ( $params['vertAlign'] ) {
5126 $params['frame']['valign'] = key( $params['vertAlign'] );
5129 $params['frame']['caption'] = $caption;
5131 # Will the image be presented in a frame, with the caption below?
5132 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5133 isset( $params['frame']['framed'] ) ||
5134 isset( $params['frame']['thumbnail'] ) ||
5135 isset( $params['frame']['manualthumb'] );
5137 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5138 # came to also set the caption, ordinary text after the image -- which
5139 # makes no sense, because that just repeats the text multiple times in
5140 # screen readers. It *also* came to set the title attribute.
5142 # Now that we have an alt attribute, we should not set the alt text to
5143 # equal the caption: that's worse than useless, it just repeats the
5144 # text. This is the framed/thumbnail case. If there's no caption, we
5145 # use the unnamed parameter for alt text as well, just for the time be-
5146 # ing, if the unnamed param is set and the alt param is not.
5148 # For the future, we need to figure out if we want to tweak this more,
5149 # e.g., introducing a title= parameter for the title; ignoring the un-
5150 # named parameter entirely for images without a caption; adding an ex-
5151 # plicit caption= parameter and preserving the old magic unnamed para-
5153 if ( $imageIsFramed ) { # Framed image
5154 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5155 # No caption or alt text, add the filename as the alt text so
5156 # that screen readers at least get some description of the image
5157 $params['frame']['alt'] = $title->getText();
5159 # Do not set $params['frame']['title'] because tooltips don't make sense
5161 } else { # Inline image
5162 if ( !isset( $params['frame']['alt'] ) ) {
5163 # No alt text, use the "caption" for the alt text
5164 if ( $caption !== '') {
5165 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5167 # No caption, fall back to using the filename for the
5169 $params['frame']['alt'] = $title->getText();
5172 # Use the "caption" for the tooltip text
5173 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5176 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5178 # Linker does the rest
5179 $time = isset( $options['time'] ) ?
$options['time'] : false;
5180 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5181 $time, $descQuery, $this->mOptions
->getThumbSize() );
5183 # Give the handler a chance to modify the parser object
5185 $handler->parserTransformHook( $this, $file );
5193 * @param $holders LinkHolderArray
5194 * @return mixed|String
5196 protected function stripAltText( $caption, $holders ) {
5197 # Strip bad stuff out of the title (tooltip). We can't just use
5198 # replaceLinkHoldersText() here, because if this function is called
5199 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5201 $tooltip = $holders->replaceText( $caption );
5203 $tooltip = $this->replaceLinkHoldersText( $caption );
5206 # make sure there are no placeholders in thumbnail attributes
5207 # that are later expanded to html- so expand them now and
5209 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5210 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5216 * Set a flag in the output object indicating that the content is dynamic and
5217 * shouldn't be cached.
5219 function disableCache() {
5220 wfDebug( "Parser output marked as uncacheable.\n" );
5221 if ( !$this->mOutput
) {
5222 throw new MWException( __METHOD__
.
5223 " can only be called when actually parsing something" );
5225 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5226 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5230 * Callback from the Sanitizer for expanding items found in HTML attribute
5231 * values, so they can be safely tested and escaped.
5233 * @param $text String
5234 * @param $frame PPFrame
5237 function attributeStripCallback( &$text, $frame = false ) {
5238 $text = $this->replaceVariables( $text, $frame );
5239 $text = $this->mStripState
->unstripBoth( $text );
5248 function getTags() {
5249 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5253 * Replace transparent tags in $text with the values given by the callbacks.
5255 * Transparent tag hooks are like regular XML-style tag hooks, except they
5256 * operate late in the transformation sequence, on HTML instead of wikitext.
5258 * @param $text string
5262 function replaceTransparentTags( $text ) {
5264 $elements = array_keys( $this->mTransparentTagHooks
);
5265 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5266 $replacements = array();
5268 foreach ( $matches as $marker => $data ) {
5269 list( $element, $content, $params, $tag ) = $data;
5270 $tagName = strtolower( $element );
5271 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5272 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5276 $replacements[$marker] = $output;
5278 return strtr( $text, $replacements );
5282 * Break wikitext input into sections, and either pull or replace
5283 * some particular section's text.
5285 * External callers should use the getSection and replaceSection methods.
5287 * @param $text String: Page wikitext
5288 * @param $section String: a section identifier string of the form:
5289 * "<flag1> - <flag2> - ... - <section number>"
5291 * Currently the only recognised flag is "T", which means the target section number
5292 * was derived during a template inclusion parse, in other words this is a template
5293 * section edit link. If no flags are given, it was an ordinary section edit link.
5294 * This flag is required to avoid a section numbering mismatch when a section is
5295 * enclosed by "<includeonly>" (bug 6563).
5297 * The section number 0 pulls the text before the first heading; other numbers will
5298 * pull the given section along with its lower-level subsections. If the section is
5299 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5301 * Section 0 is always considered to exist, even if it only contains the empty
5302 * string. If $text is the empty string and section 0 is replaced, $newText is
5305 * @param $mode String: one of "get" or "replace"
5306 * @param $newText String: replacement text for section data.
5307 * @return String: for "get", the extracted section text.
5308 * for "replace", the whole page with the section replaced.
5310 private function extractSections( $text, $section, $mode, $newText='' ) {
5311 global $wgTitle; # not generally used but removes an ugly failure mode
5312 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5314 $frame = $this->getPreprocessor()->newFrame();
5316 # Process section extraction flags
5318 $sectionParts = explode( '-', $section );
5319 $sectionIndex = array_pop( $sectionParts );
5320 foreach ( $sectionParts as $part ) {
5321 if ( $part === 'T' ) {
5322 $flags |
= self
::PTD_FOR_INCLUSION
;
5326 # Check for empty input
5327 if ( strval( $text ) === '' ) {
5328 # Only sections 0 and T-0 exist in an empty document
5329 if ( $sectionIndex == 0 ) {
5330 if ( $mode === 'get' ) {
5336 if ( $mode === 'get' ) {
5344 # Preprocess the text
5345 $root = $this->preprocessToDom( $text, $flags );
5347 # <h> nodes indicate section breaks
5348 # They can only occur at the top level, so we can find them by iterating the root's children
5349 $node = $root->getFirstChild();
5351 # Find the target section
5352 if ( $sectionIndex == 0 ) {
5353 # Section zero doesn't nest, level=big
5354 $targetLevel = 1000;
5357 if ( $node->getName() === 'h' ) {
5358 $bits = $node->splitHeading();
5359 if ( $bits['i'] == $sectionIndex ) {
5360 $targetLevel = $bits['level'];
5364 if ( $mode === 'replace' ) {
5365 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5367 $node = $node->getNextSibling();
5373 if ( $mode === 'get' ) {
5380 # Find the end of the section, including nested sections
5382 if ( $node->getName() === 'h' ) {
5383 $bits = $node->splitHeading();
5384 $curLevel = $bits['level'];
5385 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5389 if ( $mode === 'get' ) {
5390 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5392 $node = $node->getNextSibling();
5395 # Write out the remainder (in replace mode only)
5396 if ( $mode === 'replace' ) {
5397 # Output the replacement text
5398 # Add two newlines on -- trailing whitespace in $newText is conventionally
5399 # stripped by the editor, so we need both newlines to restore the paragraph gap
5400 # Only add trailing whitespace if there is newText
5401 if ( $newText != "" ) {
5402 $outText .= $newText . "\n\n";
5406 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5407 $node = $node->getNextSibling();
5411 if ( is_string( $outText ) ) {
5412 # Re-insert stripped tags
5413 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5420 * This function returns the text of a section, specified by a number ($section).
5421 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5422 * the first section before any such heading (section 0).
5424 * If a section contains subsections, these are also returned.
5426 * @param $text String: text to look in
5427 * @param $section String: section identifier
5428 * @param $deftext String: default to return if section is not found
5429 * @return string text of the requested section
5431 public function getSection( $text, $section, $deftext='' ) {
5432 return $this->extractSections( $text, $section, "get", $deftext );
5436 * This function returns $oldtext after the content of the section
5437 * specified by $section has been replaced with $text. If the target
5438 * section does not exist, $oldtext is returned unchanged.
5440 * @param $oldtext String: former text of the article
5441 * @param $section int section identifier
5442 * @param $text String: replacing text
5443 * @return String: modified text
5445 public function replaceSection( $oldtext, $section, $text ) {
5446 return $this->extractSections( $oldtext, $section, "replace", $text );
5450 * Get the ID of the revision we are parsing
5452 * @return Mixed: integer or null
5454 function getRevisionId() {
5455 return $this->mRevisionId
;
5459 * Get the revision object for $this->mRevisionId
5461 * @return Revision|null either a Revision object or null
5463 protected function getRevisionObject() {
5464 if ( !is_null( $this->mRevisionObject
) ) {
5465 return $this->mRevisionObject
;
5467 if ( is_null( $this->mRevisionId
) ) {
5471 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5472 return $this->mRevisionObject
;
5476 * Get the timestamp associated with the current revision, adjusted for
5477 * the default server-local timestamp
5479 function getRevisionTimestamp() {
5480 if ( is_null( $this->mRevisionTimestamp
) ) {
5481 wfProfileIn( __METHOD__
);
5485 $revObject = $this->getRevisionObject();
5486 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5488 # The cryptic '' timezone parameter tells to use the site-default
5489 # timezone offset instead of the user settings.
5491 # Since this value will be saved into the parser cache, served
5492 # to other users, and potentially even used inside links and such,
5493 # it needs to be consistent for all visitors.
5494 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5496 wfProfileOut( __METHOD__
);
5498 return $this->mRevisionTimestamp
;
5502 * Get the name of the user that edited the last revision
5504 * @return String: user name
5506 function getRevisionUser() {
5507 if( is_null( $this->mRevisionUser
) ) {
5508 $revObject = $this->getRevisionObject();
5510 # if this template is subst: the revision id will be blank,
5511 # so just use the current user's name
5513 $this->mRevisionUser
= $revObject->getUserText();
5514 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5515 $this->mRevisionUser
= $this->getUser()->getName();
5518 return $this->mRevisionUser
;
5522 * Mutator for $mDefaultSort
5524 * @param $sort string New value
5526 public function setDefaultSort( $sort ) {
5527 $this->mDefaultSort
= $sort;
5528 $this->mOutput
->setProperty( 'defaultsort', $sort );
5532 * Accessor for $mDefaultSort
5533 * Will use the empty string if none is set.
5535 * This value is treated as a prefix, so the
5536 * empty string is equivalent to sorting by
5541 public function getDefaultSort() {
5542 if ( $this->mDefaultSort
!== false ) {
5543 return $this->mDefaultSort
;
5550 * Accessor for $mDefaultSort
5551 * Unlike getDefaultSort(), will return false if none is set
5553 * @return string or false
5555 public function getCustomDefaultSort() {
5556 return $this->mDefaultSort
;
5560 * Try to guess the section anchor name based on a wikitext fragment
5561 * presumably extracted from a heading, for example "Header" from
5564 * @param $text string
5568 public function guessSectionNameFromWikiText( $text ) {
5569 # Strip out wikitext links(they break the anchor)
5570 $text = $this->stripSectionName( $text );
5571 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5572 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5576 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5577 * instead. For use in redirects, since IE6 interprets Redirect: headers
5578 * as something other than UTF-8 (apparently?), resulting in breakage.
5580 * @param $text String: The section name
5581 * @return string An anchor
5583 public function guessLegacySectionNameFromWikiText( $text ) {
5584 # Strip out wikitext links(they break the anchor)
5585 $text = $this->stripSectionName( $text );
5586 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5587 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5591 * Strips a text string of wikitext for use in a section anchor
5593 * Accepts a text string and then removes all wikitext from the
5594 * string and leaves only the resultant text (i.e. the result of
5595 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5596 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5597 * to create valid section anchors by mimicing the output of the
5598 * parser when headings are parsed.
5600 * @param $text String: text string to be stripped of wikitext
5601 * for use in a Section anchor
5602 * @return string Filtered text string
5604 public function stripSectionName( $text ) {
5605 # Strip internal link markup
5606 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5607 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5609 # Strip external link markup
5610 # @todo FIXME: Not tolerant to blank link text
5611 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5612 # on how many empty links there are on the page - need to figure that out.
5613 $text = preg_replace( '/\[(?:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5615 # Parse wikitext quotes (italics & bold)
5616 $text = $this->doQuotes( $text );
5619 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5624 * strip/replaceVariables/unstrip for preprocessor regression testing
5626 * @param $text string
5627 * @param $title Title
5628 * @param $options ParserOptions
5629 * @param $outputType int
5633 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5634 $this->startParse( $title, $options, $outputType, true );
5636 $text = $this->replaceVariables( $text );
5637 $text = $this->mStripState
->unstripBoth( $text );
5638 $text = Sanitizer
::removeHTMLtags( $text );
5643 * @param $text string
5644 * @param $title Title
5645 * @param $options ParserOptions
5648 function testPst( $text, Title
$title, ParserOptions
$options ) {
5649 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5654 * @param $title Title
5655 * @param $options ParserOptions
5658 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5659 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5663 * Call a callback function on all regions of the given text that are not
5664 * inside strip markers, and replace those regions with the return value
5665 * of the callback. For example, with input:
5669 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5670 * two strings will be replaced with the value returned by the callback in
5678 function markerSkipCallback( $s, $callback ) {
5681 while ( $i < strlen( $s ) ) {
5682 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5683 if ( $markerStart === false ) {
5684 $out .= call_user_func( $callback, substr( $s, $i ) );
5687 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5688 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5689 if ( $markerEnd === false ) {
5690 $out .= substr( $s, $markerStart );
5693 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5694 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5703 * Remove any strip markers found in the given text.
5705 * @param $text Input string
5708 function killMarkers( $text ) {
5709 return $this->mStripState
->killMarkers( $text );
5713 * Save the parser state required to convert the given half-parsed text to
5714 * HTML. "Half-parsed" in this context means the output of
5715 * recursiveTagParse() or internalParse(). This output has strip markers
5716 * from replaceVariables (extensionSubstitution() etc.), and link
5717 * placeholders from replaceLinkHolders().
5719 * Returns an array which can be serialized and stored persistently. This
5720 * array can later be loaded into another parser instance with
5721 * unserializeHalfParsedText(). The text can then be safely incorporated into
5722 * the return value of a parser hook.
5724 * @param $text string
5728 function serializeHalfParsedText( $text ) {
5729 wfProfileIn( __METHOD__
);
5732 'version' => self
::HALF_PARSED_VERSION
,
5733 'stripState' => $this->mStripState
->getSubState( $text ),
5734 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5736 wfProfileOut( __METHOD__
);
5741 * Load the parser state given in the $data array, which is assumed to
5742 * have been generated by serializeHalfParsedText(). The text contents is
5743 * extracted from the array, and its markers are transformed into markers
5744 * appropriate for the current Parser instance. This transformed text is
5745 * returned, and can be safely included in the return value of a parser
5748 * If the $data array has been stored persistently, the caller should first
5749 * check whether it is still valid, by calling isValidHalfParsedText().
5751 * @param $data array Serialized data
5754 function unserializeHalfParsedText( $data ) {
5755 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5756 throw new MWException( __METHOD__
.': invalid version' );
5759 # First, extract the strip state.
5760 $texts = array( $data['text'] );
5761 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5763 # Now renumber links
5764 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5766 # Should be good to go.
5771 * Returns true if the given array, presumed to be generated by
5772 * serializeHalfParsedText(), is compatible with the current version of the
5775 * @param $data Array
5779 function isValidHalfParsedText( $data ) {
5780 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;