3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Return the content of a section from an article for section editing
30 * Replaces a section by number inside an article
32 * Removes <noinclude> sections, and <includeonly> tags.
35 * objects: $wgLang, $wgContLang
37 * NOT $wgUser or $wgTitle. Keep them away!
40 * $wgUseDynamicDates*, $wgInterwikiMagic*,
41 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
42 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
45 * * only within ParserOptions
52 * Update this version number when the ParserOutput format
53 * changes in an incompatible way, so the parser cache
54 * can automatically discard old data.
56 const VERSION
= '1.6.5';
59 * Update this version number when the output of serialiseHalfParsedText()
60 * changes in an incompatible way
62 const HALF_PARSED_VERSION
= 2;
64 # Flags for Parser::setFunctionHook
65 # Also available as global constants from Defines.php
66 const SFH_NO_HASH
= 1;
67 const SFH_OBJECT_ARGS
= 2;
69 # Constants needed for external link processing
70 # Everything except bracket, space, or control characters
71 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
72 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
73 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
74 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
75 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
77 # State constants for the definition list colon extraction
78 const COLON_STATE_TEXT
= 0;
79 const COLON_STATE_TAG
= 1;
80 const COLON_STATE_TAGSTART
= 2;
81 const COLON_STATE_CLOSETAG
= 3;
82 const COLON_STATE_TAGSLASH
= 4;
83 const COLON_STATE_COMMENT
= 5;
84 const COLON_STATE_COMMENTDASH
= 6;
85 const COLON_STATE_COMMENTDASHDASH
= 7;
87 # Flags for preprocessToDom
88 const PTD_FOR_INCLUSION
= 1;
90 # Allowed values for $this->mOutputType
91 # Parameter to startExternalParse().
92 const OT_HTML
= 1; # like parse()
93 const OT_WIKI
= 2; # like preSaveTransform()
94 const OT_PREPROCESS
= 3; # like preprocess()
96 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
98 # Marker Suffix needs to be accessible staticly.
99 const MARKER_SUFFIX
= "-QINU\x7f";
102 var $mTagHooks = array();
103 var $mTransparentTagHooks = array();
104 var $mFunctionHooks = array();
105 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
106 var $mFunctionTagHooks = array();
107 var $mStripList = array();
108 var $mDefaultStripList = array();
109 var $mVarCache = array();
110 var $mImageParams = array();
111 var $mImageParamsMagicArray = array();
112 var $mMarkerIndex = 0;
113 var $mFirstCall = true;
115 # Initialised by initialiseVariables()
118 * @var MagicWordArray
123 * @var MagicWordArray
126 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
128 # Cleared with clearState():
133 var $mAutonumber, $mDTopen;
140 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
142 * @var LinkHolderArray
147 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
148 var $mTplExpandCache; # empty-frame expansion cache
149 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
150 var $mExpensiveFunctionCount; # number of expensive parser function calls
155 var $mUser; # User object; only used when doing pre-save transform
158 # These are variables reset at least once per parse regardless of $clearState
168 var $mTitle; # Title context, used for self-link rendering and similar things
169 var $mOutputType; # Output type, one of the OT_xxx constants
170 var $ot; # Shortcut alias, see setOutputType()
171 var $mRevisionObject; # The revision object of the specified revision ID
172 var $mRevisionId; # ID to display in {{REVISIONID}} tags
173 var $mRevisionTimestamp; # The timestamp of the specified revision ID
174 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
175 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
185 public function __construct( $conf = array() ) {
186 $this->mConf
= $conf;
187 $this->mUrlProtocols
= wfUrlProtocols();
188 $this->mExtLinkBracketedRegex
= '/\[((' . wfUrlProtocols() . ')'.
189 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
190 if ( isset( $conf['preprocessorClass'] ) ) {
191 $this->mPreprocessorClass
= $conf['preprocessorClass'];
192 } elseif ( defined( 'MW_COMPILED' ) ) {
193 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
194 $this->mPreprocessorClass
= 'Preprocessor_Hash';
195 } elseif ( extension_loaded( 'domxml' ) ) {
196 # PECL extension that conflicts with the core DOM extension (bug 13770)
197 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
198 $this->mPreprocessorClass
= 'Preprocessor_Hash';
199 } elseif ( extension_loaded( 'dom' ) ) {
200 $this->mPreprocessorClass
= 'Preprocessor_DOM';
202 $this->mPreprocessorClass
= 'Preprocessor_Hash';
204 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
208 * Reduce memory usage to reduce the impact of circular references
210 function __destruct() {
211 if ( isset( $this->mLinkHolders
) ) {
212 unset( $this->mLinkHolders
);
214 foreach ( $this as $name => $value ) {
215 unset( $this->$name );
220 * Do various kinds of initialisation on the first call of the parser
222 function firstCallInit() {
223 if ( !$this->mFirstCall
) {
226 $this->mFirstCall
= false;
228 wfProfileIn( __METHOD__
);
230 CoreParserFunctions
::register( $this );
231 CoreTagHooks
::register( $this );
232 $this->initialiseVariables();
234 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
235 wfProfileOut( __METHOD__
);
243 function clearState() {
244 wfProfileIn( __METHOD__
);
245 if ( $this->mFirstCall
) {
246 $this->firstCallInit();
248 $this->mOutput
= new ParserOutput
;
249 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
250 $this->mAutonumber
= 0;
251 $this->mLastSection
= '';
252 $this->mDTopen
= false;
253 $this->mIncludeCount
= array();
254 $this->mArgStack
= false;
255 $this->mInPre
= false;
256 $this->mLinkHolders
= new LinkHolderArray( $this );
258 $this->mRevisionObject
= $this->mRevisionTimestamp
=
259 $this->mRevisionId
= $this->mRevisionUser
= null;
260 $this->mVarCache
= array();
264 * Prefix for temporary replacement strings for the multipass parser.
265 * \x07 should never appear in input as it's disallowed in XML.
266 * Using it at the front also gives us a little extra robustness
267 * since it shouldn't match when butted up against identifier-like
270 * Must not consist of all title characters, or else it will change
271 * the behaviour of <nowiki> in a link.
273 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
274 # Changed to \x7f to allow XML double-parsing -- TS
275 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
276 $this->mStripState
= new StripState( $this->mUniqPrefix
);
279 # Clear these on every parse, bug 4549
280 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
282 $this->mShowToc
= true;
283 $this->mForceTocPosition
= false;
284 $this->mIncludeSizes
= array(
288 $this->mPPNodeCount
= 0;
289 $this->mDefaultSort
= false;
290 $this->mHeadings
= array();
291 $this->mDoubleUnderscores
= array();
292 $this->mExpensiveFunctionCount
= 0;
295 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
296 $this->mPreprocessor
= null;
299 wfRunHooks( 'ParserClearState', array( &$this ) );
300 wfProfileOut( __METHOD__
);
304 * Convert wikitext to HTML
305 * Do not call this function recursively.
307 * @param $text String: text we want to parse
308 * @param $title Title object
309 * @param $options ParserOptions
310 * @param $linestart boolean
311 * @param $clearState boolean
312 * @param $revid Int: number to pass in {{REVISIONID}}
313 * @return ParserOutput a ParserOutput
315 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
317 * First pass--just handle <nowiki> sections, pass the rest off
318 * to internalParse() which does all the real work.
321 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
322 $fname = __METHOD__
.'-' . wfGetCaller();
323 wfProfileIn( __METHOD__
);
324 wfProfileIn( $fname );
326 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
328 $oldRevisionId = $this->mRevisionId
;
329 $oldRevisionObject = $this->mRevisionObject
;
330 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
331 $oldRevisionUser = $this->mRevisionUser
;
332 if ( $revid !== null ) {
333 $this->mRevisionId
= $revid;
334 $this->mRevisionObject
= null;
335 $this->mRevisionTimestamp
= null;
336 $this->mRevisionUser
= null;
339 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
341 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
342 $text = $this->internalParse( $text );
344 $text = $this->mStripState
->unstripGeneral( $text );
346 # Clean up special characters, only run once, next-to-last before doBlockLevels
348 # french spaces, last one Guillemet-left
349 # only if there is something before the space
350 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
351 # french spaces, Guillemet-right
352 '/(\\302\\253) /' => '\\1 ',
353 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
355 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
357 $text = $this->doBlockLevels( $text, $linestart );
359 $this->replaceLinkHolders( $text );
362 * The page doesn't get language converted if
364 * b) Content isn't converted
365 * c) It's a conversion table
367 if ( !( $wgDisableLangConversion
368 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
369 ||
$this->mTitle
->isConversionTable() ) ) {
371 # The position of the convert() call should not be changed. it
372 # assumes that the links are all replaced and the only thing left
373 # is the <nowiki> mark.
375 $text = $wgContLang->convert( $text );
379 * A converted title will be provided in the output object if title and
380 * content conversion are enabled, the article text does not contain
381 * a conversion-suppressing double-underscore tag, and no
382 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
383 * automatic link conversion.
385 if ( !( $wgDisableLangConversion
386 ||
$wgDisableTitleConversion
387 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
388 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
389 ||
$this->mOutput
->getDisplayTitle() !== false ) )
391 $convruletitle = $wgContLang->getConvRuleTitle();
392 if ( $convruletitle ) {
393 $this->mOutput
->setTitleText( $convruletitle );
395 $titleText = $wgContLang->convertTitle( $title );
396 $this->mOutput
->setTitleText( $titleText );
400 $text = $this->mStripState
->unstripNoWiki( $text );
402 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
404 $text = $this->replaceTransparentTags( $text );
405 $text = $this->mStripState
->unstripGeneral( $text );
407 $text = Sanitizer
::normalizeCharReferences( $text );
409 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
410 $text = MWTidy
::tidy( $text );
412 # attempt to sanitize at least some nesting problems
413 # (bug #2702 and quite a few others)
415 # ''Something [http://www.cool.com cool''] -->
416 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
417 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
418 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
419 # fix up an anchor inside another anchor, only
420 # at least for a single single nested link (bug 3695)
421 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
422 '\\1\\2</a>\\3</a>\\1\\4</a>',
423 # fix div inside inline elements- doBlockLevels won't wrap a line which
424 # contains a div, so fix it up here; replace
425 # div with escaped text
426 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
427 '\\1\\3<div\\5>\\6</div>\\8\\9',
428 # remove empty italic or bold tag pairs, some
429 # introduced by rules above
430 '/<([bi])><\/\\1>/' => '',
433 $text = preg_replace(
434 array_keys( $tidyregs ),
435 array_values( $tidyregs ),
438 global $wgExpensiveParserFunctionLimit;
439 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
440 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
443 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
445 # Information on include size limits, for the benefit of users who try to skirt them
446 if ( $this->mOptions
->getEnableLimitReport() ) {
447 $max = $this->mOptions
->getMaxIncludeSize();
448 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
450 "NewPP limit report\n" .
451 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
452 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
453 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
455 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
456 $text .= "\n<!-- \n$limitReport-->\n";
458 $this->mOutput
->setText( $text );
460 $this->mRevisionId
= $oldRevisionId;
461 $this->mRevisionObject
= $oldRevisionObject;
462 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
463 $this->mRevisionUser
= $oldRevisionUser;
464 wfProfileOut( $fname );
465 wfProfileOut( __METHOD__
);
467 return $this->mOutput
;
471 * Recursive parser entry point that can be called from an extension tag
474 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
476 * @param $text String: text extension wants to have parsed
477 * @param $frame PPFrame: The frame to use for expanding any template variables
481 function recursiveTagParse( $text, $frame=false ) {
482 wfProfileIn( __METHOD__
);
483 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
484 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
485 $text = $this->internalParse( $text, false, $frame );
486 wfProfileOut( __METHOD__
);
491 * Expand templates and variables in the text, producing valid, static wikitext.
492 * Also removes comments.
494 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
495 wfProfileIn( __METHOD__
);
496 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
497 if ( $revid !== null ) {
498 $this->mRevisionId
= $revid;
500 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
501 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
502 $text = $this->replaceVariables( $text );
503 $text = $this->mStripState
->unstripBoth( $text );
504 wfProfileOut( __METHOD__
);
509 * Process the wikitext for the ?preload= feature. (bug 5210)
511 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
512 * comments, templates, arguments, tags hooks and parser functions are untouched.
514 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
515 # Parser (re)initialisation
516 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
518 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
519 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
520 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
521 $text = $this->mStripState
->unstripBoth( $text );
526 * Get a random string
530 static public function getRandomString() {
531 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
535 * Set the current user.
536 * Should only be used when doing pre-save transform.
538 * @param $user Mixed: User object or null (to reset)
540 function setUser( $user ) {
541 $this->mUser
= $user;
545 * Accessor for mUniqPrefix.
549 public function uniqPrefix() {
550 if ( !isset( $this->mUniqPrefix
) ) {
551 # @todo FIXME: This is probably *horribly wrong*
552 # LanguageConverter seems to want $wgParser's uniqPrefix, however
553 # if this is called for a parser cache hit, the parser may not
554 # have ever been initialized in the first place.
555 # Not really sure what the heck is supposed to be going on here.
557 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
559 return $this->mUniqPrefix
;
563 * Set the context title
567 function setTitle( $t ) {
568 if ( !$t ||
$t instanceof FakeTitle
) {
569 $t = Title
::newFromText( 'NO TITLE' );
572 if ( strval( $t->getFragment() ) !== '' ) {
573 # Strip the fragment to avoid various odd effects
574 $this->mTitle
= clone $t;
575 $this->mTitle
->setFragment( '' );
582 * Accessor for the Title object
584 * @return Title object
586 function getTitle() {
587 return $this->mTitle
;
591 * Accessor/mutator for the Title object
593 * @param $x New Title object or null to just get the current one
594 * @return Title object
596 function Title( $x = null ) {
597 return wfSetVar( $this->mTitle
, $x );
601 * Set the output type
603 * @param $ot Integer: new value
605 function setOutputType( $ot ) {
606 $this->mOutputType
= $ot;
609 'html' => $ot == self
::OT_HTML
,
610 'wiki' => $ot == self
::OT_WIKI
,
611 'pre' => $ot == self
::OT_PREPROCESS
,
612 'plain' => $ot == self
::OT_PLAIN
,
617 * Accessor/mutator for the output type
619 * @param $x New value or null to just get the current one
622 function OutputType( $x = null ) {
623 return wfSetVar( $this->mOutputType
, $x );
627 * Get the ParserOutput object
629 * @return ParserOutput object
631 function getOutput() {
632 return $this->mOutput
;
636 * Get the ParserOptions object
638 * @return ParserOptions object
640 function getOptions() {
641 return $this->mOptions
;
645 * Accessor/mutator for the ParserOptions object
647 * @param $x New value or null to just get the current one
648 * @return Current ParserOptions object
650 function Options( $x = null ) {
651 return wfSetVar( $this->mOptions
, $x );
657 function nextLinkID() {
658 return $this->mLinkID++
;
664 function setLinkID( $id ) {
665 $this->mLinkID
= $id;
671 function getFunctionLang() {
674 $target = $this->mOptions
->getTargetLanguage();
675 if ( $target !== null ) {
678 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $this->mTitle
->getPageLanguage();
683 * Get a User object either from $this->mUser, if set, or from the
684 * ParserOptions object otherwise
686 * @return User object
689 if ( !is_null( $this->mUser
) ) {
692 return $this->mOptions
->getUser();
696 * Get a preprocessor object
698 * @return Preprocessor instance
700 function getPreprocessor() {
701 if ( !isset( $this->mPreprocessor
) ) {
702 $class = $this->mPreprocessorClass
;
703 $this->mPreprocessor
= new $class( $this );
705 return $this->mPreprocessor
;
709 * Replaces all occurrences of HTML-style comments and the given tags
710 * in the text with a random marker and returns the next text. The output
711 * parameter $matches will be an associative array filled with data in
713 * 'UNIQ-xxxxx' => array(
716 * array( 'param' => 'x' ),
717 * '<element param="x">tag content</element>' ) )
719 * @param $elements array list of element names. Comments are always extracted.
720 * @param $text string Source text string.
721 * @param $matches array Out parameter, Array: extracted tags
722 * @param $uniq_prefix string
723 * @return String: stripped text
725 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
730 $taglist = implode( '|', $elements );
731 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
733 while ( $text != '' ) {
734 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
736 if ( count( $p ) < 5 ) {
739 if ( count( $p ) > 5 ) {
753 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
754 $stripped .= $marker;
756 if ( $close === '/>' ) {
757 # Empty element tag, <tag />
762 if ( $element === '!--' ) {
765 $end = "/(<\\/$element\\s*>)/i";
767 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
769 if ( count( $q ) < 3 ) {
770 # No end tag -- let it run out to the end of the text.
779 $matches[$marker] = array( $element,
781 Sanitizer
::decodeTagAttributes( $attributes ),
782 "<$element$attributes$close$content$tail" );
788 * Get a list of strippable XML-like elements
792 function getStripList() {
793 return $this->mStripList
;
797 * Add an item to the strip state
798 * Returns the unique tag which must be inserted into the stripped text
799 * The tag will be replaced with the original text in unstrip()
801 function insertStripItem( $text ) {
802 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
803 $this->mMarkerIndex++
;
804 $this->mStripState
->addGeneral( $rnd, $text );
809 * parse the wiki syntax used to render tables
813 function doTableStuff( $text ) {
814 wfProfileIn( __METHOD__
);
816 $lines = StringUtils
::explode( "\n", $text );
820 foreach ( $lines as $outLine ) {
821 $line = trim( $outLine );
823 # empty line, go to next line,
824 # but only append \n if outside of table
826 $output .= $outLine . "\n";
829 $firstChars = $line[0];
830 if ( strlen( $line ) > 1 ) {
831 $firstChars .= in_array( $line[1], array( '}', '+', '-' ) ) ?
$line[1] : '';
835 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line , $matches ) ) {
837 $table =& $this->last( $tables );
838 $table[0] = array(); // first row
839 $currentRow =& $table[0];
840 $table['indent'] = strlen( $matches[1] );
842 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
843 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
845 if ( $attributes !== '' ) {
846 $table['attributes'] = $attributes;
848 } elseif ( !isset( $tables[0] ) ) {
849 // we're outside the table
851 $out .= $outLine . "\n";
852 } elseif ( $firstChars === '|}' ) {
853 // trim the |} code from the line
854 $line = substr ( $line , 2 );
856 // Shorthand for last row
857 $lastRow =& $this->last( $table );
859 // a thead at the end becomes a tfoot, unless there is only one row
860 // Do this before deleting empty last lines to allow headers at the bottom of tables
861 if ( isset( $lastRow['type'] ) && $lastRow['type'] == 'thead' && isset( $table[1] ) ) {
862 $lastRow['type'] = 'tfoot';
863 for ( $i = 0; isset( $lastRow[$i] ); $i++
) {
864 $lastRow[$i]['type'] = 'th';
868 // Delete empty last lines
869 if ( empty( $lastRow ) ) {
873 $curtable = array_pop( $tables );
875 #Add a line-ending before the table, but only if there isn't one already
876 if ( substr( $out, -1 ) !== "\n" ) {
879 $o .= $this->generateTableHTML( $curtable ) . $line . "\n";
881 if ( count( $tables ) > 0 ) {
882 $table =& $this->last( $tables );
883 $currentRow =& $this->last( $table );
884 $currentElement =& $this->last( $currentRow );
886 $output =& $currentElement['content'];
893 } elseif ( $firstChars === '|-' ) {
894 // start a new row element
895 // but only when we haven't started one already
896 if ( count( $currentRow ) != 0 ) {
898 $currentRow =& $this->last( $table );
900 // Get the attributes, there's nothing else useful in $line now
901 $line = substr ( $line , 2 );
902 $attributes = $this->mStripState
->unstripBoth( $line );
903 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
904 if ( $attributes !== '' ) {
905 $currentRow['attributes'] = $attributes;
908 } elseif ( $firstChars === '|+' ) {
909 // a table caption, but only proceed if there isn't one already
910 if ( !isset ( $table['caption'] ) ) {
911 $line = substr ( $line , 2 );
913 $c = $this->getCellAttr( $line , 'caption' );
914 $table['caption'] = array();
915 $table['caption']['content'] = $c[0];
916 if ( isset( $c[1] ) ) $table['caption']['attributes'] = $c[1];
918 $output =& $table['caption']['content'];
920 } elseif ( $firstChars === '|' ||
$firstChars === '!' ||
$firstChars === '!+' ) {
921 // Which kind of cells are we dealing with
923 $line = substr ( $line , 1 );
925 if ( $firstChars === '!' ||
$firstChars === '!+' ) {
926 $line = str_replace ( '!!' , '||' , $line );
930 // Split up multiple cells on the same line.
931 $cells = StringUtils
::explodeMarkup( '||' , $line );
932 $line = ''; // save memory
934 // decide whether thead to tbody
935 if ( !array_key_exists( 'type', $currentRow ) ) {
936 $currentRow['type'] = ( $firstChars === '!' ) ?
'thead' : 'tbody' ;
937 } elseif ( $firstChars === '|' ) {
938 $currentRow['type'] = 'tbody';
941 // Loop through each table cell
942 foreach ( $cells as $cell ) {
944 $currentRow[] = array();
945 $currentElement =& $this->last( $currentRow );
947 $currentElement['type'] = $currentTag;
949 $c = $this->getCellAttr( $cell , $currentTag );
950 $currentElement['content'] = $c[0];
951 if ( isset( $c[1] ) ) $currentElement['attributes'] = $c[1];
954 $output =& $currentElement['content'];
957 $output .= "\n$outLine";
961 # Remove trailing line-ending (b/c)
962 if ( substr( $out, -1 ) === "\n" ) {
963 $out = substr( $out, 0, -1 );
966 # Close any unclosed tables
967 if ( isset( $tables ) && count( $tables ) > 0 ) {
968 for ( $i = 0; $i < count( $tables ); $i++
) {
969 $curtable = array_pop( $tables );
970 $curtable = $this->generateTableHTML( $curtable );
971 #Add a line-ending before the table, but only if there isn't one already
972 if ( substr( $out, -1 ) !== "\n" && $curtable !== "" ) {
979 wfProfileOut( __METHOD__
);
985 * Helper function for doTableStuff() separating the contents of cells from
986 * attributes. Particularly useful as there's a possible bug and this action
994 function getCellAttr ( $cell, $tagName ) {
997 $cell = trim ( $cell );
999 // A cell could contain both parameters and data
1000 $cellData = explode ( '|' , $cell , 2 );
1002 // Bug 553: Note that a '|' inside an invalid link should not
1003 // be mistaken as delimiting cell parameters
1004 if ( strpos( $cellData[0], '[[' ) !== false ) {
1005 $content = trim ( $cell );
1007 elseif ( count ( $cellData ) == 1 ) {
1008 $content = trim ( $cellData[0] );
1010 $attributes = $this->mStripState
->unstripBoth( $cellData[0] );
1011 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tagName );
1013 $content = trim ( $cellData[1] );
1015 return array( $content, $attributes );
1020 * Helper function for doTableStuff(). This converts the structured array into html.
1024 function generateTableHTML( &$table ) {
1026 $return .= str_repeat( '<dl><dd>' , $table['indent'] );
1027 $return .= '<table';
1028 $return .= isset( $table['attributes'] ) ?
$table['attributes'] : '';
1030 unset( $table['attributes'] );
1032 if ( isset( $table['caption'] ) ) {
1033 $return .= "\n<caption";
1034 $return .= isset( $table['caption']['attributes'] ) ?
$table['caption']['attributes'] : '';
1036 $return .= $table['caption']['content'];
1037 $return .= "\n</caption>";
1043 // If we only have tbodies, mark table as simple
1044 for ( $i = 0; isset( $table[$i] ); $i++
) {
1045 if ( !count( $table[$i] ) ) continue;
1046 if ( !isset( $table[$i]['type'] ) ) {
1047 $table[$i]['type'] = 'tbody';
1049 if ( !$lastSection ) {
1050 $lastSection = $table[$i]['type'];
1051 } elseif ( $lastSection != $table[$i]['type'] ) {
1056 for ( $i = 0; isset( $table[$i] ); $i++
) {
1057 if ( !count( $table[$i] ) ) continue;
1058 $empty = false; // check for empty tables
1060 if ( $table[$i]['type'] != $lastSection && !$simple ) {
1061 $return .= "\n<" . $table[$i]['type'] . '>';
1065 $return .= isset( $table[$i]['attributes'] ) ?
$table[$i]['attributes'] : '';
1067 for ( $j = 0; isset( $table[$i][$j] ); $j++
) {
1068 if ( !isset( $table[$i][$j]['type'] ) ) $table[$i][$j]['type'] = 'td';
1069 $return .= "\n<" . $table[$i][$j]['type'];
1070 $return .= isset( $table[$i][$j]['attributes'] ) ?
$table[$i][$j]['attributes'] : '';
1073 $return .= $table[$i][$j]['content'];
1074 if ( $table[$i][$j]['content'] != '' )
1077 $return .= '</' . $table[$i][$j]['type'] . '>';
1078 unset( $table[$i][$j] );
1080 $return .= "\n</tr>";
1082 if ( ( !isset( $table[$i +
1] ) && !$simple ) ||
( isset( $table[$i +
1] ) && isset( $table[$i +
1]['type'] ) && $table[$i]['type'] != $table[$i +
1]['type'] ) ) {
1083 $return .= '</' . $table[$i]['type'] . '>';
1085 $lastSection = $table[$i]['type'];
1086 unset( $table[$i] );
1089 if ( isset( $table['caption'] ) ) {
1090 $return .= "\n<tr><td></td></tr>";
1095 $return .= "\n</table>";
1096 $return .= str_repeat( '</dd></dl>' , $table['indent'] );
1102 * like end() but only works on the numeric array index and php's internal pointers
1103 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1104 * ignores associative elements and will create a 0 key will a NULL value if there were
1105 * no numric elements and an array itself if not previously defined.
1109 function &last ( &$arr ) {
1110 for ( $i = count( $arr ); ( !isset( $arr[$i] ) && $i > 0 ); $i-- ) { }
1115 * Helper function for parse() that transforms wiki markup into
1116 * HTML. Only called for $mOutputType == self::OT_HTML.
1120 function internalParse( $text, $isMain = true, $frame=false ) {
1121 wfProfileIn( __METHOD__
);
1125 # Hook to suspend the parser in this state
1126 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1127 wfProfileOut( __METHOD__
);
1131 # if $frame is provided, then use $frame for replacing any variables
1133 # use frame depth to infer how include/noinclude tags should be handled
1134 # depth=0 means this is the top-level document; otherwise it's an included document
1135 if ( !$frame->depth
) {
1138 $flag = Parser
::PTD_FOR_INCLUSION
;
1140 $dom = $this->preprocessToDom( $text, $flag );
1141 $text = $frame->expand( $dom );
1143 # if $frame is not provided, then use old-style replaceVariables
1144 $text = $this->replaceVariables( $text );
1147 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1148 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1150 # Tables need to come after variable replacement for things to work
1151 # properly; putting them before other transformations should keep
1152 # exciting things like link expansions from showing up in surprising
1154 $text = $this->doTableStuff( $text );
1156 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1158 $text = $this->doDoubleUnderscore( $text );
1160 $text = $this->doHeadings( $text );
1161 if ( $this->mOptions
->getUseDynamicDates() ) {
1162 $df = DateFormatter
::getInstance();
1163 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1165 $text = $this->replaceInternalLinks( $text );
1166 $text = $this->doAllQuotes( $text );
1167 $text = $this->replaceExternalLinks( $text );
1169 # replaceInternalLinks may sometimes leave behind
1170 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1171 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1173 $text = $this->doMagicLinks( $text );
1174 $text = $this->formatHeadings( $text, $origText, $isMain );
1176 wfProfileOut( __METHOD__
);
1181 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1182 * magic external links.
1187 function doMagicLinks( $text ) {
1188 wfProfileIn( __METHOD__
);
1189 $prots = $this->mUrlProtocols
;
1190 $urlChar = self
::EXT_LINK_URL_CLASS
;
1191 $text = preg_replace_callback(
1193 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1194 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1195 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1196 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1197 ISBN\s+(\b # m[5]: ISBN, capture number
1198 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1199 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1200 [0-9Xx] # check digit
1202 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1203 wfProfileOut( __METHOD__
);
1208 * @throws MWException
1210 * @return HTML|string
1212 function magicLinkCallback( $m ) {
1213 if ( isset( $m[1] ) && $m[1] !== '' ) {
1216 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1219 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1220 # Free external link
1221 return $this->makeFreeExternalLink( $m[0] );
1222 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1224 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1227 $CssClass = 'mw-magiclink-rfc';
1229 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1231 $urlmsg = 'pubmedurl';
1232 $CssClass = 'mw-magiclink-pmid';
1235 throw new MWException( __METHOD__
.': unrecognised match type "' .
1236 substr( $m[0], 0, 20 ) . '"' );
1238 $url = wfMsgForContent( $urlmsg, $id );
1239 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1240 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1243 $num = strtr( $isbn, array(
1248 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1250 $titleObj->escapeLocalUrl() .
1251 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1258 * Make a free external link, given a user-supplied URL
1262 function makeFreeExternalLink( $url ) {
1264 wfProfileIn( __METHOD__
);
1268 # The characters '<' and '>' (which were escaped by
1269 # removeHTMLtags()) should not be included in
1270 # URLs, per RFC 2396.
1272 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1273 $trail = substr( $url, $m2[0][1] ) . $trail;
1274 $url = substr( $url, 0, $m2[0][1] );
1277 # Move trailing punctuation to $trail
1279 # If there is no left bracket, then consider right brackets fair game too
1280 if ( strpos( $url, '(' ) === false ) {
1284 $numSepChars = strspn( strrev( $url ), $sep );
1285 if ( $numSepChars ) {
1286 $trail = substr( $url, -$numSepChars ) . $trail;
1287 $url = substr( $url, 0, -$numSepChars );
1290 $url = Sanitizer
::cleanUrl( $url );
1292 # Is this an external image?
1293 $text = $this->maybeMakeExternalImage( $url );
1294 if ( $text === false ) {
1295 # Not an image, make a link
1296 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1297 $this->getExternalLinkAttribs( $url ) );
1298 # Register it in the output object...
1299 # Replace unnecessary URL escape codes with their equivalent characters
1300 $pasteurized = self
::replaceUnusualEscapes( $url );
1301 $this->mOutput
->addExternalLink( $pasteurized );
1303 wfProfileOut( __METHOD__
);
1304 return $text . $trail;
1309 * Parse headers and return html
1313 function doHeadings( $text ) {
1314 wfProfileIn( __METHOD__
);
1315 for ( $i = 6; $i >= 1; --$i ) {
1316 $h = str_repeat( '=', $i );
1317 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1318 "<h$i>\\1</h$i>", $text );
1320 wfProfileOut( __METHOD__
);
1325 * Replace single quotes with HTML markup
1327 * @return string the altered text
1329 function doAllQuotes( $text ) {
1330 wfProfileIn( __METHOD__
);
1332 $lines = StringUtils
::explode( "\n", $text );
1333 foreach ( $lines as $line ) {
1334 $outtext .= $this->doQuotes( $line ) . "\n";
1336 $outtext = substr( $outtext, 0,-1 );
1337 wfProfileOut( __METHOD__
);
1342 * Helper function for doAllQuotes()
1344 public function doQuotes( $text ) {
1345 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1346 if ( count( $arr ) == 1 ) {
1349 # First, do some preliminary work. This may shift some apostrophes from
1350 # being mark-up to being text. It also counts the number of occurrences
1351 # of bold and italics mark-ups.
1354 for ( $i = 0; $i < count( $arr ); $i++
) {
1355 if ( ( $i %
2 ) == 1 ) {
1356 # If there are ever four apostrophes, assume the first is supposed to
1357 # be text, and the remaining three constitute mark-up for bold text.
1358 if ( strlen( $arr[$i] ) == 4 ) {
1361 } elseif ( strlen( $arr[$i] ) > 5 ) {
1362 # If there are more than 5 apostrophes in a row, assume they're all
1363 # text except for the last 5.
1364 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1367 # Count the number of occurrences of bold and italics mark-ups.
1368 # We are not counting sequences of five apostrophes.
1369 if ( strlen( $arr[$i] ) == 2 ) {
1371 } elseif ( strlen( $arr[$i] ) == 3 ) {
1373 } elseif ( strlen( $arr[$i] ) == 5 ) {
1380 # If there is an odd number of both bold and italics, it is likely
1381 # that one of the bold ones was meant to be an apostrophe followed
1382 # by italics. Which one we cannot know for certain, but it is more
1383 # likely to be one that has a single-letter word before it.
1384 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1386 $firstsingleletterword = -1;
1387 $firstmultiletterword = -1;
1389 foreach ( $arr as $r ) {
1390 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1391 $x1 = substr( $arr[$i-1], -1 );
1392 $x2 = substr( $arr[$i-1], -2, 1 );
1393 if ( $x1 === ' ' ) {
1394 if ( $firstspace == -1 ) {
1397 } elseif ( $x2 === ' ') {
1398 if ( $firstsingleletterword == -1 ) {
1399 $firstsingleletterword = $i;
1402 if ( $firstmultiletterword == -1 ) {
1403 $firstmultiletterword = $i;
1410 # If there is a single-letter word, use it!
1411 if ( $firstsingleletterword > -1 ) {
1412 $arr[$firstsingleletterword] = "''";
1413 $arr[$firstsingleletterword-1] .= "'";
1414 } elseif ( $firstmultiletterword > -1 ) {
1415 # If not, but there's a multi-letter word, use that one.
1416 $arr[$firstmultiletterword] = "''";
1417 $arr[$firstmultiletterword-1] .= "'";
1418 } elseif ( $firstspace > -1 ) {
1419 # ... otherwise use the first one that has neither.
1420 # (notice that it is possible for all three to be -1 if, for example,
1421 # there is only one pentuple-apostrophe in the line)
1422 $arr[$firstspace] = "''";
1423 $arr[$firstspace-1] .= "'";
1427 # Now let's actually convert our apostrophic mush to HTML!
1432 foreach ( $arr as $r ) {
1433 if ( ( $i %
2 ) == 0 ) {
1434 if ( $state === 'both' ) {
1440 if ( strlen( $r ) == 2 ) {
1441 if ( $state === 'i' ) {
1442 $output .= '</i>'; $state = '';
1443 } elseif ( $state === 'bi' ) {
1444 $output .= '</i>'; $state = 'b';
1445 } elseif ( $state === 'ib' ) {
1446 $output .= '</b></i><b>'; $state = 'b';
1447 } elseif ( $state === 'both' ) {
1448 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1449 } else { # $state can be 'b' or ''
1450 $output .= '<i>'; $state .= 'i';
1452 } elseif ( strlen( $r ) == 3 ) {
1453 if ( $state === 'b' ) {
1454 $output .= '</b>'; $state = '';
1455 } elseif ( $state === 'bi' ) {
1456 $output .= '</i></b><i>'; $state = 'i';
1457 } elseif ( $state === 'ib' ) {
1458 $output .= '</b>'; $state = 'i';
1459 } elseif ( $state === 'both' ) {
1460 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1461 } else { # $state can be 'i' or ''
1462 $output .= '<b>'; $state .= 'b';
1464 } elseif ( strlen( $r ) == 5 ) {
1465 if ( $state === 'b' ) {
1466 $output .= '</b><i>'; $state = 'i';
1467 } elseif ( $state === 'i' ) {
1468 $output .= '</i><b>'; $state = 'b';
1469 } elseif ( $state === 'bi' ) {
1470 $output .= '</i></b>'; $state = '';
1471 } elseif ( $state === 'ib' ) {
1472 $output .= '</b></i>'; $state = '';
1473 } elseif ( $state === 'both' ) {
1474 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1475 } else { # ($state == '')
1476 $buffer = ''; $state = 'both';
1482 # Now close all remaining tags. Notice that the order is important.
1483 if ( $state === 'b' ||
$state === 'ib' ) {
1486 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1489 if ( $state === 'bi' ) {
1492 # There might be lonely ''''', so make sure we have a buffer
1493 if ( $state === 'both' && $buffer ) {
1494 $output .= '<b><i>'.$buffer.'</i></b>';
1501 * Replace external links (REL)
1503 * Note: this is all very hackish and the order of execution matters a lot.
1504 * Make sure to run maintenance/parserTests.php if you change this code.
1508 function replaceExternalLinks( $text ) {
1510 wfProfileIn( __METHOD__
);
1512 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1513 $s = array_shift( $bits );
1516 while ( $i<count( $bits ) ) {
1518 $protocol = $bits[$i++
];
1519 $text = $bits[$i++
];
1520 $trail = $bits[$i++
];
1522 # The characters '<' and '>' (which were escaped by
1523 # removeHTMLtags()) should not be included in
1524 # URLs, per RFC 2396.
1526 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1527 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1528 $url = substr( $url, 0, $m2[0][1] );
1531 # If the link text is an image URL, replace it with an <img> tag
1532 # This happened by accident in the original parser, but some people used it extensively
1533 $img = $this->maybeMakeExternalImage( $text );
1534 if ( $img !== false ) {
1540 # Set linktype for CSS - if URL==text, link is essentially free
1541 $linktype = ( $text === $url ) ?
'free' : 'text';
1543 # No link text, e.g. [http://domain.tld/some.link]
1544 if ( $text == '' ) {
1546 $langObj = $this->getFunctionLang();
1547 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1548 $linktype = 'autonumber';
1550 # Have link text, e.g. [http://domain.tld/some.link text]s
1552 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1555 $text = $wgContLang->markNoConversion( $text );
1557 $url = Sanitizer
::cleanUrl( $url );
1559 # Use the encoded URL
1560 # This means that users can paste URLs directly into the text
1561 # Funny characters like ö aren't valid in URLs anyway
1562 # This was changed in August 2004
1563 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1564 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1566 # Register link in the output object.
1567 # Replace unnecessary URL escape codes with the referenced character
1568 # This prevents spammers from hiding links from the filters
1569 $pasteurized = self
::replaceUnusualEscapes( $url );
1570 $this->mOutput
->addExternalLink( $pasteurized );
1573 wfProfileOut( __METHOD__
);
1578 * Get an associative array of additional HTML attributes appropriate for a
1579 * particular external link. This currently may include rel => nofollow
1580 * (depending on configuration, namespace, and the URL's domain) and/or a
1581 * target attribute (depending on configuration).
1583 * @param $url String: optional URL, to extract the domain from for rel =>
1584 * nofollow if appropriate
1585 * @return Array: associative array of HTML attributes
1587 function getExternalLinkAttribs( $url = false ) {
1589 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1590 $ns = $this->mTitle
->getNamespace();
1591 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1592 $attribs['rel'] = 'nofollow';
1594 global $wgNoFollowDomainExceptions;
1595 if ( $wgNoFollowDomainExceptions ) {
1596 $bits = wfParseUrl( $url );
1597 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1598 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1599 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1600 unset( $attribs['rel'] );
1607 if ( $this->mOptions
->getExternalLinkTarget() ) {
1608 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1614 * Replace unusual URL escape codes with their equivalent characters
1616 * @param $url String
1619 * @todo This can merge genuinely required bits in the path or query string,
1620 * breaking legit URLs. A proper fix would treat the various parts of
1621 * the URL differently; as a workaround, just use the output for
1622 * statistical records, not for actual linking/output.
1624 static function replaceUnusualEscapes( $url ) {
1625 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1626 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1630 * Callback function used in replaceUnusualEscapes().
1631 * Replaces unusual URL escape codes with their equivalent character
1633 private static function replaceUnusualEscapesCallback( $matches ) {
1634 $char = urldecode( $matches[0] );
1635 $ord = ord( $char );
1636 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1637 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1638 # No, shouldn't be escaped
1641 # Yes, leave it escaped
1647 * make an image if it's allowed, either through the global
1648 * option, through the exception, or through the on-wiki whitelist
1651 function maybeMakeExternalImage( $url ) {
1652 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1653 $imagesexception = !empty( $imagesfrom );
1655 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1656 if ( $imagesexception && is_array( $imagesfrom ) ) {
1657 $imagematch = false;
1658 foreach ( $imagesfrom as $match ) {
1659 if ( strpos( $url, $match ) === 0 ) {
1664 } elseif ( $imagesexception ) {
1665 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1667 $imagematch = false;
1669 if ( $this->mOptions
->getAllowExternalImages()
1670 ||
( $imagesexception && $imagematch ) ) {
1671 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1673 $text = Linker
::makeExternalImage( $url );
1676 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1677 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1678 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1679 foreach ( $whitelist as $entry ) {
1680 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1681 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1684 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1685 # Image matches a whitelist entry
1686 $text = Linker
::makeExternalImage( $url );
1695 * Process [[ ]] wikilinks
1696 * @return String: processed text
1700 function replaceInternalLinks( $s ) {
1701 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1706 * Process [[ ]] wikilinks (RIL)
1707 * @return LinkHolderArray
1711 function replaceInternalLinks2( &$s ) {
1714 wfProfileIn( __METHOD__
);
1716 wfProfileIn( __METHOD__
.'-setup' );
1717 static $tc = FALSE, $e1, $e1_img;
1718 # the % is needed to support urlencoded titles as well
1720 $tc = Title
::legalChars() . '#%';
1721 # Match a link having the form [[namespace:link|alternate]]trail
1722 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1723 # Match cases where there is no "]]", which might still be images
1724 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1727 $holders = new LinkHolderArray( $this );
1729 # split the entire text string on occurences of [[
1730 $a = StringUtils
::explode( '[[', ' ' . $s );
1731 # get the first element (all text up to first [[), and remove the space we added
1734 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1735 $s = substr( $s, 1 );
1737 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1739 if ( $useLinkPrefixExtension ) {
1740 # Match the end of a line for a word that's not followed by whitespace,
1741 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1742 $e2 = wfMsgForContent( 'linkprefix' );
1745 if ( is_null( $this->mTitle
) ) {
1746 wfProfileOut( __METHOD__
.'-setup' );
1747 wfProfileOut( __METHOD__
);
1748 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1750 $nottalk = !$this->mTitle
->isTalkPage();
1752 if ( $useLinkPrefixExtension ) {
1754 if ( preg_match( $e2, $s, $m ) ) {
1755 $first_prefix = $m[2];
1757 $first_prefix = false;
1763 if ( $wgContLang->hasVariants() ) {
1764 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1766 $selflink = array( $this->mTitle
->getPrefixedText() );
1768 $useSubpages = $this->areSubpagesAllowed();
1769 wfProfileOut( __METHOD__
.'-setup' );
1771 # Loop for each link
1772 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1773 # Check for excessive memory usage
1774 if ( $holders->isBig() ) {
1776 # Do the existence check, replace the link holders and clear the array
1777 $holders->replace( $s );
1781 if ( $useLinkPrefixExtension ) {
1782 wfProfileIn( __METHOD__
.'-prefixhandling' );
1783 if ( preg_match( $e2, $s, $m ) ) {
1790 if ( $first_prefix ) {
1791 $prefix = $first_prefix;
1792 $first_prefix = false;
1794 wfProfileOut( __METHOD__
.'-prefixhandling' );
1797 $might_be_img = false;
1799 wfProfileIn( __METHOD__
."-e1" );
1800 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1802 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1803 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1804 # the real problem is with the $e1 regex
1807 # Still some problems for cases where the ] is meant to be outside punctuation,
1808 # and no image is in sight. See bug 2095.
1810 if ( $text !== '' &&
1811 substr( $m[3], 0, 1 ) === ']' &&
1812 strpos( $text, '[' ) !== false
1815 $text .= ']'; # so that replaceExternalLinks($text) works later
1816 $m[3] = substr( $m[3], 1 );
1818 # fix up urlencoded title texts
1819 if ( strpos( $m[1], '%' ) !== false ) {
1820 # Should anchors '#' also be rejected?
1821 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1824 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1825 $might_be_img = true;
1827 if ( strpos( $m[1], '%' ) !== false ) {
1828 $m[1] = rawurldecode( $m[1] );
1831 } else { # Invalid form; output directly
1832 $s .= $prefix . '[[' . $line ;
1833 wfProfileOut( __METHOD__
."-e1" );
1836 wfProfileOut( __METHOD__
."-e1" );
1837 wfProfileIn( __METHOD__
."-misc" );
1839 # Don't allow internal links to pages containing
1840 # PROTO: where PROTO is a valid URL protocol; these
1841 # should be external links.
1842 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1843 $s .= $prefix . '[[' . $line ;
1844 wfProfileOut( __METHOD__
."-misc" );
1848 # Make subpage if necessary
1849 if ( $useSubpages ) {
1850 $link = $this->maybeDoSubpageLink( $m[1], $text );
1855 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1857 # Strip off leading ':'
1858 $link = substr( $link, 1 );
1861 wfProfileOut( __METHOD__
."-misc" );
1862 wfProfileIn( __METHOD__
."-title" );
1863 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1864 if ( $nt === null ) {
1865 $s .= $prefix . '[[' . $line;
1866 wfProfileOut( __METHOD__
."-title" );
1870 $ns = $nt->getNamespace();
1871 $iw = $nt->getInterWiki();
1872 wfProfileOut( __METHOD__
."-title" );
1874 if ( $might_be_img ) { # if this is actually an invalid link
1875 wfProfileIn( __METHOD__
."-might_be_img" );
1876 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1879 # look at the next 'line' to see if we can close it there
1881 $next_line = $a->current();
1882 if ( $next_line === false ||
$next_line === null ) {
1885 $m = explode( ']]', $next_line, 3 );
1886 if ( count( $m ) == 3 ) {
1887 # the first ]] closes the inner link, the second the image
1889 $text .= "[[{$m[0]}]]{$m[1]}";
1892 } elseif ( count( $m ) == 2 ) {
1893 # if there's exactly one ]] that's fine, we'll keep looking
1894 $text .= "[[{$m[0]}]]{$m[1]}";
1896 # if $next_line is invalid too, we need look no further
1897 $text .= '[[' . $next_line;
1902 # we couldn't find the end of this imageLink, so output it raw
1903 # but don't ignore what might be perfectly normal links in the text we've examined
1904 $holders->merge( $this->replaceInternalLinks2( $text ) );
1905 $s .= "{$prefix}[[$link|$text";
1906 # note: no $trail, because without an end, there *is* no trail
1907 wfProfileOut( __METHOD__
."-might_be_img" );
1910 } else { # it's not an image, so output it raw
1911 $s .= "{$prefix}[[$link|$text";
1912 # note: no $trail, because without an end, there *is* no trail
1913 wfProfileOut( __METHOD__
."-might_be_img" );
1916 wfProfileOut( __METHOD__
."-might_be_img" );
1919 $wasblank = ( $text == '' );
1923 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1924 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1925 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1926 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1927 $text = $this->doQuotes( $text );
1930 # Link not escaped by : , create the various objects
1934 wfProfileIn( __METHOD__
."-interwiki" );
1935 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1936 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1937 $s = rtrim( $s . $prefix );
1938 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1939 wfProfileOut( __METHOD__
."-interwiki" );
1942 wfProfileOut( __METHOD__
."-interwiki" );
1944 if ( $ns == NS_FILE
) {
1945 wfProfileIn( __METHOD__
."-image" );
1946 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1948 # if no parameters were passed, $text
1949 # becomes something like "File:Foo.png",
1950 # which we don't want to pass on to the
1954 # recursively parse links inside the image caption
1955 # actually, this will parse them in any other parameters, too,
1956 # but it might be hard to fix that, and it doesn't matter ATM
1957 $text = $this->replaceExternalLinks( $text );
1958 $holders->merge( $this->replaceInternalLinks2( $text ) );
1960 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1961 $s .= $prefix . $this->armorLinks(
1962 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1964 $s .= $prefix . $trail;
1966 wfProfileOut( __METHOD__
."-image" );
1970 if ( $ns == NS_CATEGORY
) {
1971 wfProfileIn( __METHOD__
."-category" );
1972 $s = rtrim( $s . "\n" ); # bug 87
1975 $sortkey = $this->getDefaultSort();
1979 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1980 $sortkey = str_replace( "\n", '', $sortkey );
1981 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1982 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1985 * Strip the whitespace Category links produce, see bug 87
1986 * @todo We might want to use trim($tmp, "\n") here.
1988 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1990 wfProfileOut( __METHOD__
."-category" );
1995 # Self-link checking
1996 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1997 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1998 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2003 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2004 # @todo FIXME: Should do batch file existence checks, see comment below
2005 if ( $ns == NS_MEDIA
) {
2006 wfProfileIn( __METHOD__
."-media" );
2007 # Give extensions a chance to select the file revision for us
2008 $time = $sha1 = $descQuery = false;
2009 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2010 array( $this, $nt, &$time, &$sha1, &$descQuery ) );
2011 # Fetch and register the file (file title may be different via hooks)
2012 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
2013 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2014 $s .= $prefix . $this->armorLinks(
2015 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2016 wfProfileOut( __METHOD__
."-media" );
2020 wfProfileIn( __METHOD__
."-always_known" );
2021 # Some titles, such as valid special pages or files in foreign repos, should
2022 # be shown as bluelinks even though they're not included in the page table
2024 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2025 # batch file existence checks for NS_FILE and NS_MEDIA
2026 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2027 $this->mOutput
->addLink( $nt );
2028 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2030 # Links will be added to the output link list after checking
2031 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2033 wfProfileOut( __METHOD__
."-always_known" );
2035 wfProfileOut( __METHOD__
);
2040 * Render a forced-blue link inline; protect against double expansion of
2041 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2042 * Since this little disaster has to split off the trail text to avoid
2043 * breaking URLs in the following text without breaking trails on the
2044 * wiki links, it's been made into a horrible function.
2047 * @param $text String
2048 * @param $query Array or String
2049 * @param $trail String
2050 * @param $prefix String
2051 * @return String: HTML-wikitext mix oh yuck
2053 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2054 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2056 if ( is_string( $query ) ) {
2057 $query = wfCgiToArray( $query );
2059 if ( $text == '' ) {
2060 $text = htmlspecialchars( $nt->getPrefixedText() );
2063 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2065 return $this->armorLinks( $link ) . $trail;
2069 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2070 * going to go through further parsing steps before inline URL expansion.
2072 * Not needed quite as much as it used to be since free links are a bit
2073 * more sensible these days. But bracketed links are still an issue.
2075 * @param $text String: more-or-less HTML
2076 * @return String: less-or-more HTML with NOPARSE bits
2078 function armorLinks( $text ) {
2079 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2080 "{$this->mUniqPrefix}NOPARSE$1", $text );
2084 * Return true if subpage links should be expanded on this page.
2087 function areSubpagesAllowed() {
2088 # Some namespaces don't allow subpages
2089 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2093 * Handle link to subpage if necessary
2095 * @param $target String: the source of the link
2096 * @param &$text String: the link text, modified as necessary
2097 * @return string the full name of the link
2100 function maybeDoSubpageLink( $target, &$text ) {
2101 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2105 * Used by doBlockLevels()
2110 function closeParagraph() {
2112 if ( $this->mLastSection
!= '' ) {
2113 $result = '</' . $this->mLastSection
. ">\n";
2115 $this->mInPre
= false;
2116 $this->mLastSection
= '';
2121 * getCommon() returns the length of the longest common substring
2122 * of both arguments, starting at the beginning of both.
2125 function getCommon( $st1, $st2 ) {
2126 $fl = strlen( $st1 );
2127 $shorter = strlen( $st2 );
2128 if ( $fl < $shorter ) {
2132 for ( $i = 0; $i < $shorter; ++
$i ) {
2133 if ( $st1[$i] != $st2[$i] ) {
2141 * These next three functions open, continue, and close the list
2142 * element appropriate to the prefix character passed into them.
2147 function openList( $char ) {
2148 $result = $this->closeParagraph();
2150 if ( '*' === $char ) {
2151 $result .= '<ul><li>';
2152 } elseif ( '#' === $char ) {
2153 $result .= '<ol><li>';
2154 } elseif ( ':' === $char ) {
2155 $result .= '<dl><dd>';
2156 } elseif ( ';' === $char ) {
2157 $result .= '<dl><dt>';
2158 $this->mDTopen
= true;
2160 $result = '<!-- ERR 1 -->';
2168 * @param $char String
2173 function nextItem( $char ) {
2174 if ( '*' === $char ||
'#' === $char ) {
2176 } elseif ( ':' === $char ||
';' === $char ) {
2178 if ( $this->mDTopen
) {
2181 if ( ';' === $char ) {
2182 $this->mDTopen
= true;
2183 return $close . '<dt>';
2185 $this->mDTopen
= false;
2186 return $close . '<dd>';
2189 return '<!-- ERR 2 -->';
2194 * @param $char String
2199 function closeList( $char ) {
2200 if ( '*' === $char ) {
2201 $text = '</li></ul>';
2202 } elseif ( '#' === $char ) {
2203 $text = '</li></ol>';
2204 } elseif ( ':' === $char ) {
2205 if ( $this->mDTopen
) {
2206 $this->mDTopen
= false;
2207 $text = '</dt></dl>';
2209 $text = '</dd></dl>';
2212 return '<!-- ERR 3 -->';
2219 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2221 * @param $text String
2222 * @param $linestart Boolean: whether or not this is at the start of a line.
2224 * @return string the lists rendered as HTML
2226 function doBlockLevels( $text, $linestart ) {
2227 wfProfileIn( __METHOD__
);
2229 # Parsing through the text line by line. The main thing
2230 # happening here is handling of block-level elements p, pre,
2231 # and making lists from lines starting with * # : etc.
2233 $textLines = StringUtils
::explode( "\n", $text );
2235 $lastPrefix = $output = '';
2236 $this->mDTopen
= $inBlockElem = false;
2238 $paragraphStack = false;
2240 foreach ( $textLines as $oLine ) {
2242 if ( !$linestart ) {
2252 $lastPrefixLength = strlen( $lastPrefix );
2253 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2254 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2255 # If not in a <pre> element, scan for and figure out what prefixes are there.
2256 if ( !$this->mInPre
) {
2257 # Multiple prefixes may abut each other for nested lists.
2258 $prefixLength = strspn( $oLine, '*#:;' );
2259 $prefix = substr( $oLine, 0, $prefixLength );
2262 # ; and : are both from definition-lists, so they're equivalent
2263 # for the purposes of determining whether or not we need to open/close
2265 $prefix2 = str_replace( ';', ':', $prefix );
2266 $t = substr( $oLine, $prefixLength );
2267 $this->mInPre
= (bool)$preOpenMatch;
2269 # Don't interpret any other prefixes in preformatted text
2271 $prefix = $prefix2 = '';
2276 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2277 # Same as the last item, so no need to deal with nesting or opening stuff
2278 $output .= $this->nextItem( substr( $prefix, -1 ) );
2279 $paragraphStack = false;
2281 if ( substr( $prefix, -1 ) === ';') {
2282 # The one nasty exception: definition lists work like this:
2283 # ; title : definition text
2284 # So we check for : in the remainder text to split up the
2285 # title and definition, without b0rking links.
2287 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2289 $output .= $term . $this->nextItem( ':' );
2292 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2293 # We need to open or close prefixes, or both.
2295 # Either open or close a level...
2296 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2297 $paragraphStack = false;
2299 # Close all the prefixes which aren't shared.
2300 while ( $commonPrefixLength < $lastPrefixLength ) {
2301 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2302 --$lastPrefixLength;
2305 # Continue the current prefix if appropriate.
2306 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2307 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2310 # Open prefixes where appropriate.
2311 while ( $prefixLength > $commonPrefixLength ) {
2312 $char = substr( $prefix, $commonPrefixLength, 1 );
2313 $output .= $this->openList( $char );
2315 if ( ';' === $char ) {
2316 # @todo FIXME: This is dupe of code above
2317 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2319 $output .= $term . $this->nextItem( ':' );
2322 ++
$commonPrefixLength;
2324 $lastPrefix = $prefix2;
2327 # If we have no prefixes, go to paragraph mode.
2328 if ( 0 == $prefixLength ) {
2329 wfProfileIn( __METHOD__
."-paragraph" );
2330 # No prefix (not in list)--go to paragraph mode
2331 # XXX: use a stack for nestable elements like span, table and div
2332 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2333 $closematch = preg_match(
2334 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2335 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2336 if ( $openmatch or $closematch ) {
2337 $paragraphStack = false;
2338 # TODO bug 5718: paragraph closed
2339 $output .= $this->closeParagraph();
2340 if ( $preOpenMatch and !$preCloseMatch ) {
2341 $this->mInPre
= true;
2343 $inBlockElem = !$closematch;
2344 } elseif ( !$inBlockElem && !$this->mInPre
) {
2345 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2347 if ( $this->mLastSection
!== 'pre' ) {
2348 $paragraphStack = false;
2349 $output .= $this->closeParagraph().'<pre>';
2350 $this->mLastSection
= 'pre';
2352 $t = substr( $t, 1 );
2355 if ( trim( $t ) === '' ) {
2356 if ( $paragraphStack ) {
2357 $output .= $paragraphStack.'<br />';
2358 $paragraphStack = false;
2359 $this->mLastSection
= 'p';
2361 if ( $this->mLastSection
!== 'p' ) {
2362 $output .= $this->closeParagraph();
2363 $this->mLastSection
= '';
2364 $paragraphStack = '<p>';
2366 $paragraphStack = '</p><p>';
2370 if ( $paragraphStack ) {
2371 $output .= $paragraphStack;
2372 $paragraphStack = false;
2373 $this->mLastSection
= 'p';
2374 } elseif ( $this->mLastSection
!== 'p' ) {
2375 $output .= $this->closeParagraph().'<p>';
2376 $this->mLastSection
= 'p';
2381 wfProfileOut( __METHOD__
."-paragraph" );
2383 # somewhere above we forget to get out of pre block (bug 785)
2384 if ( $preCloseMatch && $this->mInPre
) {
2385 $this->mInPre
= false;
2387 if ( $paragraphStack === false ) {
2391 while ( $prefixLength ) {
2392 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2395 if ( $this->mLastSection
!= '' ) {
2396 $output .= '</' . $this->mLastSection
. '>';
2397 $this->mLastSection
= '';
2400 wfProfileOut( __METHOD__
);
2405 * Split up a string on ':', ignoring any occurences inside tags
2406 * to prevent illegal overlapping.
2408 * @param $str String: the string to split
2409 * @param &$before String: set to everything before the ':'
2410 * @param &$after String: set to everything after the ':'
2411 * return String: the position of the ':', or false if none found
2413 function findColonNoLinks( $str, &$before, &$after ) {
2414 wfProfileIn( __METHOD__
);
2416 $pos = strpos( $str, ':' );
2417 if ( $pos === false ) {
2419 wfProfileOut( __METHOD__
);
2423 $lt = strpos( $str, '<' );
2424 if ( $lt === false ||
$lt > $pos ) {
2425 # Easy; no tag nesting to worry about
2426 $before = substr( $str, 0, $pos );
2427 $after = substr( $str, $pos+
1 );
2428 wfProfileOut( __METHOD__
);
2432 # Ugly state machine to walk through avoiding tags.
2433 $state = self
::COLON_STATE_TEXT
;
2435 $len = strlen( $str );
2436 for( $i = 0; $i < $len; $i++
) {
2440 # (Using the number is a performance hack for common cases)
2441 case 0: # self::COLON_STATE_TEXT:
2444 # Could be either a <start> tag or an </end> tag
2445 $state = self
::COLON_STATE_TAGSTART
;
2448 if ( $stack == 0 ) {
2450 $before = substr( $str, 0, $i );
2451 $after = substr( $str, $i +
1 );
2452 wfProfileOut( __METHOD__
);
2455 # Embedded in a tag; don't break it.
2458 # Skip ahead looking for something interesting
2459 $colon = strpos( $str, ':', $i );
2460 if ( $colon === false ) {
2461 # Nothing else interesting
2462 wfProfileOut( __METHOD__
);
2465 $lt = strpos( $str, '<', $i );
2466 if ( $stack === 0 ) {
2467 if ( $lt === false ||
$colon < $lt ) {
2469 $before = substr( $str, 0, $colon );
2470 $after = substr( $str, $colon +
1 );
2471 wfProfileOut( __METHOD__
);
2475 if ( $lt === false ) {
2476 # Nothing else interesting to find; abort!
2477 # We're nested, but there's no close tags left. Abort!
2480 # Skip ahead to next tag start
2482 $state = self
::COLON_STATE_TAGSTART
;
2485 case 1: # self::COLON_STATE_TAG:
2490 $state = self
::COLON_STATE_TEXT
;
2493 # Slash may be followed by >?
2494 $state = self
::COLON_STATE_TAGSLASH
;
2500 case 2: # self::COLON_STATE_TAGSTART:
2503 $state = self
::COLON_STATE_CLOSETAG
;
2506 $state = self
::COLON_STATE_COMMENT
;
2509 # Illegal early close? This shouldn't happen D:
2510 $state = self
::COLON_STATE_TEXT
;
2513 $state = self
::COLON_STATE_TAG
;
2516 case 3: # self::COLON_STATE_CLOSETAG:
2521 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2522 wfProfileOut( __METHOD__
);
2525 $state = self
::COLON_STATE_TEXT
;
2528 case self
::COLON_STATE_TAGSLASH
:
2530 # Yes, a self-closed tag <blah/>
2531 $state = self
::COLON_STATE_TEXT
;
2533 # Probably we're jumping the gun, and this is an attribute
2534 $state = self
::COLON_STATE_TAG
;
2537 case 5: # self::COLON_STATE_COMMENT:
2539 $state = self
::COLON_STATE_COMMENTDASH
;
2542 case self
::COLON_STATE_COMMENTDASH
:
2544 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2546 $state = self
::COLON_STATE_COMMENT
;
2549 case self
::COLON_STATE_COMMENTDASHDASH
:
2551 $state = self
::COLON_STATE_TEXT
;
2553 $state = self
::COLON_STATE_COMMENT
;
2557 throw new MWException( "State machine error in " . __METHOD__
);
2561 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2562 wfProfileOut( __METHOD__
);
2565 wfProfileOut( __METHOD__
);
2570 * Return value of a magic variable (like PAGENAME)
2574 * @param $index integer
2575 * @param $frame PPFrame
2577 function getVariableValue( $index, $frame=false ) {
2578 global $wgContLang, $wgSitename, $wgServer;
2579 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2582 * Some of these require message or data lookups and can be
2583 * expensive to check many times.
2585 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2586 if ( isset( $this->mVarCache
[$index] ) ) {
2587 return $this->mVarCache
[$index];
2591 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2592 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2595 global $wgLocaltimezone;
2596 if ( isset( $wgLocaltimezone ) ) {
2597 $oldtz = date_default_timezone_get();
2598 date_default_timezone_set( $wgLocaltimezone );
2601 $localTimestamp = date( 'YmdHis', $ts );
2602 $localMonth = date( 'm', $ts );
2603 $localMonth1 = date( 'n', $ts );
2604 $localMonthName = date( 'n', $ts );
2605 $localDay = date( 'j', $ts );
2606 $localDay2 = date( 'd', $ts );
2607 $localDayOfWeek = date( 'w', $ts );
2608 $localWeek = date( 'W', $ts );
2609 $localYear = date( 'Y', $ts );
2610 $localHour = date( 'H', $ts );
2611 if ( isset( $wgLocaltimezone ) ) {
2612 date_default_timezone_set( $oldtz );
2616 case 'currentmonth':
2617 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2619 case 'currentmonth1':
2620 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2622 case 'currentmonthname':
2623 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2625 case 'currentmonthnamegen':
2626 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2628 case 'currentmonthabbrev':
2629 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2632 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2635 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2638 $value = $wgContLang->formatNum( $localMonth );
2641 $value = $wgContLang->formatNum( $localMonth1 );
2643 case 'localmonthname':
2644 $value = $wgContLang->getMonthName( $localMonthName );
2646 case 'localmonthnamegen':
2647 $value = $wgContLang->getMonthNameGen( $localMonthName );
2649 case 'localmonthabbrev':
2650 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2653 $value = $wgContLang->formatNum( $localDay );
2656 $value = $wgContLang->formatNum( $localDay2 );
2659 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2662 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2664 case 'fullpagename':
2665 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2667 case 'fullpagenamee':
2668 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2671 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2673 case 'subpagenamee':
2674 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2676 case 'basepagename':
2677 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2679 case 'basepagenamee':
2680 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2682 case 'talkpagename':
2683 if ( $this->mTitle
->canTalk() ) {
2684 $talkPage = $this->mTitle
->getTalkPage();
2685 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2690 case 'talkpagenamee':
2691 if ( $this->mTitle
->canTalk() ) {
2692 $talkPage = $this->mTitle
->getTalkPage();
2693 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2698 case 'subjectpagename':
2699 $subjPage = $this->mTitle
->getSubjectPage();
2700 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2702 case 'subjectpagenamee':
2703 $subjPage = $this->mTitle
->getSubjectPage();
2704 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2707 # Let the edit saving system know we should parse the page
2708 # *after* a revision ID has been assigned.
2709 $this->mOutput
->setFlag( 'vary-revision' );
2710 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2711 $value = $this->mRevisionId
;
2714 # Let the edit saving system know we should parse the page
2715 # *after* a revision ID has been assigned. This is for null edits.
2716 $this->mOutput
->setFlag( 'vary-revision' );
2717 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2718 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2720 case 'revisionday2':
2721 # Let the edit saving system know we should parse the page
2722 # *after* a revision ID has been assigned. This is for null edits.
2723 $this->mOutput
->setFlag( 'vary-revision' );
2724 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2725 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2727 case 'revisionmonth':
2728 # Let the edit saving system know we should parse the page
2729 # *after* a revision ID has been assigned. This is for null edits.
2730 $this->mOutput
->setFlag( 'vary-revision' );
2731 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2732 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2734 case 'revisionmonth1':
2735 # Let the edit saving system know we should parse the page
2736 # *after* a revision ID has been assigned. This is for null edits.
2737 $this->mOutput
->setFlag( 'vary-revision' );
2738 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2739 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2741 case 'revisionyear':
2742 # Let the edit saving system know we should parse the page
2743 # *after* a revision ID has been assigned. This is for null edits.
2744 $this->mOutput
->setFlag( 'vary-revision' );
2745 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2746 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2748 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2753 $value = $this->getRevisionTimestamp();
2755 case 'revisionuser':
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__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2760 $value = $this->getRevisionUser();
2763 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2766 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2769 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2772 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2774 case 'subjectspace':
2775 $value = $this->mTitle
->getSubjectNsText();
2777 case 'subjectspacee':
2778 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2780 case 'currentdayname':
2781 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2784 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2787 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2790 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2793 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2794 # int to remove the padding
2795 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2798 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2800 case 'localdayname':
2801 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2804 $value = $wgContLang->formatNum( $localYear, true );
2807 $value = $wgContLang->time( $localTimestamp, false, false );
2810 $value = $wgContLang->formatNum( $localHour, true );
2813 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2814 # int to remove the padding
2815 $value = $wgContLang->formatNum( (int)$localWeek );
2818 $value = $wgContLang->formatNum( $localDayOfWeek );
2820 case 'numberofarticles':
2821 $value = $wgContLang->formatNum( SiteStats
::articles() );
2823 case 'numberoffiles':
2824 $value = $wgContLang->formatNum( SiteStats
::images() );
2826 case 'numberofusers':
2827 $value = $wgContLang->formatNum( SiteStats
::users() );
2829 case 'numberofactiveusers':
2830 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2832 case 'numberofpages':
2833 $value = $wgContLang->formatNum( SiteStats
::pages() );
2835 case 'numberofadmins':
2836 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2838 case 'numberofedits':
2839 $value = $wgContLang->formatNum( SiteStats
::edits() );
2841 case 'numberofviews':
2842 $value = $wgContLang->formatNum( SiteStats
::views() );
2844 case 'currenttimestamp':
2845 $value = wfTimestamp( TS_MW
, $ts );
2847 case 'localtimestamp':
2848 $value = $localTimestamp;
2850 case 'currentversion':
2851 $value = SpecialVersion
::getVersion();
2854 return $wgArticlePath;
2860 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2861 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2862 wfRestoreWarnings();
2863 return $serverName ?
$serverName : $wgServer;
2865 return $wgScriptPath;
2867 return $wgStylePath;
2868 case 'directionmark':
2869 return $wgContLang->getDirMark();
2870 case 'contentlanguage':
2871 global $wgLanguageCode;
2872 return $wgLanguageCode;
2875 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2883 $this->mVarCache
[$index] = $value;
2889 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2893 function initialiseVariables() {
2894 wfProfileIn( __METHOD__
);
2895 $variableIDs = MagicWord
::getVariableIDs();
2896 $substIDs = MagicWord
::getSubstIDs();
2898 $this->mVariables
= new MagicWordArray( $variableIDs );
2899 $this->mSubstWords
= new MagicWordArray( $substIDs );
2900 wfProfileOut( __METHOD__
);
2904 * Preprocess some wikitext and return the document tree.
2905 * This is the ghost of replace_variables().
2907 * @param $text String: The text to parse
2908 * @param $flags Integer: bitwise combination of:
2909 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2910 * included. Default is to assume a direct page view.
2912 * The generated DOM tree must depend only on the input text and the flags.
2913 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2915 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2916 * change in the DOM tree for a given text, must be passed through the section identifier
2917 * in the section edit link and thus back to extractSections().
2919 * The output of this function is currently only cached in process memory, but a persistent
2920 * cache may be implemented at a later date which takes further advantage of these strict
2921 * dependency requirements.
2927 function preprocessToDom( $text, $flags = 0 ) {
2928 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2933 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2937 public static function splitWhitespace( $s ) {
2938 $ltrimmed = ltrim( $s );
2939 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2940 $trimmed = rtrim( $ltrimmed );
2941 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2943 $w2 = substr( $ltrimmed, -$diff );
2947 return array( $w1, $trimmed, $w2 );
2951 * Replace magic variables, templates, and template arguments
2952 * with the appropriate text. Templates are substituted recursively,
2953 * taking care to avoid infinite loops.
2955 * Note that the substitution depends on value of $mOutputType:
2956 * self::OT_WIKI: only {{subst:}} templates
2957 * self::OT_PREPROCESS: templates but not extension tags
2958 * self::OT_HTML: all templates and extension tags
2960 * @param $text String: the text to transform
2961 * @param $frame PPFrame Object describing the arguments passed to the template.
2962 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2963 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2964 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2969 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2970 # Is there any text? Also, Prevent too big inclusions!
2971 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2974 wfProfileIn( __METHOD__
);
2976 if ( $frame === false ) {
2977 $frame = $this->getPreprocessor()->newFrame();
2978 } elseif ( !( $frame instanceof PPFrame
) ) {
2979 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2980 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2983 $dom = $this->preprocessToDom( $text );
2984 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2985 $text = $frame->expand( $dom, $flags );
2987 wfProfileOut( __METHOD__
);
2992 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2996 static function createAssocArgs( $args ) {
2997 $assocArgs = array();
2999 foreach ( $args as $arg ) {
3000 $eqpos = strpos( $arg, '=' );
3001 if ( $eqpos === false ) {
3002 $assocArgs[$index++
] = $arg;
3004 $name = trim( substr( $arg, 0, $eqpos ) );
3005 $value = trim( substr( $arg, $eqpos+
1 ) );
3006 if ( $value === false ) {
3009 if ( $name !== false ) {
3010 $assocArgs[$name] = $value;
3019 * Warn the user when a parser limitation is reached
3020 * Will warn at most once the user per limitation type
3022 * @param $limitationType String: should be one of:
3023 * 'expensive-parserfunction' (corresponding messages:
3024 * 'expensive-parserfunction-warning',
3025 * 'expensive-parserfunction-category')
3026 * 'post-expand-template-argument' (corresponding messages:
3027 * 'post-expand-template-argument-warning',
3028 * 'post-expand-template-argument-category')
3029 * 'post-expand-template-inclusion' (corresponding messages:
3030 * 'post-expand-template-inclusion-warning',
3031 * 'post-expand-template-inclusion-category')
3032 * @param $current Current value
3033 * @param $max Maximum allowed, when an explicit limit has been
3034 * exceeded, provide the values (optional)
3036 function limitationWarn( $limitationType, $current=null, $max=null) {
3037 # does no harm if $current and $max are present but are unnecessary for the message
3038 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3039 $this->mOutput
->addWarning( $warning );
3040 $this->addTrackingCategory( "$limitationType-category" );
3044 * Return the text of a template, after recursively
3045 * replacing any variables or templates within the template.
3047 * @param $piece Array: the parts of the template
3048 * $piece['title']: the title, i.e. the part before the |
3049 * $piece['parts']: the parameter array
3050 * $piece['lineStart']: whether the brace was at the start of a line
3051 * @param $frame PPFrame The current frame, contains template arguments
3052 * @return String: the text of the template
3055 function braceSubstitution( $piece, $frame ) {
3056 global $wgContLang, $wgNonincludableNamespaces;
3057 wfProfileIn( __METHOD__
);
3058 wfProfileIn( __METHOD__
.'-setup' );
3061 $found = false; # $text has been filled
3062 $nowiki = false; # wiki markup in $text should be escaped
3063 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3064 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3065 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3066 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3068 # Title object, where $text came from
3071 # $part1 is the bit before the first |, and must contain only title characters.
3072 # Various prefixes will be stripped from it later.
3073 $titleWithSpaces = $frame->expand( $piece['title'] );
3074 $part1 = trim( $titleWithSpaces );
3077 # Original title text preserved for various purposes
3078 $originalTitle = $part1;
3080 # $args is a list of argument nodes, starting from index 0, not including $part1
3081 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3082 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3083 wfProfileOut( __METHOD__
.'-setup' );
3084 wfProfileIn( __METHOD__
."-title-$originalTitle" );
3087 wfProfileIn( __METHOD__
.'-modifiers' );
3090 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3092 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3093 # Decide whether to expand template or keep wikitext as-is.
3094 if ( $this->ot
['wiki'] ) {
3095 if ( $substMatch === false ) {
3096 $literal = true; # literal when in PST with no prefix
3098 $literal = false; # expand when in PST with subst: or safesubst:
3101 if ( $substMatch == 'subst' ) {
3102 $literal = true; # literal when not in PST with plain subst:
3104 $literal = false; # expand when not in PST with safesubst: or no prefix
3108 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3115 if ( !$found && $args->getLength() == 0 ) {
3116 $id = $this->mVariables
->matchStartToEnd( $part1 );
3117 if ( $id !== false ) {
3118 $text = $this->getVariableValue( $id, $frame );
3119 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3120 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3126 # MSG, MSGNW and RAW
3129 $mwMsgnw = MagicWord
::get( 'msgnw' );
3130 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3133 # Remove obsolete MSG:
3134 $mwMsg = MagicWord
::get( 'msg' );
3135 $mwMsg->matchStartAndRemove( $part1 );
3139 $mwRaw = MagicWord
::get( 'raw' );
3140 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3141 $forceRawInterwiki = true;
3144 wfProfileOut( __METHOD__
.'-modifiers' );
3148 wfProfileIn( __METHOD__
. '-pfunc' );
3150 $colonPos = strpos( $part1, ':' );
3151 if ( $colonPos !== false ) {
3152 # Case sensitive functions
3153 $function = substr( $part1, 0, $colonPos );
3154 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3155 $function = $this->mFunctionSynonyms
[1][$function];
3157 # Case insensitive functions
3158 $function = $wgContLang->lc( $function );
3159 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3160 $function = $this->mFunctionSynonyms
[0][$function];
3166 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3167 $initialArgs = array( &$this );
3168 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3169 if ( $flags & SFH_OBJECT_ARGS
) {
3170 # Add a frame parameter, and pass the arguments as an array
3171 $allArgs = $initialArgs;
3172 $allArgs[] = $frame;
3173 for ( $i = 0; $i < $args->getLength(); $i++
) {
3174 $funcArgs[] = $args->item( $i );
3176 $allArgs[] = $funcArgs;
3178 # Convert arguments to plain text
3179 for ( $i = 0; $i < $args->getLength(); $i++
) {
3180 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3182 $allArgs = array_merge( $initialArgs, $funcArgs );
3185 # Workaround for PHP bug 35229 and similar
3186 if ( !is_callable( $callback ) ) {
3187 wfProfileOut( __METHOD__
. '-pfunc' );
3188 wfProfileOut( __METHOD__
);
3189 throw new MWException( "Tag hook for $function is not callable\n" );
3191 $result = call_user_func_array( $callback, $allArgs );
3194 $preprocessFlags = 0;
3196 if ( is_array( $result ) ) {
3197 if ( isset( $result[0] ) ) {
3199 unset( $result[0] );
3202 # Extract flags into the local scope
3203 # This allows callers to set flags such as nowiki, found, etc.
3209 $text = $this->preprocessToDom( $text, $preprocessFlags );
3214 wfProfileOut( __METHOD__
. '-pfunc' );
3217 # Finish mangling title and then check for loops.
3218 # Set $title to a Title object and $titleText to the PDBK
3221 # Split the title into page and subpage
3223 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3224 if ( $subpage !== '' ) {
3225 $ns = $this->mTitle
->getNamespace();
3227 $title = Title
::newFromText( $part1, $ns );
3229 $titleText = $title->getPrefixedText();
3230 # Check for language variants if the template is not found
3231 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3232 $wgContLang->findVariantLink( $part1, $title, true );
3234 # Do recursion depth check
3235 $limit = $this->mOptions
->getMaxTemplateDepth();
3236 if ( $frame->depth
>= $limit ) {
3238 $text = '<span class="error">'
3239 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3245 # Load from database
3246 if ( !$found && $title ) {
3247 wfProfileIn( __METHOD__
. '-loadtpl' );
3248 if ( !$title->isExternal() ) {
3249 if ( $title->getNamespace() == NS_SPECIAL
3250 && $this->mOptions
->getAllowSpecialInclusion()
3251 && $this->ot
['html'] )
3253 $text = SpecialPageFactory
::capturePath( $title );
3254 if ( is_string( $text ) ) {
3257 $this->disableCache();
3259 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3260 $found = false; # access denied
3261 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3263 list( $text, $title ) = $this->getTemplateDom( $title );
3264 if ( $text !== false ) {
3270 # If the title is valid but undisplayable, make a link to it
3271 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3272 $text = "[[:$titleText]]";
3275 } elseif ( $title->isTrans() ) {
3276 # Interwiki transclusion
3277 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3278 $text = $this->interwikiTransclude( $title, 'render' );
3281 $text = $this->interwikiTransclude( $title, 'raw' );
3282 # Preprocess it like a template
3283 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3289 # Do infinite loop check
3290 # This has to be done after redirect resolution to avoid infinite loops via redirects
3291 if ( !$frame->loopCheck( $title ) ) {
3293 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3294 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3296 wfProfileOut( __METHOD__
. '-loadtpl' );
3299 # If we haven't found text to substitute by now, we're done
3300 # Recover the source wikitext and return it
3302 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3303 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3304 wfProfileOut( __METHOD__
);
3305 return array( 'object' => $text );
3308 # Expand DOM-style return values in a child frame
3309 if ( $isChildObj ) {
3310 # Clean up argument array
3311 $newFrame = $frame->newChild( $args, $title );
3314 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3315 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3316 # Expansion is eligible for the empty-frame cache
3317 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3318 $text = $this->mTplExpandCache
[$titleText];
3320 $text = $newFrame->expand( $text );
3321 $this->mTplExpandCache
[$titleText] = $text;
3324 # Uncached expansion
3325 $text = $newFrame->expand( $text );
3328 if ( $isLocalObj && $nowiki ) {
3329 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3330 $isLocalObj = false;
3333 # Replace raw HTML by a placeholder
3334 # Add a blank line preceding, to prevent it from mucking up
3335 # immediately preceding headings
3337 $text = "\n\n" . $this->insertStripItem( $text );
3338 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3339 # Escape nowiki-style return values
3340 $text = wfEscapeWikiText( $text );
3341 } elseif ( is_string( $text )
3342 && !$piece['lineStart']
3343 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3345 # Bug 529: if the template begins with a table or block-level
3346 # element, it should be treated as beginning a new line.
3347 # This behaviour is somewhat controversial.
3348 $text = "\n" . $text;
3351 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3352 # Error, oversize inclusion
3353 if ( $titleText !== false ) {
3354 # Make a working, properly escaped link if possible (bug 23588)
3355 $text = "[[:$titleText]]";
3357 # This will probably not be a working link, but at least it may
3358 # provide some hint of where the problem is
3359 preg_replace( '/^:/', '', $originalTitle );
3360 $text = "[[:$originalTitle]]";
3362 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3363 $this->limitationWarn( 'post-expand-template-inclusion' );
3366 if ( $isLocalObj ) {
3367 $ret = array( 'object' => $text );
3369 $ret = array( 'text' => $text );
3372 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3373 wfProfileOut( __METHOD__
);
3378 * Get the semi-parsed DOM representation of a template with a given title,
3379 * and its redirect destination title. Cached.
3383 function getTemplateDom( $title ) {
3384 $cacheTitle = $title;
3385 $titleText = $title->getPrefixedDBkey();
3387 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3388 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3389 $title = Title
::makeTitle( $ns, $dbk );
3390 $titleText = $title->getPrefixedDBkey();
3392 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3393 return array( $this->mTplDomCache
[$titleText], $title );
3396 # Cache miss, go to the database
3397 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3399 if ( $text === false ) {
3400 $this->mTplDomCache
[$titleText] = false;
3401 return array( false, $title );
3404 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3405 $this->mTplDomCache
[ $titleText ] = $dom;
3407 if ( !$title->equals( $cacheTitle ) ) {
3408 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3409 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3412 return array( $dom, $title );
3416 * Fetch the unparsed text of a template and register a reference to it.
3417 * @param Title $title
3418 * @return Array ( string or false, Title )
3420 function fetchTemplateAndTitle( $title ) {
3421 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3422 $stuff = call_user_func( $templateCb, $title, $this );
3423 $text = $stuff['text'];
3424 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3425 if ( isset( $stuff['deps'] ) ) {
3426 foreach ( $stuff['deps'] as $dep ) {
3427 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3430 return array( $text, $finalTitle );
3434 * Fetch the unparsed text of a template and register a reference to it.
3435 * @param Title $title
3436 * @return mixed string or false
3438 function fetchTemplate( $title ) {
3439 $rv = $this->fetchTemplateAndTitle( $title );
3444 * Static function to get a template
3445 * Can be overridden via ParserOptions::setTemplateCallback().
3449 static function statelessFetchTemplate( $title, $parser = false ) {
3450 $text = $skip = false;
3451 $finalTitle = $title;
3454 # Loop to fetch the article, with up to 1 redirect
3455 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3456 # Give extensions a chance to select the revision instead
3457 $id = false; # Assume current
3458 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3459 array( $parser, $title, &$skip, &$id ) );
3465 'page_id' => $title->getArticleID(),
3472 ? Revision
::newFromId( $id )
3473 : Revision
::newFromTitle( $title );
3474 $rev_id = $rev ?
$rev->getId() : 0;
3475 # If there is no current revision, there is no page
3476 if ( $id === false && !$rev ) {
3477 $linkCache = LinkCache
::singleton();
3478 $linkCache->addBadLinkObj( $title );
3483 'page_id' => $title->getArticleID(),
3484 'rev_id' => $rev_id );
3485 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3486 # We fetched a rev from a different title; register it too...
3488 'title' => $rev->getTitle(),
3489 'page_id' => $rev->getPage(),
3490 'rev_id' => $rev_id );
3494 $text = $rev->getText();
3495 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3497 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3498 if ( !$message->exists() ) {
3502 $text = $message->plain();
3506 if ( $text === false ) {
3510 $finalTitle = $title;
3511 $title = Title
::newFromRedirect( $text );
3515 'finalTitle' => $finalTitle,
3520 * Fetch a file and its title and register a reference to it.
3521 * @param Title $title
3522 * @param string $time MW timestamp
3523 * @param string $sha1 base 36 SHA-1
3524 * @return mixed File or false
3526 function fetchFile( $title, $time = false, $sha1 = false ) {
3527 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3532 * Fetch a file and its title and register a reference to it.
3533 * @param Title $title
3534 * @param string $time MW timestamp
3535 * @param string $sha1 base 36 SHA-1
3536 * @return Array ( File or false, Title of file )
3538 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3539 if ( $time === '0' ) {
3540 $file = false; // broken thumbnail forced by hook
3541 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3542 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3543 } else { // get by (name,timestamp)
3544 $file = wfFindFile( $title, array( 'time' => $time ) );
3546 $time = $file ?
$file->getTimestamp() : false;
3547 $sha1 = $file ?
$file->getSha1() : false;
3548 # Register the file as a dependency...
3549 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3550 if ( $file && !$title->equals( $file->getTitle() ) ) {
3551 # Update fetched file title
3552 $title = $file->getTitle();
3553 if ( is_null( $file->getRedirectedTitle() ) ) {
3554 # This file was not a redirect, but the title does not match.
3555 # Register under the new name because otherwise the link will
3557 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3560 return array( $file, $title );
3564 * Transclude an interwiki link.
3566 * @param $title Title
3571 function interwikiTransclude( $title, $action ) {
3572 global $wgEnableScaryTranscluding;
3574 if ( !$wgEnableScaryTranscluding ) {
3575 return wfMsgForContent('scarytranscludedisabled');
3578 $url = $title->getFullUrl( "action=$action" );
3580 if ( strlen( $url ) > 255 ) {
3581 return wfMsgForContent( 'scarytranscludetoolong' );
3583 return $this->fetchScaryTemplateMaybeFromCache( $url );
3587 * @param $url string
3588 * @return Mixed|String
3590 function fetchScaryTemplateMaybeFromCache( $url ) {
3591 global $wgTranscludeCacheExpiry;
3592 $dbr = wfGetDB( DB_SLAVE
);
3593 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3594 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3595 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3597 return $obj->tc_contents
;
3600 $text = Http
::get( $url );
3602 return wfMsgForContent( 'scarytranscludefailed', $url );
3605 $dbw = wfGetDB( DB_MASTER
);
3606 $dbw->replace( 'transcache', array('tc_url'), array(
3608 'tc_time' => $dbw->timestamp( time() ),
3609 'tc_contents' => $text)
3615 * Triple brace replacement -- used for template arguments
3618 * @param $peice array
3619 * @param $frame PPFrame
3623 function argSubstitution( $piece, $frame ) {
3624 wfProfileIn( __METHOD__
);
3627 $parts = $piece['parts'];
3628 $nameWithSpaces = $frame->expand( $piece['title'] );
3629 $argName = trim( $nameWithSpaces );
3631 $text = $frame->getArgument( $argName );
3632 if ( $text === false && $parts->getLength() > 0
3636 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3639 # No match in frame, use the supplied default
3640 $object = $parts->item( 0 )->getChildren();
3642 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3643 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3644 $this->limitationWarn( 'post-expand-template-argument' );
3647 if ( $text === false && $object === false ) {
3649 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3651 if ( $error !== false ) {
3654 if ( $object !== false ) {
3655 $ret = array( 'object' => $object );
3657 $ret = array( 'text' => $text );
3660 wfProfileOut( __METHOD__
);
3665 * Return the text to be used for a given extension tag.
3666 * This is the ghost of strip().
3668 * @param $params Associative array of parameters:
3669 * name PPNode for the tag name
3670 * attr PPNode for unparsed text where tag attributes are thought to be
3671 * attributes Optional associative array of parsed attributes
3672 * inner Contents of extension element
3673 * noClose Original text did not have a close tag
3674 * @param $frame PPFrame
3678 function extensionSubstitution( $params, $frame ) {
3679 $name = $frame->expand( $params['name'] );
3680 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3681 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3682 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3684 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3685 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3686 if ( $isFunctionTag ) {
3687 $markerType = 'none';
3689 $markerType = 'general';
3691 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3692 $name = strtolower( $name );
3693 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3694 if ( isset( $params['attributes'] ) ) {
3695 $attributes = $attributes +
$params['attributes'];
3698 if ( isset( $this->mTagHooks
[$name] ) ) {
3699 # Workaround for PHP bug 35229 and similar
3700 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3701 throw new MWException( "Tag hook for $name is not callable\n" );
3703 $output = call_user_func_array( $this->mTagHooks
[$name],
3704 array( $content, $attributes, $this, $frame ) );
3705 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3706 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3707 if ( !is_callable( $callback ) ) {
3708 throw new MWException( "Tag hook for $name is not callable\n" );
3711 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3713 $output = '<span class="error">Invalid tag extension name: ' .
3714 htmlspecialchars( $name ) . '</span>';
3717 if ( is_array( $output ) ) {
3718 # Extract flags to local scope (to override $markerType)
3720 $output = $flags[0];
3725 if ( is_null( $attrText ) ) {
3728 if ( isset( $params['attributes'] ) ) {
3729 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3730 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3731 htmlspecialchars( $attrValue ) . '"';
3734 if ( $content === null ) {
3735 $output = "<$name$attrText/>";
3737 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3738 $output = "<$name$attrText>$content$close";
3742 if ( $markerType === 'none' ) {
3744 } elseif ( $markerType === 'nowiki' ) {
3745 $this->mStripState
->addNoWiki( $marker, $output );
3746 } elseif ( $markerType === 'general' ) {
3747 $this->mStripState
->addGeneral( $marker, $output );
3749 throw new MWException( __METHOD__
.': invalid marker type' );
3755 * Increment an include size counter
3757 * @param $type String: the type of expansion
3758 * @param $size Integer: the size of the text
3759 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3761 function incrementIncludeSize( $type, $size ) {
3762 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3765 $this->mIncludeSizes
[$type] +
= $size;
3771 * Increment the expensive function count
3773 * @return Boolean: false if the limit has been exceeded
3775 function incrementExpensiveFunctionCount() {
3776 global $wgExpensiveParserFunctionLimit;
3777 $this->mExpensiveFunctionCount++
;
3778 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3785 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3786 * Fills $this->mDoubleUnderscores, returns the modified text
3788 function doDoubleUnderscore( $text ) {
3789 wfProfileIn( __METHOD__
);
3791 # The position of __TOC__ needs to be recorded
3792 $mw = MagicWord
::get( 'toc' );
3793 if ( $mw->match( $text ) ) {
3794 $this->mShowToc
= true;
3795 $this->mForceTocPosition
= true;
3797 # Set a placeholder. At the end we'll fill it in with the TOC.
3798 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3800 # Only keep the first one.
3801 $text = $mw->replace( '', $text );
3804 # Now match and remove the rest of them
3805 $mwa = MagicWord
::getDoubleUnderscoreArray();
3806 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3808 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3809 $this->mOutput
->mNoGallery
= true;
3811 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3812 $this->mShowToc
= false;
3814 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3815 $this->addTrackingCategory( 'hidden-category-category' );
3817 # (bug 8068) Allow control over whether robots index a page.
3819 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3820 # is not desirable, the last one on the page should win.
3821 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3822 $this->mOutput
->setIndexPolicy( 'noindex' );
3823 $this->addTrackingCategory( 'noindex-category' );
3825 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3826 $this->mOutput
->setIndexPolicy( 'index' );
3827 $this->addTrackingCategory( 'index-category' );
3830 # Cache all double underscores in the database
3831 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3832 $this->mOutput
->setProperty( $key, '' );
3835 wfProfileOut( __METHOD__
);
3840 * Add a tracking category, getting the title from a system message,
3841 * or print a debug message if the title is invalid.
3843 * @param $msg String: message key
3844 * @return Boolean: whether the addition was successful
3846 protected function addTrackingCategory( $msg ) {
3847 $cat = wfMsgForContent( $msg );
3849 # Allow tracking categories to be disabled by setting them to "-"
3850 if ( $cat === '-' ) {
3854 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3855 if ( $containerCategory ) {
3856 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3859 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3865 * This function accomplishes several tasks:
3866 * 1) Auto-number headings if that option is enabled
3867 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3868 * 3) Add a Table of contents on the top for users who have enabled the option
3869 * 4) Auto-anchor headings
3871 * It loops through all headlines, collects the necessary data, then splits up the
3872 * string and re-inserts the newly formatted headlines.
3874 * @param $text String
3875 * @param $origText String: original, untouched wikitext
3876 * @param $isMain Boolean
3879 function formatHeadings( $text, $origText, $isMain=true ) {
3880 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3882 # Inhibit editsection links if requested in the page
3883 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3886 $showEditLink = $this->mOptions
->getEditSection();
3888 if ( $showEditLink ) {
3889 $this->mOutput
->setEditSectionTokens( true );
3892 # Get all headlines for numbering them and adding funky stuff like [edit]
3893 # links - this is for later, but we need the number of headlines right now
3895 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3897 # if there are fewer than 4 headlines in the article, do not show TOC
3898 # unless it's been explicitly enabled.
3899 $enoughToc = $this->mShowToc
&&
3900 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3902 # Allow user to stipulate that a page should have a "new section"
3903 # link added via __NEWSECTIONLINK__
3904 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3905 $this->mOutput
->setNewSection( true );
3908 # Allow user to remove the "new section"
3909 # link via __NONEWSECTIONLINK__
3910 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3911 $this->mOutput
->hideNewSection( true );
3914 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3915 # override above conditions and always show TOC above first header
3916 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3917 $this->mShowToc
= true;
3925 # Ugh .. the TOC should have neat indentation levels which can be
3926 # passed to the skin functions. These are determined here
3930 $sublevelCount = array();
3931 $levelCount = array();
3936 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3937 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3938 $oldType = $this->mOutputType
;
3939 $this->setOutputType( self
::OT_WIKI
);
3940 $frame = $this->getPreprocessor()->newFrame();
3941 $root = $this->preprocessToDom( $origText );
3942 $node = $root->getFirstChild();
3947 foreach ( $matches[3] as $headline ) {
3948 $isTemplate = false;
3950 $sectionIndex = false;
3952 $markerMatches = array();
3953 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3954 $serial = $markerMatches[1];
3955 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3956 $isTemplate = ( $titleText != $baseTitleText );
3957 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3961 $prevlevel = $level;
3963 $level = $matches[1][$headlineCount];
3965 if ( $level > $prevlevel ) {
3966 # Increase TOC level
3968 $sublevelCount[$toclevel] = 0;
3969 if ( $toclevel<$wgMaxTocLevel ) {
3970 $prevtoclevel = $toclevel;
3971 $toc .= Linker
::tocIndent();
3974 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3975 # Decrease TOC level, find level to jump to
3977 for ( $i = $toclevel; $i > 0; $i-- ) {
3978 if ( $levelCount[$i] == $level ) {
3979 # Found last matching level
3982 } elseif ( $levelCount[$i] < $level ) {
3983 # Found first matching level below current level
3991 if ( $toclevel<$wgMaxTocLevel ) {
3992 if ( $prevtoclevel < $wgMaxTocLevel ) {
3993 # Unindent only if the previous toc level was shown :p
3994 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3995 $prevtoclevel = $toclevel;
3997 $toc .= Linker
::tocLineEnd();
4001 # No change in level, end TOC line
4002 if ( $toclevel<$wgMaxTocLevel ) {
4003 $toc .= Linker
::tocLineEnd();
4007 $levelCount[$toclevel] = $level;
4009 # count number of headlines for each level
4010 @$sublevelCount[$toclevel]++
;
4012 for( $i = 1; $i <= $toclevel; $i++
) {
4013 if ( !empty( $sublevelCount[$i] ) ) {
4017 $numbering .= $this->getFunctionLang()->formatNum( $sublevelCount[$i] );
4022 # The safe header is a version of the header text safe to use for links
4023 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4024 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
4026 # Remove link placeholders by the link text.
4027 # <!--LINK number-->
4029 # link text with suffix
4030 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4032 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4033 $tocline = preg_replace(
4034 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4035 array( '', '<$1>' ),
4038 $tocline = trim( $tocline );
4040 # For the anchor, strip out HTML-y stuff period
4041 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4042 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4044 # Save headline for section edit hint before it's escaped
4045 $headlineHint = $safeHeadline;
4047 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4048 # For reverse compatibility, provide an id that's
4049 # HTML4-compatible, like we used to.
4051 # It may be worth noting, academically, that it's possible for
4052 # the legacy anchor to conflict with a non-legacy headline
4053 # anchor on the page. In this case likely the "correct" thing
4054 # would be to either drop the legacy anchors or make sure
4055 # they're numbered first. However, this would require people
4056 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4057 # manually, so let's not bother worrying about it.
4058 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4059 array( 'noninitial', 'legacy' ) );
4060 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4062 if ( $legacyHeadline == $safeHeadline ) {
4063 # No reason to have both (in fact, we can't)
4064 $legacyHeadline = false;
4067 $legacyHeadline = false;
4068 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4072 # HTML names must be case-insensitively unique (bug 10721).
4073 # This does not apply to Unicode characters per
4074 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4075 # @todo FIXME: We may be changing them depending on the current locale.
4076 $arrayKey = strtolower( $safeHeadline );
4077 if ( $legacyHeadline === false ) {
4078 $legacyArrayKey = false;
4080 $legacyArrayKey = strtolower( $legacyHeadline );
4083 # count how many in assoc. array so we can track dupes in anchors
4084 if ( isset( $refers[$arrayKey] ) ) {
4085 $refers[$arrayKey]++
;
4087 $refers[$arrayKey] = 1;
4089 if ( isset( $refers[$legacyArrayKey] ) ) {
4090 $refers[$legacyArrayKey]++
;
4092 $refers[$legacyArrayKey] = 1;
4095 # Don't number the heading if it is the only one (looks silly)
4096 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4097 # the two are different if the line contains a link
4098 $headline = $numbering . ' ' . $headline;
4101 # Create the anchor for linking from the TOC to the section
4102 $anchor = $safeHeadline;
4103 $legacyAnchor = $legacyHeadline;
4104 if ( $refers[$arrayKey] > 1 ) {
4105 $anchor .= '_' . $refers[$arrayKey];
4107 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4108 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4110 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4111 $toc .= Linker
::tocLine( $anchor, $tocline,
4112 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4115 # Add the section to the section tree
4116 # Find the DOM node for this header
4117 while ( $node && !$isTemplate ) {
4118 if ( $node->getName() === 'h' ) {
4119 $bits = $node->splitHeading();
4120 if ( $bits['i'] == $sectionIndex ) {
4124 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4125 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4126 $node = $node->getNextSibling();
4129 'toclevel' => $toclevel,
4132 'number' => $numbering,
4133 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4134 'fromtitle' => $titleText,
4135 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4136 'anchor' => $anchor,
4139 # give headline the correct <h#> tag
4140 if ( $showEditLink && $sectionIndex !== false ) {
4141 // Output edit section links as markers with styles that can be customized by skins
4142 if ( $isTemplate ) {
4143 # Put a T flag in the section identifier, to indicate to extractSections()
4144 # that sections inside <includeonly> should be counted.
4145 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4147 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4149 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4150 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4151 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4152 // so we don't have to worry about a user trying to input one of these markers directly.
4153 // We use a page and section attribute to stop the language converter from converting these important bits
4154 // of data, but put the headline hint inside a content block because the language converter is supposed to
4155 // be able to convert that piece of data.
4156 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4157 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4158 if ( isset($editlinkArgs[2]) ) {
4159 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4166 $head[$headlineCount] = Linker
::makeHeadline( $level,
4167 $matches['attrib'][$headlineCount], $anchor, $headline,
4168 $editlink, $legacyAnchor );
4173 $this->setOutputType( $oldType );
4175 # Never ever show TOC if no headers
4176 if ( $numVisible < 1 ) {
4181 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4182 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4184 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4185 $this->mOutput
->setTOCHTML( $toc );
4189 $this->mOutput
->setSections( $tocraw );
4192 # split up and insert constructed headlines
4193 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4196 // build an array of document sections
4197 $sections = array();
4198 foreach ( $blocks as $block ) {
4199 // $head is zero-based, sections aren't.
4200 if ( empty( $head[$i - 1] ) ) {
4201 $sections[$i] = $block;
4203 $sections[$i] = $head[$i - 1] . $block;
4207 * Send a hook, one per section.
4208 * The idea here is to be able to make section-level DIVs, but to do so in a
4209 * lower-impact, more correct way than r50769
4212 * $section : the section number
4213 * &$sectionContent : ref to the content of the section
4214 * $showEditLinks : boolean describing whether this section has an edit link
4216 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4221 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4222 // append the TOC at the beginning
4223 // Top anchor now in skin
4224 $sections[0] = $sections[0] . $toc . "\n";
4227 $full .= join( '', $sections );
4229 if ( $this->mForceTocPosition
) {
4230 return str_replace( '<!--MWTOC-->', $toc, $full );
4237 * Transform wiki markup when saving a page by doing \r\n -> \n
4238 * conversion, substitting signatures, {{subst:}} templates, etc.
4240 * @param $text String: the text to transform
4241 * @param $title Title: the Title object for the current article
4242 * @param $user User: the User object describing the current user
4243 * @param $options ParserOptions: parsing options
4244 * @param $clearState Boolean: whether to clear the parser state first
4245 * @return String: the altered wiki markup
4247 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4248 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4249 $this->setUser( $user );
4254 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4255 if( $options->getPreSaveTransform() ) {
4256 $text = $this->pstPass2( $text, $user );
4258 $text = $this->mStripState
->unstripBoth( $text );
4260 $this->setUser( null ); #Reset
4266 * Pre-save transform helper function
4269 function pstPass2( $text, $user ) {
4270 global $wgContLang, $wgLocaltimezone;
4272 # Note: This is the timestamp saved as hardcoded wikitext to
4273 # the database, we use $wgContLang here in order to give
4274 # everyone the same signature and use the default one rather
4275 # than the one selected in each user's preferences.
4276 # (see also bug 12815)
4277 $ts = $this->mOptions
->getTimestamp();
4278 if ( isset( $wgLocaltimezone ) ) {
4279 $tz = $wgLocaltimezone;
4281 $tz = date_default_timezone_get();
4284 $unixts = wfTimestamp( TS_UNIX
, $ts );
4285 $oldtz = date_default_timezone_get();
4286 date_default_timezone_set( $tz );
4287 $ts = date( 'YmdHis', $unixts );
4288 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4290 # Allow translation of timezones through wiki. date() can return
4291 # whatever crap the system uses, localised or not, so we cannot
4292 # ship premade translations.
4293 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4294 $msg = wfMessage( $key )->inContentLanguage();
4295 if ( $msg->exists() ) {
4296 $tzMsg = $msg->text();
4299 date_default_timezone_set( $oldtz );
4301 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4303 # Variable replacement
4304 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4305 $text = $this->replaceVariables( $text );
4307 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4308 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4311 $sigText = $this->getUserSig( $user );
4312 $text = strtr( $text, array(
4314 '~~~~' => "$sigText $d",
4318 # Context links: [[|name]] and [[name (context)|]]
4319 global $wgLegalTitleChars;
4320 $tc = "[$wgLegalTitleChars]";
4321 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4323 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)(\s?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4324 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(\s?($tc+))\\|]]/"; # [[ns:page(context)|]]
4325 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)(\s?\\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4326 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4328 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4329 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4330 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4331 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4333 $t = $this->mTitle
->getText();
4335 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4336 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4337 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4338 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4340 # if there's no context, don't bother duplicating the title
4341 $text = preg_replace( $p2, '[[\\1]]', $text );
4344 # Trim trailing whitespace
4345 $text = rtrim( $text );
4351 * Fetch the user's signature text, if any, and normalize to
4352 * validated, ready-to-insert wikitext.
4353 * If you have pre-fetched the nickname or the fancySig option, you can
4354 * specify them here to save a database query.
4355 * Do not reuse this parser instance after calling getUserSig(),
4356 * as it may have changed if it's the $wgParser.
4359 * @param $nickname String: nickname to use or false to use user's default nickname
4360 * @param $fancySig Boolean: whether the nicknname is the complete signature
4361 * or null to use default value
4364 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4365 global $wgMaxSigChars;
4367 $username = $user->getName();
4369 # If not given, retrieve from the user object.
4370 if ( $nickname === false )
4371 $nickname = $user->getOption( 'nickname' );
4373 if ( is_null( $fancySig ) ) {
4374 $fancySig = $user->getBoolOption( 'fancysig' );
4377 $nickname = $nickname == null ?
$username : $nickname;
4379 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4380 $nickname = $username;
4381 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4382 } elseif ( $fancySig !== false ) {
4383 # Sig. might contain markup; validate this
4384 if ( $this->validateSig( $nickname ) !== false ) {
4385 # Validated; clean up (if needed) and return it
4386 return $this->cleanSig( $nickname, true );
4388 # Failed to validate; fall back to the default
4389 $nickname = $username;
4390 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4394 # Make sure nickname doesnt get a sig in a sig
4395 $nickname = $this->cleanSigInSig( $nickname );
4397 # If we're still here, make it a link to the user page
4398 $userText = wfEscapeWikiText( $username );
4399 $nickText = wfEscapeWikiText( $nickname );
4400 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4402 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4406 * Check that the user's signature contains no bad XML
4408 * @param $text String
4409 * @return mixed An expanded string, or false if invalid.
4411 function validateSig( $text ) {
4412 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4416 * Clean up signature text
4418 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4419 * 2) Substitute all transclusions
4421 * @param $text String
4422 * @param $parsing Whether we're cleaning (preferences save) or parsing
4423 * @return String: signature text
4425 function cleanSig( $text, $parsing = false ) {
4428 $this->mOptions
= new ParserOptions
;
4429 $this->clearState();
4430 $this->setTitle( $wgTitle );
4431 $this->setOutputType
= self
::OT_PREPROCESS
;
4434 # Option to disable this feature
4435 if ( !$this->mOptions
->getCleanSignatures() ) {
4439 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4440 # => Move this logic to braceSubstitution()
4441 $substWord = MagicWord
::get( 'subst' );
4442 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4443 $substText = '{{' . $substWord->getSynonym( 0 );
4445 $text = preg_replace( $substRegex, $substText, $text );
4446 $text = $this->cleanSigInSig( $text );
4447 $dom = $this->preprocessToDom( $text );
4448 $frame = $this->getPreprocessor()->newFrame();
4449 $text = $frame->expand( $dom );
4452 $text = $this->mStripState
->unstripBoth( $text );
4459 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4461 * @param $text String
4462 * @return String: signature text with /~{3,5}/ removed
4464 function cleanSigInSig( $text ) {
4465 $text = preg_replace( '/~{3,5}/', '', $text );
4470 * Set up some variables which are usually set up in parse()
4471 * so that an external function can call some class members with confidence
4473 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4474 $this->startParse( $title, $options, $outputType, $clearState );
4477 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4478 $this->setTitle( $title );
4479 $this->mOptions
= $options;
4480 $this->setOutputType( $outputType );
4481 if ( $clearState ) {
4482 $this->clearState();
4487 * Wrapper for preprocess()
4489 * @param $text String: the text to preprocess
4490 * @param $options ParserOptions: options
4491 * @param $title Title object or null to use $wgTitle
4494 public function transformMsg( $text, $options, $title = null ) {
4495 static $executing = false;
4497 # Guard against infinite recursion
4503 wfProfileIn( __METHOD__
);
4509 # It's not uncommon having a null $wgTitle in scripts. See r80898
4510 # Create a ghost title in such case
4511 $title = Title
::newFromText( 'Dwimmerlaik' );
4513 $text = $this->preprocess( $text, $title, $options );
4516 wfProfileOut( __METHOD__
);
4521 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4522 * The callback should have the following form:
4523 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4525 * Transform and return $text. Use $parser for any required context, e.g. use
4526 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4528 * Hooks may return extended information by returning an array, of which the
4529 * first numbered element (index 0) must be the return string, and all other
4530 * entries are extracted into local variables within an internal function
4531 * in the Parser class.
4533 * This interface (introduced r61913) appears to be undocumented, but
4534 * 'markerName' is used by some core tag hooks to override which strip
4535 * array their results are placed in. **Use great caution if attempting
4536 * this interface, as it is not documented and injudicious use could smash
4537 * private variables.**
4539 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4540 * @param $callback Mixed: the callback function (and object) to use for the tag
4541 * @return The old value of the mTagHooks array associated with the hook
4543 public function setHook( $tag, $callback ) {
4544 $tag = strtolower( $tag );
4545 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4546 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4547 $this->mTagHooks
[$tag] = $callback;
4548 if ( !in_array( $tag, $this->mStripList
) ) {
4549 $this->mStripList
[] = $tag;
4556 * As setHook(), but letting the contents be parsed.
4558 * Transparent tag hooks are like regular XML-style tag hooks, except they
4559 * operate late in the transformation sequence, on HTML instead of wikitext.
4561 * This is probably obsoleted by things dealing with parser frames?
4562 * The only extension currently using it is geoserver.
4565 * @todo better document or deprecate this
4567 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4568 * @param $callback Mixed: the callback function (and object) to use for the tag
4569 * @return The old value of the mTagHooks array associated with the hook
4571 function setTransparentTagHook( $tag, $callback ) {
4572 $tag = strtolower( $tag );
4573 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4574 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4575 $this->mTransparentTagHooks
[$tag] = $callback;
4581 * Remove all tag hooks
4583 function clearTagHooks() {
4584 $this->mTagHooks
= array();
4585 $this->mStripList
= $this->mDefaultStripList
;
4589 * Remove a specific tag hook. Should not be called on $wgParser.
4590 * Does not change the strip list.
4592 * @param string $tag
4595 function clearTagHook( $tag ) {
4596 if ( isset( $this->mTagHooks
[$tag] ) ) {
4597 unset( $this->mTagHooks
[$tag] );
4602 * Create a function, e.g. {{sum:1|2|3}}
4603 * The callback function should have the form:
4604 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4606 * Or with SFH_OBJECT_ARGS:
4607 * function myParserFunction( $parser, $frame, $args ) { ... }
4609 * The callback may either return the text result of the function, or an array with the text
4610 * in element 0, and a number of flags in the other elements. The names of the flags are
4611 * specified in the keys. Valid flags are:
4612 * found The text returned is valid, stop processing the template. This
4614 * nowiki Wiki markup in the return value should be escaped
4615 * isHTML The returned text is HTML, armour it against wikitext transformation
4617 * @param $id String: The magic word ID
4618 * @param $callback Mixed: the callback function (and object) to use
4619 * @param $flags Integer: a combination of the following flags:
4620 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4622 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4623 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4624 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4625 * the arguments, and to control the way they are expanded.
4627 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4628 * arguments, for instance:
4629 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4631 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4632 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4633 * working if/when this is changed.
4635 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4638 * Please read the documentation in includes/parser/Preprocessor.php for more information
4639 * about the methods available in PPFrame and PPNode.
4641 * @return The old callback function for this name, if any
4643 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4646 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4647 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4649 # Add to function cache
4650 $mw = MagicWord
::get( $id );
4652 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4654 $synonyms = $mw->getSynonyms();
4655 $sensitive = intval( $mw->isCaseSensitive() );
4657 foreach ( $synonyms as $syn ) {
4659 if ( !$sensitive ) {
4660 $syn = $wgContLang->lc( $syn );
4663 if ( !( $flags & SFH_NO_HASH
) ) {
4666 # Remove trailing colon
4667 if ( substr( $syn, -1, 1 ) === ':' ) {
4668 $syn = substr( $syn, 0, -1 );
4670 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4676 * Get all registered function hook identifiers
4680 function getFunctionHooks() {
4681 return array_keys( $this->mFunctionHooks
);
4685 * Create a tag function, e.g. <test>some stuff</test>.
4686 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4687 * Unlike parser functions, their content is not preprocessed.
4689 function setFunctionTagHook( $tag, $callback, $flags ) {
4690 $tag = strtolower( $tag );
4691 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4692 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4693 $this->mFunctionTagHooks
[$tag] : null;
4694 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4696 if ( !in_array( $tag, $this->mStripList
) ) {
4697 $this->mStripList
[] = $tag;
4704 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4705 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4706 * Placeholders created in Skin::makeLinkObj()
4707 * Returns an array of link CSS classes, indexed by PDBK.
4709 function replaceLinkHolders( &$text, $options = 0 ) {
4710 return $this->mLinkHolders
->replace( $text );
4714 * Replace <!--LINK--> link placeholders with plain text of links
4715 * (not HTML-formatted).
4717 * @param $text String
4720 function replaceLinkHoldersText( $text ) {
4721 return $this->mLinkHolders
->replaceText( $text );
4725 * Renders an image gallery from a text with one line per image.
4726 * text labels may be given by using |-style alternative text. E.g.
4727 * Image:one.jpg|The number "1"
4728 * Image:tree.jpg|A tree
4729 * given as text will return the HTML of a gallery with two images,
4730 * labeled 'The number "1"' and
4733 * @param string $text
4734 * @param array $param
4735 * @return string HTML
4737 function renderImageGallery( $text, $params ) {
4738 $ig = new ImageGallery();
4739 $ig->setContextTitle( $this->mTitle
);
4740 $ig->setShowBytes( false );
4741 $ig->setShowFilename( false );
4742 $ig->setParser( $this );
4743 $ig->setHideBadImages();
4744 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4746 if ( isset( $params['showfilename'] ) ) {
4747 $ig->setShowFilename( true );
4749 $ig->setShowFilename( false );
4751 if ( isset( $params['caption'] ) ) {
4752 $caption = $params['caption'];
4753 $caption = htmlspecialchars( $caption );
4754 $caption = $this->replaceInternalLinks( $caption );
4755 $ig->setCaptionHtml( $caption );
4757 if ( isset( $params['perrow'] ) ) {
4758 $ig->setPerRow( $params['perrow'] );
4760 if ( isset( $params['widths'] ) ) {
4761 $ig->setWidths( $params['widths'] );
4763 if ( isset( $params['heights'] ) ) {
4764 $ig->setHeights( $params['heights'] );
4767 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4769 $lines = StringUtils
::explode( "\n", $text );
4770 foreach ( $lines as $line ) {
4771 # match lines like these:
4772 # Image:someimage.jpg|This is some image
4774 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4776 if ( count( $matches ) == 0 ) {
4780 if ( strpos( $matches[0], '%' ) !== false ) {
4781 $matches[1] = rawurldecode( $matches[1] );
4783 $title = Title
::newFromText( $matches[1], NS_FILE
);
4784 if ( is_null( $title ) ) {
4785 # Bogus title. Ignore these so we don't bomb out later.
4791 if ( isset( $matches[3] ) ) {
4792 // look for an |alt= definition while trying not to break existing
4793 // captions with multiple pipes (|) in it, until a more sensible grammar
4794 // is defined for images in galleries
4796 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4797 $altmatches = StringUtils
::explode('|', $matches[3]);
4798 $magicWordAlt = MagicWord
::get( 'img_alt' );
4800 foreach ( $altmatches as $altmatch ) {
4801 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4803 $alt = $this->stripAltText( $match, false );
4806 // concatenate all other pipes
4807 $label .= '|' . $altmatch;
4810 // remove the first pipe
4811 $label = substr( $label, 1 );
4814 $ig->add( $title, $label, $alt );
4816 return $ig->toHTML();
4819 function getImageParams( $handler ) {
4821 $handlerClass = get_class( $handler );
4825 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4826 # Initialise static lists
4827 static $internalParamNames = array(
4828 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4829 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4830 'bottom', 'text-bottom' ),
4831 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4832 'upright', 'border', 'link', 'alt' ),
4834 static $internalParamMap;
4835 if ( !$internalParamMap ) {
4836 $internalParamMap = array();
4837 foreach ( $internalParamNames as $type => $names ) {
4838 foreach ( $names as $name ) {
4839 $magicName = str_replace( '-', '_', "img_$name" );
4840 $internalParamMap[$magicName] = array( $type, $name );
4845 # Add handler params
4846 $paramMap = $internalParamMap;
4848 $handlerParamMap = $handler->getParamMap();
4849 foreach ( $handlerParamMap as $magic => $paramName ) {
4850 $paramMap[$magic] = array( 'handler', $paramName );
4853 $this->mImageParams
[$handlerClass] = $paramMap;
4854 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4856 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4860 * Parse image options text and use it to make an image
4862 * @param $title Title
4863 * @param $options String
4864 * @param $holders LinkHolderArray
4865 * @return string HTML
4867 function makeImage( $title, $options, $holders = false ) {
4868 # Check if the options text is of the form "options|alt text"
4870 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4871 # * left no resizing, just left align. label is used for alt= only
4872 # * right same, but right aligned
4873 # * none same, but not aligned
4874 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4875 # * center center the image
4876 # * frame Keep original image size, no magnify-button.
4877 # * framed Same as "frame"
4878 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4879 # * upright reduce width for upright images, rounded to full __0 px
4880 # * border draw a 1px border around the image
4881 # * alt Text for HTML alt attribute (defaults to empty)
4882 # * link Set the target of the image link. Can be external, interwiki, or local
4883 # vertical-align values (no % or length right now):
4893 $parts = StringUtils
::explode( "|", $options );
4895 # Give extensions a chance to select the file revision for us
4896 $time = $sha1 = $descQuery = false;
4897 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4898 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4899 # Fetch and register the file (file title may be different via hooks)
4900 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4903 $handler = $file ?
$file->getHandler() : false;
4905 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4908 $this->addTrackingCategory( 'broken-file-category' );
4911 # Process the input parameters
4913 $params = array( 'frame' => array(), 'handler' => array(),
4914 'horizAlign' => array(), 'vertAlign' => array() );
4915 foreach ( $parts as $part ) {
4916 $part = trim( $part );
4917 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4919 if ( isset( $paramMap[$magicName] ) ) {
4920 list( $type, $paramName ) = $paramMap[$magicName];
4922 # Special case; width and height come in one variable together
4923 if ( $type === 'handler' && $paramName === 'width' ) {
4925 # (bug 13500) In both cases (width/height and width only),
4926 # permit trailing "px" for backward compatibility.
4927 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4928 $width = intval( $m[1] );
4929 $height = intval( $m[2] );
4930 if ( $handler->validateParam( 'width', $width ) ) {
4931 $params[$type]['width'] = $width;
4934 if ( $handler->validateParam( 'height', $height ) ) {
4935 $params[$type]['height'] = $height;
4938 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4939 $width = intval( $value );
4940 if ( $handler->validateParam( 'width', $width ) ) {
4941 $params[$type]['width'] = $width;
4944 } # else no validation -- bug 13436
4946 if ( $type === 'handler' ) {
4947 # Validate handler parameter
4948 $validated = $handler->validateParam( $paramName, $value );
4950 # Validate internal parameters
4951 switch( $paramName ) {
4954 # @todo FIXME: Possibly check validity here for
4955 # manualthumb? downstream behavior seems odd with
4956 # missing manual thumbs.
4958 $value = $this->stripAltText( $value, $holders );
4961 $chars = self
::EXT_LINK_URL_CLASS
;
4962 $prots = $this->mUrlProtocols
;
4963 if ( $value === '' ) {
4964 $paramName = 'no-link';
4967 } elseif ( preg_match( "/^$prots/", $value ) ) {
4968 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
4969 $paramName = 'link-url';
4970 $this->mOutput
->addExternalLink( $value );
4971 if ( $this->mOptions
->getExternalLinkTarget() ) {
4972 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4977 $linkTitle = Title
::newFromText( $value );
4979 $paramName = 'link-title';
4980 $value = $linkTitle;
4981 $this->mOutput
->addLink( $linkTitle );
4987 # Most other things appear to be empty or numeric...
4988 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4993 $params[$type][$paramName] = $value;
4997 if ( !$validated ) {
5002 # Process alignment parameters
5003 if ( $params['horizAlign'] ) {
5004 $params['frame']['align'] = key( $params['horizAlign'] );
5006 if ( $params['vertAlign'] ) {
5007 $params['frame']['valign'] = key( $params['vertAlign'] );
5010 $params['frame']['caption'] = $caption;
5012 # Will the image be presented in a frame, with the caption below?
5013 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5014 isset( $params['frame']['framed'] ) ||
5015 isset( $params['frame']['thumbnail'] ) ||
5016 isset( $params['frame']['manualthumb'] );
5018 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5019 # came to also set the caption, ordinary text after the image -- which
5020 # makes no sense, because that just repeats the text multiple times in
5021 # screen readers. It *also* came to set the title attribute.
5023 # Now that we have an alt attribute, we should not set the alt text to
5024 # equal the caption: that's worse than useless, it just repeats the
5025 # text. This is the framed/thumbnail case. If there's no caption, we
5026 # use the unnamed parameter for alt text as well, just for the time be-
5027 # ing, if the unnamed param is set and the alt param is not.
5029 # For the future, we need to figure out if we want to tweak this more,
5030 # e.g., introducing a title= parameter for the title; ignoring the un-
5031 # named parameter entirely for images without a caption; adding an ex-
5032 # plicit caption= parameter and preserving the old magic unnamed para-
5034 if ( $imageIsFramed ) { # Framed image
5035 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5036 # No caption or alt text, add the filename as the alt text so
5037 # that screen readers at least get some description of the image
5038 $params['frame']['alt'] = $title->getText();
5040 # Do not set $params['frame']['title'] because tooltips don't make sense
5042 } else { # Inline image
5043 if ( !isset( $params['frame']['alt'] ) ) {
5044 # No alt text, use the "caption" for the alt text
5045 if ( $caption !== '') {
5046 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5048 # No caption, fall back to using the filename for the
5050 $params['frame']['alt'] = $title->getText();
5053 # Use the "caption" for the tooltip text
5054 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5057 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5059 # Linker does the rest
5060 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5061 $time, $descQuery, $this->mOptions
->getThumbSize() );
5063 # Give the handler a chance to modify the parser object
5065 $handler->parserTransformHook( $this, $file );
5073 * @param $holders LinkHolderArray
5074 * @return mixed|String
5076 protected function stripAltText( $caption, $holders ) {
5077 # Strip bad stuff out of the title (tooltip). We can't just use
5078 # replaceLinkHoldersText() here, because if this function is called
5079 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5081 $tooltip = $holders->replaceText( $caption );
5083 $tooltip = $this->replaceLinkHoldersText( $caption );
5086 # make sure there are no placeholders in thumbnail attributes
5087 # that are later expanded to html- so expand them now and
5089 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5090 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5096 * Set a flag in the output object indicating that the content is dynamic and
5097 * shouldn't be cached.
5099 function disableCache() {
5100 wfDebug( "Parser output marked as uncacheable.\n" );
5101 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5102 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5106 * Callback from the Sanitizer for expanding items found in HTML attribute
5107 * values, so they can be safely tested and escaped.
5109 * @param $text String
5110 * @param $frame PPFrame
5113 function attributeStripCallback( &$text, $frame = false ) {
5114 $text = $this->replaceVariables( $text, $frame );
5115 $text = $this->mStripState
->unstripBoth( $text );
5124 function getTags() {
5125 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5129 * Replace transparent tags in $text with the values given by the callbacks.
5131 * Transparent tag hooks are like regular XML-style tag hooks, except they
5132 * operate late in the transformation sequence, on HTML instead of wikitext.
5134 * @param $text string
5138 function replaceTransparentTags( $text ) {
5140 $elements = array_keys( $this->mTransparentTagHooks
);
5141 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5142 $replacements = array();
5144 foreach ( $matches as $marker => $data ) {
5145 list( $element, $content, $params, $tag ) = $data;
5146 $tagName = strtolower( $element );
5147 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5148 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5152 $replacements[$marker] = $output;
5154 return strtr( $text, $replacements );
5158 * Break wikitext input into sections, and either pull or replace
5159 * some particular section's text.
5161 * External callers should use the getSection and replaceSection methods.
5163 * @param $text String: Page wikitext
5164 * @param $section String: a section identifier string of the form:
5165 * <flag1> - <flag2> - ... - <section number>
5167 * Currently the only recognised flag is "T", which means the target section number
5168 * was derived during a template inclusion parse, in other words this is a template
5169 * section edit link. If no flags are given, it was an ordinary section edit link.
5170 * This flag is required to avoid a section numbering mismatch when a section is
5171 * enclosed by <includeonly> (bug 6563).
5173 * The section number 0 pulls the text before the first heading; other numbers will
5174 * pull the given section along with its lower-level subsections. If the section is
5175 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5177 * @param $mode String: one of "get" or "replace"
5178 * @param $newText String: replacement text for section data.
5179 * @return String: for "get", the extracted section text.
5180 * for "replace", the whole page with the section replaced.
5181 * If the page is empty and section 0 is requested, $text (as '')
5184 private function extractSections( $text, $section, $mode, $newText='' ) {
5185 global $wgTitle; # not generally used but removes an ugly failure mode
5186 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5188 $frame = $this->getPreprocessor()->newFrame();
5190 # Process section extraction flags
5192 $sectionParts = explode( '-', $section );
5193 $sectionIndex = array_pop( $sectionParts );
5194 foreach ( $sectionParts as $part ) {
5195 if ( $part === 'T' ) {
5196 $flags |
= self
::PTD_FOR_INCLUSION
;
5199 # Preprocess the text
5200 $root = $this->preprocessToDom( $text, $flags );
5202 # <h> nodes indicate section breaks
5203 # They can only occur at the top level, so we can find them by iterating the root's children
5204 $node = $root->getFirstChild();
5206 # Find the target section
5207 if ( $sectionIndex == 0 ) {
5208 # Section zero doesn't nest, level=big
5209 $targetLevel = 1000;
5211 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5216 if ( $node->getName() === 'h' ) {
5217 $bits = $node->splitHeading();
5218 if ( $bits['i'] == $sectionIndex ) {
5219 $targetLevel = $bits['level'];
5223 if ( $mode === 'replace' ) {
5224 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5226 $node = $node->getNextSibling();
5232 if ( $mode === 'get' ) {
5239 # Find the end of the section, including nested sections
5241 if ( $node->getName() === 'h' ) {
5242 $bits = $node->splitHeading();
5243 $curLevel = $bits['level'];
5244 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5248 if ( $mode === 'get' ) {
5249 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5251 $node = $node->getNextSibling();
5254 # Write out the remainder (in replace mode only)
5255 if ( $mode === 'replace' ) {
5256 # Output the replacement text
5257 # Add two newlines on -- trailing whitespace in $newText is conventionally
5258 # stripped by the editor, so we need both newlines to restore the paragraph gap
5259 # Only add trailing whitespace if there is newText
5260 if ( $newText != "" ) {
5261 $outText .= $newText . "\n\n";
5265 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5266 $node = $node->getNextSibling();
5270 if ( is_string( $outText ) ) {
5271 # Re-insert stripped tags
5272 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5279 * This function returns the text of a section, specified by a number ($section).
5280 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5281 * the first section before any such heading (section 0).
5283 * If a section contains subsections, these are also returned.
5285 * @param $text String: text to look in
5286 * @param $section String: section identifier
5287 * @param $deftext String: default to return if section is not found
5288 * @return string text of the requested section
5290 public function getSection( $text, $section, $deftext='' ) {
5291 return $this->extractSections( $text, $section, "get", $deftext );
5295 * This function returns $oldtext after the content of the section
5296 * specified by $section has been replaced with $text.
5298 * @param $oldtext String: former text of the article
5299 * @param $section Numeric: section identifier
5300 * @param $text String: replacing text
5301 * @return String: modified text
5303 public function replaceSection( $oldtext, $section, $text ) {
5304 return $this->extractSections( $oldtext, $section, "replace", $text );
5308 * Get the ID of the revision we are parsing
5310 * @return Mixed: integer or null
5312 function getRevisionId() {
5313 return $this->mRevisionId
;
5317 * Get the revision object for $this->mRevisionId
5319 * @return Revision|null either a Revision object or null
5321 protected function getRevisionObject() {
5322 if ( !is_null( $this->mRevisionObject
) ) {
5323 return $this->mRevisionObject
;
5325 if ( is_null( $this->mRevisionId
) ) {
5329 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5330 return $this->mRevisionObject
;
5334 * Get the timestamp associated with the current revision, adjusted for
5335 * the default server-local timestamp
5337 function getRevisionTimestamp() {
5338 if ( is_null( $this->mRevisionTimestamp
) ) {
5339 wfProfileIn( __METHOD__
);
5341 $revObject = $this->getRevisionObject();
5342 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5344 if( $timestamp !== false ) {
5347 # The cryptic '' timezone parameter tells to use the site-default
5348 # timezone offset instead of the user settings.
5350 # Since this value will be saved into the parser cache, served
5351 # to other users, and potentially even used inside links and such,
5352 # it needs to be consistent for all visitors.
5353 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5356 wfProfileOut( __METHOD__
);
5358 return $this->mRevisionTimestamp
;
5362 * Get the name of the user that edited the last revision
5364 * @return String: user name
5366 function getRevisionUser() {
5367 if( is_null( $this->mRevisionUser
) ) {
5368 $revObject = $this->getRevisionObject();
5370 # if this template is subst: the revision id will be blank,
5371 # so just use the current user's name
5373 $this->mRevisionUser
= $revObject->getUserText();
5374 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5375 $this->mRevisionUser
= $this->getUser()->getName();
5378 return $this->mRevisionUser
;
5382 * Mutator for $mDefaultSort
5384 * @param $sort New value
5386 public function setDefaultSort( $sort ) {
5387 $this->mDefaultSort
= $sort;
5388 $this->mOutput
->setProperty( 'defaultsort', $sort );
5392 * Accessor for $mDefaultSort
5393 * Will use the empty string if none is set.
5395 * This value is treated as a prefix, so the
5396 * empty string is equivalent to sorting by
5401 public function getDefaultSort() {
5402 if ( $this->mDefaultSort
!== false ) {
5403 return $this->mDefaultSort
;
5410 * Accessor for $mDefaultSort
5411 * Unlike getDefaultSort(), will return false if none is set
5413 * @return string or false
5415 public function getCustomDefaultSort() {
5416 return $this->mDefaultSort
;
5420 * Try to guess the section anchor name based on a wikitext fragment
5421 * presumably extracted from a heading, for example "Header" from
5424 * @param $text string
5428 public function guessSectionNameFromWikiText( $text ) {
5429 # Strip out wikitext links(they break the anchor)
5430 $text = $this->stripSectionName( $text );
5431 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5432 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5436 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5437 * instead. For use in redirects, since IE6 interprets Redirect: headers
5438 * as something other than UTF-8 (apparently?), resulting in breakage.
5440 * @param $text String: The section name
5441 * @return string An anchor
5443 public function guessLegacySectionNameFromWikiText( $text ) {
5444 # Strip out wikitext links(they break the anchor)
5445 $text = $this->stripSectionName( $text );
5446 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5447 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5451 * Strips a text string of wikitext for use in a section anchor
5453 * Accepts a text string and then removes all wikitext from the
5454 * string and leaves only the resultant text (i.e. the result of
5455 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5456 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5457 * to create valid section anchors by mimicing the output of the
5458 * parser when headings are parsed.
5460 * @param $text String: text string to be stripped of wikitext
5461 * for use in a Section anchor
5462 * @return Filtered text string
5464 public function stripSectionName( $text ) {
5465 # Strip internal link markup
5466 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5467 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5469 # Strip external link markup
5470 # @todo FIXME: Not tolerant to blank link text
5471 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5472 # on how many empty links there are on the page - need to figure that out.
5473 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5475 # Parse wikitext quotes (italics & bold)
5476 $text = $this->doQuotes( $text );
5479 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5484 * strip/replaceVariables/unstrip for preprocessor regression testing
5488 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5489 $this->startParse( $title, $options, $outputType, true );
5491 $text = $this->replaceVariables( $text );
5492 $text = $this->mStripState
->unstripBoth( $text );
5493 $text = Sanitizer
::removeHTMLtags( $text );
5497 function testPst( $text, Title
$title, ParserOptions
$options ) {
5498 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5501 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5502 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5506 * Call a callback function on all regions of the given text that are not
5507 * inside strip markers, and replace those regions with the return value
5508 * of the callback. For example, with input:
5512 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5513 * two strings will be replaced with the value returned by the callback in
5518 function markerSkipCallback( $s, $callback ) {
5521 while ( $i < strlen( $s ) ) {
5522 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5523 if ( $markerStart === false ) {
5524 $out .= call_user_func( $callback, substr( $s, $i ) );
5527 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5528 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5529 if ( $markerEnd === false ) {
5530 $out .= substr( $s, $markerStart );
5533 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5534 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5543 * Save the parser state required to convert the given half-parsed text to
5544 * HTML. "Half-parsed" in this context means the output of
5545 * recursiveTagParse() or internalParse(). This output has strip markers
5546 * from replaceVariables (extensionSubstitution() etc.), and link
5547 * placeholders from replaceLinkHolders().
5549 * Returns an array which can be serialized and stored persistently. This
5550 * array can later be loaded into another parser instance with
5551 * unserializeHalfParsedText(). The text can then be safely incorporated into
5552 * the return value of a parser hook.
5556 function serializeHalfParsedText( $text ) {
5557 wfProfileIn( __METHOD__
);
5560 'version' => self
::HALF_PARSED_VERSION
,
5561 'stripState' => $this->mStripState
->getSubState( $text ),
5562 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5564 wfProfileOut( __METHOD__
);
5569 * Load the parser state given in the $data array, which is assumed to
5570 * have been generated by serializeHalfParsedText(). The text contents is
5571 * extracted from the array, and its markers are transformed into markers
5572 * appropriate for the current Parser instance. This transformed text is
5573 * returned, and can be safely included in the return value of a parser
5576 * If the $data array has been stored persistently, the caller should first
5577 * check whether it is still valid, by calling isValidHalfParsedText().
5579 * @param $data Serialized data
5582 function unserializeHalfParsedText( $data ) {
5583 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5584 throw new MWException( __METHOD__
.': invalid version' );
5587 # First, extract the strip state.
5588 $texts = array( $data['text'] );
5589 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5591 # Now renumber links
5592 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5594 # Should be good to go.
5599 * Returns true if the given array, presumed to be generated by
5600 * serializeHalfParsedText(), is compatible with the current version of the
5603 * @param $data Array
5607 function isValidHalfParsedText( $data ) {
5608 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;